gate: targeted -race CI step; make test log capture race-safe
Go code-health batch 3 (#1123): - .amadan/ci.d/70-race and make race run edge (16 shards), rootaws, systemd and the host loop and lease tests under -race (about 6 min). - Test log capture is synchronised (shared helpers in edge, host and activator, about 75 test files); test races in the pty and claimstop tests, the wakecheck goroutine and a bootstrap pipe hang are fixed. - No production code changes. activator and lease are not in the step yet: #1249 (45 test cleanups, and a litestream v0.5.14 Store.Close race fixed in v0.5.18). gitleaks was split out after two review rounds on its allowlist: #1251. Reviewed by Astra (round 1; the only finding was in the gitleaks allowlist, now removed from this branch). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from race-helpers into main.
87 files changed,
+609
−668
.amadan/README.md+37 −2.amadan/ci.d/70-race+42 −0.amadan/code-health.tsv+1 −2.amadan/test-gate.sh+109 −47AGENTS.md+9 −0Makefile+11 −1docs/superpowers/reviews/CHECK-BRIEF-race-helpers-R1-fix.md+20 −0docs/superpowers/reviews/FINDINGS-race-helpers-R1.md+27 −0docs/superpowers/reviews/REVIEW-BRIEF-race-helpers.md+48 −0internal/activator/admintoken_test.go+8 −4internal/activator/cmdunit_test.go+4 −1internal/activator/escrow_alert_test.go+2 −8internal/activator/haadopt_test.go+1 −6internal/activator/harelease_shutdown_test.go+3 −3internal/activator/instancekey_test.go+1 −4internal/activator/opset_test.go+1 −20internal/activator/pendingwake_linux_test.go+2 −2internal/activator/poolwithdrawal_retry_test.go+1 −5internal/activator/poolwithdrawal_test.go+1 −5internal/activator/pty_linux_test.go+20 −9internal/activator/rootfs_resident_test.go+1 −5internal/activator/rootfs_swap_release_test.go+2 −2internal/activator/rootfsrelease_test.go+1 −29internal/activator/seed_diagnostic_test.go+1 −6internal/activator/shutdown_lease_test.go+2 −36internal/activator/shuttingdown_answer_test.go+1 −6internal/activator/wakecheck_test.go+14 −2internal/activator/worker_identity_test.go+2 −2internal/edge/certbackfill_test.go+3 −8internal/edge/certsync_test.go+1 −4internal/edge/cookiescope_test.go+1 −6internal/edge/demo_terms_test.go+1 −6internal/edge/devbox_test.go+0 −20internal/edge/logcapture_test.go+56 −0internal/edge/mesh_test.go+0 −13internal/edge/proxyingress_test.go+1 −5internal/edge/purge_header_test.go+2 −9internal/edge/purge_hosts_test.go+1 −6internal/edge/regional_e2e_test.go+1 −22internal/edge/rootfs_reload_test.go+1 −6internal/edge/tunnel_test.go+1 −6internal/edge/wildcard_parents_test.go+2 −9internal/edge/wildcard_serveonly_test.go+1 −6internal/host/agent_test.go+2 −6internal/host/alertsink_page_test.go+1 −6internal/host/alertsink_test.go+1 −6internal/host/applessroute_test.go+2 −8internal/host/bootstrapfs_linux_test.go+1 −6internal/host/boxroles_test.go+1 −6internal/host/caps_pass_test.go+0 −13internal/host/claimservingretained_linux_test.go+1 −5internal/host/claimstop_transport_test.go+4 −2internal/host/configguard_test.go+6 −17internal/host/converge_adopted_test.go+1 −7internal/host/demo_policy_test.go+2 −7internal/host/demo_retirement_stream_test.go+1 −5internal/host/edgesfile_test.go+1 −4internal/host/fleetbind_test.go+1 −6internal/host/group_admission_fix_test.go+1 −6internal/host/group_hairpin_retry_test.go+3 −14internal/host/haplacement_wiring_test.go+1 −6internal/host/host_test.go+7 −6internal/host/housekeeper_group_test.go+1 −1internal/host/housekeeper_test.go+6 −37internal/host/interactive_test.go+6 −18internal/host/logcapture_test.go+71 −0internal/host/metrics_loop_test.go+2 −10internal/host/movesheldrelease_linux_test.go+1 −5internal/host/movespass_lost_test.go+5 −21internal/host/offcloudcredentials_linux_test.go+2 −9internal/host/plan14_fix3_live_linux_test.go+1 −6internal/host/plan9fix4_claimjournal_migration_linux_test.go+1 −5internal/host/rawbaseline_linux_test.go+3 −13internal/host/region_ha_g2_isolation_test.go+1 −6internal/host/relocatepass_absence_test.go+3 −3internal/host/relocatepass_carries_test.go+3 −3internal/host/relocatepass_round1_test.go+3 −3internal/host/relocatepass_test.go+1 −1internal/host/relocationfinish_unix_test.go+2 −2internal/host/relocationsweep_test.go+1 −4internal/host/replicacoordinator_test.go+1 −6internal/host/replicahomekeys_test.go+1 −5internal/host/restartscope_test.go+6 −20internal/host/rollout_test.go+2 −8internal/host/rootfs_advice_test.go+1 −5internal/host/runs_test.go+1 −5internal/host/steering_loop_test.go+3 −3
CI passed — run details
diff --git a/.amadan/README.md b/.amadan/README.md| index 9f559c4de..622b31f8a 100644 |
| --- a/.amadan/README.md |
| +++ b/.amadan/README.md |
| @@ -33,9 +33,10 @@ no longer exists. |
| | `minio-contract` | `30-minio-contract` | MinIO on loopback, no container | |
| | `gofmt` | `10-gate` | repo-wide, via `make test` — see below | |
| -Five checks have no ancestor; the deleted workflow never ran them. The |
| +Six checks have no ancestor; the deleted workflow never ran them. The |
| first three were added on 2026-11-16 after a code audit found the gate |
| -could not see them, and the code-health ratchet's two on 2026-11-17. |
| +could not see them, and the code-health ratchet's two and the race |
| +detector on 2026-11-17. |
| | added | here | | |
| |---|---|---| |
| @@ -44,6 +45,7 @@ could not see them, and the code-health ratchet's two on 2026-11-17. |
| | `govulncheck` | `50-govulncheck` | `make govulncheck`: v1.8.0 over this module and `launchctx`; fails only on vulnerabilities the code calls, less the exceptions file; see below | |
| | code-health gate | `60-code-health` | `make code-health`: the code against `.amadan/code-health.tsv`, scanned with type information; see below | |
| | code-health record | `61-code-health-record` | the record against the merge base's copy; see below | |
| +| race detector | `70-race` | `make race`: `go test -race` over the edge, rootaws and systemd packages and host's loop and lease tests, sharded like the gate; see below | |
| ## `govulncheck`: what turns it red |
| @@ -112,6 +114,39 @@ lacks. It fetches main from `origin` (readable without credentials) and, |
| the first time on a workspace, unshallows the clone. Its header says |
| how it finds the base, and why it uses HEAD's parent on main. |
| +## `-race`: what it covers, and what it leaves out |
| + |
| +`70-race` runs `make race`, which is `.amadan/test-gate.sh` with |
| +`GATE_RACE=1`: the tests in `RACE_SPLIT`'s packages, with `-race`, |
| +dealt onto shards by `test-weights.tsv` and held by the same fence as |
| +`make test`, so a new test is covered without touching anything. The |
| +packages are the ones with real concurrency: every test of |
| +`internal/edge` (less `TestLinkPinForwardedFallback`, `RACE_SKIP`: its |
| +ten bcrypt logins outlast the rate-limit window under `-race`), |
| +`internal/rootaws` and `internal/systemd`, and of `internal/host` the |
| +tests named for a loop or a lease (`RACE_ONLY`). The whole host suite under `-race` is far past |
| +the step's budget: measured once on docs-t1 (16 cores, `GOMAXPROCS=4`, |
| +the machine otherwise busy), every host shard ran past fifteen minutes. |
| +The link simulations run fewer seeds here (`LINKSIM_SEEDS`); `make test` |
| +runs them at full breadth. It is its own |
| +step because `-race` compiles those packages again and runs their tests |
| +several times slower. |
| + |
| +Three packages are left out. The root package's e2e tests build the CLI |
| +many times over and are too slow under `-race`. `internal/activator` has |
| +45 tests that shrink a package-level timing knob and restore it in a |
| +cleanup while the wake they started is still running, so the restore |
| +races the wake's read. Production never changes those knobs; the fix is |
| +for the tests to wait for their wakes, or for the knobs to stop being |
| +plain variables, and the package joins the step then. `internal/lease` trips a |
| +race inside litestream v0.5.14: `Store.Close` closes the database while |
| +the store's own snapshot monitor is still reading it. Upstream fixed it |
| +in v0.5.18 (`Store.Close` now stops its monitors first); lease joins the |
| +step with that bump. |
| + |
| +`-race` needs cgo, so the target sets `CGO_ENABLED=1`, and the runner |
| +needs a C compiler. |
| + |
| ## `gofmt`: ported by widening it, not by reproducing it |
| This section is the reason it was safe to delete the workflow, so it is |
diff --git a/.amadan/ci.d/70-race b/.amadan/ci.d/70-race| new file mode 100755 |
| index 000000000..f8396bbb4 |
| --- /dev/null |
| +++ b/.amadan/ci.d/70-race |
| @@ -0,0 +1,42 @@ |
| +#!/bin/sh |
| +# The race detector over the packages with real concurrency: the edge |
| +# (servers, pollers, the tunnel), the host agent's loops and lease handling, and the two packages those |
| +# loops call into for AWS and systemd, internal/rootaws and |
| +# internal/systemd. `make race` is the one definition; this step only |
| +# runs it, so a developer gets the same answer with the same command. |
| +# |
| +# The tests in those packages, with -race, dealt onto shards and fenced by |
| +# .amadan/test-gate.sh exactly as `make test` deals its own (GATE_RACE=1; |
| +# RACE_SPLIT in that file names the packages and how many shards each). |
| +# Every test of edge, rootaws and systemd, less one (RACE_SKIP); of |
| +# internal/host only the tests named for a loop or a lease (RACE_ONLY), |
| +# because its whole suite under -race is far past this step's budget. |
| +# Its own step, not part of 10-gate: -race compiles the packages again and |
| +# runs their tests several times slower, and a red here is a race, which |
| +# should read as that. |
| +# |
| +# Left out, each for a reason: |
| +# - the root package: its e2e tests build the CLI many times over, too |
| +# slow under -race; |
| +# - internal/activator: 45 tests shrink a package-level timing knob and |
| +# put it back in a cleanup while the wake they started is still |
| +# running, so the restore races the wake's read. The race is in how |
| +# the tests end, not in production, where the knobs never change. It |
| +# joins this step once those tests wait for their wakes, or the knobs |
| +# stop being plain variables; |
| +# - internal/lease: litestream v0.5.14's Store.Close closes the database |
| +# while its own snapshot monitor still reads it (a race inside the |
| +# dependency, fixed upstream in v0.5.18, which stops the monitors |
| +# first). Every lease test that closes a store can trip it. Add lease |
| +# here with the bump. |
| +# |
| +# Red means a data race (WARNING: DATA RACE, then the test it was found |
| +# in), or a test that fails only under the detector's timing. A race in a |
| +# test helper is fixed in the helper; edge and host each have one locked |
| +# log capture (captureLog) for exactly that. |
| +# |
| +# -race needs cgo: CGO_ENABLED=1 and a C compiler on the runner. |
| +set -eu |
| +. .amadan/go-toolchain.sh |
| + |
| +make race |
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index b27938c92..638c01f4c 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -586,7 +586,6 @@ sleep internal/activator TestAFallbackWakeRecordsTheFailureBeforeItPublishes tim |
| sleep internal/activator TestAFirstWakeEndedAfterItsExecReportsThatItRan time.Sleep 3 |
| sleep internal/activator TestAFirstWakeWithNoTimeForAVerdictBootsTheGoodBuild time.Sleep 1 |
| sleep internal/activator TestAGateRefusalOnAShortWindowAbandonsRatherThanGoingUntried time.Sleep 1 |
| -sleep internal/activator TestAHeldWakesReaskNeverOutlastsTheWait time.Sleep 1 |
| sleep internal/activator TestALateLeaseKillNeverReachesTheNextRun time.Sleep 2 |
| sleep internal/activator TestALiveExecGateGatesAWorkerSpawnFromTheLiveLink time.Sleep 1 |
| sleep internal/activator TestALiveExecGateGatesTheFlatLiveLinkSpawn time.Sleep 1 |
| @@ -2198,7 +2197,7 @@ func-lines internal/console TestHAP2ProductionDoors - 321 |
| func-lines internal/domains ReconcileAliasesReport - 364 |
| func-lines internal/edge (*Edge).ServeHTTP - 421 |
| func-lines internal/edge TestDemoAPIAliasBoundary - 360 |
| -func-lines internal/edge TestRegionalNameNeverLeavesItsRegion - 332 |
| +func-lines internal/edge TestRegionalNameNeverLeavesItsRegion - 330 |
| func-lines internal/edge TestTunnelWebSocketEndToEnd - 327 |
| func-lines internal/host (*ClaimWakeAssembly).Build - 421 |
| func-lines internal/host TestPagingIsRateLimited - 509 |
diff --git a/.amadan/test-gate.sh b/.amadan/test-gate.sh| index f3eb2b69b..b693b60c8 100755 |
| --- a/.amadan/test-gate.sh |
| +++ b/.amadan/test-gate.sh |
| @@ -51,8 +51,44 @@ |
| # |
| # The last thing the gate prints is how much CPU its jobs used against |
| # how long it took, so a slow run says whether it was short of cores. |
| +# |
| +# RACE. GATE_RACE=1 is `make race` (.amadan/ci.d/70-race), not `make |
| +# test`: the race detector over RACE_SPLIT's packages and nothing else (no |
| +# vet, gofmt, launchctx, unsplit packages or cutover witnesses; `make |
| +# test` has those). Every test in those packages is dealt onto shards and |
| +# fenced exactly as above, with -race on the list and on every shard. |
| +# RACE_SPLIT overrides the packages and their shard counts the way |
| +# TEST_SPLIT does; TEST_SPLIT itself is ignored in this mode. RACE_ONLY |
| +# narrows a package to the listed tests whose names match a regex and |
| +# RACE_SKIP drops the ones that match ("dir=regex", no spaces); the fence |
| +# then holds for what is left. -race needs |
| +# cgo, so CGO_ENABLED=1 is set here and the machine needs a C compiler. |
| set -eu |
| +race="" |
| +if [ "${GATE_RACE:-}" = 1 ]; then |
| + # The packages with real concurrency (.amadan/ci.d/70-race says why |
| + # these and not the rest), heaviest first like TEST_SPLIT. |
| + : "${RACE_SPLIT=./internal/edge=16 ./internal/host=2 ./internal/rootaws=1 ./internal/systemd=1}" |
| + # internal/host's whole suite under -race is far past the step's |
| + # budget (every shard ran past fifteen minutes on a 16-core box), so |
| + # only its loops and its lease handling: the tests named for them. |
| + : "${RACE_ONLY=./internal/host=Loop|Lease}" |
| + # Ten bcrypt logins must land inside one rate-limit window, and under |
| + # -race they take long enough for the bucket to refill. |
| + : "${RACE_SKIP=./internal/edge=^TestLinkPinForwardedFallback\$}" |
| + TEST_SPLIT=$RACE_SPLIT |
| + race=-race |
| + # The seeded simulations search for invariant breaks, which `make |
| + # test` does at full breadth. Here they only need to drive the |
| + # concurrent paths, and at full breadth under -race one link sim |
| + # alone ran past twelve minutes. A value already set is kept. |
| + : "${LINKSIM_SEEDS=50}" |
| + export LINKSIM_SEEDS |
| + CGO_ENABLED=1 |
| + export CGO_ENABLED |
| +fi |
| + |
| # Heaviest first: shards start in this order once their package's tests |
| # have compiled, and the packages that dominate the wall clock should not |
| # queue behind the others. |
| @@ -167,18 +203,21 @@ discover() { |
| return "$discover_rc" |
| } |
| -start launchctx sh -c 'cd launchctx && go vet ./... && go test ./... -count=1' |
| -start vet go vet ./... |
| -# The tagged tests: about 130 test files behind `linux && rootrunner` (the |
| -# root runner's fixtures, nearly all in internal/host) and the cutover |
| -# witnesses. Only the root runner and the cutover-witness job below ever |
| -# compiled them, so a refactor could break a root-runner test and stay |
| -# green. Its own job rather than tags on the line above, because one file, |
| -# internal/host/departure_queue_default.go, is `!rootrunner` and would |
| -# drop out of the plain vet. Nothing here runs those tests: they need |
| -# root. |
| -start vet-tags go vet -tags rootrunner,carlos_cutover_witness ./... |
| -start gofmt sh -c 'fmt_out=$(gofmt -l .); if [ -n "$fmt_out" ]; then echo "gofmt needed:"; echo "$fmt_out"; exit 1; fi; echo "gofmt -l .: clean"' |
| +# The rest of `make test`; `make race` is only the race shards. |
| +if [ -z "$race" ]; then |
| + start launchctx sh -c 'cd launchctx && go vet ./... && go test ./... -count=1' |
| + start vet go vet ./... |
| + # The tagged tests: about 130 test files behind `linux && rootrunner` (the |
| + # root runner's fixtures, nearly all in internal/host) and the cutover |
| + # witnesses. Only the root runner and the cutover-witness job below ever |
| + # compiled them, so a refactor could break a root-runner test and stay |
| + # green. Its own job rather than tags on the line above, because one file, |
| + # internal/host/departure_queue_default.go, is `!rootrunner` and would |
| + # drop out of the plain vet. Nothing here runs those tests: they need |
| + # root. |
| + start vet-tags go vet -tags rootrunner,carlos_cutover_witness ./... |
| + start gofmt sh -c 'fmt_out=$(gofmt -l .); if [ -n "$fmt_out" ]; then echo "gofmt needed:"; echo "$fmt_out"; exit 1; fi; echo "gofmt -l .: clean"' |
| +fi |
| # The split packages' test lists, all at once. `go test -list` compiles the |
| # test binary, which the shards then reuse from the build cache. One after |
| @@ -195,7 +234,7 @@ for spec in $TEST_SPLIT; do |
| ( |
| set +e |
| t0=$(date +%s) |
| - go test -count=1 -list '.*' "${spec%=*}" >"$out/list-$tag.raw" 2>&1 |
| + go test $race -count=1 -list '.*' "${spec%=*}" >"$out/list-$tag.raw" 2>&1 |
| echo $? >"$out/list-$tag.rc" |
| echo $(($(date +%s) - t0)) >"$out/list-$tag.secs" |
| ) & |
| @@ -203,40 +242,42 @@ for spec in $TEST_SPLIT; do |
| eval "list_pid_$tag=\$!" |
| done |
| -# Everything not split runs as one ordinary `go test`. Packages are named |
| -# by import path, so match TEST_SPLIT's directories through `go list`. |
| -split_paths="" |
| -for spec in $TEST_SPLIT; do |
| - discover go list "${spec%=*}" >"$out/go-list" |
| - split_paths="$split_paths $(cat "$out/go-list")" |
| -done |
| -# go list runs on its own, not in a pipeline: a pipeline's status is its |
| -# last command's, and a go list that failed halfway would hand on a short |
| -# package list with a zero status. Each go list goes through discover, and |
| -# set -e stops the gate on its status. |
| -discover go list ./... >"$out/go-list" |
| -all=$(cat "$out/go-list") |
| -if [ -z "$all" ]; then |
| - echo "go list ./... found no packages" >&2 |
| - exit 1 |
| -fi |
| -rest="" |
| -for p in $all; do |
| - case " $split_paths " in |
| - *" $p "*) ;; |
| - *) rest="$rest $p" ;; |
| - esac |
| -done |
| -# With no packages left, go test would test the current directory instead. |
| -if [ -n "$rest" ]; then |
| - # shellcheck disable=SC2086 # one word per package, on purpose |
| - start rest go test -count=1 -timeout 15m $rest |
| +if [ -z "$race" ]; then |
| + # Everything not split runs as one ordinary `go test`. Packages are named |
| + # by import path, so match TEST_SPLIT's directories through `go list`. |
| + split_paths="" |
| + for spec in $TEST_SPLIT; do |
| + discover go list "${spec%=*}" >"$out/go-list" |
| + split_paths="$split_paths $(cat "$out/go-list")" |
| + done |
| + # go list runs on its own, not in a pipeline: a pipeline's status is its |
| + # last command's, and a go list that failed halfway would hand on a short |
| + # package list with a zero status. Each go list goes through discover, and |
| + # set -e stops the gate on its status. |
| + discover go list ./... >"$out/go-list" |
| + all=$(cat "$out/go-list") |
| + if [ -z "$all" ]; then |
| + echo "go list ./... found no packages" >&2 |
| + exit 1 |
| + fi |
| + rest="" |
| + for p in $all; do |
| + case " $split_paths " in |
| + *" $p "*) ;; |
| + *) rest="$rest $p" ;; |
| + esac |
| + done |
| + # With no packages left, go test would test the current directory instead. |
| + if [ -n "$rest" ]; then |
| + # shellcheck disable=SC2086 # one word per package, on purpose |
| + start rest go test -count=1 -timeout 15m $rest |
| + fi |
| + # The fleet-run cutover witnesses (rootfs apps Plan 6 Task 16): the real CLI |
| + # against a fleet run queued across a lifetimes cutover. They and the console |
| + # controls they need are built only with this tag, which no other job and no |
| + # production build sets. |
| + start cutover-witness go test -count=1 -timeout 15m -tags carlos_cutover_witness -run '^TestQueuedFleetRunAtACutoverExpires' . |
| fi |
| -# The fleet-run cutover witnesses (rootfs apps Plan 6 Task 16): the real CLI |
| -# against a fleet run queued across a lifetimes cutover. They and the console |
| -# controls they need are built only with this tag, which no other job and no |
| -# production build sets. |
| -start cutover-witness go test -count=1 -timeout 15m -tags carlos_cutover_witness -run '^TestQueuedFleetRunAtACutoverExpires' . |
| # The split shards' -json, in weights mode only (see WEIGHTS above). |
| shard_json="" |
| @@ -264,6 +305,22 @@ deal_split() { |
| return |
| fi |
| grep -E '^(Test|Example|Fuzz)' "$out/list-$tag.raw" | sort -u >"$out/list-$tag" || true |
| + # RACE_ONLY's regex for this package, if it names one: only the tests |
| + # it matches are dealt. A regex that matches none is a failure below. |
| + set -f # a regex is not a glob |
| + for only in ${race:+${RACE_ONLY:-}}; do |
| + if [ "${only%%=*}" = "$dir" ]; then |
| + grep -E "${only#*=}" "$out/list-$tag" >"$out/list-$tag.only" || true |
| + mv "$out/list-$tag.only" "$out/list-$tag" |
| + fi |
| + done |
| + for skip in ${race:+${RACE_SKIP:-}}; do |
| + if [ "${skip%%=*}" = "$dir" ]; then |
| + grep -vE "${skip#*=}" "$out/list-$tag" >"$out/list-$tag.only" || true |
| + mv "$out/list-$tag.only" "$out/list-$tag" |
| + fi |
| + done |
| + set +f |
| listed=$(wc -l <"$out/list-$tag") |
| if [ "$listed" -eq 0 ]; then |
| fail_job "$tag" "go test -list found no tests in $pkg, which is not believable" |
| @@ -296,7 +353,7 @@ deal_split() { |
| while [ "$i" -lt "$shards" ]; do |
| pattern=$(awk -v i="$i" -F '\t' '$1 == i { printf "%s%s", sep, $2; sep = "|" }' "$out/deal-$tag") |
| if [ -n "$pattern" ]; then |
| - start "$tag@$i" go test $shard_json -count=1 -timeout 15m -run "^($pattern)\$" "$dir" |
| + start "$tag@$i" go test $race $shard_json -count=1 -timeout 15m -run "^($pattern)\$" "$dir" |
| launched=$((launched + $(awk -v i="$i" -F '\t' '$1 == i' "$out/deal-$tag" | wc -l))) |
| fi |
| i=$((i + 1)) |
| @@ -420,6 +477,11 @@ if [ -n "$failed" ]; then |
| for name in $failed; do |
| echo "--- $name" |
| grep -E '^[[:space:]]*--- FAIL|^panic:|^FAIL[[:space:]]|^[[:space:]]+[A-Za-z0-9_./-]+_test\.go:[0-9]+:|^[[:space:]]*running tests:|^[[:space:]]+Test[A-Za-z0-9_/-]* \([0-9.]+[a-z]+\)$' "$out/$name.log" 2>/dev/null | head -60 || true |
| + # A race fails its test with no message of its own, and CI keeps |
| + # only the log's tail, so the reports themselves come here too. |
| + if [ -n "$race" ]; then |
| + awk '/WARNING: DATA RACE/ { n++; p = n <= 3 } p && !/go-dist/ { print } /^==================$/ { p = 0 }' "$out/$name.log" 2>/dev/null | head -80 || true |
| + fi |
| done |
| echo |
| echo "FAILED:$failed" |
diff --git a/AGENTS.md b/AGENTS.md| index b2f7d5299..94cd29d99 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -295,6 +295,15 @@ anything. |
| anything. Imported-only and required-only findings are printed, not |
| fatal. It needs `vuln.go.dev` and the module proxy; `.amadan/README.md` |
| has the details. |
| +- `70-race` runs `make race`: `internal/edge`, `internal/rootaws`, |
| + `internal/systemd` and `internal/host`'s tests named for a loop or a |
| + lease, under `-race`, sharded by `.amadan/test-gate.sh` (`GATE_RACE=1`, |
| + `RACE_SPLIT`, `RACE_ONLY`, `RACE_SKIP`). It needs cgo and a C compiler. A test |
| + in edge, activator or host that reads the standard log uses its |
| + package's `captureLog` (a locked buffer; host also has |
| + `captureLogBuffer`), never a plain `bytes.Buffer`, and a goroutine a |
| + test starts ends before the test does. `internal/activator` and |
| + `internal/lease` are out for now (`.amadan/README.md` says why). |
| - `20-cross@5` adds `GOOS=darwin`/`windows`/`linux-arm64` compiles, one |
| per shard. **The gate is not Linux-only**: `internal/host` is linked |
| into the CLI, which people run on Macs, so a Linux-only type assumption |
diff --git a/Makefile b/Makefile| index 5eda80ea5..8eeb2c8f4 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -7,7 +7,7 @@ LDFLAGS := -s -w -X github.com/carlosframework/platform/internal/version.Build=$ |
| GOOS ?= |
| GOARCH ?= |
| -.PHONY: test build build-console fmt staticcheck govulncheck census-card census-propose code-health code-health-record console-mockup-kit parity-doc |
| +.PHONY: test build build-console fmt staticcheck govulncheck race census-card census-propose code-health code-health-record console-mockup-kit parity-doc |
| # The build gate: vet, format, tests. `.amadan/ci.d/10-gate` runs this same |
| # target, so what CI checks and what you check are one definition. |
| @@ -99,6 +99,16 @@ govulncheck: |
| (cd launchctx && go run $(GOVULNCHECK) -format json ./...) >"$$dir/launchctx.json" && \ |
| go run ./scripts/govulncheck-gate -exceptions .amadan/govulncheck-exceptions.tsv "$$dir/platform.json" "$$dir/launchctx.json" |
| +# The race detector over the packages with real concurrency, as CI runs it |
| +# (.amadan/ci.d/70-race). Not part of `make test`: -race compiles every |
| +# package again and runs its tests several times slower. The tests in |
| +# those packages (internal/host's loop and lease tests only), dealt onto |
| +# shards and fenced by .amadan/test-gate.sh exactly as `make test` deals |
| +# its own (GATE_RACE=1; RACE_SPLIT names the packages and shard counts, |
| +# RACE_ONLY narrows one). Needs cgo and a C compiler. |
| +race: |
| + GATE_RACE=1 .amadan/test-gate.sh |
| + |
| # Regenerates docs/console-mockup-kit/shell.html: a signed-in console page |
| # from the real templates with every stylesheet inlined and an empty |
| # <main> to draw a mockup in (docs/console-mockup-kit/README.md). |
diff --git a/docs/superpowers/reviews/CHECK-BRIEF-race-helpers-R1-fix.md b/docs/superpowers/reviews/CHECK-BRIEF-race-helpers-R1-fix.md| new file mode 100644 |
| index 000000000..4bdfa11de |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CHECK-BRIEF-race-helpers-R1-fix.md |
| @@ -0,0 +1,20 @@ |
| +# Scoped check: race-helpers, after round 1 (not a review round) |
| + |
| +Repo carlos/platform, branch `race-helpers` (tip in the prompt). Round 1 |
| +(`docs/superpowers/reviews/FINDINGS-race-helpers-R1.md`) found one P1: the |
| +gitleaks census allowance suppressed real hex credentials. The fix is |
| +commit d944ac57. Scope: `git show d944ac57` and `.gitleaks.toml` only. |
| + |
| +Check: |
| +1. The P1: resolved, partly, not. Each digest allowlist now matches the |
| + whole line (`regexTarget = "line"`): census tests a complete five-field |
| + entry; always-awake-consumers.json a .go path and a 64-hex digest; one |
| + chunk-boundary pattern for plan9_b8_census_test.go. Can a real |
| + credential still pass any of these (including the chunk-boundary |
| + pattern, which checks only the last line of a chunk)? |
| +2. Every other allowlist entry: exact, anchored values only? |
| +3. Does the file still fail closed if gitleaks' config fails to parse? |
| + |
| +Answer each: OK, or a finding with file:line, failure scenario and fix, |
| +marked P1 or P2. End with exactly one line: CHECK PASSED, or CHECK FAILED |
| +with the P1s. Do not edit files, spawn reviewers or run full suites. |
diff --git a/docs/superpowers/reviews/FINDINGS-race-helpers-R1.md b/docs/superpowers/reviews/FINDINGS-race-helpers-R1.md| new file mode 100644 |
| index 000000000..d254ab5db |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/FINDINGS-race-helpers-R1.md |
| @@ -0,0 +1,27 @@ |
| +Reviewed `origin/main...f8014804fbe1dd7e450c6bddb4b9b8032b840dc3`, round 1. The difference from the brief’s named commit, `302b9886`, is only the brief itself. |
| + |
| +- **P1 — The census allowance also suppresses real hexadecimal credentials.** |
| + [.gitleaks.toml:32](/home/paulca/amadan.net/carlos/platform-race-helpers/.gitleaks.toml:32) allows every `generic-api-key` finding consisting of 10–64 lowercase hexadecimal characters anywhere in matching census files or `implementation/always-awake-consumers.json`. It does not check whether the value occupies a source-digest field. |
| + |
| + **Failure scenario:** someone copies a real hexadecimal API key into a census test—for example, an `api_key = "…"` assignment. Both allowance conditions match, so the new security step silently accepts it. |
| + |
| + **Evidence:** the pinned v8.30.1 executable detected a synthetic 64-character hexadecimal API key through stdin and returned exit 1. The configured path and value expressions both match that value in an existing census-file path. Inspection of v8.30.1’s `checkFindingAllowed` confirms that this conjunction suppresses the finding. This conclusion combines the detector check with source inspection; I did not plant a file in the worktree. |
| + |
| + **Fix:** retain the path restriction, but match the actual census-entry or JSON digest-field structure using `regexTarget`, or enumerate exact approved digests. Verify that a synthetic hexadecimal credential elsewhere in the same files still fails. |
| + |
| + **Fault family:** secret-scanning exceptions must distinguish approved source digests from credentials. |
| + |
| +No additional P2 or P3 findings. |
| + |
| +The remaining checks found: |
| + |
| +- **No production Go changes:** all 78 changed Go files are tests. The other changes concern CI, configuration and documentation. |
| +- **Race gate:** discovery and shards receive `-race`; nonzero job statuses propagate to failure. Normal mode retains its existing commands. The bcrypt timing exclusion and reduced simulation seeds are consistent with the tests and documented scope. |
| +- **Excluded packages:** the README explicitly records activator’s unfinished cleanup work and lease’s dependency race. Cached litestream sources confirm that v0.5.14 closes databases before stopping monitors, while v0.5.18 reverses that order. |
| +- **Log capture:** the shared buffers synchronize reads, writes and resets. Review across all three packages found no additional assertion regression from the migration. |
| +- **Test fixes:** the rootfs cgroup-reader installation, separate claimstop context, wakecheck callback cleanup and concurrent bootstrap pipe drain address their stated failures. |
| +- **Ratchet:** only lowered—one sleep allowance removed and one function-length allowance reduced from 332 to 330. |
| + |
| +Shell syntax checks and `git diff --check` passed. The cached, pinned gitleaks executable rejected synthetic hexadecimal and GitHub-shaped credentials. Full suites were not run. The read-only sandbox prevented Go build-directory creation, so the complete Make targets were not executed. No files were changed or reviewers spawned. |
| + |
| +NOT READY |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-race-helpers.md b/docs/superpowers/reviews/REVIEW-BRIEF-race-helpers.md| new file mode 100644 |
| index 000000000..acba13b10 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/REVIEW-BRIEF-race-helpers.md |
| @@ -0,0 +1,48 @@ |
| +# Review brief: branch race-helpers, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `race-helpers`, commit 302b9886a720535d5d8b71c058df4860b79cba0d. |
| +Under review: the diff `origin/main...302b9886a720535d5d8b71c058df4860b79cba0d`. |
| +Authorities: the Go code-health plan (batch 3), AGENTS.md ("Build & test", |
| +"Stopping rules"), .amadan/README.md. |
| + |
| +You are the independent reviewer. The branch makes test log capture safe |
| +for concurrency (about 75 test files), fixes two test races and one test |
| +hang, adds `70-race` / `make race` (edge in 16 shards, rootaws, systemd, |
| +host tests named Loop or Lease; 371 s on CI) through GATE_RACE=1 in |
| +.amadan/test-gate.sh, and adds `80-gitleaks` / `make gitleaks` (v8.30.1 |
| +over tracked files, .gitleaks.toml with 211 allowlisted findings). No |
| +production code changes are claimed: confirm that. |
| + |
| +## What to check |
| + |
| +1. **gitleaks allowlist:** is it narrow (paths and specific patterns), or |
| + could a real secret added later slip through it? Any allowlisted value |
| + that is actually a real credential? Does the step fail on a planted |
| + secret, and does it scan what it claims? |
| +2. **Race step:** does it really run with -race on what it says; does |
| + GATE_RACE=1 leave the normal gate unchanged; is skipping |
| + TestLinkPinForwardedFallback and running 50 link seeds justified; do |
| + failures fail the step? activator and lease are left out because of 45 |
| + test-cleanup races and a litestream v0.5.14 Store.Close race: is that |
| + recorded honestly in the README? |
| +3. **Log capture helpers:** correct synchronisation; any test weakened by |
| + the migration (an assertion that no longer sees the log it needs, a |
| + lost t.Cleanup restoring the logger)? Sample broadly across the 75 |
| + files. |
| +4. **Test fixes:** the pty CgroupEvents swap, claimstop ctx reassignment, |
| + wakecheck goroutine ending before cleanups, the bootstrap pipe hang: |
| + each correct? |
| +5. **Ratchet record:** only lowered. |
| +6. README, AGENTS.md and step headers true to the scripts. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Follow-up list only. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3 with file:line, failure scenario and fix. End |
| +with exactly one verdict: READY, READY AFTER FIXES, or NOT READY. Do not |
| +edit files, spawn reviewers or run full suites. |
diff --git a/internal/activator/admintoken_test.go b/internal/activator/admintoken_test.go| index 1da90a94f..983a87a83 100644 |
| --- a/internal/activator/admintoken_test.go |
| +++ b/internal/activator/admintoken_test.go |
| @@ -96,17 +96,21 @@ func TestEnsureAdminTokenTightensAFileThatAlreadyHoldsAToken(t *testing.T) { |
| // test in this package (the activator's sweeper logs) can drop a line in |
| // here at any moment, and a test that fails on someone else's log line is a |
| // flake, not a finding. |
| -func captureLog(t *testing.T) *strings.Builder { |
| +// |
| +// The buffer is this package's syncBuffer, locked, for the same reason: a |
| +// goroutine still logging while the test reads (a plain strings.Builder |
| +// here is a data race that `make race` reports). |
| +func captureLog(t *testing.T) *syncBuffer { |
| t.Helper() |
| - var buf strings.Builder |
| + buf := &syncBuffer{} |
| flags := log.Flags() |
| - log.SetOutput(&buf) |
| + log.SetOutput(buf) |
| log.SetFlags(0) |
| t.Cleanup(func() { |
| log.SetOutput(os.Stderr) |
| log.SetFlags(flags) |
| }) |
| - return &buf |
| + return buf |
| } |
| // The ruling (2026-08-24): a malformed existing token is WARNED about and |
diff --git a/internal/activator/cmdunit_test.go b/internal/activator/cmdunit_test.go| index 822cd804d..a6529e09d 100644 |
| --- a/internal/activator/cmdunit_test.go |
| +++ b/internal/activator/cmdunit_test.go |
| @@ -18,7 +18,9 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| -// syncBuffer is a bytes.Buffer two goroutines may write. |
| +// syncBuffer is a bytes.Buffer two goroutines may write, and a test may |
| +// read while they do: this package's log capture (captureLog) writes |
| +// into one. |
| type syncBuffer struct { |
| mu sync.Mutex |
| b bytes.Buffer |
| @@ -30,6 +32,7 @@ func (s *syncBuffer) Write(p []byte) (int, error) { |
| return s.b.Write(p) |
| } |
| func (s *syncBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() } |
| +func (s *syncBuffer) Reset() { s.mu.Lock(); defer s.mu.Unlock(); s.b.Reset() } |
| func TestCmdVarsComposeTheRunEnvironment(t *testing.T) { |
| b := &ExecBackend{ServedPools: eligibleSharedPools, Region: "ie"} |
diff --git a/internal/activator/escrow_alert_test.go b/internal/activator/escrow_alert_test.go| index dff6ae942..b0b441624 100644 |
| --- a/internal/activator/escrow_alert_test.go |
| +++ b/internal/activator/escrow_alert_test.go |
| @@ -1,11 +1,9 @@ |
| package activator |
| import ( |
| - "bytes" |
| "context" |
| "errors" |
| "fmt" |
| - "log" |
| "os" |
| "strings" |
| "testing" |
| @@ -68,12 +66,9 @@ func TestSweepLogsAJoinedAlertAsAnAlert(t *testing.T) { |
| nb.EscrowKey = testEscrowKey(t) |
| holdLease(t, nb, rt) |
| - var buf bytes.Buffer |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - defer log.SetOutput(prev) |
| + buf := captureLog(t) |
| rep := nb.EscrowSweep(ctx, []registry.Route{rt}) |
| - log.SetOutput(prev) |
| + out := buf.String() // the sweep's lines, before anything else logs |
| if len(rep.Failing) != 1 || rep.Failing[0] != host { |
| t.Fatalf("sweep = %+v, want %s failing", rep, host) |
| @@ -81,7 +76,6 @@ func TestSweepLogsAJoinedAlertAsAnAlert(t *testing.T) { |
| if _, err := os.Lstat(escrowConflictPath(nb.DataDir, host)); err != nil { |
| t.Fatalf("no conflict marker, so the joined alert was not raised: %v", err) |
| } |
| - out := buf.String() |
| if !strings.Contains(out, "ALERT: "+host+": escrow: ") { |
| t.Fatalf("log = %q, want the alert", out) |
| } |
diff --git a/internal/activator/haadopt_test.go b/internal/activator/haadopt_test.go| index 6dc77357b..bb012ec97 100644 |
| --- a/internal/activator/haadopt_test.go |
| +++ b/internal/activator/haadopt_test.go |
| @@ -1,12 +1,10 @@ |
| package activator |
| import ( |
| - "bytes" |
| "context" |
| "encoding/json" |
| "fmt" |
| "github.com/carlosframework/platform/internal/release" |
| - "log" |
| "path/filepath" |
| "strings" |
| "testing" |
| @@ -555,10 +553,7 @@ func TestHAAdoptAmbiguousMarkerResponse(t *testing.T) { |
| } |
| func TestDepartureFinalizeTelemetry(t *testing.T) { |
| s, req := haAdoptionFixture(t) |
| - var output bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&output) |
| - defer log.SetOutput(old) |
| + output := captureLog(t) |
| body, _ := json.Marshal(hafresh.Lock{Generation: 5, Owner: heldByB, ExpiresAt: time.Now().Add(-time.Hour)}) |
| putLockFor(t, s.b, s.rt, body) |
| var err error |
diff --git a/internal/activator/harelease_shutdown_test.go b/internal/activator/harelease_shutdown_test.go| index fcc86ac72..34b61d07f 100644 |
| --- a/internal/activator/harelease_shutdown_test.go |
| +++ b/internal/activator/harelease_shutdown_test.go |
| @@ -110,7 +110,7 @@ func TestHAShutdownFinalDeadlineReservesMarker(t *testing.T) { |
| } |
| func TestHAShutdownStuckFinishWritesNoMarker(t *testing.T) { |
| - logs := lockedLog(t) |
| + logs := captureLog(t) |
| s, e, _, _, marker := shutdownFixture(t) |
| entered, unblock := make(chan struct{}), make(chan struct{}) |
| r := e.rep.(*shutdownRep) |
| @@ -195,7 +195,7 @@ func TestHANormalReleaseBudgetsUnchanged(t *testing.T) { |
| } |
| func TestHAShutdownJoinsMarker(t *testing.T) { |
| - logs := lockedLog(t) |
| + logs := captureLog(t) |
| s, e, _, _, marker := shutdownFixture(t) |
| entered, unblock := make(chan struct{}), make(chan struct{}) |
| r := e.rep.(*shutdownRep) |
| @@ -261,7 +261,7 @@ func TestHAShutdownCancelledContextKeepsReleaseBudget(t *testing.T) { |
| } |
| func TestHAShutdownLogsFailedMarkerAfterEntryRemoved(t *testing.T) { |
| - logs := lockedLog(t) |
| + logs := captureLog(t) |
| s, e, _, _, _ := shutdownFixture(t) |
| e.rep.(*shutdownRep).marker = func(context.Context, hafresh.Marker) error { return errors.New("test marker failure") } |
| ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
diff --git a/internal/activator/instancekey_test.go b/internal/activator/instancekey_test.go| index 6cccc2469..dd515c94f 100644 |
| --- a/internal/activator/instancekey_test.go |
| +++ b/internal/activator/instancekey_test.go |
| @@ -5,7 +5,6 @@ import ( |
| "context" |
| "encoding/base64" |
| "errors" |
| - "log" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -112,10 +111,8 @@ func TestEnsureInstanceKeyNeverRewritesAnExistingKey(t *testing.T) { |
| if err := os.WriteFile(p, []byte(existing), 0o600); err != nil { |
| t.Fatal(err) |
| } |
| - var buf bytes.Buffer |
| - log.SetOutput(&buf) |
| + buf := captureLog(t) |
| got, err := ensureInstanceKeyNoConfig(p) |
| - log.SetOutput(os.Stderr) |
| if err != nil || got != InstanceKeyPresent { |
| t.Fatalf("ensure over %q = %v, %v; want present", existing, got, err) |
| } |
diff --git a/internal/activator/opset_test.go b/internal/activator/opset_test.go| index 19939c959..4d70cec2b 100644 |
| --- a/internal/activator/opset_test.go |
| +++ b/internal/activator/opset_test.go |
| @@ -911,25 +911,6 @@ func TestSwapWitnessUnprovenWakeKeepsTheLease(t *testing.T) { |
| } |
| } |
| -// syncLog is a log destination that goroutines may write concurrently (the |
| -// reapers log off the test's goroutine). |
| -type syncLog struct { |
| - mu sync.Mutex |
| - b strings.Builder |
| -} |
| - |
| -func (s *syncLog) Write(p []byte) (int, error) { |
| - s.mu.Lock() |
| - defer s.mu.Unlock() |
| - return s.b.Write(p) |
| -} |
| - |
| -func (s *syncLog) String() string { |
| - s.mu.Lock() |
| - defer s.mu.Unlock() |
| - return s.b.String() |
| -} |
| - |
| // Shutdown covers a retained failed wake (spec §7.4, I2: nothing runs after |
| // Shutdown returns). No entry waits for one, so Shutdown polls its reaper |
| // until the generation is proven stopped and the lease given back, or the |
| @@ -967,7 +948,7 @@ func TestSwapWitnessShutdownWaitsForAnUnprovenWake(t *testing.T) { |
| if !retained() || b.releaseCount() != 0 { |
| t.Fatalf("retained %v, lease releases %d: want the failed wake retained with its lease", retained(), b.releaseCount()) |
| } |
| - logs := &syncLog{} |
| + logs := &syncBuffer{} |
| if !row.heal { |
| flags := log.Flags() |
| log.SetOutput(logs) |
diff --git a/internal/activator/pendingwake_linux_test.go b/internal/activator/pendingwake_linux_test.go| index 195551997..e3f9b0517 100644 |
| --- a/internal/activator/pendingwake_linux_test.go |
| +++ b/internal/activator/pendingwake_linux_test.go |
| @@ -1415,7 +1415,7 @@ type checkpointRig struct { |
| a *Service |
| rt registry.Route |
| prefix string |
| - log *lockedBuf |
| + log *syncBuffer |
| // kept receives the host each time a stop is kept pending over an |
| // unproven checkpoint (Service.checkpointKept). |
| kept chan string |
| @@ -1442,7 +1442,7 @@ func newCheckpointRig(t *testing.T, region string) *checkpointRig { |
| if err := reg.Upsert(rt); err != nil { |
| t.Fatal(err) |
| } |
| - r := &checkpointRig{fx: fx, b: b, rt: rt, prefix: b.Cfg.hibernatePrefix(rt.Host), log: lockedLog(t), kept: make(chan string, 8)} |
| + r := &checkpointRig{fx: fx, b: b, rt: rt, prefix: b.Cfg.hibernatePrefix(rt.Host), log: captureLog(t), kept: make(chan string, 8)} |
| r.a = New(Config{Bucket: fx.Bucket, Idle: time.Hour}, b, reg) |
| r.a.checkpointKept = func(host string) { r.kept <- host } |
| // Whatever a test leaves running stops before the fixture closes, |
diff --git a/internal/activator/poolwithdrawal_retry_test.go b/internal/activator/poolwithdrawal_retry_test.go| index a584b3007..fa9a563df 100644 |
| --- a/internal/activator/poolwithdrawal_retry_test.go |
| +++ b/internal/activator/poolwithdrawal_retry_test.go |
| @@ -3,7 +3,6 @@ package activator |
| import ( |
| "context" |
| "errors" |
| - "log" |
| "strings" |
| "sync/atomic" |
| "testing" |
| @@ -45,10 +44,7 @@ func TestPoolWithdrawalReconcileRetriesAdmissionAfterRestart(t *testing.T) { |
| if !view.Snapshot().Complete { |
| t.Fatal("incomplete record view") |
| } |
| - var logs syncBuffer |
| - old := log.Writer() |
| - log.SetOutput(&logs) |
| - t.Cleanup(func() { log.SetOutput(old) }) |
| + logs := captureLog(t) |
| now := time.Now() |
| withdrawn := 0 |
| cfg := provision.ReconcileConfig{ |
diff --git a/internal/activator/poolwithdrawal_test.go b/internal/activator/poolwithdrawal_test.go| index 4acedf1f5..8e5276021 100644 |
| --- a/internal/activator/poolwithdrawal_test.go |
| +++ b/internal/activator/poolwithdrawal_test.go |
| @@ -3,7 +3,6 @@ package activator |
| import ( |
| "context" |
| "errors" |
| - "log" |
| "reflect" |
| "strings" |
| "sync/atomic" |
| @@ -340,10 +339,7 @@ func TestPoolWithdrawalLogsProofAttempt(t *testing.T) { |
| if fail { |
| s.b.StartupSwept = func() bool { return false } |
| } |
| - var logs syncBuffer |
| - old := log.Writer() |
| - log.SetOutput(&logs) |
| - defer log.SetOutput(old) |
| + logs := captureLog(t) |
| job := &poolWithdrawal{route: row, owner: "pool-withdrawal/" + row.Host} |
| s.a.provePoolWithdrawal(s.b, job) |
| if !job.done || (job.err != nil) != fail { |
diff --git a/internal/activator/pty_linux_test.go b/internal/activator/pty_linux_test.go| index f470b023c..8b43eaaf6 100644 |
| --- a/internal/activator/pty_linux_test.go |
| +++ b/internal/activator/pty_linux_test.go |
| @@ -502,25 +502,32 @@ func TestRootfsTTYKeepsTheDeclaredProcess(t *testing.T) { |
| } |
| // recordEvents wraps b's cgroup reader to record every unit it is asked |
| -// about. |
| -func recordEvents(b *ExecBackend) func() []string { |
| +// about once arm is called. Install it before anything starts: a unit's |
| +// observer reads b.CgroupEvents from its own goroutine, so swapping the |
| +// field after a start is a data race. arm marks where recording begins. |
| +func recordEvents(b *ExecBackend) (arm func(), units func() []string) { |
| var mu sync.Mutex |
| - var units []string |
| + var armed bool |
| + var got []string |
| prev := b.CgroupEvents |
| b.CgroupEvents = func(slice, unit string) (bool, bool, error) { |
| mu.Lock() |
| - units = append(units, unit) |
| + if armed { |
| + got = append(got, unit) |
| + } |
| mu.Unlock() |
| if prev == nil { |
| return false, false, nil |
| } |
| return prev(slice, unit) |
| } |
| - return func() []string { |
| + arm = func() { mu.Lock(); armed = true; mu.Unlock() } |
| + units = func() []string { |
| mu.Lock() |
| defer mu.Unlock() |
| - return slices.Clone(units) |
| + return slices.Clone(got) |
| } |
| + return arm, units |
| } |
| // TTYUnitPollsAndStopsItsOwnRole (PF-7): on either kind of row, a |
| @@ -529,7 +536,8 @@ func recordEvents(b *ExecBackend) func() []string { |
| func TestTTYUnitPollsAndStopsItsOwnRole(t *testing.T) { |
| t.Run("binary", func(t *testing.T) { |
| b, rt, ctl, _, u := startBinaryTTY(t) |
| - events := recordEvents(b) |
| + arm, events := recordEvents(b) |
| + arm() |
| ctl.ttyStatus = instancectl.CmdStatus{InvocationID: "inv-t", State: instancectl.CmdRunning} |
| ctl.cmdStatus = instancectl.CmdStatus{InvocationID: "inv-t", State: instancectl.CmdGone} |
| st, err := u.Poll(context.Background()) |
| @@ -555,6 +563,7 @@ func TestTTYUnitPollsAndStopsItsOwnRole(t *testing.T) { |
| }) |
| t.Run("rootfs", func(t *testing.T) { |
| b, ctl := newRootfsBackend(t) |
| + arm, events := recordEvents(b) |
| ctl.ttyInv = "inv-t" |
| rt := rootfsRoute(b) |
| up, _ := startRootfsGen7(t, b, ctl, rt, "SHOP_MODE=live\n") |
| @@ -563,7 +572,7 @@ func TestTTYUnitPollsAndStopsItsOwnRole(t *testing.T) { |
| if err != nil { |
| t.Fatalf("StartCmd: %v", err) |
| } |
| - events := recordEvents(b) |
| + arm() |
| ctl.ttyStatusRootfs = instancectl.CmdStatus{InvocationID: "inv-t", State: instancectl.CmdRunning} |
| ctl.cmdStatusRootfs = instancectl.CmdStatus{InvocationID: "inv-t", State: instancectl.CmdGone} |
| st, err := u.Poll(context.Background()) |
| @@ -586,7 +595,9 @@ func TestTTYUnitPollsAndStopsItsOwnRole(t *testing.T) { |
| t.Errorf("the settle read %q, want the rootfs tty unit %s", got, ttyUnit) |
| } |
| for _, unit := range got { |
| - if unit != ttyUnit { |
| + // The serving generation's own observer reads its unit for as |
| + // long as it runs; that is not the session's settle. |
| + if unit != ttyUnit && unit != up.unit { |
| t.Errorf("the settle read another unit's cgroup: %s", unit) |
| } |
| } |
diff --git a/internal/activator/rootfs_resident_test.go b/internal/activator/rootfs_resident_test.go| index cb4ab2d5e..e9cd92dae 100644 |
| --- a/internal/activator/rootfs_resident_test.go |
| +++ b/internal/activator/rootfs_resident_test.go |
| @@ -11,7 +11,6 @@ import ( |
| "context" |
| "errors" |
| "fmt" |
| - "log" |
| "net/http" |
| "net/http/httptest" |
| "strconv" |
| @@ -540,10 +539,7 @@ func TestResidentReplicationIsTheActivators(t *testing.T) { |
| func TestResidentRefusalCountsNoFailure(t *testing.T) { |
| host := "shop.example.com" |
| a, b, clk, _, _, _ := residentService(t, time.Hour, residentRoute(host)) |
| - var buf syncBuffer |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(prev) }) |
| + buf := captureLog(t) |
| b.mu.Lock() |
| b.startable = func(context.Context, registry.Route) error { |
| return refuseRootfs(errors.New("this box is shared")) |
diff --git a/internal/activator/rootfs_swap_release_test.go b/internal/activator/rootfs_swap_release_test.go| index 860a80109..e98189aff 100644 |
| --- a/internal/activator/rootfs_swap_release_test.go |
| +++ b/internal/activator/rootfs_swap_release_test.go |
| @@ -741,7 +741,7 @@ func TestShutdownCancelsAReleaseBeforeASwap(t *testing.T) { |
| // the record is gone. |
| func TestSwapReleaseLeaseLossRacesTheSweep(t *testing.T) { |
| shrinkRelease(t, 200*time.Millisecond, 50*time.Millisecond) |
| - logs := captureLockedLog(t) |
| + logs := captureLog(t) |
| for round := 0; round < 5; round++ { |
| f := newRelSwapFixture(t, true) |
| incumbent := f.b.lastProc() |
| @@ -824,7 +824,7 @@ func TestUnprovenSwapReleaseIsNotABuildFailure(t *testing.T) { |
| // C8: a hibernating incumbent is neither idled nor ceilinged while the |
| // release runs; the ceiling fires on the first sweep after it ends. |
| func TestIncumbentNeverIdlesThroughAMigration(t *testing.T) { |
| - logs := captureLockedLog(t) |
| + logs := captureLog(t) |
| f := newRelSwapFixture(t, true) |
| incumbent := f.b.lastProc() |
| f.a.SetMaxRunFor(func(registry.Route) time.Duration { return 3 * time.Hour }) |
diff --git a/internal/activator/rootfsrelease_test.go b/internal/activator/rootfsrelease_test.go| index bdac13487..21696bfc3 100644 |
| --- a/internal/activator/rootfsrelease_test.go |
| +++ b/internal/activator/rootfsrelease_test.go |
| @@ -13,7 +13,6 @@ import ( |
| "errors" |
| "fmt" |
| "io" |
| - "log" |
| "net" |
| "net/http" |
| "net/http/httptest" |
| @@ -1986,33 +1985,6 @@ func TestUnprovenReleaseOnAnAwakeIncumbentIsRetried(t *testing.T) { |
| } |
| } |
| -// captureLockedLog sends the package log to a buffer goroutines may write |
| -// to, for one test. Not parallel. |
| -func captureLockedLog(t *testing.T) *lockedBuffer { |
| - t.Helper() |
| - buf := &lockedBuffer{} |
| - log.SetOutput(buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| - return buf |
| -} |
| - |
| -type lockedBuffer struct { |
| - mu sync.Mutex |
| - b bytes.Buffer |
| -} |
| - |
| -func (l *lockedBuffer) Write(p []byte) (int, error) { |
| - l.mu.Lock() |
| - defer l.mu.Unlock() |
| - return l.b.Write(p) |
| -} |
| - |
| -func (l *lockedBuffer) String() string { |
| - l.mu.Lock() |
| - defer l.mu.Unlock() |
| - return l.b.String() |
| -} |
| - |
| // shutdownIn runs Shutdown with budget in the background; the channel |
| // closes when it returns. |
| func shutdownIn(a *Service, budget time.Duration) <-chan struct{} { |
| @@ -2239,7 +2211,7 @@ func TestShutdownDrainsReleaseOps(t *testing.T) { |
| t.Run("still unproven at the deadline", func(t *testing.T) { |
| r := newConsumerRig(t, true) |
| orphan(t, r) |
| - buf := captureLockedLog(t) |
| + buf := captureLog(t) |
| select { |
| case <-shutdownIn(r.a, 300*time.Millisecond): |
| case <-time.After(5 * time.Second): |
diff --git a/internal/activator/seed_diagnostic_test.go b/internal/activator/seed_diagnostic_test.go| index 7eeb78c5a..0eaa05321 100644 |
| --- a/internal/activator/seed_diagnostic_test.go |
| +++ b/internal/activator/seed_diagnostic_test.go |
| @@ -1,9 +1,7 @@ |
| package activator |
| import ( |
| - "bytes" |
| "github.com/carlosframework/platform/internal/registry" |
| - "log" |
| "net/http/httptest" |
| "strings" |
| "testing" |
| @@ -11,10 +9,7 @@ import ( |
| ) |
| func TestUnseededDiagnosticsStayBoundedWhileEveryRequestRefuses(t *testing.T) { |
| - var logs bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&logs) |
| - defer log.SetOutput(old) |
| + logs := captureLog(t) |
| now := time.Unix(100, 0) |
| a := &Service{now: func() time.Time { return now }} |
| rt := registry.Route{Host: "b.example"} |
diff --git a/internal/activator/shutdown_lease_test.go b/internal/activator/shutdown_lease_test.go| index 51fbc15f3..fda87a644 100644 |
| --- a/internal/activator/shutdown_lease_test.go |
| +++ b/internal/activator/shutdown_lease_test.go |
| @@ -3,11 +3,8 @@ package activator |
| import ( |
| "context" |
| "errors" |
| - "log" |
| - "os" |
| "slices" |
| "strings" |
| - "sync" |
| "testing" |
| "time" |
| ) |
| @@ -217,7 +214,7 @@ func TestShutdownRetriesAFailedLeaseRelease(t *testing.T) { |
| // P3's other half: a release still unresolved when Shutdown's budget ends |
| // is logged by host, not dropped silently. |
| func TestShutdownLogsALeaseReleaseItCouldNotResolve(t *testing.T) { |
| - logs := lockedLog(t) |
| + logs := captureLog(t) |
| a, b, _, _ := testActivator(t, time.Hour) |
| b.startErr = errors.New("start failed") |
| b.releaseErrs = []error{errors.New("delete lease: timeout")} |
| @@ -238,37 +235,6 @@ func TestShutdownLogsALeaseReleaseItCouldNotResolve(t *testing.T) { |
| } |
| } |
| -// lockedBuf is a log sink safe against the activator's own goroutines. |
| -type lockedBuf struct { |
| - mu sync.Mutex |
| - buf strings.Builder |
| -} |
| - |
| -func (l *lockedBuf) Write(p []byte) (int, error) { |
| - l.mu.Lock() |
| - defer l.mu.Unlock() |
| - return l.buf.Write(p) |
| -} |
| - |
| -func (l *lockedBuf) String() string { |
| - l.mu.Lock() |
| - defer l.mu.Unlock() |
| - return l.buf.String() |
| -} |
| - |
| -func lockedLog(t *testing.T) *lockedBuf { |
| - t.Helper() |
| - l := &lockedBuf{} |
| - flags := log.Flags() |
| - log.SetOutput(l) |
| - log.SetFlags(0) |
| - t.Cleanup(func() { |
| - log.SetOutput(os.Stderr) |
| - log.SetFlags(flags) |
| - }) |
| - return l |
| -} |
| - |
| // Once Shutdown has begun, nothing wakes. A request queued on a stop must |
| // not wake the host afresh when that stop finishes after Shutdown began: |
| // the wake would take a lease once Shutdown had stopped looking. Startup |
| @@ -383,7 +349,7 @@ func TestAnExitAfterShutdownBeganIsNotUnexpected(t *testing.T) { |
| // records pass their own expiry the retries retire them (logged) instead |
| // of running forever. |
| func TestOwedReleasesAreRetiredOnceTheirRecordsExpire(t *testing.T) { |
| - logs := lockedLog(t) |
| + logs := captureLog(t) |
| a, b, _, _ := testActivator(t, time.Hour) |
| b.startErr = errors.New("start failed") |
| hosts := []string{"one.example.com", "two.example.com", "three.example.com"} |
diff --git a/internal/activator/shuttingdown_answer_test.go b/internal/activator/shuttingdown_answer_test.go| index 66ddfc88b..aebe16b9a 100644 |
| --- a/internal/activator/shuttingdown_answer_test.go |
| +++ b/internal/activator/shuttingdown_answer_test.go |
| @@ -1,8 +1,6 @@ |
| package activator |
| import ( |
| - "bytes" |
| - "log" |
| "net/http" |
| "net/http/httptest" |
| "strings" |
| @@ -30,10 +28,7 @@ func TestShuttingDownAnswersRetryAfter(t *testing.T) { |
| a.shuttingDown = true |
| a.mu.Unlock() |
| - var logs bytes.Buffer |
| - prev, flags := log.Writer(), log.Flags() |
| - log.SetOutput(&logs) |
| - t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) }) |
| + logs := captureLog(t) |
| rt := testRoute("shop.example.com") |
| rt.HA = tc.forwarded |
diff --git a/internal/activator/wakecheck_test.go b/internal/activator/wakecheck_test.go| index fff482043..70c4df19a 100644 |
| --- a/internal/activator/wakecheck_test.go |
| +++ b/internal/activator/wakecheck_test.go |
| @@ -576,14 +576,26 @@ func TestAHeldUnitRowRefusesALinkThatMovedAfterTheWait(t *testing.T) { |
| // budget) never holds the wake past wakeWaitBound. |
| func TestAHeldWakesReaskNeverOutlastsTheWait(t *testing.T) { |
| // The re-ask comes 8 polls (175 ms) into a 400 ms wait, and its answer |
| - // takes 5 s: the wait must end at its own bound. |
| + // does not come back until the test is over (the refresh's own 5 s |
| + // budget, and longer): the wait must end at its own bound. |
| shrinkHeldPoll(t, 25*time.Millisecond) |
| shrinkWakeWait(t, 400*time.Millisecond) |
| a, b := identityActivator(t, "v3") |
| + // The slow answer is released, and has returned, before the cleanups |
| + // registered above put the package's bounds back: a goroutine left |
| + // running past the test would outlive what it was testing. |
| + release, returned := make(chan struct{}), make(chan struct{}, 4) |
| var asked atomic.Int32 |
| + t.Cleanup(func() { |
| + close(release) |
| + for range asked.Load() - 1 { |
| + <-returned |
| + } |
| + }) |
| a.HeldTarget = func(string) HeldWake { |
| if asked.Add(1) > 1 { |
| - time.Sleep(5 * time.Second) // the refresh's own budget |
| + <-release |
| + defer func() { returned <- struct{}{} }() |
| } |
| return HeldWake{Target: "v1", Held: true} |
| } |
diff --git a/internal/activator/worker_identity_test.go b/internal/activator/worker_identity_test.go| index 25c52618f..2a98173f4 100644 |
| --- a/internal/activator/worker_identity_test.go |
| +++ b/internal/activator/worker_identity_test.go |
| @@ -455,8 +455,8 @@ func TestWorkerRecycleNeverConvergesWhenTheSchedulerIsPresent(t *testing.T) { |
| // is what starts it. Before the fix both respawned from live/<host>. |
| func TestAnArmedBoxNeverRecyclesAnUncapturedWorkerFromTheLiveLink(t *testing.T) { |
| const said = "has no captured build, and the release scheduler owns its recycles" |
| - capture := func(t *testing.T) *syncLog { |
| - logs := &syncLog{} |
| + capture := func(t *testing.T) *syncBuffer { |
| + logs := &syncBuffer{} |
| flags := log.Flags() |
| log.SetOutput(logs) |
| t.Cleanup(func() { log.SetOutput(os.Stderr); log.SetFlags(flags) }) |
diff --git a/internal/edge/certbackfill_test.go b/internal/edge/certbackfill_test.go| index b86725c4c..fc68e800c 100644 |
| --- a/internal/edge/certbackfill_test.go |
| +++ b/internal/edge/certbackfill_test.go |
| @@ -227,9 +227,7 @@ func TestBackfillAccountKeySeedsOnlyFromTheIssuer(t *testing.T) { |
| // bucket copy's identity, so the settled box un-settles on its next poll |
| // and republishes the newer cert — the clobber is transient, not durable. |
| func TestBackfillRepairsAnOlderLeafClobber(t *testing.T) { |
| - var buf strings.Builder |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + buf := captureLog(t) |
| s := release.NewDirStore(t.TempDir()) |
| local := autocert.DirCache(t.TempDir()) |
| newer := hostCertPEM(t, "a.example.com", time.Now().Add(48*time.Hour)) |
| @@ -326,9 +324,7 @@ func (f *failingPutStore) Put(context.Context, string, []byte, string) (string, |
| // A write-denied bucket retries every pass and says so on the file's |
| // first-and-every-tenth cadence, never every 30 seconds. |
| func TestBackfillFailureIsRetriedAndThrottled(t *testing.T) { |
| - var buf strings.Builder |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + buf := captureLog(t) |
| inner := release.NewDirStore(t.TempDir()) |
| local := autocert.DirCache(t.TempDir()) |
| putLocal(t, local, "a.example.com", hostCertPEM(t, "a.example.com", time.Now().Add(time.Hour))) |
| @@ -371,8 +367,7 @@ func TestBackfillSteadyStateDoesNotReread(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| - var buf strings.Builder |
| - log.SetOutput(&buf) |
| + buf := captureLog(t) |
| c := &putCountingStore{Store: s} |
| m.s = c |
| m.backfill(context.Background()) |
diff --git a/internal/edge/certsync_test.go b/internal/edge/certsync_test.go| index 1c7c258b6..075db4884 100644 |
| --- a/internal/edge/certsync_test.go |
| +++ b/internal/edge/certsync_test.go |
| @@ -127,10 +127,7 @@ func (f *failingStore) Delete(context.Context, string) error { |
| // failure is loud, and autocert never sees an error (a returned error would |
| // abort an issuance that actually succeeded). |
| func TestPublishingCacheBucketFailureNeverFailsTheLocalOperation(t *testing.T) { |
| - var buf bytes.Buffer |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(prev) }) |
| + buf := captureLog(t) |
| s := &failingStore{Store: release.NewDirStore(t.TempDir()), putErr: errors.New("bucket down")} |
| dir := t.TempDir() |
diff --git a/internal/edge/cookiescope_test.go b/internal/edge/cookiescope_test.go| index c75b4f245..3371a173e 100644 |
| --- a/internal/edge/cookiescope_test.go |
| +++ b/internal/edge/cookiescope_test.go |
| @@ -1,12 +1,9 @@ |
| package edge |
| import ( |
| - "bytes" |
| "fmt" |
| - "log" |
| "net/http" |
| "net/http/httptest" |
| - "os" |
| "slices" |
| "strings" |
| "testing" |
| @@ -213,9 +210,7 @@ func TestCookieScopeOnTheCachePath(t *testing.T) { |
| // One log line per route per process, naming the route. |
| func TestCookieScopeLogsOncePerRoute(t *testing.T) { |
| - var buf bytes.Buffer |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + buf := captureLog(t) |
| e := cookieEdge(t, cookieAcct, setCookies("a=1; Domain=oncarlos.com", "b=2; Domain=oncarlos.com"), cookieHost, "blog.kmqa.oncarlos.com") |
| for range 3 { |
| getCookies(t, e, "http://"+cookieHost+"/") |
diff --git a/internal/edge/demo_terms_test.go b/internal/edge/demo_terms_test.go| index 6bdfa80f3..5ea64f7e6 100644 |
| --- a/internal/edge/demo_terms_test.go |
| +++ b/internal/edge/demo_terms_test.go |
| @@ -1,9 +1,7 @@ |
| package edge |
| import ( |
| - "bytes" |
| "io" |
| - "log" |
| "net/http" |
| "net/http/httptest" |
| "net/http/httputil" |
| @@ -39,10 +37,7 @@ func TestDemoBannerTerms(t *testing.T) { |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| t.Setenv("CARLOS_DEMO_TERMS_URL", tc.value) |
| - var logs bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&logs) |
| - defer log.SetOutput(old) |
| + logs := captureLog(t) |
| reg, err := registry.Open(t.TempDir() + "/registry.db") |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/edge/devbox_test.go b/internal/edge/devbox_test.go| index d4836891c..db3fdec9b 100644 |
| --- a/internal/edge/devbox_test.go |
| +++ b/internal/edge/devbox_test.go |
| @@ -1,7 +1,6 @@ |
| package edge |
| import ( |
| - "bytes" |
| "context" |
| "crypto/tls" |
| "crypto/x509" |
| @@ -197,25 +196,6 @@ func TestDevboxEdgeSwitchesOff(t *testing.T) { |
| } |
| } |
| -// lockedBuffer is a bytes.Buffer safe for the server's goroutines to write |
| -// while the test reads it. |
| -type lockedBuffer struct { |
| - mu sync.Mutex |
| - buf bytes.Buffer |
| -} |
| - |
| -func (b *lockedBuffer) Write(p []byte) (int, error) { |
| - b.mu.Lock() |
| - defer b.mu.Unlock() |
| - return b.buf.Write(p) |
| -} |
| - |
| -func (b *lockedBuffer) String() string { |
| - b.mu.Lock() |
| - defer b.mu.Unlock() |
| - return b.buf.String() |
| -} |
| - |
| // heldBackend is an upstream whose handler signals entered and then holds |
| // the request until release is called (or the test ends). |
| func heldBackend(t *testing.T) (addr string, entered <-chan struct{}, release func()) { |
diff --git a/internal/edge/logcapture_test.go b/internal/edge/logcapture_test.go| new file mode 100644 |
| index 000000000..1c5520895 |
| --- /dev/null |
| +++ b/internal/edge/logcapture_test.go |
| @@ -0,0 +1,56 @@ |
| +package edge |
| + |
| +import ( |
| + "bytes" |
| + "log" |
| + "sync" |
| + "testing" |
| +) |
| + |
| +// This package's one log capture. The edge logs from its servers, watchers |
| +// and pollers, and a goroutine an earlier test left behind can log into any |
| +// test's capture, so the buffer is always locked: a plain bytes.Buffer or |
| +// strings.Builder handed to log.SetOutput is a data race that `make race` |
| +// reports. |
| + |
| +// lockedBuffer is a bytes.Buffer behind a lock, for a log (or a server's |
| +// ErrorLog) a test reads while something may still write to it. |
| +type lockedBuffer struct { |
| + mu sync.Mutex |
| + buf bytes.Buffer |
| +} |
| + |
| +func (b *lockedBuffer) Write(p []byte) (int, error) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + return b.buf.Write(p) |
| +} |
| + |
| +func (b *lockedBuffer) String() string { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + return b.buf.String() |
| +} |
| + |
| +func (b *lockedBuffer) Len() int { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + return b.buf.Len() |
| +} |
| + |
| +func (b *lockedBuffer) Reset() { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + b.buf.Reset() |
| +} |
| + |
| +// captureLog sends the standard logger to a locked buffer until the test |
| +// ends. |
| +func captureLog(t *testing.T) *lockedBuffer { |
| + t.Helper() |
| + buf := &lockedBuffer{} |
| + prev, flags := log.Writer(), log.Flags() |
| + log.SetOutput(buf) |
| + t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) }) |
| + return buf |
| +} |
diff --git a/internal/edge/mesh_test.go b/internal/edge/mesh_test.go| index e873dedbf..57f8c194d 100644 |
| --- a/internal/edge/mesh_test.go |
| +++ b/internal/edge/mesh_test.go |
| @@ -4,7 +4,6 @@ import ( |
| "bytes" |
| "context" |
| "encoding/hex" |
| - "log" |
| "strings" |
| "testing" |
| "time" |
| @@ -12,18 +11,6 @@ import ( |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| -// captureLog redirects the standard logger for the duration of a test — |
| -// synchronous callers only (mintMeshKey, loadMeshKeys direct calls here are |
| -// never run concurrently with the read), same shape certsync_test.go uses. |
| -func captureLog(t *testing.T) *bytes.Buffer { |
| - t.Helper() |
| - var buf bytes.Buffer |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(prev) }) |
| - return &buf |
| -} |
| - |
| // meshTestStore is a fresh directory-backed store, the same DirStore every |
| // other edge test in this package uses in place of live S3. |
| func meshTestStore(t *testing.T) release.Store { |
diff --git a/internal/edge/proxyingress_test.go b/internal/edge/proxyingress_test.go| index 0e0a12ddf..f1a454efb 100644 |
| --- a/internal/edge/proxyingress_test.go |
| +++ b/internal/edge/proxyingress_test.go |
| @@ -8,7 +8,6 @@ import ( |
| "encoding/binary" |
| "errors" |
| "io" |
| - "log" |
| "net" |
| "net/http" |
| "net/http/httptest" |
| @@ -270,10 +269,7 @@ func TestProxiedRequestReachesLimiterAndXFF(t *testing.T) { |
| fixed := time.Now() |
| e.rateLimiter = ratelimit.NewLimiter(func() time.Time { return fixed }, 100_000) |
| armed(t, e, ppLoopback, t.TempDir()) |
| - logs := &lockedBuffer{} |
| - prev := log.Writer() |
| - log.SetOutput(logs) |
| - t.Cleanup(func() { log.SetOutput(prev) }) |
| + logs := captureLog(t) |
| pe := newProxyEdge(t, e, proxyOpts{}) |
| res := pe.exchange(t, true, ppv2Proxy("203.0.113.7:51000"), http.MethodGet, rlHost, "/") |
diff --git a/internal/edge/purge_header_test.go b/internal/edge/purge_header_test.go| index ba9fbc4e5..c9aa6b884 100644 |
| --- a/internal/edge/purge_header_test.go |
| +++ b/internal/edge/purge_header_test.go |
| @@ -2,17 +2,14 @@ package edge |
| import ( |
| "bufio" |
| - "bytes" |
| "errors" |
| "fmt" |
| "io" |
| - "log" |
| "net" |
| "net/http" |
| "net/http/httptest" |
| "net/http/httptrace" |
| "net/textproto" |
| - "os" |
| "path/filepath" |
| "strings" |
| "syscall" |
| @@ -1127,9 +1124,7 @@ func TestPurgeHeaderListedInConnectionIsEatenBeforeTheHook(t *testing.T) { |
| // line per request forever. Same first-then-every-300th shape as the registry |
| // watcher in edge.go. |
| func TestPurgeHeaderComplaintLogIsRateLimited(t *testing.T) { |
| - var buf bytes.Buffer |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + buf := captureLog(t) |
| e, _ := purgeEdge(t, "noisy.example.com", false, func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Carlos-Purge", "a.example.com/smuggled") |
| @@ -1623,9 +1618,7 @@ func TestPurgeHostHeaderScrubbedFromRequestOverUnixSocket(t *testing.T) { |
| // remote party's response on the request hot path, so they share the |
| // first-then-every-300th shape every other purge complaint uses. |
| func TestPurgeHostOverrideRefusalIsLoggedRateLimited(t *testing.T) { |
| - var buf bytes.Buffer |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + buf := captureLog(t) |
| e, _ := purgeOverrideEdge(t, |
| route("a.example.com", "app-x", "tenanta"), |
diff --git a/internal/edge/purge_hosts_test.go b/internal/edge/purge_hosts_test.go| index 405f7b603..189b3df1f 100644 |
| --- a/internal/edge/purge_hosts_test.go |
| +++ b/internal/edge/purge_hosts_test.go |
| @@ -1,12 +1,9 @@ |
| package edge |
| import ( |
| - "bytes" |
| "fmt" |
| - "log" |
| "net/http" |
| "net/http/httptest" |
| - "os" |
| "strings" |
| "testing" |
| @@ -237,9 +234,7 @@ func TestPurgeHostListOneBadEntryRefusesTheWholeList(t *testing.T) { |
| // cost the purge of the hosts this edge does serve. The unserved host's own |
| // (orphaned) entry is left alone: skipped means not judged, never purged. |
| func TestPurgeHostListSkipsUnservedHosts(t *testing.T) { |
| - var buf bytes.Buffer |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + buf := captureLog(t) |
| e := purgeHostsEdge(t, titoAccount(), func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Carlos-Purge-Host", "ghost.example, tickets.acme.example") |
diff --git a/internal/edge/regional_e2e_test.go b/internal/edge/regional_e2e_test.go| index 1c5bfcb00..476ed9be0 100644 |
| --- a/internal/edge/regional_e2e_test.go |
| +++ b/internal/edge/regional_e2e_test.go |
| @@ -7,7 +7,6 @@ import ( |
| "errors" |
| "fmt" |
| "io" |
| - "log" |
| "net" |
| "net/http" |
| "net/http/httptest" |
| @@ -221,24 +220,6 @@ func rgGolden(t *testing.T, name string) map[string]string { |
| return out |
| } |
| -// rgLogBuffer is a log writer safe to read while the edge writes. |
| -type rgLogBuffer struct { |
| - mu sync.Mutex |
| - b bytes.Buffer |
| -} |
| - |
| -func (l *rgLogBuffer) Write(p []byte) (int, error) { |
| - l.mu.Lock() |
| - defer l.mu.Unlock() |
| - return l.b.Write(p) |
| -} |
| - |
| -func (l *rgLogBuffer) String() string { |
| - l.mu.Lock() |
| - defer l.mu.Unlock() |
| - return l.b.String() |
| -} |
| - |
| // rgDo drives one request at one box through its client and reads the body. |
| func rgDo(t *testing.T, be *backhaulEdge, method, rawURL string, headers map[string]string, form url.Values) (*http.Response, string) { |
| t.Helper() |
| @@ -586,9 +567,7 @@ func TestRegionalNameNeverLeavesItsRegion(t *testing.T) { |
| t.Fatalf("precondition: B answers %d %q, want 200 tuk", resp.StatusCode, body) |
| } |
| - logs := &rgLogBuffer{} |
| - log.SetOutput(logs) |
| - t.Cleanup(func() { log.SetOutput(io.Discard) }) |
| + logs := captureLog(t) |
| addr, accepts := rgTCPCounter(t) |
| for _, h := range []string{rgStar, rgApex} { |
diff --git a/internal/edge/rootfs_reload_test.go b/internal/edge/rootfs_reload_test.go| index 0ef06ce9a..b11fdd13c 100644 |
| --- a/internal/edge/rootfs_reload_test.go |
| +++ b/internal/edge/rootfs_reload_test.go |
| @@ -1,8 +1,6 @@ |
| package edge |
| import ( |
| - "bytes" |
| - "log" |
| "strings" |
| "testing" |
| @@ -96,10 +94,7 @@ func TestReloadManagesResidentRootfs(t *testing.T) { |
| // edge's diagnostic names every row only an activator would start, a |
| // resident rootfs instance included, and no binary awake row. |
| func TestNoActivatorAdviceNamesResidentRootfs(t *testing.T) { |
| - var buf bytes.Buffer |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - defer log.SetOutput(prev) |
| + buf := captureLog(t) |
| if _, err := New(reloadRegistry(t), nil); err != nil { |
| t.Fatalf("New: %v", err) |
| } |
diff --git a/internal/edge/tunnel_test.go b/internal/edge/tunnel_test.go| index 4ba3c095a..0ba487131 100644 |
| --- a/internal/edge/tunnel_test.go |
| +++ b/internal/edge/tunnel_test.go |
| @@ -1,14 +1,11 @@ |
| package edge |
| import ( |
| - "bytes" |
| "crypto/sha256" |
| "encoding/hex" |
| - "log" |
| "net" |
| "net/http" |
| "net/http/httptest" |
| - "os" |
| "strings" |
| "testing" |
| "time" |
| @@ -478,9 +475,7 @@ func TestEnableTunnelsFromEnv(t *testing.T) { |
| t.Setenv("CARLOS_TUNNEL_HOST", "tunnel.test") |
| t.Setenv("CARLOS_TUNNEL_CLIENTS", "") |
| e := newEdge() |
| - var buf bytes.Buffer |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + buf := captureLog(t) |
| if err := enableTunnelsFromEnv(e); err != nil { |
| t.Fatalf("CARLOS_TUNNEL_HOST with no static clients: %v", err) |
| } |
diff --git a/internal/edge/wildcard_parents_test.go b/internal/edge/wildcard_parents_test.go| index 7a495bcdb..e904ae9ae 100644 |
| --- a/internal/edge/wildcard_parents_test.go |
| +++ b/internal/edge/wildcard_parents_test.go |
| @@ -3,8 +3,6 @@ package edge |
| import ( |
| "context" |
| "fmt" |
| - "log" |
| - "os" |
| "path/filepath" |
| "reflect" |
| "sort" |
| @@ -431,9 +429,7 @@ func TestHomeMapWildcardCollisionMergesClasses(t *testing.T) { |
| func TestUnionDelegatedCapsAndWarns(t *testing.T) { |
| delegatedCapLogged.Store(0) // once-per-process throttles: isolate from -count>1 |
| delegationZoneUnsetOnce = sync.Once{} |
| - var buf strings.Builder |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + buf := captureLog(t) |
| local := []string{"l1.example", "l2.example"} |
| remote := make([]string, 0, 40) |
| for i := 0; i < 40; i++ { |
| @@ -564,10 +560,7 @@ func TestRefreshKeepsLastGoodNamesOnReadError(t *testing.T) { |
| } |
| // The failed reads below log by design: capture them, so they do not |
| // escape into test output, and check the names reader said so. |
| - var buf strings.Builder |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(prev) }) |
| + buf := captureLog(t) |
| reg.Close() // every read fails from here |
| if _, err := reg.ListAccountNamespaces(); err == nil { |
| t.Fatal("test bug: the read was supposed to fail") |
diff --git a/internal/edge/wildcard_serveonly_test.go b/internal/edge/wildcard_serveonly_test.go| index 2599cd77f..dfe418a69 100644 |
| --- a/internal/edge/wildcard_serveonly_test.go |
| +++ b/internal/edge/wildcard_serveonly_test.go |
| @@ -1,12 +1,10 @@ |
| package edge |
| import ( |
| - "bytes" |
| "context" |
| "crypto/tls" |
| "crypto/x509" |
| "errors" |
| - "log" |
| "net" |
| "net/http/httptest" |
| "strings" |
| @@ -121,10 +119,7 @@ func TestWildcardWithoutDNSNeverOrders(t *testing.T) { |
| w.directory = ca.URL |
| w.issuer = func() (context.Context, bool) { return context.Background(), held } |
| w.refresh() |
| - var logs bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&logs) |
| - defer log.SetOutput(old) |
| + logs := captureLog(t) |
| now := time.Now() |
| clock := func() time.Time { return now } |
| for i := 0; i < 3; i++ { |
diff --git a/internal/host/agent_test.go b/internal/host/agent_test.go| index 8860e504f..34b63905f 100644 |
| --- a/internal/host/agent_test.go |
| +++ b/internal/host/agent_test.go |
| @@ -815,9 +815,7 @@ func TestAdoptPassRefusesToStampAVersionAWrongUnitDidNotStart(t *testing.T) { |
| } |
| t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) |
| - var journal bytes.Buffer |
| - log.SetOutput(&journal) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + journal := captureLogBuffer(t) |
| restart := makeRestartRoute(reg, systemctlTryRestart, agentCheckedUnitRestart(systemdUnits{}, optDir, os.Getenv, nil), nil) |
| if err := release.Pass(ctx, reg, s, pub, optDir, restart); err != nil { |
| @@ -942,9 +940,7 @@ func TestAdoptPassStartsTheNamedUnitAgainAfterAFailedRestart(t *testing.T) { |
| } |
| t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) |
| - var journal bytes.Buffer |
| - log.SetOutput(&journal) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + captureLogBuffer(t) // keeps the pass's log out of the test output |
| if err := release.Pass(ctx, reg, s, pub, optDir, makeRestartRoute(reg, systemctlTryRestart, agentCheckedUnitRestart(systemdUnits{}, optDir, os.Getenv, nil), nil), |
| release.WithStartUnit(makeStartRoute(reg, systemctlStartUnit))); err != nil { |
diff --git a/internal/host/alertsink_page_test.go b/internal/host/alertsink_page_test.go| index 97f4fe123..6edcceaf0 100644 |
| --- a/internal/host/alertsink_page_test.go |
| +++ b/internal/host/alertsink_page_test.go |
| @@ -1,11 +1,9 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "encoding/json" |
| "errors" |
| - "log" |
| "strings" |
| "testing" |
| @@ -68,10 +66,7 @@ func TestPageOperatorUsesTheArmedSinks(t *testing.T) { |
| } |
| // No sinks: nil, and one line in the journal however often it is asked. |
| - var buf bytes.Buffer |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(prev) }) |
| + buf := captureLogBuffer(t) |
| armPaging(nil) |
| var none *alertSinks |
| for range 2 { |
diff --git a/internal/host/alertsink_test.go b/internal/host/alertsink_test.go| index 6f5571422..f586800d9 100644 |
| --- a/internal/host/alertsink_test.go |
| +++ b/internal/host/alertsink_test.go |
| @@ -1,11 +1,9 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "encoding/json" |
| "errors" |
| - "log" |
| "net" |
| "os" |
| "path/filepath" |
| @@ -445,10 +443,7 @@ func TestBoxDeliverLogsNoWebhookURL(t *testing.T) { |
| refused := "http://" + l.Addr().String() + "/services/T000/B000/" + secret |
| l.Close() |
| - var buf bytes.Buffer |
| - prev, flags := log.Writer(), log.Flags() |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) }) |
| + buf := captureLogBuffer(t) |
| counts := &alertCounters{} |
| s := newAlertSinks(refused, httpPostWebhook, "", nil, counts) |
diff --git a/internal/host/applessroute_test.go b/internal/host/applessroute_test.go| index 0e2721b51..cddeaa67e 100644 |
| --- a/internal/host/applessroute_test.go |
| +++ b/internal/host/applessroute_test.go |
| @@ -1,9 +1,7 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| - "log" |
| "net/http" |
| "net/http/httptest" |
| "path/filepath" |
| @@ -69,14 +67,10 @@ func (k *keyLog) all() []string { |
| // captureShipLog swaps the standard logger's output for the test and forgets |
| // which apps unshippable has reported, so its once-only line is observable. |
| -func captureShipLog(t *testing.T) *bytes.Buffer { |
| +func captureShipLog(t *testing.T) *lockedBuffer { |
| t.Helper() |
| unshippableSeen.Range(func(k, _ any) bool { unshippableSeen.Delete(k); return true }) |
| - var buf bytes.Buffer |
| - prev, flags := log.Writer(), log.Flags() |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) }) |
| - return &buf |
| + return captureLogBuffer(t) |
| } |
| // TestErrshipAppLessRouteWritesNothing is the dev-bucket regression end to |
diff --git a/internal/host/bootstrapfs_linux_test.go b/internal/host/bootstrapfs_linux_test.go| index 54bcb6a87..f32fc7f94 100644 |
| --- a/internal/host/bootstrapfs_linux_test.go |
| +++ b/internal/host/bootstrapfs_linux_test.go |
| @@ -3,9 +3,7 @@ |
| package host |
| import ( |
| - "bytes" |
| "errors" |
| - "log" |
| "net" |
| "os" |
| "path/filepath" |
| @@ -111,10 +109,7 @@ func TestBootstrapOwnershipWalkSkipsUnsafeEntries(t *testing.T) { |
| if err := os.WriteFile(plain, []byte("ordinary"), 0o640); err != nil { |
| t.Fatal(err) |
| } |
| - var logs bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&logs) |
| - defer log.SetOutput(old) |
| + logs := captureLogBuffer(t) |
| if err := bootstrapChownTree(dir, os.Getuid(), os.Getgid()); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/host/boxroles_test.go b/internal/host/boxroles_test.go| index 3a71dff6c..b47a90bb4 100644 |
| --- a/internal/host/boxroles_test.go |
| +++ b/internal/host/boxroles_test.go |
| @@ -1,7 +1,6 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "encoding/json" |
| "errors" |
| @@ -12,7 +11,6 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/status" |
| - "log" |
| "strings" |
| "testing" |
| "time" |
| @@ -536,10 +534,7 @@ func TestRoleBackstopJitter(t *testing.T) { |
| } |
| func TestRoleUnreadableLogThrottle(t *testing.T) { |
| - var out bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&out) |
| - t.Cleanup(func() { log.SetOutput(old) }) |
| + out := captureLogBuffer(t) |
| r, s, _, _, _ := roleReaderFixture(t) |
| s.fail = "control/box-roles/box.json" |
| now := time.Now() |
diff --git a/internal/host/caps_pass_test.go b/internal/host/caps_pass_test.go| index 73f7787df..526dd5cd4 100644 |
| --- a/internal/host/caps_pass_test.go |
| +++ b/internal/host/caps_pass_test.go |
| @@ -116,19 +116,6 @@ func readDropIns(t *testing.T, o caps.Ops, host string) (svc, sock string) { |
| return svc, sock |
| } |
| -// captureLog redirects the standard logger — where every advisory in this |
| -// package lands — for the duration of the returned func. |
| -func captureLog(t *testing.T) func() string { |
| - t.Helper() |
| - var buf bytes.Buffer |
| - old := log.Writer() |
| - flags := log.Flags() |
| - log.SetOutput(&buf) |
| - log.SetFlags(0) |
| - t.Cleanup(func() { log.SetOutput(old); log.SetFlags(flags) }) |
| - return buf.String |
| -} |
| - |
| // ---- capabilityPass -------------------------------------------------------- |
| // The pass converges from the staged manifest of the version that is LIVE, |
diff --git a/internal/host/claimservingretained_linux_test.go b/internal/host/claimservingretained_linux_test.go| index ccdc0d332..bff2b995f 100644 |
| --- a/internal/host/claimservingretained_linux_test.go |
| +++ b/internal/host/claimservingretained_linux_test.go |
| @@ -5,7 +5,6 @@ package host |
| import ( |
| "bytes" |
| "fmt" |
| - "log" |
| "os" |
| "testing" |
| @@ -37,10 +36,7 @@ func TestServingParkRetainedDoesNotBlockRetirement(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| - var report bytes.Buffer |
| - output := log.Writer() |
| - log.SetOutput(&report) |
| - defer log.SetOutput(output) |
| + report := captureLogBuffer(t) |
| for n := uint64(2); n <= 3; n++ { |
| body := fmt.Sprintf("tenant writes %d", n) |
| f.put("", body) |
diff --git a/internal/host/claimstop_transport_test.go b/internal/host/claimstop_transport_test.go| index fc99fc123..ab02d6ce3 100644 |
| --- a/internal/host/claimstop_transport_test.go |
| +++ b/internal/host/claimstop_transport_test.go |
| @@ -24,9 +24,11 @@ func TestClaimStopFullDuplexSocket(t *testing.T) { |
| server := instancectl.Server{PeerOK: func(net.Conn) error { return nil }, ClaimStop: handler} |
| done := make(chan error, 1) |
| go func() { done <- server.Serve(ctx, ln) }() |
| - ctx, timeout := context.WithTimeout(ctx, 5*time.Second) |
| + // Its own variable: reassigning ctx here raced with the server |
| + // goroutine reading it above. |
| + callCtx, timeout := context.WithTimeout(ctx, 5*time.Second) |
| defer timeout() |
| - got, err := collectClaimStop(ctx, "unused", req, c.Drainer, func(context.Context, string, string) (net.Conn, error) { return client, nil }) |
| + got, err := collectClaimStop(callCtx, "unused", req, c.Drainer, func(context.Context, string, string) (net.Conn, error) { return client, nil }) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/host/configguard_test.go b/internal/host/configguard_test.go| index 828003eaa..5807558c3 100644 |
| --- a/internal/host/configguard_test.go |
| +++ b/internal/host/configguard_test.go |
| @@ -1,7 +1,6 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "crypto/ecdh" |
| "crypto/rand" |
| @@ -9,7 +8,6 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| - "log" |
| "os" |
| "strings" |
| "sync" |
| @@ -144,15 +142,6 @@ func reasonOfGate(t *testing.T, err error) string { |
| return r.Reason |
| } |
| -func guardCaptureLog(t *testing.T) *bytes.Buffer { |
| - t.Helper() |
| - var buf bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(old) }) |
| - return &buf |
| -} |
| - |
| func TestNeedsConfigIsTheShapeTheActivatorSpawns(t *testing.T) { |
| cases := []struct { |
| name string |
| @@ -197,7 +186,7 @@ func TestGuardNoSealedConfigAdmitsKeylessBox(t *testing.T) { |
| func TestGuardKeylessBoxRefusesSealedInstanceAndPublishesIt(t *testing.T) { |
| e := newGuardEnv(t) |
| e.putConfig("bab", "shop", map[string]appconfig.Var{"DB": e.seal("pw")}) |
| - logs := guardCaptureLog(t) |
| + logs := captureLogBuffer(t) |
| g := e.guard("") |
| err := g.Gate(context.Background(), guardRoute("kpmg.example.com")) |
| @@ -293,7 +282,7 @@ func TestGuardLogsOncePerHostAndAgainWhenTheReasonChanges(t *testing.T) { |
| e := newGuardEnv(t) |
| e.putConfig("bab", "shop", map[string]appconfig.Var{"DB": e.seal("pw")}) |
| g := e.guard("") |
| - logs := guardCaptureLog(t) |
| + logs := captureLogBuffer(t) |
| ctx := context.Background() |
| for i := 0; i < 5; i++ { |
| @@ -469,7 +458,7 @@ func TestGuardBypassIsLoud(t *testing.T) { |
| } |
| g := newConfigGuard(env, noStore) |
| g.now = e.clock.now |
| - logs := guardCaptureLog(t) |
| + logs := captureLogBuffer(t) |
| if got := g.Status(); got != "bypassed (CARLOS_NO_SEALED_CONFIG)" { |
| t.Errorf("status = %q", got) |
| @@ -494,7 +483,7 @@ func TestGuardBypassIsLoud(t *testing.T) { |
| // The flag beside a real store is ignored, and says so, and is not |
| // reported as a bypass. |
| withStore := newConfigGuard(env, func(context.Context) (release.Store, error) { return e.store, nil }) |
| - logs2 := guardCaptureLog(t) |
| + logs2 := captureLogBuffer(t) |
| if got := withStore.Status(); got != "" { |
| t.Errorf("flag with a store reported %q", got) |
| } |
| @@ -505,7 +494,7 @@ func TestGuardBypassIsLoud(t *testing.T) { |
| // No flag: quiet, and nothing published. |
| plain := newConfigGuard(func(string) string { return "" }, noStore) |
| - logs3 := guardCaptureLog(t) |
| + logs3 := captureLogBuffer(t) |
| plain.Announce() |
| if plain.Status() != "" || logs3.Len() != 0 { |
| t.Errorf("a box without the flag said something: %q / %q", plain.Status(), logs3.String()) |
| @@ -573,7 +562,7 @@ func TestGuardPublishesNoSecretMaterial(t *testing.T) { |
| v := e.seal("hunter2") |
| e.putConfig("bab", "shop", map[string]appconfig.Var{"DB": v}) |
| g := e.guard(keyB64(e.other)) |
| - logs := guardCaptureLog(t) |
| + logs := captureLogBuffer(t) |
| _ = g.Gate(context.Background(), guardRoute("a.example.com")) |
| list, _ := g.Refusals() |
| raw, _ := json.Marshal(list) |
diff --git a/internal/host/converge_adopted_test.go b/internal/host/converge_adopted_test.go| index e2bdbc889..990e6925f 100644 |
| --- a/internal/host/converge_adopted_test.go |
| +++ b/internal/host/converge_adopted_test.go |
| @@ -1,9 +1,7 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| - "log" |
| "net/http" |
| "net/http/httptest" |
| "reflect" |
| @@ -431,11 +429,7 @@ func TestAdoptRestartDispatchSparesAConvergedChild(t *testing.T) { |
| // A leg past slowLegAfter says so in the journal, with what it was doing; a |
| // quick one says nothing, because the fast loop runs every two seconds. |
| func TestLogSlowSpeaksOnlyWhenSlow(t *testing.T) { |
| - var buf bytes.Buffer |
| - prev, flags := log.Writer(), log.Flags() |
| - log.SetOutput(&buf) |
| - log.SetFlags(0) |
| - t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) }) |
| + buf := captureLogBuffer(t) |
| logSlow("fast sweep", time.Now(), "3 routes") |
| if buf.Len() != 0 { |
diff --git a/internal/host/demo_policy_test.go b/internal/host/demo_policy_test.go| index 047c8ca24..4d84ba03c 100644 |
| --- a/internal/host/demo_policy_test.go |
| +++ b/internal/host/demo_policy_test.go |
| @@ -1,10 +1,8 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "errors" |
| - "log" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -245,10 +243,7 @@ func TestDemoPolicyConsoleTupleDoesNotConfigureBox(t *testing.T) { |
| } |
| func TestDemoPolicyRemovalWarningsRetry(t *testing.T) { |
| - var warnings bytes.Buffer |
| - oldWriter := log.Writer() |
| - log.SetOutput(&warnings) |
| - t.Cleanup(func() { log.SetOutput(oldWriter) }) |
| + warnings := captureLogBuffer(t) |
| for _, obstruction := range []string{"parent-file", "nonempty-drop-in-directory"} { |
| t.Run(obstruction, func(t *testing.T) { |
| dir := t.TempDir() |
| @@ -306,7 +301,7 @@ func TestDemoPolicyRemovalWarningsRetry(t *testing.T) { |
| t.Fatalf("absent drop-in: %v %v", changed, err) |
| } |
| if warnings.Len() != 0 { |
| - t.Errorf("successful/absent cleanup warned: %s", &warnings) |
| + t.Errorf("successful/absent cleanup warned: %s", warnings) |
| } |
| }) |
| } |
diff --git a/internal/host/demo_retirement_stream_test.go b/internal/host/demo_retirement_stream_test.go| index f63790daa..df57bb31b 100644 |
| --- a/internal/host/demo_retirement_stream_test.go |
| +++ b/internal/host/demo_retirement_stream_test.go |
| @@ -10,7 +10,6 @@ import ( |
| "github.com/carlosframework/platform/internal/activator" |
| "github.com/carlosframework/platform/internal/edge" |
| "github.com/carlosframework/platform/internal/provision" |
| - "log" |
| "net/http" |
| "net/http/httptest" |
| "path/filepath" |
| @@ -345,10 +344,7 @@ func TestDemoConnectClearsReadiness(t *testing.T) { |
| func TestDemoMovedFaultStillServesAndRetires(t *testing.T) { |
| for _, fault := range []string{"signature", "monotonic"} { |
| t.Run(fault, func(t *testing.T) { |
| - var logs bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&logs) |
| - defer log.SetOutput(old) |
| + logs := captureLogBuffer(t) |
| testDemoRetirementStream(t, true, false, false, fault) |
| if n := strings.Count(logs.String(), "agent: demo moved: "); n != 1 { |
| t.Fatalf("repeated fault across reconnect logged %d times, want 1", n) |
diff --git a/internal/host/edgesfile_test.go b/internal/host/edgesfile_test.go| index cf890e732..1aa3fce5b 100644 |
| --- a/internal/host/edgesfile_test.go |
| +++ b/internal/host/edgesfile_test.go |
| @@ -12,7 +12,6 @@ import ( |
| "go/ast" |
| "go/parser" |
| "go/token" |
| - "log" |
| "net/netip" |
| "os" |
| "path/filepath" |
| @@ -729,9 +728,7 @@ func TestEdgesFilePublishesPointingAliasesOfServedPrimaries(t *testing.T) { |
| } |
| return f.Hosts |
| } |
| - var buf strings.Builder |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + buf := captureLogBuffer(t) |
| hosts := publish() |
| h, ok := hosts["www.customer.com"] |
| if !ok || h.Role != "home" || !h.Alias || h.Platform { |
diff --git a/internal/host/fleetbind_test.go b/internal/host/fleetbind_test.go| index 612233067..a243e7c7d 100644 |
| --- a/internal/host/fleetbind_test.go |
| +++ b/internal/host/fleetbind_test.go |
| @@ -1,13 +1,11 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "crypto/sha256" |
| "encoding/hex" |
| "encoding/json" |
| "errors" |
| - "log" |
| "path/filepath" |
| "reflect" |
| "strings" |
| @@ -558,10 +556,7 @@ func (errPutStore) Put(ctx context.Context, key string, body []byte, ifMatch str |
| } |
| func TestFleetBindingHookLogsErrorWithoutPanicking(t *testing.T) { |
| - var buf bytes.Buffer |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - defer log.SetOutput(prev) |
| + buf := captureLogBuffer(t) |
| store := errPutStore{Store: release.NewDirStore(t.TempDir())} |
| hook := fleetBindingHook(store, "pi", "amber-gliding") |
diff --git a/internal/host/group_admission_fix_test.go b/internal/host/group_admission_fix_test.go| index d8e558d91..2701999f0 100644 |
| --- a/internal/host/group_admission_fix_test.go |
| +++ b/internal/host/group_admission_fix_test.go |
| @@ -1,10 +1,8 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "errors" |
| - "log" |
| "net/http" |
| "net/http/httptest" |
| "os" |
| @@ -254,10 +252,7 @@ func TestAdmissionAgentResponsePhase(t *testing.T) { |
| } |
| } |
| func TestAdmissionWaitingLogThrottled(t *testing.T) { |
| - var out bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&out) |
| - defer log.SetOutput(old) |
| + out := captureLogBuffer(t) |
| a := newFixedAdmission(admissionEnv, admissionHealth()) |
| a.tick(t.Context()) |
| a.tick(t.Context()) |
diff --git a/internal/host/group_hairpin_retry_test.go b/internal/host/group_hairpin_retry_test.go| index b41fffc1f..3c2e8f4a5 100644 |
| --- a/internal/host/group_hairpin_retry_test.go |
| +++ b/internal/host/group_hairpin_retry_test.go |
| @@ -2,13 +2,11 @@ package host |
| import ( |
| "bufio" |
| - "bytes" |
| "context" |
| "encoding/json" |
| "errors" |
| "fmt" |
| "io" |
| - "log" |
| "net" |
| "net/http" |
| "slices" |
| @@ -104,10 +102,7 @@ func assertHairpinWaiting(t *testing.T, a *fixedAdmission) { |
| func TestGroupHairpinAdmissionRetrySuccess(t *testing.T) { |
| f := newHairpinRetryFixture(t) |
| a := f.a |
| - var output bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&output) |
| - defer log.SetOutput(old) |
| + output := captureLogBuffer(t) |
| completions, attempts := 0, 0 |
| a.completer = groupCompleteFunc(func(context.Context, groupadmission.Launch) error { |
| completions++ |
| @@ -406,10 +401,7 @@ func TestGroupHairpinAdmissionWaitingAfterAdmit(t *testing.T) { |
| t.Fatal(err) |
| } |
| f.readers.Store(false) |
| - var output bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&output) |
| - defer log.SetOutput(old) |
| + output := captureLogBuffer(t) |
| for _, step := range []struct { |
| at time.Duration |
| logs int |
| @@ -437,10 +429,7 @@ func TestGroupHairpinAdmissionWaitingNamesRealGate(t *testing.T) { |
| a.hairpin = func(bool) error { return nil } |
| a.group = true |
| } |
| - var output bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&output) |
| - defer log.SetOutput(old) |
| + output := captureLogBuffer(t) |
| a.tick(t.Context()) |
| if strings.Contains(output.String(), "hosting") == group || strings.Contains(output.String(), "hairpin") != group { |
| t.Fatalf("wrong gate: %s", output.String()) |
diff --git a/internal/host/haplacement_wiring_test.go b/internal/host/haplacement_wiring_test.go| index 7fc96a197..8449081f5 100644 |
| --- a/internal/host/haplacement_wiring_test.go |
| +++ b/internal/host/haplacement_wiring_test.go |
| @@ -1,13 +1,11 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "encoding/json" |
| "errors" |
| "fmt" |
| "io" |
| - "log" |
| "net/http/httputil" |
| "net/url" |
| "os/exec" |
| @@ -118,10 +116,7 @@ func TestHAPlacementPageWiring(t *testing.T) { |
| // logged, as the raw-secret page is (wireRawSecretPages). It used to be |
| // dropped with _ =, so a region could run short with no trace anywhere. |
| func TestHAPlacementLogsAFailedPage(t *testing.T) { |
| - var buf bytes.Buffer |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(prev) }) |
| + buf := captureLogBuffer(t) |
| t.Cleanup(func() { setHAAwakeApps(nil) }) |
| svc := &activator.Service{} |
| armHAPlacement(svc, func(context.Context, string, string, string) error { |
diff --git a/internal/host/host_test.go b/internal/host/host_test.go| index 862d0617f..0a822952a 100644 |
| --- a/internal/host/host_test.go |
| +++ b/internal/host/host_test.go |
| @@ -1,14 +1,12 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "crypto/ed25519" |
| "encoding/base64" |
| "encoding/json" |
| "fmt" |
| "io" |
| - "log" |
| "net" |
| "os" |
| "os/exec" |
| @@ -956,9 +954,7 @@ func TestProvisionTickConfig(t *testing.T) { |
| // A key SET but unparseable must not be mistaken for a key that parsed. |
| // It lands on nil — the same unguarded end state domains.Config accepts |
| // for the same decision — and says so in the log rather than silently. |
| - var logged bytes.Buffer |
| - log.SetOutput(&logged) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + logged := captureLogBuffer(t) |
| got = provisionTickConfig(env(map[string]string{"CARLOS_RELEASE_PUBKEY": "not-a-key"})) |
| if got.ReleasePub != nil { |
| t.Error("ReleasePub set from an unparseable CARLOS_RELEASE_PUBKEY") |
| @@ -2073,12 +2069,17 @@ func TestBootstrapAppliesTmpfilesBeforeArming(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| + // Read while bootstrap writes: a pipe holds as little as one page when |
| + // its user is over the kernel's pipe-user-pages-soft limit (a busy |
| + // shared box), and a plan longer than that blocked the write forever. |
| + read := make(chan []byte, 1) |
| + go func() { b, _ := io.ReadAll(r); read <- b }() |
| stdout := os.Stdout |
| os.Stdout = w |
| berr := bootstrap(t.TempDir(), nil) |
| os.Stdout = stdout |
| w.Close() |
| - b, _ := io.ReadAll(r) |
| + b := <-read |
| if berr != nil { |
| t.Fatalf("bootstrap: %v", berr) |
| } |
diff --git a/internal/host/housekeeper_group_test.go b/internal/host/housekeeper_group_test.go| index 0d4dc6d5a..b568784ef 100644 |
| --- a/internal/host/housekeeper_group_test.go |
| +++ b/internal/host/housekeeper_group_test.go |
| @@ -99,7 +99,7 @@ func housekeeperDirEndpoint(t *testing.T) (*release.DirStore, *atomic.Int64) { |
| func TestHousekeeperGroupNeverWritesLease(t *testing.T) { |
| store, writes := housekeeperDirEndpoint(t) |
| t.Setenv("CARLOS_BOX_REFERENCE", "group") |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| hk := newHousekeeper(os.Getenv, acquireDeploymentLease) |
| old := theHousekeeper.Swap(hk) |
| t.Cleanup(func() { theHousekeeper.Store(old) }) |
diff --git a/internal/host/housekeeper_test.go b/internal/host/housekeeper_test.go| index 31d19e64f..59c097834 100644 |
| --- a/internal/host/housekeeper_test.go |
| +++ b/internal/host/housekeeper_test.go |
| @@ -28,37 +28,6 @@ import ( |
| // ---- helpers --------------------------------------------------------------- |
| -// lockedBuffer is an io.Writer safe for the election goroutine and the test |
| -// body to touch at once — log output is the assertion in the "stays quiet" |
| -// tests, so it has to be read while the loop is still running. |
| -type lockedBuffer struct { |
| - mu sync.Mutex |
| - b strings.Builder |
| -} |
| - |
| -func (l *lockedBuffer) Write(p []byte) (int, error) { |
| - l.mu.Lock() |
| - defer l.mu.Unlock() |
| - return l.b.Write(p) |
| -} |
| - |
| -func (l *lockedBuffer) String() string { |
| - l.mu.Lock() |
| - defer l.mu.Unlock() |
| - return l.b.String() |
| -} |
| - |
| -// captureRacyLog redirects the standard logger for one test, through a |
| -// mutexed buffer: unlike this package's other captureLog, the writer here is |
| -// shared with a live election goroutine. |
| -func captureRacyLog(t *testing.T) *lockedBuffer { |
| - t.Helper() |
| - buf := &lockedBuffer{} |
| - log.SetOutput(buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| - return buf |
| -} |
| - |
| // quietLog silences the standard logger for a test that doesn't assert on it. |
| func quietLog(t *testing.T) { |
| t.Helper() |
| @@ -195,7 +164,7 @@ func TestRunHousekeeperDutiesRunsEachDutyOncePerTickWhenHeld(t *testing.T) { |
| } |
| func TestRunHousekeeperDutiesSkipsQuietlyWhenNotHeld(t *testing.T) { |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| ran := 0 |
| runHousekeeperDuties(noGate, |
| housekeeperDuty{"retention pass", func(context.Context) error { ran++; return nil }}, |
| @@ -211,7 +180,7 @@ func TestRunHousekeeperDutiesSkipsQuietlyWhenNotHeld(t *testing.T) { |
| } |
| func TestRunHousekeeperDutiesLogsOneDutysErrorAndRunsTheRest(t *testing.T) { |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| later := 0 |
| runHousekeeperDuties(heldGate, |
| housekeeperDuty{"retention pass", func(context.Context) error { return errors.New("boom") }}, |
| @@ -306,7 +275,7 @@ func TestHousekeeperAcquiresTheDeploymentLeaseAndHolds(t *testing.T) { |
| } |
| func TestHousekeeperLosingTheElectionIsQuietAndKeepsTrying(t *testing.T) { |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| a := &acquirer{answer: func(int) (heldLease, error) { return nil, contended() }} |
| hk := fastHousekeeper(envFunc(map[string]string{"CARLOS_DEPLOYMENT_BUCKET": "dep-bucket"}), a) |
| // The arming line is not what this test is about; drop everything logged |
| @@ -328,7 +297,7 @@ func TestHousekeeperLosingTheElectionIsQuietAndKeepsTrying(t *testing.T) { |
| } |
| func TestHousekeeperLogsARealAcquireFailure(t *testing.T) { |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| a := &acquirer{answer: func(int) (heldLease, error) { return nil, errors.New("no credentials") }} |
| hk := fastHousekeeper(envFunc(map[string]string{"CARLOS_DEPLOYMENT_BUCKET": "dep-bucket"}), a) |
| runElection(t, hk) |
| @@ -482,7 +451,7 @@ func TestHousekeeperCancelsDutiesWhenTheHoldEnds(t *testing.T) { |
| // did not fail, so it must not be logged as a failure — and the duties behind |
| // it in the same tick are no longer this box's to run. |
| func TestRunHousekeeperDutiesStopQuietlyWhenTheHoldEndsMidTick(t *testing.T) { |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| ctx, cancel := context.WithCancel(context.Background()) |
| later := 0 |
| runHousekeeperDuties( |
| @@ -550,7 +519,7 @@ func TestMintMeshKeyLoopArmsWithoutReleasePubkey(t *testing.T) { |
| t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir()) |
| t.Setenv("CARLOS_RELEASE_PUBKEY", "") // deliberately unset — the whole point |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| // mintMeshKeyLoop never returns once armed: run it in its own goroutine |
| // (it parks in a time.Sleep for a minute, long past this test's end) and |
| // wait for the arming log line against a synchronized sink. |
diff --git a/internal/host/interactive_test.go b/internal/host/interactive_test.go| index 4b1042433..eb0504178 100644 |
| --- a/internal/host/interactive_test.go |
| +++ b/internal/host/interactive_test.go |
| @@ -19,7 +19,6 @@ import ( |
| "go/parser" |
| "go/token" |
| "io" |
| - "log" |
| "net/http" |
| "net/http/httptest" |
| "path/filepath" |
| @@ -613,20 +612,9 @@ func (wd *ixWorld) eventMsgs() []string { |
| return out |
| } |
| -// ixCaptureLog collects the package log for the test. |
| -func ixCaptureLog(t *testing.T) func() string { |
| - t.Helper() |
| - var mu sync.Mutex |
| - var buf bytes.Buffer |
| - prev := log.Writer() |
| - log.SetOutput(writerFunc(func(p []byte) (int, error) { mu.Lock(); defer mu.Unlock(); return buf.Write(p) })) |
| - t.Cleanup(func() { log.SetOutput(prev) }) |
| - return func() string { mu.Lock(); defer mu.Unlock(); return buf.String() } |
| -} |
| - |
| func TestInteractiveWorkerIgnoresAForgedGrant(t *testing.T) { |
| wd := newIxWorld(t) |
| - logs := ixCaptureLog(t) |
| + logs := captureLog(t) |
| _, other, err := ed25519.GenerateKey(rand.Reader) |
| if err != nil { |
| t.Fatal(err) |
| @@ -706,7 +694,7 @@ func TestInteractiveWorkerChecksTheIDBeforeTheGrantKey(t *testing.T) { |
| // again. |
| func TestInteractiveWorkerLogsADoorRefusalOnce(t *testing.T) { |
| wd := newIxWorld(t) |
| - logs := ixCaptureLog(t) |
| + logs := captureLog(t) |
| wd.door.refuse = http.StatusNotFound |
| rec, _ := wd.session() |
| wd.wait() |
| @@ -920,7 +908,7 @@ func TestInteractiveWorkerOnAnHARouteOnlyWhenItHoldsTheHost(t *testing.T) { |
| wd.w.routes = ixRoutes(ha) |
| var asked []string |
| wd.w.holds = func(h string) bool { asked = append(asked, h); return false } |
| - logs := ixCaptureLog(t) |
| + logs := captureLog(t) |
| rec := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| wd.grant(rec, nil, nil) |
| wd.store.reset() |
| @@ -1494,7 +1482,7 @@ func TestArmInteractivePassNeedsItsInputs(t *testing.T) { |
| {"a bad release key", svc, reg, "bm90IGEga2V5"}, |
| } { |
| t.Setenv("CARLOS_RELEASE_PUBKEY", c.key) |
| - logs := ixCaptureLog(t) |
| + logs := captureLog(t) |
| armInteractivePass(c.svc, c.reg, nil, nil) |
| if armedInteractive.Load() != nil || strings.Count(logs(), "agent: interactive sessions disabled: ") != 1 { |
| t.Fatalf("%s: armed %v, log:\n%s", c.name, armedInteractive.Load() != nil, logs()) |
| @@ -1719,7 +1707,7 @@ func TestARestartedWorkerCannotRelaunchAnEndedSession(t *testing.T) { |
| // Worker B, as after an agent restart: nothing seen. Its grant is valid |
| // and before its pickup, but the door has ended the session. |
| - logs := ixCaptureLog(t) |
| + logs := captureLog(t) |
| launchB := &ixLaunch{handle: newIxHandle(newIxTerm())} |
| b := newInteractiveWorker(&grantStore{Store: c.store, key: key, wire: wire}, ixRoutes(ixRoute(ixHost)), launchB, c.pub, "box-a") |
| var dials atomic.Int32 |
| @@ -1943,7 +1931,7 @@ func TestInteractiveWorkerLaunchErrorWaitsForTheSettlement(t *testing.T) { |
| return wd, rec, later |
| } |
| t.Run("the proof comes later", func(t *testing.T) { |
| - logs := ixCaptureLog(t) |
| + logs := captureLog(t) |
| wd, rec, later := launchFails(t) |
| time.Sleep(200 * time.Millisecond) |
| for drained := false; !drained; { |
diff --git a/internal/host/logcapture_test.go b/internal/host/logcapture_test.go| new file mode 100644 |
| index 000000000..ea5074619 |
| --- /dev/null |
| +++ b/internal/host/logcapture_test.go |
| @@ -0,0 +1,71 @@ |
| +package host |
| + |
| +import ( |
| + "log" |
| + "strings" |
| + "sync" |
| + "testing" |
| +) |
| + |
| +// This package's one log capture. Every advisory here lands on the standard |
| +// logger, and many of the tests that read it have a loop, a pass or an |
| +// election goroutine still logging while they do; a goroutine an earlier |
| +// test left behind can log into any test's capture. So the buffer is always |
| +// locked: a plain bytes.Buffer or strings.Builder handed to log.SetOutput is |
| +// a data race that `make race` reports. |
| + |
| +// lockedBuffer is a strings.Builder behind a lock, for a log a test reads |
| +// while something may still write to it. |
| +type lockedBuffer struct { |
| + mu sync.Mutex |
| + b strings.Builder |
| +} |
| + |
| +func (l *lockedBuffer) Write(p []byte) (int, error) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return l.b.Write(p) |
| +} |
| + |
| +func (l *lockedBuffer) String() string { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return l.b.String() |
| +} |
| + |
| +func (l *lockedBuffer) Len() int { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return l.b.Len() |
| +} |
| + |
| +func (l *lockedBuffer) Reset() { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + l.b.Reset() |
| +} |
| + |
| +// Bytes is a copy of what has been logged so far. |
| +func (l *lockedBuffer) Bytes() []byte { return []byte(l.String()) } |
| + |
| +// count is how many times s was logged. |
| +func (l *lockedBuffer) count(s string) int { return strings.Count(l.String(), s) } |
| + |
| +// captureLogBuffer sends the standard logger to a locked buffer, with no |
| +// timestamp prefix, until the test ends. |
| +func captureLogBuffer(t *testing.T) *lockedBuffer { |
| + t.Helper() |
| + buf := &lockedBuffer{} |
| + out, flags := log.Writer(), log.Flags() |
| + log.SetOutput(buf) |
| + log.SetFlags(0) |
| + t.Cleanup(func() { log.SetOutput(out); log.SetFlags(flags) }) |
| + return buf |
| +} |
| + |
| +// captureLog is captureLogBuffer for a test that only reads the whole log: |
| +// it returns what has been logged so far. |
| +func captureLog(t *testing.T) func() string { |
| + t.Helper() |
| + return captureLogBuffer(t).String |
| +} |
diff --git a/internal/host/metrics_loop_test.go b/internal/host/metrics_loop_test.go| index 66ec8f166..a8e88d340 100644 |
| --- a/internal/host/metrics_loop_test.go |
| +++ b/internal/host/metrics_loop_test.go |
| @@ -1,11 +1,9 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "encoding/json" |
| "errors" |
| - "log" |
| "math" |
| "os" |
| "path/filepath" |
| @@ -854,10 +852,7 @@ func TestLogRejectedAlertOverrides(t *testing.T) { |
| "CARLOS_ALERT_MEM_PCT": "85", // accepted |
| // CARLOS_ALERT_CPU_PCT unset |
| } |
| - var buf bytes.Buffer |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - defer log.SetOutput(prev) |
| + buf := captureLogBuffer(t) |
| logRejectedAlertOverrides(func(k string) string { return env[k] }) |
| @@ -900,10 +895,7 @@ func TestMetricsBoxLabelUsesFleetIdentity(t *testing.T) { |
| }) |
| t.Run("invalid fleet identity degrades to the hashed pseudonym and warns", func(t *testing.T) { |
| - var buf bytes.Buffer |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - defer log.SetOutput(prev) |
| + buf := captureLogBuffer(t) |
| got := metricsBoxLabel(envFunc(map[string]string{ |
| "CARLOS_FLEET": "pi", |
diff --git a/internal/host/movesheldrelease_linux_test.go b/internal/host/movesheldrelease_linux_test.go| index 292891856..34866dd0e 100644 |
| --- a/internal/host/movesheldrelease_linux_test.go |
| +++ b/internal/host/movesheldrelease_linux_test.go |
| @@ -6,7 +6,6 @@ import ( |
| "bytes" |
| "context" |
| "errors" |
| - "log" |
| "net" |
| "net/http" |
| "os" |
| @@ -232,10 +231,7 @@ func TestHeldReleaseRootLogsOnlyValidatedFields(t *testing.T) { |
| ctx := context.Background() |
| f := newHRFixture(t) |
| f.root.Authenticate = func(context.Context, net.Conn) (StopPeer, error) { return hrPeer, nil } |
| - var logs syncBuffer |
| - prev := log.Writer() |
| - log.SetOutput(&logs) |
| - t.Cleanup(func() { log.SetOutput(prev) }) |
| + logs := captureLogBuffer(t) |
| client := newHeldReleaseRootClient(serveClaimRootWithHeldRelease(t, ClaimRootWithLaunch{HeldRelease: f.root})) |
| forged := f.request(heldReleasePublish) |
diff --git a/internal/host/movespass_lost_test.go b/internal/host/movespass_lost_test.go| index 9efcfb1e9..e27becd37 100644 |
| --- a/internal/host/movespass_lost_test.go |
| +++ b/internal/host/movespass_lost_test.go |
| @@ -1,9 +1,7 @@ |
| package host |
| import ( |
| - "log" |
| "reflect" |
| - "strings" |
| "testing" |
| "github.com/carlosframework/platform/internal/hostclaim" |
| @@ -12,20 +10,6 @@ import ( |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| -// count is how many times s was logged (housekeeper_test.go's buffer). |
| -func (l *lockedBuffer) count(s string) int { return strings.Count(l.String(), s) } |
| - |
| -// lostLog sends the log to a buffer for the rest of the test; a pass may |
| -// log from goroutines, so the buffer is housekeeper_test.go's locked one. |
| -func lostLog(t *testing.T) *lockedBuffer { |
| - t.Helper() |
| - buf := &lockedBuffer{} |
| - out, flags := log.Writer(), log.Flags() |
| - log.SetOutput(buf) |
| - t.Cleanup(func() { log.SetOutput(out); log.SetFlags(flags) }) |
| - return buf |
| -} |
| - |
| // rcLose lists box in the host claim's Lost, as a declaration leaves it. |
| func rcLose(t *testing.T, h *phase1Harness, box string) { |
| t.Helper() |
| @@ -54,7 +38,7 @@ func TestReturningLostBoxRefusesEveryMoveStep(t *testing.T) { |
| } |
| t.Run("the source before the flip", func(t *testing.T) { |
| skipParkedSecretSubtests(t, "its flow carries <host>.env and stops at one of the parked refusals", "the_source's_recovery") |
| - buf := lostLog(t) |
| + buf := captureLogBuffer(t) |
| h := newPhase1Harness(t) |
| h.start(t, "auto") |
| rcLose(t, h, "ie-box") |
| @@ -80,7 +64,7 @@ func TestReturningLostBoxRefusesEveryMoveStep(t *testing.T) { |
| }) |
| t.Run("the target before the flip", func(t *testing.T) { |
| skipParkedSecretSubtests(t, "its flow carries <host>.env and stops at one of the parked refusals", "the_source's_recovery") |
| - lostLog(t) |
| + captureLogBuffer(t) |
| h := newPhase1Harness(t) |
| h.start(t, "auto") |
| h.pass(t) |
| @@ -96,7 +80,7 @@ func TestReturningLostBoxRefusesEveryMoveStep(t *testing.T) { |
| }) |
| t.Run("the source's recovery", func(t *testing.T) { |
| skipParkedSecretSubtests(t, "its flow carries <host>.env and stops at one of the parked refusals", "the_source's_recovery") |
| - buf := lostLog(t) |
| + buf := captureLogBuffer(t) |
| h := newRecoverHarness(t, false) |
| h.released(t) |
| rewriteP1Claim(t, h.s, func(c *hostclaim.Claim) { |
| @@ -135,7 +119,7 @@ func rcCorruptClaim(t *testing.T, s release.Store) { |
| // report and no journal sweep: nothing is reported, committed or retired. |
| func TestLostBoxGateCoversTheWholePass(t *testing.T) { |
| t.Run("an unreadable claim blocks the target's report", func(t *testing.T) { |
| - buf := lostLog(t) |
| + buf := captureLogBuffer(t) |
| h := newPhase1Harness(t) |
| h.start(t, "auto") |
| h.pass(t) |
| @@ -157,7 +141,7 @@ func TestLostBoxGateCoversTheWholePass(t *testing.T) { |
| "an unreadable claim": func(t *testing.T, h *revertHarness) { rcCorruptClaim(t, h.s) }, |
| } { |
| t.Run(name+" blocks the journal sweep", func(t *testing.T) { |
| - lostLog(t) |
| + captureLogBuffer(t) |
| h := newRevertHarness(t) |
| h.fromStopped(t) |
| h.arm(t) |
diff --git a/internal/host/offcloudcredentials_linux_test.go b/internal/host/offcloudcredentials_linux_test.go| index fafedfedb..33adcc967 100644 |
| --- a/internal/host/offcloudcredentials_linux_test.go |
| +++ b/internal/host/offcloudcredentials_linux_test.go |
| @@ -4,7 +4,6 @@ package host |
| import ( |
| "bytes" |
| - "log" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -158,10 +157,7 @@ func TestOffcloudCredentialsInvalidContentsNotRepaired(t *testing.T) { |
| t.Fatal(err) |
| } |
| defer f.Close() |
| - var logs bytes.Buffer |
| - previous := log.Writer() |
| - log.SetOutput(&logs) |
| - defer log.SetOutput(previous) |
| + logs := captureLogBuffer(t) |
| if err := secureOffcloudCredentials(f, os.Getegid()); err == nil { |
| t.Fatal("accepted invalid credentials") |
| } |
| @@ -209,10 +205,7 @@ func TestOffcloudCredentialsRefuseLinksAndSpecials(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - var logs bytes.Buffer |
| - previous := log.Writer() |
| - log.SetOutput(&logs) |
| - defer log.SetOutput(previous) |
| + logs := captureLogBuffer(t) |
| if err := repairOffcloudCredentials(path); err == nil { |
| t.Fatal("accepted unsafe credentials") |
| } |
diff --git a/internal/host/plan14_fix3_live_linux_test.go b/internal/host/plan14_fix3_live_linux_test.go| index fd34983a3..e6592c2ee 100644 |
| --- a/internal/host/plan14_fix3_live_linux_test.go |
| +++ b/internal/host/plan14_fix3_live_linux_test.go |
| @@ -1,12 +1,10 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "crypto/ed25519" |
| "encoding/json" |
| "errors" |
| - "log" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -166,10 +164,7 @@ func TestR2UnguardedConsoleUpdate(t *testing.T) { |
| for _, kind := range []string{"none", "list"} { |
| t.Run(kind, func(t *testing.T) { |
| f := r2Fixture(t, kind) |
| - var logged bytes.Buffer |
| - previousLog := log.Writer() |
| - log.SetOutput(&logged) |
| - defer log.SetOutput(previousLog) |
| + logged := captureLogBuffer(t) |
| if err := f.pass(t); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/host/plan9fix4_claimjournal_migration_linux_test.go b/internal/host/plan9fix4_claimjournal_migration_linux_test.go| index f605c7223..9f75b4f66 100644 |
| --- a/internal/host/plan9fix4_claimjournal_migration_linux_test.go |
| +++ b/internal/host/plan9fix4_claimjournal_migration_linux_test.go |
| @@ -6,7 +6,6 @@ import ( |
| "bytes" |
| "context" |
| "crypto/ed25519" |
| - "log" |
| "os" |
| "path/filepath" |
| "slices" |
| @@ -137,10 +136,7 @@ func TestPlan9Fix4RootAssemblyIgnoresReplacedLegacyDirectory(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - var logs bytes.Buffer |
| - previous := log.Writer() |
| - log.SetOutput(&logs) |
| - defer log.SetOutput(previous) |
| + logs := captureLogBuffer(t) |
| assembly, err := OpenProductionClaimAssembly(t.Context(), store, resources, owners) |
| if err != nil { |
| t.Fatalf("agent-controlled legacy directory prevented root startup: %v", err) |
diff --git a/internal/host/rawbaseline_linux_test.go b/internal/host/rawbaseline_linux_test.go| index d8ec94138..85246f8af 100644 |
| --- a/internal/host/rawbaseline_linux_test.go |
| +++ b/internal/host/rawbaseline_linux_test.go |
| @@ -6,7 +6,6 @@ import ( |
| "bytes" |
| "context" |
| "errors" |
| - "log" |
| "path/filepath" |
| "strings" |
| "testing" |
| @@ -28,15 +27,6 @@ func (s *baselinePUTStore) Put(ctx context.Context, key string, body []byte, mat |
| return s.Store.Put(ctx, key, body, match) |
| } |
| -func baselineLog(t *testing.T) *bytes.Buffer { |
| - t.Helper() |
| - var out bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&out) |
| - t.Cleanup(func() { log.SetOutput(old) }) |
| - return &out |
| -} |
| - |
| func TestEstablishRefusesRawSecretBaselineBeforeAnyPUT(t *testing.T) { |
| for _, name := range []string{"instance.key", "report.token", hostfiles.EnvItem, "tenant.txt"} { |
| t.Run(name, func(t *testing.T) { |
| @@ -60,7 +50,7 @@ func TestEstablishRefusesRawSecretBaselineBeforeAnyPUT(t *testing.T) { |
| o := x.observe(servingObserved("g2", "g1:uk:@root:uk", "g2:uk:g1:uk"), "g1", "g2") |
| store := &baselinePUTStore{Store: x.files} |
| x.f.Files = store |
| - out := baselineLog(t) |
| + out := captureLogBuffer(t) |
| err = x.f.Establish(t.Context(), o, launchInputs("g2"), x) |
| if name == "tenant.txt" { |
| if err != nil || store.puts == 0 { |
| @@ -126,7 +116,7 @@ func TestReleaseFlushRefusesRawSecretBaselineBeforeAnyPUT(t *testing.T) { |
| mkTree(t, dir, map[string]string{"tenant.txt": "current"}) |
| flush := ReleaseFlushFiles{Data: store, Registry: reg, FilesDir: func(string) string { return dir }, EnvPath: func(string) string { return filepath.Join(envDir, host+".env") }} |
| obs := hostclaim.Observed{Host: host, Claim: &hostclaim.Claim{Host: host, Holder: &hostclaim.Holder{Location: "instances/" + host + "/inc", Generation: "g6"}}} |
| - out := baselineLog(t) |
| + out := captureLogBuffer(t) |
| _, err = flush.Flush(t.Context(), obs) |
| if name == "tenant.txt" { |
| if err != nil || store.puts == 0 { |
| @@ -157,7 +147,7 @@ func TestPreparedEstablishRefusesRawSecretBaselineBeforeAnyPUT(t *testing.T) { |
| x, pm, obs, in := preparedFixture(t, name) |
| store := &baselinePUTStore{Store: x.files} |
| x.f.Files = store |
| - out := baselineLog(t) |
| + out := captureLogBuffer(t) |
| err := x.f.Establish(t.Context(), obs, in, x) |
| if !errors.Is(err, pubclass.ErrSecretPath) { |
| t.Errorf("raw prepared baseline admitted: %v", err) |
diff --git a/internal/host/region_ha_g2_isolation_test.go b/internal/host/region_ha_g2_isolation_test.go| index 6e5461642..f30d49ca0 100644 |
| --- a/internal/host/region_ha_g2_isolation_test.go |
| +++ b/internal/host/region_ha_g2_isolation_test.go |
| @@ -4,11 +4,9 @@ package host |
| import ( |
| "bufio" |
| - "bytes" |
| "context" |
| "encoding/json" |
| "fmt" |
| - "log" |
| "net" |
| "net/http" |
| "os" |
| @@ -28,10 +26,7 @@ func TestG2PoolIsolationProductionVerdict(t *testing.T) { |
| previousBuild := layoutBuild |
| layoutBuild = func() string { return "v0.34.7" } |
| t.Cleanup(func() { layoutBuild = previousBuild }) |
| - var output bytes.Buffer |
| - previousWriter := log.Writer() |
| - log.SetOutput(&output) |
| - t.Cleanup(func() { log.SetOutput(previousWriter) }) |
| + output := captureLogBuffer(t) |
| store := release.NewDirStore(t.TempDir()) |
| const invocation = "0123456789abcdef0123456789abcdef" |
| for _, ready := range []bool{false, true, false} { |
diff --git a/internal/host/relocatepass_absence_test.go b/internal/host/relocatepass_absence_test.go| index 565ab59c7..a1f0eb26f 100644 |
| --- a/internal/host/relocatepass_absence_test.go |
| +++ b/internal/host/relocatepass_absence_test.go |
| @@ -39,7 +39,7 @@ func TestRelocatePassSaysAClaimItCannotRead(t *testing.T) { |
| passClaim(t, dir, "b.example", relocatingOp("rel-b")) |
| key, _ := hostclaim.Key("b.example") |
| store := unreadableClaim{Store: dir, key: key} |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| var order []string |
| r := &RelocationRuntime{Worker: stepRecorder{name: "worker", order: &order}, Participant: stepRecorder{name: "participant", order: &order}, Box: "dst"} |
| r.once(ctx, store) |
| @@ -70,7 +70,7 @@ func TestRelocationPassBuildsTheFullPassOnceItCan(t *testing.T) { |
| local := &productionClaimLocal{legacyParticipation: true, assembly: &ClaimAssembly{Claims: store, Guard: hostguard.Guard{DataDir: t.TempDir()}, stopLocal: func(context.Context) (claimStopLocal, error) { |
| return claimStopLocal{Actor: hostbox.Actor{Box: "dst"}}, nil |
| }}} |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| var order []string |
| builds := 0 |
| unreadable := errors.New("the roster could not be read") |
| @@ -129,7 +129,7 @@ func TestRelocationPassBuildsTheFullPassOnceItCan(t *testing.T) { |
| // Claim mode is on, so a completion recorded here must be finished here: |
| // the agent never leaves the completion pass unstarted without saying so. |
| func TestStartRelocationPassSaysWhyItDidNotStart(t *testing.T) { |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| claimCtx := context.WithValue(t.Context(), claimEntryKey{}, claimEntry{Enabled: true, FlagRead: true}) |
| startRelocationPass(t.Context(), claimCtx, &ClaimWiring{}, nil, &activator.Service{}) |
| if !strings.Contains(buf.String(), "relocation completion pass not started") { |
diff --git a/internal/host/relocatepass_carries_test.go b/internal/host/relocatepass_carries_test.go| index c54762ecb..7324e91b6 100644 |
| --- a/internal/host/relocatepass_carries_test.go |
| +++ b/internal/host/relocatepass_carries_test.go |
| @@ -75,7 +75,7 @@ func TestCompletionPassFinishesOnlyWhatServesOnThisBox(t *testing.T) { |
| } |
| // No answer to "which box is this": nothing is finished. |
| f.calls = nil |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| r = &RelocationRuntime{Finish: f.finish, Hosts: hosts, Self: func(context.Context) (string, error) { return "", errors.New("no verified identity") }} |
| r.once(ctx, store) |
| if len(f.calls) != 0 || !strings.Contains(buf.String(), "no verified identity") { |
| @@ -93,7 +93,7 @@ func TestCompletionPassRetriesARefusedFinishAndAChangedClaim(t *testing.T) { |
| store := release.NewDirStore(t.TempDir()) |
| passClaim(t, store, "a.example", hostclaim.Op{}) |
| completeOn(t, store, "a.example", "rel-a", "dst", false) |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| f := &finishRecorder{err: hostbox.ErrChanged} |
| r := &RelocationRuntime{Finish: f.finish, Box: "dst"} |
| r.once(ctx, store) |
| @@ -128,7 +128,7 @@ func TestCompletionPassAlertsAnUnreadableRecord(t *testing.T) { |
| }); err != nil { |
| t.Fatal(err) |
| } |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| f := &finishRecorder{} |
| r := &RelocationRuntime{Finish: f.finish, Box: "dst"} |
| r.once(ctx, store) |
diff --git a/internal/host/relocatepass_round1_test.go b/internal/host/relocatepass_round1_test.go| index c7e0e6041..d399f2378 100644 |
| --- a/internal/host/relocatepass_round1_test.go |
| +++ b/internal/host/relocatepass_round1_test.go |
| @@ -139,7 +139,7 @@ func TestCompletionPassReadsTheHostsItsJournalsName(t *testing.T) { |
| if len(hosts) != 2 || hosts[0] != "row.example" || hosts[1] != "rowless.example" || err == nil { |
| t.Fatalf("hosts %v, err %v: want the row, the journal's host and the unreadable journal", hosts, err) |
| } |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| f := &finishRecorder{} |
| r.Finish = f.finish |
| r.once(ctx, store) |
| @@ -161,7 +161,7 @@ func TestRelocatePassAlertsPerStepAndForgetsClearedCauses(t *testing.T) { |
| r := &RelocationRuntime{Worker: stepRecorder{name: "worker", order: &order, err: same}, Participant: participant, Box: "dst"} |
| listed := []string{"a.example"} |
| r.Hosts = func() ([]string, error) { return listed, nil } |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| r.once(ctx, store) |
| r.once(ctx, store) |
| if strings.Count(buf.String(), "relocate a.example: participant: "+same.Error()) != 1 || strings.Count(buf.String(), "relocate a.example: worker: "+same.Error()) != 1 { |
| @@ -279,7 +279,7 @@ func TestLaunchRelocationPassReadsNothingTheLoopOwns(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| ctx, cancel := context.WithCancel(t.Context()) |
| done := launchRelocationPass(ctx, r, store, true) |
| <-stepped |
diff --git a/internal/host/relocatepass_test.go b/internal/host/relocatepass_test.go| index 62b81816b..0af1ffbf8 100644 |
| --- a/internal/host/relocatepass_test.go |
| +++ b/internal/host/relocatepass_test.go |
| @@ -228,7 +228,7 @@ func TestRelocatePassAlertsOnceWhileAConversionWaitsForATarget(t *testing.T) { |
| ctx := t.Context() |
| store := release.NewDirStore(t.TempDir()) |
| passClaim(t, store, "a.example", relocatingOp("rel-a")) |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| var order []string |
| none := errors.New("no eligible box for the converted landing") |
| r := &RelocationRuntime{Worker: stepRecorder{name: "worker", order: &order, err: none}, Participant: stepRecorder{name: "participant", order: &order, err: hostrelocate.ErrNotYet}, Box: "dst"} |
diff --git a/internal/host/relocationfinish_unix_test.go b/internal/host/relocationfinish_unix_test.go| index ad651b0dc..4f913f667 100644 |
| --- a/internal/host/relocationfinish_unix_test.go |
| +++ b/internal/host/relocationfinish_unix_test.go |
| @@ -259,7 +259,7 @@ func TestRelocatePassRetriesAMissingProbeFenceOwner(t *testing.T) { |
| if err := os.Remove(marker); err != nil { |
| t.Fatal(err) |
| } |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| w.pass() |
| w.pass() |
| if ok, barrier := w.marked(); ok || !w.held() || w.discharged != 0 || w.act.svc.FenceGeneration(finishHost) != 12 || !errors.Is(barrier, hostclaim.ErrPendingChore) { |
| @@ -299,7 +299,7 @@ func TestCompletionPassSaysACompletionWhoseRowIsGone(t *testing.T) { |
| t.Fatal(err) |
| } |
| w.runtime = r |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| w.pass() |
| w.pass() |
| if n := strings.Count(buf.String(), "has no row on this box"); n != 1 { |
diff --git a/internal/host/relocationsweep_test.go b/internal/host/relocationsweep_test.go| index 83e4f14e4..d1bba789d 100644 |
| --- a/internal/host/relocationsweep_test.go |
| +++ b/internal/host/relocationsweep_test.go |
| @@ -3,7 +3,6 @@ package host |
| import ( |
| "encoding/json" |
| "errors" |
| - "log" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -247,9 +246,7 @@ func TestRelocationSweepRemovesLeftoversAndLogsAStrayOnce(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| - var logged strings.Builder |
| - log.SetOutput(&logged) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + logged := captureLogBuffer(t) |
| for pass := 0; pass < 2; pass++ { |
| if err := sweepRelocationJournals(t.Context(), data, store); err != nil { |
| t.Fatalf("pass %d: %v", pass, err) |
diff --git a/internal/host/replicacoordinator_test.go b/internal/host/replicacoordinator_test.go| index 41c212e8f..b3d396ec9 100644 |
| --- a/internal/host/replicacoordinator_test.go |
| +++ b/internal/host/replicacoordinator_test.go |
| @@ -1,13 +1,11 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "crypto/sha256" |
| "encoding/hex" |
| "encoding/json" |
| "errors" |
| - "log" |
| "net/http" |
| "net/http/httptest" |
| "path/filepath" |
| @@ -603,10 +601,7 @@ func TestCoordinatorAPIConsoleUnreachable(t *testing.T) { |
| } |
| func TestCoordinatorAPIReachabilityLogsTransitions(t *testing.T) { |
| - var buf bytes.Buffer |
| - old := log.Writer() |
| - log.SetOutput(&buf) |
| - defer log.SetOutput(old) |
| + buf := captureLogBuffer(t) |
| api := &replicaCoordinatorAPI{} |
| id := replicas.Identity{Host: "shop.example.com"} |
| for _, err := range []error{nil, replicas.ErrConsoleUnreachable, replicas.ErrConsoleUnreachable, nil, nil, replicas.ErrConsoleUnreachable} { |
diff --git a/internal/host/replicahomekeys_test.go b/internal/host/replicahomekeys_test.go| index c719b92e9..68873fa21 100644 |
| --- a/internal/host/replicahomekeys_test.go |
| +++ b/internal/host/replicahomekeys_test.go |
| @@ -1,10 +1,8 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "errors" |
| - "log" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -61,9 +59,7 @@ func TestReplicaHomeKeysReadsTheListAtEveryLaunch(t *testing.T) { |
| // otherwise reach the log), and verifies nothing. |
| func TestReplicaHomeKeysLogsAMalformedListWithoutItsText(t *testing.T) { |
| sha := instancekey.Digest("home-key") |
| - var buf bytes.Buffer |
| - log.SetOutput(&buf) |
| - defer log.SetOutput(os.Stderr) |
| + buf := captureLogBuffer(t) |
| keys := replicaHomeKeys(func() ([]byte, error) { return []byte("shop-au.example.com=" + sha + "\n" + sha + "\n"), nil }) |
| if _, ok := keys("shop-au.example.com"); ok { |
| t.Fatal("a malformed list verified a key") |
diff --git a/internal/host/restartscope_test.go b/internal/host/restartscope_test.go| index 19dedcc86..86f6e3f72 100644 |
| --- a/internal/host/restartscope_test.go |
| +++ b/internal/host/restartscope_test.go |
| @@ -6,13 +6,11 @@ package host |
| // the narrowing, and that a selector this build cannot read cycles NOTHING. |
| import ( |
| - "bytes" |
| "context" |
| "crypto/ed25519" |
| "encoding/json" |
| "errors" |
| "fmt" |
| - "log" |
| "os" |
| "path/filepath" |
| "slices" |
| @@ -718,9 +716,7 @@ func TestRestartLegDropsARetryThatIsNotTheRootsGrant(t *testing.T) { |
| forShop, _ := release.SignHostRetry(release.RootSigner(priv), "bab", "shop", "a.example.com", "v2", "bk", 5, time.Now()) |
| askSignedRetry(t, ctx, s, "bab", "eleven", "a.example.com", forShop) |
| - var logbuf bytes.Buffer |
| - log.SetOutput(&logbuf) |
| - defer log.SetOutput(os.Stderr) |
| + logbuf := captureLogBuffer(t) |
| restartRequestLeg(ctx, routes, s, dd, bounce, nil, mem) |
| if n := strings.Count(logbuf.String(), "agent: retry requested for a.example.com, dropped:"); n != 4 { |
| t.Fatalf("log = %q, want four dropped retries", logbuf.String()) |
| @@ -830,9 +826,7 @@ func TestRestartLegDropsARetryWithNoManager(t *testing.T) { |
| restartRequestLeg(ctx, routes, s, dd, bounce, nil, mem) |
| legacyRetry(t, ctx, s, "bab", "eleven", "a.example.com", "") |
| - var logbuf bytes.Buffer |
| - log.SetOutput(&logbuf) |
| - defer log.SetOutput(os.Stderr) |
| + logbuf := captureLogBuffer(t) |
| if asked := restartRequestLeg(ctx, routes, s, dd, bounce, nil, mem); asked { |
| t.Fatal("a retry with no manager asked for a root pass") |
| } |
| @@ -863,9 +857,7 @@ func TestRestartLegSaysNothingOfAHistoricRetryOnABoxWithNoManager(t *testing.T) |
| restartRequestLeg(ctx, one, s, dd, bounce, nil, mem) // baseline: carloku is not here yet |
| legacyRetry(t, ctx, s, "bab", "carloku", "c.example.com", "") |
| - var logbuf bytes.Buffer |
| - log.SetOutput(&logbuf) |
| - defer log.SetOutput(os.Stderr) |
| + logbuf := captureLogBuffer(t) |
| if asked := restartRequestLeg(ctx, both, s, dd, bounce, nil, mem); asked { |
| t.Fatal("a historic retry asked for a root pass") |
| } |
| @@ -878,9 +870,7 @@ func TestRestartLegSaysNothingOfAHistoricRetryOnABoxWithNoManager(t *testing.T) |
| // must never address one for it, on the agent's half or the root pass's. |
| func TestScopedHostsAndRootPassStepOverARetry(t *testing.T) { |
| routes := titogoRoutes() |
| - var logbuf bytes.Buffer |
| - log.SetOutput(&logbuf) |
| - defer log.SetOutput(os.Stderr) |
| + logbuf := captureLogBuffer(t) |
| got := scopedHosts(routes, [2]string{"bab", "titogo"}, []release.RestartRequest{ |
| {ID: "1", Scope: release.RestartScope{Kind: release.RestartScopeRetry, Value: "bill.example.com"}}, |
| }, func(registry.Route) bool { return true }) |
| @@ -934,9 +924,7 @@ func TestRestartLegLogsARetryWithNothingHeld(t *testing.T) { |
| bounce := func(h string) bool { t.Errorf("%s was bounced", h); return true } |
| restartRequestLeg(ctx, routes, s, dd, bounce, nil, mem) |
| askRetry(t, ctx, s, priv, "bab", "eleven", "a.example.com", "v2", "bk", 5) |
| - var logbuf bytes.Buffer |
| - log.SetOutput(&logbuf) |
| - defer log.SetOutput(os.Stderr) |
| + logbuf := captureLogBuffer(t) |
| restartRequestLeg(ctx, routes, s, dd, bounce, nil, mem) |
| got := logbuf.String() |
| if !strings.Contains(got, "retry for a.example.com: nothing cleared") || strings.Contains(got, "hold is cleared") { |
| @@ -966,9 +954,7 @@ func TestRestartLegAppliesALegacySignedRetryWithTheSameChecks(t *testing.T) { |
| legacySignedRetry(t, ctx, s, priv, "bab", "eleven", "b.example.com", "v2", "bk", 5) |
| legacyRetry(t, ctx, s, "bab", "eleven", "a.example.com", "") |
| legacySignedRetry(t, ctx, s, other, "bab", "eleven", "a.example.com", "v2", "bk", 5) |
| - var logbuf bytes.Buffer |
| - log.SetOutput(&logbuf) |
| - defer log.SetOutput(os.Stderr) |
| + logbuf := captureLogBuffer(t) |
| if asked := restartRequestLeg(ctx, routes, s, dd, bounce, nil, mem); asked { |
| t.Fatal("a retry-only move asked for a root restart pass") |
| } |
diff --git a/internal/host/rollout_test.go b/internal/host/rollout_test.go| index f0ff9552b..36b1611c6 100644 |
| --- a/internal/host/rollout_test.go |
| +++ b/internal/host/rollout_test.go |
| @@ -1,12 +1,10 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "encoding/hex" |
| "encoding/json" |
| "errors" |
| - "log" |
| "os" |
| "path/filepath" |
| "reflect" |
| @@ -591,9 +589,7 @@ func TestSwapArmingDeclinesWhenPlacementFails(t *testing.T) { |
| t.Fatal(err) |
| } |
| resetRollout(t) |
| - var buf bytes.Buffer |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + buf := captureLogBuffer(t) |
| eb := armableBackend(t) |
| var got *cgroup.Manager |
| orig := placementCheck |
| @@ -663,9 +659,7 @@ func TestPlacementDeclineHonoursFailureRecords(t *testing.T) { |
| func TestSwapArmingDeclinesWhenHostClaimsAreOn(t *testing.T) { |
| resetRollout(t) |
| forbidPlacementCheck(t) |
| - var buf bytes.Buffer |
| - log.SetOutput(&buf) |
| - t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + buf := captureLogBuffer(t) |
| // No cgroups either: the claims check must come first, so the code |
| // says claims, not delegation. |
| eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: activator.Config{HostWrites: hostwrite.Config{Enabled: true}}} |
diff --git a/internal/host/rootfs_advice_test.go b/internal/host/rootfs_advice_test.go| index c0dacb7ba..84d1e7c5c 100644 |
| --- a/internal/host/rootfs_advice_test.go |
| +++ b/internal/host/rootfs_advice_test.go |
| @@ -2,7 +2,6 @@ package host |
| import ( |
| "context" |
| - "log" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -362,10 +361,7 @@ func TestResidentSettingsRefsWaitForBuildState(t *testing.T) { |
| // every rootfs row on every pass; the leg neither logs it nor retries for |
| // it, as for unchanged. Not parallel: it captures the log. |
| func TestLayoutLegIsQuietAboutKeptRootfsRows(t *testing.T) { |
| - var buf strings.Builder |
| - prev := log.Writer() |
| - log.SetOutput(&buf) |
| - defer log.SetOutput(prev) |
| + buf := captureLogBuffer(t) |
| if logLayoutResults([]layout.Result{{Host: "shop.example.com", Outcome: "kept", Reason: "rootfs instances are always nested"}}) { |
| t.Error("a kept rootfs row asked the leg to run again") |
| } |
diff --git a/internal/host/runs_test.go b/internal/host/runs_test.go| index 65f4592c7..65388a0b7 100644 |
| --- a/internal/host/runs_test.go |
| +++ b/internal/host/runs_test.go |
| @@ -1,11 +1,9 @@ |
| package host |
| import ( |
| - "bytes" |
| "context" |
| "encoding/json" |
| "errors" |
| - "log" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -385,9 +383,7 @@ func TestRunsWorkerLogsAnUnfitRequestOnce(t *testing.T) { |
| t.Fatal(err) |
| } |
| putJSONObject(t, s, key, req) |
| - var buf bytes.Buffer |
| - log.SetOutput(&buf) |
| - defer log.SetOutput(os.Stderr) |
| + buf := captureLogBuffer(t) |
| var l execLog |
| w := testWorker(s, runOwnedRoute(runHost), "box-1", "boot-1", &l) |
| for range 3 { |
diff --git a/internal/host/steering_loop_test.go b/internal/host/steering_loop_test.go| index e9ad82d99..c849d8641 100644 |
| --- a/internal/host/steering_loop_test.go |
| +++ b/internal/host/steering_loop_test.go |
| @@ -487,7 +487,7 @@ func TestSteeringLoopArmsWithoutReleasePubkey(t *testing.T) { |
| t.Setenv("CARLOS_RELEASE_PUBKEY", "") // deliberately unset — the whole point |
| t.Setenv("CARLOS_STEERING_ZONE_ID", "") |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| go steeringLoop(nil) |
| waitFor(t, "the steering loop to arm despite no CARLOS_RELEASE_PUBKEY", func() bool { |
| @@ -504,7 +504,7 @@ func TestSteeringLoopDormantWhenZoneUnset(t *testing.T) { |
| t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir()) |
| t.Setenv("CARLOS_STEERING_ZONE_ID", "") |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| go steeringLoop(nil) |
| waitFor(t, "the dormant line", func() bool { |
| @@ -523,7 +523,7 @@ func TestSteeringLoopDormantWhenZoneMalformed(t *testing.T) { |
| t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir()) |
| t.Setenv("CARLOS_STEERING_ZONE_ID", "/hostedzone/Z0ABCDEF1234") |
| - buf := captureRacyLog(t) |
| + buf := captureLogBuffer(t) |
| go steeringLoop(nil) |
| waitFor(t, "the dormant line for a malformed zone id", func() bool { |