activator, provision: place and roll back file seeds on a fleet box
Fleet seeded create (#1139), slice 2, Task 10: design §3.5 and §3.6. Placement (internal/activator/seedfleet.go). On a customer-fleet box a file seed that is not yet placed: - is admitted flat as well as nested. Claim control and a foreign layout still refuse, and so does every other seed kind and every other box; - is read through SeedObjects.Open(acct, app, host, id); - never reads staging (R3-2). Anything under moves/<host>/ refuses the wake before the replica question, and the retry restore runs with staging promotion off (restorePlainStaging); - restores an existing replica only when the seed marker beside the database names this seed (R2-2). Otherwise nothing is restored; - reports mismatch, not-a-database and copy-exists through OnSeedFailed. Every other failure fails the wake, reports nothing and is retried. A staging listing that fails is one of those (D7). Rollback (internal/provision/seedfleet.go). finishAbortedSeed hands an aborted file seed on a fleet box to rollbackFleetFileSeed and returns: no snapshot delete, no record write. It is the only code that reports rolledback, and only after, under one fence with the host still rowless: - both local locations, nested and flat, were purged and then seen empty, whatever the layout reader says now (R2-1, D5); - an exhaustive listing found nothing under the replica prefix or the staging prefix (R3-1; never lease.HasReplica). Anything else is not proven: it logs and the record keeps the hostname. Objects found are reported as failed, copy-in-storage, with where. seedAction mints a ready file seed flat on a fleet box, and only when the box has the fleet hooks. Region seeds, imports, --from and every non-fleet box are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+1,878
−27
approved_fleet_seeded_copy_test.go+1 −0internal/activator/backend_exec.go+14 −5internal/activator/seedfleet.go+118 −0internal/activator/seedfleet_linux_test.go+677 −0internal/activator/seedfleet_test.go+24 −0internal/activator/seedplace.go+47 −12internal/activator/seedplace_linux_test.go+7 −4internal/host/seedwiring.go+4 −2internal/host/seedwiring_test.go+2 −2internal/provision/seedfleet.go+260 −0internal/provision/seedfleet_test.go+708 −0internal/provision/seedreconcile.go+16 −2
CI failed — run details
diff --git a/approved_fleet_seeded_copy_test.go b/approved_fleet_seeded_copy_test.go| index 827005226..514618d60 100644 |
| --- a/approved_fleet_seeded_copy_test.go |
| +++ b/approved_fleet_seeded_copy_test.go |
| @@ -38,6 +38,7 @@ func TestApprovedFleetSeededCopy(t *testing.T) { |
| {"FS-42", "internal/console/seedfile_copy.go", "began seeding %s from a file (%s, %d bytes)"}, |
| {"FS-43", "internal/console/seedfile_copy.go", "uploaded the seed file for %s"}, |
| {"FS-25", "internal/console/seedfile_copy.go", "This deployment’s seeds floor does not allow seed files yet. An operator publishes it again with carlos system seeds-floor publish."}, |
| + {"FS-40", "internal/activator/seedfleet.go", "%s could not start from its seed: a copy of data already exists for this hostname."}, |
| {"docs seed-file", "docs/site/cli.md", "To start a new instance from a SQLite database file you already have, add --seed-file. The file can be up to 4 GiB. The CLI uploads it, the console checks that it is a sound database, and the new instance starts from it the first time it wakes. This is for an app that runs in a region. You can't combine it with --from, and the new instance is an ordinary one, so --kind, --addr and --role don't apply. If the upload or the check fails, nothing is created, and the hostname is free again once its box has cleaned up."}, |
| } |
| for _, row := range rows { |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index 4925f51b4..b35f239e6 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -326,6 +326,14 @@ type ExecBackend struct { |
| // OnSeedPlaced records a seed placed (Task 4): the record's CAS to |
| // placed, then the snapshot's delete. Nil: not recorded here. |
| OnSeedPlaced func(ctx context.Context, account, app, host, id string) error |
| + // CustomerFleet is a box of a customer fleet (CARLOS_FLEET resolves). |
| + // It runs flat, and places a file seed by the fleet rules (seedfleet.go). |
| + CustomerFleet bool |
| + // OnSeedFailed reports a fleet file seed's terminal failure (fleet |
| + // seeded create design §3.6) with a reason code: "mismatch", |
| + // "not-a-database" or "copy-exists". Nil off a fleet: the wake fails |
| + // and logs, as before. |
| + OnSeedFailed func(ctx context.Context, acct, app, host, id, code string) error |
| // OnDemoClaimSeedWake rechecks the durable claim after taking the lease, |
| // before restore or exec. A stale row cannot restart an aborted target. |
| OnDemoClaimSeedWake func(context.Context, registry.Route, *seeds.RowSeed) error |
| @@ -1071,10 +1079,11 @@ func (b *ExecBackend) Restore(ctx context.Context, rt registry.Route) (bool, err |
| return b.restorePlain(ctx, rt) |
| } |
| -// restorePlain is Restore for a row with no seed to place: the warm cache, |
| -// then the staging fallback, then the host's own replica, and fresh only |
| -// when there is none of the three. |
| -func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool, error) { |
| +// restorePlainStaging is restorePlain (seedfleet.go), with the staging |
| +// fallback on or off. Off is for a fleet file seed's retry alone, which |
| +// never reads staging (fleet seeded create design §3.6, R3-2): the restore |
| +// then reads the host's own prefix and nothing else. |
| +func (b *ExecBackend) restorePlainStaging(ctx context.Context, rt registry.Route, staging bool) (bool, error) { |
| // An HA host restores by the HA rules (hawake.go), never through the |
| // warm cache or the staging fallback below. |
| if s, ha, err := b.haRestore(ctx, rt); err != nil { |
| @@ -1128,7 +1137,7 @@ func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool |
| // earlier stay on this box (the legacy cut does not delete the own |
| // prefix it leaves behind), and the promotion's mirror replaces it. |
| var promoted map[string]lease.MirrorObject |
| - if b.Mirror != nil && !b.Phase1 { |
| + if staging && b.Mirror != nil && !b.Phase1 { |
| var err error |
| if promoted, err = b.promoteStagedReplica(ctx, host); err != nil { |
| // HARD failure, same rule as restoreReplica's own error paths |
diff --git a/internal/activator/seedfleet.go b/internal/activator/seedfleet.go| new file mode 100644 |
| index 000000000..f7434bf31 |
| --- /dev/null |
| +++ b/internal/activator/seedfleet.go |
| @@ -0,0 +1,118 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +// File seeds on a customer-fleet box (fleet seeded create design §3.5, |
| +// §3.6). Placement is seededRestore's, with three rules of its own, each |
| +// for a seed that is not yet placed: |
| +// |
| +// - staging is never read. Anything under moves/<host>/ refuses the |
| +// wake before the replica question is asked, and the retry restore |
| +// runs with staging promotion off (R3-2); |
| +// - a replica under the host's prefix is restored only when the seed |
| +// marker beside the database names this seed. Any other replica was |
| +// not made by this seed and is never restored (R2-2); |
| +// - a failure that a retry cannot fix is reported to the console, which |
| +// aborts the seed. The hostname is then held until the box's rollback |
| +// proves nothing of it is left (provision.rollbackFleetFileSeed). |
| +// |
| +// Once placed, the row's wakes are ordinary restores. |
| + |
| +// fleetFileSeed reports a file seed this customer-fleet box has still to |
| +// place: the one case the rules above are for. A region box, a --from seed, |
| +// an import and a placed seed all answer false, and behave as before. |
| +func (b *ExecBackend) fleetFileSeed(src *seeds.RowSeed) bool { |
| + return b.CustomerFleet && src != nil && src.Kind == seeds.KindFile && src.State != seeds.StatePlaced |
| +} |
| + |
| +// seedCopyExists is FS-40: the member's sentence for a fleet seed file |
| +// refused because a copy this seed did not make is in the fleet's storage. |
| +func seedCopyExists(host string, err error) error { |
| + return &SeedPlacementError{Sentence: fmt.Sprintf("%s could not start from its seed: a copy of data already exists for this hostname.", host), |
| + Err: err, code: provision.SeedCodeCopyExists} |
| +} |
| + |
| +// restorePlain is Restore for a row with no seed to place: the warm cache, |
| +// then the staging fallback, then the host's own replica, and fresh only |
| +// when there is none of the three. |
| +func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool, error) { |
| + return b.restorePlainStaging(ctx, rt, true) |
| +} |
| + |
| +// stagingEmpty is the staging probe, over b.Mirror.List (which lists the |
| +// prefix whole): true only for a listing that answered and found nothing. |
| +// A box with no bucket reader cannot answer, which is an error and never |
| +// "empty". |
| +func (b *ExecBackend) stagingEmpty(ctx context.Context, host string) (bool, error) { |
| + if b.Mirror == nil { |
| + return false, errors.New("this box has no reader for its bucket's staging prefix") |
| + } |
| + staged, err := b.Mirror.List(ctx, b.Cfg.Bucket, MovesPrefix(host)) |
| + if err != nil { |
| + return false, err |
| + } |
| + return len(staged) == 0, nil |
| +} |
| + |
| +// fleetSeedStagingRefusal is the staging rule, asked before the replica |
| +// question: nil only when moves/<host>/ was listed and is empty. Objects |
| +// there are a copy this seed did not make (reported, FS-40). A listing |
| +// that fails is not an answer: the wake fails, nothing is reported, and the |
| +// next wake asks again (plan decision D7). |
| +func (b *ExecBackend) fleetSeedStagingRefusal(ctx context.Context, host string) error { |
| + empty, err := b.stagingEmpty(ctx, host) |
| + if err != nil { |
| + return fmt.Errorf("seed fallback for %s: cannot tell whether a staged copy of it exists: %w", host, err) |
| + } |
| + if !empty { |
| + return seedCopyExists(host, fmt.Errorf("objects under %s", MovesPrefix(host))) |
| + } |
| + return nil |
| +} |
| + |
| +// fleetSeedReplicaRefusal is the admission rule for a host that has a |
| +// replica: nil only when the <db>.seed marker beside dbPath names id, which |
| +// is this seed's own earlier placement (the marker is written before the |
| +// database is renamed into place, so before any upload). No marker, another |
| +// seed's, or one that cannot be read does not prove the replica is this |
| +// seed's: reported, FS-40, and nothing is restored. |
| +func fleetSeedReplicaRefusal(host, id, dbPath string) error { |
| + marker, err := ReadSeedMarker(dbPath) |
| + if err != nil { |
| + return seedCopyExists(host, fmt.Errorf("the seed marker beside %s cannot be read: %w", dbPath, err)) |
| + } |
| + if marker != id { |
| + return seedCopyExists(host, fmt.Errorf("the host has a replica, and the seed marker beside %s names %q", dbPath, marker)) |
| + } |
| + return nil |
| +} |
| + |
| +// reportSeedFailure tells the console of a failure no retry can fix, for a |
| +// fleet file seed: a snapshot that does not match its record, one that is |
| +// not a database, or a copy that already exists. Every other failure |
| +// carries no code and is reported to nobody: the wake fails and the next |
| +// one tries again. The report is best effort. A door that cannot be |
| +// reached leaves the seed ready, the wake still fails, and the next wake |
| +// finds the same failure and reports it again. |
| +func (b *ExecBackend) reportSeedFailure(ctx context.Context, rt registry.Route, src *seeds.RowSeed, err error) { |
| + var spe *SeedPlacementError |
| + if !b.fleetFileSeed(src) || !errors.As(err, &spe) || spe.code == "" { |
| + return |
| + } |
| + if b.OnSeedFailed == nil { |
| + log.Printf("activator: %s: seed %s failed for good (%s), and this box has no door to report it to", rt.Host, src.ID, spe.code) |
| + return |
| + } |
| + if rerr := b.OnSeedFailed(ctx, rt.Account, rt.App, rt.Host, src.ID, spe.code); rerr != nil { |
| + log.Printf("activator: %s: seed %s failed for good (%s); not reported yet: %v", rt.Host, src.ID, spe.code, rerr) |
| + } |
| +} |
diff --git a/internal/activator/seedfleet_linux_test.go b/internal/activator/seedfleet_linux_test.go| new file mode 100644 |
| index 000000000..ea86d1f6b |
| --- /dev/null |
| +++ b/internal/activator/seedfleet_linux_test.go |
| @@ -0,0 +1,677 @@ |
| +//go:build linux |
| + |
| +package activator |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +// listCountingMirror counts the listings of the fleet's bucket: admission |
| +// may list staging, and the retry restore must not. |
| +type listCountingMirror struct { |
| + *fakeMirrorStore |
| + lists []string |
| +} |
| + |
| +func (m *listCountingMirror) List(ctx context.Context, bucket, prefix string) (map[string]lease.MirrorObject, error) { |
| + m.lists = append(m.lists, prefix) |
| + return m.fakeMirrorStore.List(ctx, bucket, prefix) |
| +} |
| + |
| +// fleetSeedRig is a customer-fleet box and a file seed's row on it. |
| +type fleetSeedRig struct { |
| + b *ExecBackend |
| + rt registry.Route |
| + objs *fakeSeedObjects |
| + id string |
| + mirror *listCountingMirror |
| + failed []string // OnSeedFailed's codes |
| + placed []string // OnSeedPlaced's calls |
| + restored int // restoreReplica's calls |
| +} |
| + |
| +// fleetFileSeedRig builds the rig: flat (the customer-fleet layout) or |
| +// nested, a ready file seed whose snapshot is a small database, an empty |
| +// bucket, and no replica of the host's own unless a test says so. |
| +func fleetFileSeedRig(t *testing.T, flat bool) *fleetSeedRig { |
| + t.Helper() |
| + r := &fleetSeedRig{mirror: &listCountingMirror{fakeMirrorStore: newFakeMirrorStore()}} |
| + if flat { |
| + r.b = testExecBackend(t) |
| + host := "shop.example.com" |
| + r.rt = registry.Route{Host: host, Kind: "instance", Hibernate: true, |
| + DBPath: provision.DefaultDBPath(r.b.DataDir, host), Socket: provision.DefaultSocket(host)} |
| + } else { |
| + r.b, r.rt = nestedBackend(t, &fakeControl{}, &fakeUnit{}) |
| + } |
| + r.rt.Account, r.rt.App = "acct", "shop" |
| + r.rt, r.objs, r.id = seededRoute(t, r.b, r.rt, seeds.StateReady) |
| + src, _ := seeds.ParseRowSeed(r.rt.SeedSource) |
| + src.Kind = seeds.KindFile |
| + r.rt.SeedSource = src.Encode() |
| + r.b.CustomerFleet = true |
| + r.b.Mirror = r.mirror |
| + r.b.OnSeedFailed = func(_ context.Context, acct, app, host, id, code string) error { |
| + if acct != "acct" || app != "shop" || host != r.rt.Host || id != r.id { |
| + t.Errorf("OnSeedFailed(%s, %s, %s, %s): not this seed", acct, app, host, id) |
| + } |
| + r.failed = append(r.failed, code) |
| + return nil |
| + } |
| + r.b.OnSeedPlaced = func(_ context.Context, acct, app, host, id string) error { |
| + r.placed = append(r.placed, acct+"/"+app+"/"+host+"/"+id) |
| + return nil |
| + } |
| + setKnob(t, &hasOwnReplica, func(context.Context, string, string, string) (bool, error) { return false, nil }) |
| + setKnob(t, &restoreReplica, func(_ context.Context, dbPath, _, _, _ string) (bool, error) { |
| + r.restored++ |
| + return true, writeMinimalSQLite(dbPath) |
| + }) |
| + return r |
| +} |
| + |
| +func (r *fleetSeedRig) ownReplica(t *testing.T, has bool) *int { |
| + t.Helper() |
| + n := 0 |
| + setKnob(t, &hasOwnReplica, func(context.Context, string, string, string) (bool, error) { n++; return has, nil }) |
| + return &n |
| +} |
| + |
| +// writeMarker leaves this seed's marker beside the row's database, as the |
| +// placement that made the replica did. |
| +func (r *fleetSeedRig) writeMarker(t *testing.T, id string) { |
| + t.Helper() |
| + if err := os.MkdirAll(filepath.Dir(r.rt.DBPath), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(r.rt.DBPath+SeedMarkerSuffix, []byte(id+"\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (r *fleetSeedRig) keys(prefix string) []string { |
| + got, _ := r.mirror.fakeMirrorStore.List(context.Background(), r.b.Cfg.Bucket, prefix) |
| + var out []string |
| + for k := range got { |
| + out = append(out, k) |
| + } |
| + return out |
| +} |
| + |
| +const copyExistsSentence = "shop.example.com could not start from its seed: a copy of data already exists for this hostname." |
| + |
| +func requireRefusal(t *testing.T, fresh bool, err error, want string) { |
| + t.Helper() |
| + var spe *SeedPlacementError |
| + if fresh || !errors.As(err, &spe) || !strings.Contains(spe.Sentence, want) { |
| + t.Fatalf("Restore = fresh %v, %v; want a %q refusal that is never fresh", fresh, err, want) |
| + } |
| +} |
| + |
| +func TestFleetFileSeedPlacesThroughStoreDoorAndReportsPlaced(t *testing.T) { |
| + r := fleetFileSeedRig(t, true) |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + if err != nil || fresh { |
| + t.Fatalf("Restore = fresh %v, %v", fresh, err) |
| + } |
| + if want := []string{"acct/shop/" + r.rt.Host + "/" + r.id}; !reflect.DeepEqual(r.objs.opened, want) { |
| + t.Fatalf("snapshot opened as %q, want %q", r.objs.opened, want) |
| + } |
| + if got, _ := os.ReadFile(r.rt.DBPath); !bytes.Equal(got, r.objs.body[r.id]) { |
| + t.Fatal("the database at the row's path is not the snapshot") |
| + } |
| + if len(r.placed) != 0 { |
| + t.Fatalf("placed was reported before the first upload: %q", r.placed) |
| + } |
| + if err := r.b.SeedPlaced(context.Background(), r.rt, &syncRep{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := []string{"acct/shop/" + r.rt.Host + "/" + r.id}; !reflect.DeepEqual(r.placed, want) { |
| + t.Fatalf("placed = %q, want %q", r.placed, want) |
| + } |
| + if len(r.failed) != 0 { |
| + t.Fatalf("failed reported: %q", r.failed) |
| + } |
| +} |
| + |
| +func TestFleetFileSeedCheckFailureReportsFailed(t *testing.T) { |
| + r := fleetFileSeedRig(t, true) |
| + body := []byte("not sqlite at all, but the right length and hash") |
| + sum := sha256.Sum256(body) |
| + r.rt.SeedSource = seeds.RowSeed{ID: r.id, Kind: seeds.KindFile, SHA256: hex.EncodeToString(sum[:]), Bytes: int64(len(body)), State: seeds.StateReady}.Encode() |
| + r.objs.body[r.id] = body |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + requireRefusal(t, fresh, err, "integrity check") |
| + if !reflect.DeepEqual(r.failed, []string{provision.SeedCodeNotADatabase}) { |
| + t.Fatalf("failed = %q, want one not-a-database", r.failed) |
| + } |
| + if _, err := os.Lstat(r.rt.DBPath); !os.IsNotExist(err) { |
| + t.Fatalf("a refused snapshot left a database at the row's path: %v", err) |
| + } |
| +} |
| + |
| +func TestFleetFileSeedMismatchReportsFailed(t *testing.T) { |
| + r := fleetFileSeedRig(t, true) |
| + r.objs.body[r.id] = r.objs.body[r.id][:100] |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + requireRefusal(t, fresh, err, "length or sha256") |
| + if !reflect.DeepEqual(r.failed, []string{provision.SeedCodeMismatch}) { |
| + t.Fatalf("failed = %q, want one mismatch", r.failed) |
| + } |
| + if _, err := os.Lstat(r.rt.DBPath); !os.IsNotExist(err) { |
| + t.Fatalf("a refused snapshot left a database at the row's path: %v", err) |
| + } |
| + // A door that cannot be reached does not change the wake's answer. |
| + r.b.OnSeedFailed = func(context.Context, string, string, string, string, string) error { return errors.New("door down") } |
| + fresh, err = r.b.Restore(context.Background(), r.rt) |
| + requireRefusal(t, fresh, err, "length or sha256") |
| + r.b.OnSeedFailed = nil |
| + fresh, err = r.b.Restore(context.Background(), r.rt) |
| + requireRefusal(t, fresh, err, "length or sha256") |
| +} |
| + |
| +// A read that fails, a disk that fails: the wake fails, nothing is |
| +// reported, and the next wake places the seed. |
| +func TestFleetFileSeedUnreadReportsNothing(t *testing.T) { |
| + r := fleetFileSeedRig(t, true) |
| + r.objs.err = errors.New("store door down") |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + requireRefusal(t, fresh, err, "could not be read") |
| + r.objs.err, r.objs.midway = nil, errors.New("connection reset") |
| + fresh, err = r.b.Restore(context.Background(), r.rt) |
| + requireRefusal(t, fresh, err, "could not be read") |
| + if len(r.failed) != 0 { |
| + t.Fatalf("a retryable failure was reported as %q", r.failed) |
| + } |
| + r.objs.midway = nil |
| + if fresh, err := r.b.Restore(context.Background(), r.rt); err != nil || fresh { |
| + t.Fatalf("the retry = fresh %v, %v; want the seed placed", fresh, err) |
| + } |
| +} |
| + |
| +// R2-2: a replica under the host's prefix is this seed's only with the |
| +// marker to prove it. Without, nothing is restored. |
| +func TestFleetFileSeedReplicaWithoutMarkerReportsFailed(t *testing.T) { |
| + other, _ := seeds.NewID() |
| + for name, leave := range map[string]func(t *testing.T, r *fleetSeedRig){ |
| + "no marker": func(*testing.T, *fleetSeedRig) {}, |
| + "another seed's": func(t *testing.T, r *fleetSeedRig) { r.writeMarker(t, other) }, |
| + "an empty marker": func(t *testing.T, r *fleetSeedRig) { r.writeMarker(t, "") }, |
| + "a marker that is not a file": func(t *testing.T, r *fleetSeedRig) { |
| + if err := os.MkdirAll(r.rt.DBPath+SeedMarkerSuffix, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "a marker that is a link to this seed's id": func(t *testing.T, r *fleetSeedRig) { |
| + target := filepath.Join(t.TempDir(), "m") |
| + os.WriteFile(target, []byte(r.id+"\n"), 0o600) |
| + os.MkdirAll(filepath.Dir(r.rt.DBPath), 0o700) |
| + if err := os.Symlink(target, r.rt.DBPath+SeedMarkerSuffix); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + } { |
| + for _, flat := range []bool{true, false} { |
| + t.Run(fmt.Sprintf("%s, flat %v", name, flat), func(t *testing.T) { |
| + r := fleetFileSeedRig(t, flat) |
| + r.ownReplica(t, true) |
| + leave(t, r) |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + requireRefusal(t, fresh, err, "a copy of data already exists") |
| + if flat && err.Error() != copyExistsSentence { |
| + t.Fatalf("sentence = %q, want FS-40 %q", err.Error(), copyExistsSentence) |
| + } |
| + if !reflect.DeepEqual(r.failed, []string{provision.SeedCodeCopyExists}) { |
| + t.Fatalf("failed = %q, want one copy-exists", r.failed) |
| + } |
| + if r.restored != 0 || r.objs.opens != 0 || len(r.placed) != 0 { |
| + t.Fatalf("restored %d, fetched %d, placed %q; want nothing restored, fetched or recorded", r.restored, r.objs.opens, r.placed) |
| + } |
| + if _, err := os.Lstat(r.rt.DBPath); !os.IsNotExist(err) { |
| + t.Fatalf("a database is at the row's path: %v", err) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestFleetFileSeedReplicaWithMarkerRestoresAndReportsPlaced(t *testing.T) { |
| + r := fleetFileSeedRig(t, true) |
| + r.ownReplica(t, true) |
| + r.writeMarker(t, r.id) |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + if err != nil || fresh { |
| + t.Fatalf("Restore = fresh %v, %v", fresh, err) |
| + } |
| + if r.restored != 1 || r.objs.opens != 0 { |
| + t.Fatalf("restored %d, fetched %d; want its own replica restored and no fetch", r.restored, r.objs.opens) |
| + } |
| + if want := []string{"acct/shop/" + r.rt.Host + "/" + r.id}; !reflect.DeepEqual(r.placed, want) { |
| + t.Fatalf("placed = %q, want %q", r.placed, want) |
| + } |
| + if len(r.failed) != 0 { |
| + t.Fatalf("failed reported: %q", r.failed) |
| + } |
| +} |
| + |
| +// R3-2: a matching marker does not bound what a restore would read while |
| +// anything is staged, so a retry with staged objects is refused before the |
| +// replica question is even asked. Nothing is promoted, nothing restored. |
| +func TestFleetFileSeedRetryRefusesStaging(t *testing.T) { |
| + for _, flat := range []bool{true, false} { |
| + r := fleetFileSeedRig(t, flat) |
| + asked := r.ownReplica(t, true) |
| + r.writeMarker(t, r.id) |
| + staged := MovesPrefix(r.rt.Host) + "generations/a/snapshot" |
| + r.mirror.put(r.b.Cfg.Bucket, staged, "e1") |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + requireRefusal(t, fresh, err, "a copy of data already exists") |
| + if !reflect.DeepEqual(r.failed, []string{provision.SeedCodeCopyExists}) { |
| + t.Fatalf("failed = %q, want one copy-exists", r.failed) |
| + } |
| + if r.restored != 0 || r.objs.opens != 0 || *asked != 0 { |
| + t.Fatalf("restored %d, fetched %d, replica asked %d; want none", r.restored, r.objs.opens, *asked) |
| + } |
| + if got := r.keys(""); !reflect.DeepEqual(got, []string{staged}) { |
| + t.Fatalf("the bucket now holds %q; the staged object was promoted or dropped", got) |
| + } |
| + // With no replica either, the fresh fetch is refused the same way: |
| + // once placed, an ordinary wake would promote the staged copy over it. |
| + r2 := fleetFileSeedRig(t, flat) |
| + r2.mirror.put(r2.b.Cfg.Bucket, staged, "e1") |
| + fresh, err = r2.b.Restore(context.Background(), r2.rt) |
| + requireRefusal(t, fresh, err, "a copy of data already exists") |
| + if r2.objs.opens != 0 || !reflect.DeepEqual(r2.failed, []string{provision.SeedCodeCopyExists}) { |
| + t.Fatalf("fresh placement over staging: fetched %d, failed %q", r2.objs.opens, r2.failed) |
| + } |
| + } |
| +} |
| + |
| +// R3-2, the other half: staging is empty at admission and an object lands |
| +// there before the restore. The retry restore runs with promotion off, so |
| +// the bucket is listed once, by admission, and the staged object is neither |
| +// promoted nor dropped. |
| +func TestFleetFileSeedRestoreOwnNeverPromotesStaging(t *testing.T) { |
| + r := fleetFileSeedRig(t, true) |
| + r.writeMarker(t, r.id) |
| + staged := MovesPrefix(r.rt.Host) + "generations/a/snapshot" |
| + setKnob(t, &hasOwnReplica, func(context.Context, string, string, string) (bool, error) { |
| + r.mirror.put(r.b.Cfg.Bucket, staged, "e1") // after admission's listing |
| + return true, nil |
| + }) |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + if err != nil || fresh || r.restored != 1 { |
| + t.Fatalf("Restore = fresh %v, %v, restored %d; want its own replica restored", fresh, err, r.restored) |
| + } |
| + if want := []string{MovesPrefix(r.rt.Host)}; !reflect.DeepEqual(r.mirror.lists, want) { |
| + t.Fatalf("bucket listings = %q, want only admission's %q", r.mirror.lists, want) |
| + } |
| + if got := r.keys(""); !reflect.DeepEqual(got, []string{staged}) { |
| + t.Fatalf("the bucket now holds %q; the staged object was promoted or dropped", got) |
| + } |
| + if len(r.failed) != 0 { |
| + t.Fatalf("failed reported: %q", r.failed) |
| + } |
| +} |
| + |
| +// Decision D7: a staging listing that fails is not an answer. The wake |
| +// fails, nothing is reported, and nothing is read. |
| +func TestFleetFileSeedStagingListErrorReportsNothing(t *testing.T) { |
| + for name, breakIt := range map[string]func(r *fleetSeedRig){ |
| + "the listing fails": func(r *fleetSeedRig) { r.mirror.failList = true }, |
| + "no bucket reader on the box": func(r *fleetSeedRig) { r.b.Mirror = nil }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + r := fleetFileSeedRig(t, true) |
| + asked := r.ownReplica(t, true) |
| + r.writeMarker(t, r.id) |
| + breakIt(r) |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + if err == nil || fresh { |
| + t.Fatalf("Restore = fresh %v, %v; want a failed wake", fresh, err) |
| + } |
| + if len(r.failed) != 0 || r.restored != 0 || r.objs.opens != 0 || *asked != 0 { |
| + t.Fatalf("failed %q, restored %d, fetched %d, replica asked %d; want nothing", r.failed, r.restored, r.objs.opens, *asked) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Design §3.6's last sentence: once placed, a fleet file seed's wakes are |
| +// ordinary restores and staging behaves as it does today. |
| +func TestFleetFileSeedOncePlacedPromotesStagingAsToday(t *testing.T) { |
| + r := fleetFileSeedRig(t, true) |
| + r.rt = withSeedState(t, r.rt, seeds.StatePlaced) |
| + r.mirror.put(r.b.Cfg.Bucket, MovesPrefix(r.rt.Host)+"generations/a/snapshot", "e1") |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + if err != nil || fresh || r.restored != 1 || len(r.failed) != 0 { |
| + t.Fatalf("Restore = fresh %v, %v, restored %d, failed %q", fresh, err, r.restored, r.failed) |
| + } |
| + if got := r.keys(r.b.Cfg.hibernatePrefix(r.rt.Host) + "/"); len(got) != 1 { |
| + t.Fatalf("own prefix = %q; want the staged replica promoted", got) |
| + } |
| +} |
| + |
| +func TestFlatFleetBoxAdmitsFileSeed(t *testing.T) { |
| + r := fleetFileSeedRig(t, true) |
| + if l, _ := r.b.Layout(r.rt); l != LayoutFlat { |
| + t.Fatalf("the rig's row classifies as %v, want flat", l) |
| + } |
| + if fresh, err := r.b.Restore(context.Background(), r.rt); err != nil || fresh { |
| + t.Fatalf("Restore = fresh %v, %v; want the seed placed flat", fresh, err) |
| + } |
| + if m, _ := os.ReadFile(r.rt.DBPath + SeedMarkerSuffix); strings.TrimSpace(string(m)) != r.id { |
| + t.Fatalf("marker = %q, want %s", m, r.id) |
| + } |
| + // Claim control refuses on a fleet as anywhere. |
| + c := fleetFileSeedRig(t, true) |
| + c.b.ClaimArmed = true |
| + fresh, err := c.b.Restore(context.Background(), c.rt) |
| + requireRefusal(t, fresh, err, "claim control") |
| + // So does a row that is neither flat nor nested. |
| + f := fleetFileSeedRig(t, true) |
| + f.rt.Socket = filepath.Join(t.TempDir(), "x.sock") |
| + fresh, err = f.b.Restore(context.Background(), f.rt) |
| + requireRefusal(t, fresh, err, "nested") |
| + // And a --from seed keeps today's flat refusal on a fleet box. |
| + p := fleetFileSeedRig(t, true) |
| + src, _ := seeds.ParseRowSeed(p.rt.SeedSource) |
| + src.Kind = seeds.KindReplica |
| + p.rt.SeedSource = src.Encode() |
| + fresh, err = p.b.Restore(context.Background(), p.rt) |
| + requireRefusal(t, fresh, err, "nested") |
| + for _, x := range []*fleetSeedRig{c, f, p} { |
| + if x.objs.opens != 0 || len(x.failed) != 0 { |
| + t.Fatalf("a refused wake fetched %d and reported %q", x.objs.opens, x.failed) |
| + } |
| + } |
| +} |
| + |
| +func TestFlatNonFleetBoxStillRefuses(t *testing.T) { |
| + r := fleetFileSeedRig(t, true) |
| + r.b.CustomerFleet = false |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + requireRefusal(t, fresh, err, "nested") |
| + if r.objs.opens != 0 || len(r.failed) != 0 || len(r.mirror.lists) != 0 { |
| + t.Fatalf("fetched %d, reported %q, listed %q; want none", r.objs.opens, r.failed, r.mirror.lists) |
| + } |
| +} |
| + |
| +// Off a fleet a file seed is a --from seed to the box, exactly as before |
| +// this change: no staging listing, no marker rule, no report, and a |
| +// mismatch is a failed wake that is retried. |
| +func TestRegionFileSeedPlacementUnchanged(t *testing.T) { |
| + r := fleetFileSeedRig(t, false) |
| + r.b.CustomerFleet = false |
| + r.ownReplica(t, true) // a replica with no marker restores, as today |
| + r.mirror.put(r.b.Cfg.Bucket, MovesPrefix(r.rt.Host)+"generations/a/snapshot", "e1") |
| + os.MkdirAll(filepath.Dir(r.rt.DBPath), 0o700) |
| + fresh, err := r.b.Restore(context.Background(), r.rt) |
| + if err != nil || fresh || r.restored != 1 || len(r.failed) != 0 { |
| + t.Fatalf("Restore = fresh %v, %v, restored %d, failed %q", fresh, err, r.restored, r.failed) |
| + } |
| + m := fleetFileSeedRig(t, false) |
| + m.b.CustomerFleet = false |
| + m.objs.body[m.id] = m.objs.body[m.id][:100] |
| + fresh, err = m.b.Restore(context.Background(), m.rt) |
| + requireRefusal(t, fresh, err, "length or sha256") |
| + if len(m.failed) != 0 || len(m.mirror.lists) != 0 { |
| + t.Fatalf("a region box reported %q and listed %q", m.failed, m.mirror.lists) |
| + } |
| +} |
| + |
| +// snapshotWith is a small valid database holding one table named table, so |
| +// two seeds' snapshots differ. |
| +func snapshotWith(t *testing.T, table string) (body []byte, sha string) { |
| + t.Helper() |
| + p := filepath.Join(t.TempDir(), "snap.db") |
| + db, err := sql.Open("sqlite", p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := db.Exec("create table " + table + "(x)"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := db.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + body, err = os.ReadFile(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sum := sha256.Sum256(body) |
| + return body, hex.EncodeToString(sum[:]) |
| +} |
| + |
| +// Review focus 1 (R2-2), deterministic, over the real placement, the real |
| +// purge and the real rollback. The replica uploads, the placed report |
| +// fails, and the member deletes. The row goes; the next pass purges the |
| +// box, finds the replica and holds the hostname; with the prefix emptied |
| +// the pass after it reports rolledback. A second seed at the hostname then |
| +// places its own snapshot, not the first seed's data. |
| +func TestFleetFileSeedInterruptedPlacementHoldsHostname(t *testing.T) { |
| + ctx := context.Background() |
| + const host = "shop.example.com" |
| + store := release.NewDirStore(t.TempDir()) |
| + acct := domains.Sqid(2) |
| + manifest, _ := json.Marshal(map[string]any{"id": 2, "sqid": acct, "name": "Shop", "created_at": "2026-08-02T09:00:00Z"}) |
| + if _, err := store.Put(ctx, domains.AccountManifestKey(acct), manifest, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + |
| + b := testExecBackend(t) |
| + b.CustomerFleet = true |
| + b.Cfg.Prefix = "instances" |
| + bucket := newFakeMirrorStore() // the fleet's own bucket: replica and staging |
| + b.Mirror = bucket |
| + objs := &fakeSeedObjects{body: map[string][]byte{}} |
| + b.Seeds = objs |
| + replicaPrefix := provision.FleetSeedReplicaPrefix(b.Cfg.Prefix, host) |
| + setKnob(t, &hasOwnReplica, func(ctx context.Context, bkt, prefix, _ string) (bool, error) { |
| + got, err := bucket.List(ctx, bkt, prefix+"/") |
| + return len(got) != 0, err |
| + }) |
| + setKnob(t, &restoreReplica, func(context.Context, string, string, string, string) (bool, error) { |
| + t.Error("a replica was restored: the first seed's data came back") |
| + return false, errors.New("no restore in this test") |
| + }) |
| + |
| + // The console's door, as slice 3 builds it: failed records the reason, |
| + // placed is unreachable, and rolledback is only noted here (the test |
| + // plays the console's finish itself). |
| + var reports []string |
| + placedErr := errors.New("door unreachable") |
| + report := func(ctx context.Context, a, app, h, id, op, code, held string) error { |
| + reports = append(reports, strings.TrimSpace(op+" "+code+" "+held)) |
| + switch op { |
| + case provision.FleetSeedPlaced: |
| + return placedErr |
| + case provision.FleetSeedFailed: |
| + _, err := provision.SetRecordSeed(ctx, store, a, app, h, provision.SeedFail(id, code)) |
| + return err |
| + } |
| + return nil |
| + } |
| + b.OnSeedPlaced = func(ctx context.Context, a, app, h, id string) error { |
| + return report(ctx, a, app, h, id, provision.FleetSeedPlaced, "", "") |
| + } |
| + b.OnSeedFailed = func(ctx context.Context, a, app, h, id, code string) error { |
| + return report(ctx, a, app, h, id, provision.FleetSeedFailed, code, "") |
| + } |
| + fenced, gen := false, uint64(0) |
| + hooks := &provision.SeedHooks{ |
| + Data: release.NewDirStore(t.TempDir()), |
| + NextFenceGen: func() (uint64, error) { gen++; return gen, nil }, |
| + FenceForRollback: func(context.Context, string, uint64) (bool, error) { |
| + fenced = true |
| + return true, nil |
| + }, |
| + LiftFence: func(string, uint64) { fenced = false }, |
| + RemoveLocal: func(rt registry.Route) error { |
| + if !fenced { |
| + t.Error("purged while the host was not fenced") |
| + } |
| + return b.PurgeSeedLocalFor(rt) |
| + }, |
| + LocalSeedID: ReadSeedMarker, |
| + RetireKey: RetireSeedKey, |
| + DeleteReplica: func(context.Context, string) error { return errors.New("a fleet box deletes no replica") }, |
| + Fleet: &provision.FleetSeedHooks{ |
| + Report: report, |
| + ReplicaPrefix: b.Cfg.Prefix, |
| + ListPrefix: func(ctx context.Context, prefix string) ([]string, error) { |
| + got, err := bucket.List(ctx, b.Cfg.Bucket, prefix) |
| + var keys []string |
| + for k := range got { |
| + keys = append(keys, k) |
| + } |
| + return keys, err |
| + }, |
| + }, |
| + } |
| + cfg := provision.ReconcileConfig{Region: "fleet/pi", FleetBox: "pi-1", DataDir: b.DataDir, Seeds: hooks} |
| + pass := func() { |
| + t.Helper() |
| + if err := provision.Reconcile(ctx, store, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + seedRecord := func(table string, at time.Time) (provision.Record, []byte) { |
| + t.Helper() |
| + body, sha := snapshotWith(t, table) |
| + id, _ := seeds.NewID() |
| + objs.body[id] = body |
| + rec := provision.Record{Schema: 1, Account: acct, App: "shop", Host: host, Slug: "shop", Channel: "stable", Region: "fleet/pi", CreatedAt: at, |
| + Seed: &provision.SeedSource{ID: id, Kind: seeds.KindFile, State: seeds.StateReady, SHA256: sha, Bytes: int64(len(body)), By: "t", At: at}} |
| + if err := provision.CreateRecord(ctx, store, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + return rec, body |
| + } |
| + row := func() registry.Route { |
| + t.Helper() |
| + rt, err := reg.Get(host) |
| + if err != nil || rt == nil { |
| + t.Fatalf("no row for %s: %v", host, err) |
| + } |
| + return *rt |
| + } |
| + flat := provision.DefaultDBPath(b.DataDir, host) |
| + |
| + // The first seed is minted flat, placed, and its replica uploads. |
| + first, firstBody := seedRecord("first", time.Now().UTC().Add(-time.Hour)) |
| + pass() |
| + rt := row() |
| + if rt.DBPath != flat { |
| + t.Fatalf("minted at %s, want the flat path %s", rt.DBPath, flat) |
| + } |
| + if fresh, err := b.Restore(ctx, rt); err != nil || fresh { |
| + t.Fatalf("placing the first seed: fresh %v, %v", fresh, err) |
| + } |
| + if got, _ := os.ReadFile(flat); !bytes.Equal(got, firstBody) { |
| + t.Fatal("the first seed's snapshot is not at the row's path") |
| + } |
| + bucket.put(b.Cfg.Bucket, replicaPrefix+"generations/g1/0000000000000001.ltx", "e1") |
| + // The placed report is lost. |
| + if err := b.SeedPlaced(ctx, rt, &syncRep{}); !errors.Is(err, placedErr) { |
| + t.Fatalf("SeedPlaced = %v, want the door's failure", err) |
| + } |
| + // The member deletes: the console aborts the seed. |
| + if _, err := provision.SetRecordSeed(ctx, store, acct, "shop", host, provision.SeedAbort(first.Seed.ID)); err != nil { |
| + t.Fatal(err) |
| + } |
| + reports = nil |
| + |
| + pass() // the row goes first |
| + if got, _ := reg.Get(host); got != nil { |
| + t.Fatalf("the aborted seed's row is still up: %+v", got) |
| + } |
| + if _, err := os.Lstat(flat); err != nil { |
| + t.Fatalf("the database went with the row: %v", err) |
| + } |
| + if len(reports) != 0 { |
| + t.Fatalf("the row's pass reported %q", reports) |
| + } |
| + |
| + pass() // purge, find the replica, hold |
| + for _, p := range []string{flat, flat + SeedMarkerSuffix} { |
| + if _, err := os.Lstat(p); !os.IsNotExist(err) { |
| + t.Fatalf("%s survived the purge: %v", p, err) |
| + } |
| + } |
| + if want := []string{"failed copy-in-storage replica"}; !reflect.DeepEqual(reports, want) { |
| + t.Fatalf("reports = %q, want %q", reports, want) |
| + } |
| + held, err := provision.GetRecord(ctx, store, acct, "shop", host) |
| + if err != nil || held.Seed.State != seeds.StateAborted || held.Seed.Reason != provision.SeedCodeCopyInStorage { |
| + t.Fatalf("record = %+v, %v; want aborted, holding the hostname, with the reason", held.Seed, err) |
| + } |
| + pass() // and again: still held |
| + if len(reports) != 2 || reports[1] != "failed copy-in-storage replica" { |
| + t.Fatalf("reports = %q; want the hostname still held", reports) |
| + } |
| + |
| + // The fleet owner empties the host's replica prefix. |
| + for k := range bucket.buckets[b.Cfg.Bucket] { |
| + if strings.HasPrefix(k, replicaPrefix) { |
| + bucket.Delete(ctx, b.Cfg.Bucket, k) |
| + } |
| + } |
| + reports = nil |
| + pass() |
| + if want := []string{"rolledback"}; !reflect.DeepEqual(reports, want) { |
| + t.Fatalf("reports = %q, want %q", reports, want) |
| + } |
| + if fenced { |
| + t.Fatal("the rollback left its fence") |
| + } |
| + |
| + // The console finishes the record, and a second seed takes the hostname. |
| + if err := provision.DeleteRecord(ctx, store, acct, "shop", host); err != nil { |
| + t.Fatal(err) |
| + } |
| + second, secondBody := seedRecord("second", time.Now().UTC()) |
| + if bytes.Equal(firstBody, secondBody) { |
| + t.Fatal("the two snapshots are the same bytes; the test proves nothing") |
| + } |
| + pass() |
| + rt = row() |
| + opens := objs.opens |
| + if fresh, err := b.Restore(ctx, rt); err != nil || fresh { |
| + t.Fatalf("placing the second seed: fresh %v, %v", fresh, err) |
| + } |
| + if got, _ := os.ReadFile(rt.DBPath); !bytes.Equal(got, secondBody) { |
| + t.Fatal("the second seed's database is not its own snapshot") |
| + } |
| + if m, _ := os.ReadFile(rt.DBPath + SeedMarkerSuffix); strings.TrimSpace(string(m)) != second.Seed.ID { |
| + t.Fatalf("marker = %q, want the second seed %s", m, second.Seed.ID) |
| + } |
| + if objs.opens != opens+1 || objs.opened[len(objs.opened)-1] != acct+"/shop/"+host+"/"+second.Seed.ID { |
| + t.Fatalf("the second placement opened %q", objs.opened) |
| + } |
| +} |
diff --git a/internal/activator/seedfleet_test.go b/internal/activator/seedfleet_test.go| new file mode 100644 |
| index 000000000..2c72583b4 |
| --- /dev/null |
| +++ b/internal/activator/seedfleet_test.go |
| @@ -0,0 +1,24 @@ |
| +package activator |
| + |
| +import ( |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +// The fleet rollback (provision.rollbackFleetFileSeed) lists the two |
| +// prefixes a host can be restored from. provision cannot import this |
| +// package, so it spells them itself; this pins its spelling to the one the |
| +// restore and the staging promotion use, for an empty and a set box prefix. |
| +func TestFleetRollbackPrefixesAreTheActivators(t *testing.T) { |
| + for _, prefix := range []string{"", "instances", "a/b", "a/b/"} { |
| + for _, host := range []string{"shop.example.com", "a.b.example.co"} { |
| + if got, want := provision.FleetSeedReplicaPrefix(prefix, host), HibernatePrefix(prefix, host)+"/"; got != want { |
| + t.Errorf("replica prefix (%q, %q) = %q, the activator restores from %q", prefix, host, got, want) |
| + } |
| + if got, want := provision.FleetSeedStagingPrefix(host), MovesPrefix(host); got != want { |
| + t.Errorf("staging prefix (%q) = %q, the activator promotes from %q", host, got, want) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/activator/seedplace.go b/internal/activator/seedplace.go| index 71ee80a42..4a58c335a 100644 |
| --- a/internal/activator/seedplace.go |
| +++ b/internal/activator/seedplace.go |
| @@ -16,14 +16,18 @@ import ( |
| "github.com/carlosframework/platform/internal/instancefs" |
| "github.com/carlosframework/platform/internal/layout/pubclass" |
| "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/seeds" |
| ) |
| -// SeedObjects reads a seed's snapshot, seeds/<host>/<id>/snapshot.db, from |
| -// this box's own region data bucket. |
| +// SeedObjects reads a seed's snapshot. A region box reads |
| +// seeds/<host>/<id>/snapshot.db from its own region data bucket and ignores |
| +// the account and app. A customer-fleet box reads the seed file's key under |
| +// apps/<account>/<app>/ through the store door (fleet seeded create design |
| +// §3.3, §3.5). |
| type SeedObjects interface { |
| - Open(ctx context.Context, host, id string) (io.ReadCloser, error) |
| + Open(ctx context.Context, acct, app, host, id string) (io.ReadCloser, error) |
| } |
| // SeedMarkerSuffix names the installation evidence beside a placed |
| @@ -47,17 +51,22 @@ var ( |
| type SeedPlacementError struct { |
| Sentence string |
| Err error |
| + // code is set on a failure no retry can fix: the reason a fleet box |
| + // reports for a seed file (reportSeedFailure). "" is retried. |
| + code string |
| } |
| func (e *SeedPlacementError) Error() string { return e.Sentence } |
| func (e *SeedPlacementError) Unwrap() error { return e.Err } |
| func seedMismatch(host string) error { |
| - return &SeedPlacementError{Sentence: fmt.Sprintf("%s could not start from its seed: the snapshot's length or sha256 does not match its record.", host)} |
| + return &SeedPlacementError{Sentence: fmt.Sprintf("%s could not start from its seed: the snapshot's length or sha256 does not match its record.", host), |
| + code: provision.SeedCodeMismatch} |
| } |
| func seedNotDB(host string, err error) error { |
| - return &SeedPlacementError{Sentence: fmt.Sprintf("%s could not start from its seed: the snapshot is not a database that passes an integrity check.", host), Err: err} |
| + return &SeedPlacementError{Sentence: fmt.Sprintf("%s could not start from its seed: the snapshot is not a database that passes an integrity check.", host), Err: err, |
| + code: provision.SeedCodeNotADatabase} |
| } |
| func seedUnread(host string, err error) error { |
| @@ -98,7 +107,11 @@ func seedRestores(src *seeds.RowSeed) bool { |
| // instancefs, so no symlink there is followed. |
| func (b *ExecBackend) seededRestore(ctx context.Context, rt registry.Route, src *seeds.RowSeed) (bool, error) { |
| host := rt.Host |
| + // fleet: a file seed this customer-fleet box has still to place, which |
| + // has rules of its own (seedfleet.go). |
| + fleet := b.fleetFileSeed(src) |
| fail := func(err error) (bool, error) { |
| + b.reportSeedFailure(ctx, rt, src, err) |
| var spe *SeedPlacementError |
| if errors.As(err, &spe) && spe.Err != nil { |
| log.Printf("activator: %s: seed %s: %v: %v", host, src.ID, err, spe.Err) |
| @@ -130,8 +143,11 @@ func (b *ExecBackend) seededRestore(ctx context.Context, rt registry.Route, src |
| // marker is written to name the seed (final review carry item): the |
| // rollback's missing-row purge and an aborted seed's local purge decide |
| // by the marker, and a database with none is left in place. |
| + // |
| + // An unplaced fleet file seed never reads staging (R3-2): its restore |
| + // runs with staging promotion off. |
| restoreOwn := func() (bool, error) { |
| - fresh, err := b.restorePlain(ctx, rt) |
| + fresh, err := b.restorePlainStaging(ctx, rt, !fleet) |
| if err != nil { |
| return false, err |
| } |
| @@ -157,7 +173,9 @@ func (b *ExecBackend) seededRestore(ctx context.Context, rt registry.Route, src |
| return fail(seedRefusedClaim(host)) |
| } |
| paths := b.pathsFor(rt) |
| - if paths.layout != LayoutNested { |
| + // A customer-fleet box runs flat, and takes a file seed flat (design |
| + // §3.5 item 0). Every other seed, and every other box, is nested only. |
| + if paths.layout != LayoutNested && !(fleet && paths.layout == LayoutFlat) { |
| return fail(seedRefusedFlat(host)) |
| } |
| dir, base := filepath.Dir(paths.dbPath), filepath.Base(paths.dbPath) |
| @@ -167,6 +185,14 @@ func (b *ExecBackend) seededRestore(ctx context.Context, rt registry.Route, src |
| return fail(seedPlaceFailed(host, err)) |
| } |
| + // A fleet file seed is refused while anything is staged for its host, |
| + // before the replica question (R3-2). |
| + if fleet { |
| + if err := b.fleetSeedStagingRefusal(ctx, host); err != nil { |
| + return fail(err) |
| + } |
| + } |
| + |
| // Step 1: a replica of its own means this host was placed already. A |
| // listing that cannot tell fails the wake: read as "no replica", it |
| // would place the snapshot over a lineage that exists. |
| @@ -175,6 +201,13 @@ func (b *ExecBackend) seededRestore(ctx context.Context, rt registry.Route, src |
| return fail(fmt.Errorf("seed fallback for %s: cannot tell whether it has a replica of its own: %w", host, err)) |
| } |
| if has { |
| + // On a fleet the replica is this seed's only with its marker to |
| + // prove it (R2-2). Without, nothing is restored. |
| + if fleet { |
| + if err := fleetSeedReplicaRefusal(host, src.ID, paths.dbPath); err != nil { |
| + return fail(err) |
| + } |
| + } |
| if _, err := restoreOwn(); err != nil { |
| return false, err |
| } |
| @@ -243,7 +276,7 @@ func (b *ExecBackend) seededRestore(ctx context.Context, rt registry.Route, src |
| if err := purgeSeedTarget(dir, base, paths.layout == LayoutNested); err != nil { |
| return fail(seedPlaceFailed(host, err)) |
| } |
| - if err := b.placeSeed(ctx, host, src, dir, base); err != nil { |
| + if err := b.placeSeed(ctx, rt, src, dir, base); err != nil { |
| return fail(err) |
| } |
| // The placed snapshot is this assignment's copy now (startrule.go). |
| @@ -435,14 +468,15 @@ func purgeSeedTarget(dir, base string, legacyTemps bool) error { |
| // entry renamed onto dir/base must still be it. Anything else is refused, |
| // and a refusal after the rename removes the marker and the database, so no |
| // unchecked file is ever kept as this seed. |
| -func (b *ExecBackend) placeSeed(ctx context.Context, host string, src *seeds.RowSeed, dir, base string) error { |
| +func (b *ExecBackend) placeSeed(ctx context.Context, rt registry.Route, src *seeds.RowSeed, dir, base string) error { |
| + host := rt.Host |
| tmp := seedTempName(base, src.ID) |
| defer func() { |
| for _, n := range []string{tmp, tmp + "-wal", tmp + "-shm"} { |
| _ = instancefs.RemoveAllBeneath(dir, n) |
| } |
| }() |
| - wrote, err := b.fetchSeed(ctx, host, src, dir, tmp) |
| + wrote, err := b.fetchSeed(ctx, rt, src, dir, tmp) |
| if err != nil { |
| return err |
| } |
| @@ -507,8 +541,9 @@ func sameFileAt(dir, name string, want os.FileInfo) error { |
| // sha256 against the row as it writes, and returns the identity of the file |
| // it wrote. It reads at most one byte more than the row records, so an |
| // oversized object is refused without being read. |
| -func (b *ExecBackend) fetchSeed(ctx context.Context, host string, src *seeds.RowSeed, dir, tmp string) (os.FileInfo, error) { |
| - rc, err := b.Seeds.Open(ctx, host, src.ID) |
| +func (b *ExecBackend) fetchSeed(ctx context.Context, rt registry.Route, src *seeds.RowSeed, dir, tmp string) (os.FileInfo, error) { |
| + host := rt.Host |
| + rc, err := b.Seeds.Open(ctx, rt.Account, rt.App, host, src.ID) |
| if err != nil { |
| return nil, seedUnread(host, err) |
| } |
diff --git a/internal/activator/seedplace_linux_test.go b/internal/activator/seedplace_linux_test.go| index f08ac8886..abf0ee9e0 100644 |
| --- a/internal/activator/seedplace_linux_test.go |
| +++ b/internal/activator/seedplace_linux_test.go |
| @@ -25,13 +25,16 @@ type fakeSeedObjects struct { |
| body map[string][]byte // id -> snapshot |
| err error |
| opens int |
| - read int64 // bytes the fallback pulled from the object |
| + // opened is every Open, as account/app/host/id. |
| + opened []string |
| + read int64 // bytes the fallback pulled from the object |
| // midway, when set, fails the read after the first 100 bytes. |
| midway error |
| } |
| -func (f *fakeSeedObjects) Open(_ context.Context, host, id string) (io.ReadCloser, error) { |
| +func (f *fakeSeedObjects) Open(_ context.Context, acct, app, host, id string) (io.ReadCloser, error) { |
| f.opens++ |
| + f.opened = append(f.opened, acct+"/"+app+"/"+host+"/"+id) |
| if f.err != nil { |
| return nil, f.err |
| } |
| @@ -1091,7 +1094,7 @@ type holdingSeedObjects struct { |
| release chan struct{} |
| } |
| -func (h *holdingSeedObjects) Open(_ context.Context, _, id string) (io.ReadCloser, error) { |
| +func (h *holdingSeedObjects) Open(_ context.Context, _, _, _, id string) (io.ReadCloser, error) { |
| b := h.body[id] |
| return io.NopCloser(io.MultiReader(bytes.NewReader(b[:1]), |
| readerFunc(func() { h.started <- struct{}{}; <-h.release }), bytes.NewReader(b[1:]))), nil |
| @@ -1122,7 +1125,7 @@ func TestFlatFleetTwoSeedsPlaceConcurrently(t *testing.T) { |
| } |
| errs := make(chan error, 2) |
| for _, h := range hosts { |
| - go func() { errs <- b.placeSeed(context.Background(), h, srcs[h], dir, h+".db") }() |
| + go func() { errs <- b.placeSeed(context.Background(), registry.Route{Host: h}, srcs[h], dir, h+".db") }() |
| } |
| <-objs.started |
| <-objs.started |
diff --git a/internal/host/seedwiring.go b/internal/host/seedwiring.go| index 00ef379f2..98450ab79 100644 |
| --- a/internal/host/seedwiring.go |
| +++ b/internal/host/seedwiring.go |
| @@ -23,8 +23,10 @@ import ( |
| type storeSeedObjects struct{ s release.Store } |
| // Open streams seeds/<host>/<id>/snapshot.db. A store that cannot stream is |
| -// refused rather than read whole: a seed can be gigabytes. |
| -func (o storeSeedObjects) Open(ctx context.Context, host, id string) (io.ReadCloser, error) { |
| +// refused rather than read whole: a seed can be gigabytes. The account and |
| +// app are a fleet reader's (activator.SeedObjects): a region snapshot's key |
| +// has neither. |
| +func (o storeSeedObjects) Open(ctx context.Context, _, _, host, id string) (io.ReadCloser, error) { |
| if err := seeds.Check(host, id); err != nil { |
| return nil, fmt.Errorf("seed %q of %s: %w", id, host, err) |
| } |
diff --git a/internal/host/seedwiring_test.go b/internal/host/seedwiring_test.go| index 3540a44a9..96088c872 100644 |
| --- a/internal/host/seedwiring_test.go |
| +++ b/internal/host/seedwiring_test.go |
| @@ -219,7 +219,7 @@ func TestStoreSeedObjectsOpensTheSnapshotKey(t *testing.T) { |
| if _, err := data.Put(ctx, seeds.SnapshotKey("shop-1.example.com", id), []byte("db-bytes"), ""); err != nil { |
| t.Fatal(err) |
| } |
| - rc, err := storeSeedObjects{data}.Open(ctx, "shop-1.example.com", id) |
| + rc, err := storeSeedObjects{data}.Open(ctx, "", "", "shop-1.example.com", id) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -228,7 +228,7 @@ func TestStoreSeedObjectsOpensTheSnapshotKey(t *testing.T) { |
| if string(b) != "db-bytes" { |
| t.Fatalf("read %q", b) |
| } |
| - if _, err := (storeSeedObjects{data}).Open(ctx, "shop-1.example.com", "../x"); err == nil { |
| + if _, err := (storeSeedObjects{data}).Open(ctx, "", "", "shop-1.example.com", "../x"); err == nil { |
| t.Fatal("a malformed id opened something") |
| } |
| } |
diff --git a/internal/provision/seedfleet.go b/internal/provision/seedfleet.go| new file mode 100644 |
| index 000000000..a9590f4e9 |
| --- /dev/null |
| +++ b/internal/provision/seedfleet.go |
| @@ -0,0 +1,260 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "os" |
| + "path" |
| + "path/filepath" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +// The fleet seeds door's vocabulary (fleet seeded create design §3.5, |
| +// §3.6): the three operations a fleet box reports, the reason codes it |
| +// sends with failed, and where a held copy is. A box sends codes, never |
| +// text a member reads (plan decisions D4, D12). |
| +const ( |
| + FleetSeedPlaced = "placed" |
| + FleetSeedFailed = "failed" |
| + FleetSeedRolledBack = "rolledback" |
| + |
| + SeedCodeMismatch = "mismatch" |
| + SeedCodeNotADatabase = "not-a-database" |
| + SeedCodeCopyExists = "copy-exists" |
| + SeedCodeCopyInStorage = "copy-in-storage" |
| + |
| + SeedHeldReplica = "replica" |
| + SeedHeldStaging = "staging" |
| + SeedHeldBoth = "both" |
| +) |
| + |
| +// FleetSeedHooks is what a customer-fleet box needs to finish a file seed |
| +// (design §3.6). A fleet box cannot write records, so every transition it |
| +// makes is reported to the console's door. |
| +type FleetSeedHooks struct { |
| + // Report sends placed, failed or rolledback to the console door. code |
| + // is "" except with failed, and held is "" except with code |
| + // copy-in-storage (decision D12). |
| + Report func(ctx context.Context, acct, app, host, id, op, code, held string) error |
| + // ListPrefix lists every key under prefix in the fleet's own bucket, |
| + // exhaustively (release.Store.List, which paginates). An error is "not |
| + // proven", whatever keys came with it. |
| + ListPrefix func(ctx context.Context, prefix string) ([]string, error) |
| + // ReplicaPrefix is the box's replica key prefix (the activator's |
| + // cfg.Prefix). |
| + ReplicaPrefix string |
| +} |
| + |
| +// FleetSeedReplicaPrefix and FleetSeedStagingPrefix are the two prefixes a |
| +// host can be restored from, each ending in a slash so a host whose name |
| +// only begins with this one is not listed: the activator's |
| +// HibernatePrefix(prefix, host) + "/" and MovesPrefix(host). They are |
| +// spelled here because this package cannot import the activator; |
| +// TestFleetRollbackPrefixesAreTheActivators pins them to it. |
| +func FleetSeedReplicaPrefix(prefix, host string) string { return path.Join(prefix, host) + "/" } |
| +func FleetSeedStagingPrefix(host string) string { return "moves/" + host + "/" } |
| + |
| +// fleetFileSeed reports a file seed on a customer-fleet box: the one case |
| +// whose abort is finished by rollbackFleetFileSeed and nothing else. |
| +func fleetFileSeed(cfg ReconcileConfig, rec Record) bool { |
| + _, onFleet := registry.FleetPlacement(cfg.Region) |
| + return onFleet && rec.Seed != nil && rec.Seed.Kind == seeds.KindFile |
| +} |
| + |
| +// seedMintRefusal is seedAction's layout question for a ready seed with no |
| +// row: "" to mint, or why not. Every seed mints nested. A file seed on a |
| +// customer-fleet box also mints flat (design §3.5 item 0), and only when |
| +// the box can report it: without the fleet hooks nothing could ever record |
| +// it placed or roll it back. A layout that cannot be read mints nothing. |
| +func seedMintRefusal(rec Record, cfg ReconcileConfig, nested func() (bool, error)) string { |
| + ok, err := nested() |
| + if err != nil { |
| + return fmt.Sprintf("this box's layout could not be read (%v)", err) |
| + } |
| + if !fleetFileSeed(cfg, rec) { |
| + if !ok { |
| + return "this box does not mint nested" |
| + } |
| + return "" |
| + } |
| + if !fleetRollbackArmed(cfg.Seeds) { |
| + return "this fleet box cannot report a seed file's progress" |
| + } |
| + return "" |
| +} |
| + |
| +// fleetRollbackArmed reports the rollback's box hooks and all three fleet |
| +// hooks. |
| +func fleetRollbackArmed(h *SeedHooks) bool { |
| + return rollbackArmed(h) && h.Fleet != nil && h.Fleet.Report != nil && h.Fleet.ListPrefix != nil |
| +} |
| + |
| +// fleetSeedLstat and fleetSeedReadDir are seams for the tests. |
| +var ( |
| + fleetSeedLstat = os.Lstat |
| + fleetSeedReadDir = os.ReadDir |
| +) |
| + |
| +// rollbackFleetFileSeed is design §3.6 steps 1 to 4 for an aborted file seed |
| +// on a customer-fleet box, and the only code that may report rolledback. It |
| +// runs on a pass that found no row for the host (retireAbortedSeedRow |
| +// removes one first). |
| +// |
| +// The invariant: the hostname is released only when this box has proved |
| +// that nothing of the seed is left. It reports rolledback only after, under |
| +// one fence, with the host still rowless: |
| +// |
| +// - both supported local locations, nested and flat, were purged and then |
| +// seen empty (fleetSeedLocalLeft). Both, whatever the layout reader |
| +// says now: the layout intent can change between retirement and |
| +// rollback, and layout migration moves only rows that still exist, so |
| +// the current layout is no evidence of where the seed's data is (plan |
| +// R2-1, decision D5). Unlike the region rule, the purge does not ask |
| +// the marker; |
| +// - an exhaustive listing found no object under the host's replica prefix |
| +// or its staging prefix. Never lease.HasReplica: that answers only for |
| +// a head or root-layout files, and misses a generation left behind |
| +// once its head is gone (R3-1). |
| +// |
| +// Anything else is "not proven": a hook missing, a fence that does not |
| +// proceed, a row that appeared, a purge or a stat that fails, a listing |
| +// error. It logs and returns, the record stays aborted and holds the |
| +// hostname, and the next pass asks again. Objects found are reported as |
| +// failed with copy-in-storage and where they are (decisions D6, D12), which |
| +// keeps the seed aborted and tells the member why. It writes no record and |
| +// deletes no snapshot: both are the console's, after the door. |
| +func rollbackFleetFileSeed(ctx context.Context, reg *registry.Registry, cfg ReconcileConfig, rec Record) { |
| + host, id := rec.Host, rec.Seed.ID |
| + held := func(format string, a ...any) { |
| + log.Printf("provision: %s: aborted seed %s keeps its hostname: %s", host, id, fmt.Sprintf(format, a...)) |
| + } |
| + h := cfg.Seeds |
| + switch { |
| + case !fleetFileSeed(cfg, rec) || rec.Seed.State != seeds.StateAborted: |
| + held("it is not an aborted seed file on a fleet box") |
| + return |
| + case !cfg.ownsRecord(rec): |
| + held("its record is another box's") |
| + return |
| + case !fleetRollbackArmed(h): |
| + held("this box cannot fence, list its bucket or reach the console's door") |
| + return |
| + } |
| + // The host names both local paths and both prefixes. |
| + if err := seeds.Check(host, id); err != nil { |
| + held("its host or seed id is not one: %v", err) |
| + return |
| + } |
| + gen, err := h.NextFenceGen() |
| + if err == nil && gen == 0 { |
| + err = errors.New("the generation source answered 0") |
| + } |
| + if err != nil { |
| + held("no fence generation: %v", err) |
| + return |
| + } |
| + proceed, err := h.FenceForRollback(ctx, host, gen) |
| + defer h.LiftFence(host, gen) // a hook that failed may have fenced first |
| + if err != nil || !proceed { |
| + held("the host is not fenced and stopped yet (%v)", err) |
| + return |
| + } |
| + // Everything below runs under the fence. |
| + row, err := reg.Get(host) |
| + if err != nil { |
| + held("the route could not be read: %v", err) |
| + return |
| + } |
| + if row != nil { |
| + held("a route appeared at the host, so nothing local is removed") |
| + return |
| + } |
| + locations := []registry.Route{ |
| + {Host: host, Kind: "instance", DBPath: NestedDBPath(cfg.DataDir, host), Socket: NestedSocket(host)}, |
| + {Host: host, Kind: "instance", DBPath: DefaultDBPath(cfg.DataDir, host), Socket: DefaultSocket(host)}, |
| + } |
| + for _, rt := range locations { |
| + if err := h.RemoveLocal(rt); err != nil { |
| + held("remove its local data at %s: %v", rt.DBPath, err) |
| + return |
| + } |
| + } |
| + for _, rt := range locations { |
| + left, err := fleetSeedLocalLeft(rt.DBPath) |
| + if err != nil { |
| + held("cannot tell whether %s is empty: %v", rt.DBPath, err) |
| + return |
| + } |
| + if len(left) != 0 { |
| + held("%s is still on this box after the purge", strings.Join(left, ", ")) |
| + return |
| + } |
| + } |
| + replica, err := h.Fleet.ListPrefix(ctx, FleetSeedReplicaPrefix(h.Fleet.ReplicaPrefix, host)) |
| + if err != nil { |
| + held("its replica prefix could not be listed: %v", err) |
| + return |
| + } |
| + staged, err := h.Fleet.ListPrefix(ctx, FleetSeedStagingPrefix(host)) |
| + if err != nil { |
| + held("its staging prefix could not be listed: %v", err) |
| + return |
| + } |
| + if len(replica) != 0 || len(staged) != 0 { |
| + where := SeedHeldBoth |
| + switch { |
| + case len(staged) == 0: |
| + where = SeedHeldReplica |
| + case len(replica) == 0: |
| + where = SeedHeldStaging |
| + } |
| + held("a copy of its data is still in the fleet's storage (%d object(s) under %s, %d under %s)", |
| + len(replica), FleetSeedReplicaPrefix(h.Fleet.ReplicaPrefix, host), len(staged), FleetSeedStagingPrefix(host)) |
| + if err := h.Fleet.Report(ctx, rec.Account, rec.App, host, id, FleetSeedFailed, SeedCodeCopyInStorage, where); err != nil { |
| + log.Printf("provision: %s: aborted seed %s: the copy in storage was not reported: %v", host, id, err) |
| + } |
| + return |
| + } |
| + if err := h.Fleet.Report(ctx, rec.Account, rec.App, host, id, FleetSeedRolledBack, "", ""); err != nil { |
| + held("nothing of it is left, but the console did not hear so: %v", err) |
| + return |
| + } |
| + log.Printf("provision: %s: aborted seed %s: nothing of it is left on this box or in the fleet's storage; reported rolled back", host, id) |
| +} |
| + |
| +// fleetSeedLocalLeft names what could stand in for a seed's database at |
| +// dbPath: the database, its WAL and SHM, its <db>.seed marker, litestream's |
| +// metadata, and any fetch temp of this database (".seed-<base>-", any seed |
| +// id). It is the purge's own list (the activator's purgeSeedTarget), read |
| +// back. Lstat, so a symlink there counts as there. Only "does not exist" |
| +// is absence: any other error is returned, and the caller has no proof. |
| +func fleetSeedLocalLeft(dbPath string) ([]string, error) { |
| + dir, base := filepath.Dir(dbPath), filepath.Base(dbPath) |
| + var left []string |
| + for _, n := range []string{base, base + "-wal", base + "-shm", base + ".seed", base + "-litestream", ".activator-" + base + "-litestream"} { |
| + p := filepath.Join(dir, n) |
| + if _, err := fleetSeedLstat(p); err == nil { |
| + left = append(left, p) |
| + } else if !errors.Is(err, os.ErrNotExist) { |
| + return nil, err |
| + } |
| + } |
| + ents, err := fleetSeedReadDir(dir) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return left, nil // no directory: no temp in it |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + for _, e := range ents { |
| + if strings.HasPrefix(e.Name(), ".seed-"+base+"-") { |
| + left = append(left, filepath.Join(dir, e.Name())) |
| + } |
| + } |
| + return left, nil |
| +} |
diff --git a/internal/provision/seedfleet_test.go b/internal/provision/seedfleet_test.go| new file mode 100644 |
| index 000000000..2bd3c236e |
| --- /dev/null |
| +++ b/internal/provision/seedfleet_test.go |
| @@ -0,0 +1,708 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +// fleetSeedBox is a fleet box's rollback hooks over a real data directory, |
| +// with the fleet's bucket as two listings. It records the steps in order, |
| +// and its Report refuses to hear rolledback while either local location |
| +// still holds seed data: the invariant, checked where it is reported. |
| +type fleetSeedBox struct { |
| + t *testing.T |
| + dataDir string |
| + host string |
| + steps []string |
| + proceed bool |
| + fenceErr error |
| + onFence func() |
| + gen uint64 |
| + fenced map[string]uint64 |
| + removeErr map[string]error // by database path |
| + keepLocal bool // RemoveLocal answers nil and removes nothing |
| + keys map[string][]string |
| + listErr map[string]error |
| + reports []string |
| + reportErr error |
| +} |
| + |
| +func newFleetSeedBox(t *testing.T, host string) *fleetSeedBox { |
| + return &fleetSeedBox{t: t, host: host, proceed: true, fenced: map[string]uint64{}, |
| + removeErr: map[string]error{}, keys: map[string][]string{}, listErr: map[string]error{}} |
| +} |
| + |
| +func (b *fleetSeedBox) replicaPrefix() string { return "instances/" + b.host + "/" } |
| +func (b *fleetSeedBox) stagingPrefix() string { return "moves/" + b.host + "/" } |
| + |
| +func (b *fleetSeedBox) hooks(h *SeedHooks) { |
| + h.NextFenceGen = func() (uint64, error) { b.gen++; return b.gen, nil } |
| + h.FenceForRollback = func(_ context.Context, host string, gen uint64) (bool, error) { |
| + b.steps = append(b.steps, "fence") |
| + if b.fenceErr != nil || !b.proceed { |
| + return false, b.fenceErr |
| + } |
| + b.fenced[host] = gen |
| + if b.onFence != nil { |
| + b.onFence() |
| + } |
| + return true, nil |
| + } |
| + h.LiftFence = func(host string, gen uint64) { |
| + b.steps = append(b.steps, "lift") |
| + if b.fenced[host] == gen { |
| + delete(b.fenced, host) |
| + } |
| + } |
| + h.LocalSeedID = func(string) (string, error) { |
| + b.t.Error("the fleet rollback read a seed marker: its purge does not depend on one") |
| + return "", nil |
| + } |
| + h.DeleteReplica = func(context.Context, string) error { |
| + b.t.Error("the fleet rollback deleted a replica") |
| + return nil |
| + } |
| + h.RetireKey = func(string, string, string) error { |
| + b.t.Error("the fleet rollback retired an instance key") |
| + return nil |
| + } |
| + h.RemoveLocal = func(rt registry.Route) error { |
| + b.steps = append(b.steps, "purge "+rt.DBPath) |
| + if _, ok := b.fenced[rt.Host]; !ok { |
| + b.t.Errorf("purged %s while the host was not fenced and stopped", rt.DBPath) |
| + } |
| + if err := b.removeErr[rt.DBPath]; err != nil { |
| + return err |
| + } |
| + if b.keepLocal { |
| + return nil |
| + } |
| + for _, p := range seedDataAt(rt.DBPath) { |
| + if err := os.RemoveAll(p); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| + } |
| + h.Fleet = &FleetSeedHooks{ |
| + ReplicaPrefix: "instances", |
| + ListPrefix: func(_ context.Context, prefix string) ([]string, error) { |
| + b.steps = append(b.steps, "list "+prefix) |
| + if len(b.fenced) == 0 { |
| + b.t.Errorf("listed %s while the host was not fenced", prefix) |
| + } |
| + return b.keys[prefix], b.listErr[prefix] |
| + }, |
| + Report: func(_ context.Context, acct, app, host, id, op, code, held string) error { |
| + b.steps = append(b.steps, "report "+op) |
| + b.reports = append(b.reports, strings.TrimSpace(op+" "+code+" "+held)) |
| + if op == FleetSeedRolledBack { |
| + if len(b.fenced) == 0 { |
| + b.t.Error("rolledback was reported with the fence lifted") |
| + } |
| + if left := b.localLeft(); len(left) != 0 { |
| + b.t.Errorf("rolledback was reported while seed data is still on the box: %v", left) |
| + } |
| + if len(b.keys[b.replicaPrefix()])+len(b.keys[b.stagingPrefix()]) != 0 { |
| + b.t.Error("rolledback was reported while the fleet's bucket holds a copy") |
| + } |
| + } |
| + return b.reportErr |
| + }, |
| + } |
| +} |
| + |
| +// localLeft is the seed data at either supported location. |
| +func (b *fleetSeedBox) localLeft() []string { |
| + var left []string |
| + for _, db := range []string{NestedDBPath(b.dataDir, b.host), DefaultDBPath(b.dataDir, b.host)} { |
| + left = append(left, seedDataAt(db)...) |
| + } |
| + return left |
| +} |
| + |
| +// seedDataAt is what of a seed exists at db: the database, its WAL and SHM, |
| +// its marker, and its own fetch temps. |
| +func seedDataAt(db string) []string { |
| + var got []string |
| + for _, p := range []string{db, db + "-wal", db + "-shm", db + ".seed"} { |
| + if _, err := os.Lstat(p); err == nil { |
| + got = append(got, p) |
| + } |
| + } |
| + temps, _ := filepath.Glob(filepath.Join(filepath.Dir(db), ".seed-"+filepath.Base(db)+"-*")) |
| + return append(got, temps...) |
| +} |
| + |
| +// placeFleetSeedData leaves at db what a placement, or one cut short, |
| +// leaves: the database, WAL, SHM, marker and a fetch temp. |
| +func placeFleetSeedData(t *testing.T, db, id string) { |
| + t.Helper() |
| + if err := os.MkdirAll(filepath.Dir(db), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + temp := filepath.Join(filepath.Dir(db), ".seed-"+filepath.Base(db)+"-"+id+".tmp") |
| + for p, body := range map[string]string{db: "the seed's data", db + "-wal": "wal", db + "-shm": "shm", db + ".seed": id, temp: "half a fetch"} { |
| + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +const ( |
| + layoutFlat = release.LayoutModeFlat |
| + layoutNested = release.LayoutModeNested |
| +) |
| + |
| +// fleetSeedCfg is box pi-1 of fleet pi, with the rollback and fleet hooks. |
| +// layout is what the layout reader answers now; "!" is a reader that fails. |
| +func fleetSeedCfg(t *testing.T, box *fleetSeedBox, layout string) ReconcileConfig { |
| + t.Helper() |
| + h := &SeedHooks{Data: dirStore(t)} |
| + box.hooks(h) |
| + box.dataDir = t.TempDir() |
| + return ReconcileConfig{Region: "fleet/pi", FleetBox: "pi-1", Pools: []string{"tito"}, DataDir: box.dataDir, Seeds: h, |
| + Layout: func(context.Context, release.Store) (string, error) { |
| + if layout == "!" { |
| + return "", errors.New("layout intent unreadable") |
| + } |
| + return layout, nil |
| + }} |
| +} |
| + |
| +func fleetFileSeedRecord(t *testing.T, s release.Store, sqid, state, label string) Record { |
| + t.Helper() |
| + rec := acmeRecord(sqid) |
| + rec.Region = "fleet/pi" |
| + if label != "" { |
| + rec.FleetBox, rec.FleetBoxAt = label, "2026-10-30T09:00:00Z" |
| + } |
| + id, _ := seeds.NewID() |
| + rec.Seed = &SeedSource{ID: id, Kind: seeds.KindFile, State: state, SHA256: "a", Bytes: 1, By: "t", At: time.Now()} |
| + if err := CreateRecord(ctx, s, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + return rec |
| +} |
| + |
| +// abortedFleetSeed is an aborted fleet file seed with no row on the box, |
| +// its snapshot in the box's Data store (where a region seed's would be, so |
| +// a delete through the region path would show). |
| +func abortedFleetSeed(t *testing.T, layout string) (release.Store, Record, *fleetSeedBox, ReconcileConfig, *registry.Registry) { |
| + t.Helper() |
| + s, sqid := setup(t) |
| + rec := fleetFileSeedRecord(t, s, sqid, seeds.StateAborted, "") |
| + box := newFleetSeedBox(t, rec.Host) |
| + cfg := fleetSeedCfg(t, box, layout) |
| + if _, err := cfg.Seeds.Data.Put(ctx, seeds.SnapshotKey(rec.Host, rec.Seed.ID), []byte("db"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + return s, rec, box, cfg, regWith(t) |
| +} |
| + |
| +// requireUntouchedByBox: the fleet rollback writes no record and deletes no |
| +// snapshot. Both are the console's, after the door hears rolledback. |
| +func requireUntouchedByBox(t *testing.T, s release.Store, cfg ReconcileConfig, rec Record) { |
| + t.Helper() |
| + requireSeedState(t, s, rec, seeds.StateAborted) |
| + if _, _, err := cfg.Seeds.Data.Get(ctx, seeds.SnapshotKey(rec.Host, rec.Seed.ID)); err != nil { |
| + t.Fatalf("the box touched the snapshot: %v", err) |
| + } |
| +} |
| + |
| +func TestFleetFileSeedRollbackReportsRolledBackWhenEmpty(t *testing.T) { |
| + s, rec, box, cfg, reg := abortedFleetSeed(t, layoutFlat) |
| + nested, flat := NestedDBPath(cfg.DataDir, rec.Host), DefaultDBPath(cfg.DataDir, rec.Host) |
| + placeFleetSeedData(t, flat, rec.Seed.ID) |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []string{"fence", "purge " + nested, "purge " + flat, "list " + box.replicaPrefix(), "list " + box.stagingPrefix(), "report rolledback", "lift"} |
| + if !reflect.DeepEqual(box.steps, want) { |
| + t.Fatalf("steps = %q\n want %q", box.steps, want) |
| + } |
| + if !reflect.DeepEqual(box.reports, []string{"rolledback"}) { |
| + t.Fatalf("reports = %q", box.reports) |
| + } |
| + if len(box.fenced) != 0 { |
| + t.Fatalf("a fence was left: %v", box.fenced) |
| + } |
| + requireUntouchedByBox(t, s, cfg, rec) |
| + // A report the door did not hear is sent again by the next pass. |
| + box.reportErr = errors.New("door unreachable") |
| + box.reports = nil |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(box.reports, []string{"rolledback"}) { |
| + t.Fatalf("second pass reports = %q", box.reports) |
| + } |
| +} |
| + |
| +func TestFleetFileSeedRollbackListingErrorReportsNothing(t *testing.T) { |
| + for _, which := range []string{"replica", "staging"} { |
| + t.Run(which, func(t *testing.T) { |
| + s, rec, box, cfg, reg := abortedFleetSeed(t, layoutFlat) |
| + prefix := box.replicaPrefix() |
| + if which == "staging" { |
| + prefix = box.stagingPrefix() |
| + } |
| + box.listErr[prefix] = errors.New("throttled") |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(box.reports) != 0 { |
| + t.Fatalf("a listing that failed was reported as %q", box.reports) |
| + } |
| + requireUntouchedByBox(t, s, cfg, rec) |
| + // The same when the failed listing also returned keys, or none. |
| + box.listErr[prefix] = nil |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(box.reports, []string{"rolledback"}) { |
| + t.Fatalf("once it lists: reports = %q", box.reports) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// R3-1: head.json is gone and a generation is left, so lease.HasReplica |
| +// would answer false. The exhaustive listing still finds it. |
| +func TestFleetFileSeedRollbackOrphanedGenerationHolds(t *testing.T) { |
| + s, rec, box, cfg, reg := abortedFleetSeed(t, layoutNested) |
| + box.keys[box.replicaPrefix()] = []string{box.replicaPrefix() + "g-0001/0000/0000000000000001-0000000000000001.ltx"} |
| + for pass := 0; pass < 2; pass++ { |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if want := []string{"failed copy-in-storage replica", "failed copy-in-storage replica"}; !reflect.DeepEqual(box.reports, want) { |
| + t.Fatalf("reports = %q, want %q", box.reports, want) |
| + } |
| + requireUntouchedByBox(t, s, cfg, rec) |
| + // A lock.json kept by an abandoned lease holds it too (gap G10). |
| + box.keys[box.replicaPrefix()] = []string{box.replicaPrefix() + "lock.json"} |
| + box.reports = nil |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(box.reports, []string{"failed copy-in-storage replica"}) { |
| + t.Fatalf("lock.json alone: reports = %q", box.reports) |
| + } |
| +} |
| + |
| +// R3-2: objects under moves/<host>/ hold the hostname as a replica does. |
| +func TestFleetFileSeedRollbackWithStagedObjectsHolds(t *testing.T) { |
| + s, rec, box, cfg, reg := abortedFleetSeed(t, layoutFlat) |
| + box.keys[box.stagingPrefix()] = []string{box.stagingPrefix() + "generations/a/snapshot"} |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + box.keys[box.replicaPrefix()] = []string{box.replicaPrefix() + "head.json"} |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := []string{"failed copy-in-storage staging", "failed copy-in-storage both"}; !reflect.DeepEqual(box.reports, want) { |
| + t.Fatalf("reports = %q, want %q", box.reports, want) |
| + } |
| + requireUntouchedByBox(t, s, cfg, rec) |
| +} |
| + |
| +func TestFleetFileSeedRollbackFenceDeclinedDoesNothing(t *testing.T) { |
| + for name, decline := range map[string]func(*fleetSeedBox){ |
| + "deferred": func(b *fleetSeedBox) { b.proceed = false }, |
| + "failed": func(b *fleetSeedBox) { b.fenceErr = errors.New("stop unproven") }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + s, rec, box, cfg, reg := abortedFleetSeed(t, layoutFlat) |
| + flat := DefaultDBPath(cfg.DataDir, rec.Host) |
| + placeFleetSeedData(t, flat, rec.Seed.ID) |
| + decline(box) |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := []string{"fence", "lift"}; !reflect.DeepEqual(box.steps, want) { |
| + t.Fatalf("steps = %q, want %q", box.steps, want) |
| + } |
| + if len(seedDataAt(flat)) != 5 { |
| + t.Fatalf("local data was removed without the fence: %v", seedDataAt(flat)) |
| + } |
| + requireUntouchedByBox(t, s, cfg, rec) |
| + }) |
| + } |
| +} |
| + |
| +func TestFleetFileSeedRollbackRowAppearedUnderFence(t *testing.T) { |
| + _, rec, box, cfg, reg := abortedFleetSeed(t, layoutFlat) |
| + flat := DefaultDBPath(cfg.DataDir, rec.Host) |
| + placeFleetSeedData(t, flat, rec.Seed.ID) |
| + box.onFence = func() { |
| + if err := reg.Upsert(registry.Route{Host: rec.Host, Kind: "instance", Socket: DefaultSocket(rec.Host), DBPath: flat}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // Called directly: a pass that already saw no row is the caller. |
| + rollbackFleetFileSeed(ctx, reg, cfg, rec) |
| + if want := []string{"fence", "lift"}; !reflect.DeepEqual(box.steps, want) { |
| + t.Fatalf("steps = %q, want %q", box.steps, want) |
| + } |
| + if len(seedDataAt(flat)) != 5 { |
| + t.Fatalf("a row's local data was removed: %v", seedDataAt(flat)) |
| + } |
| +} |
| + |
| +// A flat directory holds every instance on the box. The rollback purges |
| +// DefaultDBPath for its own host, and another instance's database and fetch |
| +// temp neither go nor hold this seed's hostname. |
| +func TestFleetFileSeedRollbackPurgesFlatPath(t *testing.T) { |
| + s, rec, box, cfg, reg := abortedFleetSeed(t, layoutFlat) |
| + flat := DefaultDBPath(cfg.DataDir, rec.Host) |
| + placeFleetSeedData(t, flat, rec.Seed.ID) |
| + other := DefaultDBPath(cfg.DataDir, "other.go.tito.io") |
| + otherID, _ := seeds.NewID() |
| + placeFleetSeedData(t, other, otherID) |
| + var purged []registry.Route |
| + inner := cfg.Seeds.RemoveLocal |
| + cfg.Seeds.RemoveLocal = func(rt registry.Route) error { purged = append(purged, rt); return inner(rt) } |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []registry.Route{ |
| + {Host: rec.Host, Kind: "instance", DBPath: NestedDBPath(cfg.DataDir, rec.Host), Socket: NestedSocket(rec.Host)}, |
| + {Host: rec.Host, Kind: "instance", DBPath: flat, Socket: DefaultSocket(rec.Host)}, |
| + } |
| + if !reflect.DeepEqual(purged, want) { |
| + t.Fatalf("purged %+v\n want %+v", purged, want) |
| + } |
| + if !reflect.DeepEqual(box.reports, []string{"rolledback"}) { |
| + t.Fatalf("reports = %q; another instance's files must not hold this hostname", box.reports) |
| + } |
| + if len(seedDataAt(other)) != 5 { |
| + t.Fatalf("another instance's data went with the rollback: %v", seedDataAt(other)) |
| + } |
| +} |
| + |
| +func TestFleetFileSeedRollbackNotOwnerDoesNothing(t *testing.T) { |
| + s, sqid := setup(t) |
| + rec := fleetFileSeedRecord(t, s, sqid, seeds.StateAborted, "pi-2") |
| + box := newFleetSeedBox(t, rec.Host) |
| + cfg := fleetSeedCfg(t, box, layoutFlat) |
| + reg := regWith(t) |
| + placeFleetSeedData(t, DefaultDBPath(cfg.DataDir, rec.Host), rec.Seed.ID) |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + rollbackFleetFileSeed(ctx, reg, cfg, rec) // and past the scan, by its own check |
| + if len(box.steps) != 0 { |
| + t.Fatalf("another box's seed: steps = %q", box.steps) |
| + } |
| + requireSeedState(t, s, rec, seeds.StateAborted) |
| +} |
| + |
| +// On a fleet box a file seed never takes the region path, armed or not: a |
| +// box missing a hook reports nothing, writes no record, deletes no snapshot. |
| +func TestFleetFileSeedRollbackUnarmedDoesNothing(t *testing.T) { |
| + for name, disarm := range map[string]func(*SeedHooks){ |
| + "no fleet hooks": func(h *SeedHooks) { h.Fleet = nil }, |
| + "no fence": func(h *SeedHooks) { h.FenceForRollback = nil }, |
| + "no lister": func(h *SeedHooks) { h.Fleet.ListPrefix = nil }, |
| + "no reporter": func(h *SeedHooks) { h.Fleet.Report = nil }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + s, rec, box, cfg, reg := abortedFleetSeed(t, layoutFlat) |
| + placeFleetSeedData(t, DefaultDBPath(cfg.DataDir, rec.Host), rec.Seed.ID) |
| + disarm(cfg.Seeds) |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(box.steps) != 0 { |
| + t.Fatalf("steps = %q", box.steps) |
| + } |
| + requireUntouchedByBox(t, s, cfg, rec) |
| + }) |
| + } |
| +} |
| + |
| +// Plan R2-1, decision D5: the layout reader is no evidence of where the |
| +// seed's data is. Both supported locations are purged and then proved empty |
| +// under the fence, whatever the reader says now, and rolledback is never |
| +// reported while either holds seed data (fleetSeedBox.Report checks that on |
| +// every report). Each row runs a pass with its fault, then one without. |
| +func TestFleetFileSeedRollbackLayoutChangedHolds(t *testing.T) { |
| + type fix struct { |
| + box *fleetSeedBox |
| + cfg ReconcileConfig |
| + rec Record |
| + flat string |
| + nest string |
| + } |
| + for _, c := range []struct { |
| + name string |
| + layout string // what the layout reader answers at rollback |
| + at string // where the seed's data was left: flat, nested, both |
| + fault func(t *testing.T, f fix) (clear func()) |
| + // held: the faulted pass must purge nothing more, list nothing and |
| + // report nothing. |
| + held bool |
| + }{ |
| + {name: "left flat, reader now says nested", layout: layoutNested, at: "flat"}, |
| + {name: "left nested, reader now says flat", layout: layoutFlat, at: "nested"}, |
| + {name: "left in both, reader cannot be read", layout: "!", at: "both"}, |
| + {name: "left flat, no layout intent", layout: release.LayoutModeNone, at: "flat"}, |
| + {name: "purge of the flat location fails", layout: layoutNested, at: "both", held: true, |
| + fault: func(t *testing.T, f fix) func() { |
| + f.box.removeErr[f.flat] = errors.New("read-only file system") |
| + return func() { delete(f.box.removeErr, f.flat) } |
| + }}, |
| + {name: "purge of the nested location fails", layout: layoutFlat, at: "both", held: true, |
| + fault: func(t *testing.T, f fix) func() { |
| + f.box.removeErr[f.nest] = errors.New("read-only file system") |
| + return func() { delete(f.box.removeErr, f.nest) } |
| + }}, |
| + {name: "purge answers done and leaves the data", layout: layoutFlat, at: "flat", held: true, |
| + fault: func(t *testing.T, f fix) func() { |
| + f.box.keepLocal = true |
| + return func() { f.box.keepLocal = false } |
| + }}, |
| + {name: "stat of the flat database errors", layout: layoutNested, at: "nested", held: true, |
| + fault: func(t *testing.T, f fix) func() { |
| + setFleetSeedStat(t, func(p string) (fs.FileInfo, error) { |
| + if p == f.flat { |
| + return nil, &fs.PathError{Op: "lstat", Path: p, Err: syscall.EIO} |
| + } |
| + return os.Lstat(p) |
| + }, nil) |
| + return func() { fleetSeedLstat = os.Lstat } |
| + }}, |
| + {name: "stat of the nested marker errors", layout: layoutFlat, at: "flat", held: true, |
| + fault: func(t *testing.T, f fix) func() { |
| + setFleetSeedStat(t, func(p string) (fs.FileInfo, error) { |
| + if p == f.nest+".seed" { |
| + return nil, &fs.PathError{Op: "lstat", Path: p, Err: syscall.EACCES} |
| + } |
| + return os.Lstat(p) |
| + }, nil) |
| + return func() { fleetSeedLstat = os.Lstat } |
| + }}, |
| + {name: "the flat directory cannot be read for temps", layout: layoutNested, at: "nested", held: true, |
| + fault: func(t *testing.T, f fix) func() { |
| + setFleetSeedStat(t, nil, func(dir string) ([]os.DirEntry, error) { |
| + if dir == filepath.Dir(f.flat) { |
| + return nil, &fs.PathError{Op: "open", Path: dir, Err: syscall.EIO} |
| + } |
| + return os.ReadDir(dir) |
| + }) |
| + return func() { fleetSeedReadDir = os.ReadDir } |
| + }}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + s, rec, box, cfg, reg := abortedFleetSeed(t, c.layout) |
| + f := fix{box: box, cfg: cfg, rec: rec, flat: DefaultDBPath(cfg.DataDir, rec.Host), nest: NestedDBPath(cfg.DataDir, rec.Host)} |
| + if c.at == "flat" || c.at == "both" { |
| + placeFleetSeedData(t, f.flat, rec.Seed.ID) |
| + } |
| + if c.at == "nested" || c.at == "both" { |
| + placeFleetSeedData(t, f.nest, rec.Seed.ID) |
| + } |
| + if c.fault != nil { |
| + clear := c.fault(t, f) |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(box.reports) != 0 { |
| + t.Fatalf("with the fault: reports = %q, want none", box.reports) |
| + } |
| + for _, st := range box.steps { |
| + if strings.HasPrefix(st, "list ") { |
| + t.Fatalf("with the fault the bucket was listed before the local proof: %q", box.steps) |
| + } |
| + } |
| + requireUntouchedByBox(t, s, cfg, rec) |
| + clear() |
| + } |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(box.reports, []string{"rolledback"}) { |
| + t.Fatalf("reports = %q, want one rolledback", box.reports) |
| + } |
| + if left := box.localLeft(); len(left) != 0 { |
| + t.Fatalf("seed data left on the box: %v", left) |
| + } |
| + requireUntouchedByBox(t, s, cfg, rec) |
| + }) |
| + } |
| +} |
| + |
| +func setFleetSeedStat(t *testing.T, lstat func(string) (fs.FileInfo, error), readDir func(string) ([]os.DirEntry, error)) { |
| + t.Helper() |
| + oldL, oldR := fleetSeedLstat, fleetSeedReadDir |
| + t.Cleanup(func() { fleetSeedLstat, fleetSeedReadDir = oldL, oldR }) |
| + if lstat != nil { |
| + fleetSeedLstat = lstat |
| + } |
| + if readDir != nil { |
| + fleetSeedReadDir = readDir |
| + } |
| +} |
| + |
| +// The row goes first, as for --from: the pass that finds a row retires it |
| +// and leaves everything else, and a later pass with no row rolls back. |
| +func TestFleetFileSeedRowRetiredBeforeRollback(t *testing.T) { |
| + s, sqid := setup(t) |
| + rec := fleetFileSeedRecord(t, s, sqid, seeds.StateReady, "") |
| + box := newFleetSeedBox(t, rec.Host) |
| + cfg := fleetSeedCfg(t, box, layoutFlat) |
| + reg := regWith(t) |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + row := mustGet(t, reg, rec.Host) |
| + if row.DBPath != DefaultDBPath(cfg.DataDir, rec.Host) || row.Seed != "" || row.SeedSource != SeedColumn(rec) { |
| + t.Fatalf("flat fleet mint = db %q seed %q col %q", row.DBPath, row.Seed, row.SeedSource) |
| + } |
| + placeFleetSeedData(t, row.DBPath, rec.Seed.ID) |
| + if _, err := SetRecordSeed(ctx, s, rec.Account, rec.App, rec.Host, SeedAbort(rec.Seed.ID)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rt, _ := reg.Get(rec.Host); rt != nil { |
| + t.Fatalf("the aborted seed's row is still up: %+v", rt) |
| + } |
| + if len(box.steps) != 0 || len(seedDataAt(row.DBPath)) != 5 { |
| + t.Fatalf("the row's pass did more than retire it: steps %q", box.steps) |
| + } |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !reflect.DeepEqual(box.reports, []string{"rolledback"}) { |
| + t.Fatalf("reports = %q", box.reports) |
| + } |
| + requireSeedState(t, s, rec, seeds.StateAborted) |
| +} |
| + |
| +// Rule 1: a flat customer-fleet box mints a ready file seed, flat. Every |
| +// other flat mint, and claim control, still refuse. |
| +func TestFleetFileSeedMintLayout(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + kind string |
| + layout string |
| + tweak func(*ReconcileConfig) |
| + mints bool |
| + }{ |
| + {name: "flat fleet box, file seed", kind: seeds.KindFile, layout: layoutFlat, mints: true}, |
| + {name: "nested fleet box, file seed", kind: seeds.KindFile, layout: layoutNested, mints: true}, |
| + {name: "flat fleet box, --from seed", kind: seeds.KindReplica, layout: layoutFlat}, |
| + {name: "layout unreadable", kind: seeds.KindFile, layout: "!"}, |
| + {name: "claim control", kind: seeds.KindFile, layout: layoutFlat, tweak: func(c *ReconcileConfig) { c.ClaimEnabled = true }}, |
| + {name: "no fleet hooks", kind: seeds.KindFile, layout: layoutFlat, tweak: func(c *ReconcileConfig) { c.Seeds.Fleet = nil }}, |
| + {name: "no fleet hooks, nested", kind: seeds.KindFile, layout: layoutNested, tweak: func(c *ReconcileConfig) { c.Seeds.Fleet = nil }}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + s, sqid := setup(t) |
| + rec := acmeRecord(sqid) |
| + rec.Region = "fleet/pi" |
| + id, _ := seeds.NewID() |
| + rec.Seed = &SeedSource{ID: id, Kind: c.kind, State: seeds.StateReady, SHA256: "a", Bytes: 1, By: "t", At: time.Now()} |
| + if err := CreateRecord(ctx, s, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := fleetSeedCfg(t, newFleetSeedBox(t, rec.Host), c.layout) |
| + if c.tweak != nil { |
| + c.tweak(&cfg) |
| + } |
| + reg := regWith(t) |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + rt, _ := reg.Get(rec.Host) |
| + if (rt != nil) != c.mints { |
| + t.Fatalf("row = %+v; want minted %v", rt, c.mints) |
| + } |
| + if rt != nil && rt.Seed != "" { |
| + t.Fatalf("a seeded row carries the seed command %q", rt.Seed) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Off a fleet nothing changes: a flat region box mints no file seed, and an |
| +// aborted one takes Task 4's path (the snapshot's delete and the record's |
| +// CAS to rolled-back), with no report, even with fleet hooks present. |
| +func TestRegionFileSeedRollbackUnchanged(t *testing.T) { |
| + s, sqid := setup(t) |
| + rec := seededRecord(t, s, sqid, seeds.KindFile, seeds.StateAborted) |
| + fbox := newFleetSeedBox(t, rec.Host) |
| + stray := fleetSeedCfg(t, fbox, layoutNested) |
| + box := newDiskBox(t, s, rec) |
| + data := dirStore(t) |
| + cfg := diskSeedCfg(t, data, box) |
| + cfg.Seeds.Fleet = stray.Seeds.Fleet |
| + snap := seeds.SnapshotKey(rec.Host, rec.Seed.ID) |
| + if _, err := data.Put(ctx, snap, []byte("db"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + db := NestedDBPath(cfg.DataDir, rec.Host) |
| + placeLocal(t, db, rec.Seed.ID) |
| + if err := Reconcile(ctx, s, regWith(t), cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + requireSeedState(t, s, rec, seeds.StateRolledBack) |
| + if want := []string{"read-marker", "fence", "read-marker", "remove-local", "lift"}; !reflect.DeepEqual(box.steps, want) { |
| + t.Fatalf("steps = %q, want %q", box.steps, want) |
| + } |
| + if _, _, err := data.Get(ctx, snap); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("snapshot: %v; want it deleted", err) |
| + } |
| + if len(fbox.steps) != 0 { |
| + t.Fatalf("a region box used the fleet hooks: %q", fbox.steps) |
| + } |
| + |
| + t.Run("flat region box mints no file seed", func(t *testing.T) { |
| + s, sqid := setup(t) |
| + rec := seededRecord(t, s, sqid, seeds.KindFile, seeds.StateReady) |
| + cfg := nestedSeedCfg(dirStore(t)) |
| + cfg.Layout = func(context.Context, release.Store) (string, error) { return release.LayoutModeFlat, nil } |
| + cfg.Seeds.Fleet = stray.Seeds.Fleet |
| + reg := regWith(t) |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rt, _ := reg.Get(rec.Host); rt != nil { |
| + t.Fatalf("a flat region box minted a file seed: %+v", rt) |
| + } |
| + }) |
| +} |
| + |
| +// The two restore-capable prefixes, spelled once here for the rollback and |
| +// pinned against the activator's own in its tests. |
| +func TestFleetSeedPrefixes(t *testing.T) { |
| + for _, c := range []struct{ prefix, host, replica string }{ |
| + {"instances", "shop.example.com", "instances/shop.example.com/"}, |
| + {"", "shop.example.com", "shop.example.com/"}, |
| + {"a/b/", "shop.example.com", "a/b/shop.example.com/"}, |
| + } { |
| + if got := FleetSeedReplicaPrefix(c.prefix, c.host); got != c.replica { |
| + t.Errorf("replica prefix (%q, %q) = %q, want %q", c.prefix, c.host, got, c.replica) |
| + } |
| + } |
| + if got := FleetSeedStagingPrefix("shop.example.com"); got != "moves/shop.example.com/" { |
| + t.Errorf("staging prefix = %q", got) |
| + } |
| +} |
diff --git a/internal/provision/seedreconcile.go b/internal/provision/seedreconcile.go| index 8bb6992ee..84f747b06 100644 |
| --- a/internal/provision/seedreconcile.go |
| +++ b/internal/provision/seedreconcile.go |
| @@ -69,6 +69,11 @@ type SeedHooks struct { |
| // It never removes a key or a line that predates the import, and it is |
| // not part of RemoveLocal. Nothing there is not an error. |
| RetireKey func(dbPath, host, envBefore string) error |
| + |
| + // Fleet is a customer-fleet box's file seed hooks (fleet seeded create |
| + // design §3.6, seedfleet.go). Nil off a fleet. Nil on a fleet: no file |
| + // seed is minted there, and an aborted one keeps its hostname. |
| + Fleet *FleetSeedHooks |
| } |
| type seedVerdict int |
| @@ -148,8 +153,8 @@ func seedAction(rec Record, row *registry.Route, cfg ReconcileConfig, nested fun |
| log.Printf("provision: %s: not minting a seeded instance: its record does not describe a hibernating instance", rec.Host) |
| return seedSkip |
| } |
| - if ok, err := nested(); err != nil || !ok { |
| - log.Printf("provision: %s: not minting a seeded instance: this box does not mint nested (%v)", rec.Host, err) |
| + if why := seedMintRefusal(rec, cfg, nested); why != "" { |
| + log.Printf("provision: %s: not minting a seeded instance: %s", rec.Host, why) |
| return seedSkip |
| } |
| return seedOrdinary |
| @@ -241,11 +246,20 @@ func abortRetiresRow(rec Record) bool { |
| // A host or id that fails seeds.Check names no snapshot (no valid key |
| // could hold one), so nothing is deleted and the record is still rolled |
| // back. |
| +// |
| +// A file seed on a customer-fleet box takes none of that path: its abort is |
| +// finished by rollbackFleetFileSeed alone (fleet seeded create design §3.6). |
| func finishAbortedSeed(ctx context.Context, s release.Store, reg *registry.Registry, cfg ReconcileConfig, rec Record) { |
| if cfg.DryRun { |
| log.Printf("provision: dry-run: would finish aborted seed %s of %s", rec.Seed.ID, rec.Host) |
| return |
| } |
| + // On a customer-fleet box a file seed's hostname is released by one |
| + // function and by nothing below: no snapshot delete, no record write. |
| + if fleetFileSeed(cfg, rec) { |
| + rollbackFleetFileSeed(ctx, reg, cfg, rec) |
| + return |
| + } |
| if abortRetiresRow(rec) && !purgeAbortedFromLocal(ctx, reg, cfg, rec) { |
| return |
| } |