Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a453df83e | ||
|
|
2d42ed6c17 | ||
|
|
90e68fb8ef | ||
|
|
6a2ac2f1db | ||
|
|
4ced47941d | ||
|
|
6df8d4b332 | ||
|
|
ff535fae1f | ||
|
|
b6911fb63f | ||
|
|
24f4a5ebac |
No files matched your search
@@ -9,6 +9,16 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
# Release candidates: a push to coraza-release/** builds the SAME image
|
||||
# but publishes ONLY :<coraza-spoa/VERSION>-rc and :<sha>, never :latest
|
||||
# and never the plain :<VERSION> (see "Resolve tags"). Deliberately NOT
|
||||
# release/**: that prefix also triggers build-push.yaml (the edge image),
|
||||
# which would re-publish the edge's :<VERSION>-rc tag from this branch.
|
||||
# A candidate is rolled out per host through WHP's coraza image pin
|
||||
# (/etc/whp/coraza-image); :latest moves only with a later main publish,
|
||||
# after the staged rollout succeeded. apply-coraza-waf-mode.sh pulls
|
||||
# :latest on every WAF mode apply, so moving :latest IS a fleet rollout.
|
||||
- 'coraza-release/**'
|
||||
paths:
|
||||
- 'coraza-spoa/**'
|
||||
- 'scripts/assemble-multiarch-index.sh'
|
||||
@@ -27,7 +37,7 @@ on:
|
||||
# repos: docs/arm64/IMAGE-PIPELINE-PLAN.md sections 4.1 / 4.4.
|
||||
jobs:
|
||||
Build-and-Push:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ephemeral
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -70,6 +80,31 @@ jobs:
|
||||
username: shadowdao
|
||||
password: ${{ secrets.GHCR_TOKEN }}
|
||||
|
||||
# Publishing strategy (mirrors build-push.yaml). main: :latest +
|
||||
# :<version> + :<sha>. coraza-release/**: :<version>-rc + :<sha> ONLY.
|
||||
# Any other ref (e.g. workflow_dispatch on a feature branch) is refused.
|
||||
# <version> is coraza-spoa/VERSION (this image's own YYYY.MM.N, separate
|
||||
# from the edge image's repo-root VERSION).
|
||||
- name: Resolve tags
|
||||
id: tags
|
||||
env:
|
||||
REF: ${{ gitea.ref }}
|
||||
SHA: ${{ gitea.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VERSION="$(cat coraza-spoa/VERSION)"
|
||||
[[ "$VERSION" =~ ^[0-9]{4}\.[0-9]{2}\.[0-9]+$ ]] || { echo "::error::coraza-spoa/VERSION '$VERSION' is not YYYY.MM.N"; exit 1; }
|
||||
case "$REF" in
|
||||
refs/heads/main)
|
||||
list="latest ${VERSION} ${SHA}" ;;
|
||||
refs/heads/coraza-release/*)
|
||||
list="${VERSION}-rc ${SHA}" ;;
|
||||
*)
|
||||
echo "::error::refusing to publish from ref ${REF} (only main and coraza-release/**)"; exit 1 ;;
|
||||
esac
|
||||
echo "list=${list}" >> "$GITHUB_OUTPUT"
|
||||
echo "publishing: ${list}"
|
||||
|
||||
# amd64: required. Failure here fails the job and publishes nothing, as
|
||||
# before. Pushed untagged by digest to both registries (same digest in
|
||||
# each); the tag is only created by the assemble step below.
|
||||
@@ -97,15 +132,22 @@ jobs:
|
||||
PKG_CACHE=${{ steps.pkgcache.outputs.url }}
|
||||
outputs: type=image,"name=repo.anhonesthost.net/cloud-hosting-platform/coraza-spoa,ghcr.io/shadowdao/coraza-spoa",push-by-digest=true,name-canonical=true,push=true
|
||||
|
||||
- name: Assemble :latest index
|
||||
- name: Assemble multi-arch index
|
||||
env:
|
||||
AMD64_DIGEST: ${{ steps.amd64.outputs.digest }}
|
||||
ARM64_DIGEST: ${{ steps.arm64.outputs.digest }}
|
||||
ARM64_OUTCOME: ${{ steps.arm64.outcome }}
|
||||
TAG_LIST: ${{ steps.tags.outputs.list }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tag_args=()
|
||||
for t in $TAG_LIST; do tag_args+=(--tag "$t"); done
|
||||
[ ${#tag_args[@]} -gt 0 ] || { echo "::error::no tags resolved"; exit 1; }
|
||||
scripts/assemble-multiarch-index.sh \
|
||||
--amd64 "$AMD64_DIGEST" \
|
||||
--arm64 "$ARM64_DIGEST" --arm64-outcome "$ARM64_OUTCOME" \
|
||||
--repo repo.anhonesthost.net/cloud-hosting-platform/coraza-spoa \
|
||||
--repo ghcr.io/shadowdao/coraza-spoa \
|
||||
--tag latest
|
||||
"${tag_args[@]}"
|
||||
echo "amd64 digest: $AMD64_DIGEST"
|
||||
echo "arm64 digest: ${ARM64_DIGEST:-<none>} (${ARM64_OUTCOME})"
|
||||
@@ -28,7 +28,7 @@ on:
|
||||
# read only from THIS run's step output).
|
||||
jobs:
|
||||
Build-and-Push:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ephemeral
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- name: Checkout
|
||||
|
||||
@@ -20,7 +20,7 @@ on:
|
||||
|
||||
jobs:
|
||||
Mirror-Base:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ephemeral
|
||||
strategy:
|
||||
# fail-fast=false so one image's upstream being down doesn't block the
|
||||
# others from refreshing.
|
||||
|
||||
@@ -15,6 +15,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
- **Superseded-cert retirement**: covered by the same file (`TestRetirementRules`, `TestSanOverlapRetirement`). A new bundle retires any OTHER pem/lineage sharing ANY name (CN or SAN) with it - the pem moved to `cert-retired/`, the lineage's live+archive+renewal moved TOGETHER to `/etc/letsencrypt/retired/<stamp>/` (leaving archive/ behind makes certbot refuse the name forever), never deleted; the bundle's own `--cert-name` lineage is `live/<primary>` exactly and is never retired - unless that cert is still the only valid one for a name this edge serves (`retirement_blockers()`). `GET /api/capabilities` advertises this to WHP, which must not use whole-site re-bundling without it. Expired pems already in the crt dir are moved to `cert-retired/` by `cert_retire_expired_pems` (never the last pem, never `default_self_signed_cert.pem`). Expired lineages are never published (`cert_is_expired` in `cert-publish-lib.sh`, `leaf_is_expired()` in Python). Fixtures: `scripts/test-fixtures/san-certs/`.
|
||||
- **Multi-arch index assembly (coraza-spoa)**: `python3 scripts/test-assemble-multiarch-index.py` - offline (NOT run in the image build; it also reads `.gitea/workflows/build-push-coraza.yaml`); `scripts/assemble-multiarch-index.sh` turns the by-digest amd64 + arm64 pushes into the tag(s): arm64 is attached only if THIS run's arm64 step outcome is `success` (failure => amd64-only tag, never a stale arm64), a bad amd64 digest publishes nothing. `scripts/e2e-coraza-multiarch.sh` rehearses the whole thing against throwaway local registries (see coraza-spoa/README.md "Multi-arch").
|
||||
- **Publish verify gate**: `python3 scripts/test-verify-published-tags.py` - offline (needs `jq`; NOT run in the image build); `scripts/verify-published-tags.sh` is the last build-push.yaml step: every tag in every registry must resolve, carry the assembled platforms, and share ONE index digest. The digest is the sha256 of `imagetools inspect --raw` cross-checked against the text `Digest:` line / bare `--format` output (buildx 0.28 ignores `--format` and prints full text; CI run 5381).
|
||||
- **Supervisor fast relaunch**: `python3 scripts/test-haproxy-supervisor-relaunch.py` - runs in the image build; needs a real `haproxy` (skips without one). Starts a real master, runs the real `haproxy-supervisor.sh`, SIGABRTs the worker and asserts a new master is serving < 3 s after the old one exits, started from bash (python stub never ran), marker present during and gone after, no second master, invalid config -> python fallback. `scripts/test-haproxy-supervisor.py` (stubs, ~60 s) covers the fast/fallback/idempotency logic. Run both after touching `haproxy-supervisor.sh`.
|
||||
- **Per-host thread count knob**: `python3 scripts/test-nbthread-knob.py` - runs in the image build; `HAPROXY_NBTHREAD` (container env, 1-64; invalid/unset = ignored) renders `nbthread N` in `global` ONLY when set, so every other host's config is byte-identical. Real `haproxy -c` of `nbthread 1` is the `nbthread-1` scenario in `scripts/validate-rendered-config.py`. WHP side: `/etc/whp/edge-nbthread` -> `lib-edge-container.sh` -> `docker run -e` at recreate.
|
||||
- **Health-check timing**: `python3 scripts/test-health-check-timing.py` - runs in the image build; one `default-server inter 30s fastinter 10s downinter 30s rise 2 fall 3` in `defaults` + `spread-checks 50` in `global` (hap_header.tpl), never per server line; the Coraza SPOA server keeps `inter 2s`. Pins that a dead backend is still detected in <= 2 min and that `fastinter` (which sizes the post-reload start-up stagger window) stays >= 5s. Real `haproxy -c` coverage: the `check-timing`/`spread-checks` assertions in `scripts/validate-rendered-config.py`.
|
||||
- **Default splash**: `python3 scripts/test-default-splash.py` - offline (runs in the image build); unrouted hosts (server hostname, bare IP, unknown names) are answered by `http-request return ... file /haproxy/errors/default-splash.html` BEFORE the Coraza SPOE call, never for a routed host (`routed_hosts.list`/`routed_wildcards.list`, written by `generate_config()` from the routing rows and in the rollback set), never for ACME/blocked/suspended. Run it after touching the splash block, the routing ACL templates, or the domain loops in `generate_config()`. See README "Default Splash".
|
||||
@@ -183,4 +184,4 @@ re-reads it on reload, so a failed runtime command must degrade to
|
||||
- gunicorn uses `haproxy_gunicorn_worker.TimeoutThreadWorker` (gthread + client socket timeout + first-byte deadline + total header deadline + wedge watchdog). Stock gthread leaves client sockets blocking with NO timeout; `--timeout` only watches the main thread's heartbeat
|
||||
- Supports deployment on servers with git directory at `/root/whp` and web file sync via rsync to `/docker/whp/web/`
|
||||
- HAProxy is the 3.2 LTS series from haproxy.debian.net (`trixie-backports-3.2`, native OpenSSL 3.5 QUIC); exact build in `/haproxy/HAPROXY_VERSION`. Debian trixie's 3.0.11 had the DNS-resolver watchdog abort (haproxy #3101)
|
||||
- HAProxy runs as `haproxy -W -db` (foreground master, started by `haproxy_manager.spawn_haproxy_master()`), NOT daemonised: `daemon` re-points the master's stderr at /dev/null and loses ALERTs and the ha_panic/watchdog thread dump. Its stderr is appended to `/var/log/haproxy/haproxy-stderr.log` (haproxy-logs volume) and `scripts/haproxy-stderr-relay.py` re-emits it on the container stderr (`haproxy-stderr: ` prefix). The in-container supervisor probes with `pidof` every `HAPROXY_SUPERVISOR_INTERVAL` (default 2 s) and only runs python when HAProxy is gone; Crash evidence (dump blocks opened only by the anchored `Thread N is about to kill` header, `[ALERT] (PID) :`, `Current worker (N) exited with code N`; ANCHORED patterns, so keywords echoed from URLs/Host/server names never match) bypasses the bucket within a budget (1000 lines / 10 min, 60 s cooldown after a bound closes a block) and goes to STDERR (journald PRIORITY 3); routine reload noise is collapsed into one `[relay] reload/start ok: N routine lines collapsed` line per reload and everything benign goes to STDOUT (PRIORITY 6; docker's journald driver does not parse `<N>` prefixes), with a per-minute `[relay] suppressed N lines` summary. `python3 scripts/test-haproxy-stderr-relay.py` (offline) covers the relay
|
||||
- HAProxy runs as `haproxy -W -db` (foreground master, started by `haproxy_manager.spawn_haproxy_master()`), NOT daemonised: `daemon` re-points the master's stderr at /dev/null and loses ALERTs and the ha_panic/watchdog thread dump. Its stderr is appended to `/var/log/haproxy/haproxy-stderr.log` (haproxy-logs volume) and `scripts/haproxy-stderr-relay.py` re-emits it on the container stderr (`haproxy-stderr: ` prefix). The in-container supervisor probes with `pidof` every `HAPROXY_SUPERVISOR_INTERVAL` (default 1 s) and, when HAProxy is gone, relaunches it DIRECTLY FROM BASH against the on-disk config (`haproxy -c` then the same `haproxy -W -db -S ...` command, detached to PID 1; ~0.8 s measured on an idle host, was 16 s through python on a starved one) and falls back to `ensure_haproxy.py` only if the config is missing/invalid or the launch fails; while recovering it keeps the marker `/tmp/haproxy-restarting` (`<epoch> <pid>`, `HAPROXY_SUPERVISOR_MARKER`) so the host watchdog does not `docker restart` on top of it; Crash evidence (dump blocks opened only by the anchored `Thread N is about to kill` header, `[ALERT] (PID) :`, `Current worker (N) exited with code N`; ANCHORED patterns, so keywords echoed from URLs/Host/server names never match) bypasses the bucket within a budget (1000 lines / 10 min, 60 s cooldown after a bound closes a block) and goes to STDERR (journald PRIORITY 3); routine reload noise is collapsed into one `[relay] reload/start ok: N routine lines collapsed` line per reload and everything benign goes to STDOUT (PRIORITY 6; docker's journald driver does not parse `<N>` prefixes), with a per-minute `[relay] suppressed N lines` summary. `python3 scripts/test-haproxy-stderr-relay.py` (offline) covers the relay
|
||||
@@ -167,6 +167,7 @@ RUN python3 /haproxy/scripts/test-wpadmin-gate.py \
|
||||
&& python3 /haproxy/scripts/test-access-log-receiver.py \
|
||||
&& python3 /haproxy/scripts/test-haproxy-stderr-relay.py \
|
||||
&& python3 /haproxy/scripts/test-haproxy-supervisor.py \
|
||||
&& python3 /haproxy/scripts/test-haproxy-supervisor-relaunch.py \
|
||||
&& python3 /haproxy/scripts/test-config-rollback.py \
|
||||
&& python3 /haproxy/scripts/test-cert-write-safety.py \
|
||||
&& python3 /haproxy/scripts/test-cert-scripts.py \
|
||||
|
||||
@@ -11,6 +11,20 @@
|
||||
|
||||
ARG CORAZA_SPOA_VERSION=v0.7.1
|
||||
|
||||
# Coraza engine override (security): coraza-spoa v0.7.1 pins
|
||||
# github.com/corazawaf/coraza/v3 v3.7.0, which is affected by the v3.8.x
|
||||
# advisories (jsDecode octal bypass GHSA-pc5q-qfxp-ggqv, JSON key-collision
|
||||
# bypass GHSA-5gj4-9gm7-2fx2, ProcessURI dropping ARGS_GET GHSA-x26q-wvhg-fh4m,
|
||||
# first-Content-Type desync GHSA-w253-m66g-rx24, ...). The engine is upgraded
|
||||
# IN PLACE (go get of this exact version, verified against go.sum /
|
||||
# sum.golang.org) instead of moving to coraza-spoa v0.9.x, so the SPOA agent
|
||||
# and coraza-coreruleset (CRS 4.25.0) stay exactly what WHP's WAF regression
|
||||
# net (scripts/tests/waf-regression in the WHP repo) measures; only the
|
||||
# engine changes. The build FAILS if the binary does not embed this version.
|
||||
# Behaviour changes that matter are documented in config.yaml
|
||||
# (SecArgumentsLimit) and in the WHP PR that moved the regression net.
|
||||
ARG CORAZA_VERSION=v3.8.1
|
||||
|
||||
# golang:1.25 from the in-house mirror. The 2026-05-12 Cloudflare incident
|
||||
# took out docker.io blob pulls TWICE in one day (first for python:3.12-slim,
|
||||
# then for this image's golang:1.25), so both are mirrored at
|
||||
@@ -24,6 +38,7 @@ ARG CORAZA_SPOA_VERSION=v0.7.1
|
||||
# the final distroless stage is per target platform (gcr.io publishes arm64).
|
||||
FROM --platform=$BUILDPLATFORM repo.anhonesthost.net/cloud-hosting-platform/golang:1.25 AS build
|
||||
ARG CORAZA_SPOA_VERSION
|
||||
ARG CORAZA_VERSION
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
# OPTIONAL internal package cache, e.g. --build-arg PKG_CACHE=https://192.168.1.40
|
||||
@@ -49,8 +64,10 @@ RUN /usr/local/sbin/pkg-cache-repos.sh apt \
|
||||
RUN git clone --depth 1 --branch "${CORAZA_SPOA_VERSION}" \
|
||||
https://github.com/corazawaf/coraza-spoa.git . \
|
||||
&& eval "$(/usr/local/sbin/pkg-cache-repos.sh go-env)" \
|
||||
&& go get "github.com/corazawaf/coraza/v3@${CORAZA_VERSION}" \
|
||||
&& go mod download \
|
||||
&& CGO_ENABLED=0 GOOS="${TARGETOS:-linux}" GOARCH="${TARGETARCH:-amd64}" go build -trimpath -ldflags='-s -w' -o /out/coraza-spoa . \
|
||||
&& go version -m /out/coraza-spoa | grep -E "^[[:space:]]+dep[[:space:]]+github.com/corazawaf/coraza/v3[[:space:]]+${CORAZA_VERSION}[[:space:]]" \
|
||||
&& /usr/local/sbin/pkg-cache-repos.sh restore
|
||||
|
||||
# Catalog extractor: walks the bundled CRS at build time and emits
|
||||
|
||||
@@ -65,8 +65,14 @@ CRS rules are bundled into the coraza-spoa binary at build time, so the CRS vers
|
||||
1. Check upstream releases: <https://github.com/corazawaf/coraza-spoa/releases>
|
||||
2. Skim the CHANGELOG for new/changed rules in the `overrides.conf` ID ranges.
|
||||
3. Bump `ARG CORAZA_SPOA_VERSION` in the Dockerfile.
|
||||
4. Push to `main` — the Gitea workflow at `.gitea/workflows/build-push-coraza.yaml` rebuilds + pushes `:latest`.
|
||||
5. On each host, run `container-manager.sh recreate coraza-spoa` to pull the new image.
|
||||
4. The Coraza ENGINE is pinned separately (`ARG CORAZA_VERSION`, upgraded in place with `go get`; the build fails if the
|
||||
binary does not embed it). Move it together with WHP's WAF regression net (`scripts/tests/waf-regression` +
|
||||
`scripts/tests/coraza-body-parse-harness` go.mod in the WHP repo), which must pass on the new engine first.
|
||||
5. Bump `coraza-spoa/VERSION` (YYYY.MM.N) and push a `coraza-release/<anything>` branch: CI publishes ONLY
|
||||
`:<VERSION>-rc` and `:<sha>` (never `:latest`). Roll it out host by host with WHP's coraza image pin
|
||||
(`/etc/whp/coraza-image`, then `container-manager.sh recreate coraza-spoa`).
|
||||
6. Only after the staged rollout, merge to `main`: CI then publishes `:latest` + `:<VERSION>` + `:<sha>`. Moving
|
||||
`:latest` IS a fleet-wide rollout: `apply-coraza-waf-mode.sh` pulls `:latest` on every WAF mode apply on unpinned hosts.
|
||||
|
||||
## Tuning false positives
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
2026.11.1
|
||||
@@ -57,6 +57,42 @@ applications:
|
||||
# trees that could not be sampled. Depth 64 itself costs ~21 ms.
|
||||
SecRequestBodyJsonDepthLimit 64
|
||||
|
||||
# Argument-count limit, per source (ARGS_GET, ARGS_POST, ARGS_PATH).
|
||||
# Coraza 3.8 started ENFORCING SecArgumentsLimit (default 1000) on
|
||||
# urlencoded and JSON bodies and on the query string: parsing stops at
|
||||
# the limit, ARGUMENTS_LIMIT_REACHED is set, and every argument after it
|
||||
# is never inspected (GHSA-3ww9-vw83-9w5x). Coraza <= 3.7 inspected every
|
||||
# urlencoded/JSON argument. With the default, "1000 filler args + an
|
||||
# LFI in arg 1001" bypassed 930120 (an enforced rule) on 3.8.1 in WHP's
|
||||
# regression net. Upstream pairs the cap with deny rules 200004/200005,
|
||||
# but those live in Coraza's own coraza.conf-recommended; the
|
||||
# @coraza.conf-recommended Included above is the one embedded in
|
||||
# coraza-coreruleset v4.25.0, which predates them.
|
||||
# 65536 = SecRequestBodyLimit / 2: a urlencoded pair is at least two
|
||||
# bytes ("a&"), so no body we accept can reach the limit, and the query
|
||||
# string is bounded by tune.bufsize (16 KB) far below it. Every argument
|
||||
# is therefore inspected, exactly as on 3.7. Memory stays bounded by
|
||||
# the body limit (the reason upstream added the cap). WHP's JSON
|
||||
# argument-count guard (991900030/031, ">= 1000" in pre-overrides.conf)
|
||||
# is unaffected: it counts what this limit lets through.
|
||||
SecArgumentsLimit 65536
|
||||
|
||||
# Defense in depth for the limit above (unreachable while it is
|
||||
# >= SecRequestBodyLimit / 2): if arguments were ever dropped, Coraza
|
||||
# did not see the whole request. Same two-rule shape as WHP's JSON
|
||||
# guard: 209620 switches the engine on in enforce mode
|
||||
# (tx.whp_enforce_mode, set in phase 1 by WHP's local-overrides.conf),
|
||||
# 209621 denies; in detect_only it only logs (audit-logged). Phase 2
|
||||
# and placed before pre-overrides/CRS so it runs before every CRS
|
||||
# phase-2 rule. ARGUMENTS_LIMIT_REACHED exists only on Coraza >= 3.8,
|
||||
# which is why this lives in the image, not in WHP's rendered files.
|
||||
SecRule TX:whp_enforce_mode "@eq 1" \
|
||||
"id:209620,phase:2,pass,nolog,t:none,chain"
|
||||
SecRule ARGUMENTS_LIMIT_REACHED "@eq 1" \
|
||||
"t:none,ctl:ruleEngine=On"
|
||||
SecRule ARGUMENTS_LIMIT_REACHED "@eq 1" \
|
||||
"id:209621,phase:2,deny,status:400,log,t:none,msg:'Argument limit reached: arguments were dropped uninspected',tag:'whp/coraza-arguments-limit',ctl:auditEngine=On"
|
||||
|
||||
Include @crs-setup.conf.example
|
||||
|
||||
# Runtime-managed PRE-CRS exclusions written by WHP UI. Empty by default.
|
||||
|
||||
@@ -10,9 +10,26 @@
|
||||
#
|
||||
# The liveness probe is `pidof` (a few ms), NOT python: ensure_haproxy.py imports
|
||||
# the 4000-line manager (Flask, Jinja, ...) which costs ~0.5 s of CPU per run and
|
||||
# was affordable at 15 s but not at 2 s. python only runs when haproxy is gone.
|
||||
# 2026-11 evidence: every watchdog abort took the whole edge down for 15-52 s,
|
||||
# most of it detection latency + start; the default is now 2 s (was 15).
|
||||
# was affordable at 15 s but not at 2 s. 2026-11 evidence: every watchdog abort
|
||||
# took the whole edge down for 15-52 s, most of it detection latency + start.
|
||||
#
|
||||
# FAST PATH (2026-11-26, whp02 abort: python took 16 s just to LOG "process not
|
||||
# found" on an I/O-starved host). When haproxy is gone the loop relaunches it
|
||||
# DIRECTLY FROM BASH against the config on disk (the one the dead master loaded
|
||||
# successfully minutes ago): `haproxy -c -f cfg` first, then the same command,
|
||||
# flags, user and detach trick as haproxy_manager.spawn_haproxy_master()
|
||||
# (`haproxy -W -db -S /tmp/haproxy-cli,level,admin -f cfg`, stderr appended to the
|
||||
# stderr log, re-parented to PID 1 so gunicorn reaps it). Only if that fails
|
||||
# (config missing/invalid, haproxy exits or never logs "Loading success.") does
|
||||
# it fall back to `python ensure_haproxy.py` (regenerates + validates + starts).
|
||||
# Never starts a second master: pidof is re-checked after validation, right
|
||||
# before the launch. Every step is logged with a UTC millisecond timestamp.
|
||||
#
|
||||
# While a recovery is in progress the loop keeps HAPROXY_SUPERVISOR_MARKER
|
||||
# (default /tmp/haproxy-restarting) containing "<epoch-seconds> <supervisor pid>"
|
||||
# so the host watchdog (WHP panel/internal/watchdog/haproxy.go) can see the
|
||||
# in-place restart is underway and not `docker restart` on top of it. It is
|
||||
# removed when the recovery finishes (success or failure).
|
||||
#
|
||||
# Two backoffs:
|
||||
# * a restart attempt that FAILS (config HAProxy rejects): the loop doubles its
|
||||
@@ -36,10 +53,15 @@ _posint() { # _posint VALUE DEFAULT
|
||||
esac
|
||||
}
|
||||
|
||||
INTERVAL="$(_posint "${HAPROXY_SUPERVISOR_INTERVAL:-}" 2)"
|
||||
INTERVAL="$(_posint "${HAPROXY_SUPERVISOR_INTERVAL:-}" 1)"
|
||||
MAX_BACKOFF="$(_posint "${HAPROXY_SUPERVISOR_MAX_BACKOFF:-}" 30)"
|
||||
QUICK_DEATH="$(_posint "${HAPROXY_SUPERVISOR_QUICK_DEATH:-}" 10)"
|
||||
STABLE="$(_posint "${HAPROXY_SUPERVISOR_STABLE:-}" 60)"
|
||||
START_WAIT="$(_posint "${HAPROXY_START_WAIT:-}" 10)"
|
||||
CFG="${HAPROXY_SUPERVISOR_CFG:-/etc/haproxy/haproxy.cfg}"
|
||||
BIN="${HAPROXY_SUPERVISOR_BIN:-haproxy}"
|
||||
MASTER_SOCK="${HAPROXY_SUPERVISOR_SOCKET:-/tmp/haproxy-cli}"
|
||||
MARKER="${HAPROXY_SUPERVISOR_MARKER:-/tmp/haproxy-restarting}"
|
||||
STEPS=""
|
||||
for s in ${HAPROXY_SUPERVISOR_BACKOFF_STEPS:-2 5 10 30}; do
|
||||
v="$(_posint "$s" 0)"
|
||||
@@ -58,6 +80,115 @@ _step() {
|
||||
echo "${v}"
|
||||
}
|
||||
|
||||
# --- logging / timing helpers -------------------------------------------------
|
||||
_now_ms() {
|
||||
if [ -n "${EPOCHREALTIME:-}" ]; then
|
||||
local t="${EPOCHREALTIME/./}" # microseconds
|
||||
echo $(( t / 1000 ))
|
||||
else
|
||||
echo $(( $(date +%s) * 1000 ))
|
||||
fi
|
||||
}
|
||||
_log() { # _log LEVEL MESSAGE... (stderr = container stderr, like the old echo)
|
||||
local lvl="$1"; shift
|
||||
printf '%s [haproxy-supervisor] %s: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)" "${lvl}" "$*" >&2
|
||||
}
|
||||
|
||||
_stderr_log() { # same fallback as haproxy_manager._stderr_log_path()
|
||||
local p="${HAPROXY_STDERR_LOG:-/var/log/haproxy/haproxy-stderr.log}"
|
||||
if mkdir -p "$(dirname "${p}")" 2>/dev/null && (umask 027; : >>"${p}") 2>/dev/null; then
|
||||
echo "${p}"
|
||||
else
|
||||
echo /tmp/haproxy-stderr.log
|
||||
fi
|
||||
}
|
||||
|
||||
_marker_set() { printf '%s %s\n' "$(date +%s)" "$$" >"${MARKER}" 2>/dev/null || true; }
|
||||
_marker_clear() { rm -f "${MARKER}" 2>/dev/null || true; }
|
||||
trap _marker_clear EXIT
|
||||
# A marker left by a supervisor that was SIGKILLed mid-recovery (`docker restart`
|
||||
# kills everything after PID 1 exits; no EXIT trap runs) survives in /tmp, which
|
||||
# a restart does not reset. This process never started that recovery: drop it.
|
||||
_marker_clear
|
||||
|
||||
# Direct bash relaunch. Return 0 = haproxy is up (started here or already
|
||||
# running), 1 = caller must fall back to ensure_haproxy.py.
|
||||
fast_relaunch() {
|
||||
local t0="$1" t cfg_ms log_path offset text i
|
||||
if [ ! -r "${CFG}" ]; then
|
||||
_log WARN "fast path skipped: config ${CFG} missing/unreadable"
|
||||
return 1
|
||||
fi
|
||||
if ! command -v "${BIN}" >/dev/null 2>&1; then
|
||||
_log WARN "fast path skipped: ${BIN} not found on PATH"
|
||||
return 1
|
||||
fi
|
||||
if ! timeout 20 "${BIN}" -c -q -f "${CFG}" >/dev/null 2>&1; then
|
||||
_log WARN "fast path skipped: '${BIN} -c -f ${CFG}' rejected the on-disk config"
|
||||
return 1
|
||||
fi
|
||||
t="$(_now_ms)"; cfg_ms=$(( t - t0 ))
|
||||
_log INFO "on-disk config valid (+${cfg_ms} ms)"
|
||||
# Idempotency: never a second master. Re-check right before launching (the
|
||||
# validation above took time; the API's start_haproxy may have won).
|
||||
if pidof -q haproxy; then
|
||||
_log INFO "haproxy is already running; nothing to start"
|
||||
return 0
|
||||
fi
|
||||
log_path="$(_stderr_log)"
|
||||
offset="$(stat -c %s "${log_path}" 2>/dev/null || echo 0)"
|
||||
# Same detach as spawn_haproxy_master(): the double fork re-parents haproxy to
|
||||
# PID 1 (gunicorn reaps it; a zombie child of this loop would keep pidof true).
|
||||
( chmod 0640 "${log_path}" 2>/dev/null
|
||||
"${BIN}" -W -db -S "${MASTER_SOCK},level,admin" -f "${CFG}" \
|
||||
</dev/null >>"${log_path}" 2>&1 & )
|
||||
t="$(_now_ms)"
|
||||
_log INFO "launched '${BIN} -W -db -S ${MASTER_SOCK},level,admin -f ${CFG}' (+$(( t - t0 )) ms)"
|
||||
# Wait for "Loading success." (deadline HAPROXY_START_WAIT; alive + no [ALERT] at
|
||||
# the deadline also counts), exactly like spawn_haproxy_master().
|
||||
for i in $(seq 1 $(( START_WAIT * 10 ))); do
|
||||
text="$(tail -c +$(( offset + 1 )) "${log_path}" 2>/dev/null || true)"
|
||||
case "${text}" in
|
||||
*"Loading success."*)
|
||||
t="$(_now_ms)"
|
||||
_log INFO "haproxy up in place: config loaded (+$(( t - t0 )) ms since detection)"
|
||||
return 0 ;;
|
||||
esac
|
||||
# exited (or never came up) after the 1 s grace: stop waiting
|
||||
if [ "${i}" -gt 10 ] && ! pidof -q haproxy; then break; fi
|
||||
sleep 0.1
|
||||
done
|
||||
if pidof -q haproxy; then
|
||||
case "${text}" in *"[ALERT]"*) ;; *)
|
||||
_log INFO "haproxy up in place: alive, slow to log (+$(( $(_now_ms) - t0 )) ms since detection)"
|
||||
return 0 ;;
|
||||
esac
|
||||
fi
|
||||
_log ERROR "direct relaunch failed: $(printf '%s' "${text}" | tail -n 3 | tr '\n' '|')"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Recover a missing haproxy: fast path, then the python fallback.
|
||||
recover() {
|
||||
local t0
|
||||
t0="$(_now_ms)"
|
||||
_marker_set
|
||||
_log WARN "haproxy process not found — attempting in-place restart (direct relaunch first)"
|
||||
if fast_relaunch "${t0}"; then
|
||||
_marker_clear
|
||||
return 0
|
||||
fi
|
||||
_log WARN "falling back to ensure_haproxy.py (+$(( $(_now_ms) - t0 )) ms)"
|
||||
if python /haproxy/scripts/ensure_haproxy.py 2>&1; then
|
||||
_log INFO "ensure_haproxy.py succeeded (+$(( $(_now_ms) - t0 )) ms since detection)"
|
||||
_marker_clear
|
||||
return 0
|
||||
fi
|
||||
_log ERROR "ensure_haproxy.py failed (+$(( $(_now_ms) - t0 )) ms)"
|
||||
_marker_clear
|
||||
return 1
|
||||
}
|
||||
|
||||
delay="${INTERVAL}"
|
||||
last_start=-1 # SECONDS at our last successful (re)start; -1 = none yet
|
||||
quick=0 # consecutive deaths within QUICK_DEATH of a start
|
||||
@@ -75,14 +206,14 @@ while true; do
|
||||
if [ "${up}" -lt "${QUICK_DEATH}" ]; then
|
||||
quick=$((quick + 1))
|
||||
wait_s="$(_step "${quick}")"
|
||||
echo "haproxy-supervisor: haproxy died ${up}s after start (quick death #${quick}); waiting ${wait_s}s before restart" >&2
|
||||
_log WARN "haproxy died ${up}s after start (quick death #${quick}); waiting ${wait_s}s before restart"
|
||||
sleep "${wait_s}"
|
||||
pidof -q haproxy && continue
|
||||
elif [ "${up}" -ge "${STABLE}" ]; then
|
||||
quick=0
|
||||
fi
|
||||
fi
|
||||
if python /haproxy/scripts/ensure_haproxy.py 2>&1; then
|
||||
if recover; then
|
||||
delay="${INTERVAL}"
|
||||
last_start="${SECONDS}"
|
||||
else
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real-haproxy test for the supervisor's FAST relaunch path.
|
||||
|
||||
Starts a real `haproxy -W -db` master with a minimal config, runs the REAL
|
||||
scripts/haproxy-supervisor.sh next to it (python is stubbed on PATH so any
|
||||
fallback to ensure_haproxy.py is detected), then kills the worker with SIGABRT
|
||||
(exactly the 2026-11-19/25/26 failure: the master logs exit-on-failure and
|
||||
exits 134). Asserts:
|
||||
|
||||
* the master really exits (the premise of the bug),
|
||||
* a NEW master is serving within 3 s of that exit (it was 16 s on whp02),
|
||||
* it was started directly from bash (the python stub never ran),
|
||||
* the recovery marker existed during the restart and is gone afterwards,
|
||||
* the supervisor log lines carry timestamps for each step,
|
||||
* a second master is never started while one is running,
|
||||
* an invalid on-disk config falls back to ensure_haproxy.py (python stub).
|
||||
|
||||
Needs a real `haproxy`, `pidof`, `bash`, `timeout` (no procps: children are read from /proc). Skips (exit 0, loudly)
|
||||
when haproxy is not installed, so it is meaningful in the image build (where
|
||||
validate-rendered-config.py also needs the binary) and on a dev box with haproxy.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
SUPERVISOR = os.path.join(HERE, 'haproxy-supervisor.sh')
|
||||
HAPROXY = shutil.which('haproxy')
|
||||
|
||||
PYTHON_STUB = """#!/bin/sh
|
||||
date +%s.%N >> "$STATE/python-ran"
|
||||
exit 1
|
||||
"""
|
||||
|
||||
|
||||
def _free_port():
|
||||
s = socket.socket()
|
||||
s.bind(('127.0.0.1', 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
return port
|
||||
|
||||
|
||||
def _all_pids():
|
||||
r = subprocess.run(['pidof', 'haproxy'], stdout=subprocess.PIPE, text=True)
|
||||
return sorted(int(x) for x in r.stdout.split())
|
||||
|
||||
|
||||
def _master_pids():
|
||||
"""haproxy processes whose parent is not itself haproxy (workers share the name)."""
|
||||
pids = _all_pids()
|
||||
out = []
|
||||
for pid in pids:
|
||||
try:
|
||||
with open('/proc/%d/stat' % pid) as fh:
|
||||
ppid = int(fh.read().rsplit(')', 1)[1].split()[1])
|
||||
except (OSError, ValueError, IndexError):
|
||||
continue
|
||||
if ppid not in pids:
|
||||
out.append(pid)
|
||||
return out
|
||||
|
||||
|
||||
def _worker_of(master):
|
||||
"""Children of `master` from /proc (the image has no procps/pgrep)."""
|
||||
out = []
|
||||
for name in os.listdir('/proc'):
|
||||
if not name.isdigit():
|
||||
continue
|
||||
try:
|
||||
with open('/proc/%s/stat' % name) as fh:
|
||||
ppid = int(fh.read().rsplit(')', 1)[1].split()[1])
|
||||
except (OSError, ValueError, IndexError):
|
||||
continue
|
||||
if ppid == master:
|
||||
out.append(int(name))
|
||||
return sorted(out)
|
||||
|
||||
|
||||
@unittest.skipUnless(HAPROXY, 'haproxy binary not installed')
|
||||
class RelaunchTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
if _all_pids():
|
||||
self.skipTest('another haproxy is already running on this host')
|
||||
self.d = tempfile.mkdtemp(prefix='hap-relaunch-')
|
||||
self.state = os.path.join(self.d, 'state')
|
||||
os.mkdir(self.state)
|
||||
self.port = _free_port()
|
||||
self.cfg = os.path.join(self.d, 'haproxy.cfg')
|
||||
self.write_cfg(valid=True)
|
||||
self.log = os.path.join(self.d, 'stderr.log')
|
||||
self.marker = os.path.join(self.d, 'restarting')
|
||||
self.sock = os.path.join(self.d, 'cli')
|
||||
py = os.path.join(self.d, 'python')
|
||||
with open(py, 'w') as fh:
|
||||
fh.write(PYTHON_STUB)
|
||||
os.chmod(py, os.stat(py).st_mode | stat.S_IXUSR)
|
||||
self.env = dict(os.environ, PATH=self.d + ':' + os.environ['PATH'], STATE=self.state,
|
||||
HAPROXY_SUPERVISOR_CFG=self.cfg, HAPROXY_SUPERVISOR_MARKER=self.marker,
|
||||
HAPROXY_SUPERVISOR_SOCKET=self.sock, HAPROXY_STDERR_LOG=self.log)
|
||||
self.sup = None
|
||||
|
||||
def tearDown(self):
|
||||
if self.sup:
|
||||
self.sup.terminate()
|
||||
try:
|
||||
self.sup.wait(5)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.sup.kill()
|
||||
self.sup.wait()
|
||||
for pid in _all_pids():
|
||||
try:
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
except OSError:
|
||||
pass
|
||||
if getattr(self, 'suplog', None):
|
||||
self.suplog.close()
|
||||
end = time.monotonic() + 5
|
||||
while _all_pids() and time.monotonic() < end: # let the kernel finish reaping before the next test
|
||||
time.sleep(0.05)
|
||||
shutil.rmtree(self.d, ignore_errors=True)
|
||||
|
||||
def write_cfg(self, valid):
|
||||
body = ('global\n maxconn 100\n\n'
|
||||
'defaults\n mode http\n timeout connect 1s\n timeout client 5s\n timeout server 5s\n\n'
|
||||
'frontend fe\n bind 127.0.0.1:%d\n http-request return status 200 content-type text/plain string ok\n'
|
||||
% self.port)
|
||||
if not valid:
|
||||
body += '\nthis-is-not-a-haproxy-keyword 1\n'
|
||||
with open(self.cfg, 'w') as fh:
|
||||
fh.write(body)
|
||||
|
||||
def start_master(self):
|
||||
with open(self.log, 'ab') as lf:
|
||||
subprocess.Popen([HAPROXY, '-W', '-db', '-S', self.sock + ',level,admin', '-f', self.cfg],
|
||||
stdin=subprocess.DEVNULL, stdout=lf, stderr=lf, start_new_session=True)
|
||||
self.wait_for(lambda: self.serving(), 10, 'initial master serving')
|
||||
return _master_pids()[0]
|
||||
|
||||
def serving(self):
|
||||
try:
|
||||
with socket.create_connection(('127.0.0.1', self.port), timeout=0.5) as c:
|
||||
c.sendall(b'GET / HTTP/1.0\r\n\r\n')
|
||||
return b'200' in c.recv(64)
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def wait_for(self, fn, timeout, what):
|
||||
end = time.monotonic() + timeout
|
||||
while time.monotonic() < end:
|
||||
if fn():
|
||||
return time.monotonic()
|
||||
time.sleep(0.02)
|
||||
self.fail('timed out waiting for ' + what)
|
||||
|
||||
def start_supervisor(self, **extra):
|
||||
env = dict(self.env, **extra)
|
||||
self.suplog = open(os.path.join(self.d, 'supervisor.out'), 'w')
|
||||
self.sup = subprocess.Popen(['bash', SUPERVISOR], env=env, stdout=self.suplog, stderr=subprocess.STDOUT,
|
||||
stdin=subprocess.DEVNULL)
|
||||
|
||||
def sup_output(self):
|
||||
self.suplog.flush()
|
||||
with open(os.path.join(self.d, 'supervisor.out')) as fh:
|
||||
return fh.read()
|
||||
|
||||
def test_worker_abort_is_relaunched_directly_in_under_3_seconds(self):
|
||||
master = self.start_master()
|
||||
self.start_supervisor()
|
||||
workers = _worker_of(master)
|
||||
self.assertTrue(workers, 'no worker under the master')
|
||||
os.kill(workers[0], signal.SIGABRT)
|
||||
# premise: the master exits on a worker abort (exit-on-failure)
|
||||
died = self.wait_for(lambda: master not in _master_pids(), 5, 'master to exit after the worker abort')
|
||||
up = self.wait_for(lambda: self.serving() and master not in _master_pids(), 10, 'relaunched edge serving')
|
||||
gap = up - died
|
||||
self.wait_for(lambda: 'haproxy up in place' in self.sup_output(), 3, 'supervisor "up in place" line')
|
||||
out = self.sup_output()
|
||||
print('measured relaunch time (master exit -> serving): %.2f s' % gap)
|
||||
self.assertLess(gap, 3.0, out)
|
||||
new = _master_pids()
|
||||
self.assertEqual(len(new), 1, 'exactly one master, got %r' % new)
|
||||
self.assertNotEqual(new[0], master)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.state, 'python-ran')), 'fast path fell back to python\n' + out)
|
||||
for step in ('haproxy process not found', 'on-disk config valid', 'launched', 'haproxy up in place'):
|
||||
self.assertIn(step, out)
|
||||
self.assertRegex(out, r'\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \[haproxy-supervisor\]')
|
||||
self.wait_for(lambda: not os.path.exists(self.marker), 3, 'marker cleared')
|
||||
|
||||
def test_marker_exists_while_restarting(self):
|
||||
master = self.start_master()
|
||||
self.start_supervisor()
|
||||
os.kill(_worker_of(master)[0], signal.SIGABRT)
|
||||
seen = []
|
||||
end = time.monotonic() + 8
|
||||
while time.monotonic() < end:
|
||||
if os.path.exists(self.marker):
|
||||
with open(self.marker) as fh:
|
||||
seen.append(fh.read().split())
|
||||
if seen and not os.path.exists(self.marker):
|
||||
break
|
||||
time.sleep(0.005)
|
||||
# the recovery is ~100s of ms: a 5 ms poll sees the marker unless it was missed entirely
|
||||
self.assertTrue(seen, 'marker never observed\n' + self.sup_output())
|
||||
self.assertEqual(len(seen[0]), 2)
|
||||
self.assertLess(abs(int(seen[0][0]) - time.time()), 30)
|
||||
|
||||
def test_running_master_is_never_duplicated(self):
|
||||
master = self.start_master()
|
||||
self.start_supervisor()
|
||||
time.sleep(3.5)
|
||||
self.assertEqual(_master_pids(), [master])
|
||||
self.assertNotIn('haproxy process not found', self.sup_output())
|
||||
|
||||
def test_invalid_config_falls_back_to_ensure_haproxy(self):
|
||||
master = self.start_master()
|
||||
self.start_supervisor()
|
||||
self.write_cfg(valid=False)
|
||||
os.kill(_worker_of(master)[0], signal.SIGABRT)
|
||||
self.wait_for(lambda: os.path.exists(os.path.join(self.state, 'python-ran')), 8, 'python fallback')
|
||||
self.assertIn('rejected the on-disk config', self.sup_output())
|
||||
self.assertEqual(_master_pids(), [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not HAPROXY:
|
||||
print('SKIP: haproxy not installed; the real-haproxy relaunch test did not run')
|
||||
unittest.main()
|
||||
@@ -25,7 +25,7 @@ exit ${ENSURE_RC:-0}
|
||||
"""
|
||||
|
||||
|
||||
class SupervisorTests(unittest.TestCase):
|
||||
class SupervisorBase:
|
||||
def setUp(self):
|
||||
self.d = tempfile.mkdtemp(prefix='hap-sup-')
|
||||
self.state = os.path.join(self.d, 'state')
|
||||
@@ -39,6 +39,10 @@ class SupervisorTests(unittest.TestCase):
|
||||
def run_sup(self, seconds, **env):
|
||||
e = dict(os.environ, PATH=self.d + ':' + os.environ['PATH'], STATE=self.state)
|
||||
e.setdefault('LIFE', '0')
|
||||
# keep the fast path OFF unless a test opts in (no config -> python fallback)
|
||||
e.setdefault('HAPROXY_SUPERVISOR_CFG', os.path.join(self.d, 'no-such.cfg'))
|
||||
e.setdefault('HAPROXY_SUPERVISOR_MARKER', os.path.join(self.state, 'marker'))
|
||||
e.setdefault('HAPROXY_STDERR_LOG', os.path.join(self.d, 'stderr.log'))
|
||||
e.update(env)
|
||||
try:
|
||||
subprocess.run(['bash', SCRIPT], env=e, timeout=seconds, stdout=subprocess.PIPE,
|
||||
@@ -54,6 +58,8 @@ class SupervisorTests(unittest.TestCase):
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
class SupervisorTests(SupervisorBase, unittest.TestCase):
|
||||
def test_non_integer_interval_does_not_kill_the_supervisor(self):
|
||||
self.assertEqual(self.run_sup(8, HAPROXY_SUPERVISOR_INTERVAL='0.5', ENSURE_RC='1'), 'running')
|
||||
self.assertGreaterEqual(len(self.starts()), 2) # fell back to the default interval and kept trying
|
||||
@@ -93,5 +99,78 @@ class SupervisorTests(unittest.TestCase):
|
||||
self.assertEqual(self.starts(), [])
|
||||
|
||||
|
||||
# stand-in `haproxy`: -c validates (rc from $CHECK_RC); a launch stamps the start,
|
||||
# logs the line the supervisor waits for, and records whether the marker existed
|
||||
HAPROXY = """#!/bin/sh
|
||||
if [ "$1" = "-c" ]; then exit ${CHECK_RC:-0}; fi
|
||||
[ -f "$MARKER" ] && echo yes >> "$STATE/marker-seen"
|
||||
date +%s.%N > "$STATE/started"
|
||||
date +%s.%N >> "$STATE/direct"
|
||||
echo "[NOTICE] Loading success." >&2
|
||||
exit ${LAUNCH_RC:-0}
|
||||
"""
|
||||
|
||||
|
||||
class FastPathTests(SupervisorBase, unittest.TestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
p = os.path.join(self.d, 'haproxy')
|
||||
with open(p, 'w') as fh:
|
||||
fh.write(HAPROXY)
|
||||
os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR)
|
||||
self.cfg = os.path.join(self.d, 'haproxy.cfg')
|
||||
with open(self.cfg, 'w') as fh:
|
||||
fh.write('# stub\n')
|
||||
|
||||
def fast_env(self, **kw):
|
||||
e = dict(HAPROXY_SUPERVISOR_CFG=self.cfg, MARKER=os.path.join(self.state, 'marker'),
|
||||
HAPROXY_SUPERVISOR_INTERVAL='1', LIFE='1000')
|
||||
e.update(kw)
|
||||
return e
|
||||
|
||||
def direct(self):
|
||||
try:
|
||||
with open(os.path.join(self.state, 'direct')) as fh:
|
||||
return fh.read().split()
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
def test_dead_haproxy_is_relaunched_directly_without_python(self):
|
||||
self.run_sup(4, **self.fast_env(LIFE='0')) # LIFE=0: haproxy is always "gone" at the first poll
|
||||
self.assertGreaterEqual(len(self.direct()), 1)
|
||||
self.assertEqual(self.starts(), []) # ensure_haproxy.py / python never ran
|
||||
with open(os.path.join(self.state, 'marker-seen')) as fh:
|
||||
self.assertEqual(fh.read().split(), ['yes'] * len(self.direct()))
|
||||
self.assertFalse(os.path.exists(os.path.join(self.state, 'marker'))) # cleared after the recovery
|
||||
|
||||
def test_invalid_config_falls_back_to_python(self):
|
||||
self.run_sup(4, **self.fast_env(LIFE='0', CHECK_RC='1'))
|
||||
self.assertEqual(self.direct(), [])
|
||||
self.assertGreaterEqual(len(self.starts()), 1)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.state, 'marker')))
|
||||
|
||||
def test_failed_direct_launch_falls_back_to_python(self):
|
||||
# haproxy binary not on PATH: the direct path cannot start it
|
||||
self.run_sup(4, **self.fast_env(LIFE='0', HAPROXY_SUPERVISOR_BIN='no-such-haproxy-bin'))
|
||||
self.assertEqual(self.direct(), [])
|
||||
self.assertGreaterEqual(len(self.starts()), 1)
|
||||
|
||||
def test_missing_config_falls_back_to_python(self):
|
||||
self.run_sup(4, **self.fast_env(LIFE='0', HAPROXY_SUPERVISOR_CFG=os.path.join(self.d, 'gone.cfg')))
|
||||
self.assertEqual(self.direct(), [])
|
||||
self.assertGreaterEqual(len(self.starts()), 1)
|
||||
|
||||
def test_running_haproxy_never_gets_a_second_master(self):
|
||||
with open(os.path.join(self.state, 'started'), 'w') as fh:
|
||||
fh.write(str(time.time()))
|
||||
self.assertEqual(self.run_sup(3, **self.fast_env()), 'running')
|
||||
self.assertEqual(self.direct(), [])
|
||||
self.assertEqual(self.starts(), [])
|
||||
|
||||
def test_poll_interval_defaults_to_one_second(self):
|
||||
self.run_sup(3, **{k: v for k, v in self.fast_env(LIFE='0').items() if k != 'HAPROXY_SUPERVISOR_INTERVAL'})
|
||||
self.assertGreaterEqual(len(self.direct()), 1) # first relaunch inside the 3 s budget (2 s poll + start would not fit twice)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user