diff --git a/deployments/systemd-user-service.md b/deployments/systemd-user-service.md index e8e94515b..9e78729ba 100644 --- a/deployments/systemd-user-service.md +++ b/deployments/systemd-user-service.md @@ -97,7 +97,8 @@ the dashboard's health endpoint behind the token. A watchdog can curl ```ini [Unit] Description=Archie UI Service -After=network.target +After=network.target archie-state-store.service +Wants=archie-state-store.service [Service] Type=simple @@ -121,6 +122,11 @@ GATEWAY_TOKEN=... # presented to archie-gateway STATE_STORE_TOKEN=... # presented to archie-state-store ``` +`After=` orders the start, it does not wait for the store to bind. The UI +process closes that gap itself: its event pump retries priming with backoff +until the State Store answers, so the activity feed goes live once the store +is up rather than staying history-only until the next restart. + ```ini ExecStart=%h/.local/bin/archie-ui -config %h/.config/archie/config.toml -token-file %h/.local/share/archie/web-token ``` diff --git a/internal/container/pool.go b/internal/container/pool.go index 18d3e583f..0006c58a9 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -88,6 +88,9 @@ type Pool struct { mu sync.Mutex active int + // 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. @@ -237,13 +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 is keyed to the container ID and never -// touches p.active: Release (or Close) remains the only owner of the active -// slot. Docker stop and remove are idempotent, so a timer that fires after -// Release has already removed the container only logs a warning. +// lifetime cap elapses. The timer never touches p.active: Release (or Close) +// remains the only owner of the active slot. func (p *Pool) armMaxUptime(ctx context.Context, id string) { - time.AfterFunc(p.cfg.MaxUptime, func() { + timer := time.AfterFunc(p.cfg.MaxUptime, func() { + if !p.claimTeardown(id) { + return + } + defer p.forgetTeardown(id) zero := 0 stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) defer cancel() @@ -254,6 +272,49 @@ func (p *Pool) armMaxUptime(ctx context.Context, id string) { p.log.Warn("max uptime remove failed", "id", id[:12], "err", err) } }) + + p.mu.Lock() + defer p.mu.Unlock() + p.teardownLocked(id).timer = timer +} + +// 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() + 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 t != nil && t.timer != nil { + t.timer.Stop() + } +} + +// 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 @@ -290,21 +351,29 @@ func (p *Pool) Release(ctx context.Context, c *Container) { time.Sleep(p.cfg.GracePeriod) } - // 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() + // 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() - 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 645d21114..9f4561b12 100644 --- a/internal/container/pool_test.go +++ b/internal/container/pool_test.go @@ -367,3 +367,194 @@ func TestAcquireEnforcesMaxUptime(t *testing.T) { t.Fatalf("expected at least one stop and remove, got stop=%d remove=%d", stopCalls.Load(), removeCalls.Load()) } } + +// A released container is already gone, so its max-uptime reaper has nothing +// left to reap. Leaving the timer armed made it fire an hour later against a +// dead ID, logging "max uptime stop failed ... No such container" as though +// teardown had gone wrong. +func TestReleaseCancelsTheMaxUptimeTimer(t *testing.T) { + const containerID = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210" + + var stopCalls, removeCalls atomic.Int32 + 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) + 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: 60 * time.Millisecond}, + log: discardLogger(), + } + + c, err := pool.Acquire(context.Background(), nil, nil) + if err != nil { + t.Fatalf("Acquire: %v", err) + } + pool.Release(context.Background(), c) + + // Deterministic half: the reaper is disarmed and its bookkeeping dropped, + // so nothing is left that could fire. The wait below is the observable + // consequence, not the proof. + pool.mu.Lock() + remaining := len(pool.teardowns) + pool.mu.Unlock() + if remaining != 0 { + t.Errorf("pool still holds %d armed teardown entr(ies) after Release, want 0", remaining) + } + + stopAfterRelease, removeAfterRelease := stopCalls.Load(), removeCalls.Load() + time.Sleep(200 * time.Millisecond) + + if got := stopCalls.Load(); got != stopAfterRelease { + t.Errorf("stop called %d times after Release, want %d: the max uptime timer still fired", got, stopAfterRelease) + } + if got := removeCalls.Load(); got != removeAfterRelease { + t.Errorf("remove called %d times after Release, want %d: the max uptime timer still fired", got, removeAfterRelease) + } +} + +// MaxUptime is a hard lifetime cap from creation, enforced "regardless of +// task state" (Config.MaxUptime). A grace period is task state, so a +// container that outlives the cap while waiting out its grace window is still +// reaped: cancelling the reaper before the grace sleep would extend the cap +// by GracePeriod. +func TestGracePeriodDoesNotExtendTheMaxUptimeCap(t *testing.T) { + const containerID = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789" + + stopped := make(chan struct{}, 4) + 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"): + select { + case stopped <- struct{}{}: + default: + } + w.WriteHeader(http.StatusNoContent) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID): + 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: 30 * time.Millisecond, GracePeriod: 2 * time.Second}, + log: discardLogger(), + } + + c, err := pool.Acquire(context.Background(), nil, nil) + if err != nil { + t.Fatalf("Acquire: %v", err) + } + + released := make(chan struct{}) + go func() { + defer close(released) + pool.Release(context.Background(), c) + }() + + // The cap must bite while Release is still sleeping out the grace period. + select { + case <-stopped: + case <-released: + t.Fatal("Release returned before the max uptime cap fired; the grace period extended the cap") + case <-time.After(time.Second): + t.Fatal("max uptime cap never fired during the grace period") + } + <-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.go b/internal/webui/event_pump.go index 3f7d46658..ce3d35600 100644 --- a/internal/webui/event_pump.go +++ b/internal/webui/event_pump.go @@ -22,6 +22,14 @@ const ( eventPumpPageSize = 200 ) +// Backoff bounds for priming. The UI process and the State Store are separate +// units with no ordering between them, so a refused dial at startup is +// ordinary rather than fatal and the pump waits the store out. +const ( + eventPumpPrimeRetryMin = 250 * time.Millisecond + eventPumpPrimeRetryMax = 30 * time.Second +) + // eventPump is the UI process's substitute for the daemon's in-process event // bus. The daemon hands persisted events to Server.Broadcast from its own bus // subscription (internal/app/archied/main.go's persistAndBroadcastEvents); a @@ -42,6 +50,36 @@ type eventPump struct { // watermark is the highest event id already handed to broadcast. It only // ever moves forward, and only past an event that was delivered. watermark int64 + // primeRetryMin is the first backoff between priming attempts. Zero + // means eventPumpPrimeRetryMin; a test sets it small. + primeRetryMin time.Duration +} + +// primeWithRetry primes, retrying with capped exponential backoff until it +// succeeds or ctx ends. Returning on the first error instead left the +// activity feed history-only for the life of the process whenever the UI won +// the startup race against the State Store. +func (p *eventPump) primeWithRetry(ctx context.Context) error { + delay := p.primeRetryMin + if delay <= 0 { + delay = eventPumpPrimeRetryMin + } + for attempt := 1; ; attempt++ { + err := p.prime(ctx) + if err == nil { + return nil + } + if ctx.Err() != nil { + return err + } + p.log("event pump priming failed; retrying", "attempt", attempt, "retry_in", delay, "err", err) + select { + case <-ctx.Done(): + return err + case <-time.After(delay): + } + delay = min(delay*2, eventPumpPrimeRetryMax) + } } // eventReader is the one method the pump needs, so a test can drive it @@ -65,7 +103,7 @@ func (s *Server) PumpEvents(ctx context.Context, interval time.Duration) error { interval = DefaultEventPollInterval } pump := s.newEventPump() - if err := pump.prime(ctx); err != nil { + if err := pump.primeWithRetry(ctx); err != nil { return fmt.Errorf("prime event pump: %w", err) } pump.run(ctx, interval) diff --git a/internal/webui/event_pump_test.go b/internal/webui/event_pump_test.go index 181d01a1d..29f2d4712 100644 --- a/internal/webui/event_pump_test.go +++ b/internal/webui/event_pump_test.go @@ -3,6 +3,7 @@ package webui import ( "bufio" "context" + "errors" "net/http" "net/http/httptest" "strings" @@ -162,3 +163,80 @@ func openSSEStream(t *testing.T, ctx context.Context, ts *httptest.Server) <-cha }() return lines } + +// flakyEventReader fails its first failures calls, then answers an empty +// table. It stands in for the State Store during the window where the UI +// process is up and the store has not bound its listener yet. +type flakyEventReader struct { + failures int + calls int +} + +func (f *flakyEventReader) EventsSince(context.Context, int64, int) ([]events.Event, error) { + f.calls++ + if f.calls <= f.failures { + return nil, errors.New("connection refused") + } + return nil, nil +} + +// 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 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, + }, + } + + 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, + } + + ctx := t.Context() + if tc.deadline > 0 { + timed, cancel := context.WithTimeout(ctx, tc.deadline) + defer cancel() + ctx = timed + } + + 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) + } + }) + } +}