From 6c7c58b35ac90a57ae2f95e3e6a7dba664393535 Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 30 Sep 2026 01:36:23 +0000 Subject: [PATCH] infra: RestartMode=direct so OnFailure= fires only at the start limit; one lock for fly-runtime rollback and fallback Verified on systemd 257: with the default RestartMode=normal the unit passes through failed before every auto-restart, so OnFailure= ran on the first crash. The session drop-in now sets RestartMode=direct. session, legacy, fallback and the trap rollback share one flock; a switch holds it only until its restart is queued (restart --no-block, health checked against the new invocation), and the rollback skips restoring an older drop-in once a fallback has completed. lint.sh covers the drop-in key, the interleaving and the shared lock; runbook corrected. --- infra/05-deploy.sh | 2 +- infra/bin/fly-runtime | 62 +++++++++++++++++++++--- infra/docs/runbook.md | 19 ++++++-- infra/tests/lint.sh | 45 +++++++++++++++-- infra/units/fly-runtime-fallback.service | 3 +- 5 files changed, 112 insertions(+), 19 deletions(-) diff --git a/infra/05-deploy.sh b/infra/05-deploy.sh index eeb164c..cbdcf8f 100644 --- a/infra/05-deploy.sh +++ b/infra/05-deploy.sh @@ -397,7 +397,7 @@ The 'current' symlink has NOT been moved; the running release is untouched." # the shadow for the new flysim-session binary; the trust gates before the release (the # parity and service tests, the compat check just below) are what vouch for it. A bad # release is caught afterwards by the persistent fallback: while the drop-in exists, - # flysim.service carries OnFailure=fly-runtime-fallback.service with a 3-starts-in-10-minutes + # flysim.service carries OnFailure=fly-runtime-fallback.service and RestartMode=direct with a 3-starts-in-10-minutes # limit, so a session binary that will not stay up puts the fly back on legacy by itself # (`fly-runtime fallback`, /run/fly/runtime-fellback.json), whoever restarted it. if ct_exec "$CTID" -- test -f /etc/systemd/system/flysim.service.d/10-runtime.conf; then diff --git a/infra/bin/fly-runtime b/infra/bin/fly-runtime index c43cfad..6247f65 100755 --- a/infra/bin/fly-runtime +++ b/infra/bin/fly-runtime @@ -41,8 +41,13 @@ # OnFailure=fly-runtime-fallback.service # StartLimitIntervalSec=600 # StartLimitBurst=3 +# [Service] +# RestartMode=direct # -# so while the session runtime is selected, three starts of flysim.service inside ten minutes +# RestartMode=direct is essential (systemd >= 254; verified on 257): with the default +# RestartMode=normal the unit passes through `failed` before every Restart=always restart and +# OnFailure= fires on the FIRST crash, watchdog kill or start timeout. With `direct` the unit +# goes from one start straight to the next and only the start limit puts it in `failed`. So while the session runtime is selected, three starts of flysim.service inside ten minutes # (crashes, watchdog kills, a start that never becomes ready, the restarts fly-watchdog and # fly-loop-recover make for a stream that does not come up) end in the failed state, and systemd # runs fly-runtime-fallback.service, i.e. `fly-runtime fallback`: write ${FELLBACK_FILE}, remove @@ -68,6 +73,7 @@ set -euo pipefail : "${FLY_RUNTIME_LOG:=/var/lib/fly/runtime.log}" : "${FLY_RUNTIME_FELLBACK:=/run/fly/runtime-fellback.json}" : "${FLY_RUNTIME_LOCK:=/run/fly/runtime.lock}" +: "${FLY_RUNTIME_LOCK_WAIT:=150}" DROPIN_DIR="${FLY_SYSTEMD_DIR}/${FLY_SERVICE}.d" DROPIN="${DROPIN_DIR}/10-runtime.conf" RUNTIME_LOG="$FLY_RUNTIME_LOG" @@ -123,12 +129,15 @@ write_dropin() { cat >"$tmp" <= 254 otherwise passes through the failed state (and OnFailure=) before EVERY auto-restart. +# Keep [Service] in step with units/flysim-session.service. [Unit] OnFailure=${FALLBACK_UNIT} StartLimitIntervalSec=600 StartLimitBurst=3 [Service] +RestartMode=direct ExecStart= ExecStart=${SESSION_BIN} Environment=FLY_SESSION_DIR=${SESSION_DIR} @@ -143,6 +152,11 @@ healthy() { local deadline=$(( $(date +%s) + FLY_RUNTIME_HEALTH_TIMEOUT )) local first="" while [ "$(date +%s)" -lt "$deadline" ]; do + if [ -n "$old_invocation" ] \ + && [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then + sleep 1 + continue + fi if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then local frame frame="$(curl -fsS "${FLY_CONTROL_URL}/status" 2>/dev/null \ @@ -161,13 +175,38 @@ healthy() { return 1 } +# One lock (${FLY_RUNTIME_LOCK}) serialises every change of the drop-in: `fallback`, `session`, +# `legacy` and the rollback in on_exit. A switch holds it from before it reads the current state +# until its restart has been queued (`restart --no-block`), and lets go before the health wait, so +# an OnFailure= fallback is never held up by a start that does not become ready. Re-entrant per +# process. Waits FLY_RUNTIME_LOCK_WAIT (150 s). +locked=0 +take_lock() { + if [ "$locked" -eq 1 ]; then return 0; fi + mkdir -p "$(dirname "$FLY_RUNTIME_LOCK")" 2>/dev/null || true + exec 9>>"$FLY_RUNTIME_LOCK" + if flock -w "$FLY_RUNTIME_LOCK_WAIT" 9; then locked=1; return 0; fi + log "could not take ${FLY_RUNTIME_LOCK} within ${FLY_RUNTIME_LOCK_WAIT} s" + return 1 +} +drop_lock() { + exec 9>&- + locked=0 +} + restarted=0 +old_invocation="" restart_and_check() { systemctl daemon-reload systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true log "restarting ${FLY_SERVICE} on the $(current) runtime" restarted=1 - systemctl restart "$FLY_SERVICE" + # --no-block: a blocking restart of a unit that never becomes READY holds this process (and + # the lock) for minutes, starving the OnFailure= fallback. `healthy` therefore has to prove + # that it is talking to the NEW invocation, not the old process that is still shutting down. + old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" + systemctl restart --no-block "$FLY_SERVICE" || { drop_lock; return 1; } + drop_lock healthy } @@ -179,9 +218,7 @@ restart_and_check() { # watchdog) judges health, and a oneshot unit must not sit in a 90 s notify start. do_fallback() { local reason="$1" result nrestarts saved - mkdir -p "$(dirname "$FLY_RUNTIME_LOCK")" 2>/dev/null || true - exec 9>>"$FLY_RUNTIME_LOCK" - flock -w 60 9 || log "could not take ${FLY_RUNTIME_LOCK} within 60 s; continuing" + take_lock || log "continuing without the lock" if [ ! -f "$DROPIN" ]; then log "fallback: the legacy runtime is already selected; nothing to do" return 0 @@ -221,7 +258,10 @@ do_fallback() { # An interrupted or failed switch puts the previous state back. `switching` is 1 from just # before the drop-in is touched until the switch has finished; `prev_dropin` is a copy of the -# drop-in that was there before (empty: none, i.e. legacy). +# drop-in that was there before (empty: none, i.e. legacy). The rollback runs under the lock and +# does nothing when a fallback has completed since the switch began (FELLBACK_FILE exists: the +# switch deleted it under the lock, only a finished fallback writes it): restoring the older +# drop-in then would strand the stream on the session runtime after it was taken off. switching=0 switch_target="" prev_dropin="" @@ -231,7 +271,11 @@ on_exit() { trap - EXIT INT TERM HUP if [ "$switching" -eq 1 ]; then switching=0 - if [ "$switch_target" = session ]; then + take_lock || true + if [ "$switch_target" = session ] && [ -f "$FELLBACK_FILE" ]; then + record "legacy (switch to session interrupted or failed (exit ${rc}); a fallback completed meanwhile, not restoring the older drop-in)" + restarted=0 + elif [ "$switch_target" = session ]; then if [ -n "$prev_dropin" ] && [ -f "$prev_dropin" ]; then mkdir -p "$DROPIN_DIR" && cp -f "$prev_dropin" "$DROPIN" else @@ -299,6 +343,7 @@ if [ "$command" = session ]; then flysim: ${legacy_compat} flysim-session: ${session_compat}" fi + take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching" before="$(current)" if [ -f "$DROPIN" ]; then prev_dropin="$(mktemp "${DROPIN}.prev.XXXXXX")" @@ -343,6 +388,7 @@ if [ "$command" = session ]; then fi # legacy +take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching" before="$(current)" switch_target=legacy switching=1 diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index ad34322..8133bb7 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -470,9 +470,13 @@ pct exec $CTID -- /opt/fly/bin/fly-runtime legacy # the one-command rollback switches back to legacy by itself and exits 1 (`--no-fallback` leaves it to the operator). Every switch is logged (`journalctl -t fly-runtime`, `/var/lib/fly/runtime.log`). - **The fallback outlives the switch (C1).** While the session runtime is selected, the drop-in - also sets `OnFailure=fly-runtime-fallback.service`, `StartLimitBurst=3` and - `StartLimitIntervalSec=600`, and `MALLOC_ARENA_MAX=2` (glibc arena fragmentation was the whole - of the 5-8 MB/h RSS growth). Three starts of `flysim.service` within ten minutes, from any + also sets `OnFailure=fly-runtime-fallback.service`, `StartLimitBurst=3`, + `StartLimitIntervalSec=600` and `RestartMode=direct`, and `MALLOC_ARENA_MAX=2` (glibc arena + fragmentation was the whole of the 5-8 MB/h RSS growth). `RestartMode=direct` is what makes the + limit real: since systemd 254 the default (`normal`) sends the unit through the `failed` state + before every `Restart=always` restart, so `OnFailure=` would fire on the first crash, watchdog + kill or start timeout (seen on systemd 257, the container's). With `direct` the unit goes from + one start to the next and only hitting the start limit fails it. Three starts of `flysim.service` within ten minutes, from any cause and any caller (a reboot, the watchdog or `fly-loop-recover` restarting it, a deploy, a binary that crashes, hangs before READY or is killed by `WatchdogSec`) make systemd run `fly-runtime fallback`: it writes `/run/fly/runtime-fellback.json` (time, reason, unit result), @@ -480,13 +484,18 @@ pct exec $CTID -- /opt/fly/bin/fly-runtime legacy # the one-command rollback a `fly-runtime` journal line. It is idempotent, and it does nothing if the release has no executable `flysim`. Look with `fly-runtime status` (it prints the reason) or `cat /run/fly/runtime-fellback.json`; the container is then on legacy until an operator runs - `fly-runtime session` again, which clears the reason file. Three legitimate restarts in ten + `fly-runtime session` again, which clears the reason file. Restarts you make yourself count + too, and once the limit is reached systemd refuses the next start and runs the fallback. Three legitimate restarts in ten minutes count the same as three crashes: after that many, prefer `fly-runtime legacy`, do the work, then switch back. - **Interrupted switches roll back.** `fly-runtime` traps INT, TERM and HUP (an ssh that drops mid-switch): an unfinished `session` removes the drop-in again (or restores the one that was there) and restarts `flysim.service` on that state, so a drop-in that never passed its health - check is never left behind. + check is never left behind. `session`, `legacy`, `fallback` and that rollback all take one lock + (`/run/fly/runtime.lock`); a switch holds it while it changes the drop-in and queues the restart + (`systemctl restart --no-block`, so a unit that never becomes READY cannot hold it) and releases + it for the health wait. The rollback does nothing when a fallback finished after the switch began (the + reason file exists), so it can never put back an older drop-in over a fallback. - **What stays the same.** Everything that names `flysim.service` keeps working unchanged: `fly.target`, `flyedge.service`'s `Requires=`, the watchdog, `fly-loop-recover`'s restart and its sudoers line, `fly-loop-reset`, `fly-reset-to-milestone` (run with the service stopped, on diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index d1674b5..e330943 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -653,7 +653,7 @@ if fly_runtime && [ -f "$rt_dropin" ] \ && grep -qx "ExecStart=$rt_dir/release/flysim-session" "$rt_dropin" \ && grep -qx 'ExecStart=' "$rt_dropin" \ && grep -qx 'Environment=FLY_SESSION_DIR=/run/fly/session' "$rt_dropin" \ - && grep -qx 'restart flysim.service' "$rt_dir/systemctl.log" \ + && grep -qx 'restart --no-block flysim.service' "$rt_dir/systemctl.log" \ && [ "$(env RT_DIR="$rt_dir" PATH="$rt_dir/bin:$PATH" FLY_SYSTEMD_DIR="$rt_dir/systemd" bash "$INFRA_DIR/bin/fly-runtime" status 2>/dev/null | head -n1)" = session ]; then pass "fly-runtime session: the drop-in names flysim-session and /run/fly/session, flysim.service restarted, healthy" else @@ -685,12 +685,13 @@ fly_runtime || fail "fly-runtime session (healthy) failed before the fallback te if grep -qx 'OnFailure=fly-runtime-fallback.service' "$rt_dropin" \ && grep -qx 'StartLimitBurst=3' "$rt_dropin" \ && grep -qx 'StartLimitIntervalSec=600' "$rt_dropin" \ + && grep -qx 'RestartMode=direct' "$rt_dropin" \ && grep -qx 'Environment=MALLOC_ARENA_MAX=2' "$rt_dropin" \ && [ -f "$FALLBACK_UNIT" ] \ && grep -qE '^ExecStart=/opt/fly/bin/fly-runtime fallback$' "$FALLBACK_UNIT" \ && grep -qx 'Type=oneshot' "$FALLBACK_UNIT" \ && ! grep -q '^\[Install\]' "$FALLBACK_UNIT"; then - pass "session drop-in: OnFailure= fallback unit, 3 starts in 600 s, MALLOC_ARENA_MAX=2; the unit runs 'fly-runtime fallback'" + pass "session drop-in: OnFailure= fallback unit, 3 starts in 600 s, RestartMode=direct (else OnFailure= fires on every crash), MALLOC_ARENA_MAX=2; the unit runs 'fly-runtime fallback'" else fail "session drop-in/fallback unit wrong ($(tr '\n' ' ' < "$rt_dropin"))" fi @@ -778,7 +779,7 @@ fi # Signals: an interrupted switch rolls back to the previous state. rt_interrupt() { # $1 = signal: run `session` on an unhealthy runtime, signal it mid-wait, print its status local sig="$1" pid rc=0 n=0 base - base="$(rt_ncalls '^restart flysim.service')" + base="$(rt_ncalls '^restart --no-block flysim.service')" env RT_DIR="$rt_dir" PATH="$rt_dir/bin:$PATH" FLY_RELEASE_DIR="$rt_dir/release" \ FLY_ENV_FILE="$rt_dir/fly.env" FLY_SYSTEMD_DIR="$rt_dir/systemd" \ FLY_RUNTIME_LOG="$rt_dir/runtime.log" FLY_RUNTIME_HEALTH_TIMEOUT=60 RT_HEALTHY=0 \ @@ -787,9 +788,10 @@ rt_interrupt() { # $1 = signal: run `session` on an unhealthy runtime, signal i signal.signal(signal.SIGINT, signal.SIG_DFL) # a background job of a non-interactive shell starts with INT ignored os.execvp(sys.argv[1], sys.argv[1:])' bash "$INFRA_DIR/bin/fly-runtime" session >/dev/null 2>&1 & pid=$! - while [ "$(rt_ncalls '^restart flysim.service')" -le "$base" ] && [ "$n" -lt 100 ]; do + while [ "$(rt_ncalls '^restart --no-block flysim.service')" -le "$base" ] && [ "$n" -lt 100 ]; do n=$((n + 1)); sleep 0.1 done + if [ -n "${2:-}" ]; then "$2" >/dev/null 2>&1 || true; fi kill "-$sig" "$pid" 2>/dev/null || true wait "$pid" || rc=$? echo "$rc" @@ -817,6 +819,41 @@ if [ "$got_rc" = 143 ] && cmp -s "$rt_dropin" "$rt_dir/dropin.before" \ else fail "an interrupted re-run of session must restore the earlier drop-in (rc=$got_rc)" fi +# M2, deterministic interleaving: a re-run of `session` over an older drop-in is waiting for +# health, an OnFailure= fallback completes, THEN the switch is interrupted. The rollback must +# not put the older drop-in back (it has no OnFailure=, and the stream would be stranded on the +# session runtime). +# shellcheck disable=SC2317 # called through rt_interrupt +rt_fallback_now() { + env RT_DIR="$rt_dir" PATH="$rt_dir/bin:$PATH" FLY_RELEASE_DIR="$rt_dir/release" \ + FLY_SYSTEMD_DIR="$rt_dir/systemd" FLY_RUNTIME_LOG="$rt_dir/runtime.log" \ + FLY_RUNTIME_FELLBACK="$rt_fellback" FLY_RUNTIME_LOCK="$rt_dir/run/runtime.lock" \ + bash "$INFRA_DIR/bin/fly-runtime" fallback "lint interleaving" +} +mkdir -p "$(dirname "$rt_dropin")" +printf '# older-session-marker\n[Service]\nExecStart=\nExecStart=/previous\n' > "$rt_dropin" +got_rc="$(rt_interrupt TERM rt_fallback_now)" +if [ "$got_rc" = 143 ] && [ ! -f "$rt_dropin" ] && [ -f "$rt_fellback" ] \ + && grep -q 'a fallback completed meanwhile' "$rt_dir/runtime.log"; then + pass "rollback after a completed fallback leaves legacy selected (does not restore the older drop-in)" +else + fail "rollback must not restore an older drop-in after a completed fallback (rc=$got_rc, drop-in present=$([ -f "$rt_dropin" ] && echo yes || echo no))" +fi +# ... and the two share ONE lock: a held lock stops `session` from touching anything. +rm -f "$rt_dropin" "$rt_fellback" +( + exec 8>>"$rt_dir/run/runtime.lock" + flock 8 + RT_ARGS=(session) + if ! fly_runtime FLY_RUNTIME_LOCK_WAIT=1 && [ ! -f "$rt_dropin" ]; then + touch "$rt_dir/lock-respected" + fi +) +if [ -f "$rt_dir/lock-respected" ]; then + pass "fly-runtime session waits on the same lock as fallback and does not switch without it" +else + fail "fly-runtime session must take the shared ${FLY_RUNTIME_LOCK:-runtime.lock} lock" +fi rm -f "$rt_dropin" mv "$rt_dir/release/flysim-session" "$rt_dir/flysim-session.away" if ! fly_runtime && [ ! -f "$rt_dropin" ]; then diff --git a/infra/units/fly-runtime-fallback.service b/infra/units/fly-runtime-fallback.service index 8cb542d..6f3d5d4 100644 --- a/infra/units/fly-runtime-fallback.service +++ b/infra/units/fly-runtime-fallback.service @@ -3,7 +3,8 @@ # The persistent fallback from the session runtime to the legacy loop (SERVE-01 review, C1). # It is never enabled and in no target: the drop-in that `fly-runtime session` writes on # flysim.service (10-runtime.conf) carries `OnFailure=fly-runtime-fallback.service` together with -# StartLimitIntervalSec=600 and StartLimitBurst=3, so three starts of flysim.service on the +# StartLimitIntervalSec=600, StartLimitBurst=3 and RestartMode=direct (without it OnFailure= fires on +# every crash, not at the start limit), so three starts of flysim.service on the # session binary inside ten minutes -- from any cause, and from any caller: a reboot, the # watchdog, fly-loop-recover, a deploy -- run this unit once. `fly-runtime fallback` removes the # drop-in (which removes this OnFailure= too), daemon-reloads, restarts flysim.service on the