Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Nginx as a workaround to get log streaming working again #767

Merged
merged 1 commit into from
Jan 12, 2025

Conversation

elcajon
Copy link
Collaborator

@elcajon elcajon commented Jan 12, 2025

Proposed Changes

This PR adds Nginx to this add-on and sets up a proxy to distinguish between HA and HA logs requests.

Thanks to @othorp (home-assistant/supervisor#5509 (comment)) for figuring out the correct proxy settings!

location ~ /api/hassio/.*/logs {
    proxy_cache off;
    proxy_buffering off;
    proxy_hide_header Content-Type;
    add_header Content-Type "text/event-stream";
}

This PR will have no impact on currently running tunnels.

It runs an nginx proxy on port 8321 (inside the Cloudflare add-on Docker) with the correct settings to get log streaming working again.

Can be testet with remotely managed tunnels by changing the host from homeassistant:8123 to localhost:8321.

image image

I would like to merge this without a disruptive change to continue testing until a workaround/solution is available.

If it seems to be stable after some first testing.

We can think about changing the local managed tunnel uri to localhost:8321 in the future as well, which would have some impact on the current following setup logic:

bashio::log.debug "Checking if SSL is used..."
if bashio::var.true "$(bashio::core.ssl)" ; then
ha_service_protocol="https"
else
ha_service_protocol="http"
fi
bashio::log.debug "ha_service_protocol: ${ha_service_protocol}"
if bashio::var.is_empty "${ha_service_protocol}" ; then
bashio::exit.nok "Error checking if SSL is enabled"
fi
# Add Service for Home Assistant if 'external_hostname' is set
if bashio::config.has_value 'external_hostname' ; then
config=$(bashio::jq "${config}" ".\"ingress\" += [{\"hostname\": \"${external_hostname}\", \"service\": \"${ha_service_protocol}://homeassistant:$(bashio::core.port)\"}]")
fi

For testing, clone the branch in /addons and then run the add-on locally with a tunnel token.

Related Issues

#744

Summary by CodeRabbit

Release Notes

  • New Features

    • Added Nginx configuration for improved service proxying
    • Enhanced dependency management configuration
  • Bug Fixes

    • Implemented workaround for live log streaming issue
  • Chores

    • Updated Nginx version to 1.26.2-r4
    • Improved service management scripts for Nginx
  • Infrastructure

    • Added new Renovate configuration for dependency tracking

Copy link

coderabbitai bot commented Jan 12, 2025

Walkthrough

This pull request introduces enhancements to the Cloudflared Home Assistant add-on, focusing on improving dependency management and adding an Nginx service configuration. The changes include a new Renovate configuration for tracking dependencies, a script to manage Nginx versioning, a detailed Nginx configuration template, and S6 overlay scripts for managing the Nginx service lifecycle. The modifications aim to provide more robust service handling and dependency tracking within the add-on.

Changes

File Change Summary
.github/renovate.json Added regex manager configuration for tracking dependencies in rootfs/build.sh
cloudflared/rootfs/build.sh Added nginx_version variable set to "1.26.2-r4" and installation command
cloudflared/rootfs/etc/nginx/template/nginx.conf.gtpl New Nginx configuration template with detailed server and location block settings
cloudflared/rootfs/etc/s6-overlay/s6-rc.d/nginx/finish New script for managing Nginx service shutdown and error handling
cloudflared/rootfs/etc/s6-overlay/s6-rc.d/nginx/run New script for configuring and starting Nginx service
cloudflared/rootfs/etc/s6-overlay/s6-rc.d/nginx/type Added longrun service type configuration

Sequence Diagram

sequenceDiagram
    participant Build as build.sh
    participant Renovate as Renovate Config
    participant Nginx as Nginx Service
    participant S6 as S6 Overlay

    Renovate->>Build: Track dependencies
    Build->>Build: Set Nginx version
    Build->>Nginx: Install Nginx
    S6->>Nginx: Configure service
    S6->>Nginx: Start service
    Nginx->>Nginx: Process requests
    S6->>Nginx: Monitor service health
Loading

The sequence diagram illustrates the workflow of dependency tracking, Nginx installation, configuration, and service management within the Cloudflared Home Assistant add-on.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@elcajon elcajon added new-feature New features or options. enhancement Enhancement of the code, not introducing new features. labels Jan 12, 2025
@brenner-tobias
Copy link
Owner

Thanks a lot! While testing one first thought: If we want to keep this as an optional workaround and expect a fix outside of this add-on at some point, would it not be sufficient to document a solution using the NGINX HA add-on and the tunnel with a catch-all rule on our end?

@elcajon
Copy link
Collaborator Author

elcajon commented Jan 12, 2025

I assume so, but without further Nginx configuration this would not work via the official nginx add-on. I had already tested some configurations locally with Nginx and Caddy. It's not that easy to get it to work if you're not familiar with proxies.

I'm not so happy with this solution either, because I don't think it should be solved in the add-on, but I think for locally managed tunnels we could easily switch back if there is a solution upstream in the future.

@brenner-tobias
Copy link
Owner

I tested it locally and it looks good to me.
Now I think we have to ask ourselves if we want to include this or if we just live with the limited functionality for now.

Have we identified any additional things (next to live logging) that are not working? If it is only that, I could live with the limited functionality, especially since the logs can be accessed while in the local network.

On the other hand, I am also fine with integrating this workaround for anyone interested in fixing it themselves since it is not affecting anyone else. So if you want to include it, I am happy to approve the changes once the documentation is also updated with a comment and solution for the remote tunnels.

@elcajon
Copy link
Collaborator Author

elcajon commented Jan 12, 2025

I see what you mean, and I don't feel comfortable adding something new that isn't really related to the core functionality of the add-on. I also don't want to extend that functionality in the future.

I don't think we have any other direct limitations apart from the live logs. But missing logs while debugging automations etc. seems to be crucial for me - also while away from home.

I honestly don't know if we should even mention it in the docs at this point. Anyone who comes across the problem and reads about it in the discussions could make the change. Otherwise, I would rather make it available quietly to not confuse the average user.

Another thought regarding the new live streaming from cameras (grpc) functionality, I really don't know if this will work with our current add-on configuration/solution, I don't have any devices to test this new functionality.

@brenner-tobias
Copy link
Owner

fair point regarding the logging. Let's introduce it in a silent way and see what pops up in the issues and discussions.

@elcajon elcajon marked this pull request as ready for review January 12, 2025 22:24
@elcajon elcajon added bugfix Inconsistencies or issues which will cause a problem for users or implementors. and removed enhancement Enhancement of the code, not introducing new features. new-feature New features or options. labels Jan 12, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
cloudflared/rootfs/etc/s6-overlay/s6-rc.d/nginx/run (1)

16-18: Add error handling for jq command.

While set -e will catch failures, explicit error handling would be better for debugging.

Consider:

-JSON_CONF=$(jq --arg port $(bashio::core.port) \
-    '({port: $port})' \
-    /data/options.json)
+if ! JSON_CONF=$(jq --arg port $(bashio::core.port) \
+    '({port: $port})' \
+    /data/options.json); then
+    bashio::log.error "Failed to process JSON configuration"
+    exit 1
+fi
.github/renovate.json (1)

29-34: Consider adding documentation for the expected comment format.

To help maintainers, consider adding a comment block above the regex manager configuration showing the expected format:

     {
+      // Matches version information from build script comments
+      // Expected format:
+      // # renovate: datasource=<source> depName=<name> versioning=<optional> ARG <name>_version="<version>"
+      // Example:
+      // # renovate: datasource=github-releases depName=nginx/nginx versioning=loose ARG nginx_version="1.26.2"
       "customType": "regex",
       "fileMatch": ["/rootfs/build.sh$"],
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc5aae2 and e2ad3c0.

📒 Files selected for processing (6)
  • .github/renovate.json (1 hunks)
  • cloudflared/rootfs/build.sh (1 hunks)
  • cloudflared/rootfs/etc/nginx/template/nginx.conf.gtpl (1 hunks)
  • cloudflared/rootfs/etc/s6-overlay/s6-rc.d/nginx/finish (1 hunks)
  • cloudflared/rootfs/etc/s6-overlay/s6-rc.d/nginx/run (1 hunks)
  • cloudflared/rootfs/etc/s6-overlay/s6-rc.d/nginx/type (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • cloudflared/rootfs/etc/s6-overlay/s6-rc.d/nginx/type
🔇 Additional comments (5)
cloudflared/rootfs/build.sh (1)

30-32: LGTM! Version management looks good.

Good practices observed:

  • Version pinning with renovate integration
  • Using --no-cache flag for installation

Let's verify if this is the latest stable version:

✅ Verification successful

✓ Nginx version 1.26.2-r4 verified as current

The specified version matches the latest stable version available in Alpine Linux repositories.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check latest nginx version in Alpine
curl -s https://dl-cdn.alpinelinux.org/alpine/latest-stable/main/x86_64/APKINDEX.tar.gz | tar -xz -C /tmp && cat /tmp/APKINDEX | grep -A1 "P:nginx"

Length of output: 2139

cloudflared/rootfs/etc/nginx/template/nginx.conf.gtpl (2)

23-25: Consider adding access control for the proxy.

The proxy is listening on port 8321 without any access control. While this might be intended for internal use, consider adding IP-based restrictions for additional security.

Consider adding:

 listen 8321;
+allow 127.0.0.1;
+deny all;
 proxy_buffering off;

36-47: Verify log streaming configuration.

The configuration for log streaming looks correct with:

  • Proper header handling
  • Disabled caching and buffering
  • Content-Type set for event-stream

Let's verify if there are any other log-related endpoints that might need similar handling:

✅ Verification successful

Log streaming configuration is properly isolated and complete

The /api/hassio/.*/logs endpoint is the only log streaming endpoint in the configuration, and it has all the necessary settings for proper event streaming. No other endpoints require similar streaming configuration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for log-related API endpoints in the codebase
rg -l "api.*logs?" | grep -i "api"

Length of output: 34


Script:

#!/bin/bash
# Find all nginx configuration files
echo "=== Nginx Configuration Files ==="
fd -e conf -e gtpl -e template . | grep -i "nginx"

# Search for location blocks in these files
echo -e "\n=== Location Blocks with API Patterns ==="
rg "location.*api" -A 5

# Search for hassio-related patterns
echo -e "\n=== Hassio API Patterns ==="
rg "/hassio/" -A 5

Length of output: 1630


Script:

#!/bin/bash
# View the complete nginx configuration
echo "=== Complete Nginx Configuration ==="
cat cloudflared/rootfs/etc/nginx/template/nginx.conf.gtpl

# Find all location blocks
echo -e "\n=== All Location Blocks ==="
rg "^\s+location\s+" -A 5 cloudflared/rootfs/etc/nginx/template/nginx.conf.gtpl

Length of output: 2101

cloudflared/rootfs/etc/s6-overlay/s6-rc.d/nginx/finish (1)

7-27: LGTM! Robust error handling implementation.

The script properly handles:

  • Service exit codes
  • Signal handling
  • Container exit code management
  • Appropriate logging
.github/renovate.json (1)

29-34: LGTM! Well-structured regex manager configuration.

The regex configuration correctly captures version information from build script comments, with proper handling of optional versioning parameter.

.github/renovate.json Show resolved Hide resolved
@elcajon
Copy link
Collaborator Author

elcajon commented Jan 12, 2025

Changing the categorization to bugfix to avoid issuing a minor version change

@elcajon elcajon merged commit 57aac9f into main Jan 12, 2025
28 of 29 checks passed
@elcajon elcajon deleted the log-streaming-workaround branch January 12, 2025 22:28
@github-actions github-actions bot locked and limited conversation to collaborators Jan 14, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bugfix Inconsistencies or issues which will cause a problem for users or implementors.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants