tests: lock every log capture; end goroutines with their tests
Prepares edge, activator and host for a -race CI step. Each package now has one locked log capture (captureLog; host also has captureLogBuffer) in place of plain buffers and duplicate locked types. Races the detector found, all in tests or provoked by them: - activator pty test swapped CgroupEvents after an observer had started - host claimstop test reassigned a ctx its server goroutine was reading - activator watchFirstWake read firstWakeSettle inside its goroutine, so a test restoring the knob raced it. It now reads the value first; the wait and the failure reason are unchanged. Census overlay included. wakecheck's slow answer now ends before the test's cleanups run, in place of a 5 s sleep that outlived the test. The bootstrap tmpfiles test reads its stdout pipe while writing, which hung on a one-page pipe.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
83 files changed,
+337
−620
.amadan/code-health.tsv+1 −2docs/superpowers/notes/census-proposal-race-helpers.md+19 −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/wakeplan.go+6 −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 −3internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-race-helpers.tsv+5 −0
Intent
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/docs/superpowers/notes/census-proposal-race-helpers.md b/docs/superpowers/notes/census-proposal-race-helpers.md| new file mode 100644 |
| index 000000000..4c9641454 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-race-helpers.md |
| @@ -0,0 +1,19 @@ |
| +# Census approval: race-helpers |
| + |
| +Ruling `census-ruling-race-helpers`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/activator/wakeplan.go` `Service.watchFirstWake` | body | unchanged (10) | reads firstWakeSettle once before starting the watcher goroutine instead of inside it; the same value is used for the same wait and the same failure reason, and nothing root opens, runs or reads changes | |
| + |
| +Envelopes re-pinned: `internal/activator`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/activator/wakeplan.go` `Service.watchFirstWake`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route |
| + |
| +Seal: `c9cd3c8fdf31240b83affa0b2798422f3a99e1d0d400dbaf68665c1127996448` โ `207dbb26de8b2899772cb5814f7985f22d3bfa706f94f8f808957f1e288eadd0`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-race-helpers.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
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/wakeplan.go b/internal/activator/wakeplan.go| index 099288957..ccadd95b7 100644 |
| --- a/internal/activator/wakeplan.go |
| +++ b/internal/activator/wakeplan.go |
| @@ -912,8 +912,12 @@ func (a *Service) watchFirstWake(e *actEntry, g Gen, plan WakePlan) { |
| cancelled(rt) |
| return |
| } |
| + // Read before the goroutine starts: a test shrinks firstWakeSettle and |
| + // puts it back when it ends, and a watcher scheduled after that would |
| + // read it as it is written (`make race`). |
| + settle := firstWakeSettle |
| go func() { |
| - r := observeSettle(ctx, proc, firstWakeSettle) |
| + r := observeSettle(ctx, proc, settle) |
| a.mu.Lock() |
| rt, unexpected, release := e.route, e.unexpectedExit, e.firstWatchRelease |
| a.mu.Unlock() |
| @@ -948,7 +952,7 @@ func (a *Service) watchFirstWake(e *actEntry, g Gen, plan WakePlan) { |
| // current (and admits an attempt onto it) before the failure is |
| // recorded. |
| a.emitPlanned(plan, GenEvent{Kind: GenFailed, Route: rt, Failed: plan.Boot, Mode: plan.Mode, FirstWake: true, |
| - Reason: "exited within " + firstWakeSettle.String() + " of becoming healthy", At: time.Now(), FailedUnder: plan.FailedUnder}) |
| + Reason: "exited within " + settle.String() + " of becoming healthy", At: time.Now(), FailedUnder: plan.FailedUnder}) |
| end() |
| default: // an intentional stop cancelled it |
| cancelled(rt) |
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 aa8cce854..9456c1d63 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 { |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index fa6913fa2..925321336 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -245,3 +245,4 @@ plan14-root-reads-ha-1192.tsv 8df52839a0c961d3721f3a5c3247d06202dae4e00d011844b7 |
| plan14-root-reads-audit-bugs-2.tsv 1610abfc476fe45d259494242243756dac9cfec49cdd7f7f7b238329392241a1 |
| plan14-root-reads-bounded-systemctl.tsv 16cae3931aadfa57a5293d69becf318645681400777cc08972cf08eb449c2457 |
| plan14-root-reads-mail-submission-followups.tsv c9cd3c8fdf31240b83affa0b2798422f3a99e1d0d400dbaf68665c1127996448 |
| +plan14-root-reads-race-helpers.tsv 207dbb26de8b2899772cb5814f7985f22d3bfa706f94f8f808957f1e288eadd0 |
diff --git a/internal/provision/testdata/plan14-root-reads-race-helpers.tsv b/internal/provision/testdata/plan14-root-reads-race-helpers.tsv| new file mode 100644 |
| index 000000000..1ca4da7f3 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-race-helpers.tsv |
| @@ -0,0 +1,5 @@ |
| +# Census overlay race-helpers, written by census-propose (#369). census-ruling-race-helpers, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-race-helpers.md. |
| +# 1 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy 8a9c79cad8aee34584e1e6b2467faae7b404791821162e73e6e4ee787af81a96 internal/activator/wakeplan.go Service.watchFirstWake legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-race-helpers;basis=reads firstWakeSettle once before starting the watcher goroutine instead of inside it; the same value is used for the same wait and the same failure reason, and nothing root opens, runs or reads changes whole:Route@1256,whole:Route@2166,whole:Route@2173,whole:Route@2448,whole:Route@2455,whole:Route@2702,whole:Route@406,whole:Route@413,whole:Route@868,whole:Route@926 4cd2a9c67f74c1a00a33464393bf4f2e6e8b049491ec2ad19817b8c0191f30c8 |
| +internal/activator/wakeplan.go Service.watchFirstWake legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-race-helpers;basis=reads firstWakeSettle once before starting the watcher goroutine instead of inside it; the same value is used for the same wait and the same failure reason, and nothing root opens, runs or reads changes whole:Route@1256,whole:Route@2166,whole:Route@2173,whole:Route@2448,whole:Route@2455,whole:Route@2702,whole:Route@406,whole:Route@413,whole:Route@868,whole:Route@926 4cd2a9c67f74c1a00a33464393bf4f2e6e8b049491ec2ad19817b8c0191f30c8 |
| +@coverage internal/activator 6850c53377aee5a1d92ce990a98eb955d8d157774b0b05d2117937657e4bcfd4 |