activator: a rootfs lifetime's first-boot marker, so a replacement box never boots it empty (branch review P1-1)
GoodVersion is this box's registry, so a replacement box with a fresh registry read a served instance whose replica was lost as a first boot and placed an empty database. The evidence now lives beside the replica: <hibernate prefix>/rootfs-initialized/<incarnation>.json in the hibernate bucket (FilesStore, the replica's bucket and credentials), one key per record lifetime. A fresh rootfs wake with no good build reads the marker under the lease (present refuses with errRootfsReplicaMissing, unreadable refuses), records a pending first boot on the agent's own disk, places the placeholder, then writes the marker create-only and starts only once it is confirmed. A warm wake that finds this box's pending record writes the marker before anything starts, so a failed write or an agent stopped after the placement never serves unmarked. Every failure is a rootfs refusal with the lease given back. Budget: one GET per fresh rootfs wake, one PUT per first boot, nothing periodic; binary rows untouched.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+740
−8
internal/activator/activator.go+14 −3internal/activator/activator_test.go+4 −0internal/activator/production_backend_test.go+16 −0internal/activator/rootfs_gate_test.go+54 −0internal/activator/rootfs_invariants_test.go+6 −1internal/activator/rootfs_service.go+4 −3internal/activator/rootfsdb_test.go+12 −1internal/activator/rootfsmarker.go+276 −0internal/activator/rootfsmarker_test.go+354 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 5d772417a..be05c789d 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -2577,15 +2577,26 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| // 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. |
| + // database to replicate (Review Focus 8). The good build is this box's |
| + // registry only, so the first boot also asks the bucket (branch review |
| + // r1 P1-1, rootfsmarker.go): the lifetime's first-boot marker, read |
| + // under this lease, refuses when it is there or cannot be read, and is |
| + // written and confirmed before the start. A row that is not fresh only |
| + // settles a first boot this box left pending. A binary row has its seed |
| + // and creates its own file, and never takes this path. |
| placed := false |
| + if !fresh && rt.Rootfs() { |
| + if err := a.settleRootfsFirstBoot(ctx, rt); err != nil { |
| + w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease) |
| + return w, err |
| + } |
| + } |
| 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 { |
| + if err := a.rootfsFirstBoot(ctx, rt); err != nil { |
| w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease) |
| return w, err |
| } |
diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go| index 21b7fde52..49684b033 100644 |
| --- a/internal/activator/activator_test.go |
| +++ b/internal/activator/activator_test.go |
| @@ -520,6 +520,10 @@ type fakeBackend struct { |
| startableAsks map[string]int |
| placeholders int |
| placeErr error |
| + // marker is the first-boot marker capability (rootfsmarker_test.go): |
| + // the bucket's markers and this box's pending first boots, in memory. |
| + // Guarded by mu. |
| + marker fakeMarker |
| // repWrap, when set, wraps the replica each lease's Replicate hands |
| // back (Plan 3 Task 8: a replica with the lease's own loss signal). |
diff --git a/internal/activator/production_backend_test.go b/internal/activator/production_backend_test.go| index 466f4c8ac..6d0656f41 100644 |
| --- a/internal/activator/production_backend_test.go |
| +++ b/internal/activator/production_backend_test.go |
| @@ -46,6 +46,19 @@ func TestProductionBackendImplementsRootfsSeams(t *testing.T) { |
| } |
| return p.PlaceRootfsDB(context.Background(), unit) |
| }, |
| + "rootfsFirstBootMarker": func() error { |
| + m, ok := b.(rootfsFirstBootMarker) |
| + if !ok { |
| + t.Fatal("SplitBackend is not a rootfsFirstBootMarker") |
| + } |
| + if _, err := m.RootfsInitialized(context.Background(), unit); err == nil { |
| + return nil |
| + } |
| + if err := m.SettleRootfsFirstBoot(context.Background(), unit); err != nil { |
| + t.Errorf("SettleRootfsFirstBoot on a unit row = %v, want nothing pending", err) |
| + } |
| + return m.BeginRootfsFirstBoot(unit) |
| + }, |
| "ProcessReader": func() error { |
| r, ok := b.(ProcessReader) |
| if !ok { |
| @@ -69,6 +82,9 @@ func TestProductionBackendImplementsRootfsSeams(t *testing.T) { |
| if err := rows["rootfsDBPlacer"](); !errors.Is(err, errNoRootfsDB) { |
| t.Errorf("PlaceRootfsDB on a unit row = %v, want errNoRootfsDB", err) |
| } |
| + if err := rows["rootfsFirstBootMarker"](); !errors.Is(err, errNoRootfsMarker) { |
| + t.Errorf("BeginRootfsFirstBoot on a unit row = %v, want errNoRootfsMarker", err) |
| + } |
| if err := rows["ProcessReader"](); !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) { |
| t.Errorf("Processes on a unit row = %v, want a marked errNoRootfsControl", err) |
| } |
diff --git a/internal/activator/rootfs_gate_test.go b/internal/activator/rootfs_gate_test.go| index 23f2155ca..b574711a4 100644 |
| --- a/internal/activator/rootfs_gate_test.go |
| +++ b/internal/activator/rootfs_gate_test.go |
| @@ -63,6 +63,60 @@ func (b *fakeBackend) PlaceRootfsDB(context.Context, registry.Route) error { |
| return b.placeErr |
| } |
| +// fakeMarker is fakeBackend's first-boot marker: marked holds the |
| +// bucket's markers and pending this box's pending first boots, each keyed |
| +// host@incarnation; readErr and writeErr answer the read and the write. |
| +type fakeMarker struct { |
| + marked, pending map[string]bool |
| + readErr, writeErr error |
| + reads, writes int |
| +} |
| + |
| +func markerID(rt registry.Route) string { |
| + return fmt.Sprintf("%s@%d", rt.Host, rt.Incarnation) |
| +} |
| + |
| +func (b *fakeBackend) RootfsInitialized(_ context.Context, rt registry.Route) (bool, error) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + b.marker.reads++ |
| + b.order = append(b.order, "marker-read") |
| + if b.marker.readErr != nil { |
| + return false, b.marker.readErr |
| + } |
| + return b.marker.marked[markerID(rt)], nil |
| +} |
| + |
| +func (b *fakeBackend) BeginRootfsFirstBoot(rt registry.Route) error { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + if b.marker.pending == nil { |
| + b.marker.pending = map[string]bool{} |
| + } |
| + b.marker.pending[markerID(rt)] = true |
| + return nil |
| +} |
| + |
| +func (b *fakeBackend) SettleRootfsFirstBoot(_ context.Context, rt registry.Route) error { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + id := markerID(rt) |
| + if !b.marker.pending[id] { |
| + return nil |
| + } |
| + b.marker.writes++ |
| + b.order = append(b.order, "marker-write") |
| + if b.marker.writeErr != nil { |
| + return b.marker.writeErr |
| + } |
| + if b.marker.marked == nil { |
| + b.marker.marked = map[string]bool{} |
| + } |
| + b.marker.marked[id] = true |
| + delete(b.marker.pending, id) |
| + return nil |
| +} |
| + |
| // SyncAndWait is a first upload asked of the replica, counted and logged. |
| func (r *fakeRep) SyncAndWait(context.Context) error { |
| r.mu.Lock() |
diff --git a/internal/activator/rootfs_invariants_test.go b/internal/activator/rootfs_invariants_test.go| index 1be36acba..26c7cb441 100644 |
| --- a/internal/activator/rootfs_invariants_test.go |
| +++ b/internal/activator/rootfs_invariants_test.go |
| @@ -94,7 +94,7 @@ var ( |
| // the seam exists, whatever the forwarder is called. |
| var ( |
| rootfsNamePattern = regexp.MustCompile(`(?i)rootfs`) |
| - rootfsSeamInterfaces = []string{"RootfsControl", "rootfsStartable", "rootfsDBPlacer", "ProcessReader", "ReleaseBackend", "RootfsWorkerBackend"} |
| + rootfsSeamInterfaces = []string{"RootfsControl", "rootfsStartable", "rootfsDBPlacer", "ProcessReader", "ReleaseBackend", "RootfsWorkerBackend", "rootfsFirstBootMarker"} |
| ) |
| // isRootfsFile is the files the structural guard reads whole. |
| @@ -888,6 +888,11 @@ var rootfsRefusals = []struct { |
| {"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))}, |
| + // Branch review r1 P1-1: the first-boot marker's refusals, as |
| + // rootfsFirstBoot and settleRootfsFirstBoot mark them. |
| + {"no first-boot marker store (errNoRootfsMarker, marked)", refuseRootfs(fmt.Errorf("x: %w", errNoRootfsMarker))}, |
| + {"a first-boot marker that cannot be read (marked)", refuseRootfs(fmt.Errorf("x: read the first-boot marker: %w", errors.New("x")))}, |
| + {"a first-boot marker that cannot be written (marked)", refuseRootfs(fmt.Errorf("x: write the first-boot marker: %w", errors.New("x")))}, |
| // Task 15 round 1: the HA containment refusal of a rootfs row, as |
| // StartStaged marks it. |
| {"an HA containment refusal of a rootfs row (marked)", refuseRootfs(refusedUncontained(errors.New("x")))}, |
diff --git a/internal/activator/rootfs_service.go b/internal/activator/rootfs_service.go| index 01ccbe42f..0eca710b0 100644 |
| --- a/internal/activator/rootfs_service.go |
| +++ b/internal/activator/rootfs_service.go |
| @@ -323,9 +323,10 @@ func (a *Service) placeRootfsDB(ctx context.Context, rt registry.Route) error { |
| // (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. |
| +// uploads it, and if neither lands the next fresh wake on any box finds the |
| +// lifetime's first-boot marker, written and confirmed before the start |
| +// (rootfsmarker.go), and refuses (errRootfsReplicaMissing), the safe |
| +// direction. GoodVersion alone could not say so on another box. |
| func syncRootfsPlaceholder(ctx context.Context, host string, rep Rep) { |
| s, ok := rep.(interface{ SyncAndWait(context.Context) error }) |
| if !ok { |
diff --git a/internal/activator/rootfsdb_test.go b/internal/activator/rootfsdb_test.go| index 4309618d8..8e1003819 100644 |
| --- a/internal/activator/rootfsdb_test.go |
| +++ b/internal/activator/rootfsdb_test.go |
| @@ -25,6 +25,7 @@ import ( |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| // TestPlaceRootfsDBWritesAnEmptySQLiteDatabase: the file is at the row's |
| @@ -229,10 +230,20 @@ func (b *bucketBackend) placements() int { |
| // bucketService is a Service over the staged rootfs rig, with its replica |
| // on real Litestream and restoreReplica restoring from it. |
| func bucketService(t *testing.T) (*Service, *bucketBackend, *stagedRootfsCtl, registry.Route) { |
| + t.Helper() |
| + dir := t.TempDir() |
| + return bucketServiceOn(t, &bucketRig{dir: dir}, release.NewDirStore(filepath.Join(dir, "bucket"))) |
| +} |
| + |
| +// bucketServiceOn is bucketService over a given replica rig and hibernate |
| +// bucket (FilesStore, where the first-boot marker lives), so two boxes, |
| +// each with its own registry, data directory and agent, can share one |
| +// region's bucket. |
| +func bucketServiceOn(t *testing.T, rig *bucketRig, bucket release.Store) (*Service, *bucketBackend, *stagedRootfsCtl, registry.Route) { |
| t.Helper() |
| eb, ctl, rt := newStagedRootfsRig(t) |
| + eb.FilesStore = bucket |
| ctl.setServe(serveVersions(t, eb, rt, 0, "v1")) // serves, never opens CARLOS_DB |
| - rig := &bucketRig{dir: t.TempDir()} |
| old := restoreReplica |
| restoreReplica = func(ctx context.Context, dbPath, _, _, _ string) (bool, error) { return rig.restore(ctx, dbPath) } |
| t.Cleanup(func() { restoreReplica = old }) |
diff --git a/internal/activator/rootfsmarker.go b/internal/activator/rootfsmarker.go| new file mode 100644 |
| index 000000000..9055bbf86 |
| --- /dev/null |
| +++ b/internal/activator/rootfsmarker.go |
| @@ -0,0 +1,276 @@ |
| +// rootfsmarker.go is the cross-box half of "never boot empty after |
| +// serving" for a rootfs instance (branch review r1, P1-1). The local |
| +// good-build check (doWake step 2a, rt.GoodVersion) is registry state: a |
| +// replacement box with a fresh registry has none, so it cannot tell a first |
| +// boot from a lost database. The evidence that can is a marker in the |
| +// bucket the replica lives in, beside the replica, scoped to the |
| +// instance's lifetime: |
| +// |
| +// <hibernate prefix>/rootfs-initialized/<incarnation>.json |
| +// |
| +// It is written, and its write confirmed, before a placeholder instance |
| +// first starts. A fresh wake (no local database, no replica) reads it under |
| +// the lease before placing a placeholder: present, or unreadable, refuses. |
| +// |
| +// The request budget: one GET per fresh rootfs wake, one PUT per first |
| +// boot, nothing periodic. A warm wake asks the bucket nothing; it only |
| +// looks for this box's own pending first boot on its local disk. |
| +// |
| +// The pending first boot closes the gap between the placement and the |
| +// marker. A placed database is a warm cache to every later wake on this |
| +// box, which reads no marker; so the pending record is written on this |
| +// box's own disk (the agent's data directory, never the tenant's instance |
| +// directory) before the placement and removed only once the marker is |
| +// confirmed, and every warm wake that finds it writes the marker before |
| +// anything starts. A marker write that failed, or an agent that stopped |
| +// between the placement and the write, therefore never serves unmarked. |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// rootfsMarkerDir is the marker's directory under the instance's |
| +// hibernate prefix, beside the replica's generations and lock.json. |
| +const rootfsMarkerDir = "rootfs-initialized" |
| + |
| +// rootfsPendingDir is the agent's own record of first boots whose marker |
| +// is not confirmed yet, under ExecBackend.DataDir. |
| +const rootfsPendingDir = ".rootfs-first-boot" |
| + |
| +// rootfsMarkerKey is rt's marker key: the instance's hibernate prefix (the |
| +// replica's), then the lifetime. The lifetime is the row's Incarnation, |
| +// the record's lifetime number (provision's host incarnation slot): a |
| +// hostname deleted and created again gets a higher one, so the new |
| +// lifetime never reads the old lifetime's marker. A row from before |
| +// lifetimes has 0; two such lifetimes of one host share the key, and the |
| +// later one is refused (it reads as served), the safe direction. |
| +func (c Config) rootfsMarkerKey(rt registry.Route) string { |
| + return c.hibernatePrefix(rt.Host) + "/" + rootfsMarkerDir + "/" + strconv.FormatUint(rt.Incarnation, 10) + ".json" |
| +} |
| + |
| +// rootfsMarker is the marker's body. Nothing reads it: an object at the |
| +// key, whatever it holds, is the evidence. It says what wrote it, for an |
| +// operator. |
| +type rootfsMarker struct { |
| + Host string `json:"host"` |
| + Account string `json:"account"` |
| + App string `json:"app"` |
| + Incarnation uint64 `json:"incarnation"` |
| + At string `json:"at"` |
| +} |
| + |
| +// rootfsFirstBootMarker is the backend's half: the bucket marker and this |
| +// box's pending first boots. ExecBackend has it; SplitBackend forwards it. |
| +type rootfsFirstBootMarker interface { |
| + // RootfsInitialized reads rt's marker: true when an object is at the |
| + // key, false only on a definite not-found. Any other answer is an |
| + // error, and the wake refuses on it. |
| + RootfsInitialized(ctx context.Context, rt registry.Route) (bool, error) |
| + // BeginRootfsFirstBoot records on this box's disk, durably, that a |
| + // first boot of rt's lifetime is placing a database whose marker is not |
| + // confirmed yet. |
| + BeginRootfsFirstBoot(rt registry.Route) error |
| + // SettleRootfsFirstBoot writes rt's marker when this box has a first |
| + // boot of rt's lifetime pending, and clears the pending record once the |
| + // write is confirmed. Nothing pending: nil, with nothing asked of the |
| + // bucket. |
| + SettleRootfsFirstBoot(ctx context.Context, rt registry.Route) error |
| +} |
| + |
| +// errNoRootfsMarker is a backend, or a box, that cannot read or write a |
| +// rootfs instance's first-boot marker: a first boot refuses before it |
| +// places anything. |
| +var errNoRootfsMarker = errors.New("activator: this box cannot read or write a rootfs instance's first-boot marker") |
| + |
| +// rootfsFirstBoot is doWake's step 2a for a fresh rootfs row with no good |
| +// build, under the lease: the marker read (present or unreadable refuses, |
| +// present as errRootfsReplicaMissing), the pending record, the placeholder |
| +// (D7), then the marker written and confirmed. Every failure is a rootfs |
| +// refusal: nothing of the build has run, so it is never the build's |
| +// failure. The capabilities are checked before the bucket is asked. |
| +func (a *Service) rootfsFirstBoot(ctx context.Context, rt registry.Route) error { |
| + if _, ok := a.backend.(rootfsDBPlacer); !ok { |
| + return refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoRootfsDB)) |
| + } |
| + m, ok := a.backend.(rootfsFirstBootMarker) |
| + if !ok { |
| + return refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoRootfsMarker)) |
| + } |
| + marked, err := m.RootfsInitialized(ctx, rt) |
| + if err != nil { |
| + return refuseRootfs(fmt.Errorf("%s: read the first-boot marker: %w", rt.Host, err)) |
| + } |
| + if marked { |
| + log.Printf("activator: %s: no database and no replica, and lifetime %d has booted before (its first-boot marker is there): refusing an empty boot", rt.Host, rt.Incarnation) |
| + return refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errRootfsReplicaMissing)) |
| + } |
| + if err := m.BeginRootfsFirstBoot(rt); err != nil { |
| + return refuseRootfs(fmt.Errorf("%s: record the first boot: %w", rt.Host, err)) |
| + } |
| + if err := a.placeRootfsDB(ctx, rt); err != nil { |
| + return err |
| + } |
| + if err := m.SettleRootfsFirstBoot(ctx, rt); err != nil { |
| + return refuseRootfs(fmt.Errorf("%s: write the first-boot marker: %w", rt.Host, err)) |
| + } |
| + return nil |
| +} |
| + |
| +// settleRootfsFirstBoot is step 2a for a rootfs row that is not fresh: a |
| +// first boot this box left pending (its marker write failed, or the agent |
| +// stopped after the placement) gets its marker before anything starts. A |
| +// backend without the marker cannot have begun one. |
| +func (a *Service) settleRootfsFirstBoot(ctx context.Context, rt registry.Route) error { |
| + m, ok := a.backend.(rootfsFirstBootMarker) |
| + if !ok { |
| + return nil |
| + } |
| + if err := m.SettleRootfsFirstBoot(ctx, rt); err != nil { |
| + return refuseRootfs(fmt.Errorf("%s: write the first-boot marker: %w", rt.Host, err)) |
| + } |
| + return nil |
| +} |
| + |
| +// RootfsInitialized reads rt's marker from the hibernate bucket |
| +// (FilesStore, the replica's bucket and credentials). |
| +func (b *ExecBackend) RootfsInitialized(ctx context.Context, rt registry.Route) (bool, error) { |
| + if b.FilesStore == nil { |
| + return false, errNoRootfsMarker |
| + } |
| + _, _, err := b.FilesStore.Get(ctx, b.Cfg.rootfsMarkerKey(rt)) |
| + switch { |
| + case err == nil: |
| + return true, nil |
| + case errors.Is(err, os.ErrNotExist): |
| + return false, nil |
| + } |
| + return false, err |
| +} |
| + |
| +// rootfsPendingPath is rt's pending record: the agent's data directory, |
| +// which no tenant writes, one file per host and lifetime. |
| +func (b *ExecBackend) rootfsPendingPath(rt registry.Route) (string, error) { |
| + if b.DataDir == "" { |
| + return "", errNoRootfsMarker |
| + } |
| + name := rt.Host + "@" + strconv.FormatUint(rt.Incarnation, 10) |
| + if rt.Host == "" || filepath.Base(name) != name { |
| + return "", fmt.Errorf("activator: no pending first-boot record for host %q", rt.Host) |
| + } |
| + return filepath.Join(b.DataDir, rootfsPendingDir, name), nil |
| +} |
| + |
| +// BeginRootfsFirstBoot writes rt's pending record, synced, and its |
| +// directory synced, before the placement. |
| +func (b *ExecBackend) BeginRootfsFirstBoot(rt registry.Route) error { |
| + if b.FilesStore == nil { |
| + return errNoRootfsMarker |
| + } |
| + p, err := b.rootfsPendingPath(rt) |
| + if err != nil { |
| + return err |
| + } |
| + dir := filepath.Dir(p) |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + return err |
| + } |
| + f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) |
| + if err != nil { |
| + return err |
| + } |
| + _, werr := f.Write([]byte(b.Cfg.rootfsMarkerKey(rt) + "\n")) |
| + serr := f.Sync() |
| + cerr := f.Close() |
| + if err := errors.Join(werr, serr, cerr); err != nil { |
| + return err |
| + } |
| + syncDirBestEffort(dir) |
| + return nil |
| +} |
| + |
| +// SettleRootfsFirstBoot writes rt's marker if this box has its first boot |
| +// pending: create-only, so a marker already there (this box's own earlier |
| +// write whose answer was lost) is kept and counts as confirmed. The |
| +// pending record goes only after the write is confirmed; a removal that |
| +// fails is logged, and costs one more PUT at the next wake. |
| +func (b *ExecBackend) SettleRootfsFirstBoot(ctx context.Context, rt registry.Route) error { |
| + p, err := b.rootfsPendingPath(rt) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err := os.Lstat(p); errors.Is(err, os.ErrNotExist) { |
| + return nil |
| + } else if err != nil { |
| + return err |
| + } |
| + if b.FilesStore == nil { |
| + return errNoRootfsMarker |
| + } |
| + body, err := json.Marshal(rootfsMarker{Host: rt.Host, Account: rt.Account, App: rt.App, Incarnation: rt.Incarnation, At: time.Now().UTC().Format(time.RFC3339)}) |
| + if err != nil { |
| + return err |
| + } |
| + key := b.Cfg.rootfsMarkerKey(rt) |
| + if _, err := b.FilesStore.Put(ctx, key, body, ""); err != nil && !errors.Is(err, release.ErrCASConflict) { |
| + return err |
| + } |
| + if err := os.Remove(p); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + log.Printf("activator: %s: first-boot marker %s confirmed; its pending record stays: %v", rt.Host, key, err) |
| + return nil |
| + } |
| + syncDirBestEffort(filepath.Dir(p)) |
| + return nil |
| +} |
| + |
| +// syncDirBestEffort syncs a directory's entries where the platform can |
| +// (not on Windows, which refuses a directory sync). |
| +func syncDirBestEffort(dir string) { |
| + if d, err := os.Open(dir); err == nil { |
| + _ = d.Sync() |
| + d.Close() |
| + } |
| +} |
| + |
| +// RootfsInitialized, BeginRootfsFirstBoot and SettleRootfsFirstBoot |
| +// forward to the exec side. A unit-backed row, or an exec side without |
| +// them, is errNoRootfsMarker; Settle there has nothing pending. |
| +func (b *SplitBackend) RootfsInitialized(ctx context.Context, rt registry.Route) (bool, error) { |
| + if m, ok := b.execMarker(rt); ok { |
| + return m.RootfsInitialized(ctx, rt) |
| + } |
| + return false, fmt.Errorf("%s: %w", rt.Host, errNoRootfsMarker) |
| +} |
| + |
| +func (b *SplitBackend) BeginRootfsFirstBoot(rt registry.Route) error { |
| + if m, ok := b.execMarker(rt); ok { |
| + return m.BeginRootfsFirstBoot(rt) |
| + } |
| + return fmt.Errorf("%s: %w", rt.Host, errNoRootfsMarker) |
| +} |
| + |
| +func (b *SplitBackend) SettleRootfsFirstBoot(ctx context.Context, rt registry.Route) error { |
| + if m, ok := b.execMarker(rt); ok { |
| + return m.SettleRootfsFirstBoot(ctx, rt) |
| + } |
| + return nil |
| +} |
| + |
| +func (b *SplitBackend) execMarker(rt registry.Route) (rootfsFirstBootMarker, bool) { |
| + if rt.Backing == registry.BackingUnit { |
| + return nil, false |
| + } |
| + m, ok := b.Exec.(rootfsFirstBootMarker) |
| + return m, ok |
| +} |
diff --git a/internal/activator/rootfsmarker_test.go b/internal/activator/rootfsmarker_test.go| new file mode 100644 |
| index 000000000..50f53056a |
| --- /dev/null |
| +++ b/internal/activator/rootfsmarker_test.go |
| @@ -0,0 +1,354 @@ |
| +//go:build linux |
| + |
| +package activator |
| + |
| +// Branch review r1 P1-1: a rootfs instance never boots empty after it has |
| +// served, across boxes. The local good build (GoodVersion) is registry |
| +// state, so a replacement box with a fresh registry cannot tell a first |
| +// boot from a lost database; the lifetime's first-boot marker beside the |
| +// replica can (rootfsmarker.go). The two-box and the real-store tests run |
| +// the production ExecBackend over a shared bucket (release.DirStore) and |
| +// real Litestream; the rest use fakeBackend's marker. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// faultyBucket is a hibernate bucket whose Get or Put can be made to fail, |
| +// counting what it is asked. |
| +type faultyBucket struct { |
| + release.Store |
| + mu sync.Mutex |
| + getErr, putErr error |
| + gets, puts int |
| +} |
| + |
| +func (f *faultyBucket) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + f.mu.Lock() |
| + err := f.getErr |
| + if strings.Contains(key, "/"+rootfsMarkerDir+"/") { |
| + f.gets++ |
| + } |
| + f.mu.Unlock() |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + return f.Store.Get(ctx, key) |
| +} |
| + |
| +func (f *faultyBucket) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + f.mu.Lock() |
| + err := f.putErr |
| + if strings.Contains(key, "/"+rootfsMarkerDir+"/") { |
| + f.puts++ |
| + } |
| + f.mu.Unlock() |
| + if err != nil { |
| + return "", err |
| + } |
| + return f.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +func (f *faultyBucket) set(getErr, putErr error) { |
| + f.mu.Lock() |
| + f.getErr, f.putErr = getErr, putErr |
| + f.mu.Unlock() |
| +} |
| + |
| +func (f *faultyBucket) counts() (gets, puts int) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.gets, f.puts |
| +} |
| + |
| +func wakeOnce(a *Service, rt registry.Route) error { |
| + done, err := a.beginRequest(context.Background(), rt) |
| + if err == nil { |
| + done() |
| + } |
| + return err |
| +} |
| + |
| +func markerPresent(t *testing.T, s release.Store, eb *ExecBackend, rt registry.Route) bool { |
| + t.Helper() |
| + _, _, err := s.Get(context.Background(), eb.Cfg.rootfsMarkerKey(rt)) |
| + if err == nil { |
| + return true |
| + } |
| + if !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("read the marker: %v", err) |
| + } |
| + return false |
| +} |
| + |
| +// The failure the review names, end to end: box A first-boots lifetime 1, |
| +// writes the marker before the start and serves; it never records a good |
| +// build anywhere box B can see, and the replica is then lost. Box B, with |
| +// its own registry and data directory (GoodVersion empty, no database, no |
| +// replica), reads the marker under its lease and refuses: nothing placed, |
| +// nothing started, the lease given back, and never the build's failure. |
| +func TestRootfsReplacementBoxRefusesAfterTheReplicaIsLost(t *testing.T) { |
| + dir := t.TempDir() |
| + rig := &bucketRig{dir: dir} |
| + bucket := &faultyBucket{Store: release.NewDirStore(filepath.Join(dir, "bucket"))} |
| + |
| + aA, bbA, ctlA, rtA := bucketServiceOn(t, rig, bucket) |
| + rtA.Incarnation = 1 |
| + if err := wakeOnce(aA, rtA); err != nil { |
| + t.Fatalf("box A's first boot: %v; calls:\n%s", err, ctlA.joined()) |
| + } |
| + if bbA.placements() != 1 || !markerPresent(t, bucket.Store, bbA.ExecBackend, rtA) { |
| + t.Fatalf("box A: placements %d, marker %v; want 1, present", bbA.placements(), markerPresent(t, bucket.Store, bbA.ExecBackend, rtA)) |
| + } |
| + if gets, puts := bucket.counts(); gets != 1 || puts != 1 { |
| + t.Fatalf("box A's first boot asked the bucket %d GETs and %d PUTs for the marker, want 1 and 1", gets, puts) |
| + } |
| + sleepEntry(t, aA, rtA.Host) |
| + if err := os.RemoveAll(filepath.Join(rig.dir, "replica")); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + aB, bbB, ctlB, rtB := bucketServiceOn(t, rig, bucket) |
| + rtB.Incarnation = 1 |
| + if rtB.GoodVersion != "" || rtB.DBPath == rtA.DBPath { |
| + t.Fatalf("rig: box B's row %+v is not a fresh box's", rtB) |
| + } |
| + err := wakeOnce(aB, rtB) |
| + if !errors.Is(err, errRootfsReplicaMissing) || !errors.Is(err, errRootfsRefused) { |
| + t.Fatalf("box B's wake = %v, want a rootfs refusal with errRootfsReplicaMissing", err) |
| + } |
| + if v := verdictOf(err); v != gateNoOwnership { |
| + t.Errorf("verdictOf = %d, want gateNoOwnership (never the build's failure)", v) |
| + } |
| + if bbB.placements() != 0 || len(ctlB.started()) != 0 { |
| + t.Fatalf("box B placed %d and started %v: it booted empty", bbB.placements(), ctlB.started()) |
| + } |
| + if _, err := os.Stat(rtB.DBPath); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("box B wrote a database: %v", err) |
| + } |
| + if aB.entryCount() != 0 { |
| + t.Fatal("box B kept an entry for the refused wake") |
| + } |
| + if gets, puts := bucket.counts(); gets != 2 || puts != 1 { |
| + t.Fatalf("after box B: %d marker GETs and %d PUTs, want 2 and 1 (one GET for the fresh wake, no write)", gets, puts) |
| + } |
| +} |
| + |
| +// A deleted and recreated instance with the same host is a new lifetime |
| +// (a higher Incarnation): it does not inherit the old lifetime's marker, |
| +// so its fresh first boot places, writes its own marker and serves. |
| +func TestRootfsRecreatedLifetimeFirstBootsAfresh(t *testing.T) { |
| + dir := t.TempDir() |
| + rig := &bucketRig{dir: dir} |
| + bucket := release.NewDirStore(filepath.Join(dir, "bucket")) |
| + a, bb, ctl, rt := bucketServiceOn(t, rig, bucket) |
| + old := rt |
| + old.Incarnation = 1 |
| + body := []byte(`{"host":"` + rt.Host + `","incarnation":1}`) |
| + if _, err := bucket.Put(context.Background(), bb.Cfg.rootfsMarkerKey(old), body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + rt.Incarnation = 2 |
| + if err := wakeOnce(a, rt); err != nil { |
| + t.Fatalf("the new lifetime's first boot: %v; calls:\n%s", err, ctl.joined()) |
| + } |
| + if bb.placements() != 1 || len(ctl.started()) != 1 { |
| + t.Fatalf("placements %d, starts %d; want 1, 1", bb.placements(), len(ctl.started())) |
| + } |
| + if !markerPresent(t, bucket, bb.ExecBackend, rt) { |
| + t.Fatal("the new lifetime's marker was not written") |
| + } |
| + if bb.Cfg.rootfsMarkerKey(rt) == bb.Cfg.rootfsMarkerKey(old) { |
| + t.Fatal("two lifetimes share one marker key") |
| + } |
| +} |
| + |
| +// The marker sits beside the replica: under the instance's hibernate |
| +// prefix, one key per lifetime. |
| +func TestRootfsMarkerKeyIsBesideTheReplica(t *testing.T) { |
| + c := Config{Prefix: "instances"} |
| + rt := rootfsGateRoute("shop.example.com") |
| + rt.Incarnation = 7 |
| + if got, want := c.rootfsMarkerKey(rt), c.hibernatePrefix(rt.Host)+"/rootfs-initialized/7.json"; got != want { |
| + t.Fatalf("marker key %q, want %q", got, want) |
| + } |
| +} |
| + |
| +// A marker that cannot be written refuses the first boot before anything |
| +// starts, with the lease given back. The placed database is a warm cache |
| +// to the next wake on this box, which reads no marker: that wake writes it |
| +// first (the pending record), refuses while it still cannot, and starts |
| +// only once it is confirmed. |
| +func TestRootfsUnwritableMarkerRefusesTheFirstBoot(t *testing.T) { |
| + dir := t.TempDir() |
| + bucket := &faultyBucket{Store: release.NewDirStore(filepath.Join(dir, "bucket"))} |
| + a, bb, ctl, rt := bucketServiceOn(t, &bucketRig{dir: dir}, bucket) |
| + bucket.set(nil, errors.New("access denied")) |
| + |
| + for i := 0; i < 2; i++ { |
| + err := wakeOnce(a, rt) |
| + if err == nil || !strings.Contains(err.Error(), "access denied") || !errors.Is(err, errRootfsRefused) { |
| + t.Fatalf("wake %d = %v, want a rootfs refusal carrying the write's error", i, err) |
| + } |
| + if v := verdictOf(err); v != gateNoOwnership { |
| + t.Errorf("wake %d: verdictOf = %d, want gateNoOwnership", i, v) |
| + } |
| + if n := len(ctl.started()); n != 0 { |
| + t.Fatalf("wake %d: started %d with no marker confirmed", i, n) |
| + } |
| + } |
| + if _, puts := bucket.counts(); puts != 2 { |
| + t.Fatalf("marker PUTs %d, want 2: the warm retry must write it again", puts) |
| + } |
| + if bb.placements() != 1 { |
| + t.Fatalf("placements %d, want 1 (the retry is warm)", bb.placements()) |
| + } |
| + |
| + bucket.set(nil, nil) |
| + if err := wakeOnce(a, rt); err != nil { |
| + t.Fatalf("the wake once the bucket takes the write: %v; calls:\n%s", err, ctl.joined()) |
| + } |
| + if !markerPresent(t, bucket.Store, bb.ExecBackend, rt) || len(ctl.started()) != 1 { |
| + t.Fatalf("marker %v, starts %d; want present, 1", markerPresent(t, bucket.Store, bb.ExecBackend, rt), len(ctl.started())) |
| + } |
| + pend, _ := bb.rootfsPendingPath(rt) |
| + if _, err := os.Stat(pend); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("the pending record outlived its confirmed marker: %v", err) |
| + } |
| + sleepEntry(t, a, rt.Host) |
| + // Settled: a warm wake asks the bucket nothing. |
| + gets, puts := bucket.counts() |
| + if err := wakeOnce(a, rt); err != nil { |
| + t.Fatalf("a warm wake: %v", err) |
| + } |
| + if g, p := bucket.counts(); g != gets || p != puts { |
| + t.Fatalf("a settled warm wake asked the bucket %d GETs and %d PUTs", g-gets, p-puts) |
| + } |
| +} |
| + |
| +// A marker that cannot be read refuses (fail closed): no placeholder, no |
| +// pending record, no start, no write. |
| +func TestRootfsUnreadableMarkerRefuses(t *testing.T) { |
| + dir := t.TempDir() |
| + bucket := &faultyBucket{Store: release.NewDirStore(filepath.Join(dir, "bucket"))} |
| + a, bb, ctl, rt := bucketServiceOn(t, &bucketRig{dir: dir}, bucket) |
| + bucket.set(errors.New("slow down"), nil) |
| + err := wakeOnce(a, rt) |
| + if err == nil || !strings.Contains(err.Error(), "slow down") || !errors.Is(err, errRootfsRefused) { |
| + t.Fatalf("wake = %v, want a rootfs refusal carrying the read's error", err) |
| + } |
| + if errors.Is(err, errRootfsReplicaMissing) { |
| + t.Errorf("an unreadable marker reads as a present one: %v", err) |
| + } |
| + if bb.placements() != 0 || len(ctl.started()) != 0 { |
| + t.Fatalf("placements %d, starts %d; want 0, 0", bb.placements(), len(ctl.started())) |
| + } |
| + if _, puts := bucket.counts(); puts != 0 { |
| + t.Fatalf("marker PUTs %d after an unreadable read", puts) |
| + } |
| + pend, _ := bb.rootfsPendingPath(rt) |
| + if _, err := os.Stat(pend); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("a pending record was written: %v", err) |
| + } |
| +} |
| + |
| +// A box with no hibernate bucket store cannot read or write the marker: |
| +// the first boot refuses before it places anything. |
| +func TestRootfsFirstBootWithoutAMarkerStoreRefuses(t *testing.T) { |
| + a, bb, ctl, rt := bucketService(t) |
| + bb.FilesStore = nil |
| + err := wakeOnce(a, rt) |
| + if !errors.Is(err, errNoRootfsMarker) || !errors.Is(err, errRootfsRefused) { |
| + t.Fatalf("wake = %v, want a refused errNoRootfsMarker", err) |
| + } |
| + if bb.placements() != 0 || len(ctl.started()) != 0 { |
| + t.Fatalf("placements %d, starts %d; want 0, 0", bb.placements(), len(ctl.started())) |
| + } |
| +} |
| + |
| +// Through fakeBackend: the order (marker read, placeholder, marker write, |
| +// start), and each refusal giving the lease back with nothing started. |
| +func TestRootfsFirstBootMarkerOrderAndRefusals(t *testing.T) { |
| + t.Run("order", func(t *testing.T) { |
| + a, b, _, _ := gateService(t) |
| + b.restoreFresh = true |
| + if err := wakeOnce(a, rootfsGateRoute("shop.example.com")); err != nil { |
| + t.Fatalf("first wake: %v", err) |
| + } |
| + ev := b.events() |
| + idx := func(s string) int { |
| + for i, e := range ev { |
| + if e == s || strings.HasPrefix(e, s) { |
| + return i |
| + } |
| + } |
| + return -1 |
| + } |
| + r, p, w, s := idx("marker-read"), idx("placeholder"), idx("marker-write"), idx("start") |
| + if r < 0 || !(r < p && p < w && w < s) { |
| + t.Fatalf("order %v: want marker-read, placeholder, marker-write, start", ev) |
| + } |
| + }) |
| + for name, set := range map[string]func(b *fakeBackend, rt registry.Route){ |
| + "present": func(b *fakeBackend, rt registry.Route) { b.marker.marked = map[string]bool{markerID(rt): true} }, |
| + "unreadable": func(b *fakeBackend, _ registry.Route) { b.marker.readErr = errors.New("unreadable") }, |
| + "unwritable": func(b *fakeBackend, _ registry.Route) { b.marker.writeErr = errors.New("unwritable") }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + a, b, _, _ := gateService(t) |
| + b.restoreFresh = true |
| + rt := rootfsGateRoute("shop.example.com") |
| + b.mu.Lock() |
| + set(b, rt) |
| + b.mu.Unlock() |
| + err := dueWake(a, rt) |
| + if err == nil || !errors.Is(err, errRootfsRefused) { |
| + t.Fatalf("wake = %v, want a rootfs refusal", err) |
| + } |
| + if (name == "present") != errors.Is(err, errRootfsReplicaMissing) { |
| + t.Errorf("wake = %v: errRootfsReplicaMissing only for a present marker", err) |
| + } |
| + if b.starts != 0 || b.releases != 1 { |
| + t.Fatalf("starts %d, releases %d; want 0, 1", b.starts, b.releases) |
| + } |
| + if want := map[string]int{"present": 0, "unreadable": 0, "unwritable": 1}[name]; b.placeholders != want { |
| + t.Fatalf("placeholders %d, want %d", b.placeholders, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A binary row is untouched: a fresh wake and a warm one never read or |
| +// write a marker, nor record a pending first boot. |
| +func TestBinaryWakesAskNoMarker(t *testing.T) { |
| + for _, fresh := range []bool{true, false} { |
| + t.Run(fmt.Sprintf("fresh=%v", fresh), func(t *testing.T) { |
| + a, b, _, _ := testActivator(t, time.Hour) |
| + a.gens = true |
| + t.Cleanup(func() { a.Shutdown(context.Background()) }) |
| + b.restoreFresh = fresh |
| + rt := testRoute("blog.example.com") |
| + rt.Seed = `["seed"]` |
| + b.marker.pending = map[string]bool{markerID(rt): true} // never settled for a binary row |
| + if err := wakeOnce(a, rt); err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + if b.marker.reads != 0 || b.marker.writes != 0 || len(b.marker.marked) != 0 { |
| + t.Fatalf("a binary wake asked the marker: reads %d, writes %d, marked %v", b.marker.reads, b.marker.writes, b.marker.marked) |
| + } |
| + }) |
| + } |
| +} |