activator: rootfs rows refused before the lease, and, for the agent's life, after a startup sweep that did not prove every leftover gone; unless overlap swaps are armed and the box's rootfs gates pass; first boot places an empty database; never boot empty after serving
Plan 3 Task 7. The admission (rootfsRefusalLocked under a.mu, then the backend's rootfsStartable off it, shared per host under the service's lifetime) runs in begin before an entry is made and in doWake before step 0.5 (and before the claim path), so an unknown runtime on any row, an unarmed or unswept box and each of Plan 2's gate reasons take no lease, restore or live-link materialization. ArmRootfs is called once the overlap scheduler arms; MarkRootfsSwept only from a clean startup sweep. SplitBackend forwards rootfsStartable and PlaceRootfsDB. Rootfs gate I/O derives its deadlines from the caller's ctx. A served rootfs row that restores fresh refuses (RFS-3-C15); a first boot gets D7's empty WAL database (RENAME_NOREPLACE, pinned by identity) and its first upload; a rootfs row's restored database is checked without the table count, so the placeholder restores. firstWakeBudgetFor gives a rootfs planned first wake its own bound. RFS-3-C12, C14, C15 built.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
25 files changed,
+2,059
−63
approved_rootfs_copy_test.go+4 −0internal/activator/activator.go+129 −6internal/activator/activator_test.go+12 −0internal/activator/backend_exec.go+7 −5internal/activator/backend_unit.go+26 −0internal/activator/logsink.go+10 −0internal/activator/production_backend_test.go+122 −0internal/activator/rootfs.go+17 −8internal/activator/rootfs_gate_test.go+621 −0internal/activator/rootfs_invariants_test.go+8 −0internal/activator/rootfs_service.go+284 −0internal/activator/rootfs_staged_test.go+8 −0internal/activator/rootfs_test.go+11 −8internal/activator/rootfsdb.go+224 −0internal/activator/rootfsdb_test.go+319 −0internal/activator/wakeplan.go+1 −1internal/host/agent.go+1 −6internal/host/layoutleg.go+27 −0internal/host/rollout.go+4 −0internal/host/rootfsplacement.go+33 −19internal/host/rootfsplacement_test.go+11 −8internal/host/rootfsstart_test.go+1 −1internal/host/startupsweep_test.go+168 −0internal/rolloutwords/words.go+9 −0internal/rolloutwords/words_test.go+2 −1
diff --git a/approved_rootfs_copy_test.go b/approved_rootfs_copy_test.go| index 8993f0c32..a9774f751 100644 |
| --- a/approved_rootfs_copy_test.go |
| +++ b/approved_rootfs_copy_test.go |
| @@ -180,6 +180,10 @@ var rootfsCopyBuilt = []string{ |
| "RFS-2-C01", "RFS-2-C02", "RFS-2-C03", "RFS-2-C04", "RFS-2-C05", "RFS-2-C06", "RFS-2-C11", "RFS-2-C12", |
| // Plan 2 Task 9: the agent's rootfs start (internal/activator/rootfs.go) |
| "RFS-2-C09", |
| + // Plan 3 Task 7: the rootfs refusal event and its unarmed reason |
| + // (internal/rolloutwords/words.go), the served-never-empty reason |
| + // (internal/activator/rootfs_service.go) |
| + "RFS-3-C12", "RFS-3-C14", "RFS-3-C15", |
| } |
| func mustParseRootfsRecord(t *testing.T) []copyRow { |
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index ad8e23ab5..2e76f7893 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -468,6 +468,11 @@ const ( |
| type actEntry struct { |
| claimResult *wokenInstance |
| + // rootfsAdmitted: begin made this entry right after the backend's |
| + // rootfs gates passed for it (rootfsStartRefusal), so doWake asks only |
| + // the cheap locked half again (rootfsWakeRefusal). Set at construction, |
| + // before the wake goroutine starts; never written again. |
| + rootfsAdmitted bool |
| // probe is set for an entry ProbeWake made (moves Plan 3 Task 5): the |
| // claim path runs with the probe's policy, and the entry is held for |
| // the move while its registry row is. |
| @@ -1284,6 +1289,21 @@ type Service struct { |
| // gens is the generations switch (SetGenerations) as read at New. Off: |
| // every spawn binds the canonical socket and no retire hook fires. |
| gens bool |
| + // rootfsArmed (ArmRootfs) and rootfsSwept (MarkRootfsSwept) open the |
| + // rootfs admission (rootfs apps Plan 3 Task 7, rootfs_service.go): the |
| + // overlap scheduler armed on this boot, and a startup sweep that proved |
| + // every leftover unit gone. Each is set once by internal/host and never |
| + // cleared. |
| + rootfsArmed atomic.Bool |
| + rootfsSwept atomic.Bool |
| + // rootfsGateMu guards rootfsGateRuns (one ask of the backend's rootfs |
| + // gates per host in flight, rootfsBackendGates) and rootfsRefusedSeen |
| + // (the last early refusal reported per host, noteRootfsRefusal). A leaf |
| + // lock: nothing is called while it is held, and a.mu is never taken |
| + // under it. |
| + rootfsGateMu sync.Mutex |
| + rootfsGateRuns map[string]*rootfsGateRun |
| + rootfsRefusedSeen map[string]string |
| // cacheGens is host -> *atomic.Uint64, the newest generation that has |
| // been current for that host (CacheGen). A sync.Map, never under a.mu: |
| // the edge cache reads it while holding the cache's own lock. |
| @@ -1513,6 +1533,10 @@ func (a *Service) begin(ctx context.Context, rt registry.Route, stamp bool, req |
| return nil, err |
| } |
| extended := false |
| + // gated: this request asked the backend's rootfs gates for rt (off |
| + // a.mu) and they passed; the next pass of the loop may make the entry. |
| + // Spent on that pass, whatever it finds. |
| + gated := false |
| for { |
| a.mu.Lock() |
| if a.fences[rt.Host] != 0 { |
| @@ -1531,7 +1555,40 @@ func (a *Service) begin(ctx context.Context, rt registry.Route, stamp bool, req |
| return nil, errShuttingDown |
| } |
| e := a.entries[rt.Host] |
| + admitted := gated |
| + gated = false |
| if e == nil { |
| + // The rootfs admission (Plan 3 Task 7, INV-3), before an entry |
| + // is made, so a refused row never reaches Acquire, Restore or |
| + // the live link: the locked half here; for a rootfs row, the |
| + // backend's gates off a.mu (they may do I/O), then the loop |
| + // again from the top, where an entry another request made |
| + // meanwhile is coalesced on. An awake or waking host's requests |
| + // never pay the gates. |
| + if err := a.rootfsRefusalLocked(rt); err != nil { |
| + a.mu.Unlock() |
| + err = notAdmitted(err) |
| + a.noteRootfsRefusal(rt, err) |
| + return nil, err |
| + } |
| + if rt.Rootfs() && !admitted { |
| + a.mu.Unlock() |
| + // Within this request's own wait bound, like the wait on a |
| + // wake: a gate that outlasts it answers errWakeTimeout. |
| + gctx, cancel := context.WithDeadline(ctx, arrival.Add(wakeWaitBound)) |
| + err := a.rootfsStartRefusal(gctx, rt) |
| + cancel() |
| + if err != nil { |
| + if errors.Is(err, errRootfsNotAdmitted) { |
| + a.noteRootfsRefusal(rt, err) |
| + } else if ctx.Err() == nil && errors.Is(err, context.DeadlineExceeded) { |
| + err = errWakeTimeout |
| + } |
| + return nil, err |
| + } |
| + gated = true |
| + continue |
| + } |
| // Asleep → kick off ONE wake; this request and any latecomers all |
| // coalesce on e.ready rather than racing a second lease claim |
| // (singleflight). The wake runs detached so even its initiator is |
| @@ -1544,7 +1601,7 @@ func (a *Service) begin(ctx context.Context, rt registry.Route, stamp bool, req |
| // found nothing and started a second wake — two lease acquires |
| // and two restore attempts per request (#184, seen only as a |
| // loaded-suite test flake because the window is that narrow). |
| - e = &actEntry{host: rt.Host, route: rt, state: actWaking, ready: make(chan struct{})} |
| + e = &actEntry{host: rt.Host, route: rt, state: actWaking, ready: make(chan struct{}), rootfsAdmitted: admitted} |
| a.entries[rt.Host] = e |
| go a.wake(e) |
| edge.MarkWoke(req) |
| @@ -1617,8 +1674,9 @@ func (a *Service) beginRequest(ctx context.Context, rt registry.Route) (release |
| // awaitWake is a waiter's wait on one wake: begin's and WakeWorker's. It |
| // returns nil once ready closes (the caller then reads e.err), ctx.Err(), or |
| // errWakeTimeout at the deadline. A first wake onto a new build gives its |
| -// waiters arrival + firstWakeBudget (zero-downtime spec §8.2): enough for |
| -// B's health window, B's kill and the good build's boot. Only that kind of |
| +// waiters arrival + firstWakeBudgetFor (zero-downtime spec §8.2): enough for |
| +// B's health window, B's kill and the good build's boot (a rootfs row's |
| +// window is its own health bound, Plan 3 Task 7). Only that kind of |
| // wake (firstWake is set only by a planner, flag on), and once per caller: |
| // *extended carries across the caller's loop. |
| // |
| @@ -1636,13 +1694,13 @@ func (a *Service) awaitWake(ctx context.Context, e *actEntry, ready <-chan struc |
| return ctx.Err() |
| case <-deadline.C: |
| a.mu.Lock() |
| - fw := e.firstWake |
| + fw, rt := e.firstWake, e.route |
| a.mu.Unlock() |
| if !fw || *extended { |
| return errWakeTimeout |
| } |
| *extended = true |
| - deadline.Reset(time.Until(arrival.Add(firstWakeBudget))) |
| + deadline.Reset(time.Until(arrival.Add(firstWakeBudgetFor(rt)))) |
| if wakeBoundExtended != nil { |
| wakeBoundExtended() |
| } |
| @@ -1837,7 +1895,11 @@ func (a *Service) wake(e *actEntry) { |
| // the generation detail is the operator's. |
| log.Printf("activator: %s: wake failed and its generation is not proven stopped: %v", e.host, err) |
| } |
| - if msg, ok := a.wakeFailureEvent(e, err); ok { |
| + if errors.Is(err, errRootfsNotAdmitted) { |
| + // Refused before the lease (Plan 3 Task 7): reported once per |
| + // change, not on every attempt. |
| + a.noteRootfsRefusal(e.route, err) |
| + } else if msg, ok := a.wakeFailureEvent(e, err); ok { |
| emitEvent(a.Logs, e.route, "error", msg) |
| } |
| } else { |
| @@ -2137,6 +2199,14 @@ type wokenInstance struct { |
| // them here without a.mu is safe by construction. |
| func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, error) { |
| if a.cfg.HostWrites.Enabled { |
| + // The rootfs admission before the claim path's lease too (INV-3): |
| + // an unknown runtime, or a rootfs row this box refuses, takes |
| + // nothing (Plan 2's gates also refuse every rootfs row here). |
| + if err := a.rootfsWakeRefusal(ctx, e, e.route); err != nil { |
| + w := &wokenInstance{stopOutcome: &stopObservation{}} |
| + w.stopOutcome.notStarted() // nothing taken, nothing started |
| + return w, err |
| + } |
| return a.doClaimWake(ctx, e) |
| } |
| rt := e.route |
| @@ -2182,6 +2252,19 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| a.mu.Unlock() |
| } |
| + // 0.4. The rootfs admission (rootfs apps Plan 3 Task 7, INV-3), on the |
| + // row just refreshed, off a.mu and before anything below: an unknown |
| + // runtime on any row, and a rootfs row this box refuses (unarmed, the |
| + // startup sweep unproven, or any of Plan 2's gates through the |
| + // backend's rootfsStartable), is refused before Acquire, Restore and |
| + // the live link's materialization. It covers every wake that did not |
| + // come through begin's own ask: due wakes, planned and pinned wakes, |
| + // workers and probes. The refusal holds no lease, so nothing waits on a |
| + // TTL. Plan 2's gates still run inside Start as the second line. |
| + if err := a.rootfsWakeRefusal(ctx, e, rt); err != nil { |
| + return w, err |
| + } |
| + |
| // 0.5. Refuse a fenced or conflicting row before it ever reaches Acquire |
| // or Restore (design §6.8). The in-Start/in-Seed refusal below still |
| // exists as the second line of defense, but by the time either of those |
| @@ -2352,6 +2435,33 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| return w, ErrFenced |
| } |
| + // 2a. A rootfs row never boots empty after serving (Plan 3 Task 7, |
| + // Review Focus 4): fresh (no local database, no replica) on a row with |
| + // a good build is a lost database, not a first boot, so nothing starts |
| + // and the lease goes back. A first boot (no good build yet) gets the |
| + // empty SQLite database of D7 instead, under this lease and before |
| + // anything runs, so an app that never opens CARLOS_DB still leaves a |
| + // database to replicate (Review Focus 8). A binary row has its seed and |
| + // creates its own file, and never takes this path. |
| + placed := false |
| + if fresh && rt.Rootfs() { |
| + if rt.GoodVersion != "" { |
| + w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease) |
| + return w, refuseRootfs(fmt.Errorf("%s: %w", host, errRootfsReplicaMissing)) |
| + } |
| + if err := a.placeRootfsDB(ctx, rt); err != nil { |
| + w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease) |
| + return w, err |
| + } |
| + placed = true |
| + log.Printf("activator: %s: first boot: placed an empty database before the start", host) |
| + w.steps.mark(a.now(), "placeholder") |
| + if ctx.Err() != nil || !a.wakeAllowed(host) { |
| + w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease) |
| + return w, ErrFenced |
| + } |
| + } |
| + |
| // 2b. One executable identity for this wake (settings spec §4.2, Astra |
| // I1 #5): chosen now, recorded now, under the lease taken in step 1 and |
| // before the seed and the spawn, and the only file this wake runs, its |
| @@ -2657,6 +2767,12 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| log.Printf("activator: %s: seed placement not recorded yet: %v", host, err) |
| } |
| } |
| + // 5c. The placeholder's first upload (D7), in 5b's shape: the replica |
| + // holds a database before the scheduler can record this build as good. |
| + // A failure only logs (syncRootfsPlaceholder). |
| + if placed { |
| + syncRootfsPlaceholder(ctx, host, rep) |
| + } |
| w.steps.mark(a.now(), "replicate") |
| // 6. Co-spawn the sidecar, last — only once the instance is healthy and |
| @@ -5545,6 +5661,13 @@ func (a *Service) serveWakeError(w http.ResponseWriter, r *http.Request, rt regi |
| http.Error(w, "instance is waking; retry shortly", http.StatusServiceUnavailable) |
| case errors.Is(err, context.Canceled): |
| // The client hung up while queued; nothing to write. |
| + case errors.Is(err, errRootfsNotAdmitted): |
| + // A rootfs row this box refused before the lease (Plan 3 Task 7): |
| + // today's text. Quiet here, like the config guard: the refusal is |
| + // logged, and for unarmed sent as the member's event, once per |
| + // change (noteRootfsRefusal), not once per request. |
| + edge.MarkAnswered(r) |
| + http.Error(w, "instance failed to wake", http.StatusServiceUnavailable) |
| default: |
| // The wake failure is already the member's platform log error |
| // (this log line, shipped by logsink.go); marking it keeps the |
diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go| index 9cd88dbfd..939448dd6 100644 |
| --- a/internal/activator/activator_test.go |
| +++ b/internal/activator/activator_test.go |
| @@ -49,6 +49,9 @@ type fakeRep struct { |
| err error |
| closed bool |
| closes int |
| + // syncs counts SyncAndWait calls (a first upload asked for: SeedPlaced, |
| + // Plan 3 Task 7's placeholder). |
| + syncs int |
| // b, when set, is bumped on Close. production's Rep.Close "does the |
| // final checkpoint/sync and releases the lease" (Rep's doc comment), so |
| // a successful Close is the fake's equivalent of the lease coming free |
| @@ -504,6 +507,15 @@ type fakeBackend struct { |
| // ident is the identity capability (settings spec §4.2, Task 5c), |
| // opted into per test (wakeidentity_test.go). Guarded by mu. |
| ident identityFake |
| + |
| + // Rootfs apps Plan 3 Task 7 (rootfs_gate_test.go). startable is the |
| + // backend's early rootfs gates' answer (nil passes) and startableAsks |
| + // counts them per host; placeholders counts PlaceRootfsDB calls, which |
| + // answer placeErr. |
| + startable func(ctx context.Context, rt registry.Route) error |
| + startableAsks map[string]int |
| + placeholders int |
| + placeErr error |
| } |
| // Layout is fakeBackend's Classifier implementation, always present so |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index b88aab5a4..2f23552e0 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -214,9 +214,11 @@ type ExecBackend struct { |
| // host.RootfsPlacementAllowed with the box's facts: every rule a |
| // rootfs row must meet before this box starts it (spec §5.7). Nil, |
| // either one: no rootfs row starts here (rootfs apps plan 2; wired by |
| - // Task 8, read by Task 9's start path). |
| - RootfsOK func() error |
| - RootfsPlacement func(rt registry.Route) error |
| + // Task 8, read by Task 9's start path). Each does I/O bounded by the |
| + // ctx it is handed (Plan 3 Task 7: the Service asks them before the |
| + // lease, off a.mu, under the service's lifetime). |
| + RootfsOK func(ctx context.Context) error |
| + RootfsPlacement func(ctx context.Context, rt registry.Route) error |
| // Seeds reads a seed's snapshot from this region's data bucket |
| // (seeded-instances spec §3.4). Nil: no seed can be placed here, and a |
| // seeded row's wake fails rather than starting empty. |
| @@ -869,7 +871,7 @@ func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool |
| // that never had a snapshot — and the alternatives to failing here are |
| // both worse than a down route: serving a corrupt database, or (if |
| // this returned fresh) running the route's seed over recoverable data. |
| - if err := lease.CheckDB(dbPath); err != nil { |
| + if err := restoredDBCheck(rt)(dbPath); err != nil { |
| q := dbPath + quarantineSuffix |
| _ = os.Remove(q) // keep exactly one: the newest failure is the evidence |
| if mvErr := os.Rename(dbPath, q); mvErr != nil { |
| @@ -1887,7 +1889,7 @@ func (b *ExecBackend) BuildIdentity(rt registry.Route, build string) (release.St |
| // it is nested or it does not start. |
| func (b *ExecBackend) Start(ctx context.Context, rt registry.Route) (Proc, string, error) { |
| if rt.Runtime == registry.RuntimeRootfsV1 { |
| - if err := b.rootfsGates(rt); err != nil { |
| + if err := b.rootfsGates(ctx, rt); err != nil { |
| return nil, "", err |
| } |
| proc, id, err := b.startRootfsFromLive(ctx, rt, rt.Socket, 0) |
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go| index e6b64abb3..0fb737811 100644 |
| --- a/internal/activator/backend_unit.go |
| +++ b/internal/activator/backend_unit.go |
| @@ -319,6 +319,32 @@ func (b *SplitBackend) SeedPlaced(ctx context.Context, rt registry.Route, rep Re |
| } |
| return nil |
| } |
| + |
| +// rootfsStartable forwards the early rootfs gates (Plan 3 Task 7) to the |
| +// exec side, which answers its rootfsGates. A unit-backed row, or an exec |
| +// side without the gates, is refused: there is no unchecked path, and an |
| +// interface only ExecBackend implements would otherwise be invisible here |
| +// (Astra R1 4). |
| +func (b *SplitBackend) rootfsStartable(ctx context.Context, rt registry.Route) error { |
| + if rt.Backing != registry.BackingUnit { |
| + if s, ok := b.Exec.(rootfsStartable); ok { |
| + return s.rootfsStartable(ctx, rt) |
| + } |
| + } |
| + return refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoRootfsControl)) |
| +} |
| + |
| +// PlaceRootfsDB forwards a rootfs first boot's database (D7) to the exec |
| +// side. A unit-backed row, or an exec side without it, is errNoRootfsDB. |
| +func (b *SplitBackend) PlaceRootfsDB(ctx context.Context, rt registry.Route) error { |
| + if rt.Backing != registry.BackingUnit { |
| + if p, ok := b.Exec.(rootfsDBPlacer); ok { |
| + return p.PlaceRootfsDB(ctx, rt) |
| + } |
| + } |
| + return fmt.Errorf("%s: %w", rt.Host, errNoRootfsDB) |
| +} |
| + |
| func (b *SplitBackend) Restore(ctx context.Context, rt registry.Route) (bool, error) { |
| return b.pick(rt).Restore(ctx, rt) |
| } |
diff --git a/internal/activator/logsink.go b/internal/activator/logsink.go| index 6a7bc6749..3cbe909f6 100644 |
| --- a/internal/activator/logsink.go |
| +++ b/internal/activator/logsink.go |
| @@ -137,6 +137,16 @@ func memberSafeWakeReason(err error) string { |
| // N1). |
| err = ErrFenced |
| } |
| + if errors.Is(err, errRootfsReplicaMissing) { |
| + // A rootfs row that has served, with no database and no replica |
| + // (Plan 3 Task 7): RFS-3-C15, whole. |
| + return "wake failed: " + rootfsReplicaMissingText |
| + } |
| + if errors.Is(err, errRootfsUnarmed) { |
| + // A rootfs row on a box whose overlap scheduler has not armed (Plan |
| + // 3 Task 7, D2): RFS-3-C12 with RFS-3-C14, the wake event's words. |
| + return rootfsUnarmedEvent() |
| + } |
| if errors.Is(err, ErrBuildNotPublished) { |
| // A worker wake refused because its build could not be published |
| // before the exec (plan 4's ErrBuildNotPublished, flag on or off). |
diff --git a/internal/activator/production_backend_test.go b/internal/activator/production_backend_test.go| new file mode 100644 |
| index 000000000..519fe7e78 |
| --- /dev/null |
| +++ b/internal/activator/production_backend_test.go |
| @@ -0,0 +1,122 @@ |
| +package activator |
| + |
| +// The production composition (internal/host/agent.go builds the Service |
| +// over a SplitBackend whose fields promote nothing), so every interface |
| +// Plan 3 adds must be implemented on SplitBackend itself [Astra R1 4]. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// productionBackend is the composition agent.go builds: eb on the exec |
| +// side, a UnitBackend on the unit side. |
| +func productionBackend(t *testing.T, eb *ExecBackend) *SplitBackend { |
| + t.Helper() |
| + return &SplitBackend{Exec: eb, Unit: &UnitBackend{OptDir: eb.OptDir}} |
| +} |
| + |
| +// TestProductionBackendImplementsRootfsSeams: the production composition |
| +// satisfies every interface Plan 3 adds, and a unit-backed row is refused |
| +// by each. Task D (ProcessReader), R1 (ReleaseBackend) and W1 |
| +// (RootfsWorkerBackend) add their rows. |
| +func TestProductionBackendImplementsRootfsSeams(t *testing.T) { |
| + t.Parallel() |
| + eb, _ := newRootfsBackend(t) |
| + var b Backend = productionBackend(t, eb) |
| + unit := rootfsRoute(eb) |
| + unit.Backing = registry.BackingUnit |
| + rows := map[string]func() error{ |
| + "rootfsStartable": func() error { |
| + s, ok := b.(rootfsStartable) |
| + if !ok { |
| + t.Fatal("SplitBackend is not a rootfsStartable") |
| + } |
| + return s.rootfsStartable(context.Background(), unit) |
| + }, |
| + "rootfsDBPlacer": func() error { |
| + p, ok := b.(rootfsDBPlacer) |
| + if !ok { |
| + t.Fatal("SplitBackend is not a rootfsDBPlacer") |
| + } |
| + return p.PlaceRootfsDB(context.Background(), unit) |
| + }, |
| + } |
| + for name, refusal := range rows { |
| + if err := refusal(); err == nil { |
| + t.Errorf("%s: a unit-backed rootfs row was not refused", name) |
| + } |
| + } |
| + if err := rows["rootfsStartable"](); !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) { |
| + t.Errorf("rootfsStartable on a unit row = %v, want a marked errNoRootfsControl", err) |
| + } |
| + if err := rows["rootfsDBPlacer"](); !errors.Is(err, errNoRootfsDB) { |
| + t.Errorf("PlaceRootfsDB on a unit row = %v, want errNoRootfsDB", err) |
| + } |
| + // An exec row is forwarded: the exec side's own answers. |
| + if err := b.(rootfsStartable).rootfsStartable(context.Background(), rootfsRoute(eb)); err != nil { |
| + t.Errorf("rootfsStartable on the exec side's passing row = %v", err) |
| + } |
| +} |
| + |
| +// countingSplit is the production composition with the lease and the |
| +// restore counted (and refused: nothing here may reach S3). |
| +type countingSplit struct { |
| + *SplitBackend |
| + mu sync.Mutex |
| + acquires, restores int |
| +} |
| + |
| +func (b *countingSplit) Acquire(context.Context, registry.Route) (Lease, error) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + b.acquires++ |
| + return nil, errors.New("no lease in this test") |
| +} |
| + |
| +func (b *countingSplit) Restore(context.Context, registry.Route) (bool, error) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + b.restores++ |
| + return false, errors.New("no restore in this test") |
| +} |
| + |
| +// Through the production composition: an ExecBackend whose rootfs probe |
| +// fails refuses the wake before Acquire (the early gate reaches the exec |
| +// side through SplitBackend), and a unit-backed rootfs row is refused by |
| +// SplitBackend's own rootfsStartable. |
| +func TestRootfsGatesThroughTheProductionBackend(t *testing.T) { |
| + eb, ctl := newRootfsBackend(t) |
| + eb.RootfsOK = func(context.Context) error { return errors.New("root-image fail") } |
| + cb := &countingSplit{SplitBackend: productionBackend(t, eb)} |
| + a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, cb, nil) |
| + a.gens = true |
| + armRootfsForTest(a) |
| + t.Cleanup(func() { a.Shutdown(context.Background()) }) |
| + rt := rootfsRoute(eb) |
| + for _, wake := range []func() error{ |
| + func() error { _, err := a.beginRequest(context.Background(), rt); return err }, |
| + func() error { return dueWake(a, rt) }, |
| + } { |
| + err := wake() |
| + if err == nil || !errors.Is(err, errRootfsNotAdmitted) || !errors.Is(err, errRootfsRefused) { |
| + t.Fatalf("wake = %v, want the probe's refusal before the lease", err) |
| + } |
| + } |
| + if cb.acquires != 0 || cb.restores != 0 { |
| + t.Fatalf("acquires %d, restores %d: the refusal came after the lease", cb.acquires, cb.restores) |
| + } |
| + if calls := ctl.callList(); len(calls) != 0 { |
| + t.Fatalf("root was asked %v", calls) |
| + } |
| + unit := rt |
| + unit.Backing = registry.BackingUnit |
| + if err := cb.rootfsStartable(context.Background(), unit); !errors.Is(err, errNoRootfsControl) { |
| + t.Fatalf("a unit-backed rootfs row: %v, want errNoRootfsControl", err) |
| + } |
| +} |
diff --git a/internal/activator/rootfs.go b/internal/activator/rootfs.go| index 91c575a27..0b63a70d0 100644 |
| --- a/internal/activator/rootfs.go |
| +++ b/internal/activator/rootfs.go |
| @@ -124,12 +124,21 @@ func (b *ExecBackend) rootfsControl() (RootfsControl, error) { |
| // RootfsOK or RootfsPlacement refuses. It runs before LiveIdentity, so a |
| // refused start never materializes the live link (whose hook relays a |
| // stage to root), binds a listener, writes a launch file or asks root |
| -// anything. Every refusal is marked errRootfsRefused. |
| -func (b *ExecBackend) rootfsGates(rt registry.Route) error { |
| - return refuseRootfs(b.rootfsGateCheck(rt)) |
| +// anything. Every refusal is marked errRootfsRefused. ctx bounds the two |
| +// gates that do I/O (the readiness ask, the owner read): the Service asks |
| +// them before the lease (rootfsStartable) under its own bound. |
| +func (b *ExecBackend) rootfsGates(ctx context.Context, rt registry.Route) error { |
| + return refuseRootfs(b.rootfsGateCheck(ctx, rt)) |
| } |
| -func (b *ExecBackend) rootfsGateCheck(rt registry.Route) error { |
| +// rootfsStartable is the Service's early ask of rootfsGates (Plan 3 Task |
| +// 7, INV-3): the same gates, before Acquire, Restore and LiveIdentity, so |
| +// a refused rootfs row takes no lease and materializes nothing. |
| +func (b *ExecBackend) rootfsStartable(ctx context.Context, rt registry.Route) error { |
| + return b.rootfsGates(ctx, rt) |
| +} |
| + |
| +func (b *ExecBackend) rootfsGateCheck(ctx context.Context, rt registry.Route) error { |
| if err := b.nestedReady(rt); err != nil { |
| return err |
| } |
| @@ -143,13 +152,13 @@ func (b *ExecBackend) rootfsGateCheck(rt registry.Route) error { |
| if b.RootfsOK == nil { |
| return fmt.Errorf("%s: %w: no rootfs probe on this box", rt.Host, errNoRootfsControl) |
| } |
| - if err := b.RootfsOK(); err != nil { |
| + if err := b.RootfsOK(ctx); err != nil { |
| return fmt.Errorf("%s: refusing to wake a rootfs instance: %w", rt.Host, err) |
| } |
| if b.RootfsPlacement == nil { |
| return fmt.Errorf("%s: %w: no rootfs placement check on this box", rt.Host, errNoRootfsControl) |
| } |
| - if err := b.RootfsPlacement(rt); err != nil { |
| + if err := b.RootfsPlacement(ctx, rt); err != nil { |
| return fmt.Errorf("%s: %w", rt.Host, err) |
| } |
| if b.Cfg.HostWrites.Enabled { |
| @@ -197,7 +206,7 @@ func (b *ExecBackend) startRootfsFromLive(ctx context.Context, rt registry.Route |
| // was asked to run (Astra R1 3), so stagedIdentityOf never refuses a rootfs |
| // generation that is running. |
| func (b *ExecBackend) startRootfsGen(ctx context.Context, rt registry.Route, n uint64, perGen bool, id *release.StagedIdentity) (Proc, Gen, error) { |
| - if err := b.rootfsGates(rt); err != nil { |
| + if err := b.rootfsGates(ctx, rt); err != nil { |
| return nil, Gen{}, err |
| } |
| sock := rt.Socket |
| @@ -246,7 +255,7 @@ func (b *ExecBackend) startStagedRootfs(ctx context.Context, rt registry.Route, |
| if err != nil { |
| return g, nil, refuseRootfs(fmt.Errorf("%s: a staged rootfs start: %w", rt.Host, err)) |
| } |
| - if err := b.rootfsGates(rt); err != nil { |
| + if err := b.rootfsGates(ctx, rt); err != nil { |
| return g, nil, err |
| } |
| if g.Tier == (cgroup.Limit{}) { |
diff --git a/internal/activator/rootfs_gate_test.go b/internal/activator/rootfs_gate_test.go| new file mode 100644 |
| index 000000000..dc294be42 |
| --- /dev/null |
| +++ b/internal/activator/rootfs_gate_test.go |
| @@ -0,0 +1,621 @@ |
| +package activator |
| + |
| +// Rootfs apps Plan 3 Task 7: where a rootfs row may start, and how long its |
| +// wake may take. INV-3 (refuse before the lease), the startup proof, the |
| +// gates off a.mu, the served-never-empty refusal, the placeholder database |
| +// (D7) and the rootfs first-wake budget, over fakeBackend; the production |
| +// composition's half is production_backend_test.go, the real control |
| +// handler's rootfs_admission_test.go, and D7's file rootfsdb_test.go. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/rolloutwords" |
| +) |
| + |
| +// armRootfsForTest opens a's rootfs admission as a box with the overlap |
| +// scheduler armed and a clean startup sweep would. |
| +func armRootfsForTest(a *Service) { |
| + a.ArmRootfs() |
| + a.MarkRootfsSwept() |
| +} |
| + |
| +// rootfsStartable is fakeBackend's early rootfs gates: startable's answer, |
| +// nil when unset, counted per host. |
| +func (b *fakeBackend) rootfsStartable(ctx context.Context, rt registry.Route) error { |
| + b.mu.Lock() |
| + if b.startableAsks == nil { |
| + b.startableAsks = map[string]int{} |
| + } |
| + b.startableAsks[rt.Host]++ |
| + f := b.startable |
| + b.mu.Unlock() |
| + if f == nil { |
| + return nil |
| + } |
| + return f(ctx, rt) |
| +} |
| + |
| +func (b *fakeBackend) startableAsked(host string) int { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + return b.startableAsks[host] |
| +} |
| + |
| +// PlaceRootfsDB is fakeBackend's D7 placement: counted, in the order log, |
| +// answering placeErr. |
| +func (b *fakeBackend) PlaceRootfsDB(context.Context, registry.Route) error { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + b.placeholders++ |
| + b.order = append(b.order, "placeholder") |
| + return b.placeErr |
| +} |
| + |
| +// SyncAndWait is a first upload asked of the replica, counted and logged. |
| +func (r *fakeRep) SyncAndWait(context.Context) error { |
| + r.mu.Lock() |
| + r.syncs++ |
| + b := r.b |
| + r.mu.Unlock() |
| + if b != nil { |
| + b.record("sync") |
| + } |
| + return nil |
| +} |
| + |
| +func (r *fakeRep) syncCount() int { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + return r.syncs |
| +} |
| + |
| +// gateCounts is what a refused wake must not have touched (INV-3). |
| +type gateCounts struct{ acquires, restores, materialized, captures, starts, records int } |
| + |
| +func (b *fakeBackend) gateCounts() gateCounts { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + return gateCounts{acquires: b.acquires, restores: b.restores, materialized: b.ident.materializes, captures: b.ident.captures, starts: b.starts} |
| +} |
| + |
| +// rootfsSink is a concurrency-safe EventSink. |
| +type rootfsSink struct { |
| + mu sync.Mutex |
| + events []eventRec |
| +} |
| + |
| +func (s *rootfsSink) App(string, string, string, string) {} |
| +func (s *rootfsSink) Event(acct, app, host, level, msg string) { |
| + s.mu.Lock() |
| + s.events = append(s.events, eventRec{acct, app, host, level, msg}) |
| + s.mu.Unlock() |
| +} |
| +func (s *rootfsSink) msgs() []string { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + var out []string |
| + for _, e := range s.events { |
| + out = append(out, e.msg) |
| + } |
| + return out |
| +} |
| + |
| +// rootfsGateRoute is a hibernating rootfs row of host. |
| +func rootfsGateRoute(host string) registry.Route { |
| + rt := testRoute(host) |
| + rt.Runtime = registry.RuntimeRootfsV1 |
| + rt.App, rt.Account = "shop", "acme" |
| + return rt |
| +} |
| + |
| +// gateService is a Service over fakeBackend with generations on, its |
| +// rootfs admission open, a build-state hook that counts its records, and |
| +// an identity capability whose live link would have to be materialized |
| +// (so a wake that got as far as LiveIdentity counts one). |
| +func gateService(t *testing.T) (*Service, *fakeBackend, *rootfsSink, *int) { |
| + t.Helper() |
| + a, b, _, _ := testActivator(t, time.Hour) |
| + a.gens = true |
| + armRootfsForTest(a) |
| + sink := &rootfsSink{} |
| + a.Logs = sink |
| + records := new(int) |
| + var rmu sync.Mutex |
| + a.BeforeExec = func(context.Context, string, string) error { rmu.Lock(); *records++; rmu.Unlock(); return nil } |
| + b.mu.Lock() |
| + b.ident.on, b.ident.live, b.ident.materializeTo = true, "", "v1" |
| + b.mu.Unlock() |
| + t.Cleanup(func() { a.Shutdown(context.Background()) }) |
| + return a, b, sink, records |
| +} |
| + |
| +// dueWake is a wake that did not come through begin (the due sweep's |
| +// shape): an entry made and woken, synchronously here. It returns the |
| +// wake's error. |
| +func dueWake(a *Service, rt registry.Route) error { |
| + e := &actEntry{host: rt.Host, route: rt, state: actWaking, ready: make(chan struct{})} |
| + a.mu.Lock() |
| + a.entries[rt.Host] = e |
| + a.mu.Unlock() |
| + a.wake(e) |
| + return e.err |
| +} |
| + |
| +// gateCase is one reason a box refuses a rootfs row. |
| +type gateCase struct { |
| + name string |
| + // set shapes the Service, the backend and the row; want is a fragment |
| + // of the refusal; locked says the cheap half refuses (the backend's |
| + // gates are never asked). |
| + set func(t *testing.T, a *Service, b *fakeBackend, rt *registry.Route) |
| + want string |
| + locked bool |
| +} |
| + |
| +// planTwoGate returns a startable answering what the real ExecBackend's |
| +// rootfsGates answers for its own rootfs row once mut has been applied: |
| +// each of Plan 2's reasons, through the real gates. |
| +func planTwoGate(t *testing.T, mut func(eb *ExecBackend, rt *registry.Route)) func(context.Context, registry.Route) error { |
| + t.Helper() |
| + eb, _ := newRootfsBackend(t) |
| + ert := rootfsRoute(eb) |
| + mut(eb, &ert) |
| + return func(ctx context.Context, _ registry.Route) error { return eb.rootfsStartable(ctx, ert) } |
| +} |
| + |
| +func rootfsGateCases(t *testing.T) []gateCase { |
| + gate := func(mut func(eb *ExecBackend, rt *registry.Route)) func(*testing.T, *Service, *fakeBackend, *registry.Route) { |
| + return func(t *testing.T, _ *Service, b *fakeBackend, _ *registry.Route) { b.startable = planTwoGate(t, mut) } |
| + } |
| + return []gateCase{ |
| + {"unknown runtime", func(_ *testing.T, _ *Service, _ *fakeBackend, rt *registry.Route) { rt.Runtime = "rootfs-v2" }, "does not know the instance's runtime", true}, |
| + {"generations off", func(_ *testing.T, a *Service, _ *fakeBackend, _ *registry.Route) { a.gens = false }, "overlap scheduler armed", true}, |
| + {"ArmRootfs not called", func(_ *testing.T, a *Service, _ *fakeBackend, _ *registry.Route) { a.rootfsArmed.Store(false) }, "overlap scheduler armed", true}, |
| + {"startup sweep not proven", func(_ *testing.T, a *Service, _ *fakeBackend, _ *registry.Route) { a.rootfsSwept.Store(false) }, "startup sweep did not prove", true}, |
| + {"not nested-ready", gate(func(eb *ExecBackend, _ *registry.Route) { |
| + eb.NestedOK = func() error { return errors.New("no isolation mounts") } |
| + }), "no isolation mounts", false}, |
| + {"layout flat", gate(func(eb *ExecBackend, rt *registry.Route) { |
| + rt.DBPath, rt.Socket = provision.DefaultDBPath(eb.DataDir, rt.Host), filepath.Join(eb.RunDirOverride, rt.Host+".sock") |
| + }), "nested isolation", false}, |
| + {"layout conflicting", gate(func(eb *ExecBackend, _ *registry.Route) { |
| + eb.LayoutFacts.Peers = func() ([]registry.Route, error) { return []registry.Route{testRoute("other.example.com")}, nil } |
| + eb.LayoutFacts.SameID = func(string, string) bool { return true } |
| + }), "collides with other.example.com", false}, |
| + {"probe not passed", gate(func(eb *ExecBackend, _ *registry.Route) { |
| + eb.RootfsOK = func(context.Context) error { return errors.New("root-image fail") } |
| + }), "root-image fail", false}, |
| + {"no probe", gate(func(eb *ExecBackend, _ *registry.Route) { eb.RootfsOK = nil }), "no rootfs probe", false}, |
| + {"placement refused", gate(func(eb *ExecBackend, _ *registry.Route) { |
| + eb.RootfsPlacement = func(context.Context, registry.Route) error { return errors.New("this box is shared") } |
| + }), "this box is shared", false}, |
| + {"no placement check", gate(func(eb *ExecBackend, _ *registry.Route) { eb.RootfsPlacement = nil }), "no rootfs placement check", false}, |
| + {"claim switch on", gate(func(eb *ExecBackend, _ *registry.Route) { eb.Cfg.HostWrites.Enabled = true }), "claim", false}, |
| + {"no rootfs control half", gate(func(eb *ExecBackend, _ *registry.Route) { eb.Control = plainControl(eb.Control) }), "cannot start a rootfs instance", false}, |
| + } |
| +} |
| + |
| +// INV-3: every reason a box refuses a rootfs row refuses it before the |
| +// lease, through begin (a request, and ServeHTTP's answer) and through |
| +// doWake (a wake that did not come through begin): no Acquire, no |
| +// Restore, no live link materialized or captured, no build state |
| +// recorded, no start, no entry left. Task 8 adds rootfsTick's rows. |
| +func TestRootfsRefusalPrecedesTheLease(t *testing.T) { |
| + for _, c := range rootfsGateCases(t) { |
| + for _, path := range []string{"begin", "doWake", "ServeHTTP"} { |
| + t.Run(c.name+"/"+path, func(t *testing.T) { |
| + a, b, _, records := gateService(t) |
| + rt := rootfsGateRoute("shop.example.com") |
| + c.set(t, a, b, &rt) |
| + var err error |
| + switch path { |
| + case "begin": |
| + _, err = a.beginRequest(context.Background(), rt) |
| + case "doWake": |
| + err = dueWake(a, rt) |
| + case "ServeHTTP": |
| + rec := httptest.NewRecorder() |
| + a.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://shop.example.com/", nil), rt, okHandler()) |
| + if rec.Code != http.StatusServiceUnavailable || !strings.Contains(rec.Body.String(), "instance failed to wake") { |
| + t.Fatalf("ServeHTTP = %d %q, want 503 instance failed to wake", rec.Code, rec.Body.String()) |
| + } |
| + _, err = a.beginRequest(context.Background(), rt) // the error the answer was for |
| + } |
| + if err == nil || !strings.Contains(err.Error(), c.want) { |
| + t.Fatalf("err = %v, want a refusal saying %q", err, c.want) |
| + } |
| + if !errors.Is(err, errRootfsRefused) || !errors.Is(err, errRootfsNotAdmitted) { |
| + t.Fatalf("err = %v is not marked a refusal before the lease", err) |
| + } |
| + if v := verdictOf(err); v != gateNoOwnership { |
| + t.Errorf("verdictOf = %d, want gateNoOwnership", v) |
| + } |
| + if got := b.gateCounts(); got != (gateCounts{}) { |
| + t.Fatalf("a refused wake touched %+v; want nothing", got) |
| + } |
| + if *records != 0 { |
| + t.Fatalf("a refused wake recorded %d build states", *records) |
| + } |
| + if n := a.entryCount(); n != 0 { |
| + t.Fatalf("%d entries left; want none", n) |
| + } |
| + if asked := b.startableAsked(rt.Host); c.locked && asked != 0 { |
| + t.Fatalf("the backend's gates were asked %d times for a refusal the locked half makes", asked) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// Gens on, ArmRootfs not called: refused, and the member's event is |
| +// RFS-3-C12 with RFS-3-C14, once for many tries; after ArmRootfs it wakes. |
| +func TestRootfsWakeRefusedUnarmed(t *testing.T) { |
| + a, b, sink, _ := gateService(t) |
| + a.rootfsArmed.Store(false) |
| + rt := rootfsGateRoute("shop.example.com") |
| + for i := 0; i < 3; i++ { |
| + if _, err := a.beginRequest(context.Background(), rt); !errors.Is(err, errRootfsUnarmed) { |
| + t.Fatalf("try %d: err = %v, want errRootfsUnarmed", i, err) |
| + } |
| + if err := dueWake(a, rt); !errors.Is(err, errRootfsUnarmed) { |
| + t.Fatalf("due wake %d: err = %v, want errRootfsUnarmed", i, err) |
| + } |
| + } |
| + want := "this box cannot run the instance: overlap swaps are not armed here" |
| + if got := fmt.Sprintf(rolloutwords.EventRootfsRefused, rolloutwords.RootfsRefusedUnarmed); got != want { |
| + t.Fatalf("C12 with C14 = %q", got) |
| + } |
| + if msgs := sink.msgs(); len(msgs) != 1 || msgs[0] != want { |
| + t.Fatalf("events %q, want %q once", msgs, want) |
| + } |
| + if got := b.gateCounts(); got.acquires != 0 { |
| + t.Fatalf("an unarmed box took the lease: %+v", got) |
| + } |
| + a.ArmRootfs() |
| + done, err := a.beginRequest(context.Background(), rt) |
| + if err != nil { |
| + t.Fatalf("after ArmRootfs: %v", err) |
| + } |
| + done() |
| + if got := b.gateCounts(); got.acquires != 1 || got.starts != 1 { |
| + t.Fatalf("after ArmRootfs: %+v, want one lease and one start", got) |
| + } |
| +} |
| + |
| +// A binary hibernating row wakes with neither ArmRootfs nor the startup |
| +// proof, and no rootfs gate is asked for it (INV-6). |
| +func TestBinaryWakeNotGated(t *testing.T) { |
| + a, b, _, _ := testActivator(t, time.Hour) |
| + a.gens = true |
| + t.Cleanup(func() { a.Shutdown(context.Background()) }) |
| + rt := testRoute("blog.example.com") |
| + done, err := a.beginRequest(context.Background(), rt) |
| + if err != nil { |
| + t.Fatalf("binary wake: %v", err) |
| + } |
| + done() |
| + if b.acquires != 1 || b.startableAsked(rt.Host) != 0 || b.placeholders != 0 { |
| + t.Fatalf("acquires %d, gate asks %d, placeholders %d", b.acquires, b.startableAsked(rt.Host), b.placeholders) |
| + } |
| +} |
| + |
| +// An unknown runtime never wakes, however the box is armed, and it is the |
| +// operator's to see: no member event (no member can cause one). |
| +func TestUnknownRuntimeNeverWakes(t *testing.T) { |
| + a, b, sink, _ := gateService(t) |
| + rt := rootfsGateRoute("shop.example.com") |
| + rt.Runtime, rt.Hibernate = "rootfs-v2", true |
| + if _, err := a.beginRequest(context.Background(), rt); !errors.Is(err, errRuntimeUnknown) { |
| + t.Fatalf("begin: %v, want errRuntimeUnknown", err) |
| + } |
| + if err := dueWake(a, rt); !errors.Is(err, errRuntimeUnknown) { |
| + t.Fatalf("due wake: %v, want errRuntimeUnknown", err) |
| + } |
| + if b.acquires != 0 || b.startableAsked(rt.Host) != 0 { |
| + t.Fatalf("acquires %d, gate asks %d", b.acquires, b.startableAsked(rt.Host)) |
| + } |
| + if msgs := sink.msgs(); len(msgs) != 0 { |
| + t.Fatalf("member events %q, want none", msgs) |
| + } |
| + // A sidecar row is a row too. |
| + sc := testWorkerRoute("bot.example.com") |
| + sc.Runtime = "rootfs-v2" |
| + if err := a.WakeWorker(sc); err == nil { |
| + t.Fatal("an unknown-runtime sidecar woke") |
| + } |
| + waitFor(t, "the sidecar's wake to end", func() bool { return a.entryCount() == 0 }) |
| + if b.acquires != 0 { |
| + t.Fatalf("an unknown-runtime sidecar took the lease") |
| + } |
| +} |
| + |
| +// Review Focus 4: a rootfs row that has served, fresh on restore (no |
| +// database, no replica), never boots empty: RFS-3-C15, nothing started, |
| +// the lease given back, no placeholder. |
| +func TestServedRootfsNeverBootsEmpty(t *testing.T) { |
| + a, b, sink, _ := gateService(t) |
| + b.restoreFresh = true |
| + rt := rootfsGateRoute("shop.example.com") |
| + rt.GoodVersion = "v1" |
| + err := dueWake(a, rt) |
| + if !errors.Is(err, errRootfsReplicaMissing) { |
| + t.Fatalf("err = %v, want errRootfsReplicaMissing", err) |
| + } |
| + if v := verdictOf(err); v != gateNoOwnership { |
| + t.Errorf("verdictOf = %d: a missing replica is not the build's failure", v) |
| + } |
| + if b.starts != 0 || b.releases != 1 || b.placeholders != 0 { |
| + t.Fatalf("starts %d, releases %d, placeholders %d; want 0, 1, 0", b.starts, b.releases, b.placeholders) |
| + } |
| + want := "wake failed: the instance has served before and its database replica is missing, so it was not started with an empty database" |
| + if msgs := sink.msgs(); len(msgs) != 1 || msgs[0] != want { |
| + t.Fatalf("events %q, want %q", msgs, want) |
| + } |
| +} |
| + |
| +// The same refusal, read as the placeholder's: a served row never gets one. |
| +func TestServedRootfsPlacesNoPlaceholder(t *testing.T) { |
| + a, b, _, _ := gateService(t) |
| + b.restoreFresh = true |
| + rt := rootfsGateRoute("shop.example.com") |
| + rt.GoodVersion = "v1" |
| + if _, err := a.beginRequest(context.Background(), rt); !errors.Is(err, errRootfsReplicaMissing) { |
| + t.Fatalf("err = %v", err) |
| + } |
| + if b.placeholders != 0 { |
| + t.Fatalf("placeholders %d, want 0", b.placeholders) |
| + } |
| +} |
| + |
| +// A first boot (no good build yet) may boot fresh: the placeholder is |
| +// placed under the lease before the start, no seed runs, and the replica |
| +// is asked for its first upload once, after Replicate. |
| +func TestFirstRootfsWakeMayBootFresh(t *testing.T) { |
| + a, b, _, _ := gateService(t) |
| + b.restoreFresh = true |
| + rt := rootfsGateRoute("shop.example.com") |
| + done, err := a.beginRequest(context.Background(), rt) |
| + if err != nil { |
| + t.Fatalf("first wake: %v", err) |
| + } |
| + done() |
| + if b.starts != 1 || b.seeds != 0 || b.placeholders != 1 { |
| + t.Fatalf("starts %d, seeds %d, placeholders %d; want 1, 0, 1", b.starts, b.seeds, b.placeholders) |
| + } |
| + ev := b.events() |
| + idx := func(s string) int { |
| + for i, e := range ev { |
| + if e == s || strings.HasPrefix(e, s) { |
| + return i |
| + } |
| + } |
| + return -1 |
| + } |
| + if p, s, y := idx("placeholder"), idx("start"), idx("sync"); p < 0 || s < 0 || y < 0 || !(idx("restore") < p && p < s && s < y) { |
| + t.Fatalf("order %v: want restore, placeholder, start, then the first sync", ev) |
| + } |
| + if n := b.reps[len(b.reps)-1].syncCount(); n != 1 { |
| + t.Fatalf("SyncAndWait asked %d times, want once", n) |
| + } |
| +} |
| + |
| +// A binary hibernating row that boots fresh places nothing: its seed runs |
| +// as today. |
| +func TestBinaryFreshWakePlacesNothing(t *testing.T) { |
| + a, b, _, _ := testActivator(t, time.Hour) |
| + a.gens = true |
| + t.Cleanup(func() { a.Shutdown(context.Background()) }) |
| + b.restoreFresh = true |
| + rt := testRoute("blog.example.com") |
| + rt.Seed = `["seed"]` |
| + done, err := a.beginRequest(context.Background(), rt) |
| + if err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + done() |
| + if b.placeholders != 0 || b.seeds != 1 { |
| + t.Fatalf("placeholders %d, seeds %d; want 0, 1", b.placeholders, b.seeds) |
| + } |
| + if n := b.reps[len(b.reps)-1].syncCount(); n != 0 { |
| + t.Fatalf("a binary wake asked for a first upload %d times", n) |
| + } |
| +} |
| + |
| +// noPlacer is a backend with the early gates but no rootfsDBPlacer. |
| +type noPlacer struct{ Backend } |
| + |
| +func (noPlacer) rootfsStartable(context.Context, registry.Route) error { return nil } |
| + |
| +// A placement that fails starts nothing and gives the lease back; so does |
| +// a backend that cannot place one (errNoRootfsDB). |
| +func TestRootfsPlaceholderFailureStartsNothing(t *testing.T) { |
| + t.Run("placement fails", func(t *testing.T) { |
| + a, b, _, _ := gateService(t) |
| + b.restoreFresh = true |
| + b.placeErr = errors.New("disk full") |
| + err := dueWake(a, rootfsGateRoute("shop.example.com")) |
| + if err == nil || !strings.Contains(err.Error(), "disk full") { |
| + t.Fatalf("err = %v", err) |
| + } |
| + if v := verdictOf(err); v != gateNoOwnership { |
| + t.Errorf("verdictOf = %d, want gateNoOwnership", v) |
| + } |
| + if b.starts != 0 || b.releases != 1 { |
| + t.Fatalf("starts %d, releases %d; want 0, 1", b.starts, b.releases) |
| + } |
| + }) |
| + t.Run("no placer", func(t *testing.T) { |
| + a, b, _, _ := gateService(t) |
| + b.restoreFresh = true |
| + a.backend = noPlacer{b} |
| + err := dueWake(a, rootfsGateRoute("shop.example.com")) |
| + if !errors.Is(err, errNoRootfsDB) { |
| + t.Fatalf("err = %v, want errNoRootfsDB", err) |
| + } |
| + if b.starts != 0 || b.releases != 1 || b.acquires != 1 { |
| + t.Fatalf("acquires %d, starts %d, releases %d; want 1, 0, 1", b.acquires, b.starts, b.releases) |
| + } |
| + }) |
| +} |
| + |
| +// [Astra R1 8] The backend's gates run off a.mu and are shared per host: |
| +// while host A's gate is blocked, a request to binary host B and to awake |
| +// rootfs host C complete; C's requests never ask the gates; twenty cold |
| +// requests to A ask them once and coalesce on one wake; and Shutdown is |
| +// not held up by A's gate, which ends with the service's lifetime. |
| +func TestRootfsGatesRunOffTheLock(t *testing.T) { |
| + a, b, _, _ := gateService(t) |
| + b.mu.Lock() |
| + b.ident.on = false |
| + b.mu.Unlock() |
| + hostA, hostB, hostC := "a.example.com", "blog.example.com", "c.example.com" |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + var once sync.Once |
| + b.startable = func(ctx context.Context, rt registry.Route) error { |
| + if rt.Host != hostA { |
| + return nil |
| + } |
| + once.Do(func() { close(entered) }) |
| + select { |
| + case <-release: |
| + return nil |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + } |
| + } |
| + arrangeAwake(t, a, rootfsGateRoute(hostC)) |
| + asksC := b.startableAsked(hostC) |
| + |
| + const n = 20 |
| + errs := make(chan error, n) |
| + for i := 0; i < n; i++ { |
| + go func() { |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + done, err := a.beginRequest(ctx, rootfsGateRoute(hostA)) |
| + if err == nil { |
| + done() |
| + } |
| + errs <- err |
| + }() |
| + } |
| + <-entered |
| + for _, rt := range []registry.Route{testRoute(hostB), rootfsGateRoute(hostC)} { |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| + done, err := a.beginRequest(ctx, rt) |
| + cancel() |
| + if err != nil { |
| + t.Fatalf("%s while A's gate is blocked: %v", rt.Host, err) |
| + } |
| + done() |
| + } |
| + if got := b.startableAsked(hostC); got != asksC { |
| + t.Fatalf("awake host C's request asked the gates (%d -> %d)", asksC, got) |
| + } |
| + waitFor(t, "every request to A to join the one ask", func() bool { return a.rootfsGateWaiters(hostA) == n }) |
| + close(release) |
| + for i := 0; i < n; i++ { |
| + if err := <-errs; err != nil { |
| + t.Fatalf("a request to A: %v", err) |
| + } |
| + } |
| + if got := b.startableAsked(hostA); got != 1 { |
| + t.Fatalf("twenty cold requests asked A's gates %d times, want once", got) |
| + } |
| + if got := b.gateCounts(); got.acquires != 3 { |
| + t.Fatalf("acquires %d, want one per host", got.acquires) |
| + } |
| + |
| + t.Run("shutdown", func(t *testing.T) { |
| + a, b, _, _ := gateService(t) |
| + entered := make(chan struct{}) |
| + var once sync.Once |
| + b.startable = func(ctx context.Context, rt registry.Route) error { |
| + once.Do(func() { close(entered) }) |
| + <-ctx.Done() |
| + return ctx.Err() |
| + } |
| + res := make(chan error, 1) |
| + go func() { |
| + _, err := a.beginRequest(context.Background(), rootfsGateRoute(hostA)) |
| + res <- err |
| + }() |
| + <-entered |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| + defer cancel() |
| + began := time.Now() |
| + a.Shutdown(ctx) |
| + if took := time.Since(began); took > time.Second { |
| + t.Fatalf("Shutdown took %s behind a blocked rootfs gate", took) |
| + } |
| + select { |
| + case err := <-res: |
| + if err == nil { |
| + t.Fatal("a request whose gate ended with the service woke") |
| + } |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("the request behind the gate did not end with the service") |
| + } |
| + if b.acquires != 0 { |
| + t.Fatalf("acquires %d after shutdown", b.acquires) |
| + } |
| + }) |
| +} |
| + |
| +// rootfsGateWaiters is how many callers wait on host's ask in flight. |
| +func (a *Service) rootfsGateWaiters(host string) int { |
| + a.rootfsGateMu.Lock() |
| + defer a.rootfsGateMu.Unlock() |
| + if r := a.rootfsGateRuns[host]; r != nil { |
| + return r.waiters |
| + } |
| + return 0 |
| +} |
| + |
| +// The first-wake budget is the row's own: a rootfs row's health bound plus |
| +// the kill reserve, the binary 55 s otherwise. |
| +func TestFirstWakeBudgetIsTheRowsBound(t *testing.T) { |
| + if got := firstWakeBudgetFor(testRoute("blog.example.com")); got != firstWakeBudget { |
| + t.Fatalf("binary budget %s, want %s", got, firstWakeBudget) |
| + } |
| + if got, want := firstWakeBudgetFor(rootfsGateRoute("shop.example.com")), rootfsHealthTimeout+firstWakeKillReserve; got != want || want != 145*time.Second { |
| + t.Fatalf("rootfs budget %s, want %s (145 s)", got, want) |
| + } |
| +} |
| + |
| +// A rootfs build's planned first wake is judged on the rootfs bound, and |
| +// its waiters wait that long: with a binary first-wake budget of 600 ms |
| +// (B's window 300 ms, the waiters' 600 ms) and a rootfs bound of 2 s, a |
| +// rootfs B that answers at 900 ms serves, and the request that woke it is |
| +// answered. |
| +func TestRootfsPlannedFirstWakeGetsTheRootfsBudget(t *testing.T) { |
| + shrinkHealthBounds(t, 300*time.Millisecond, 2*time.Second, 100*time.Millisecond) |
| + ob, or, ow := firstWakeBudget, firstWakeKillReserve, wakeWaitBound |
| + firstWakeBudget, firstWakeKillReserve, wakeWaitBound = 600*time.Millisecond, 300*time.Millisecond, 100*time.Millisecond |
| + t.Cleanup(func() { firstWakeBudget, firstWakeKillReserve, wakeWaitBound = ob, or, ow }) |
| + lb, ctl := newRootfsLaunch(t, &fakeSwapBackend{fakeBackend: &fakeBackend{}}) |
| + next, good := stagedRootfsIdentity(t, lb.eb, "v2"), stagedRootfsIdentity(t, lb.eb, "v3") |
| + ctl.setServe(serveVersions(t, lb.eb, lb.rt, 900*time.Millisecond, "v2", "v3")) |
| + a, rt, evs := rootfsPlanned(t, lb, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good}, registry.RuntimeRootfsV1) |
| + done, err := a.beginRequest(context.Background(), rt) |
| + if err != nil { |
| + t.Fatalf("the planned wake: %v; calls:\n%s", err, ctl.joined()) |
| + } |
| + done() |
| + if g, _ := a.genStateForTest(rt.Host); g.Build != "v2" { |
| + t.Fatalf("serving %+v, want B", g) |
| + } |
| + evs.wait(t, GenHealthy) |
| +} |
diff --git a/internal/activator/rootfs_invariants_test.go b/internal/activator/rootfs_invariants_test.go| index cbe43b50e..509b7f6ef 100644 |
| --- a/internal/activator/rootfs_invariants_test.go |
| +++ b/internal/activator/rootfs_invariants_test.go |
| @@ -880,6 +880,14 @@ var rootfsRefusals = []struct { |
| {"root's /cmd 403 (CmdRootfs's ErrStagedImage, marked)", refuseRootfs(fmt.Errorf("start cmd: %w", fmt.Errorf("%w: x", instancectl.ErrStagedImage)))}, |
| {"an unknown runtime (errRuntimeUnknown, marked)", refuseRootfs(fmt.Errorf("x: %w", errRuntimeUnknown))}, |
| {"a staged start with a partial identity (marked)", refuseRootfs(fmt.Errorf("x: %w", errPartialStagedIdentity))}, |
| + // Task 7: the early gate's refusals (rootfsStartRefusal marks every |
| + // one), the served-never-empty refusal and the placeholder's. |
| + {"unarmed (errRootfsUnarmed, as the early gate marks it)", notAdmitted(fmt.Errorf("x: %w", errRootfsUnarmed))}, |
| + {"an unknown runtime (errRuntimeUnknown, as the early gate marks it)", notAdmitted(fmt.Errorf("x: %w", errRuntimeUnknown))}, |
| + {"the startup sweep unproven (errRootfsUnswept, as the early gate marks it)", notAdmitted(fmt.Errorf("x: %w", errRootfsUnswept))}, |
| + {"a backend gate's refusal, as the early gate marks it", notAdmitted(refuseRootfs(errors.New("x")))}, |
| + {"a served row with no replica (errRootfsReplicaMissing, marked)", refuseRootfs(fmt.Errorf("x: %w", errRootfsReplicaMissing))}, |
| + {"no placeholder placer (errNoRootfsDB, marked)", refuseRootfs(fmt.Errorf("x: %w", errNoRootfsDB))}, |
| } |
| func TestRootfsRefusalsAreNotBuildFailures(t *testing.T) { |
diff --git a/internal/activator/rootfs_service.go b/internal/activator/rootfs_service.go| index 60fe2100c..a3cc36d0f 100644 |
| --- a/internal/activator/rootfs_service.go |
| +++ b/internal/activator/rootfs_service.go |
| @@ -6,10 +6,14 @@ |
| package activator |
| import ( |
| + "context" |
| "errors" |
| + "fmt" |
| + "log" |
| "time" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/rolloutwords" |
| ) |
| // errRuntimeUnknown refuses a row whose runtime this agent does not know |
| @@ -30,3 +34,283 @@ func healthBoundFor(rt registry.Route) time.Duration { |
| } |
| return spawnHealthTimeout |
| } |
| + |
| +// firstWakeBudgetFor is a first wake's whole budget (zero-downtime spec |
| +// §8.2): firstWakeBudget for a binary row; for a rootfs row its own health |
| +// bound plus the kill reserve, so a 120 s boot is judged on its own bound, |
| +// not the binary 55 s (Plan 3 Task 7). spawnPlanned's health deadline and |
| +// awaitWake's extension both read it. |
| +func firstWakeBudgetFor(rt registry.Route) time.Duration { |
| + if rt.Rootfs() { |
| + return healthBoundFor(rt) + firstWakeKillReserve |
| + } |
| + return firstWakeBudget |
| +} |
| + |
| +// The admission refusals (Plan 3 Task 7, INV-3), each asked before the |
| +// lease. errRootfsUnarmed: generations are off, or the overlap scheduler |
| +// has not armed on this boot (deviation D2). errRootfsUnswept: the startup |
| +// sweep did not prove every leftover unit of the previous agent gone |
| +// (Astra R3 3; the controller's ruling: closed for the Service's life). |
| +var ( |
| + errRootfsUnarmed = errors.New("activator: rootfs instances need generations and the overlap scheduler armed on this box") |
| + errRootfsUnswept = errors.New("activator: rootfs instances stay off until the agent restarts: the startup sweep did not prove every leftover unit gone") |
| +) |
| + |
| +// rootfsReplicaMissingText is RFS-3-C15, the member's wake reason for |
| +// errRootfsReplicaMissing. |
| +const rootfsReplicaMissingText = "the instance has served before and its database replica is missing, so it was not started with an empty database" // RFS-3-C15 |
| + |
| +// errRootfsReplicaMissing refuses a rootfs row that has served (its |
| +// GoodVersion is set) when Restore found no local database and no replica: |
| +// booting it would hand a member an empty database where their data was |
| +// (Review Focus 4). Nothing starts and no placeholder is written. |
| +var errRootfsReplicaMissing = errors.New(rootfsReplicaMissingText) |
| + |
| +// errRootfsNotAdmitted marks a refusal of the Service's early rootfs gate |
| +// (rootfsStartRefusal): asked before the lease, so it took nothing. The |
| +// wake's member event and the HTTP answer read it (noteRootfsRefusal, |
| +// serveWakeError). |
| +var errRootfsNotAdmitted = errors.New("activator: rootfs start not admitted") |
| + |
| +// rootfsAdmission wraps an early-gate refusal: errors.Is matches both |
| +// errRootfsRefused (a refusal, never the build's failure: verdictOf, |
| +// classifyStep) and errRootfsNotAdmitted. The text is the cause's. |
| +type rootfsAdmission struct{ err error } |
| + |
| +func (e rootfsAdmission) Error() string { return e.err.Error() } |
| +func (e rootfsAdmission) Unwrap() error { return e.err } |
| +func (e rootfsAdmission) Is(target error) bool { |
| + return target == errRootfsRefused || target == errRootfsNotAdmitted |
| +} |
| + |
| +func notAdmitted(err error) error { |
| + if err == nil { |
| + return nil |
| + } |
| + return rootfsAdmission{err: err} |
| +} |
| + |
| +// rootfsStartable is the backend's own rootfs gates, asked before the |
| +// lease. ExecBackend answers rootfsGates(rt); SplitBackend forwards to its |
| +// exec side and refuses a unit-backed row. A backend without it refuses a |
| +// rootfs row (refuseRootfs(errNoRootfsControl)): there is no unchecked |
| +// path. It may do I/O (the control service's readiness, a cached owner |
| +// read), so it is never called with a.mu held [Astra R1 8]. ctx bounds |
| +// every I/O it does. |
| +type rootfsStartable interface { |
| + rootfsStartable(ctx context.Context, rt registry.Route) error |
| +} |
| + |
| +// rootfsGateBound bounds one ask of the backend's gates: the readiness ask |
| +// (DeadlineReady, 5 s) and an owner read (10 s), with room. |
| +const rootfsGateBound = 30 * time.Second |
| + |
| +// ArmRootfs records that the overlap scheduler has armed on this boot (D2: |
| +// the runtime half of "rootfs rows need the rollout scheduler"). Only |
| +// internal/host calls it, once the manager is armed; never cleared. |
| +func (a *Service) ArmRootfs() { a.rootfsArmed.Store(true) } |
| + |
| +// MarkRootfsSwept records that the startup sweep answered with no error, |
| +// so every unit a previous agent left is proven gone (Astra R3 3). Only |
| +// internal/host calls it, once, from the startup sweep; never cleared, and |
| +// never set later in the Service's life: after a failed sweep rootfs |
| +// admission stays closed until an agent restart sweeps clean (the seeds' |
| +// seedSweptAtStart shape). |
| +func (a *Service) MarkRootfsSwept() { a.rootfsSwept.Store(true) } |
| + |
| +// rootfsRefusalLocked is the cheap half of the rootfs admission, under |
| +// a.mu: nil for a binary row with a valid runtime; an unknown runtime on |
| +// any row is errRuntimeUnknown; a rootfs row is errRootfsUnarmed unless |
| +// generations are on and ArmRootfs was called, then errRootfsUnswept until |
| +// MarkRootfsSwept. It does no I/O. |
| +func (a *Service) rootfsRefusalLocked(rt registry.Route) error { |
| + if !registry.ValidRuntime(rt.Runtime) { |
| + return fmt.Errorf("%s: runtime %q: %w", rt.Host, rt.Runtime, errRuntimeUnknown) |
| + } |
| + if !rt.Rootfs() { |
| + return nil |
| + } |
| + if !a.gens || !a.rootfsArmed.Load() { |
| + return fmt.Errorf("%s: %w", rt.Host, errRootfsUnarmed) |
| + } |
| + if !a.rootfsSwept.Load() { |
| + return fmt.Errorf("%s: %w", rt.Host, errRootfsUnswept) |
| + } |
| + return nil |
| +} |
| + |
| +// rootfsStartRefusal is the whole rootfs admission, never with a.mu held: |
| +// the locked half (taking a.mu briefly), then, for a rootfs row, the |
| +// backend's rootfsStartable, shared per host (rootfsBackendGates). Every |
| +// non-nil answer of either half is marked errRootfsRefused and |
| +// errRootfsNotAdmitted, except the caller's own ctx ending, which is |
| +// returned as it is. |
| +func (a *Service) rootfsStartRefusal(ctx context.Context, rt registry.Route) error { |
| + a.mu.Lock() |
| + err := a.rootfsRefusalLocked(rt) |
| + a.mu.Unlock() |
| + if err != nil { |
| + return notAdmitted(err) |
| + } |
| + if !rt.Rootfs() { |
| + return nil |
| + } |
| + if err := a.rootfsBackendGates(ctx, rt); err != nil { |
| + if ctx.Err() != nil && errors.Is(err, ctx.Err()) { |
| + return err |
| + } |
| + return notAdmitted(refuseRootfs(err)) |
| + } |
| + a.clearRootfsRefusal(rt.Host) |
| + return nil |
| +} |
| + |
| +// rootfsGateRun is one ask of the backend's gates for a host: its answer |
| +// is published by closing done. waiters counts the callers that took it |
| +// (the logs' and the tests' view of the coalescing), under rootfsGateMu. |
| +type rootfsGateRun struct { |
| + done chan struct{} |
| + err error |
| + waiters int |
| +} |
| + |
| +// rootfsBackendGates asks the backend's rootfsStartable for rt, one ask per |
| +// host at a time: a caller that arrives while an ask is in flight waits |
| +// for it and takes its answer, so a request storm on a cold host asks the |
| +// gates once. The ask runs on its own goroutine under the service's |
| +// lifetime and rootfsGateBound, never under one caller's ctx (a caller |
| +// that hangs up must not fail the others), and Shutdown's cancellation of |
| +// the lifetime ends it. A caller stops waiting when its own ctx ends. |
| +func (a *Service) rootfsBackendGates(ctx context.Context, rt registry.Route) error { |
| + s, ok := a.backend.(rootfsStartable) |
| + if !ok { |
| + return refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoRootfsControl)) |
| + } |
| + a.rootfsGateMu.Lock() |
| + run := a.rootfsGateRuns[rt.Host] |
| + if run == nil { |
| + run = &rootfsGateRun{done: make(chan struct{})} |
| + if a.rootfsGateRuns == nil { |
| + a.rootfsGateRuns = map[string]*rootfsGateRun{} |
| + } |
| + a.rootfsGateRuns[rt.Host] = run |
| + parent := a.lifeCtx |
| + if parent == nil { |
| + parent = context.Background() |
| + } |
| + go func() { |
| + gctx, cancel := context.WithTimeout(parent, rootfsGateBound) |
| + defer cancel() |
| + err := s.rootfsStartable(gctx, rt) |
| + a.rootfsGateMu.Lock() |
| + delete(a.rootfsGateRuns, rt.Host) |
| + run.err = err |
| + a.rootfsGateMu.Unlock() |
| + close(run.done) |
| + }() |
| + } |
| + run.waiters++ |
| + a.rootfsGateMu.Unlock() |
| + select { |
| + case <-run.done: |
| + return run.err |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + } |
| +} |
| + |
| +// noteRootfsRefusal reports an early-gate refusal once per change of its |
| +// text for the host: the operator's log line, and for unarmed the member's |
| +// event (RFS-3-C12 filled with RFS-3-C14). An unknown runtime (no member |
| +// can cause one), an unproven startup sweep and a backend gate refusal |
| +// (whose Plan 2 reason is the operator's) log only. A request storm or a |
| +// sweep's due wakes against a refusing box report it once, not per try. |
| +func (a *Service) noteRootfsRefusal(rt registry.Route, err error) { |
| + msg := err.Error() |
| + a.rootfsGateMu.Lock() |
| + if a.rootfsRefusedSeen == nil { |
| + a.rootfsRefusedSeen = map[string]string{} |
| + } |
| + same := a.rootfsRefusedSeen[rt.Host] == msg |
| + a.rootfsRefusedSeen[rt.Host] = msg |
| + a.rootfsGateMu.Unlock() |
| + if same { |
| + return |
| + } |
| + log.Printf("activator: %s: not started, refused before the lease: %v", rt.Host, err) |
| + if errors.Is(err, errRootfsUnarmed) { |
| + emitEvent(a.Logs, rt, "error", rootfsUnarmedEvent()) |
| + } |
| +} |
| + |
| +// clearRootfsRefusal forgets the host's last reported refusal, once its |
| +// admission passes: a later refusal is a change and is reported again. |
| +func (a *Service) clearRootfsRefusal(host string) { |
| + a.rootfsGateMu.Lock() |
| + delete(a.rootfsRefusedSeen, host) |
| + a.rootfsGateMu.Unlock() |
| +} |
| + |
| +// rootfsUnarmedEvent is the member's event for errRootfsUnarmed: |
| +// RFS-3-C12 filled with RFS-3-C14. |
| +func rootfsUnarmedEvent() string { |
| + return fmt.Sprintf(rolloutwords.EventRootfsRefused, rolloutwords.RootfsRefusedUnarmed) |
| +} |
| + |
| +// rootfsWakeRefusal is doWake's ask of the admission, off a.mu, before the |
| +// lease: the whole of it, unless begin asked the backend's gates for this |
| +// very entry an instant before (e.rootfsAdmitted), when only the locked |
| +// half is asked again (it is cheap, and a ruling that changed since is |
| +// seen). |
| +func (a *Service) rootfsWakeRefusal(ctx context.Context, e *actEntry, rt registry.Route) error { |
| + if e.rootfsAdmitted { |
| + a.mu.Lock() |
| + err := a.rootfsRefusalLocked(rt) |
| + a.mu.Unlock() |
| + return notAdmitted(err) |
| + } |
| + return a.rootfsStartRefusal(ctx, rt) |
| +} |
| + |
| +// rootfsDBPlacer places the empty SQLite database of a rootfs first boot |
| +// (D7). ExecBackend has it; SplitBackend forwards it. |
| +type rootfsDBPlacer interface { |
| + PlaceRootfsDB(ctx context.Context, rt registry.Route) error |
| +} |
| + |
| +// errNoRootfsDB is a backend that cannot place a rootfs instance's |
| +// database: the first boot fails before anything starts. |
| +var errNoRootfsDB = errors.New("activator: this backend cannot place a rootfs instance's database") |
| + |
| +// placeRootfsDB is doWake's D7 step: the backend's PlaceRootfsDB, or |
| +// errNoRootfsDB. Either failure is marked a refusal (nothing of the build |
| +// has run, so it is never the build's failure). |
| +func (a *Service) placeRootfsDB(ctx context.Context, rt registry.Route) error { |
| + p, ok := a.backend.(rootfsDBPlacer) |
| + if !ok { |
| + return refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoRootfsDB)) |
| + } |
| + if err := p.PlaceRootfsDB(ctx, rt); err != nil { |
| + return refuseRootfs(fmt.Errorf("%s: place the first database: %w", rt.Host, err)) |
| + } |
| + return nil |
| +} |
| + |
| +// syncRootfsPlaceholder is the placeholder's first upload, step 5b's shape |
| +// (SeedPlaced): once replication runs, so the replica holds a database |
| +// before the scheduler can record the build as good. A failure only logs: |
| +// the replicator keeps trying on its interval, the next sleep's checkpoint |
| +// uploads it, and if neither lands the next wake reads "served, no |
| +// database, no replica" and refuses (errRootfsReplicaMissing), the safe |
| +// direction. |
| +func syncRootfsPlaceholder(ctx context.Context, host string, rep Rep) { |
| + s, ok := rep.(interface{ SyncAndWait(context.Context) error }) |
| + if !ok { |
| + log.Printf("activator: %s: first database placed; the replicator cannot confirm its first upload", host) |
| + return |
| + } |
| + if err := s.SyncAndWait(ctx); err != nil { |
| + log.Printf("activator: %s: first database placed; its first upload is not confirmed yet: %v", host, err) |
| + } |
| +} |
diff --git a/internal/activator/rootfs_staged_test.go b/internal/activator/rootfs_staged_test.go| index 1d6d67bf9..c809f214f 100644 |
| --- a/internal/activator/rootfs_staged_test.go |
| +++ b/internal/activator/rootfs_staged_test.go |
| @@ -155,6 +155,12 @@ func (b *rootfsLaunch) KillGen(ctx context.Context, _ registry.Route, n uint64) |
| return b.eb.KillGen(ctx, b.rt, n) |
| } |
| +// rootfsStartable is the real backend's early gates (Plan 3 Task 7), over |
| +// the rig's own row, as KillGen is. |
| +func (b *rootfsLaunch) rootfsStartable(ctx context.Context, _ registry.Route) error { |
| + return b.eb.rootfsStartable(ctx, b.rt) |
| +} |
| + |
| func newRootfsLaunch(t *testing.T, fb *fakeSwapBackend) (*rootfsLaunch, *stagedRootfsCtl) { |
| t.Helper() |
| eb, ctl, rt := newStagedRootfsRig(t) |
| @@ -176,6 +182,7 @@ func rootfsSwapFixture(t *testing.T, mode SwapMode) (*swapFixture, *rootfsLaunch |
| f.a.mu.Lock() |
| f.a.entries[f.host].route.Runtime = registry.RuntimeRootfsV1 |
| f.a.mu.Unlock() |
| + armRootfsForTest(f.a) |
| id := stagedRootfsIdentity(t, lb.eb, "v2") |
| at := f.attempt(mode) |
| at.StagedPath, at.Digest = id.StagedPath, id.Digest |
| @@ -193,6 +200,7 @@ func rootfsPlanned(t *testing.T, b Backend, plan WakePlan, runtime string) (*Ser |
| } |
| a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg) |
| a.gens = true |
| + armRootfsForTest(a) |
| evs := &genLog{} |
| a.OnGen = evs.add |
| a.Planner = func(context.Context, registry.Route) WakePlan { return plan } |
diff --git a/internal/activator/rootfs_test.go b/internal/activator/rootfs_test.go| index c34926724..98b077de2 100644 |
| --- a/internal/activator/rootfs_test.go |
| +++ b/internal/activator/rootfs_test.go |
| @@ -45,8 +45,8 @@ func newRootfsBackend(t *testing.T) (*ExecBackend, *fakeControl) { |
| unit.set("active", "inv1", true, true) |
| ctl.stopHook = func(string, instancectl.Role) { unit.set("inactive", "inv1", false, false) } |
| b, _ := nestedBackend(t, ctl, unit) |
| - b.RootfsOK = func() error { return nil } |
| - b.RootfsPlacement = func(registry.Route) error { return nil } |
| + b.RootfsOK = func(context.Context) error { return nil } |
| + b.RootfsPlacement = func(context.Context, registry.Route) error { return nil } |
| b.ControlGroup = func(context.Context, string) (string, error) { return "", nil } |
| stageRootfsImage(t, b, "v1", release.KindRootfs) |
| pointLive(t, b, rootfsTestHost, release.VersionPath(b.OptDir, rootfsTestAcct, "v1", rootfsTestApp)) |
| @@ -270,11 +270,11 @@ func TestRootfsStartRefusesBeforeRootOnEveryGate(t *testing.T) { |
| }{ |
| "no rootfs channel": {func(b *ExecBackend, _ *registry.Route) { b.Control = plainControl(b.Control) }, "cannot start a rootfs instance"}, |
| "rootfs probe failed": {func(b *ExecBackend, _ *registry.Route) { |
| - b.RootfsOK = func() error { return errors.New("root-image fail") } |
| + b.RootfsOK = func(context.Context) error { return errors.New("root-image fail") } |
| }, "root-image fail"}, |
| "no rootfs gate": {func(b *ExecBackend, _ *registry.Route) { b.RootfsOK = nil }, "cannot start a rootfs instance"}, |
| "placement refused": {func(b *ExecBackend, _ *registry.Route) { |
| - b.RootfsPlacement = func(registry.Route) error { return errors.New("rootfs placement refused: shared") } |
| + b.RootfsPlacement = func(context.Context, registry.Route) error { return errors.New("rootfs placement refused: shared") } |
| }, "shared"}, |
| "no placement gate": {func(b *ExecBackend, _ *registry.Route) { b.RootfsPlacement = nil }, "cannot start a rootfs instance"}, |
| "claim control armed": {func(b *ExecBackend, _ *registry.Route) { b.Cfg.HostWrites.Enabled = true }, "claim"}, |
| @@ -948,8 +948,11 @@ func TestRootfsCmdUnitPollsStopsAndProvesTheRootfsUnit(t *testing.T) { |
| func TestBinaryRowsAreUntouchedByTheRootfsPath(t *testing.T) { |
| t.Parallel() |
| b, ctl := newRootfsBackend(t) |
| - b.RootfsOK = func() error { t.Error("RootfsOK asked for a binary row"); return nil } |
| - b.RootfsPlacement = func(registry.Route) error { t.Error("RootfsPlacement asked for a binary row"); return nil } |
| + b.RootfsOK = func(context.Context) error { t.Error("RootfsOK asked for a binary row"); return nil } |
| + b.RootfsPlacement = func(context.Context, registry.Route) error { |
| + t.Error("RootfsPlacement asked for a binary row") |
| + return nil |
| + } |
| rt := nestedRoute(b, "blog.example.com") |
| stageLive(t, b, rt.Host, "v1") |
| ctl.onStart = serveHealthy(t, rt.Socket) |
| @@ -1111,13 +1114,13 @@ func TestRootfsRefusalsAreNeverABuildFailure(t *testing.T) { |
| }, |
| "probe failed": func(t *testing.T) error { |
| b, _ := newRootfsBackend(t) |
| - b.RootfsOK = func() error { return errors.New("root-image fail") } |
| + b.RootfsOK = func(context.Context) error { return errors.New("root-image fail") } |
| _, _, err := b.StartGenExe(context.Background(), rootfsRoute(b), 2, true, release.StagedIdentity{}) |
| return err |
| }, |
| "placement refused": func(t *testing.T) error { |
| b, _ := newRootfsBackend(t) |
| - b.RootfsPlacement = func(registry.Route) error { return errors.New("this box is shared") } |
| + b.RootfsPlacement = func(context.Context, registry.Route) error { return errors.New("this box is shared") } |
| _, _, err := b.StartGen(context.Background(), rootfsRoute(b), 2, true) |
| return err |
| }, |
diff --git a/internal/activator/rootfsdb.go b/internal/activator/rootfsdb.go| new file mode 100644 |
| index 000000000..63caaf174 |
| --- /dev/null |
| +++ b/internal/activator/rootfsdb.go |
| @@ -0,0 +1,224 @@ |
| +// rootfsdb.go is D7 of rootfs apps Plan 3 (Task 7, Astra R1 finding 8): |
| +// the empty SQLite database a rootfs instance's first boot gets at |
| +// CARLOS_DB. A binary app creates its database when it boots; a rootfs app |
| +// whose data lives elsewhere never does, and litestream replicates nothing |
| +// for a file that does not exist, so after its first serve the row would |
| +// read as "served, no database, no replica" and every restart would be |
| +// refused (errRootfsReplicaMissing). An app that does use SQLite opens an |
| +// existing, empty database: WAL mode, the default page size, no tables. |
| +package activator |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "io/fs" |
| + "log" |
| + "os" |
| + "path/filepath" |
| + "sync" |
| + |
| + "github.com/carlosframework/platform/internal/instancefs" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/registry" |
| + |
| + _ "modernc.org/sqlite" |
| +) |
| + |
| +// rootfsDBTemp is the placeholder's name in the instance directory until |
| +// it is renamed onto the database's own name. |
| +const rootfsDBTemp = ".carlos-db-placeholder.tmp" |
| + |
| +// errRootfsDBTaken: something is already at the database's name, though |
| +// Restore saw none. Whatever it is, it is left as it is. |
| +var errRootfsDBTaken = errors.New("activator: something is already at the instance's database path; it was left as it is") |
| + |
| +// errRootfsDBChanged: the placeholder written into the instance directory |
| +// is no longer the file or the bytes the agent wrote. |
| +var errRootfsDBChanged = errors.New("activator: the placeholder database was replaced in the instance directory") |
| + |
| +var ( |
| + emptyDBOnce sync.Once |
| + emptyDBBytes []byte |
| + emptyDBErr error |
| +) |
| + |
| +// emptySQLiteDB is an empty SQLite database's bytes, built once per |
| +// process in a private temporary directory the agent owns: sql.Open, a |
| +// busy_timeout, journal_mode=WAL (which writes page 1), Close, read, |
| +// remove. The SQLite driver only ever opens this private copy, never a |
| +// path in a tenant-writable directory. |
| +func emptySQLiteDB() ([]byte, error) { |
| + emptyDBOnce.Do(func() { emptyDBBytes, emptyDBErr = buildEmptySQLiteDB() }) |
| + return emptyDBBytes, emptyDBErr |
| +} |
| + |
| +func buildEmptySQLiteDB() ([]byte, error) { |
| + dir, err := os.MkdirTemp("", "carlos-empty-db-") |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer os.RemoveAll(dir) |
| + path := filepath.Join(dir, "empty.db") |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + return nil, err |
| + } |
| + db.SetMaxOpenConns(1) |
| + var mode string |
| + _, err = db.Exec("PRAGMA busy_timeout=5000") |
| + if err == nil { |
| + err = db.QueryRow("PRAGMA journal_mode=WAL").Scan(&mode) |
| + } |
| + if cerr := db.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + return nil, fmt.Errorf("activator: build an empty database: %w", err) |
| + } |
| + if mode != "wal" { |
| + return nil, fmt.Errorf("activator: build an empty database: journal mode %q, not wal", mode) |
| + } |
| + raw, err := os.ReadFile(path) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(raw) == 0 { |
| + return nil, errors.New("activator: build an empty database: SQLite wrote nothing") |
| + } |
| + return raw, nil |
| +} |
| + |
| +// PlaceRootfsDB places a rootfs first boot's empty database at the row's |
| +// nested database path (the CARLOS_DB the web process gets), under the |
| +// wake's lease, before anything runs (Plan 3 Task 7, D7). |
| +// |
| +// The instance directory is the tenant uid's to write, so the file is |
| +// written as placeSeed writes one: emptySQLiteDB's bytes to rootfsDBTemp |
| +// through instancefs.OpenBeneath (O_CREATE|O_EXCL, 0600), synced, then |
| +// pinned by identity: reopened beneath the directory and refused unless it |
| +// is the same file with the same bytes, still the entry at the temp name, |
| +// then renamed onto the database's name with RENAME_NOREPLACE, so there is |
| +// no check-then-rename window [pf 8.6]. EEXIST means something is at the |
| +// base name, which Restore did not see: whatever it is, of any kind, is |
| +// left alone, never overwritten, and the refusal is logged. The temp name |
| +// is removed on every path. |
| +func (b *ExecBackend) PlaceRootfsDB(ctx context.Context, rt registry.Route) error { |
| + if !rt.Rootfs() { |
| + return fmt.Errorf("%s: a placeholder database is only for a rootfs instance", rt.Host) |
| + } |
| + p := b.pathsFor(rt) |
| + if p.layout != LayoutNested { |
| + return fmt.Errorf("%s: a rootfs database is placed only in a nested instance directory, and this row is %s", rt.Host, p.layout) |
| + } |
| + dir, base, err := splitDBPath(p.dbPath) |
| + if err != nil { |
| + return err |
| + } |
| + want, err := emptySQLiteDB() |
| + if err != nil { |
| + return err |
| + } |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + // The instance directory, as prepare makes it before a start. |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + return err |
| + } |
| + _ = instancefs.RemoveAllBeneath(dir, rootfsDBTemp) // a crashed attempt's |
| + defer func() { _ = instancefs.RemoveAllBeneath(dir, rootfsDBTemp) }() |
| + wrote, err := writeBeneathExcl(dir, rootfsDBTemp, want) |
| + if err != nil { |
| + return err |
| + } |
| + f, err := openSameFile(dir, rootfsDBTemp, wrote) |
| + if err != nil { |
| + return fmt.Errorf("%s: %w: %v", rt.Host, errRootfsDBChanged, err) |
| + } |
| + got, rerr := io.ReadAll(io.LimitReader(f, int64(len(want))+1)) |
| + f.Close() |
| + if rerr != nil { |
| + return rerr |
| + } |
| + if !bytes.Equal(got, want) { |
| + return fmt.Errorf("%s: %w", rt.Host, errRootfsDBChanged) |
| + } |
| + if err := sameFileAt(dir, rootfsDBTemp, wrote); err != nil { |
| + return fmt.Errorf("%s: %w: %v", rt.Host, errRootfsDBChanged, err) |
| + } |
| + if err := instancefs.RenameBetweenNoReplace(dir, rootfsDBTemp, dir, base); err != nil { |
| + if errors.Is(err, fs.ErrExist) { |
| + log.Printf("activator: %s: not placing the first database: %s is already taken (left as it is)", rt.Host, base) |
| + return fmt.Errorf("%s: %w", rt.Host, errRootfsDBTaken) |
| + } |
| + return err |
| + } |
| + if err := sameFileAt(dir, base, wrote); err != nil { |
| + // What was renamed is not the file this wrote: the temp name was |
| + // replaced after the last check. What is there now came from the |
| + // directory's other writer, as a file placed at the name directly |
| + // would have, so it is left as it is and never taken for ours. |
| + log.Printf("activator: %s: the first database at %s is not the one placed (left as it is)", rt.Host, base) |
| + return fmt.Errorf("%s: %w: %v", rt.Host, errRootfsDBChanged, err) |
| + } |
| + return nil |
| +} |
| + |
| +// restoredDBCheck is the proof a restored database must pass before |
| +// anything serves from it: lease.CheckDB (integrity and at least one table) |
| +// for a binary row, whose app made its own schema before its first |
| +// replication; checkRootfsRestoredDB for a rootfs row, whose replica may |
| +// be D7's placeholder and nothing more (an app that never opens CARLOS_DB), |
| +// which has no tables by design. Without it, the restart from the replica |
| +// that D7 exists for would read the placeholder as corrupt (Review Focus 8). |
| +func restoredDBCheck(rt registry.Route) func(path string) error { |
| + if rt.Rootfs() { |
| + return checkRootfsRestoredDB |
| + } |
| + return lease.CheckDB |
| +} |
| + |
| +// checkRootfsRestoredDB is CheckDB without the table count: the restored |
| +// file opens read-only and its integrity_check is ok. The agent restored |
| +// it into the instance directory itself, under the lease, before anything |
| +// of the instance runs, as CheckDB does for a binary row. |
| +func checkRootfsRestoredDB(path string) error { |
| + db, err := sql.Open("sqlite", "file:"+path+"?mode=ro") |
| + if err != nil { |
| + return err |
| + } |
| + defer db.Close() |
| + db.SetMaxOpenConns(1) |
| + if _, err := db.Exec("PRAGMA busy_timeout=5000"); err != nil { |
| + return fmt.Errorf("open: %w", err) |
| + } |
| + var res string |
| + if err := db.QueryRow("PRAGMA integrity_check").Scan(&res); err != nil { |
| + return fmt.Errorf("integrity_check: %w", err) |
| + } |
| + if res != "ok" { |
| + return fmt.Errorf("integrity_check: %s", res) |
| + } |
| + return nil |
| +} |
| + |
| +// writeBeneathExcl creates dir/name beneath dir (O_EXCL, 0600), writes |
| +// data, syncs it, and returns the identity of the file it wrote. |
| +func writeBeneathExcl(dir, name string, data []byte) (os.FileInfo, error) { |
| + f, err := instancefs.OpenBeneath(dir, name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) |
| + if err != nil { |
| + return nil, err |
| + } |
| + _, werr := f.Write(data) |
| + serr := f.Sync() |
| + fi, iderr := f.Stat() |
| + cerr := f.Close() |
| + if err := errors.Join(werr, serr, iderr, cerr); err != nil { |
| + return nil, err |
| + } |
| + return fi, nil |
| +} |
diff --git a/internal/activator/rootfsdb_test.go b/internal/activator/rootfsdb_test.go| new file mode 100644 |
| index 000000000..606e05acf |
| --- /dev/null |
| +++ b/internal/activator/rootfsdb_test.go |
| @@ -0,0 +1,319 @@ |
| +//go:build linux |
| + |
| +package activator |
| + |
| +// D7 (Plan 3 Task 7, Astra R1 finding 8), production-wired: the real |
| +// ExecBackend's PlaceRootfsDB and Restore, the replica a directory the |
| +// test owns (restoreReplica stubbed to copy from it), and a lease whose |
| +// replica's first upload copies the local database there. |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// TestPlaceRootfsDBWritesAnEmptySQLiteDatabase: the file is at the row's |
| +// nested database path, 0600, an SQLite database in WAL mode with no |
| +// tables that the restore check for a rootfs row accepts (and that the |
| +// binary check, which wants a table, would not); a symlink, file or |
| +// directory already at the name is left exactly as it was, nothing is |
| +// written through it, and the temp name is gone on every path. |
| +func TestPlaceRootfsDBWritesAnEmptySQLiteDatabase(t *testing.T) { |
| + t.Parallel() |
| + eb, _ := newRootfsBackend(t) |
| + rt := rootfsRoute(eb) |
| + dbPath := provision.NestedDBPath(eb.DataDir, rt.Host) |
| + if rt.DBPath != dbPath { |
| + t.Fatalf("the rootfs row's database is %q, want the nested %q", rt.DBPath, dbPath) |
| + } |
| + if err := eb.PlaceRootfsDB(context.Background(), rt); err != nil { |
| + t.Fatalf("PlaceRootfsDB: %v", err) |
| + } |
| + fi, err := os.Lstat(dbPath) |
| + if err != nil || !fi.Mode().IsRegular() || fi.Mode().Perm() != 0o600 { |
| + t.Fatalf("placed %v, %v: want a regular 0600 file", fi, err) |
| + } |
| + if err := checkRootfsRestoredDB(dbPath); err != nil { |
| + t.Fatalf("the rootfs restore check refuses the placeholder: %v", err) |
| + } |
| + if err := lease.CheckDB(dbPath); err == nil { |
| + t.Fatal("lease.CheckDB accepted a database with no tables: the rootfs check is no longer the only one that must") |
| + } |
| + db, err := sql.Open("sqlite", "file:"+dbPath+"?mode=ro") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var mode string |
| + var tables int |
| + if err := db.QueryRow("PRAGMA journal_mode").Scan(&mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := db.QueryRow("SELECT count(*) FROM sqlite_master").Scan(&tables); err != nil { |
| + t.Fatal(err) |
| + } |
| + db.Close() |
| + if mode != "wal" || tables != 0 { |
| + t.Fatalf("journal mode %q, %d schema entries; want wal and none", mode, tables) |
| + } |
| + assertNoTemp(t, filepath.Dir(dbPath)) |
| + |
| + for name, plant := range map[string]func(t *testing.T, path, outside string){ |
| + "symlink": func(t *testing.T, path, outside string) { |
| + if err := os.Symlink(outside, path); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "file": func(t *testing.T, path, _ string) { |
| + if err := os.WriteFile(path, []byte("the tenant's own"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "directory": func(t *testing.T, path, _ string) { |
| + if err := os.Mkdir(path, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + eb, _ := newRootfsBackend(t) |
| + rt := rootfsRoute(eb) |
| + dir := filepath.Dir(rt.DBPath) |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + outside := filepath.Join(t.TempDir(), "outside") |
| + if err := os.WriteFile(outside, []byte("not the instance's"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + plant(t, rt.DBPath, outside) |
| + before, _ := os.Lstat(rt.DBPath) |
| + err := eb.PlaceRootfsDB(context.Background(), rt) |
| + if !errors.Is(err, errRootfsDBTaken) { |
| + t.Fatalf("PlaceRootfsDB over a planted %s = %v, want errRootfsDBTaken", name, err) |
| + } |
| + after, aerr := os.Lstat(rt.DBPath) |
| + if aerr != nil || !os.SameFile(before, after) || before.Mode() != after.Mode() { |
| + t.Fatalf("the planted %s changed: %v %v", name, after, aerr) |
| + } |
| + if got, _ := os.ReadFile(outside); string(got) != "not the instance's" { |
| + t.Fatalf("written through the planted %s: %q", name, got) |
| + } |
| + if name == "file" { |
| + if got, _ := os.ReadFile(rt.DBPath); string(got) != "the tenant's own" { |
| + t.Fatalf("the planted file was overwritten: %q", got) |
| + } |
| + } |
| + assertNoTemp(t, dir) |
| + }) |
| + } |
| +} |
| + |
| +func assertNoTemp(t *testing.T, dir string) { |
| + t.Helper() |
| + if _, err := os.Lstat(filepath.Join(dir, rootfsDBTemp)); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("the temp name is still there: %v", err) |
| + } |
| +} |
| + |
| +// bucketRig is the replica side of TestRootfsAppWithoutSQLiteRestarts: a |
| +// directory standing in for the instance's replica prefix. |
| +type bucketRig struct { |
| + dir string |
| + mu sync.Mutex |
| + restores int |
| + syncs int |
| +} |
| + |
| +func (r *bucketRig) replica() string { return filepath.Join(r.dir, "replica.db") } |
| + |
| +func copyFile(src, dst string) error { |
| + in, err := os.Open(src) |
| + if err != nil { |
| + return err |
| + } |
| + defer in.Close() |
| + out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err := io.Copy(out, in); err != nil { |
| + out.Close() |
| + return err |
| + } |
| + return out.Close() |
| +} |
| + |
| +// bucketRep is the running replica: its first upload copies the local |
| +// database to the bucket; Close is the sleep's final checkpoint. |
| +type bucketRep struct { |
| + rig *bucketRig |
| + dbPath string |
| +} |
| + |
| +func (r *bucketRep) Err() error { return nil } |
| +func (r *bucketRep) SyncAndWait(context.Context) error { |
| + r.rig.mu.Lock() |
| + r.rig.syncs++ |
| + r.rig.mu.Unlock() |
| + return copyFile(r.dbPath, r.rig.replica()) |
| +} |
| +func (r *bucketRep) Close(context.Context) error { return nil } |
| + |
| +type bucketLease struct{ rig *bucketRig } |
| + |
| +func (l bucketLease) Replicate(_ context.Context, dbPath string, _ time.Duration) (Rep, error) { |
| + return &bucketRep{rig: l.rig, dbPath: dbPath}, nil |
| +} |
| +func (bucketLease) Release(context.Context) error { return nil } |
| + |
| +// bucketBackend is the real ExecBackend with the lease over the rig, and |
| +// PlaceRootfsDB counted on its way to the real one. |
| +type bucketBackend struct { |
| + *ExecBackend |
| + rig *bucketRig |
| + mu sync.Mutex |
| + placed int |
| +} |
| + |
| +func (b *bucketBackend) Acquire(context.Context, registry.Route) (Lease, error) { |
| + return bucketLease{rig: b.rig}, nil |
| +} |
| + |
| +func (b *bucketBackend) PlaceRootfsDB(ctx context.Context, rt registry.Route) error { |
| + b.mu.Lock() |
| + b.placed++ |
| + b.mu.Unlock() |
| + return b.ExecBackend.PlaceRootfsDB(ctx, rt) |
| +} |
| + |
| +func (b *bucketBackend) placements() int { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + return b.placed |
| +} |
| + |
| +// Review Focus 8: an app that never opens CARLOS_DB restarts. Its first |
| +// wake places the placeholder and serves, and the replica holds it after |
| +// the first sync. Once it has served (GoodVersion set): (a) a wake on the |
| +// same box uses the warm file, with no refusal and no new placeholder; |
| +// (b) with the local database gone (a new box, a lost disk), Restore |
| +// restores the placeholder from the replica and the wake serves; (c) with |
| +// the replica gone too, the wake refuses with errRootfsReplicaMissing, |
| +// starts nothing and places nothing. |
| +func TestRootfsAppWithoutSQLiteRestarts(t *testing.T) { |
| + eb, ctl, rt := newStagedRootfsRig(t) |
| + ctl.setServe(serveVersions(t, eb, rt, 0, "v1")) // serves, never opens CARLOS_DB |
| + rig := &bucketRig{dir: t.TempDir()} |
| + old := restoreReplica |
| + restoreReplica = func(_ context.Context, dbPath, _, _, _ string) (bool, error) { |
| + rig.mu.Lock() |
| + defer rig.mu.Unlock() |
| + if _, err := os.Stat(rig.replica()); errors.Is(err, os.ErrNotExist) { |
| + return false, nil |
| + } |
| + rig.restores++ |
| + return true, copyFile(rig.replica(), dbPath) |
| + } |
| + t.Cleanup(func() { restoreReplica = old }) |
| + bb := &bucketBackend{ExecBackend: eb, rig: rig} |
| + 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}, bb, reg) |
| + a.gens = true |
| + armRootfsForTest(a) |
| + t.Cleanup(func() { a.Shutdown(context.Background()) }) |
| + |
| + wake := func() error { |
| + done, err := a.beginRequest(context.Background(), rt) |
| + if err == nil { |
| + done() |
| + } |
| + return err |
| + } |
| + sleep := func() { |
| + t.Helper() |
| + a.mu.Lock() |
| + e := a.entries[rt.Host] |
| + if e == nil || e.state != actAwake { |
| + a.mu.Unlock() |
| + t.Fatalf("no awake entry to stop: %+v", e) |
| + } |
| + a.beginStopLocked(e, StopIdle) |
| + a.mu.Unlock() |
| + waitFor(t, "the instance to sleep", func() bool { return a.entryCount() == 0 }) |
| + } |
| + removeLocal := func() { |
| + for _, s := range []string{"", "-wal", "-shm"} { |
| + if err := os.Remove(rt.DBPath + s); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + |
| + // The first boot. |
| + if err := wake(); err != nil { |
| + t.Fatalf("first wake: %v; calls:\n%s", err, ctl.joined()) |
| + } |
| + if bb.placements() != 1 || rig.syncs != 1 { |
| + t.Fatalf("placements %d, first uploads %d; want 1, 1", bb.placements(), rig.syncs) |
| + } |
| + local, _ := os.ReadFile(rt.DBPath) |
| + inBucket, err := os.ReadFile(rig.replica()) |
| + if err != nil || len(local) == 0 || !bytes.Equal(local, inBucket) { |
| + t.Fatalf("the replica does not hold the placeholder after the first sync (%v)", err) |
| + } |
| + sleep() |
| + rt.GoodVersion = "v1" // it has served |
| + |
| + t.Run("a: warm on the same box", func(t *testing.T) { |
| + if err := wake(); err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + if bb.placements() != 1 || rig.restores != 0 { |
| + t.Fatalf("placements %d, restores %d; want no new placeholder and no restore", bb.placements(), rig.restores) |
| + } |
| + sleep() |
| + }) |
| + t.Run("b: the local database is gone", func(t *testing.T) { |
| + removeLocal() |
| + if err := wake(); err != nil { |
| + t.Fatalf("wake from the replica: %v", err) |
| + } |
| + if rig.restores != 1 || bb.placements() != 1 { |
| + t.Fatalf("restores %d, placements %d; want the replica restored and no new placeholder", rig.restores, bb.placements()) |
| + } |
| + sleep() |
| + }) |
| + t.Run("c: the replica is gone too", func(t *testing.T) { |
| + removeLocal() |
| + if err := os.Remove(rig.replica()); err != nil { |
| + t.Fatal(err) |
| + } |
| + starts := len(ctl.started()) |
| + err := wake() |
| + if !errors.Is(err, errRootfsReplicaMissing) { |
| + t.Fatalf("wake = %v, want errRootfsReplicaMissing", err) |
| + } |
| + if len(ctl.started()) != starts || bb.placements() != 1 { |
| + t.Fatalf("starts %d -> %d, placements %d: a served row booted or got a placeholder", starts, len(ctl.started()), bb.placements()) |
| + } |
| + if _, err := os.Stat(rt.DBPath); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("a database was written: %v", err) |
| + } |
| + }) |
| +} |
diff --git a/internal/activator/wakeplan.go b/internal/activator/wakeplan.go| index 0419da74e..867958047 100644 |
| --- a/internal/activator/wakeplan.go |
| +++ b/internal/activator/wakeplan.go |
| @@ -378,7 +378,7 @@ func (a *Service) spawnPlanned(ctx context.Context, e *actEntry, rt registry.Rou |
| var healthBy time.Time |
| var left time.Duration |
| if canFall { |
| - healthBy = e.wakeStart.Add(firstWakeBudget - firstWakeKillReserve) |
| + healthBy = e.wakeStart.Add(firstWakeBudgetFor(rt) - firstWakeKillReserve) |
| gate = verdictFloorGate(gate, healthBy, healthBoundFor(rt), &left) |
| } |
| // Every exec here that runs the good build in another build's place is |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index e89c5fdb0..f9a7049ae 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -671,12 +671,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| Claims: claims.Writes.Enabled, |
| Sweep: func(ctx context.Context) error { |
| sw, err := eb.Control.Sweep(ctx) |
| - if err != nil { |
| - log.Printf("agent: instance sweep: %v (nested wakes refuse until the channel answers)", err) |
| - } else if len(sw.Units) > 0 { |
| - log.Printf("agent: swept %d instance unit(s) left from a previous agent: %v", len(sw.Units), sw.Units) |
| - } |
| - return err |
| + return startupSwept(sw, err, svc) |
| }, |
| Recover: func(ctx context.Context, swept bool) *layout.Pass { |
| seedSweptAtStart.Store(swept) |
diff --git a/internal/host/layoutleg.go b/internal/host/layoutleg.go| index 7c2380e09..b0e3aac6a 100644 |
| --- a/internal/host/layoutleg.go |
| +++ b/internal/host/layoutleg.go |
| @@ -20,6 +20,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/layout" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -363,6 +364,32 @@ func startActivator(ctx context.Context, sweep func(context.Context) error, reco |
| start() |
| } |
| +// rootfsSweptMarker is the activator's MarkRootfsSwept. |
| +type rootfsSweptMarker interface{ MarkRootfsSwept() } |
| + |
| +// startupSwept is activatorStart's Sweep's answer to the control |
| +// service's one sweep of every instance unit a previous agent left (the |
| +// sweep itself stays in the Sweep literal, where the startup wiring guard |
| +// reads it): logged, and, only when it answered with no error, the proof |
| +// rootfs admission waits for |
| +// (MarkRootfsSwept, rootfs apps Plan 3 Task 7, Astra R3 3). A 502 (some |
| +// units would not stop) or a transport error marks nothing, and nothing |
| +// here sweeps again: a second full sweep after Start would stop this |
| +// agent's own units, so rootfs admission stays closed until an agent |
| +// restart sweeps clean, as seedSweptAtStart does for seeds. Binary rows |
| +// are unaffected either way. |
| +func startupSwept(sw instancectl.SweepResponse, err error, svc rootfsSweptMarker) error { |
| + if err != nil { |
| + log.Printf("agent: instance sweep: %v (nested wakes refuse until the channel answers; rootfs instances stay off until the agent restarts with a clean sweep)", err) |
| + return err |
| + } |
| + if len(sw.Units) > 0 { |
| + log.Printf("agent: swept %d instance unit(s) left from a previous agent: %v", len(sw.Units), sw.Units) |
| + } |
| + svc.MarkRootfsSwept() |
| + return nil |
| +} |
| + |
| // activatorStart keeps sweep, recovery and Start ordered. Legacy boxes run |
| // the sequence in the background; claim boxes still call Start alone. |
| // Ready releases requests and agent duties only after Start returns. The |
diff --git a/internal/host/rollout.go b/internal/host/rollout.go| index c401883db..6ae5ee5b6 100644 |
| --- a/internal/host/rollout.go |
| +++ b/internal/host/rollout.go |
| @@ -403,6 +403,10 @@ func armRollout(ctx context.Context, getenv func(string) string, svc *activator. |
| m.Pass(routes) |
| } |
| rolloutMgr.Store(m) |
| + // The runtime half of D2 (rootfs apps Plan 3 Task 7): rootfs rows start |
| + // only where the scheduler has armed on this boot. Never on a |
| + // refuseManaged path, which returns before here. |
| + svc.ArmRootfs() |
| log.Printf("agent: overlap swaps armed (%s=overlap)", rollout.SwapEnv) |
| return m |
| } |
diff --git a/internal/host/rootfsplacement.go b/internal/host/rootfsplacement.go| index 66e47b851..9a216f1a9 100644 |
| --- a/internal/host/rootfsplacement.go |
| +++ b/internal/host/rootfsplacement.go |
| @@ -216,7 +216,13 @@ type fleetOwnerAnswer struct { |
| // completed sees the cached answer. A failed read is shared with the |
| // callers that waited for it and cached for none: the next caller reads |
| // again. |
| -func fleetOwnerCheck(store release.Store, fleet string, now func() time.Time) func(acct string) (bool, error) { |
| +// |
| +// ctx (Plan 3 Task 7) bounds the caller: the read a caller starts derives |
| +// its deadline from that caller's ctx, and a caller waiting on another's |
| +// read stops waiting when its own ctx ends. A read that ended with its |
| +// starter's ctx is an error like any other: shared with its waiters, cached |
| +// for none. |
| +func fleetOwnerCheck(store release.Store, fleet string, now func() time.Time) func(ctx context.Context, acct string) (bool, error) { |
| var mu sync.Mutex |
| cache := map[string]fleetOwnerAnswer{} |
| inflight := map[string]*fleetOwnerRead{} |
| @@ -225,9 +231,9 @@ func fleetOwnerCheck(store release.Store, fleet string, now func() time.Time) fu |
| cache[acct] = fleetOwnerAnswer{owns: owns, until: now().Add(ttl)} |
| mu.Unlock() |
| } |
| - read := func(acct string) (bool, error) { |
| + read := func(ctx context.Context, acct string) (bool, error) { |
| key := release.FleetOwnerKey(acct, fleet) |
| - ctx, cancel := context.WithTimeout(context.Background(), fleetOwnerReadTimeout) |
| + ctx, cancel := context.WithTimeout(ctx, fleetOwnerReadTimeout) |
| defer cancel() |
| body, _, err := store.Get(ctx, key) |
| if errors.Is(err, os.ErrNotExist) { |
| @@ -248,7 +254,7 @@ func fleetOwnerCheck(store release.Store, fleet string, now func() time.Time) fu |
| remember(acct, true, fleetOwnerPositiveTTL) |
| return true, nil |
| } |
| - return func(acct string) (bool, error) { |
| + return func(ctx context.Context, acct string) (bool, error) { |
| if acct == "" || acct == "." || acct == ".." || strings.ContainsAny(acct, `/\`) { |
| return false, nil |
| } |
| @@ -259,13 +265,17 @@ func fleetOwnerCheck(store release.Store, fleet string, now func() time.Time) fu |
| } |
| if r, ok := inflight[acct]; ok { |
| mu.Unlock() |
| - <-r.done |
| - return r.owns, r.err |
| + select { |
| + case <-r.done: |
| + return r.owns, r.err |
| + case <-ctx.Done(): |
| + return false, ctx.Err() |
| + } |
| } |
| r := &fleetOwnerRead{done: make(chan struct{})} |
| inflight[acct] = r |
| mu.Unlock() |
| - r.owns, r.err = read(acct) |
| + r.owns, r.err = read(ctx, acct) |
| mu.Lock() |
| delete(inflight, acct) |
| mu.Unlock() |
| @@ -335,19 +345,21 @@ type agentRootfs struct { |
| pools string |
| claim bool |
| overlap bool // swapArming's answer, never asked again |
| - owner func(acct string) (bool, error) |
| + owner func(ctx context.Context, acct string) (bool, error) |
| } |
| // armedRootfs is the agent's rootfs wiring, for the status tick; nil on a |
| // box with no activator. |
| var armedRootfs atomic.Pointer[agentRootfs] |
| -// ready asks the control service's /ready/rootfs under DeadlineReady. |
| -func (a *agentRootfs) ready() error { |
| +// ready asks the control service's /ready/rootfs under DeadlineReady, |
| +// within ctx: the wake's early gate hands the Service's bound, so a |
| +// shutdown ends the ask (Plan 3 Task 7). |
| +func (a *agentRootfs) ready(ctx context.Context) error { |
| if a.control == nil { |
| return errNoRootfsControl |
| } |
| - ctx, cancel := context.WithTimeout(context.Background(), instancectl.DeadlineReady) |
| + ctx, cancel := context.WithTimeout(ctx, instancectl.DeadlineReady) |
| defer cancel() |
| return a.control.ReadyRootfs(ctx) |
| } |
| @@ -358,17 +370,18 @@ func (a *agentRootfs) ready() error { |
| // no binary wake pays the nested self-check or a /ready read for it. |
| func (a *agentRootfs) arm(eb *activator.ExecBackend) { |
| eb.RootfsOK = a.ready |
| - eb.RootfsPlacement = func(rt registry.Route) error { |
| + eb.RootfsPlacement = func(ctx context.Context, rt registry.Route) error { |
| if rt.Runtime != registry.RuntimeRootfsV1 { |
| return nil |
| } |
| - return RootfsPlacementAllowed(a.facts(), rt) |
| + return RootfsPlacementAllowed(a.facts(ctx), rt) |
| } |
| } |
| // facts builds the facts the wake and the status probe share, from the |
| -// agent's wiring. Called per check (the readiness answer is live). |
| -func (a *agentRootfs) facts() RootfsBoxFacts { |
| +// agent's wiring. Called per check (the readiness answer is live). ctx |
| +// bounds the readiness ask and, through FleetOwner, the owner read. |
| +func (a *agentRootfs) facts(ctx context.Context) RootfsBoxFacts { |
| f := RootfsBoxFacts{ |
| SingleTenant: a.single, |
| Fleet: a.fleet, |
| @@ -377,13 +390,14 @@ func (a *agentRootfs) facts() RootfsBoxFacts { |
| OverlapSwaps: a.overlap, |
| NestedReady: a.nested != nil && a.nested() == nil, |
| } |
| - if err := a.ready(); err == nil { |
| + if err := a.ready(ctx); err == nil { |
| f.RootfsReady = true |
| } else { |
| f.RootfsBlocked = failingProbeCheck(err) |
| } |
| - if a.fleet != "" { |
| - f.FleetOwner = a.owner |
| + if a.fleet != "" && a.owner != nil { |
| + owner := a.owner |
| + f.FleetOwner = func(acct string) (bool, error) { return owner(ctx, acct) } |
| } |
| return f |
| } |
| @@ -409,7 +423,7 @@ func (a *agentRootfs) probe(p *status.Probes) { |
| if a == nil { |
| return |
| } |
| - f := a.facts() |
| + f := a.facts(context.Background()) |
| p.RootfsReady = RootfsBoxReady(f) == nil |
| p.RootfsBlocked = rootfsBlockedWord(f) |
| } |
diff --git a/internal/host/rootfsplacement_test.go b/internal/host/rootfsplacement_test.go| index 2ac2d53f2..4dbb91149 100644 |
| --- a/internal/host/rootfsplacement_test.go |
| +++ b/internal/host/rootfsplacement_test.go |
| @@ -94,7 +94,8 @@ func TestFleetOwnerCheckCoalescesConcurrentMisses(t *testing.T) { |
| } |
| var mu sync.Mutex |
| now := time.Now() |
| - check := fleetOwnerCheck(s, "pi", func() time.Time { mu.Lock(); defer mu.Unlock(); return now }) |
| + owner := fleetOwnerCheck(s, "pi", func() time.Time { mu.Lock(); defer mu.Unlock(); return now }) |
| + check := func(acct string) (bool, error) { return owner(context.Background(), acct) } |
| burst := func(t *testing.T, wantGets int) { |
| t.Helper() |
| release := s.holdGets() |
| @@ -285,7 +286,8 @@ func TestFleetOwnerCheckReadsTheRowsAccountRecord(t *testing.T) { |
| t.Fatal(err) |
| } |
| now := time.Now() |
| - check := fleetOwnerCheck(s, "pi", func() time.Time { return now }) |
| + owner := fleetOwnerCheck(s, "pi", func() time.Time { return now }) |
| + check := func(acct string) (bool, error) { return owner(context.Background(), acct) } |
| if ok, err := check("acct1"); !ok || err != nil { |
| t.Fatalf("owner: %v %v", ok, err) |
| } |
| @@ -337,7 +339,8 @@ func TestFleetOwnerCheckCachesOnlyNotFound(t *testing.T) { |
| t.Parallel() |
| s := &faultStore{Store: release.NewDirStore(t.TempDir())} |
| now := time.Now() |
| - check := fleetOwnerCheck(s, "pi", func() time.Time { return now }) |
| + owner := fleetOwnerCheck(s, "pi", func() time.Time { return now }) |
| + check := func(acct string) (bool, error) { return owner(context.Background(), acct) } |
| s.failNext(fmt.Errorf("fleet door: GET accounts/acct1/fleets/pi.json: %w", os.ErrNotExist)) |
| if ok, err := check("acct1"); ok || err != nil { |
| @@ -417,18 +420,18 @@ func TestAgentRootfsFacts(t *testing.T) { |
| {"no nested gate", &agentRootfs{control: fakeRootfsReady{}, overlap: true}, true, "", false}, |
| } |
| for _, c := range cases { |
| - f := c.a.facts() |
| + f := c.a.facts(context.Background()) |
| if f.RootfsReady != c.ready || f.RootfsBlocked != c.blocked || f.NestedReady != c.nestedReady { |
| t.Errorf("%s: facts = ready %v blocked %q nested %v, want %v %q %v", c.name, f.RootfsReady, f.RootfsBlocked, f.NestedReady, c.ready, c.blocked, c.nestedReady) |
| } |
| } |
| - owner := func(string) (bool, error) { return true, nil } |
| - fleet := (&agentRootfs{fleet: "pi", pools: "gold", single: true, claim: true, overlap: true, owner: owner}).facts() |
| + owner := func(context.Context, string) (bool, error) { return true, nil } |
| + fleet := (&agentRootfs{fleet: "pi", pools: "gold", single: true, claim: true, overlap: true, owner: owner}).facts(context.Background()) |
| if fleet.Fleet != "pi" || fleet.Pools != "gold" || !fleet.SingleTenant || !fleet.ClaimControl || !fleet.OverlapSwaps || fleet.FleetOwner == nil { |
| t.Errorf("fleet facts = %+v", fleet) |
| } |
| - if plat := (&agentRootfs{owner: owner}).facts(); plat.FleetOwner != nil { |
| + if plat := (&agentRootfs{owner: owner}).facts(context.Background()); plat.FleetOwner != nil { |
| t.Error("a platform box was handed an owner check") |
| } |
| } |
| @@ -457,7 +460,7 @@ func TestAgentRootfsStatusProbe(t *testing.T) { |
| // record still publishes rootfs_ready, and the tick reads no record. |
| read := 0 |
| a = &agentRootfs{nested: func() error { return nil }, control: fakeRootfsReady{}, overlap: true, fleet: "pi", |
| - owner: func(string) (bool, error) { read++; return false, nil }} |
| + owner: func(context.Context, string) (bool, error) { read++; return false, nil }} |
| a.probe(&p) |
| if !p.RootfsReady || read != 0 { |
| t.Errorf("fleet box: ready %v, owner reads %d", p.RootfsReady, read) |
diff --git a/internal/host/rootfsstart_test.go b/internal/host/rootfsstart_test.go| index 4252ad9cf..698503984 100644 |
| --- a/internal/host/rootfsstart_test.go |
| +++ b/internal/host/rootfsstart_test.go |
| @@ -99,7 +99,7 @@ func TestArmedRootfsGatesRefuseARootfsStartOnASharedBox(t *testing.T) { |
| rf.arm(eb) |
| binary := registry.Route{Host: "blog.example.com", Kind: "instance", Hibernate: true} |
| - if err := eb.RootfsPlacement(binary); err != nil { |
| + if err := eb.RootfsPlacement(context.Background(), binary); err != nil { |
| t.Fatalf("a binary row's placement: %v", err) |
| } |
| if nestedAsked != 0 || len(ctl.list()) != 0 { |
diff --git a/internal/host/startupsweep_test.go b/internal/host/startupsweep_test.go| new file mode 100644 |
| index 000000000..0493e9b44 |
| --- /dev/null |
| +++ b/internal/host/startupsweep_test.go |
| @@ -0,0 +1,168 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rolloutwords" |
| + "github.com/carlosframework/platform/internal/version" |
| +) |
| + |
| +type sweptMarks struct { |
| + mu sync.Mutex |
| + n int |
| +} |
| + |
| +func (m *sweptMarks) MarkRootfsSwept() { m.mu.Lock(); m.n++; m.mu.Unlock() } |
| + |
| +// TestStartupSweepMarksOnlyWhenClean: the startup sweep wrapper, over the |
| +// real control client, opens rootfs admission (MarkRootfsSwept) only when |
| +// the sweep answers with no error: never on a 502 (some instance units |
| +// would not stop) or a transport error. It sweeps exactly once per call, |
| +// and marking never sweeps. |
| +func TestStartupSweepMarksOnlyWhenClean(t *testing.T) { |
| + t.Parallel() |
| + for name, c := range map[string]struct { |
| + status int |
| + body instancectl.SweepResponse |
| + down bool // the control socket does not answer |
| + marks int |
| + }{ |
| + "clean": {status: http.StatusOK, body: instancectl.SweepResponse{Units: []string{"carlos-instance-rootfs-cmd@shop.example.com.service"}}, marks: 1}, |
| + "nothing left": {status: http.StatusOK, marks: 1}, |
| + "a unit kept": {status: http.StatusBadGateway, body: instancectl.SweepResponse{Failed: map[string]string{"carlos-instance-rootfs-cmd@shop.example.com.service": "stop: exit status 1"}}}, |
| + "transport error": {down: true}, |
| + "list-units fails": {status: http.StatusBadGateway}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + t.Parallel() |
| + sock := filepath.Join(t.TempDir(), "c.sock") |
| + var mu sync.Mutex |
| + sweeps := 0 |
| + if !c.down { |
| + ln, err := net.Listen("unix", sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method == http.MethodPost && r.URL.Path == "/sweep" { |
| + mu.Lock() |
| + sweeps++ |
| + mu.Unlock() |
| + } |
| + w.Header().Set(instancectl.BuildHeader, version.Build) |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(c.status) |
| + _ = json.NewEncoder(w).Encode(c.body) |
| + })} |
| + go func() { _ = srv.Serve(ln) }() |
| + t.Cleanup(func() { srv.Close() }) |
| + } |
| + marks := &sweptMarks{} |
| + // The agent's Sweep literal: one sweep through the real client, |
| + // its answer to startupSwept. |
| + sw, serr := instancectl.NewClient(sock).Sweep(context.Background()) |
| + err := startupSwept(sw, serr, marks) |
| + if (err == nil) != (c.marks == 1) { |
| + t.Fatalf("err = %v with %d marks wanted", err, c.marks) |
| + } |
| + if marks.n != c.marks { |
| + t.Fatalf("MarkRootfsSwept called %d times, want %d", marks.n, c.marks) |
| + } |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if want := map[bool]int{true: 0, false: 1}[c.down]; sweeps != want { |
| + t.Fatalf("swept %d times, want %d", sweeps, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Arming the overlap scheduler opens the rootfs admission's armed half |
| +// (ArmRootfs) and a refused arming does not: an unarmed box's refusal is |
| +// the member's RFS-3-C12 event with RFS-3-C14, an armed box's refusal for |
| +// another reason (here, no exec backend) is the operator's log alone. |
| +func TestArmingOpensRootfsAdmission(t *testing.T) { |
| + _, pub, err := release.GenerateKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + unarmed := "this box cannot run the instance: overlap swaps are not armed here" |
| + if got := rolloutwords.EventRootfsRefused; got != "this box cannot run the instance: %s" || rolloutwords.RootfsRefusedUnarmed != "overlap swaps are not armed here" { |
| + t.Fatalf("copy: %q %q", got, rolloutwords.RootfsRefusedUnarmed) |
| + } |
| + rt := registry.Route{Host: "shop.example.com", Kind: "instance", App: "shop", Account: "acme", Status: "ready", |
| + Hibernate: true, Runtime: registry.RuntimeRootfsV1} |
| + for name, c := range map[string]struct { |
| + store func(context.Context) (release.Store, error) |
| + armed bool |
| + }{ |
| + "armed": {func(context.Context) (release.Store, error) { return release.NewDirStore(t.TempDir()), nil }, true}, |
| + "unavailable": {func(context.Context) (release.Store, error) { return nil, errors.New("no deployment store") }, false}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + svc, reg, dd := rolloutFixture(t, true) |
| + svc.GenerationsFile = release.GenerationsPath(dd) |
| + sink := &armSink{} |
| + svc.Logs = sink |
| + svc.MarkRootfsSwept() |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + t.Cleanup(cancel) |
| + if m := armRollout(ctx, overlapEnv(pub), svc, reg, dd, nil, c.store); (m != nil) != c.armed { |
| + t.Fatalf("armed = %v, want %v", m != nil, c.armed) |
| + } |
| + t.Cleanup(func() { svc.Shutdown(context.Background()) }) |
| + rctx, rcancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer rcancel() |
| + req := httptest.NewRequest(http.MethodGet, "http://shop.example.com/", nil).WithContext(rctx) |
| + rec := httptest.NewRecorder() |
| + svc.ServeHTTP(rec, req, rt, http.NotFoundHandler()) |
| + if rec.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("status %d, want 503", rec.Code) |
| + } |
| + got := sink.has(unarmed) |
| + if got == c.armed { |
| + t.Fatalf("armed %v, unarmed event %v; events %v", c.armed, got, sink.list()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type armSink struct { |
| + mu sync.Mutex |
| + events []string |
| +} |
| + |
| +func (s *armSink) App(string, string, string, string) {} |
| +func (s *armSink) Event(_, _, _, _, msg string) { |
| + s.mu.Lock() |
| + s.events = append(s.events, msg) |
| + s.mu.Unlock() |
| +} |
| +func (s *armSink) list() []string { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return append([]string(nil), s.events...) |
| +} |
| +func (s *armSink) has(msg string) bool { |
| + for _, e := range s.list() { |
| + if e == msg { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +var _ activator.EventSink = (*armSink)(nil) |
diff --git a/internal/rolloutwords/words.go b/internal/rolloutwords/words.go| index 0e0edb74a..58313fe4e 100644 |
| --- a/internal/rolloutwords/words.go |
| +++ b/internal/rolloutwords/words.go |
| @@ -68,6 +68,15 @@ const ( |
| EventBounceSidecar = "sidecar restarting (%s)" |
| ) |
| +// The rootfs refusal event (rootfs apps Plan 3 Task 7), approved in the |
| +// rootfs copy deck (docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md): |
| +// a rootfs instance this box refused before its lease. The event is filled |
| +// with one of the reasons below. |
| +const ( |
| + EventRootfsRefused = "this box cannot run the instance: %s" // RFS-3-C12 |
| + RootfsRefusedUnarmed = "overlap swaps are not armed here" // RFS-3-C14, fills RFS-3-C12 |
| +) |
| + |
| // States: the REASON column of `carlos instances list` (spec §9.1). |
| const ( |
| StateHeld = "held: build %s failed on this box" |
diff --git a/internal/rolloutwords/words_test.go b/internal/rolloutwords/words_test.go| index d0e62ba62..5b363fc6e 100644 |
| --- a/internal/rolloutwords/words_test.go |
| +++ b/internal/rolloutwords/words_test.go |
| @@ -16,6 +16,7 @@ func allWords() map[string]string { |
| "EventStagingRefused": EventStagingRefused, "EventBounceInstance": EventBounceInstance, |
| "EventBounceSidecar": EventBounceSidecar, "StateHeld": StateHeld, "StateRollingOut": StateRollingOut, |
| "StateAsleep": StateAsleep, "StateConfigPending": StateConfigPending, "reasonUnknown": reasonUnknown, |
| + "EventRootfsRefused": EventRootfsRefused, "RootfsRefusedUnarmed": RootfsRefusedUnarmed, |
| } |
| for k, v := range causes { |
| out["cause "+k] = v |
| @@ -48,7 +49,7 @@ func TestVerbsAreWhereTheCallersPutThem(t *testing.T) { |
| "EventCohortHalted": 3, "EventFallbackServed": 2, "EventConfigPending": 2, |
| "EventStagingRefused": 1, "EventBounceInstance": 1, "EventBounceSidecar": 1, |
| "StateHeld": 1, "StateRollingOut": 0, "StateAsleep": 1, "StateConfigPending": 0, "reasonUnknown": 1, |
| - "unavailableUnknown": 1, |
| + "unavailableUnknown": 1, "EventRootfsRefused": 1, "RootfsRefusedUnarmed": 0, |
| } { |
| s := words[name] |
| if strings.Count(s, "%s") != want || strings.Count(s, "%") != want { |