diff --git a/internal/container/pool.go b/internal/container/pool.go index 018602bbd..0006c58a9 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -88,9 +88,9 @@ type Pool struct { mu sync.Mutex active int - // reapers holds the armed max-uptime timer for each live container, - // keyed by ID, so Release can cancel the one it is tearing down. - reapers map[string]*time.Timer + // teardowns holds the one-shot teardown state for each live container, + // keyed by ID. See containerTeardown. + teardowns map[string]*containerTeardown } // Config is the subset of daemon container configuration the pool needs. @@ -240,14 +240,28 @@ func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string return &Container{ID: resp.ID}, nil } +// containerTeardown is the one-shot teardown state for a live container: its +// armed max-uptime reaper, and whether Docker stop/remove has been claimed. +// +// Both the reaper and Release tear a container down, and Timer.Stop cannot +// unwind a callback that has already begun, so cancelling the timer is not +// enough to keep them from overlapping. Claiming decides the winner instead: +// exactly one path talks to Docker, and the loser skips straight to its own +// bookkeeping. +type containerTeardown struct { + timer *time.Timer + closed bool +} + // armMaxUptime schedules a hard stop and remove for a container once its // lifetime cap elapses. The timer never touches p.active: Release (or Close) -// remains the only owner of the active slot. Release cancels the timer, so a -// container that finished normally is not reaped a second time against an ID -// Docker has already forgotten. +// remains the only owner of the active slot. func (p *Pool) armMaxUptime(ctx context.Context, id string) { timer := time.AfterFunc(p.cfg.MaxUptime, func() { - p.forgetReaper(id) + if !p.claimTeardown(id) { + return + } + defer p.forgetTeardown(id) zero := 0 stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) defer cancel() @@ -261,29 +275,46 @@ func (p *Pool) armMaxUptime(ctx context.Context, id string) { p.mu.Lock() defer p.mu.Unlock() - if p.reapers == nil { - p.reapers = make(map[string]*time.Timer) - } - p.reapers[id] = timer + p.teardownLocked(id).timer = timer } -// cancelMaxUptime disarms a container's reaper, if it has not already fired. -func (p *Pool) cancelMaxUptime(id string) { +// claimTeardown reports whether the caller owns this container's Docker +// teardown. The first caller wins; every later one is told to stay out. +func (p *Pool) claimTeardown(id string) bool { p.mu.Lock() - timer := p.reapers[id] - delete(p.reapers, id) + defer p.mu.Unlock() + t := p.teardownLocked(id) + if t.closed { + return false + } + t.closed = true + return true +} + +// forgetTeardown disarms the reaper and drops the container's bookkeeping, so +// the map does not grow for the life of the pool. +func (p *Pool) forgetTeardown(id string) { + p.mu.Lock() + t := p.teardowns[id] + delete(p.teardowns, id) p.mu.Unlock() - if timer != nil { - timer.Stop() + if t != nil && t.timer != nil { + t.timer.Stop() } } -// forgetReaper drops a timer's own map entry as it fires, so the map does not -// grow for the life of the pool. -func (p *Pool) forgetReaper(id string) { - p.mu.Lock() - delete(p.reapers, id) - p.mu.Unlock() +// teardownLocked returns the container's teardown state, creating it on first +// use. Callers must hold p.mu. +func (p *Pool) teardownLocked(id string) *containerTeardown { + if p.teardowns == nil { + p.teardowns = make(map[string]*containerTeardown) + } + t := p.teardowns[id] + if t == nil { + t = &containerTeardown{} + p.teardowns[id] = t + } + return t } // releaseDecision reports how Release should tear a container down: whether @@ -320,26 +351,29 @@ func (p *Pool) Release(ctx context.Context, c *Container) { time.Sleep(p.cfg.GracePeriod) } - // Disarm only now. MaxUptime is a cap from creation enforced regardless of - // task state, so it must still bite during the grace period above; - // cancelling before the sleep would quietly extend the cap by GracePeriod. - p.cancelMaxUptime(c.ID) + // Claim only now. MaxUptime is a cap from creation enforced regardless of + // task state, so the reaper must still be free to bite during the grace + // period above; claiming before the sleep would quietly extend the cap by + // GracePeriod. Losing the claim means the reaper already removed this + // container, so there is nothing left to stop. + if p.claimTeardown(c.ID) { + // Detach from ctx before stopping. Release runs on the way out of a + // task, and the most important reason a task is on its way out is + // that it was cancelled -- at which point ctx is already dead, the + // graceful stop fails immediately, and the container is left to the + // forced remove below. Teardown is cleanup, so it gets its own + // deadline rather than inheriting the caller's cancellation. + stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) + defer cancel() - // Detach from ctx before stopping. Release runs on the way out of a - // task, and the most important reason a task is on its way out is - // that it was cancelled -- at which point ctx is already dead, the - // graceful stop fails immediately, and the container is left to the - // forced remove below. Teardown is cleanup, so it gets its own - // deadline rather than inheriting the caller's cancellation. - stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) - defer cancel() - - if _, err := p.cli.ContainerStop(stopCtx, c.ID, client.ContainerStopOptions{Timeout: stopTimeout}); err != nil { - p.log.Warn("container stop failed", "id", c.ID[:12], "err", err) - } - if _, err := p.cli.ContainerRemove(context.WithoutCancel(ctx), c.ID, client.ContainerRemoveOptions{Force: true}); err != nil { - p.log.Warn("container remove failed", "id", c.ID[:12], "err", err) + if _, err := p.cli.ContainerStop(stopCtx, c.ID, client.ContainerStopOptions{Timeout: stopTimeout}); err != nil { + p.log.Warn("container stop failed", "id", c.ID[:12], "err", err) + } + if _, err := p.cli.ContainerRemove(context.WithoutCancel(ctx), c.ID, client.ContainerRemoveOptions{Force: true}); err != nil { + p.log.Warn("container remove failed", "id", c.ID[:12], "err", err) + } } + p.forgetTeardown(c.ID) p.mu.Lock() p.active-- diff --git a/internal/container/pool_test.go b/internal/container/pool_test.go index 4bf4f2a27..9f4561b12 100644 --- a/internal/container/pool_test.go +++ b/internal/container/pool_test.go @@ -416,10 +416,10 @@ func TestReleaseCancelsTheMaxUptimeTimer(t *testing.T) { // so nothing is left that could fire. The wait below is the observable // consequence, not the proof. pool.mu.Lock() - remaining := len(pool.reapers) + remaining := len(pool.teardowns) pool.mu.Unlock() if remaining != 0 { - t.Errorf("pool still holds %d armed reaper(s) after Release, want 0", remaining) + t.Errorf("pool still holds %d armed teardown entr(ies) after Release, want 0", remaining) } stopAfterRelease, removeAfterRelease := stopCalls.Load(), removeCalls.Load() @@ -495,3 +495,66 @@ func TestGracePeriodDoesNotExtendTheMaxUptimeCap(t *testing.T) { } <-released } + +// Timer.Stop cannot unwind a callback that has already begun, so cancelling +// is not enough on its own: teardown has to be claimed once, by whichever of +// the reaper and Release gets there first. Firing the reaper before Release +// is the deterministic stand-in for the two overlapping. +func TestReleaseAfterTheReaperFiredDoesNotTearDownTwice(t *testing.T) { + const containerID = "0f1e2d3c4b5a69780f1e2d3c4b5a69780f1e2d3c4b5a69780f1e2d3c4b5a6978" + + var stopCalls, removeCalls atomic.Int32 + reaped := make(chan struct{}, 1) + dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/containers/create"): + writeDockerJSON(t, w, map[string]any{"Id": containerID, "Warnings": []string{}}) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/start"): + w.WriteHeader(http.StatusNoContent) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/stop"): + stopCalls.Add(1) + w.WriteHeader(http.StatusNoContent) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID): + removeCalls.Add(1) + select { + case reaped <- struct{}{}: + default: + } + w.WriteHeader(http.StatusNoContent) + default: + http.Error(w, "unexpected Docker API path "+r.URL.Path, http.StatusNotFound) + } + })) + t.Cleanup(dockerAPI.Close) + + dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dockerClient.Close() }) + + pool := &Pool{ + cli: dockerClient, + cfg: Config{Image: "test/image", MaxUptime: 20 * time.Millisecond}, + log: discardLogger(), + } + + c, err := pool.Acquire(context.Background(), nil, nil) + if err != nil { + t.Fatalf("Acquire: %v", err) + } + + select { + case <-reaped: + case <-time.After(2 * time.Second): + t.Fatal("max uptime reaper never ran") + } + pool.Release(context.Background(), c) + + if got := stopCalls.Load(); got != 1 { + t.Errorf("stop called %d times, want 1: the reaper and Release both tore the container down", got) + } + if got := removeCalls.Load(); got != 1 { + t.Errorf("remove called %d times, want 1: the reaper and Release both tore the container down", got) + } +} diff --git a/internal/webui/event_pump_test.go b/internal/webui/event_pump_test.go index fcf9812ac..29f2d4712 100644 --- a/internal/webui/event_pump_test.go +++ b/internal/webui/event_pump_test.go @@ -183,37 +183,60 @@ func (f *flakyEventReader) EventsSince(context.Context, int64, int) ([]events.Ev // archie-ui binds before archie-state-store is guaranteed to be listening, so // the first prime is routinely refused. Returning on that error left the // activity feed history-only until the process was restarted by hand. -func TestPumpPrimingRetriesUntilTheStoreAnswers(t *testing.T) { - reader := &flakyEventReader{failures: 3} - pump := &eventPump{ - store: reader, - log: func(string, ...any) {}, - broadcast: func(events.Event) {}, - primeRetryMin: time.Millisecond, +func TestPumpPriming(t *testing.T) { + forever := 1 << 30 + + tests := []struct { + name string + // failures is how many EventsSince calls are refused before the + // store starts answering. + failures int + // deadline bounds the prime; zero means the test's own context, so + // priming runs until it succeeds. + deadline time.Duration + wantErr bool + wantCalls int // 0 means "unbounded, do not assert" + }{ + { + name: "retries until the store answers", + failures: 3, + wantCalls: 4, + }, + { + name: "gives up when the context ends", + failures: forever, + deadline: 20 * time.Millisecond, + wantErr: true, + }, } - if err := pump.primeWithRetry(t.Context()); err != nil { - t.Fatalf("primeWithRetry: %v", err) - } - if reader.calls != 4 { - t.Fatalf("EventsSince called %d times, want 4 (3 refusals then success)", reader.calls) - } -} + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + reader := &flakyEventReader{failures: tc.failures} + pump := &eventPump{ + store: reader, + log: func(string, ...any) {}, + broadcast: func(events.Event) {}, + primeRetryMin: time.Millisecond, + } -// A shutdown during the retry wait must end the pump, not hold the process -// open until the store appears. -func TestPumpPrimingStopsRetryingWhenTheContextEnds(t *testing.T) { - reader := &flakyEventReader{failures: 1 << 30} - pump := &eventPump{ - store: reader, - log: func(string, ...any) {}, - broadcast: func(events.Event) {}, - primeRetryMin: time.Millisecond, - } + ctx := t.Context() + if tc.deadline > 0 { + timed, cancel := context.WithTimeout(ctx, tc.deadline) + defer cancel() + ctx = timed + } - ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond) - defer cancel() - if err := pump.primeWithRetry(ctx); err == nil { - t.Fatal("primeWithRetry returned no error after the context ended") + err := pump.primeWithRetry(ctx) + if tc.wantErr && err == nil { + t.Fatal("primeWithRetry returned no error") + } + if !tc.wantErr && err != nil { + t.Fatalf("primeWithRetry: %v", err) + } + if tc.wantCalls > 0 && reader.calls != tc.wantCalls { + t.Fatalf("EventsSince called %d times, want %d", reader.calls, tc.wantCalls) + } + }) } }