fix(shater-core): name which of the four ways shaterd migrate ended
Both call sites swallowed the result. /etc/uci-defaults/30_shater-core ran `shaterd migrate >/dev/null 2>&1` — stdout, stderr AND the exit status gone, so a refusal was indistinguishable from a success on the one screen the operator who caused it was reading. /etc/init.d/shater logged, but with a single sentence that described only one of the outcomes: "routing rules that still carry the removed dst_domain/dst_ip options stay DISABLED until this succeeds. Free space on /overlay and re-run". On a DOWNGRADE every clause of that is false — nothing is disabled, /overlay is not the problem, and re-running never helps, because the fix is to put the newer package back. A confident wrong diagnosis costs more than no diagnosis. The outcome is now classified with a CLOSED positive list — ok / downgrade / unreadable / failed — and the last rung is the point of it: an unrecognised failure says it is unrecognised and quotes the binary verbatim instead of being reported as one of the causes we can name. `downgrade` is recognised by the substring "newer than this build", which both model.migrateWith's refusal and model.ErrSchemaTooNew contain; that seam is a contract and is now pinned. log_syslog=0 is honoured, not worked around. It is a statement about the syslog stream, not a request to be left uninformed, so failures go to two channels that are not syslog: the script's own stderr (the operator's terminal on a hand-typed restart; the package manager's output inside `apk add`), and /etc/shater/migrate-failed on flash — written on failure, REMOVED on the first success, so its absence is the honest all-clear. syslog gets the same line when log_syslog allows it. A migration that SUCCEEDED stays routine. uci-defaults still exits 0, deliberately: a uci-defaults script that does not is kept and re-run at every boot, and this one re-runs a detached enable+restart of shater/shater-cron plus a firewall reload — one recoverable failure would become permanent boot-time churn, to carry a status nothing reads. The retry that matters already exists in start_service, which runs the migration every start. Found by mutation while writing the tests: reverting start_service's call site left every other test green, because they all call shater_migrate directly. The reporter would have been perfect and unreachable. TestInitScriptStartServiceUses- TheReporter closes that. Verified: sh -n and busybox ash -n on the target (ImmortalWrt 25.12.1 r37978), the classifier exercised there under busybox ash against the real uci; six mutations rolled back one at a time, each caught by name. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BHw89tdWddzhjUc4bAH4tS
This commit is contained in:
1 parent
d1f43dbbe6
commit
735aa5428f
3 files changed
+746
-15
No files matched your search
@@ -252,6 +252,142 @@ _slog() {
|
||||
[ "$(uci -q get shater.globals.log_syslog)" = "0" ] || logger -t shater "$@"
|
||||
}
|
||||
|
||||
# A line the operator gets EVEN WITH globals.log_syslog=0, without going behind
|
||||
# that setting's back.
|
||||
#
|
||||
# log_syslog is a statement about ONE destination: the syslog stream (see _slog
|
||||
# above — the same toggle silences the daemon's own stderr->logread fan-out).
|
||||
# Honouring it by staying silent everywhere turns "keep syslog quiet" into "never
|
||||
# tell me the config could not be brought forward", which is not what it says and
|
||||
# not what anybody means by it. So the refusal goes somewhere else instead:
|
||||
#
|
||||
# * THIS SCRIPT'S OWN STDERR, unconditionally. That is not the syslog stream; it
|
||||
# is the reply to whoever invoked the script. Typed by hand it lands on the
|
||||
# operator's terminal at the moment they are looking at it; run from
|
||||
# 30_shater-core inside `apk add` / `opkg install` it lands in the package
|
||||
# manager's output, which is the one screen an installing operator does read.
|
||||
# At boot it goes to procd's stderr (console) — not durable, hence the file.
|
||||
# * /etc/shater/migrate-failed, on flash, written on failure and REMOVED on the
|
||||
# first success. That is the durable half: it survives the reboot nobody
|
||||
# watched, `cat` reads it, and its absence is the honest all-clear. Written
|
||||
# AFTER the stderr line on purpose — a full /overlay is one of the named
|
||||
# causes of the failure it is reporting, so it must never be the only channel.
|
||||
# * syslog too, but only when log_syslog allows it — that channel keeps
|
||||
# obeying the operator exactly as before.
|
||||
#
|
||||
# One call, one text, three destinations, so the wording cannot drift between
|
||||
# them. Failures only: _shout is not a status line.
|
||||
SHATER_MIGRATE_BREADCRUMB=/etc/shater/migrate-failed
|
||||
_shout() {
|
||||
echo "shater: $*" >&2
|
||||
_slog -p daemon.err "$*"
|
||||
mkdir -p "$(dirname "$SHATER_MIGRATE_BREADCRUMB")" 2>/dev/null
|
||||
echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*" \
|
||||
> "$SHATER_MIGRATE_BREADCRUMB" 2>/dev/null || :
|
||||
}
|
||||
|
||||
# --- `shaterd migrate`: which of the four things happened --------------------
|
||||
#
|
||||
# The schema version on disk, as an integer. 0 for "absent" and 0 for anything
|
||||
# non-numeric, DELIBERATELY the same two answers model.readSchemaVersion gives
|
||||
# (`strconv.Atoi` of a garbage value is 0 with the error dropped) — this number
|
||||
# is only ever used to name a version in a message, and a shell that disagreed
|
||||
# with the binary about what v0 means would print a version the binary never saw.
|
||||
shater_schema_version() {
|
||||
local v
|
||||
v=$(uci -q get shater.globals.schema_version) || v=""
|
||||
case "$v" in
|
||||
"") echo 0 ;;
|
||||
*[!0-9]*) echo 0 ;;
|
||||
*) echo "$v" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# shater_migrate_class <rc> <output-of-shaterd-migrate> — prints EXACTLY one of:
|
||||
#
|
||||
# ok the binary reported success (it may or may not have had work)
|
||||
# downgrade REFUSED: the config on disk is NEWER than this build
|
||||
# unreadable /etc/config/shater could not be read at all
|
||||
# failed it failed for a reason this script does not recognise
|
||||
#
|
||||
# A CLOSED POSITIVE LIST, and the last rung is the point of it. Until v0.2.19 all
|
||||
# four of these were reported with ONE sentence, and that sentence described only
|
||||
# the third one: "routing rules that still carry the removed dst_domain/dst_ip
|
||||
# options stay DISABLED until this succeeds. Free space on /overlay and re-run".
|
||||
# On a DOWNGRADE every clause of that is false — nothing is disabled, /overlay is
|
||||
# not the problem, and re-running does not help, because the fix is to put the
|
||||
# newer package back. A confident wrong diagnosis costs more than no diagnosis.
|
||||
#
|
||||
# `downgrade` is recognised from the binary's own words. That is a CONTRACT with
|
||||
# shater/model: both refusals — model.migrateWith's "config schema v%d newer than
|
||||
# this build (v%d); upgrade the package" and model.ErrSchemaTooNew's "config
|
||||
# schema newer than this build" — contain the substring matched below, and
|
||||
# TestMigrateDowngradeSignatureIsAContract (shater/cmd/shaterd) fails if either
|
||||
# stops containing it. If the wording is ever changed anyway, this degrades to
|
||||
# `failed`, which names itself as unrecognised and quotes the binary verbatim —
|
||||
# the recoverable side. It cannot degrade into one of the confident branches.
|
||||
shater_migrate_class() {
|
||||
local rc="$1" out="$2"
|
||||
|
||||
[ "$rc" = "0" ] && { echo ok; return 0; }
|
||||
|
||||
case "$out" in
|
||||
*"newer than this build"*) echo downgrade; return 0 ;;
|
||||
esac
|
||||
|
||||
# Asked LAST, so a refusal we can name is never re-labelled as an I/O problem.
|
||||
# `uci export` fails both when the file is missing and when it does not parse,
|
||||
# which is the same thing from here: nothing can be said about a schema that
|
||||
# cannot be read.
|
||||
uci -q export shater >/dev/null 2>&1 || { echo unreadable; return 0; }
|
||||
|
||||
echo failed
|
||||
}
|
||||
|
||||
# Run the migration and report it. Called from start_service and mirrored by
|
||||
# /etc/uci-defaults/30_shater-core; see the long note at the call site for why
|
||||
# this never refuses to start.
|
||||
shater_migrate() {
|
||||
local before after out rc class
|
||||
|
||||
before=$(shater_schema_version)
|
||||
out=$("$PROG" migrate 2>&1)
|
||||
rc=$?
|
||||
class=$(shater_migrate_class "$rc" "$out")
|
||||
after=$(shater_schema_version)
|
||||
|
||||
case "$class" in
|
||||
ok)
|
||||
# The all-clear is the ABSENCE of the breadcrumb, so a fixed router stops
|
||||
# claiming to be broken the moment it is fixed.
|
||||
rm -f "$SHATER_MIGRATE_BREADCRUMB"
|
||||
# Nothing to do is not news; obeys log_syslog like every other status line.
|
||||
[ "$before" = "$after" ] && return 0
|
||||
_slog -p daemon.info \
|
||||
"UCI schema migrated: v$before -> v$after. The config as it was at v$before was copied to /etc/shater/config.pre-v$before.bak before the first change."
|
||||
;;
|
||||
downgrade)
|
||||
_shout "UCI schema migration REFUSED — this is a DOWNGRADE, not a broken config. /etc/config/shater carries schema v$after, which is NEWER than this build understands, so nothing was migrated and nothing on disk was changed. Your settings are intact; they are also unchangeable, because the daemon and the panel refuse every config write for the same reason and a save from the panel will fail too. Nothing on this router fixes it: install a shater build that understands schema v$after — the one that ran here before the downgrade (docs-shater/INSTALL.md has the pinned per-version feed). Starting anyway, so the panel stays reachable. '$PROG migrate' said: ${out:-no output}"
|
||||
;;
|
||||
unreadable)
|
||||
_shout "UCI schema migration FAILED and /etc/config/shater CANNOT BE READ ('uci export shater' fails), so this script cannot even say which schema is on disk. A config that is missing or does not parse is neither migrated nor repaired here. Starting anyway — the daemon will come up on whatever it can parse, which may be nothing, leaving it inert with the panel still reachable. Check /etc/config/shater by hand; an /etc/shater/config.pre-v*.bak copy from an earlier migration may be next to it. '$PROG migrate' said: ${out:-no output}"
|
||||
;;
|
||||
failed)
|
||||
_shout "UCI schema migration FAILED for a reason this script does not recognise; the config on disk is still at schema v$after. Starting anyway: refusing to start would take the admin panel down with it, and the panel is the only way to fix the box. The mundane cause is a full /overlay, where 'uci commit' cannot write — check 'df /overlay' first, then re-run '$PROG migrate' or restart the service.$(
|
||||
[ "$after" = "1" ] && printf ' %s' "While the config stays at v1, routing rules that still carry the removed dst_domain/dst_ip options are held DISABLED by the daemon and reported as such — those rules are not in force."
|
||||
) '$PROG migrate' said: ${out:-no output}"
|
||||
;;
|
||||
*)
|
||||
# shater_migrate_class returns a closed set and every member of it is
|
||||
# handled above, so this is unreachable. It exists to say "this script
|
||||
# disagrees with itself" out loud instead of picking one of the confident
|
||||
# branches and being wrong quietly — which is the exact failure the closed
|
||||
# list replaced.
|
||||
_shout "INTERNAL: '$PROG migrate' produced a result /etc/init.d/shater cannot classify (class='$class', rc=$rc). That is a bug in this script, not a state of the router. Starting anyway. Output was: ${out:-no output}"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Announce/withdraw "this daemon is being replaced, not switched off". Read by
|
||||
# `shaterd run` when it receives SIGTERM.
|
||||
shater_mark_restart() {
|
||||
@@ -367,20 +503,19 @@ start_service() {
|
||||
# Bring the UCI schema forward before the daemon reads it (idempotent;
|
||||
# refuses a newer schema) so an upgraded package never applies a stale config.
|
||||
#
|
||||
# THE FAILURE IS LOGGED, NOT SWALLOWED. This is the only place the schema
|
||||
# migration runs at boot (`shaterd run`, the SIGHUP reconcile and the panel's
|
||||
# config write all read UCI directly), so if it fails here it does not get
|
||||
# retried until the next start. And it CAN fail for a mundane reason — a full
|
||||
# /overlay makes `uci commit` fail — after which the config still carries the
|
||||
# schema-v1 `dst_domain`/`dst_ip` options. The daemon holds every rule that
|
||||
# still has them DISABLED and reports it, so nothing is silently misrouted, but
|
||||
# rules the operator wrote are then not in force and the reason has to be
|
||||
# visible somewhere. Hence: log the binary's own stderr, and start anyway —
|
||||
# refusing to start would take the admin panel down with it, and the panel is
|
||||
# the only way to fix the box.
|
||||
local migrate_out
|
||||
migrate_out=$("$PROG" migrate 2>&1) || _slog -p daemon.err \
|
||||
"UCI schema migration FAILED: ${migrate_out:-no output from $PROG migrate}. Starting anyway; routing rules that still carry the removed dst_domain/dst_ip options stay DISABLED until this succeeds. Free space on /overlay and re-run '$PROG migrate', or restart the service."
|
||||
# THE FAILURE IS REPORTED, NOT SWALLOWED, AND IT IS NAMED. This is the only
|
||||
# place the schema migration runs at boot (`shaterd run`, the SIGHUP reconcile
|
||||
# and the panel's config write all read UCI directly), so if it fails here it
|
||||
# does not get retried until the next start — which is also why this, and not
|
||||
# the uci-defaults call, is the report that matters: it comes back at every
|
||||
# boot and every restart for as long as the problem lasts.
|
||||
#
|
||||
# The three outcomes are three different problems with three different fixes
|
||||
# (free space / put the newer package back / the file is unreadable), and
|
||||
# shater_migrate says which one it was instead of asserting the middle one at
|
||||
# all of them. Start regardless in every case: refusing to start would take the
|
||||
# admin panel down with it, and the panel is the only way to fix the box.
|
||||
shater_migrate
|
||||
|
||||
procd_open_instance shater
|
||||
# shaterd runs in the FOREGROUND under procd (must never daemonize). `run` is
|
||||
|
||||
@@ -283,7 +283,97 @@ migrate_l3_zone_wildcard() {
|
||||
migrate_l3_zone_wildcard
|
||||
|
||||
# Bring the UCI schema forward on upgrade (idempotent; refuses a newer schema).
|
||||
[ -x /usr/bin/shaterd ] && /usr/bin/shaterd migrate >/dev/null 2>&1
|
||||
#
|
||||
# THE RESULT IS NO LONGER THROWN AWAY. `>/dev/null 2>&1` discarded stdout, stderr
|
||||
# AND the exit status, so a refusal here was indistinguishable from success — on
|
||||
# the one screen the operator who caused it is actually looking at.
|
||||
#
|
||||
# WHY THIS STILL `exit 0`s (the script ends with one, and this block does not
|
||||
# change that). A uci-defaults script that exits non-zero is NOT deleted and runs
|
||||
# again at every boot. That is the wrong trade here, three times over:
|
||||
#
|
||||
# * This file does far more than migrate — it seeds rt_tables, the shater_l3
|
||||
# fw4 zone and its per-zone forwardings, applies sysctl, and launches a
|
||||
# DETACHED BRING-UP that enables and RESTARTS shater/shater-cron and reloads
|
||||
# the firewall. Re-running all of that at every boot to carry one bit of "the
|
||||
# migration failed" would bounce the tunnel on every boot, after S99 had
|
||||
# already started it. One recoverable failure would become permanent churn.
|
||||
# * The exit status is not a reporting channel: nothing reads a uci-defaults
|
||||
# script's status, and neither procd nor the package manager surfaces it. It
|
||||
# buys no diagnosis, only the re-run.
|
||||
# * The retry it would buy already exists, and is better. /etc/init.d/shater
|
||||
# runs the same migration on EVERY start with the full classified report, so
|
||||
# a failure is retried at every boot and every restart regardless. And
|
||||
# re-running cannot fix either real cause anyway: a downgrade is fixed by
|
||||
# installing the right package, a full /overlay by freeing space.
|
||||
#
|
||||
# So: capture the status, name the cause, record it durably, and exit 0. The
|
||||
# script has done everything it can do, and the failure is not lost.
|
||||
#
|
||||
# The classification is the same closed positive list /etc/init.d/shater uses
|
||||
# (shater_migrate_class there, with the long argument for why the list is closed
|
||||
# and why `downgrade` is matched on the binary's own words). It is repeated here
|
||||
# rather than shared because the package installs no shell library the two could
|
||||
# both source; TestMigrateClassifiersAgree (shater/cmd/shaterd) runs both over
|
||||
# the same inputs and fails if they ever disagree.
|
||||
SHATER_MIGRATE_BREADCRUMB=/etc/shater/migrate-failed
|
||||
|
||||
shater_migrate_class() {
|
||||
local rc="$1" out="$2"
|
||||
[ "$rc" = "0" ] && { echo ok; return 0; }
|
||||
case "$out" in
|
||||
*"newer than this build"*) echo downgrade; return 0 ;;
|
||||
esac
|
||||
uci -q export shater >/dev/null 2>&1 || { echo unreadable; return 0; }
|
||||
echo failed
|
||||
}
|
||||
|
||||
# stderr, unconditionally: inside `apk add` / `opkg install` that is the package
|
||||
# manager's own output, i.e. the installing operator's screen. Plus the durable
|
||||
# breadcrumb on flash, which /etc/init.d/shater removes on the first successful
|
||||
# migration. Deliberately NOT syslog — globals.log_syslog may be off by the
|
||||
# operator's choice, and this path honours it by using other channels instead.
|
||||
shater_migrate_shout() {
|
||||
echo "shater: $*" >&2
|
||||
mkdir -p "$(dirname "$SHATER_MIGRATE_BREADCRUMB")" 2>/dev/null
|
||||
echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*" \
|
||||
> "$SHATER_MIGRATE_BREADCRUMB" 2>/dev/null || :
|
||||
}
|
||||
|
||||
run_migrate() {
|
||||
local out rc class schema
|
||||
[ -x /usr/bin/shaterd ] || return 0
|
||||
|
||||
out=$(/usr/bin/shaterd migrate 2>&1)
|
||||
rc=$?
|
||||
class=$(shater_migrate_class "$rc" "$out")
|
||||
schema=$(uci -q get shater.globals.schema_version)
|
||||
case "$schema" in ""|*[!0-9]*) schema=0 ;; esac
|
||||
|
||||
case "$class" in
|
||||
ok)
|
||||
rm -f "$SHATER_MIGRATE_BREADCRUMB"
|
||||
;;
|
||||
downgrade)
|
||||
shater_migrate_shout "install: UCI schema migration REFUSED — /etc/config/shater is schema v$schema and the shater build being installed understands an older one, so this is a DOWNGRADE. Nothing was migrated and nothing on disk was changed: your settings are intact, and also unchangeable, because the daemon and the panel refuse every config write for the same reason. Install a build that understands schema v$schema again (docs-shater/INSTALL.md has the pinned per-version feed). 'shaterd migrate' said: ${out:-no output}"
|
||||
;;
|
||||
unreadable)
|
||||
shater_migrate_shout "install: UCI schema migration FAILED and /etc/config/shater CANNOT BE READ ('uci export shater' fails), so the schema on disk cannot even be named. Check the file by hand before configuring anything. 'shaterd migrate' said: ${out:-no output}"
|
||||
;;
|
||||
failed)
|
||||
shater_migrate_shout "install: UCI schema migration FAILED for a reason this script does not recognise; the config is still at schema v$schema. The mundane cause is a full /overlay ('uci commit' cannot write) — check 'df /overlay'. /etc/init.d/shater retries this on every start and reports it there too. 'shaterd migrate' said: ${out:-no output}"
|
||||
;;
|
||||
*)
|
||||
# Unreachable: shater_migrate_class returns a closed set, all of it
|
||||
# handled above. Named rather than swept up, so a script that disagrees
|
||||
# with itself says so instead of picking a confident branch and being
|
||||
# wrong quietly.
|
||||
shater_migrate_shout "install: INTERNAL — 'shaterd migrate' produced a result this script cannot classify (class='$class', rc=$rc). That is a bug in /etc/uci-defaults/30_shater-core. Output was: ${out:-no output}"
|
||||
;;
|
||||
esac
|
||||
return 0
|
||||
}
|
||||
run_migrate
|
||||
|
||||
# Apply our sysctl knobs NOW (boot applies them via procd's sysctl service, but
|
||||
# on a live opkg/apk install nothing else re-reads sysctl.d — without this, an
|
||||
|
||||
@@ -0,0 +1,506 @@
|
||||
// Executing the SHIPPED shell that reports how `shaterd migrate` went.
|
||||
//
|
||||
// WHY THIS TEST IS SHAPED LIKE THIS
|
||||
//
|
||||
// The defect it pins was not a wrong verdict, it was a confident wrong SENTENCE.
|
||||
// Both places that run `shaterd migrate` used to collapse every way it can end
|
||||
// into one message:
|
||||
//
|
||||
// /etc/uci-defaults/30_shater-core: shaterd migrate >/dev/null 2>&1
|
||||
// -- stdout, stderr AND the exit status discarded; a refusal looked exactly
|
||||
// like a success on the one screen the operator who caused it was reading.
|
||||
// /etc/init.d/shater: "...routing rules that still carry the removed
|
||||
// dst_domain/dst_ip options stay DISABLED until this succeeds. Free space on
|
||||
// /overlay and re-run '<prog> migrate'..."
|
||||
// -- every clause of which is FALSE on a downgrade: nothing is disabled,
|
||||
// /overlay is not the problem, and re-running never helps, because the fix
|
||||
// is to put the newer package back.
|
||||
//
|
||||
// No Go test could see either: the migration verdict itself (model.Migrate,
|
||||
// model.ErrSchemaTooNew) was correct and covered the whole time. So this runs the
|
||||
// real shell — it sources the packaged /etc/init.d/shater and it EXTRACTS the
|
||||
// classifier out of the packaged uci-defaults script (which cannot be sourced:
|
||||
// unlike the init script it has top-level side effects, up to and including a
|
||||
// detached service restart) — and it checks the sentences that reach the human.
|
||||
//
|
||||
// /etc/uci-defaults/30_shater-core deliberately still exits 0 after a failed
|
||||
// migration. A uci-defaults script that exits non-zero is kept and re-run at
|
||||
// EVERY boot, and that file also seeds firewall zones and launches a detached
|
||||
// enable+restart of shater/shater-cron — so carrying one bit of "it failed" in
|
||||
// the exit status would bounce the tunnel on every boot forever, to say something
|
||||
// nothing reads. The failure is carried by the breadcrumb file and by
|
||||
// /etc/init.d/shater, which re-runs the migration on every start. That decision
|
||||
// is asserted below (TestUciDefaultsExitsZero) so it cannot be "fixed" silently.
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/sagernet/sing-box/shater/model"
|
||||
)
|
||||
|
||||
const uciDefaultsPath = "../../../openwrt/shater-core/files/etc/uci-defaults/30_shater-core"
|
||||
|
||||
// downgradeSignature is the substring both shell classifiers match to recognise
|
||||
// "the config on disk is newer than this build". It is a contract with
|
||||
// shater/model; TestMigrateDowngradeSignatureIsAContract pins the Go side.
|
||||
const downgradeSignature = "newer than this build"
|
||||
|
||||
func skipUnlessPOSIX(t *testing.T) {
|
||||
t.Helper()
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("needs a POSIX /bin/sh; the gate runs on linux")
|
||||
}
|
||||
}
|
||||
|
||||
func abs(t *testing.T, p string) string {
|
||||
t.Helper()
|
||||
a, err := filepath.Abs(p)
|
||||
if err != nil {
|
||||
t.Fatalf("resolve %s: %v", p, err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// stubUCI writes a fake `uci` onto a PATH directory. The real one is not on the
|
||||
// gate's container, and the classifier's "can the config be read at all?" rung
|
||||
// IS `uci export`, so without a stub that rung would answer "unreadable" for
|
||||
// every input and the test would be measuring nothing.
|
||||
//
|
||||
// exportOK -> `uci -q export shater` exit status
|
||||
// schemaFile-> file whose contents `uci -q get shater.globals.schema_version`
|
||||
// prints (missing/empty file => the option is absent, exit 1)
|
||||
func stubUCI(t *testing.T, exportOK bool, schemaFile string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
rc := "0"
|
||||
if !exportOK {
|
||||
rc = "1"
|
||||
}
|
||||
body := `#!/bin/sh
|
||||
case "$*" in
|
||||
*"export shater"*) exit ` + rc + ` ;;
|
||||
*"get shater.globals.schema_version"*)
|
||||
[ -s "` + schemaFile + `" ] || exit 1
|
||||
cat "` + schemaFile + `"
|
||||
exit 0 ;;
|
||||
esac
|
||||
exit 1
|
||||
`
|
||||
p := filepath.Join(dir, "uci")
|
||||
if err := os.WriteFile(p, []byte(body), 0o755); err != nil {
|
||||
t.Fatalf("write uci stub: %v", err)
|
||||
}
|
||||
// `logger` is called by _slog and is also absent from the container. A missing
|
||||
// logger must not be what makes a case pass or fail.
|
||||
lg := filepath.Join(dir, "logger")
|
||||
if err := os.WriteFile(lg, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
|
||||
t.Fatalf("write logger stub: %v", err)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
// runSh runs a snippet with the stub directory first on PATH.
|
||||
func runSh(t *testing.T, pathDir, snippet string, args ...string) (string, string) {
|
||||
t.Helper()
|
||||
argv := append([]string{"-c", snippet, "sh"}, args...)
|
||||
cmd := exec.Command("/bin/sh", argv...)
|
||||
cmd.Env = append(os.Environ(), "PATH="+pathDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
var out, errb strings.Builder
|
||||
cmd.Stdout = &out
|
||||
cmd.Stderr = &errb
|
||||
_ = cmd.Run() // the snippets report by output, not by exit status
|
||||
return out.String(), errb.String()
|
||||
}
|
||||
|
||||
// extractFunc pulls one shell function verbatim out of a file, so a test can run
|
||||
// the code that actually ships in a file it must not source.
|
||||
func extractFunc(t *testing.T, path, name string) string {
|
||||
t.Helper()
|
||||
src, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", path, err)
|
||||
}
|
||||
lines := strings.Split(string(src), "\n")
|
||||
start := -1
|
||||
for i, l := range lines {
|
||||
if strings.HasPrefix(l, name+"() {") {
|
||||
start = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if start < 0 {
|
||||
t.Fatalf("%s does not define %s() at top level", path, name)
|
||||
}
|
||||
for i := start; i < len(lines); i++ {
|
||||
if lines[i] == "}" {
|
||||
return strings.Join(lines[start:i+1], "\n") + "\n"
|
||||
}
|
||||
}
|
||||
t.Fatalf("%s: no closing brace for %s()", path, name)
|
||||
return ""
|
||||
}
|
||||
|
||||
// classCases is the whole input space the classifier is claimed to cover. Each
|
||||
// row is (exit status, what the binary printed, is the config readable).
|
||||
var classCases = []struct {
|
||||
name string
|
||||
rc string
|
||||
out string
|
||||
exportOK bool
|
||||
want string
|
||||
why string
|
||||
}{
|
||||
{"success", "0", "shaterd migrate: ok", true, "ok",
|
||||
"exit 0 is exit 0; nothing else is consulted"},
|
||||
{"success-unreadable-config", "0", "shaterd migrate: ok", false, "ok",
|
||||
"a successful migration is not re-judged by a later uci probe"},
|
||||
{"downgrade-migrate", "1",
|
||||
"shaterd migrate: config schema v3 newer than this build (v2); upgrade the package",
|
||||
true, "downgrade", "model.migrateWith's refusal"},
|
||||
{"downgrade-write-guard", "1",
|
||||
"config schema newer than this build: /etc/config/shater is schema v3 and this build understands only v2",
|
||||
true, "downgrade", "model.ErrSchemaTooNew's wording, same substring"},
|
||||
{"downgrade-wins-over-unreadable", "1",
|
||||
"config schema v9 newer than this build (v2)", false, "downgrade",
|
||||
"a refusal we can NAME is never relabelled as an I/O problem"},
|
||||
{"unreadable", "1", "shaterd migrate: no migration path from schema v7", false, "unreadable",
|
||||
"uci export fails => the schema on disk cannot be named at all"},
|
||||
{"failed-disk-full", "1",
|
||||
"shaterd migrate: back up the config before migrating: no space left on device",
|
||||
true, "failed", "a real failure with a readable config"},
|
||||
{"failed-unknown-wording", "1", "something nobody has written yet", true, "failed",
|
||||
"an unrecognised failure must land on the rung that SAYS it is unrecognised"},
|
||||
{"failed-empty-output", "1", "", true, "failed",
|
||||
"no output is still a failure, and still not a downgrade"},
|
||||
}
|
||||
|
||||
// TestInitScriptMigrateClassification runs the shipped init script's classifier
|
||||
// over every row.
|
||||
func TestInitScriptMigrateClassification(t *testing.T) {
|
||||
skipUnlessPOSIX(t)
|
||||
script := abs(t, initScriptPath)
|
||||
for _, tc := range classCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := stubUCI(t, tc.exportOK, filepath.Join(t.TempDir(), "schema"))
|
||||
out, errb := runSh(t, dir,
|
||||
`. "$1" || exit 3; shater_migrate_class "$2" "$3"`, script, tc.rc, tc.out)
|
||||
if got := strings.TrimSpace(out); got != tc.want {
|
||||
t.Errorf("shater_migrate_class(%s, %q, exportOK=%v) = %q, want %q (%s)\nstderr: %s",
|
||||
tc.rc, tc.out, tc.exportOK, got, tc.want, tc.why, errb)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigrateClassifiersAgree is the anti-drift device for the one function that
|
||||
// had to be written twice. The package installs no shell library the init script
|
||||
// and the uci-defaults script could both source, so the closed list exists in two
|
||||
// files; this runs BOTH shipped copies over the same rows and fails the moment
|
||||
// they disagree — which is the only failure mode duplication actually has.
|
||||
func TestMigrateClassifiersAgree(t *testing.T) {
|
||||
skipUnlessPOSIX(t)
|
||||
script := abs(t, initScriptPath)
|
||||
fn := extractFunc(t, abs(t, uciDefaultsPath), "shater_migrate_class")
|
||||
|
||||
fnFile := filepath.Join(t.TempDir(), "uci_defaults_classifier.sh")
|
||||
if err := os.WriteFile(fnFile, []byte(fn), 0o644); err != nil {
|
||||
t.Fatalf("write extracted classifier: %v", err)
|
||||
}
|
||||
|
||||
for _, tc := range classCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := stubUCI(t, tc.exportOK, filepath.Join(t.TempDir(), "schema"))
|
||||
initOut, _ := runSh(t, dir,
|
||||
`. "$1" || exit 3; shater_migrate_class "$2" "$3"`, script, tc.rc, tc.out)
|
||||
ucidOut, _ := runSh(t, dir,
|
||||
`. "$1" || exit 3; shater_migrate_class "$2" "$3"`, fnFile, tc.rc, tc.out)
|
||||
i, u := strings.TrimSpace(initOut), strings.TrimSpace(ucidOut)
|
||||
if i != u {
|
||||
t.Errorf("the two shipped classifiers DISAGREE on (rc=%s, out=%q, exportOK=%v): "+
|
||||
"/etc/init.d/shater says %q, /etc/uci-defaults/30_shater-core says %q",
|
||||
tc.rc, tc.out, tc.exportOK, i, u)
|
||||
}
|
||||
if u != tc.want {
|
||||
t.Errorf("uci-defaults classifier = %q, want %q (%s)", u, tc.want, tc.why)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestInitScriptMigrateReporting is the point of the whole file: not which token
|
||||
// came out, but which SENTENCE reached the operator. Each row asserts what the
|
||||
// message must say and — just as important — what it must NOT say, because the
|
||||
// bug being fixed was a message that said the right words about the wrong cause.
|
||||
func TestInitScriptMigrateReporting(t *testing.T) {
|
||||
skipUnlessPOSIX(t)
|
||||
script := abs(t, initScriptPath)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
migrateRC int
|
||||
migrateOut string
|
||||
// schema before / after the fake migrate ("" = option absent)
|
||||
schemaBefore string
|
||||
schemaAfter string
|
||||
exportOK bool
|
||||
wantStderr []string
|
||||
denyStderr []string
|
||||
wantCrumb bool
|
||||
}{
|
||||
{
|
||||
name: "migrated", migrateRC: 0, migrateOut: "ok",
|
||||
schemaBefore: "1", schemaAfter: "2", exportOK: true,
|
||||
// The migration that WORKED is routine: it obeys log_syslog and says
|
||||
// nothing on stderr. Silence here is the assertion.
|
||||
denyStderr: []string{"FAILED", "REFUSED", "shater:"},
|
||||
wantCrumb: false,
|
||||
},
|
||||
{
|
||||
name: "nothing-to-do", migrateRC: 0, migrateOut: "ok",
|
||||
schemaBefore: "2", schemaAfter: "2", exportOK: true,
|
||||
denyStderr: []string{"FAILED", "REFUSED", "shater:"},
|
||||
wantCrumb: false,
|
||||
},
|
||||
{
|
||||
name: "downgrade",
|
||||
migrateRC: 1,
|
||||
migrateOut: "shaterd migrate: config schema v3 newer than this build (v2); upgrade the package",
|
||||
schemaBefore: "3", schemaAfter: "3", exportOK: true,
|
||||
wantStderr: []string{
|
||||
"REFUSED", "DOWNGRADE", "schema v3",
|
||||
"nothing on disk was changed", "settings are intact",
|
||||
"install a shater build", "Starting anyway",
|
||||
},
|
||||
// The old single message. On a downgrade every one of these is a lie.
|
||||
denyStderr: []string{"dst_domain", "/overlay", "Free space"},
|
||||
wantCrumb: true,
|
||||
},
|
||||
{
|
||||
name: "unreadable",
|
||||
migrateRC: 1,
|
||||
migrateOut: "shaterd migrate: no migration path from schema v7",
|
||||
schemaBefore: "", schemaAfter: "", exportOK: false,
|
||||
wantStderr: []string{"CANNOT BE READ", "uci export shater", "Starting anyway"},
|
||||
denyStderr: []string{"DOWNGRADE", "dst_domain"},
|
||||
wantCrumb: true,
|
||||
},
|
||||
{
|
||||
name: "failed-at-v1-names-the-disabled-rules",
|
||||
migrateRC: 1,
|
||||
migrateOut: "shaterd migrate: back up the config before migrating: no space left on device",
|
||||
schemaBefore: "1", schemaAfter: "1", exportOK: true,
|
||||
wantStderr: []string{
|
||||
"does not recognise", "schema v1", "/overlay", "Starting anyway",
|
||||
"dst_domain", "DISABLED",
|
||||
},
|
||||
denyStderr: []string{"DOWNGRADE", "CANNOT BE READ"},
|
||||
wantCrumb: true,
|
||||
},
|
||||
{
|
||||
name: "failed-at-v2-must-not-name-them",
|
||||
migrateRC: 1,
|
||||
migrateOut: "shaterd migrate: uci commit: exit status 1",
|
||||
schemaBefore: "2", schemaAfter: "2", exportOK: true,
|
||||
wantStderr: []string{"does not recognise", "schema v2", "/overlay"},
|
||||
// v1's dst_domain/dst_ip consequence is a v1 fact. Asserting it at v2
|
||||
// is the same class of lie the whole change removes.
|
||||
denyStderr: []string{"dst_domain", "DOWNGRADE"},
|
||||
wantCrumb: true,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
schemaFile := filepath.Join(tmp, "schema")
|
||||
if err := os.WriteFile(schemaFile, []byte(tc.schemaBefore), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := stubUCI(t, tc.exportOK, schemaFile)
|
||||
|
||||
// A fake `shaterd` that reproduces one outcome, and moves the schema on
|
||||
// disk the way a real migration would.
|
||||
fake := filepath.Join(tmp, "fakeshaterd")
|
||||
body := "#!/bin/sh\n" +
|
||||
"printf '%s\\n' " + shQuote(tc.migrateOut) + "\n" +
|
||||
"printf '%s' " + shQuote(tc.schemaAfter) + " > " + shQuote(schemaFile) + "\n" +
|
||||
"exit " + itoa(tc.migrateRC) + "\n"
|
||||
if err := os.WriteFile(fake, []byte(body), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crumb := filepath.Join(tmp, "migrate-failed")
|
||||
|
||||
// Source the shipped script, point it at the fakes, run the real
|
||||
// reporter. PROG and SHATER_MIGRATE_BREADCRUMB are plain top-level
|
||||
// variables precisely so this is possible.
|
||||
_, errb := runSh(t, dir,
|
||||
`. "$1" || exit 3; PROG="$2"; SHATER_MIGRATE_BREADCRUMB="$3"; shater_migrate`,
|
||||
script, fake, crumb)
|
||||
|
||||
for _, want := range tc.wantStderr {
|
||||
if !strings.Contains(errb, want) {
|
||||
t.Errorf("the operator was never told %q.\ngot stderr:\n%s", want, errb)
|
||||
}
|
||||
}
|
||||
for _, deny := range tc.denyStderr {
|
||||
if strings.Contains(errb, deny) {
|
||||
t.Errorf("the message claims %q, which is not true of this failure.\ngot stderr:\n%s", deny, errb)
|
||||
}
|
||||
}
|
||||
_, err := os.Stat(crumb)
|
||||
if tc.wantCrumb && err != nil {
|
||||
t.Errorf("no durable record left at %s: %v — with log_syslog=0 and nobody at the console this failure would vanish entirely", crumb, err)
|
||||
}
|
||||
if !tc.wantCrumb && err == nil {
|
||||
b, _ := os.ReadFile(crumb)
|
||||
t.Errorf("a breadcrumb was left behind after a SUCCESSFUL migration; its absence is the all-clear: %s", b)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigrateBreadcrumbIsClearedOnRecovery pins the other half of the durable
|
||||
// channel: a router that has been fixed must stop claiming to be broken. A
|
||||
// breadcrumb that is only ever written is a permanent false alarm.
|
||||
func TestMigrateBreadcrumbIsClearedOnRecovery(t *testing.T) {
|
||||
skipUnlessPOSIX(t)
|
||||
script := abs(t, initScriptPath)
|
||||
tmp := t.TempDir()
|
||||
schemaFile := filepath.Join(tmp, "schema")
|
||||
if err := os.WriteFile(schemaFile, []byte("2"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := stubUCI(t, true, schemaFile)
|
||||
fake := filepath.Join(tmp, "fakeshaterd")
|
||||
if err := os.WriteFile(fake, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crumb := filepath.Join(tmp, "migrate-failed")
|
||||
if err := os.WriteFile(crumb, []byte("an earlier boot failed here"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runSh(t, dir,
|
||||
`. "$1" || exit 3; PROG="$2"; SHATER_MIGRATE_BREADCRUMB="$3"; shater_migrate`,
|
||||
script, fake, crumb)
|
||||
if _, err := os.Stat(crumb); err == nil {
|
||||
t.Fatalf("the breadcrumb survived a successful migration at %s — the router would keep reporting a failure it no longer has", crumb)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInitScriptStartServiceUsesTheReporter pins the WIRING, which nothing else
|
||||
// here can see.
|
||||
//
|
||||
// Found by mutation: reverting start_service's call back to the old
|
||||
// `migrate_out=$("$PROG" migrate 2>&1) || _slog ...` one-liner left every other
|
||||
// test in this file green, because they all call shater_migrate directly. The
|
||||
// reporter would have been perfect and unreachable — the exact shape of "the Go
|
||||
// half was correct and fully covered while the feature did not work" that the
|
||||
// init-script gate exists for.
|
||||
//
|
||||
// start_service cannot be executed here (procd calls, nft, flag files), so the
|
||||
// assertion is on the shipped text: `$PROG migrate` may be run in exactly ONE
|
||||
// place, and that place must be inside shater_migrate(); start_service must
|
||||
// reach it by name.
|
||||
func TestInitScriptStartServiceUsesTheReporter(t *testing.T) {
|
||||
b, err := os.ReadFile(abs(t, initScriptPath))
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", initScriptPath, err)
|
||||
}
|
||||
s := string(b)
|
||||
|
||||
if n := strings.Count(s, `"$PROG" migrate 2>&1`); n != 1 {
|
||||
t.Errorf(`/etc/init.d/shater runs '"$PROG" migrate 2>&1' %d times, want exactly 1 `+
|
||||
`(inside shater_migrate). A second call site is a second place that can `+
|
||||
`swallow the result.`, n)
|
||||
}
|
||||
body := extractFunc(t, abs(t, initScriptPath), "shater_migrate")
|
||||
if !strings.Contains(body, `"$PROG" migrate 2>&1`) {
|
||||
t.Error("shater_migrate() does not run the migration; the one call site is somewhere else")
|
||||
}
|
||||
start := extractFunc(t, abs(t, initScriptPath), "start_service")
|
||||
if !strings.Contains(start, "\n\tshater_migrate\n") {
|
||||
t.Error("start_service() no longer calls shater_migrate — the classified report is " +
|
||||
"dead code and boot is back to whatever the call site says")
|
||||
}
|
||||
// The old call site's own variable. Deliberately a CODE token and not the old
|
||||
// sentence: shater_migrate's comment quotes that sentence verbatim to explain
|
||||
// what was wrong with it, and a guard that cannot tell an explanation from the
|
||||
// thing it explains fails on its own documentation (it did, first run).
|
||||
if strings.Contains(s, "migrate_out") {
|
||||
t.Error(`/etc/init.d/shater still carries the old ` + "`migrate_out`" +
|
||||
` call site — the one-message-for-every-cause reporting is back`)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigrateDowngradeSignatureIsAContract pins the shell<->Go seam. The shell
|
||||
// cannot ask the binary "was that a downgrade?" — `shaterd migrate` exits 1 for
|
||||
// every failure — so it recognises the refusal by the binary's own words. That
|
||||
// makes the wording a contract, and an uncontracted contract is a trap: reword
|
||||
// the Go message and the shell silently stops naming downgrades, with nothing
|
||||
// anywhere to say so.
|
||||
//
|
||||
// Both refusals are checked, one at runtime and one in source:
|
||||
// - model.ErrSchemaTooNew is an exported value, so its text is asserted live;
|
||||
// - model.migrateWith's message is a format string inside an unexported
|
||||
// function reachable only through a real `uci` binary, so it is asserted by
|
||||
// reading the file it lives in. Change either and this fails.
|
||||
func TestMigrateDowngradeSignatureIsAContract(t *testing.T) {
|
||||
// Deliberately NOT skipped on Windows: this one is pure text and the seam is
|
||||
// worth checking wherever the tests run.
|
||||
if !strings.Contains(model.ErrSchemaTooNew.Error(), downgradeSignature) {
|
||||
t.Errorf("model.ErrSchemaTooNew is now %q, which no longer contains %q — "+
|
||||
"/etc/init.d/shater and /etc/uci-defaults/30_shater-core classify a refused "+
|
||||
"DOWNGRADE by that substring and would silently fall back to the generic "+
|
||||
"'failed' message", model.ErrSchemaTooNew.Error(), downgradeSignature)
|
||||
}
|
||||
|
||||
src, err := os.ReadFile(abs(t, "../../model/migrate.go"))
|
||||
if err != nil {
|
||||
t.Fatalf("read model/migrate.go: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(src), downgradeSignature) {
|
||||
t.Errorf("shater/model/migrate.go no longer contains %q — migrateWith's "+
|
||||
"\"config schema v%%d newer than this build (v%%d)\" refusal is what the two "+
|
||||
"shipped shell scripts match on to say DOWNGRADE instead of the generic "+
|
||||
"failure message", downgradeSignature)
|
||||
}
|
||||
|
||||
// And the two shipped scripts must be matching on that same string.
|
||||
for _, p := range []string{initScriptPath, uciDefaultsPath} {
|
||||
b, err := os.ReadFile(abs(t, p))
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", p, err)
|
||||
}
|
||||
if !strings.Contains(string(b), downgradeSignature) {
|
||||
t.Errorf("%s no longer matches on %q", p, downgradeSignature)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestUciDefaultsExitsZero pins the decision explained at the top of this file:
|
||||
// a failed migration must NOT make 30_shater-core exit non-zero, because a
|
||||
// uci-defaults script that does is kept and re-run at every boot — and this one
|
||||
// re-runs a detached enable+restart of shater/shater-cron and a firewall reload.
|
||||
func TestUciDefaultsExitsZero(t *testing.T) {
|
||||
b, err := os.ReadFile(abs(t, uciDefaultsPath))
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", uciDefaultsPath, err)
|
||||
}
|
||||
s := string(b)
|
||||
if !strings.HasSuffix(strings.TrimRight(s, "\n"), "exit 0") {
|
||||
t.Error("30_shater-core no longer ends in `exit 0`: it would survive its first " +
|
||||
"boot and re-run its detached service restart on every boot afterwards")
|
||||
}
|
||||
if strings.Contains(s, "shaterd migrate >/dev/null 2>&1") {
|
||||
t.Error("30_shater-core is discarding `shaterd migrate`'s output and status again")
|
||||
}
|
||||
}
|
||||
|
||||
func shQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }
|
||||
|
||||
func itoa(i int) string { return strconv.Itoa(i) }
|
||||
Reference in new issue
Block a user