| index 72deb2a8a..06c0f11eb 100644 |
| --- a/internal/activator/rootfsrelease_test.go |
| +++ b/internal/activator/rootfsrelease_test.go |
| @@ -13,15 +13,21 @@ import ( |
| "errors" |
| "fmt" |
| "io" |
| + "log" |
| "net" |
| + "net/http" |
| + "net/http/httptest" |
| "os" |
| "path/filepath" |
| "slices" |
| "strings" |
| "sync" |
| + "sync/atomic" |
| "testing" |
| "time" |
| |
| + "github.com/carlosframework/platform/internal/hostclaim" |
| + "github.com/carlosframework/platform/internal/hostwrite" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/provision" |
| @@ -1378,6 +1384,41 @@ func TestEveryReleaseResultIsClassified(t *testing.T) { |
| t.Errorf("%s: residentFailure = true", name) |
| } |
| } |
| + // Resident accounting (R1c): a release's own result counts toward the |
| + // resident's backoff only when classifyRelease reads it as failed, |
| + // bare or inside a wake's error. |
| + for _, c := range []struct { |
| + name string |
| + err error |
| + want releaseOutcome |
| + }{ |
| + {"a ReleaseError", rerr, releaseFailed}, |
| + {"a timed-out ReleaseError", &ReleaseError{Build: "v2", TimedOut: true, Took: time.Minute}, releaseFailed}, |
| + {"a signal's ReleaseError", &ReleaseError{Build: "v2", Signal: "9"}, releaseFailed}, |
| + {"errReleaseUnproven", errReleaseUnproven, releaseUnproven}, |
| + {"errReleaseUnproven after a lease trip", fmt.Errorf("%w: %w: %w (x)", errSwapLeaseLost, errReleaseLeaseLost, errReleaseUnproven), releaseUnproven}, |
| + {"errReleaseOpen", errReleaseOpen, releaseRefused}, |
| + {"errReleaseNoLease (marked)", refuseRootfs(errReleaseNoLease), releaseRefused}, |
| + {"errReleaseNoLease (bare)", errReleaseNoLease, releaseRefused}, |
| + {"the lease lost", fmt.Errorf("%w: %w", errSwapLeaseLost, errReleaseLeaseLost), releaseCancelled}, |
| + {"the vanished unit", errReleaseVanished, releaseCancelled}, |
| + {"no exit recorded", errReleaseNoExit, releaseCancelled}, |
| + } { |
| + if !isReleaseResult(c.err) { |
| + t.Errorf("%s: not read as a release's result", c.name) |
| + } |
| + for _, err := range []error{c.err, fmt.Errorf("start shop.example.com: %w", c.err)} { |
| + if got := classifyRelease(err, false); got != c.want { |
| + t.Errorf("%s: classifyRelease = %v, want %v", c.name, got, c.want) |
| + } |
| + if got, want := residentFailure(err), c.want == releaseFailed; got != want { |
| + t.Errorf("%s (%v): residentFailure = %v, want %v", c.name, err, got, want) |
| + } |
| + } |
| + } |
| + if residentFailure(nil) { |
| + t.Error("a passed release counts as a resident failure") |
| + } |
| } |
| |
| // What a member reads for a failed wake that carries a release result |
| @@ -1403,3 +1444,655 @@ func TestReleaseMemberWords(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// --- R1c: every consumer reads the record; Shutdown drains it ---------------- |
| + |
| +// releaseCmdFake is cmdFakeBackend (a nested layout and the run seam) with |
| +// releaseFake's release seam and process read on the same fakeBackend, so |
| +// one Service has an awake instance, its runs and its release. |
| +type releaseCmdFake struct { |
| + *cmdFakeBackend |
| + rel *releaseFake |
| +} |
| + |
| +func (b *releaseCmdFake) Processes(rt registry.Route, id release.StagedIdentity) (map[string]release.Process, error) { |
| + return b.rel.Processes(rt, id) |
| +} |
| + |
| +func (b *releaseCmdFake) ReleaseEnv(ctx context.Context, rt registry.Route) (map[string]string, error) { |
| + return b.rel.ReleaseEnv(ctx, rt) |
| +} |
| + |
| +func (b *releaseCmdFake) StartRelease(ctx context.Context, rt registry.Route, id release.StagedIdentity, env map[string]string, out io.Writer) (CmdUnit, error) { |
| + return b.rel.StartRelease(ctx, rt, id, env, out) |
| +} |
| + |
| +var ( |
| + _ ReleaseBackend = (*releaseCmdFake)(nil) |
| + _ ProcessReader = (*releaseCmdFake)(nil) |
| + _ CmdBackend = (*releaseCmdFake)(nil) |
| +) |
| + |
| +// consumerRig is a Service over releaseCmdFake with shop.example.com woken |
| +// through the ordinary path (a process, a replica, the lease), so every |
| +// stop path, the sweep and RunCmd act on a real entry. rrt is the same row |
| +// as a release reads it: rootfs, good on v1, with v2 staged. |
| +type consumerRig struct { |
| + a *Service |
| + cb *cmdFakeBackend |
| + rel *releaseFake |
| + clk *fakeClock |
| + sink *rootfsSink |
| + rt registry.Route |
| + rrt registry.Route |
| + e *actEntry |
| + id release.StagedIdentity |
| + held *ownedLease |
| +} |
| + |
| +func newConsumerRig(t *testing.T, gens bool) *consumerRig { |
| + t.Helper() |
| + fb := &fakeBackend{layoutFn: func(registry.Route) (Layout, string) { return LayoutNested, "" }} |
| + cb := &cmdFakeBackend{fakeBackend: fb} |
| + cb.unit = &fakeCmdUnit{rep: fb.lastRep} |
| + rel := &releaseFake{fakeBackend: fb, procs: releaseDeclared(), unit: newReleaseUnit(), started: make(chan struct{})} |
| + clk := &fakeClock{t: time.Unix(1_700_000_000, 0)} |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, &releaseCmdFake{cmdFakeBackend: cb, rel: rel}, reg) |
| + a.now = clk.now |
| + a.gens = gens |
| + sink := &rootfsSink{} |
| + a.Logs = sink |
| + a.GenerationsFile = filepath.Join(t.TempDir(), "generations.json") |
| + rt := testRoute("shop.example.com") |
| + arrangeAwake(t, a, rt) |
| + a.mu.Lock() |
| + e := a.entries[rt.Host] |
| + a.mu.Unlock() |
| + rrt := rt |
| + rrt.Runtime, rrt.App, rrt.Account, rrt.Version = registry.RuntimeRootfsV1, "shop", "acme", "v1" |
| + rrt.GoodVersion, rrt.GoodDigest = "v1", "aa11" |
| + id := release.StagedIdentity{Version: "v2", StagedPath: filepath.Join(t.TempDir(), "v2", "rootfs.squashfs"), Digest: "bb22"} |
| + return &consumerRig{a: a, cb: cb, rel: rel, clk: clk, sink: sink, rt: rt, rrt: rrt, e: e, id: id, |
| + held: newOwnedLease(time.Now().Add(time.Hour), false)} |
| +} |
| + |
| +// gate is the site's ownership gate: the entry is still the host's and |
| +// awake. |
| +func (r *consumerRig) gate() error { |
| + r.a.mu.Lock() |
| + defer r.a.mu.Unlock() |
| + if r.a.entries[r.rt.Host] != r.e || r.e.state != actAwake { |
| + return errSwapSuperseded |
| + } |
| + return nil |
| +} |
| + |
| +// start runs a release for the entry in the background and waits for its |
| +// unit to start; its result arrives on the channel. |
| +func (r *consumerRig) start(t *testing.T, ctx context.Context) <-chan releaseResult { |
| + t.Helper() |
| + ch := make(chan releaseResult, 1) |
| + go func() { |
| + ex, err := r.a.runRelease(ctx, r.e, r.rrt, r.id, r.held, r.gate) |
| + ch <- releaseResult{ex, err} |
| + }() |
| + select { |
| + case <-r.rel.started: |
| + case res := <-ch: |
| + t.Fatalf("runRelease returned before its start: %v, %v", res.executed, res.err) |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("StartRelease was never called") |
| + } |
| + return ch |
| +} |
| + |
| +// endRun stops and releases a run, its unit proven settled. |
| +func endRun(t *testing.T, h CmdHandle) { |
| + t.Helper() |
| + if err := h.Stop(context.Background()); err != nil { |
| + t.Fatalf("the run's stop: %v", err) |
| + } |
| + h.Release() |
| +} |
| + |
| +// fresh gives the fake a new unit and start signal, for a second release. |
| +func (r *consumerRig) fresh() { |
| + r.rel.rmu.Lock() |
| + r.rel.unit, r.rel.started = newReleaseUnit(), make(chan struct{}) |
| + r.rel.rmu.Unlock() |
| +} |
| + |
| +func (r *consumerRig) record() *releaseOp { |
| + r.a.mu.Lock() |
| + defer r.a.mu.Unlock() |
| + return r.a.releaseOps[r.rt.Host] |
| +} |
| + |
| +// awake reports whether the entry is still the host's, awake, and asked to |
| +// stop by nothing. |
| +func (r *consumerRig) awake() bool { |
| + r.a.mu.Lock() |
| + defer r.a.mu.Unlock() |
| + return r.a.entries[r.rt.Host] == r.e && r.e.state == actAwake && r.e.stopWhy == "" |
| +} |
| + |
| +// pendingStop reports whether the entry is still the host's, stopping with |
| +// its stop pending. |
| +func (r *consumerRig) pendingStop() bool { |
| + r.a.mu.Lock() |
| + defer r.a.mu.Unlock() |
| + return r.a.entries[r.rt.Host] == r.e && r.e.state == actStopping && r.e.pendingStop |
| +} |
| + |
| +// sweepUntilGone sweeps until the entry's pending stop has finished (a |
| +// sweep skips an entry whose last proof is still in flight). |
| +func (r *consumerRig) sweepUntilGone(t *testing.T) { |
| + t.Helper() |
| + for i := 0; i < 100 && r.a.entryCount() > 0; i++ { |
| + r.a.sweepOnce() |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + waitFor(t, "the stop to finish", func() bool { return r.a.entryCount() == 0 }) |
| +} |
| + |
| +// sweepPass runs finishPendingStops as the sweep and Shutdown run it. |
| +func (r *consumerRig) sweepPass() { |
| + r.a.mu.Lock() |
| + r.a.finishPendingStops() |
| + r.a.mu.Unlock() |
| +} |
| + |
| +// stuckUnit makes every settle of u fail until the returned func is called. |
| +func stuckUnit(u *releaseUnit) (unstick func()) { |
| + var mu sync.Mutex |
| + stuck := true |
| + u.mu.Lock() |
| + u.settle = func(int) error { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if stuck { |
| + return errors.New("processes remained in the unit's cgroup") |
| + } |
| + return nil |
| + } |
| + u.mu.Unlock() |
| + return func() { |
| + mu.Lock() |
| + stuck = false |
| + mu.Unlock() |
| + } |
| +} |
| + |
| +// INV-R1: with a record for the host, every consumer of "is a release |
| +// running or unproven here" reads the record, and proceeds once it is |
| +// proven gone. |
| +func TestReleaseOpConsumersReadTheRecord(t *testing.T) { |
| + t.Run("a run and a second release", func(t *testing.T) { |
| + r := newConsumerRig(t, false) |
| + ch := r.start(t, context.Background()) |
| + if _, err := r.a.RunCmd(context.Background(), r.rt, CmdSpec{RunID: "run_a"}); !errors.Is(err, ErrCmdBusy) { |
| + t.Fatalf("RunCmd during a release = %v, want ErrCmdBusy", err) |
| + } |
| + if r.cb.cmdStarts != 0 { |
| + t.Fatal("a run started its unit beside a release") |
| + } |
| + if _, err := r.a.runRelease(context.Background(), r.e, r.rrt, r.id, r.held, r.gate); !errors.Is(err, errReleaseOpen) { |
| + t.Fatalf("a second release = %v, want errReleaseOpen", err) |
| + } |
| + if n := r.rel.startCount(); n != 1 { |
| + t.Fatalf("%d release starts, want 1", n) |
| + } |
| + if !pinned(t, r.a, r.rt.Host, "v2") { |
| + t.Fatal("the generations file does not name the release's build") |
| + } |
| + r.rel.unit.done("1", "0", "success") |
| + if res := wait(t, ch); res.err != nil { |
| + t.Fatalf("the release = %v", res.err) |
| + } |
| + // Proven: each proceeds. |
| + if pinned(t, r.a, r.rt.Host, "v2") { |
| + t.Fatal("the pin outlived the record") |
| + } |
| + h, err := r.a.RunCmd(context.Background(), r.rt, CmdSpec{RunID: "run_b"}) |
| + if err != nil { |
| + t.Fatalf("RunCmd after the proof = %v", err) |
| + } |
| + endRun(t, h) |
| + r.fresh() |
| + ch = r.start(t, context.Background()) |
| + r.rel.unit.done("1", "0", "success") |
| + if res := wait(t, ch); res.err != nil { |
| + t.Fatalf("a release after the proof = %v", res.err) |
| + } |
| + }) |
| + |
| + // The sweep's three stops of an awake owner: deferred while the record |
| + // is open, taken on the first sweep after it goes. |
| + for _, arm := range []struct { |
| + name string |
| + install func(r *consumerRig) |
| + }{ |
| + {"idle", func(r *consumerRig) { r.clk.advance(2 * time.Hour) }}, |
| + {"the awake ceiling", func(r *consumerRig) { |
| + r.a.SetMaxRunFor(func(registry.Route) time.Duration { return time.Minute }) |
| + r.clk.advance(2 * time.Minute) |
| + }}, |
| + {"plan-disabled", func(r *consumerRig) { r.a.SetDisabledFor(func(registry.Route) bool { return true }) }}, |
| + } { |
| + t.Run("the sweep: "+arm.name, func(t *testing.T) { |
| + r := newConsumerRig(t, false) |
| + ch := r.start(t, context.Background()) |
| + arm.install(r) |
| + r.a.sweepOnce() |
| + if !r.awake() { |
| + t.Fatalf("the sweep stopped the owner of an open release (stopWhy %q)", r.a.stopWhyOf(r.rt.Host)) |
| + } |
| + r.rel.unit.done("1", "0", "success") |
| + if res := wait(t, ch); res.err != nil { |
| + t.Fatalf("the release = %v", res.err) |
| + } |
| + r.a.sweepOnce() |
| + if r.awake() { |
| + t.Fatal("the first sweep after the proof did not stop the owner") |
| + } |
| + waitFor(t, "the stop", func() bool { return r.a.entryCount() == 0 }) |
| + }) |
| + } |
| + |
| + // A stop of the owner keeps its lease while the record is open: |
| + // releasable is false and finishStop keeps the stop pending, with the |
| + // replica open, under either generations setting. |
| + for _, gens := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("a stop of the owner, gens %v", gens), func(t *testing.T) { |
| + r := newConsumerRig(t, gens) |
| + unstick := stuckUnit(r.rel.unit) |
| + ch := r.start(t, context.Background()) |
| + rep := r.cb.lastRep() |
| + r.a.Bounce(r.rt.Host) |
| + res := wait(t, ch) |
| + if !errors.Is(res.err, errReleaseUnproven) { |
| + t.Fatalf("the release = %v, want errReleaseUnproven", res.err) |
| + } |
| + waitFor(t, "the stop to be kept pending", r.pendingStop) |
| + if r.a.releasable(r.e) { |
| + t.Fatal("releasable is true with the record open") |
| + } |
| + for i := 0; i < 3; i++ { |
| + r.a.sweepOnce() |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + if !r.pendingStop() || rep.isClosed() { |
| + t.Fatalf("the stop finished over an open record (pending %v, replica closed %v)", r.pendingStop(), rep.isClosed()) |
| + } |
| + unstick() |
| + r.clk.advance(actStopTimeout) |
| + r.a.sweepOnce() |
| + waitFor(t, "the reaper's proof", func() bool { return r.record() == nil }) |
| + r.sweepUntilGone(t) |
| + if !rep.isClosed() { |
| + t.Fatal("the replica was not closed after the proof") |
| + } |
| + }) |
| + } |
| + |
| + // The owner gone (R3's failed wake leaves owner nil): a wake of the |
| + // host, the resident tick and a fence are refused while the record is |
| + // open, before any lease; once it is proven the host wakes. |
| + t.Run("the owner gone", func(t *testing.T) { |
| + r := newConsumerRig(t, true) |
| + unstick := stuckUnit(r.rel.unit) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + ch := r.start(t, ctx) |
| + cancel() |
| + if res := wait(t, ch); !errors.Is(res.err, errReleaseUnproven) { |
| + t.Fatalf("the release = %v, want errReleaseUnproven", res.err) |
| + } |
| + r.a.mu.Lock() |
| + delete(r.a.entries, r.rt.Host) |
| + r.a.releaseOps[r.rt.Host].owner = nil |
| + r.a.rememberStopLocked(r.rt.Host, &stopObservation{mainStop: true, mainExited: true, sidecarStop: true, sidecarExited: true, replicaClosed: true, leaseReleased: true}) |
| + r.a.mu.Unlock() |
| + acquires := r.cb.acquireCount() |
| + |
| + w := httptest.NewRecorder() |
| + r.a.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://"+r.rt.Host+"/", nil), r.rt, okHandler()) |
| + if w.Code == http.StatusOK { |
| + t.Fatal("a request woke the host over an open release record") |
| + } |
| + if _, err := r.a.beginRequest(context.Background(), r.rt); !errors.Is(err, errWakeUnproven) { |
| + t.Fatalf("a wake of the host = %v, want errWakeUnproven", err) |
| + } |
| + fctx, fcancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + if _, err := r.a.FenceAndStop(fctx, r.rt.Host, 1); !errors.Is(err, ErrStopUnproven) { |
| + t.Errorf("a fence over an open release record = %v, want ErrStopUnproven", err) |
| + } |
| + fcancel() |
| + r.a.LiftFence(r.rt.Host, 1) |
| + armRootfsForTest(r.a) |
| + r.a.residentJitter = func() float64 { return 0 } |
| + res := residentRoute(r.rt.Host) |
| + r.a.residentLister = &fakeResidents{routes: []registry.Route{res}} |
| + var reserved atomic.Int32 |
| + r.a.residentGatesPassed = func(string) { reserved.Add(1) } |
| + tickSettled(t, r.a) |
| + if r.a.hasEntry(r.rt.Host) || reserved.Load() != 0 { |
| + t.Fatalf("the resident tick reserved the host %d times over an open release record", reserved.Load()) |
| + } |
| + if got := r.cb.acquireCount(); got != acquires { |
| + t.Fatalf("%d lease acquires over an open release record", got-acquires) |
| + } |
| + |
| + unstick() |
| + r.clk.advance(actStopTimeout) |
| + r.sweepPass() |
| + waitFor(t, "the reaper's proof", func() bool { return r.record() == nil }) |
| + tickSettled(t, r.a) |
| + if r.a.awakeEntry(r.rt.Host) == nil { |
| + t.Fatal("the resident tick did not start the host after the proof") |
| + } |
| + if got := r.cb.acquireCount(); got != acquires+1 { |
| + t.Fatalf("%d lease acquires after the proof, want 1", got-acquires) |
| + } |
| + }) |
| + |
| + // A claims-on wake asks the same record at its head. |
| + t.Run("a claimed wake", func(t *testing.T) { |
| + read := false |
| + a := &Service{cfg: Config{HostWrites: hostwrite.Config{Enabled: true}, Claims: &ClaimRuntime{Box: "box", |
| + Read: func(context.Context, string) (hostclaim.Observed, error) { |
| + read = true |
| + return claimedObs("x.example"), nil |
| + }, |
| + StopForeign: func(context.Context, string) error { return nil }}}} |
| + a.releaseOps = map[string]*releaseOp{"x.example": {host: "x.example"}} |
| + e := &actEntry{host: "x.example", route: registry.Route{Host: "x.example", Kind: "instance"}} |
| + if _, err := a.doClaimWake(context.Background(), e); !errors.Is(err, errWakeUnproven) { |
| + t.Fatalf("doClaimWake = %v, want errWakeUnproven", err) |
| + } |
| + if read { |
| + t.Fatal("the claim was read for a host with an open release record") |
| + } |
| + }) |
| +} |
| + |
| +// INV-R2: an unproven release of an awake incumbent, whose owner never |
| +// stops, is retried by the sweep's pass alone, and once proven its pin |
| +// goes and the host takes a release and a run again. |
| +func TestUnprovenReleaseOnAnAwakeIncumbentIsRetried(t *testing.T) { |
| + r := newConsumerRig(t, true) |
| + unstick := stuckUnit(r.rel.unit) |
| + ch := r.start(t, context.Background()) |
| + r.rel.unit.done("1", "0", "success") |
| + res := wait(t, ch) |
| + if !errors.Is(res.err, errReleaseUnproven) || classifyRelease(res.err, true) != releaseUnproven { |
| + t.Fatalf("the release = %v, want errReleaseUnproven", res.err) |
| + } |
| + op := r.record() |
| + if op == nil { |
| + t.Fatal("the record went with its unit unproven") |
| + } |
| + r.a.mu.Lock() |
| + state := op.state |
| + r.a.mu.Unlock() |
| + if state != releaseNotProven || !r.awake() { |
| + t.Fatalf("state %d, owner awake %v; want releaseNotProven beside an awake owner", state, r.awake()) |
| + } |
| + // The sweep's pass is its one retrier, at most every actStopTimeout. |
| + n := len(r.rel.unit.stopTimes()) |
| + r.a.sweepOnce() |
| + time.Sleep(50 * time.Millisecond) |
| + if got := len(r.rel.unit.stopTimes()); got != n { |
| + t.Fatalf("the sweep's pass made %d settle attempts inside actStopTimeout", got-n) |
| + } |
| + r.clk.advance(actStopTimeout) |
| + r.a.sweepOnce() |
| + waitFor(t, "the sweep's retry", func() bool { return len(r.rel.unit.stopTimes()) == n+1 }) |
| + if !pinned(t, r.a, r.rt.Host, "v2") { |
| + t.Fatal("the pin went with the unit unproven") |
| + } |
| + if _, err := r.a.RunCmd(context.Background(), r.rt, CmdSpec{RunID: "run_a"}); !errors.Is(err, ErrCmdBusy) { |
| + t.Fatalf("RunCmd over an unproven release = %v, want ErrCmdBusy", err) |
| + } |
| + unstick() |
| + r.clk.advance(actStopTimeout) |
| + r.a.sweepOnce() |
| + waitFor(t, "the reaper's proof", func() bool { return r.record() == nil }) |
| + waitFor(t, "the pin to leave the file", func() bool { return !pinned(t, r.a, r.rt.Host, "v2") }) |
| + if !r.awake() { |
| + t.Fatal("the owner was stopped") |
| + } |
| + r.a.mu.Lock() |
| + history := r.a.stopHistory[r.rt.Host] |
| + r.a.mu.Unlock() |
| + if history != nil { |
| + t.Errorf("the proof of an owned record wrote a stop history %+v over the live owner", history) |
| + } |
| + h, err := r.a.RunCmd(context.Background(), r.rt, CmdSpec{RunID: "run_b"}) |
| + if err != nil { |
| + t.Fatalf("RunCmd after the proof = %v", err) |
| + } |
| + endRun(t, h) |
| + r.fresh() |
| + ch = r.start(t, context.Background()) |
| + r.rel.unit.done("1", "0", "success") |
| + if res := wait(t, ch); res.err != nil { |
| + t.Fatalf("a release after the proof = %v", res.err) |
| + } |
| +} |
| + |
| +// 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{} { |
| + done := make(chan struct{}) |
| + go func() { |
| + ctx, cancel := context.WithTimeout(context.Background(), budget) |
| + defer cancel() |
| + a.Shutdown(ctx) |
| + close(done) |
| + }() |
| + return done |
| +} |
| + |
| +func returned(ch <-chan struct{}) bool { |
| + select { |
| + case <-ch: |
| + return true |
| + default: |
| + return false |
| + } |
| +} |
| + |
| +// INV-R2: Shutdown runs the one retry path until every record is proven or |
| +// its budget ends, and names each record it leaves. |
| +func TestShutdownDrainsReleaseOps(t *testing.T) { |
| + // orphan leaves the rig's record ownerless (R3's failed wake), its |
| + // entry gone and its lease owed. |
| + orphan := func(t *testing.T, r *consumerRig) (unstick func(), owed *fakeLease) { |
| + t.Helper() |
| + unstick = stuckUnit(r.rel.unit) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + ch := r.start(t, ctx) |
| + cancel() |
| + if res := wait(t, ch); !errors.Is(res.err, errReleaseUnproven) { |
| + t.Fatalf("the release = %v, want errReleaseUnproven", res.err) |
| + } |
| + owed = &fakeLease{b: r.cb.fakeBackend} |
| + r.a.mu.Lock() |
| + delete(r.a.entries, r.rt.Host) |
| + op := r.a.releaseOps[r.rt.Host] |
| + op.owner, op.owed = nil, owed |
| + r.a.mu.Unlock() |
| + return unstick, owed |
| + } |
| + |
| + t.Run("an ownerless record with an owed lease", func(t *testing.T) { |
| + r := newConsumerRig(t, true) |
| + unstick, _ := orphan(t, r) |
| + releases := r.cb.releaseCount() |
| + tries := len(r.rel.unit.stopTimes()) |
| + r.clk.advance(actStopTimeout) |
| + done := shutdownIn(r.a, 10*time.Second) |
| + waitFor(t, "Shutdown's pass to retry the settle", func() bool { return len(r.rel.unit.stopTimes()) > tries }) |
| + time.Sleep(300 * time.Millisecond) |
| + if returned(done) { |
| + t.Fatal("Shutdown returned with the record unproven inside its budget") |
| + } |
| + unstick() |
| + r.clk.advance(actStopTimeout) |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("Shutdown did not return once the record could be proven") |
| + } |
| + if r.record() != nil { |
| + t.Fatal("Shutdown returned with the record left") |
| + } |
| + if got := r.cb.releaseCount(); got != releases+1 { |
| + t.Fatalf("%d lease releases, want the owed lease given back once", got-releases) |
| + } |
| + r.a.mu.Lock() |
| + history := r.a.stopHistory[r.rt.Host] |
| + r.a.mu.Unlock() |
| + if history == nil || !history.uncertain { |
| + t.Errorf("stop history %+v, want the uncertainty kept", history) |
| + } |
| + }) |
| + |
| + t.Run("a stopping incumbent", func(t *testing.T) { |
| + r := newConsumerRig(t, true) |
| + unstick := stuckUnit(r.rel.unit) |
| + ch := r.start(t, context.Background()) |
| + rep := r.cb.lastRep() |
| + var provenAtClose atomic.Bool |
| + rep.setOnClose(func() { provenAtClose.Store(r.record() == nil && r.rel.unit.isProven()) }) |
| + done := shutdownIn(r.a, 10*time.Second) |
| + if res := wait(t, ch); !errors.Is(res.err, errReleaseUnproven) || classifyRelease(res.err, true) != releaseUnproven { |
| + t.Fatalf("the release = %v, want errReleaseUnproven", res.err) |
| + } |
| + time.Sleep(300 * time.Millisecond) |
| + if returned(done) || rep.isClosed() { |
| + t.Fatalf("Shutdown returned %v, replica closed %v, with the release unproven", returned(done), rep.isClosed()) |
| + } |
| + unstick() |
| + r.clk.advance(actStopTimeout) |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("Shutdown did not return once the release was proven") |
| + } |
| + if !rep.isClosed() || !provenAtClose.Load() { |
| + t.Fatalf("replica closed %v, the release proven at its close %v", rep.isClosed(), provenAtClose.Load()) |
| + } |
| + }) |
| + |
| + t.Run("still unproven at the deadline", func(t *testing.T) { |
| + r := newConsumerRig(t, true) |
| + orphan(t, r) |
| + buf := captureLockedLog(t) |
| + select { |
| + case <-shutdownIn(r.a, 300*time.Millisecond): |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("Shutdown outlived its budget") |
| + } |
| + if r.record() == nil { |
| + t.Fatal("the record went unproven") |
| + } |
| + out := buf.String() |
| + if !strings.Contains(out, "release command(s) not proven stopped") || !strings.Contains(out, "shop.example.com (build v2)") { |
| + t.Fatalf("the exit log does not name the record:\n%s", out) |
| + } |
| + }) |
| +} |
| + |
| +func (u *releaseUnit) isProven() bool { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + return u.proven |
| +} |
| + |
| +// A stop of the owner while the release polls cancels it: its unit is |
| +// stopped and proven before the replica closes, and a run asked for |
| +// meanwhile starts no unit. Run with -race. |
| +func TestStopSettlesARunningRelease(t *testing.T) { |
| + for _, gens := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("gens %v", gens), func(t *testing.T) { |
| + r := newConsumerRig(t, gens) |
| + var omu sync.Mutex |
| + var order []string |
| + note := func(s string) { |
| + omu.Lock() |
| + order = append(order, s) |
| + omu.Unlock() |
| + } |
| + // The settle is held until the run has had its say, so the |
| + // record is open for the run's whole admission. |
| + hold := make(chan struct{}) |
| + r.rel.unit.settle = func(int) error { <-hold; note("release settled"); return nil } |
| + ch := r.start(t, context.Background()) |
| + rep := r.cb.lastRep() |
| + rep.setOnClose(func() { note("replica closed") }) |
| + var wg sync.WaitGroup |
| + var runErr error |
| + wg.Add(2) |
| + go func() { |
| + defer wg.Done() |
| + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) |
| + defer cancel() |
| + _, runErr = r.a.RunCmd(ctx, r.rt, CmdSpec{RunID: "run_a"}) |
| + }() |
| + go func() { defer wg.Done(); r.a.Bounce(r.rt.Host) }() |
| + wg.Wait() |
| + close(hold) |
| + res := wait(t, ch) |
| + if !errors.Is(res.err, context.Canceled) || classifyRelease(res.err, false) != releaseCancelled { |
| + t.Fatalf("the release = %v, want a cancellation", res.err) |
| + } |
| + if runErr == nil { |
| + t.Fatal("a run was admitted during the release") |
| + } |
| + if r.cb.cmdStarts != 0 { |
| + t.Fatal("a run started its unit during the release") |
| + } |
| + waitFor(t, "the record to go", func() bool { return r.record() == nil }) |
| + r.sweepUntilGone(t) |
| + omu.Lock() |
| + got := slices.Clone(order) |
| + omu.Unlock() |
| + if want := []string{"release settled", "replica closed"}; !slices.Equal(got, want) { |
| + t.Fatalf("order %q, want %q", got, want) |
| + } |
| + }) |
| + } |
| +} |