diff --git a/docs/changelog.md b/docs/changelog.md index 447d3952..b64d0f1f 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -19,6 +19,37 @@ docstring gives: it is a record, not a claim about now. ## 2026-11-17 +- **The socket proxy closed quiet log follows every ten minutes, and the lab + now alerts when an agent drops log lines.** `loki.source.docker` follows + each container's `/logs?follow=1` through docker-socket-proxy, and the + repository's `haproxy.cfg` inherited upstream's `timeout client 10m` and + `timeout server 10m`. A container that wrote nothing for ten minutes had its + follow closed. Alloy reconnected from its saved position, got the last line + again and shipped it again. On `fenrir` that was `sensor-zeek`'s last line, + from 2026-11-09 06:26:34. From 2026-11-16 it was seven days old, and Loki + refused every copy: 1363 entries in + `loki_write_dropped_entries_total{reason="ingester_error"}`, with no alert, + because the lab's Prometheus had no rule on that counter + ([#1552](https://github.com/Gerrrt/HomeLab/issues/1552)). + - **The fix lifts both timeouts for the log path only.** The pinned image + runs HAProxy 3.4.2, which has `http-request set-timeout client`, but its + manual says the value "must be non-null". So the client side gets `24d`, + just under HAProxy's longest timer, not 0. `set-timeout server` needs a + section with backend capabilities, and the frontend has none, so the path + is routed to upstream's `docker-events` backend, whose only difference is + `timeout server 0`. The routing is a second `homelab` block, and + `check_socket_proxy.sh`'s drift check now expects two. + - **`check_socket_proxy.sh` proves it** on a copy of the config with the + idle timeouts cut to 5 seconds: a follow on a quiet container must still + be open after 20, and without the two lines the same follow must close. + - **`LogEntriesDropped` is in `lab.rules.yaml`**, with the estate's + expression and `for: 1h`, and a firing test of `fenrir`'s shape. + + Not yet deployed or verified on `fenrir`: that needs `make up STACK=sensor` + and an hour with no recurring `could not transfer logs` for a quiet + container and a flat dropped counter. Recreating a container clears one + instance of this; it does not fix the cause. + - **The office wall page is in the sensitive stack** ([ADR-0119](adr/0119-put-the-office-wall-dashboard-on-a-pi-5-on-hicks.md)). `stacks/sensitive/wall/` holds static HTML, CSS and JS in the Tokyo Night diff --git a/docs/security.md b/docs/security.md index 9e0baee1..dfbecde3 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1227,12 +1227,16 @@ from Home Assistant with *not enough permissions*. It is upstream's template with that one rule replaced by the three `/containers` paths the clients send, read from three days of the proxy's own request log. That covers the six compose stacks and `deploy-agent.sh`'s - `alloy-socket-proxy`. + `alloy-socket-proxy`. It also holds a log follow open past upstream's + ten-minute idle timeouts, for that path only + ([#1552](https://github.com/Gerrrt/HomeLab/issues/1552)); that widens no + path, and only lets an allowed stream stay up. - **`check_socket_proxy.sh` boots the pinned image on it in CI.** Alloy's paths must answer, and `archive`, `export`, `top`, `changes`, `stats`, `attach` and the `..` and encoded-slash spellings must be refused by the - proxy itself. It also fails when an image bump changes upstream's template - under the committed copy. + proxy itself. A follow on a quiet container must outlast the idle timeouts. + It also fails when an image bump changes upstream's template under the + committed copy. - **`check_compose_health.py` fails a proxy that does not mount the config or is not started on it,** because either one alone falls back to the image's template without any visible change. diff --git a/scripts/check_socket_proxy.sh b/scripts/check_socket_proxy.sh index 7a2dd17d..8f4bbfb2 100755 --- a/scripts/check_socket_proxy.sh +++ b/scripts/check_socket_proxy.sh @@ -27,9 +27,18 @@ # The proxy's own log must show each one denied with no backend # (``). A 403 or a 404 from the daemon would mean the request # got through. +# idle a log follow on a quiet container stays open past the proxy's +# idle timeouts (#1552). Ten minutes is too long to wait in CI, so +# this boots a second proxy on a copy of the file with the defaults' +# `timeout client` and `timeout server` cut to 5s, and holds the +# follow for 20s. A third proxy, on the same copy without the two +# #1552 lines, must close the same follow before then, so the test +# is shown able to fail. `/events` is followed too and its lifetime +# printed, for the record and not as a pass or fail: no client here +# uses it, and its behaviour is upstream's. # # And it checks drift: it rebuilds upstream's template from this file by -# undoing the two marked differences, and requires the result to equal the +# undoing the marked differences, and requires the result to equal the # template in the pinned image byte for byte. A Dependabot bump that changes # upstream's rules therefore fails here, rather than being silently replaced by # a copy of the old ones. @@ -77,10 +86,13 @@ fi IMAGE="$("${REPO_ROOT}/scripts/image-for.sh" docker-socket-proxy)" TAG="sockproxycheck-$$" +IDLE_TAG="${TAG}-idle" +CONTROL_TAG="${TAG}-control" +QUIET_TAG="${TAG}-quiet" WORK="$(mktemp -d)" # shellcheck disable=SC2317,SC2329 # reached through the EXIT trap cleanup() { - docker rm -f "${TAG}" >/dev/null 2>&1 || true + docker rm -f "${TAG}" "${IDLE_TAG}" "${CONTROL_TAG}" "${QUIET_TAG}" >/dev/null 2>&1 || true rm -rf "${WORK}" 2>/dev/null || true } trap cleanup EXIT @@ -108,8 +120,11 @@ out, inside, blocks = [], False, 0 for line in lines: if line.strip().startswith("# BEGIN homelab"): inside, blocks = True, blocks + 1 - # 2. The block stands where upstream's one prefix rule stood. - out.append(" http-request allow if { path,url_dec -m reg -i ^(/v[\\d\\.]+)?/containers } { env(CONTAINERS) -m bool }\n") + # 2. The first block stands where upstream's one prefix rule stood. + # The second, the log follow's backend (#1552), adds a line upstream + # does not have, so it rebuilds to nothing. + if blocks == 1: + out.append(" http-request allow if { path,url_dec -m reg -i ^(/v[\\d\\.]+)?/containers } { env(CONTAINERS) -m bool }\n") continue if line.strip() == "# END homelab": inside = False @@ -118,8 +133,8 @@ for line in lines: continue # 3. The resolved bind line, back to the placeholder the entrypoint fills. out.append(" bind ${BIND_CONFIG}\n" if line == " bind [::]:2375 v4v6\n" else line) -if blocks != 1 or inside: - sys.exit(f"expected exactly one closed `# BEGIN homelab` block, found {blocks}") +if blocks != 2 or inside: + sys.exit(f"expected exactly two closed `# BEGIN homelab` blocks, found {blocks}") open(dst, "w", encoding="utf-8").writelines(out) REBUILD if [[ -f "${WORK}/rebuilt.template" ]] && cmp -s "${WORK}/upstream.template" "${WORK}/rebuilt.template"; then @@ -260,9 +275,106 @@ else fail "POST /containers/create -> $(grep -oE '[0-9]{3}' <<<"${out}" | head -1 || echo none), expected 403" fi +# --------------------------------------------------------------------------- +info "idle: a log follow outlives the proxy's idle timeouts (#1552)" +# --------------------------------------------------------------------------- +# The two copies. Both cut the defaults' ten minutes to IDLE; the control also +# drops the set-timeout line and the second homelab block. +IDLE=5 +HOLD=20 +python3 - "${CFG}" "${WORK}" "${IDLE}" <<'COPIES' || die "could not derive the idle-test configs from ${CFG##*/}" +import pathlib, sys +src, work, idle = sys.argv[1], pathlib.Path(sys.argv[2]), sys.argv[3] +text = open(src, encoding="utf-8").read() +for name in ("client", "server"): + old = f" timeout {name} 10m\n" + if text.count(old) != 1: + sys.exit(f"`timeout {name} 10m` is not in defaults exactly once") + text = text.replace(old, f" timeout {name} {idle}s\n") +fixed = text +lines, out, block = text.splitlines(keepends=True), [], 0 +inside = False +for line in lines: + if line.strip().startswith("# BEGIN homelab"): + block += 1 + inside = block == 2 + live = not line.lstrip().startswith("#") + if (live and "set-timeout client" in line) or inside: + if line.strip() == "# END homelab": + inside = False + continue + out.append(line) +control = "".join(out) +rules = "".join(l for l in out if not l.lstrip().startswith("#")) +if rules.count("set-timeout") or rules.count("logs$") != 1: + sys.exit("the control still lifts the timeout, or lost the /logs allow rule") +for name, body in (("idle", fixed), ("control", control)): + d = work / name + d.mkdir() + (d / "haproxy.cfg").write_text(body, encoding="utf-8") +COPIES +chmod -R a+rX "${WORK}/idle" "${WORK}/control" +printf 'EVENTS=1\n' >> "${WORK}/env" + +# A container that writes nothing: the follow has nothing to send. +docker run --network none -d --name "${QUIET_TAG}" --label homelab.logs=off \ + --cap-drop ALL --security-opt no-new-privileges:true \ + --entrypoint sleep "${IMAGE}" 600 >/dev/null +QUIET="$(docker inspect -f '{{.Id}}' "${QUIET_TAG}")" + +boot() { # name dir + docker run --network none -d --name "$1" --label homelab.logs=off \ + --cap-drop ALL --security-opt no-new-privileges:true \ + --env-file "${WORK}/env" \ + -v /var/run/docker.sock:/var/run/docker.sock:ro \ + -v "$2:/usr/local/etc/socket-proxy:ro" \ + "${IMAGE}" haproxy -f /usr/local/etc/socket-proxy/haproxy.cfg >/dev/null + local i + for ((i = 0; i < 30; i++)); do + docker exec "$1" wget -q -O /dev/null -T 2 http://127.0.0.1:2375/version 2>/dev/null && return 0 + sleep 1 + done + docker logs --tail 20 "$1" 2>&1 | sed 's/^/ /' + die "the scratch proxy $1 never answered /version" +} + +# Holds a follow open for up to HOLD seconds and prints how long it lasted. +# busybox `timeout` kills wget at HOLD, so HOLD means the stream was still up; +# anything less means the proxy (or the daemon) closed it. +held() { # container path + local start end + start="$(date +%s)" + docker exec "$1" timeout "${HOLD}" wget -q -O /dev/null -T 60 "http://127.0.0.1:2375$2" >/dev/null 2>&1 || true + end="$(date +%s)" + echo $((end - start)) +} + +boot "${IDLE_TAG}" "${WORK}/idle" +boot "${CONTROL_TAG}" "${WORK}/control" +FOLLOW="/containers/${QUIET}/logs?follow=1&stdout=1&stderr=1" + +lasted="$(held "${IDLE_TAG}" "${FOLLOW}")" +if ((lasted >= HOLD)); then + pass "a follow on a quiet container is still open after ${lasted}s, ${IDLE}s idle timeouts" +else + fail "a follow on a quiet container closed after ${lasted}s, with ${IDLE}s idle timeouts; expected ${HOLD}s" +fi +lasted="$(held "${CONTROL_TAG}" "${FOLLOW}")" +# At least IDLE - 1, so a refusal or a broken request, which ends at once, +# cannot pass for the timeout. +if ((lasted >= IDLE - 1 && lasted < HOLD)); then + pass "without the #1552 lines the same follow closes after ${lasted}s, so the test can fail" +elif ((lasted < IDLE - 1)); then + fail "without the #1552 lines the follow ended after ${lasted}s, before the ${IDLE}s timeout: it never streamed" +else + fail "without the #1552 lines the follow still lasted ${lasted}s: the test above proves nothing" +fi +lasted="$(held "${IDLE_TAG}" "/events")" +info "for the record: /events, upstream's timeout server 0 and nothing else, lasted ${lasted}s of ${HOLD}s" + if ((FAILED)); then printf '\033[0;31mFAIL\033[0m the socket proxy config does not hold\n' exit 1 fi -printf '\033[0;32mOK\033[0m %d allowed, %d refused by the proxy, and upstream'"'"'s template unchanged\n' \ +printf '\033[0;32mOK\033[0m %d allowed, %d refused by the proxy, a quiet log follow held, and upstream'"'"'s template unchanged\n' \ "${#ALLOWED[@]}" "$((${#REFUSED[@]} + 1))" diff --git a/stacks/lab/README.md b/stacks/lab/README.md index 5cc7a824..41d5dbc2 100644 --- a/stacks/lab/README.md +++ b/stacks/lab/README.md @@ -59,7 +59,8 @@ prometheus/ prometheus.yaml six scrape jobs — this stack's four, the domain's windows_exporter and odin's Velociraptor; no alerting block, no file_sd - rules/lab.rules.yaml 22 rules — four for this stack watching itself, + rules/lab.rules.yaml 23 rules — four for this stack watching itself, + one for its agents dropping log lines (#1552), two for the guests' disks, three for the domain ADR-0029 sized, seven for golem's backups (ADR-0053), three for fenrir's Zeek archive diff --git a/stacks/lab/prometheus/rules/lab.rules.yaml b/stacks/lab/prometheus/rules/lab.rules.yaml index 7bd6f78f..fde6f472 100644 --- a/stacks/lab/prometheus/rules/lab.rules.yaml +++ b/stacks/lab/prometheus/rules/lab.rules.yaml @@ -1,11 +1,12 @@ --- # The lab stack watching itself. # -# Twenty-two rules, and the number is still the point. The estate has 48; ADR-0007 -# names giving up "Loki, the dashboards and 40 alert rules" as the price of -# keeping lab telemetry out of the estate, and this file does not pretend to -# replace them. Four cover this stack's own working — the things that would make -# every other signal here silently wrong. Two cover the disks of the guests that +# Twenty-three rules, and the number is still the point. The estate has 48; +# ADR-0007 names giving up "Loki, the dashboards and 40 alert rules" as the +# price of keeping lab telemetry out of the estate, and this file does not +# pretend to replace them. Five cover this stack's own working, its agents' +# log shipping included — the things that would make every other signal here +# silently wrong. Two cover the disks of the guests that # push here, in the detail only their own node_exporter has; the estate pages on # the same disks, read another way (ADR-0070). Three cover the domain ADR-0029 sized, # and they are here rather than in a stack of their own because this Prometheus @@ -129,6 +130,36 @@ groups: those journal lines are skipped. Loki refuses any line older than 168 hours. + # The estate's rule of the same name, carried here (#1552). Every guest's + # Alloy pushes its own internals here as job="-alloy" (config.alloy's + # selfmetrics), so the expression needs no change. Until this rule, a + # lab guest losing log lines said so only in its own Alloy's log: fenrir + # dropped a re-sent Zeek line every ten minutes from 2026-11-16, when the + # line turned seven days old, with nothing firing anywhere. + # LokiIngestionStalled cannot see that, because the other lines kept + # arriving. + # + # `for: 1h` for the estate's reason: an Alloy restart replays history and + # Loki refuses the old part of it in one burst, which rate() over 15m + # carries for fifteen minutes and no longer. stack.rules.yaml has the + # measurements (#341). Loss that keeps happening outlasts the hour. + - alert: LogEntriesDropped + expr: | + sum by (job, reason) (rate(loki_write_dropped_entries_total[15m])) > 0 + for: 1h + labels: + component: lab + severity: warning + category: correctness + annotations: + summary: "{{ $labels.job }} has been losing log lines to {{ $labels.reason }} for an hour" + description: >- + The lab's Loki has been rejecting these entries for an hour, so this + is not the burst an agent restart produces. Ask Loki which limit it + is applying with `sum by (reason) (loki_discarded_samples_total)`. + An entry older than 168 hours means an agent is re-sending old + lines: a Docker log follow that keeps reconnecting does that (#1552). + # The guests' own disks: `alexander`, and `odin`, whose Alloy pushes here # (stacks/soc). The estate's HostDisk* rules cannot see either, because # neither pushes to VLAN 99 (ADR-0007). So until 2026-10-01 nothing diff --git a/stacks/lab/prometheus/tests/lab.test.yaml b/stacks/lab/prometheus/tests/lab.test.yaml index 0523e27e..cfbf0ba7 100644 --- a/stacks/lab/prometheus/tests/lab.test.yaml +++ b/stacks/lab/prometheus/tests/lab.test.yaml @@ -11,7 +11,7 @@ # input, the second proves it does not produce one for the input production # actually supplies. # -# All twenty-two rules in lab.rules.yaml are covered here. That is a deliberate +# All twenty-three rules in lab.rules.yaml are covered here. That is a deliberate # difference from the estate's tests, where four of the nine stack rules are # syntax-checked only: this file is small enough that "test the ones that were # hard" has no advantage over testing all of them, and a new stack has no @@ -153,6 +153,49 @@ tests: alertname: LokiIngestionStalled exp_alerts: [] + # --- LogEntriesDropped: fenrir's shape (#1552) --------------------------- + # One re-sent line refused every ten minutes, for as long as the follow kept + # reconnecting. Steady loss, so it outlasts the hour and fires. + - interval: 1m + input_series: + - series: 'loki_write_dropped_entries_total{instance="fenrir",job="fenrir-alloy",reason="ingester_error"}' + values: "0+0.1x180" + alert_rule_test: + - eval_time: 90m + alertname: LogEntriesDropped + exp_alerts: + - exp_labels: + job: fenrir-alloy + reason: ingester_error + component: lab + severity: warning + category: correctness + exp_annotations: + summary: "fenrir-alloy has been losing log lines to ingester_error for an hour" + description: >- + The lab's Loki has been rejecting these entries for an hour, so + this is not the burst an agent restart produces. Ask Loki which + limit it is applying with `sum by (reason) + (loki_discarded_samples_total)`. An entry older than 168 hours + means an agent is re-sending old lines: a Docker log follow + that keeps reconnecting does that (#1552). + + # --- LogEntriesDropped: quiet for an agent-restart burst ----------------- + # A restart replay is one step in the counter and then flat, the shape the + # estate measured (#341). rate() over 15m carries it for fifteen minutes, so + # `for: 1h` is never met: quiet during the burst and after it. + - interval: 1m + input_series: + - series: 'loki_write_dropped_entries_total{instance="odin",job="odin-alloy",reason="ingester_error"}' + values: "0x5 0+6646x5 33231x170" + alert_rule_test: + - eval_time: 25m + alertname: LogEntriesDropped + exp_alerts: [] + - eval_time: 170m + alertname: LogEntriesDropped + exp_alerts: [] + # --- InstanceDown, for a guest that is off on purpose --------------------- # ADR-0029 runs the endpoints per session. An endpoint reading `up == 0` is # not an outage, and a rule that says it is would fire more or less forever. diff --git a/stacks/observability/docker-socket-proxy/haproxy.cfg b/stacks/observability/docker-socket-proxy/haproxy.cfg index 3f63d9cf..46dc77e9 100644 --- a/stacks/observability/docker-socket-proxy/haproxy.cfg +++ b/stacks/observability/docker-socket-proxy/haproxy.cfg @@ -3,14 +3,18 @@ # where scripts/deploy-agent.sh copies it into a volume. # # This is tecnativa/docker-socket-proxy v0.5.0's haproxy.cfg.template, byte for -# byte, with two differences: +# byte, with three differences: # # 1. The bind line is resolved. The image's entrypoint seds ${BIND_CONFIG} # into ITS template only, and this file is passed to haproxy as-is, so it # carries the value the entrypoint computes when DISABLE_IPV6 is unset. # # 2. CONTAINERS=1 allows three paths, not the whole /containers prefix. That -# is the block marked "homelab" below, and the reason this file exists. +# is the first block marked "homelab" below, and the reason this file +# exists. +# +# 3. A log follow is held open however long its container is quiet. That is +# one line in the first block and the whole of the second (#1552). # # Why 2. Upstream's rule is a prefix match, so CONTAINERS=1 also allowed # GET /containers/{id}/archive, /export, /top and /changes. POST=0 does not stop @@ -34,12 +38,35 @@ # /containers/{id}/json/../archive. HAProxy's `path` does not include the query # string, so ?stdout=1&follow=1 on logs still matches. # +# Why 3. loki.source.docker follows /containers/{id}/logs?follow=1, and a +# quiet container sends nothing down that stream. The defaults' `timeout client +# 10m` and `timeout server 10m` therefore closed it after ten idle minutes. +# Alloy reconnected from its saved position, Docker returned the last line +# again, and Alloy shipped it again: a duplicate every ten minutes, until the +# line was seven days old and Loki rejected each copy as too old. That was +# 1363 dropped entries on fenrir by 2026-11-17, all one Zeek line of +# 2026-11-09. Busy containers never reach the timeout. Two lines lift it for +# that path only, and every other request keeps upstream's ten minutes: +# +# - `http-request set-timeout client 24d`, the client side. HAProxy's manual +# says the value "must be non-null", so it is not 0. 24 days is just under +# the 2^31 ms a HAProxy timer holds. It sits before the allow rule, because +# an allow ends rule evaluation. +# - `use_backend docker-events`, the server side. `set-timeout server` works +# only in a section with backend capabilities, and this frontend has none. +# Upstream's docker-events backend differs from dockerbackend only by +# `timeout server 0`, which is what a follow needs. That line is a second +# block at the end, because HAProxy warns when an http-request rule follows +# a use_backend, and the first block stands where upstream's rule stood. +# # scripts/check_socket_proxy.sh boots the pinned image on this file and checks # both halves: the three paths answer, and archive, export, top, changes, # stats and the traversal and encoding variants get the proxy's own 403. It -# also rebuilds upstream's template from this file and requires it to equal the -# one in the pinned image. A Dependabot bump that changes upstream's rules -# therefore fails CI, instead of being silently overridden by this copy. +# also proves that a log follow outlives the idle timeouts, on a copy with them +# cut to seconds, and that the same follow is closed without the two lines +# above. And it rebuilds upstream's template from this file and requires it to +# equal the one in the pinned image. A Dependabot bump that changes upstream's +# rules therefore fails CI, instead of being silently overridden by this copy. # # HAProxy reads this only at start. scripts/reload-config.sh restarts the # container on every `make up`, before Alloy, so a config-only change still @@ -109,6 +136,8 @@ frontend dockerfrontend # BEGIN homelab: CONTAINERS=1 allows these three paths, not the /containers prefix (Tecnativa/docker-socket-proxy#182) http-request allow if { path,url_dec -m reg -i ^(/v[\d\.]+)?/containers/json$ } { env(CONTAINERS) -m bool } http-request allow if { path,url_dec -m reg -i ^(/v[\d\.]+)?/containers/[a-zA-Z0-9_.-]+/json$ } { env(CONTAINERS) -m bool } + # A log follow is idle while its container is quiet: no client timeout on it (#1552, the header's 3.) + http-request set-timeout client 24d if { path,url_dec -m reg -i ^(/v[\d\.]+)?/containers/[a-zA-Z0-9_.-]+/logs$ } { env(CONTAINERS) -m bool } http-request allow if { path,url_dec -m reg -i ^(/v[\d\.]+)?/containers/[a-zA-Z0-9_.-]+/logs$ } { env(CONTAINERS) -m bool } # END homelab http-request allow if { path,url_dec -m reg -i ^(/v[\d\.]+)?/distribution } { env(DISTRIBUTION) -m bool } @@ -133,3 +162,6 @@ frontend dockerfrontend default_backend dockerbackend use_backend docker-events if { path,url_dec -m reg -i ^(/v[\d\.]+)?/events } + # BEGIN homelab: a log follow goes to the backend with no server timeout (#1552, the header's 3.) + use_backend docker-events if { path,url_dec -m reg -i ^(/v[\d\.]+)?/containers/[a-zA-Z0-9_.-]+/logs$ } + # END homelab