console: seed files on a customer fleet
Plan Task 16 (#1139 slice 3): begin, upload, readiness, sweep, finish and delete for a fleet-placed file seed, and every retirement entrance. - Begin admits a fleet placement and asks seedFleetReady: a claim console first (R3-1), the floor at the fleet protocol (FS-25), one active box (FS-21/22), a fresh heartbeat with its seeds floor (FS-22/23), no claim control (FS-24), nested only (FS-26, D13). - seedStorageRefusal's fleet branch (R2-2): a fleet file seed needs only the deployment bucket; begin and upload agree. Its snapshot goes to apps/<sqid>/<app>/seeds/<host>/<id>/snapshot.db, create-only. - The sweep lists every fleet-placed app's seeds, trashed apps included (R1-4), and runs without a data bucket; it deletes an abandoned seed's snapshot and keeps the record (R3-3). It never rolls a fleet seed back. - The finish deletes the fleet key and never a fleet replica. - Delete (D9, R1-5): reserving or ready aborts (202 FS-13); aborted is 409, FS-34 naming the held place (FS-36 to FS-38), else FS-33. - Purge (R1-1): the Trash page, the expiry pass's early purge and the trash sweep refuse (FS-35) while a fleet file seed holds a hostname.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+1,319
−103
internal/console/apiinstanceimport.go+15 −7internal/console/expirypass.go+10 −0internal/console/lifetimes_purge.go+9 −0internal/console/ownership.go+13 −0internal/console/seedfile.go+278 −38internal/console/seedfile_copy.go+30 −0internal/console/seedfile_test.go+4 −5internal/console/seedfilefleet_test.go+594 −0internal/console/seedfinish.go+14 −6internal/console/seedfloor.go+25 −15internal/console/seedpurgehold_test.go+173 −0internal/console/seedsweep.go+123 −31internal/provision/fleet_seeded_create_3_census_test.go+31 −1
CI failed — run details
diff --git a/internal/console/apiinstanceimport.go b/internal/console/apiinstanceimport.go| index d255946f4..fc919029c 100644 |
| --- a/internal/console/apiinstanceimport.go |
| +++ b/internal/console/apiinstanceimport.go |
| @@ -387,8 +387,12 @@ type importUpload struct { |
| app, host, by string |
| id string |
| kind string // the seed's: seeds.KindImport or seeds.KindFile |
| - dir, spool string |
| - release func() |
| + // store and key are where the snapshot goes (seedSnapshotTarget), |
| + // decided from the record before the hand-over. |
| + store release.Store |
| + key string |
| + dir, spool string |
| + release func() |
| // unit is the request's admitted unit, handed over before the |
| // goroutine starts: the job ends it after its last write |
| // (lifetimes_cutover.go). |
| @@ -487,8 +491,9 @@ func (s *Server) handleAPIImportUpload(w http.ResponseWriter, r *http.Request) { |
| writeJSON(w, http.StatusAccepted, map[string]string{"state": "checking"}) |
| handedOver = true |
| s.seedCopies.Add(1) |
| + store, key := s.seedSnapshotTarget(rec) |
| go s.runImportUpload(&importUpload{ctx: context.WithoutCancel(ctx), acct: acct, app: app, host: host, by: principal, |
| - id: seed.ID, kind: seed.Kind, dir: dir, spool: spool, release: releaseScratch, unit: detachUnit(ctx)}) |
| + id: seed.ID, kind: seed.Kind, store: store, key: key, dir: dir, spool: spool, release: releaseScratch, unit: detachUnit(ctx)}) |
| } |
| // readImportRecord reads host's record under instanceStoreTimeout. |
| @@ -666,7 +671,7 @@ func (s *Server) runImportUpload(j *importUpload) { |
| return |
| } |
| uctx, ucancel := context.WithTimeout(ctx, seedUploadDeadline) |
| - err = putSnapshot(uctx, s.cfg.SeedData, j.spool, seeds.SnapshotKey(host, j.id)) |
| + err = putSnapshot(uctx, j.store, j.spool, j.key) |
| ucancel() |
| if errors.Is(err, release.ErrCASConflict) { |
| // Another writer put this seed's snapshot first, and owns the |
| @@ -999,7 +1004,10 @@ func (s *Server) abortAnswered(w http.ResponseWriter, r *http.Request, sqid, app |
| // - any other uncommitted state: 409, abort the import instead (SD-N57). |
| // - a file seed reserving, aborted or rolled-back: aborted (or left |
| // aborting) and answered 202 with FS-13, or finished once rolled back |
| -// (fileSeedDeleteRule); the box's rollback and the finish free it. |
| +// (fileSeedDeleteRule); the box's rollback and the finish free it. On |
| +// a customer fleet a ready one is aborted too, and an aborted one is |
| +// refused (409 FS-33 or FS-34) until its box proves it clean (plan |
| +// D9, R1-5). |
| // - committed, a --from seed, any other file seed, an unseeded record, |
| // or a record that will not decode: the ordinary delete, conditional on the etag read here |
| // (deleteRead), answered as finished. |
| @@ -1064,8 +1072,8 @@ func (s *Server) importDeleteRule(w http.ResponseWriter, r *http.Request, acct * |
| // A file seed not yet ready is aborted, waited for or finished, never |
| // deleted outright (seedfile.go); a ready or placed one takes the |
| // ordinary delete, as --from's does. |
| - if rec != nil && fileSeedUnreadied(rec.Seed) { |
| - return s.fileSeedDeleteRule(w, r, acct, app, host, rec.Seed, again) |
| + if rec != nil && fileSeedUnreadied(rec) { |
| + return s.fileSeedDeleteRule(w, r, acct, app, host, rec, again) |
| } |
| if rec == nil || !rec.Seed.Import() || rec.Seed.State == seeds.StateCommitted { |
| return s.deleteRead(w, r, acct, app, host, etag, again) |
diff --git a/internal/console/expirypass.go b/internal/console/expirypass.go| index 8053a4684..8b03e7336 100644 |
| --- a/internal/console/expirypass.go |
| +++ b/internal/console/expirypass.go |
| @@ -243,6 +243,16 @@ func (s *Server) purgeOne(ctx context.Context, r AppRow, now time.Time, ev evide |
| s.audit(acct, r.App, expiryActor, "purge-refused", "did not delete "+r.App+": it has email set up. Delete it from the Trash page") |
| return |
| } |
| + // A fleet file seed still holding a hostname (plan R1-1): not purged |
| + // until its box has proved it clean. The next pass asks again. |
| + if msg, err := s.fleetSeedPurgeRefusal(ctx, r.Sqid, r.App); err != nil || msg != "" { |
| + if err != nil { |
| + msg = err.Error() |
| + jobFailed(ctx, fmt.Errorf("expiry pass: %s/%s: fleet seeds: %w; not purging", r.Sqid, r.App, err)) |
| + } |
| + log.Printf("console: expiry pass: %s/%s: %s Not purging it this pass.", r.Sqid, r.App, msg) |
| + return |
| + } |
| // The purge's own guards first, at the marker clock this decision was |
| // made about: a purge they refuse (store estate, a production flag, a |
| // restore since) retires no media job. Then the app's media jobs, |
diff --git a/internal/console/lifetimes_purge.go b/internal/console/lifetimes_purge.go| index 8913586c4..a37fd0d9b 100644 |
| --- a/internal/console/lifetimes_purge.go |
| +++ b/internal/console/lifetimes_purge.go |
| @@ -241,6 +241,15 @@ func (s *Server) sweepTrashedApp(ctx context.Context, a release.TrashedApp, now |
| s.lifetimeLogHourly("trash-sweep "+a.Account+"/"+a.App, "console: trash sweep: %s/%s has email estate; not purging it. Delete it from the Trash page", a.Account, a.App) |
| return |
| } |
| + // A fleet file seed still holding a hostname (plan R1-1): not purged |
| + // until its box has proved it clean (FS-35 in the log). |
| + if msg, err := s.fleetSeedPurgeRefusal(ctx, a.Account, a.App); err != nil { |
| + s.lifetimeLogHourly("trash-sweep "+a.Account+"/"+a.App, "console: trash sweep: %s/%s: fleet seeds: %v; not purging", a.Account, a.App, err) |
| + return |
| + } else if msg != "" { |
| + s.lifetimeLogHourly("trash-sweep "+a.Account+"/"+a.App, "console: trash sweep: %s/%s: %s", a.Account, a.App, msg) |
| + return |
| + } |
| // The purge's own guards first, at the marker's clock: a purge they |
| // refuse (store estate, a production flag) retires no media job. Then |
| // the app's media jobs, before any purge step: while a task is still |
diff --git a/internal/console/ownership.go b/internal/console/ownership.go| index 5f4251210..b5c8a39ef 100644 |
| --- a/internal/console/ownership.go |
| +++ b/internal/console/ownership.go |
| @@ -544,6 +544,19 @@ func (s *Server) handlePurgeApp(w http.ResponseWriter, r *http.Request) { |
| fail(purgeAdvice(err, app)) |
| return |
| } |
| + // A fleet file seed's hostname is released only once its box has proved |
| + // nothing of it is left (fleet seeded create design §3.6, plan R1-1): |
| + // the purge would retire its record without that proof. Asked before |
| + // any teardown below, and refused (FS-35) while one holds a hostname, |
| + // or when the records cannot be read whole. |
| + if msg, err := s.fleetSeedPurgeRefusal(r.Context(), acct.Sqid, app); err != nil { |
| + log.Printf("console: purge %s/%s: fleet seeds: %v", acct.Sqid, app, err) |
| + fail(purgeAdvice(err, app)) |
| + return |
| + } else if msg != "" { |
| + fail(msg) |
| + return |
| + } |
| if s.cfg.HostClaim { |
| if s.cfg.ClaimPurge == nil { |
| s.renderDoorRefusal(w, r, claimResponseRefusal(hostops.ErrContract)) |
diff --git a/internal/console/seedfile.go b/internal/console/seedfile.go| index fb9e71b3e..3b0e4f82b 100644 |
| --- a/internal/console/seedfile.go |
| +++ b/internal/console/seedfile.go |
| @@ -6,9 +6,9 @@ |
| // placed; aborted, rolled-back), not the import's swap, so a region file |
| // seed is --from-shaped everywhere except how its bytes arrive. |
| // |
| -// This file holds the file seed's begin, its readiness rule and the |
| -// helpers the import door calls when it meets a file seed. Fleet records |
| -// are refused here until slice 3 of the plan. |
| +// This file holds the file seed's begin, its readiness rules (a region's, |
| +// and a customer fleet's, slice 3) and the helpers the import door calls |
| +// when it meets a file seed. |
| package console |
| @@ -19,13 +19,16 @@ import ( |
| "log" |
| "net/http" |
| "os" |
| + "sort" |
| "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/regionlabel" |
| + "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/seeds" |
| + "github.com/carlosframework/platform/internal/status" |
| ) |
| // seedFileReserveTTL is how long a file seed may stay reserving before the |
| @@ -59,12 +62,14 @@ func (s *Server) createFileSeed(w http.ResponseWriter, r *http.Request, c seedCr |
| } |
| // beginFileSeed runs after the create door's own checks, seedOneDoorRefusal |
| -// and seedCommonRefusal among them. It refuses a pool (FS-20), a fleet |
| -// (seedPlacementRefusal's sentence, until slice 3) and an HA region |
| -// (FS-16); a region record must be in this console's region (FS-15), as |
| -// the import's must, because the snapshot goes to this console's data |
| -// bucket. Then seedFileReady, the size and sha256, and private storage as |
| -// the import does. The record is written reserving, kind file, with the |
| +// and seedCommonRefusal among them. It refuses a pool (FS-20) and an HA |
| +// region (FS-16); a region record must be in this console's region |
| +// (FS-15), as the import's must, because the snapshot goes to this |
| +// console's data bucket. A fleet-placed record skips the region and |
| +// data-bucket checks: its snapshot goes to the deployment bucket, which the |
| +// fleet's box reads through the store door (fleet seeded create design |
| +// §3.3), and its readiness is seedFleetReady's. Then the size and sha256, |
| +// and private storage as the import does. The record is written reserving, kind file, with the |
| // sha256 and length the upload must match and no Replaces or VerifyHash, |
| // before any byte of the snapshot is stored (design §3.2). It answers 201 |
| // with the record view. |
| @@ -76,6 +81,7 @@ func (s *Server) createFileSeed(w http.ResponseWriter, r *http.Request, c seedCr |
| func (s *Server) beginFileSeed(w http.ResponseWriter, r *http.Request, c seedCreate, imp seedImportReq) { |
| ctx := r.Context() |
| acct, app, host := c.acct, c.app, c.rec.Host |
| + fleet, onFleet := registry.FleetPlacement(c.rec.Region) |
| if ref := fileSeedPlacementRefusal(c); ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| @@ -87,13 +93,17 @@ func (s *Server) beginFileSeed(w http.ResponseWriter, r *http.Request, c seedCre |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
| - if c.rec.Region != s.cfg.Region { |
| + if !onFleet && c.rec.Region != s.cfg.Region { |
| jsonError(w, http.StatusConflict, fmt.Sprintf(fileSeedRegionCopy, s.dbRegionName(s.cfg.Region), host)) |
| return |
| } |
| checks, cancel := context.WithTimeout(ctx, instanceStoreTimeout) |
| defer cancel() |
| - if ref := s.seedFileReady(checks, c.rec.Region); ref != nil { |
| + ready := func() *doorRefusal { return s.seedFileReady(checks, c.rec.Region) } |
| + if onFleet { |
| + ready = func() *doorRefusal { return s.seedFleetReady(checks, fleet) } |
| + } |
| + if ref := ready(); ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
| @@ -198,17 +208,22 @@ func (s *Server) beginFileSeed(w http.ResponseWriter, r *http.Request, c seedCre |
| out := s.publicRecordView(ctx, rec) |
| out.PrivateStoreBucket = privateBucket |
| out.RegionFrom = c.regionFrom |
| - out.RegionName = s.placeOf(rec.Region, s.candsOrHome(viewCtx)) // never fleet-placed: refused above |
| + // A fleet-placed record's Region is the fleet itself, as the ordinary |
| + // create answers it. |
| + if !onFleet { |
| + out.RegionName = s.placeOf(rec.Region, s.candsOrHome(viewCtx)) |
| + } |
| // The region's label (region labels §4), as every create answer has. |
| out.RegionLabel = regionlabel.ForRecord(rec, s.regionHome(), s.regionNames()).Text |
| writeJSON(w, http.StatusCreated, out) |
| } |
| -// fileSeedPlacementRefusal is a file seed's placement rule. A pool has its |
| -// own sentence (FS-20), since file seeds will reach a fleet but not a pool. |
| -// A fleet keeps seedPlacementRefusal's sentence until slice 3 admits it. |
| +// fileSeedPlacementRefusal is a file seed's placement rule. A customer |
| +// fleet is admitted (slice 3; its readiness is seedFleetReady's). A pool has |
| +// its own sentence (FS-20), since file seeds reach a fleet but not a pool. |
| +// A demo, or a placement that is not a fleet, keeps seedPlacementRefusal's. |
| func fileSeedPlacementRefusal(c seedCreate) *doorRefusal { |
| - if c.rec.Demo != nil || c.placed != "" { |
| + if _, fleet := registry.FleetPlacement(c.placed); c.rec.Demo != nil || c.placed != "" && !fleet { |
| return seedPlacementRefusal(c) |
| } |
| if c.m.Pool != "" { |
| @@ -242,19 +257,45 @@ func (s *Server) refuseHASeed(w http.ResponseWriter, rec *provision.Record, kind |
| // seedStorageRefusal is the one answer to "can this console store this |
| // seed's snapshot" (plan R2-2), asked by begin and by the upload alike so |
| -// the two never disagree. placement is the record's Region column. |
| -// kind and placement are unused until slice 3's fleet branch reads them. An |
| -// import and a region file seed need this console's data bucket and the |
| -// hibernation bucket its replicas live in; the refusal is the import's, |
| -// byte for byte (seedNoDataRefusal). Slice 3 adds the fleet file seed's |
| -// branch here, which needs the deployment bucket instead. |
| +// the two never disagree, and nothing else checks storage. placement is |
| +// the record's Region column. An import and a region file seed need this |
| +// console's data bucket and the hibernation bucket its replicas live in; |
| +// the refusal is the import's, byte for byte (seedNoDataRefusal). A fleet |
| +// file seed needs the deployment bucket and nothing regional: its snapshot |
| +// goes there (seedSnapshotTarget), and its replica is the fleet's own. |
| func (s *Server) seedStorageRefusal(kind, placement string) *doorRefusal { |
| + if _, fleet := registry.FleetPlacement(placement); fleet && kind == seeds.KindFile { |
| + if s.cfg.Releases == nil { |
| + return seedNoDataRefusal() |
| + } |
| + return nil |
| + } |
| if s.cfg.SeedData == nil || s.cfg.HibernateBucket == "" { |
| return seedNoDataRefusal() |
| } |
| return nil |
| } |
| +// seedSnapshotTarget is where rec's seed snapshot lives: a fleet file |
| +// seed's in the deployment bucket at seeds.FleetSnapshotKey, which the |
| +// fleet's box reads through the store door (fleet seeded create design |
| +// §3.3); every other seed's in this console's data bucket at |
| +// seeds.SnapshotKey. The key is built from the record's own values, never |
| +// from a request (seeds.Check has passed on them). |
| +func (s *Server) seedSnapshotTarget(rec *provision.Record) (release.Store, string) { |
| + if seedOnFleet(rec) { |
| + return s.cfg.Releases, seeds.FleetSnapshotKey(rec.Account, rec.App, rec.Host, rec.Seed.ID) |
| + } |
| + return s.cfg.SeedData, seeds.SnapshotKey(rec.Host, rec.Seed.ID) |
| +} |
| + |
| +// seedOnFleet reports a fleet file seed: a file seed whose record is |
| +// placed on a customer fleet. |
| +func seedOnFleet(rec *provision.Record) bool { |
| + _, fleet := registry.FleetPlacement(rec.Region) |
| + return fleet && rec.Seed != nil && rec.Seed.Kind == seeds.KindFile |
| +} |
| + |
| // seedFileReady is seedRegionReady with the file protocol: the published |
| // floor's Min must be at least seeds.FileSeedProtocol (FS-25), and every |
| // box in the region must report at least max(FileSeedProtocol, floor.Min). |
| @@ -265,9 +306,13 @@ func (s *Server) seedFileReady(ctx context.Context, region string) *doorRefusal |
| } |
| // seedUploadReady is the upload's readiness re-check, by the seed's kind: |
| -// an import keeps its one-box rule, a file seed asks seedFileReady. |
| +// an import keeps its one-box rule, a file seed asks seedFileReady, or on a |
| +// fleet seedFleetReady, as its begin did. |
| func (s *Server) seedUploadReady(ctx context.Context, rec *provision.Record) *doorRefusal { |
| if rec.Seed != nil && rec.Seed.Kind == seeds.KindFile { |
| + if fleet, ok := registry.FleetPlacement(rec.Region); ok { |
| + return s.seedFleetReady(ctx, fleet) |
| + } |
| return s.seedFileReady(ctx, rec.Region) |
| } |
| return s.seedRegionReady(ctx, rec.Region, true) |
| @@ -316,40 +361,55 @@ func (s *Server) abortFileSeed(ctx context.Context, sqid, app, host, id, reason, |
| } |
| // fileSeedUnreadied reports a file seed the delete door must not drop |
| -// outright: reserving (its upload not landed), aborted or rolled-back. |
| -func fileSeedUnreadied(seed *provision.SeedSource) bool { |
| +// outright: reserving (its upload not landed), aborted or rolled-back; and |
| +// on a customer fleet, ready too (plan D9): a fleet file seed's hostname is |
| +// released only after its box proves nothing of it is left (design §3.6), |
| +// so nothing before placement may take the ordinary delete. |
| +func fileSeedUnreadied(rec *provision.Record) bool { |
| + seed := rec.Seed |
| if seed == nil || seed.Kind != seeds.KindFile { |
| return false |
| } |
| switch seed.State { |
| case seeds.StateReserving, seeds.StateAborted, seeds.StateRolledBack: |
| return true |
| + case seeds.StateReady: |
| + return seedOnFleet(rec) |
| } |
| return false |
| } |
| // fileSeedDeleteRule is the delete door's answer to a file seed that never |
| // became ready (plan D9's region case, pulled forward at the slice 1 |
| -// review). The ordinary delete would drop the record without the box's |
| -// rollback or the console's finish, stranding the private store the begin |
| -// made, so the next --seed-file on the host would meet the store-taken |
| -// refusal. So: |
| +// review), or on a customer fleet never placed (slice 3). The ordinary |
| +// delete would drop the record without the box's rollback or the |
| +// console's finish, stranding the private store the begin made, so the |
| +// next --seed-file on the host would meet the store-taken refusal; and on |
| +// a fleet it would release a hostname nothing has proved free. So: |
| // |
| -// - reserving: aborted (SeedAbortFileUploadBecause, a CAS that acts only |
| -// while it is still reserving), the serial bumped, and 202 with FS-13. |
| -// - aborted (by this door, the sweep or a failed upload): 202 with FS-13 |
| -// again, writing nothing; the box has its rollback still to do. |
| +// - reserving (and on a fleet, ready): aborted, the serial bumped, and |
| +// 202 with FS-13. A region seed's abort acts only while it is still |
| +// reserving (SeedAbortFileUploadBecause); a fleet seed's from either |
| +// state (SeedAbort). |
| +// - aborted, on a region (by this door, the sweep or a failed upload): |
| +// 202 with FS-13 again, writing nothing; the box has its rollback still |
| +// to do. |
| +// - aborted, on a fleet, whatever its reason (plan R1-5): 409, writing |
| +// nothing. Only the fleet's box can release the hostname, by reporting |
| +// rolledback to the seeds door once it has proved the seed gone; until |
| +// then the answer says why it is held (fleetSeedHeldSentence). |
| // - rolled-back: the console's finish (store, snapshot, replica, then |
| // the record), answered as a finished delete. |
| // |
| -// The record holds the hostname until the finish deletes it. A ready or |
| -// placed file seed is not here: it takes the ordinary delete, exactly as a |
| -// --from seed in those states does. |
| +// The record holds the hostname until the finish deletes it. A region |
| +// ready or a placed file seed is not here: it takes the ordinary delete, |
| +// exactly as a --from seed in those states does. |
| // |
| // An abort CAS that finds the seed moved on (its upload landed, the sweep |
| // got there) decides once more from a fresh read when again allows, else |
| // answers SD-N60. |
| -func (s *Server) fileSeedDeleteRule(w http.ResponseWriter, r *http.Request, acct *Account, app, host string, seed *provision.SeedSource, again bool) (answered, finished bool) { |
| +func (s *Server) fileSeedDeleteRule(w http.ResponseWriter, r *http.Request, acct *Account, app, host string, rec *provision.Record, again bool) (answered, finished bool) { |
| + seed, onFleet := rec.Seed, seedOnFleet(rec) |
| if s.cfg.HostClaim { |
| // No finish runs on a claim console, so nothing there may abort a |
| // seed whose finish frees the host; no seed door begins one there. |
| @@ -360,6 +420,10 @@ func (s *Server) fileSeedDeleteRule(w http.ResponseWriter, r *http.Request, acct |
| aborting := map[string]string{"state": "aborting", "message": fmt.Sprintf(fileSeedDeletingCopy, host)} |
| switch seed.State { |
| case seeds.StateAborted: |
| + if onFleet { |
| + jsonError(w, http.StatusConflict, fleetSeedHeldSentence(host, seed)) |
| + return true, false |
| + } |
| writeJSON(w, http.StatusAccepted, aborting) |
| return true, false |
| case seeds.StateRolledBack: |
| @@ -370,7 +434,11 @@ func (s *Server) fileSeedDeleteRule(w http.ResponseWriter, r *http.Request, acct |
| } |
| ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), instanceStoreTimeout) |
| defer cancel() |
| - _, err := provision.SetRecordSeed(ctx, s.cfg.Releases, acct.Sqid, app, host, provision.SeedAbortFileUploadBecause(seed.ID, "")) |
| + abort := provision.SeedAbortFileUploadBecause(seed.ID, "") |
| + if onFleet { |
| + abort = provision.SeedAbort(seed.ID) |
| + } |
| + _, err := provision.SetRecordSeed(ctx, s.cfg.Releases, acct.Sqid, app, host, abort) |
| switch { |
| case errors.Is(err, os.ErrNotExist): |
| return true, true // gone already: the delete's idempotent answer |
| @@ -394,3 +462,175 @@ func (s *Server) fileSeedDeleteRule(w http.ResponseWriter, r *http.Request, acct |
| writeJSON(w, http.StatusAccepted, aborting) |
| return true, false |
| } |
| + |
| +// seedFleetReady is the fleet file seed's readiness (fleet seeded create |
| +// design §3.4), asked by begin and by the upload's re-check alike. nil |
| +// means go ahead. In order: |
| +// |
| +// - a claim-enabled console refuses first (plan R3-1), before any fleet |
| +// check, as seedRegionReadyForEdges does: such a console neither sweeps |
| +// nor finishes a seed, so it must never admit one; |
| +// - the seeds floor is published and usable, with Min at least |
| +// seeds.FleetFileSeedProtocol (FS-25); |
| +// - the fleet has exactly one active box (decision D8): a file seed's |
| +// record is created unlabelled, before fleet labelling, so one box must |
| +// be its owner (FS-21); none is unconfirmed (FS-22); |
| +// - the fleet's heartbeats read whole, and the box's is fresh and carries |
| +// Metrics, Layout and SeedsFloor, once (FS-22, a 503, the box logged); |
| +// - the box's seeds floor is the region check's rule (seedfloor.go): |
| +// protocol at least max(FleetFileSeedProtocol, floor.Min), the floor's |
| +// min_release armed, carlos.prev none or vouched for it, and the root |
| +// floor guard not refusing (FS-23); |
| +// - no claim control on the box (FS-24); |
| +// - the box runs nested (FS-26; a flat box is refused, decision D13). |
| +// |
| +// Every missing, zero or unreadable fact is not ready. A box with an old |
| +// heartbeat (no seeds_floor) never reads as ready. |
| +func (s *Server) seedFleetReady(ctx context.Context, fleet string) *doorRefusal { |
| + if s.cfg.HostClaim { |
| + return seedClaimConsoleRefusal() |
| + } |
| + floor, ref := s.publishedSeedsFloor(ctx) |
| + if ref != nil { |
| + return ref |
| + } |
| + if floor.Min < seeds.FleetFileSeedProtocol { |
| + return &doorRefusal{Status: http.StatusConflict, Msg: fileSeedFloorCopy} |
| + } |
| + unconfirmed := &doorRefusal{Status: http.StatusServiceUnavailable, Msg: fmt.Sprintf(fileSeedFleetUnconfirmedCopy, fleet)} |
| + reg, err := openRegistry(s.cfg.Registry) |
| + if err != nil { |
| + log.Printf("console: seed file readiness: fleet %s: registry: %v", fleet, err) |
| + return unconfirmed |
| + } |
| + regBoxes, err := reg.ListFleetBoxes(fleet) |
| + if err != nil { |
| + log.Printf("console: seed file readiness: fleet %s: list its boxes: %v", fleet, err) |
| + return unconfirmed |
| + } |
| + var active []string |
| + for _, b := range regBoxes { |
| + if b.Status == "active" { |
| + active = append(active, b.Label) |
| + } |
| + } |
| + switch { |
| + case len(active) == 0: |
| + log.Printf("console: seed file readiness: fleet %s has no active box", fleet) |
| + return unconfirmed |
| + case len(active) > 1: |
| + return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(fileSeedFleetBoxesCopy, fleet)} |
| + } |
| + label := active[0] |
| + beats, complete, err := status.LoadBoxesComplete(ctx, release.NewPrefixStore(s.cfg.Releases, "fleets/"+fleet+"/")) |
| + if err != nil || !complete { |
| + log.Printf("console: seed file readiness: fleet %s: heartbeats complete %v: %v", fleet, complete, err) |
| + return unconfirmed |
| + } |
| + var b status.Box |
| + seen := 0 |
| + for _, hb := range beats { |
| + if hb.Label == label { |
| + b, seen = hb, seen+1 |
| + } |
| + } |
| + why := "" |
| + switch { |
| + case seen == 0: |
| + why = "no heartbeat" |
| + case seen > 1: |
| + why = "more than one heartbeat with this label" |
| + case status.BoxStale(b, time.Now(), status.SnapshotPeriod): |
| + why = "stale heartbeat, generated " + b.GeneratedAt.UTC().Format(time.RFC3339) |
| + case b.Metrics == nil || b.Metrics.Layout == nil: |
| + why = "no layout report" |
| + case b.Metrics.SeedsFloor == nil: |
| + why = "no seeds floor report" |
| + } |
| + if why != "" { |
| + log.Printf("console: seed file readiness: box %q in fleet %s is unconfirmed: %s", label, fleet, why) |
| + return unconfirmed |
| + } |
| + f := b.Metrics.SeedsFloor |
| + prevOK := b.Metrics.PrevRelease == "none" || f.PrevAllowedFor == floor.MinRelease |
| + rootRefused := (f.MovesFloorState != "" || f.MovesFloorGeneration != 0 || f.FloorState != "" || f.FloorGeneration != 0) && |
| + (f.FloorState != "accepted" || f.FloorGeneration == 0) |
| + switch { |
| + case f.Protocol < max(seeds.FleetFileSeedProtocol, floor.Min) || rootRefused || f.MinRelease != floor.MinRelease || !prevOK: |
| + return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(fileSeedFleetBelowFloorCopy, label, fleet)} |
| + case b.Metrics.HostClaimEnabled: |
| + return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(fileSeedFleetClaimCopy, label, fleet)} |
| + case b.Metrics.Layout.Mode != "nested": |
| + return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(fileSeedFleetLayoutCopy, label, fleet)} |
| + } |
| + return nil |
| +} |
| + |
| +// fleetSeedHeldSentence is the delete door's 409 for an aborted fleet file |
| +// seed (plan R1-5). FS-30 with a held place gets FS-34, whose location the |
| +// console builds from the host and the held enum alone (decision D12; |
| +// FS-36, FS-37, FS-38): a box never supplies text a member reads. Every |
| +// other reason, and FS-30 with no held (none is expected), gets FS-33. |
| +func fleetSeedHeldSentence(host string, seed *provision.SeedSource) string { |
| + replica := fmt.Sprintf(fileSeedHeldReplicaCopy, host) |
| + staging := fmt.Sprintf(fileSeedHeldStagingCopy, host) |
| + where := "" |
| + if seed.Reason == fileSeedCopyInStorageCopy { |
| + switch seed.Held { |
| + case provision.SeedHeldReplica: |
| + where = replica |
| + case provision.SeedHeldStaging: |
| + where = staging |
| + case provision.SeedHeldBoth: |
| + where = fmt.Sprintf(fileSeedHeldBothCopy, replica, staging) |
| + } |
| + } |
| + if where == "" { |
| + return fmt.Sprintf(fileSeedHeldCopy, host) |
| + } |
| + return fmt.Sprintf(fileSeedHeldInStorageCopy, host, where) |
| +} |
| + |
| +// unfinishedFleetFileSeeds names, sorted, the hosts of sqid/app whose record |
| +// is a fleet file seed in any state but placed or rolled-back (plan R1-1): |
| +// a hostname its box has not yet proved free (design §3.6). Every entrance |
| +// that retires the app's records or deletes its keys (the Trash page's |
| +// purge, the expiry pass's early purge, the trash sweep) asks it before any |
| +// destructive work, and refuses while it names any host, with FS-35 |
| +// (fleetSeedPurgeRefusal). It reads strictly: a record that will not decode, |
| +// a listing it cannot finish or one past instanceListMax is an error, and |
| +// the caller refuses on it too (fail closed). Once the box reports |
| +// rolledback and the record is finished, the host is no longer named. |
| +func (s *Server) unfinishedFleetFileSeeds(ctx context.Context, sqid, app string) ([]string, error) { |
| + recs, unreadable, err := s.listRecordsStrict(ctx, sqid, app, instanceListMax) |
| + if err != nil { |
| + return nil, fmt.Errorf("list the instances of %s/%s: %w", sqid, app, err) |
| + } |
| + if len(unreadable) > 0 { |
| + return nil, fmt.Errorf("list the instances of %s/%s: %d records could not be read", sqid, app, len(unreadable)) |
| + } |
| + var hosts []string |
| + for i := range recs { |
| + rec := &recs[i] |
| + if seedOnFleet(rec) && rec.Seed.State != seeds.StatePlaced && rec.Seed.State != seeds.StateRolledBack { |
| + hosts = append(hosts, rec.Host) |
| + } |
| + } |
| + sort.Strings(hosts) |
| + return hosts, nil |
| +} |
| + |
| +// fleetSeedPurgeRefusal is the purge entrances' check, before any |
| +// destructive work: "" to go ahead, else the sentence that refuses (FS-35, |
| +// naming the held hosts). An error reading the records refuses too, with |
| +// err set for the caller to log or answer in its own words. |
| +func (s *Server) fleetSeedPurgeRefusal(ctx context.Context, sqid, app string) (string, error) { |
| + hosts, err := s.unfinishedFleetFileSeeds(ctx, sqid, app) |
| + if err != nil { |
| + return "", err |
| + } |
| + if len(hosts) == 0 { |
| + return "", nil |
| + } |
| + return fmt.Sprintf(fileSeedPurgeHeldCopy, app, strings.Join(hosts, ", ")), nil |
| +} |
diff --git a/internal/console/seedfile_copy.go b/internal/console/seedfile_copy.go| index 92508f6d8..a30facbbc 100644 |
| --- a/internal/console/seedfile_copy.go |
| +++ b/internal/console/seedfile_copy.go |
| @@ -18,6 +18,19 @@ const ( |
| fileSeedMismatchCopy = "the upload does not match the file this create began with, so it was not kept." |
| // FS-20: %s is the app. |
| fileSeedPoolCopy = "%s places its instances in a pool, so it cannot take a seeded instance." |
| + // FS-21: %s is the fleet. A file seed's record is created unlabelled, |
| + // so its fleet must have one active box to own it (decision D8). |
| + fileSeedFleetBoxesCopy = "fleet %s has more than one active box. A seeded instance needs a fleet with one active box for now." |
| + // FS-22: %s is the fleet. A 503: a box with no fresh, whole heartbeat, |
| + // or none active; the log names the box. |
| + fileSeedFleetUnconfirmedCopy = "could not confirm every box in fleet %s. Try again in a minute." |
| + // FS-23: %s is the boxes, then the fleet. |
| + fileSeedFleetBelowFloorCopy = "the platform on %s in fleet %s is below the seeds floor. Update it, then try again." |
| + // FS-24: %s is the boxes, then the fleet. |
| + fileSeedFleetClaimCopy = "claim control is on for %s in fleet %s. Seeded instances are not supported there yet." |
| + // FS-26: %s is the boxes, then the fleet. Shown for any box whose |
| + // layout is not nested (decision D13). |
| + fileSeedFleetLayoutCopy = "%s in fleet %s keeps all its instances in one shared directory. A seed file needs a box that keeps each instance in its own." |
| // FS-25: capital T, as its sibling SD-N3. |
| fileSeedFloorCopy = "This deployment’s seeds floor does not allow seed files yet. An operator publishes it again with carlos system seeds-floor publish." |
| @@ -33,6 +46,23 @@ const ( |
| // FS-30, code copy-in-storage; the record keeps where (held) beside it. |
| fileSeedCopyInStorageCopy = "a copy of its data is still in the fleet’s storage" |
| + // FS-33: %s is the host. The delete door's 409 for an aborted fleet |
| + // file seed whose box has not yet proved it clean. |
| + fileSeedHeldCopy = "%s was not created. Its hostname is free again once its box has cleaned up." |
| + // FS-34: %s is the host, then the location (FS-36, FS-37 or FS-38). |
| + // The delete door's 409 for FS-30 with a held place (decision D12). |
| + fileSeedHeldInStorageCopy = "%s keeps its hostname while a copy of its data is still in the fleet’s storage, under %s. Remove everything there, and the hostname is free again after the box’s next pass." |
| + // FS-36: held replica; %s is the host. The box's CARLOS_HIBERNATE_PREFIX |
| + // goes before it, if set: the console never sees that prefix. |
| + fileSeedHeldReplicaCopy = "%s/ (after the box’s CARLOS_HIBERNATE_PREFIX, if set)" |
| + // FS-37: held staging; %s is the host. |
| + fileSeedHeldStagingCopy = "moves/%s/" |
| + // FS-38: held both; FS-36, then FS-37. |
| + fileSeedHeldBothCopy = "%s and %s" |
| + // FS-35: %s is the app, then the hosts. The Trash page's "Delete now" |
| + // and the trash sweeps' log, while a fleet file seed holds a hostname. |
| + fileSeedPurgeHeldCopy = "%s can’t be deleted permanently until its fleet box has cleaned up %s." |
| + |
| // FS-41: an import object whose kind is neither absent nor "file". Only a hand-written API call reaches it; the CLI sends one or |
| // the other. |
| fileSeedKindCopy = "kind must be file, or left out for an import" |
diff --git a/internal/console/seedfile_test.go b/internal/console/seedfile_test.go| index 7ec5a2768..511f408c5 100644 |
| --- a/internal/console/seedfile_test.go |
| +++ b/internal/console/seedfile_test.go |
| @@ -139,6 +139,7 @@ func TestFileSeedUploadMismatchAborts(t *testing.T) { |
| mk func(*testing.T) fromFixture |
| }{ |
| {"region", newFileSeedFixture}, |
| + {"fleet", newFleetFileFixture}, |
| } { |
| t.Run(row.name, func(t *testing.T) { |
| f := row.mk(t) |
| @@ -154,6 +155,7 @@ func TestFileSeedUploadMismatchAborts(t *testing.T) { |
| } |
| requireFileState(t, rec, begun.Seed.ID, seeds.StateAborted, fileSeedMismatchCopy) |
| f.requireNothingUploaded(t) |
| + f.requireNoFleetSnapshot(t) |
| f.requireClean(t) |
| // The right file now is refused: the seed has gone. |
| if code, out := uploadImport(t, f, fileHost, body); code != http.StatusConflict || |
| @@ -196,7 +198,8 @@ func TestFileSeedRefusesPool(t *testing.T) { |
| } |
| // fleetSeedCreate posts body for shop on a fleet-placed world and requires |
| -// the --from and import placement refusal, with nothing written. |
| +// the --from and import placement refusal, with nothing written. A file |
| +// seed is admitted on a fleet since slice 3 (seedfilefleet_test.go). |
| func fleetSeedCreate(t *testing.T, body string) { |
| t.Helper() |
| fx, token, reg := d1World(t, "code-fs-fleet", "pi-1") |
| @@ -211,10 +214,6 @@ func fleetSeedCreate(t *testing.T, body string) { |
| } |
| } |
| -func TestFileSeedRefusesFleetUntilSlice3(t *testing.T) { |
| - fleetSeedCreate(t, fileSeedBody("b.example.com", importSHA, 10)) |
| -} |
| - |
| func TestFromOnFleetStillRefuses(t *testing.T) { |
| fleetSeedCreate(t, `{"host":"b.example.com","from":{"host":"a.example.com"}}`) |
| } |
diff --git a/internal/console/seedfilefleet_test.go b/internal/console/seedfilefleet_test.go| new file mode 100644 |
| index 000000000..22253c855 |
| --- /dev/null |
| +++ b/internal/console/seedfilefleet_test.go |
| @@ -0,0 +1,594 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "os" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// File seeds on a customer fleet (#1139 slice 3, plan Task 16): begin, |
| +// upload, readiness, sweep, finish, delete and every retirement entrance. |
| + |
| +const seedFleet = "pi" |
| + |
| +// newFleetFileFixture is the file seed world with shop placed on bab's |
| +// fleet pi: one active box pi-1, whose fresh, nested heartbeat reports the |
| +// fleet protocol, and the seeds floor at the fleet protocol. |
| +func newFleetFileFixture(t *testing.T) fromFixture { |
| + t.Helper() |
| + f := newImportFixture(t) |
| + if err := seeds.PublishFloor(context.Background(), f.fx.rel, seeds.Floor{Min: seeds.FleetFileSeedProtocol, MinRelease: "v0.27.0"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg, err := openRegistry(f.fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if ok, err := reg.CreateFleet(registry.Fleet{Name: seedFleet, Account: "bab", Bucket: "pi-data"}); err != nil || !ok { |
| + t.Fatalf("create fleet: %v %v", ok, err) |
| + } |
| + if err := reg.AddFleetBox(registry.FleetBox{Fleet: seedFleet, Label: "pi-1", TokenHash: strings.Repeat("a", 64)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + fleetSeedBeat(t, f.fx, "pi-1", nil) |
| + if err := f.fx.st.SetAppPlacement(OpsAccountID, fromApp, "fleet/"+seedFleet); err != nil { |
| + t.Fatal(err) |
| + } |
| + return f |
| +} |
| + |
| +// fleetSeedBeat writes label's heartbeat on fleet pi: fresh, nested, at the |
| +// fleet protocol and the floor's min_release, then mut. |
| +func fleetSeedBeat(t *testing.T, fx *consoleFixture, label string, mut func(*status.Box)) { |
| + t.Helper() |
| + b := status.Box{GeneratedAt: time.Now(), Label: label, Metrics: &status.BoxMetrics{ |
| + Layout: &status.LayoutReport{Mode: "nested"}, Release: "v0.27.0", PrevRelease: "none", |
| + SeedsFloor: &status.SeedsFloorReport{Protocol: seeds.FleetFileSeedProtocol, MinRelease: "v0.27.0"}}} |
| + if mut != nil { |
| + mut(&b) |
| + } |
| + if err := status.WriteBox(context.Background(), release.NewPrefixStore(fx.rel, "fleets/"+seedFleet+"/"), b); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func fleetSnapshotOf(host, id string) string { return seeds.FleetSnapshotKey("bab", fromApp, host, id) } |
| + |
| +func (f fromFixture) hasKey(t *testing.T, key string) bool { |
| + t.Helper() |
| + _, _, err := f.fx.srv.cfg.Releases.Get(context.Background(), key) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + return err == nil |
| +} |
| + |
| +// requireNoFleetSnapshot: nothing under shop's fleet seeds prefix. |
| +func (f fromFixture) requireNoFleetSnapshot(t *testing.T) { |
| + t.Helper() |
| + if keys, err := f.fx.rel.List(context.Background(), seeds.FleetSnapshotsPrefix("bab", fromApp)); err != nil || len(keys) != 0 { |
| + t.Fatalf("fleet seeds = %v, %v; want none", keys, err) |
| + } |
| +} |
| + |
| +// fleetSeedRecord writes a fleet-placed record of shop on host whose file |
| +// seed is in state, with reason and held, and puts its fleet snapshot. It |
| +// answers the id. |
| +func (f fromFixture) fleetSeedRecord(t *testing.T, host, state, reason, held string, at time.Time) string { |
| + t.Helper() |
| + id := newSeedID(t) |
| + rec := provision.Record{Schema: 1, Host: host, Slug: strings.SplitN(host, ".", 2)[0], App: fromApp, Account: "bab", |
| + Channel: "stable", Region: "fleet/" + seedFleet, CreatedAt: time.Now().UTC(), |
| + Seed: &provision.SeedSource{ID: id, Kind: seeds.KindFile, State: state, Reason: reason, Held: held, |
| + SHA256: strings.Repeat("a", 64), Bytes: 4, By: "alice@keymail.dev", At: at}} |
| + if err := provision.CreateRecord(context.Background(), f.fx.rel, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.fx.rel.Put(context.Background(), fleetSnapshotOf(host, id), []byte("snap"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + return id |
| +} |
| + |
| +func (f fromFixture) rawRecord(t *testing.T, host string) []byte { |
| + t.Helper() |
| + raw, _, err := f.fx.rel.Get(context.Background(), provision.RecordKey("bab", fromApp, host)) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + return raw |
| +} |
| + |
| +func TestFileSeedBeginFleetWritesDeploymentKey(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + body, _ := sqliteBytes(t) |
| + begun := f.beginFile(t, fileHost, body) |
| + if begun.Region != "fleet/"+seedFleet || begun.FleetBox != "" { |
| + t.Fatalf("record placed %q labelled %q; want fleet/pi, unlabelled", begun.Region, begun.FleetBox) |
| + } |
| + id := begun.Seed.ID |
| + requireFileState(t, begun, id, seeds.StateReserving, "") |
| + rec := f.uploaded(t, fileHost, body) |
| + requireFileState(t, rec, id, seeds.StateReady, "") |
| + got, _, err := f.fx.rel.Get(context.Background(), seeds.FleetSnapshotKey("bab", fromApp, fileHost, id)) |
| + if err != nil || !bytes.Equal(got, body) { |
| + t.Fatalf("fleet snapshot = %d bytes, %v; want the upload", len(got), err) |
| + } |
| + f.requireNothingUploaded(t) // nothing in the data bucket |
| + f.requireClean(t) |
| +} |
| + |
| +// R2-2: one storage prerequisite. Begin and upload agree for every kind and |
| +// storage shape, and a fleet file seed needs nothing regional. |
| +func TestSeedStoragePrereqBeginMatchesUpload(t *testing.T) { |
| + f := newImportFixture(t) |
| + s := f.fx.srv |
| + data, rel := s.cfg.SeedData, s.cfg.Releases |
| + for _, c := range []struct { |
| + kind, placement string |
| + data, bucket bool |
| + want bool // refused |
| + }{ |
| + {seeds.KindImport, "", true, true, false}, |
| + {seeds.KindImport, "", false, true, true}, |
| + {seeds.KindImport, "", true, false, true}, |
| + {seeds.KindFile, "", true, true, false}, |
| + {seeds.KindFile, "", false, true, true}, |
| + {seeds.KindFile, "", true, false, true}, |
| + {seeds.KindFile, "fleet/pi", true, true, false}, |
| + {seeds.KindFile, "fleet/pi", false, false, false}, |
| + {seeds.KindImport, "fleet/pi", false, true, true}, |
| + } { |
| + s.cfg.SeedData, s.cfg.HibernateBucket = nil, "" |
| + if c.data { |
| + s.cfg.SeedData = data |
| + } |
| + if c.bucket { |
| + s.cfg.HibernateBucket = "data-test" |
| + } |
| + // Begin and the upload both ask seedStorageRefusal, and nothing |
| + // else asks about storage: the same question, the same answer. |
| + ref := s.seedStorageRefusal(c.kind, c.placement) |
| + if (ref != nil) != c.want { |
| + t.Errorf("%s on %q (data %v, bucket %v): refused %v, want %v", c.kind, c.placement, c.data, c.bucket, ref != nil, c.want) |
| + } |
| + if ref != nil && *ref != *seedNoDataRefusal() { |
| + t.Errorf("%s on %q: %+v, want the import's refusal", c.kind, c.placement, ref) |
| + } |
| + } |
| + s.cfg.Releases = nil |
| + if s.seedStorageRefusal(seeds.KindFile, "fleet/pi") == nil { |
| + t.Error("a fleet file seed with no deployment bucket was admitted") |
| + } |
| + s.cfg.Releases, s.cfg.SeedData, s.cfg.HibernateBucket = rel, data, "data-test" |
| + |
| + // End to end: a fleet file seed goes from begin through its PUT to |
| + // ready with no data bucket at all. |
| + g := newFleetFileFixture(t) |
| + g.fx.srv.cfg.SeedData, g.fx.srv.cfg.HibernateBucket = nil, "" |
| + body, _ := sqliteBytes(t) |
| + begun := g.beginFile(t, fileHost, body) |
| + requireFileState(t, g.uploaded(t, fileHost, body), begun.Seed.ID, seeds.StateReady, "") |
| + if !g.hasKey(t, fleetSnapshotOf(fileHost, begun.Seed.ID)) { |
| + t.Fatal("no fleet snapshot") |
| + } |
| +} |
| + |
| +// R3-1: a claim-enabled console admits no fleet file seed, at begin or PUT. |
| +func TestFileSeedFleetClaimConsoleRefuses(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + body, _ := sqliteBytes(t) |
| + begun := f.beginFile(t, fileHost, body) |
| + claim := seedClaimConsoleRefusal().Msg |
| + f.fx.srv.cfg.HostClaim = true |
| + if code, out := uploadImport(t, f, fileHost, body); code != http.StatusConflict || str(t, out, "error") != claim { |
| + t.Fatalf("PUT on a claim console = %d %v", code, out) |
| + } |
| + rec, _ := f.record(t, fileHost) |
| + requireFileState(t, rec, begun.Seed.ID, seeds.StateReserving, "") |
| + f.requireNoFleetSnapshot(t) |
| + // Asked first, before any fleet check: a fleet that is not ready at |
| + // all still gets the claim sentence. |
| + if ref := f.fx.srv.seedFleetReady(context.Background(), "nowhere"); ref == nil || ref.Msg != claim { |
| + t.Fatalf("seedFleetReady on a claim console = %+v", ref) |
| + } |
| + if code, out := f.create(t, fileSeedBody("other.shop.example.com", importSHA, 10)); code != http.StatusConflict || str(t, out, "error") != claim { |
| + t.Fatalf("begin on a claim console = %d %v", code, out) |
| + } |
| + f.requireNoRecord(t, "other.shop.example.com") |
| + f.requireNoFleetSnapshot(t) |
| +} |
| + |
| +func TestSeedFleetReadyNamesBoxes(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + ctx := context.Background() |
| + if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref != nil { |
| + t.Fatalf("a ready fleet: %+v", ref) |
| + } |
| + unconfirmed := fmt.Sprintf(fileSeedFleetUnconfirmedCopy, seedFleet) |
| + below := fmt.Sprintf(fileSeedFleetBelowFloorCopy, "pi-1", seedFleet) |
| + for _, c := range []struct { |
| + what string |
| + mut func(*status.Box) |
| + status int |
| + msg string |
| + }{ |
| + {"no seeds_floor", func(b *status.Box) { b.Metrics.SeedsFloor = nil }, http.StatusServiceUnavailable, unconfirmed}, |
| + {"no layout", func(b *status.Box) { b.Metrics.Layout = nil }, http.StatusServiceUnavailable, unconfirmed}, |
| + {"no metrics", func(b *status.Box) { b.Metrics = nil }, http.StatusServiceUnavailable, unconfirmed}, |
| + {"protocol 3", func(b *status.Box) { b.Metrics.SeedsFloor.Protocol = seeds.FileSeedProtocol }, http.StatusConflict, below}, |
| + {"another min_release", func(b *status.Box) { b.Metrics.SeedsFloor.MinRelease = "v0.26.0" }, http.StatusConflict, below}, |
| + {"carlos.prev not vouched", func(b *status.Box) { b.Metrics.PrevRelease = "v0.20.0" }, http.StatusConflict, below}, |
| + {"root floor refused", func(b *status.Box) { b.Metrics.SeedsFloor.FloorState = "refused" }, http.StatusConflict, below}, |
| + {"flat", func(b *status.Box) { b.Metrics.Layout.Mode = "flat" }, http.StatusConflict, fmt.Sprintf(fileSeedFleetLayoutCopy, "pi-1", seedFleet)}, |
| + {"layout unknown", func(b *status.Box) { b.Metrics.Layout.Mode = "" }, http.StatusConflict, fmt.Sprintf(fileSeedFleetLayoutCopy, "pi-1", seedFleet)}, |
| + } { |
| + fleetSeedBeat(t, f.fx, "pi-1", c.mut) |
| + if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref == nil || ref.Status != c.status || ref.Msg != c.msg { |
| + t.Errorf("%s: %+v, want %d %q", c.what, ref, c.status, c.msg) |
| + } |
| + } |
| + // carlos.prev vouched for the floor's release is fine. |
| + fleetSeedBeat(t, f.fx, "pi-1", func(b *status.Box) { b.Metrics.PrevRelease, b.Metrics.SeedsFloor.PrevAllowedFor = "v0.20.0", "v0.27.0" }) |
| + if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref != nil { |
| + t.Fatalf("a vouched carlos.prev: %+v", ref) |
| + } |
| + // A floor below the fleet protocol is FS-25. |
| + fleetSeedBeat(t, f.fx, "pi-1", nil) |
| + _, etag, err := f.fx.rel.Get(ctx, seeds.FloorKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.fx.rel.Put(ctx, seeds.FloorKey, []byte(`{"min":3,"min_release":"v0.27.0"}`), etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref == nil || ref.Status != http.StatusConflict || ref.Msg != fileSeedFloorCopy { |
| + t.Fatalf("a floor at the region file protocol: %+v", ref) |
| + } |
| +} |
| + |
| +func TestSeedFleetReadyStaleHeartbeat(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + fleetSeedBeat(t, f.fx, "pi-1", func(b *status.Box) { b.GeneratedAt = time.Now().Add(-time.Hour) }) |
| + if ref := f.fx.srv.seedFleetReady(context.Background(), seedFleet); ref == nil || ref.Status != http.StatusServiceUnavailable || |
| + ref.Msg != fmt.Sprintf(fileSeedFleetUnconfirmedCopy, seedFleet) { |
| + t.Fatalf("a stale heartbeat: %+v", ref) |
| + } |
| +} |
| + |
| +func TestSeedFleetReadyRefusesTwoActiveBoxes(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + reg, _ := openRegistry(f.fx.regPath) |
| + if err := reg.AddFleetBox(registry.FleetBox{Fleet: seedFleet, Label: "pi-2", TokenHash: strings.Repeat("b", 64)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + fleetSeedBeat(t, f.fx, "pi-2", nil) |
| + ctx := context.Background() |
| + if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref == nil || ref.Status != http.StatusConflict || ref.Msg != fmt.Sprintf(fileSeedFleetBoxesCopy, seedFleet) { |
| + t.Fatalf("two active boxes: %+v", ref) |
| + } |
| + // A detached box does not count; no active box at all is FS-22. |
| + if err := reg.SetFleetBoxStatus(seedFleet, "pi-2", "detached"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref != nil { |
| + t.Fatalf("one active box and one detached: %+v", ref) |
| + } |
| + if err := reg.SetFleetBoxStatus(seedFleet, "pi-1", "detached"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ref := f.fx.srv.seedFleetReady(ctx, seedFleet); ref == nil || ref.Status != http.StatusServiceUnavailable { |
| + t.Fatalf("no active box: %+v", ref) |
| + } |
| + // And the begin refuses before writing anything. |
| + if err := reg.SetFleetBoxStatus(seedFleet, "pi-1", "active"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.SetFleetBoxStatus(seedFleet, "pi-2", "active"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if code, out := f.create(t, fileSeedBody(fileHost, importSHA, 10)); code != http.StatusConflict || str(t, out, "error") != fmt.Sprintf(fileSeedFleetBoxesCopy, seedFleet) { |
| + t.Fatalf("begin on a two-box fleet = %d %v", code, out) |
| + } |
| + f.requireNoRecord(t, fileHost) |
| +} |
| + |
| +func TestSeedFleetReadyRefusesClaimControl(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + fleetSeedBeat(t, f.fx, "pi-1", func(b *status.Box) { b.Metrics.HostClaimEnabled = true }) |
| + if ref := f.fx.srv.seedFleetReady(context.Background(), seedFleet); ref == nil || ref.Status != http.StatusConflict || |
| + ref.Msg != fmt.Sprintf(fileSeedFleetClaimCopy, "pi-1", seedFleet) { |
| + t.Fatalf("a claim-control box: %+v", ref) |
| + } |
| +} |
| + |
| +// Decision D13: a flat fleet box takes no file seed. (The plan's |
| +// TestSeedFleetReadyAdmitsFlat predates D13; this is its replacement.) |
| +func TestSeedFleetReadyRefusesFlat(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + fleetSeedBeat(t, f.fx, "pi-1", func(b *status.Box) { b.Metrics.Layout.Mode = "flat" }) |
| + if code, out := f.create(t, fileSeedBody(fileHost, importSHA, 10)); code != http.StatusConflict || |
| + str(t, out, "error") != fmt.Sprintf(fileSeedFleetLayoutCopy, "pi-1", seedFleet) { |
| + t.Fatalf("begin on a flat box = %d %v", code, out) |
| + } |
| + f.requireNoRecord(t, fileHost) |
| +} |
| + |
| +// D9: a delete before placement aborts; then, while the record holds the |
| +// hostname, every delete is refused. |
| +func TestDeleteFleetFileSeedBeforePlacementAborts(t *testing.T) { |
| + for _, ready := range []bool{false, true} { |
| + f := newFleetFileFixture(t) |
| + body, _ := sqliteBytes(t) |
| + begun := f.beginFile(t, fileHost, body) |
| + if ready { |
| + f.uploaded(t, fileHost, body) |
| + } |
| + code, out := deleteInstance(t, f, fileHost) |
| + if code != http.StatusAccepted || out["state"] != "aborting" || out["message"] != fmt.Sprintf(fileSeedDeletingCopy, fileHost) { |
| + t.Fatalf("ready %v: delete = %d %v, want 202 FS-13", ready, code, out) |
| + } |
| + rec, err := f.record(t, fileHost) |
| + if err != nil { |
| + t.Fatalf("ready %v: the record went: %v", ready, err) |
| + } |
| + requireFileState(t, rec, begun.Seed.ID, seeds.StateAborted, "") |
| + before := f.rawRecord(t, fileHost) |
| + if code, out := deleteInstance(t, f, fileHost); code != http.StatusConflict || str(t, out, "error") != fmt.Sprintf(fileSeedHeldCopy, fileHost) { |
| + t.Fatalf("ready %v: second delete = %d %v, want 409 FS-33", ready, code, out) |
| + } |
| + if !bytes.Equal(before, f.rawRecord(t, fileHost)) { |
| + t.Fatalf("ready %v: the second delete changed the record", ready) |
| + } |
| + } |
| +} |
| + |
| +func TestDeleteHeldFleetFileSeedRefuses(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + held := func(where string) string { |
| + return fmt.Sprintf(fileSeedHeldInStorageCopy, fileHost, where) |
| + } |
| + replica := fmt.Sprintf(fileSeedHeldReplicaCopy, fileHost) |
| + staging := fmt.Sprintf(fileSeedHeldStagingCopy, fileHost) |
| + for _, c := range []struct { |
| + what, reason, held, want string |
| + }{ |
| + {"no reason", "", "", fmt.Sprintf(fileSeedHeldCopy, fileHost)}, |
| + {"FS-27", fileSeedBoxMismatchCopy, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)}, |
| + {"FS-28", fileSeedBoxIntegrityCopy, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)}, |
| + {"FS-29", fileSeedCopyExistsCopy, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)}, |
| + {"FS-30 replica", fileSeedCopyInStorageCopy, provision.SeedHeldReplica, held(replica)}, |
| + {"FS-30 staging", fileSeedCopyInStorageCopy, provision.SeedHeldStaging, held(staging)}, |
| + {"FS-30 both", fileSeedCopyInStorageCopy, provision.SeedHeldBoth, held(fmt.Sprintf(fileSeedHeldBothCopy, replica, staging))}, |
| + {"FS-30 with no held", fileSeedCopyInStorageCopy, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)}, |
| + {"an upload failure", importNotADB, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)}, |
| + {"FS-17", fileSeedMismatchCopy, "", fmt.Sprintf(fileSeedHeldCopy, fileHost)}, |
| + } { |
| + f.fleetSeedRecord(t, fileHost, seeds.StateAborted, c.reason, c.held, time.Now()) |
| + before := f.rawRecord(t, fileHost) |
| + if code, out := deleteInstance(t, f, fileHost); code != http.StatusConflict || str(t, out, "error") != c.want { |
| + t.Errorf("%s: delete = %d %v, want 409 %q", c.what, code, out, c.want) |
| + } |
| + if !bytes.Equal(before, f.rawRecord(t, fileHost)) { |
| + t.Errorf("%s: the record changed", c.what) |
| + } |
| + if err := f.fx.rel.Delete(context.Background(), provision.RecordKey("bab", fromApp, fileHost)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // The examples' wording, end to end, for the reviewer's eye. |
| + if got := held(replica); got != "push.shop.example.com keeps its hostname while a copy of its data is still in the fleet’s storage, under push.shop.example.com/ (after the box’s CARLOS_HIBERNATE_PREFIX, if set). Remove everything there, and the hostname is free again after the box’s next pass." { |
| + t.Fatalf("FS-34 with FS-36 = %q", got) |
| + } |
| +} |
| + |
| +// Rolled back (the door's word, after the box's proof) the delete finishes |
| +// it; placed, it is the ordinary delete. |
| +func TestDeleteFleetFileSeedRolledBackFinishesPlacedIsOrdinary(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + f.fx.srv.cfg.SeedData = nil |
| + id := f.fleetSeedRecord(t, fileHost, seeds.StateRolledBack, "", "", time.Now()) |
| + if code, out := deleteInstance(t, f, fileHost); code != http.StatusOK || out["result"] != "deleted" { |
| + t.Fatalf("rolled back: delete = %d %v", code, out) |
| + } |
| + f.requireNoRecord(t, fileHost) |
| + if f.hasKey(t, fleetSnapshotOf(fileHost, id)) { |
| + t.Fatal("the finish left the fleet snapshot") |
| + } |
| + f.fleetSeedRecord(t, "placed.shop.example.com", seeds.StatePlaced, "", "", time.Now()) |
| + if code, out := deleteInstance(t, f, "placed.shop.example.com"); code != http.StatusOK || out["result"] != "deleted" { |
| + t.Fatalf("placed: delete = %d %v", code, out) |
| + } |
| + f.requireNoRecord(t, "placed.shop.example.com") |
| +} |
| + |
| +func TestDeleteRegionFileSeedIsOrdinary(t *testing.T) { |
| + f := newFileSeedFixture(t) |
| + body, _ := sqliteBytes(t) |
| + f.beginFile(t, fileHost, body) |
| + f.uploaded(t, fileHost, body) |
| + if code, out := deleteInstance(t, f, fileHost); code != http.StatusOK || out["result"] != "deleted" { |
| + t.Fatalf("delete = %d %v, want the ordinary 200", code, out) |
| + } |
| + f.requireNoRecord(t, fileHost) |
| +} |
| + |
| +func TestFinishFleetFileSeedUsesDeploymentKey(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + f.fx.srv.cfg.SeedData, f.fx.srv.cfg.HibernateBucket = nil, "" |
| + id := f.fleetSeedRecord(t, fileHost, seeds.StateRolledBack, "", "", time.Now()) |
| + if err := f.fx.srv.finishSeed(context.Background(), "bab", fromApp, fileHost, id); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.requireNoRecord(t, fileHost) |
| + if f.hasKey(t, fleetSnapshotOf(fileHost, id)) { |
| + t.Fatal("the fleet snapshot survived the finish") |
| + } |
| +} |
| + |
| +// ---- the sweep ---------------------------------------------------------- |
| + |
| +// modReleases gives the fixture's deployment store last-modified listings: |
| +// every key is as old as mods says, or new. |
| +type modReleases struct { |
| + release.Store |
| + mu sync.Mutex |
| + mods map[string]time.Time |
| +} |
| + |
| +func (m *modReleases) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) { |
| + keys, err := m.Store.List(ctx, prefix) |
| + if err != nil { |
| + return nil, err |
| + } |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + out := make([]release.KeyMod, 0, len(keys)) |
| + for _, k := range keys { |
| + mod, ok := m.mods[k] |
| + if !ok { |
| + mod = time.Now() |
| + } |
| + out = append(out, release.KeyMod{Key: k, Mod: mod}) |
| + } |
| + return out, nil |
| +} |
| + |
| +// sweepable arms the fixture's deployment store for the sweep's fleet half. |
| +func (f fromFixture) sweepable() { |
| + f.fx.srv.cfg.Releases = &modReleases{Store: f.fx.srv.cfg.Releases, mods: map[string]time.Time{}} |
| +} |
| + |
| +func (f fromFixture) state(t *testing.T, host string) string { |
| + t.Helper() |
| + rec, err := f.record(t, host) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return "gone" |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return rec.Seed.State |
| +} |
| + |
| +// R3-3: the snapshot goes on abandonment, the record stays. |
| +func TestSeedsPassDeletesAbortedFleetFileSnapshotKeepsRecord(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + f.sweepable() |
| + id := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, fileSeedCopyInStorageCopy, provision.SeedHeldReplica, time.Now()) |
| + f.fx.srv.seedsPass(context.Background(), time.Now()) |
| + if f.hasKey(t, fleetSnapshotOf(fileHost, id)) { |
| + t.Fatal("an aborted fleet file seed's snapshot survived the sweep") |
| + } |
| + if got := f.state(t, fileHost); got != seeds.StateAborted { |
| + t.Fatalf("record = %s, want it kept aborted", got) |
| + } |
| +} |
| + |
| +// R1-4: a trashed app's snapshots are swept too. |
| +func TestSeedsPassDeletesAbortedFleetFileSnapshotInTrashedApp(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + f.sweepable() |
| + id := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, "", "", time.Now()) |
| + if err := release.TrashApp(context.Background(), f.fx.rel, "bab", fromApp, "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.fx.st.TrashAppRow(OpsAccountID, fromApp, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.fx.srv.seedsPass(context.Background(), time.Now()) |
| + if f.hasKey(t, fleetSnapshotOf(fileHost, id)) { |
| + t.Fatal("a trashed app's aborted fleet snapshot survived the sweep") |
| + } |
| + if got := f.state(t, fileHost); got != seeds.StateAborted { |
| + t.Fatalf("record = %s, want it kept aborted", got) |
| + } |
| +} |
| + |
| +func TestSeedsPassAbortsStuckFleetFileReservation(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + f.sweepable() |
| + now := time.Now() |
| + stuck := f.fleetSeedRecord(t, fileHost, seeds.StateReserving, "", "", now.Add(-seedFileReserveTTL-time.Minute)) |
| + live := f.fleetSeedRecord(t, "live.shop.example.com", seeds.StateReserving, "", "", now.Add(-time.Minute)) |
| + f.fx.srv.seedsPass(context.Background(), now) |
| + if got := f.state(t, fileHost); got != seeds.StateAborted || f.hasKey(t, fleetSnapshotOf(fileHost, stuck)) { |
| + t.Fatalf("a stuck fleet reservation = %s, snapshot kept %v", got, f.hasKey(t, fleetSnapshotOf(fileHost, stuck))) |
| + } |
| + if got := f.state(t, "live.shop.example.com"); got != seeds.StateReserving || !f.hasKey(t, fleetSnapshotOf("live.shop.example.com", live)) { |
| + t.Fatalf("a live fleet reservation = %s", got) |
| + } |
| + // The sweep never rolls a fleet file seed back: only the door does. |
| + f.fx.srv.seedsPass(context.Background(), now.Add(time.Hour)) |
| + if got := f.state(t, fileHost); got != seeds.StateAborted { |
| + t.Fatalf("after a second pass = %s, want aborted", got) |
| + } |
| +} |
| + |
| +func TestSeedsPassDeletesOrphanFleetSnapshotAfterAnHour(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + f.sweepable() |
| + id := newSeedID(t) |
| + key := fleetSnapshotOf(fileHost, id) |
| + if _, err := f.fx.rel.Put(context.Background(), key, []byte("snap"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now() |
| + f.fx.srv.seedsPass(context.Background(), now) |
| + if !f.hasKey(t, key) { |
| + t.Fatal("a fresh orphan was deleted") |
| + } |
| + f.fx.srv.seedsPass(context.Background(), now.Add(2*time.Hour)) |
| + if f.hasKey(t, key) { |
| + t.Fatal("an orphan past the hour survived") |
| + } |
| +} |
| + |
| +func TestSeedsPassFleetHalfRunsWithoutSeedData(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + f.sweepable() |
| + f.fx.srv.cfg.SeedData = nil |
| + id := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, "", "", time.Now()) |
| + f.fx.srv.seedsPass(context.Background(), time.Now()) |
| + if f.hasKey(t, fleetSnapshotOf(fileHost, id)) { |
| + t.Fatal("the fleet half did not run without a data bucket") |
| + } |
| +} |
| + |
| +// An aborted fleet file seed whose fleet has no active box: nothing proves |
| +// it gone, so nothing finishes it and the hostname stays held. |
| +func TestFleetFileSeedNoOwnerNeverFinished(t *testing.T) { |
| + f := newFleetFileFixture(t) |
| + f.sweepable() |
| + reg, _ := openRegistry(f.fx.regPath) |
| + if err := reg.SetFleetBoxStatus(seedFleet, "pi-1", "detached"); err != nil { |
| + t.Fatal(err) |
| + } |
| + id := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, "", "", time.Now()) |
| + now := time.Now() |
| + for i := 0; i < 2; i++ { |
| + f.fx.srv.seedsPass(context.Background(), now.Add(time.Duration(i)*2*time.Hour)) |
| + } |
| + if err := f.fx.srv.finishSeed(context.Background(), "bab", fromApp, fileHost, id); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := f.state(t, fileHost); got != seeds.StateAborted { |
| + t.Fatalf("record = %s, want it kept aborted", got) |
| + } |
| + if code, _ := deleteInstance(t, f, fileHost); code != http.StatusConflict { |
| + t.Fatalf("delete = %d, want 409", code) |
| + } |
| +} |
diff --git a/internal/console/seedfinish.go b/internal/console/seedfinish.go| index 24378a9d4..3805273d3 100644 |
| --- a/internal/console/seedfinish.go |
| +++ b/internal/console/seedfinish.go |
| @@ -33,7 +33,9 @@ import ( |
| // when no other instance names that environment (M10), read strictly: |
| // a record of the app that will not decode counts as one (Plan 8 M7). |
| // A store with another seed, or none, is never touched. |
| -// 2. The seed's snapshot, seeds/<host>/<id>/snapshot.db. |
| +// 2. The seed's snapshot, seeds/<host>/<id>/snapshot.db; for a fleet file |
| +// seed, apps/<sqid>/<app>/seeds/<host>/<id>/snapshot.db in the |
| +// deployment bucket (seedSnapshotTarget), which needs no data bucket. |
| // 3. For a --from seed, every key under the host's replica prefix in the |
| // data bucket (M11). It is this seed's: the record is create-only and |
| // the create door's leftover-replica rail refused the host if anything |
| @@ -109,21 +111,27 @@ func (s *Server) finishSeedOnce(ctx context.Context, sqid, app, host, seedID str |
| } |
| ctx = withDemoClaimOperation(ctx, op.ID) |
| } |
| + // A fleet file seed's snapshot is in the deployment bucket, and its |
| + // replica is the fleet's own, which this console never deletes: its |
| + // box proved it gone before it reported rolledback (design §3.6). |
| + onFleet := seedOnFleet(rec) |
| + snapshots, snapshot := s.seedSnapshotTarget(rec) |
| // Checked before anything is destroyed: without it the store would be |
| // torn down and every later finish fail with the record holding the |
| // host. |
| - if s.cfg.SeedData == nil { |
| + if snapshots == nil { |
| return fmt.Errorf("finish seed %s of %s: this console has no data bucket to delete its snapshot from", seedID, host) |
| } |
| if err := s.finishSeedStore(ctx, sqid, app, host, seedID, rec.Environment); err != nil { |
| return err |
| } |
| - if err := s.cfg.SeedData.Delete(ctx, seeds.SnapshotKey(host, seedID)); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + if err := snapshots.Delete(ctx, snapshot); err != nil && !errors.Is(err, os.ErrNotExist) { |
| return fmt.Errorf("delete the snapshot of seed %s of %s: %w", seedID, host, err) |
| } |
| - // A file seed places as a --from seed does, so its rollback may leave a |
| - // replica too. |
| - if rec.Seed.Kind == seeds.KindReplica || rec.Seed.Kind == seeds.KindFile || rec.Seed.DemoClaim() { |
| + // A region file seed places as a --from seed does, so its rollback may |
| + // leave a replica too. A fleet one's replica is never this console's |
| + // (deleteSeedReplica would refuse it anyway, leftoverCheckApplies). |
| + if !onFleet && (rec.Seed.Kind == seeds.KindReplica || rec.Seed.Kind == seeds.KindFile || rec.Seed.DemoClaim()) { |
| var gone bool |
| if etag, gone, err = s.deleteSeedReplica(ctx, rec, etag); err != nil { |
| return err |
diff --git a/internal/console/seedfloor.go b/internal/console/seedfloor.go| index d93671e46..80cfbcb15 100644 |
| --- a/internal/console/seedfloor.go |
| +++ b/internal/console/seedfloor.go |
| @@ -54,21 +54,9 @@ func (s *Server) seedRegionReadyForEdges(ctx context.Context, region string, one |
| if s.cfg.HostClaim { |
| return seedClaimConsoleRefusal() |
| } |
| - floor, err := seeds.ReadFloor(ctx, s.cfg.Releases) |
| - if err == nil && floor != nil { |
| - // A floor PublishFloor would never write (a hand-edited or |
| - // truncated object) is as good as unreadable: an empty min_release |
| - // would match every box that could not read its own floor. |
| - if ok, perr := seeds.ReleaseAtOrAbove(floor.MinRelease, floor.MinRelease); !ok || perr != nil { |
| - err = fmt.Errorf("published floor has no usable min_release %q", floor.MinRelease) |
| - } |
| - } |
| - if err != nil { |
| - log.Printf("console: seeds floor: %v", err) |
| - return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: "could not read the seeds floor. Try again."} |
| - } |
| - if floor == nil { |
| - return &doorRefusal{Status: http.StatusConflict, Msg: "This deployment has no seeds floor yet. An operator publishes it with carlos system seeds-floor publish."} |
| + floor, ref := s.publishedSeedsFloor(ctx) |
| + if ref != nil { |
| + return ref |
| } |
| minProtocol := max(seeds.RequiredProtocol, floor.Min) |
| if rule != nil { |
| @@ -175,6 +163,28 @@ func (s *Server) seedRegionReadyForEdges(ctx context.Context, region string, one |
| return nil |
| } |
| +// publishedSeedsFloor reads the published seeds floor for a seed door's |
| +// readiness check: the floor, or the refusal when it is absent or not |
| +// usable. A floor PublishFloor would never write (a hand-edited or |
| +// truncated object) is as good as unreadable: an empty min_release would |
| +// match every box that could not read its own floor. |
| +func (s *Server) publishedSeedsFloor(ctx context.Context) (*seeds.Floor, *doorRefusal) { |
| + floor, err := seeds.ReadFloor(ctx, s.cfg.Releases) |
| + if err == nil && floor != nil { |
| + if ok, perr := seeds.ReleaseAtOrAbove(floor.MinRelease, floor.MinRelease); !ok || perr != nil { |
| + err = fmt.Errorf("published floor has no usable min_release %q", floor.MinRelease) |
| + } |
| + } |
| + if err != nil { |
| + log.Printf("console: seeds floor: %v", err) |
| + return nil, &doorRefusal{Status: http.StatusServiceUnavailable, Msg: "could not read the seeds floor. Try again."} |
| + } |
| + if floor == nil { |
| + return nil, &doorRefusal{Status: http.StatusConflict, Msg: "This deployment has no seeds floor yet. An operator publishes it with carlos system seeds-floor publish."} |
| + } |
| + return floor, nil |
| +} |
| + |
| // seedClaimConsoleRefusal is the seed doors' answer on a console with claim |
| // control on. The --from door also gives it for a source whose claim could |
| // not be read, which seedRegionReady's own check makes unreachable today. |
diff --git a/internal/console/seedpurgehold_test.go b/internal/console/seedpurgehold_test.go| new file mode 100644 |
| index 000000000..9aba358f3 |
| --- /dev/null |
| +++ b/internal/console/seedpurgehold_test.go |
| @@ -0,0 +1,173 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +// Every retirement entrance waits for a fleet file seed's box (plan R1-1): |
| +// the Trash page's purge (lifetimes on and off), the expiry pass's early |
| +// purge and the trash sweep. The fleet's box is offline throughout, and its |
| +// replica objects (in the fleet's own bucket, which the console never sees) |
| +// are left: only the box's rolledback report frees the app. |
| + |
| +const fleetHeldHost = "held.shop.example.com" |
| + |
| +// purgeHoldWorld is shop (bab) with lifetimes on or off, a fleet-placed |
| +// file seed at fleetHeldHost in state, and shop trashed at trashedAt. |
| +func purgeHoldWorld(t *testing.T, on bool, state string, trashedAt time.Time) lifetimesFx { |
| + t.Helper() |
| + var l lifetimesFx |
| + if on { |
| + l = newLtOn(t).lifetimesFx |
| + } else { |
| + l = newLifetimesFx(t) |
| + } |
| + rec := provision.Record{Schema: 1, Host: fleetHeldHost, Slug: "held", App: ltApp, Account: "bab", Channel: "stable", |
| + Region: "fleet/pi", CreatedAt: time.Now().UTC(), |
| + Seed: &provision.SeedSource{ID: newSeedID(t), Kind: seeds.KindFile, State: state, Reason: fileSeedCopyInStorageCopy, |
| + Held: provision.SeedHeldReplica, SHA256: strings.Repeat("a", 64), Bytes: 4, By: "alice@keymail.dev", At: time.Now().UTC()}} |
| + if state != seeds.StateAborted { |
| + rec.Seed.Reason, rec.Seed.Held = "", "" |
| + } |
| + if err := provision.CreateRecord(context.Background(), l.fx.rel, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.TrashApp(context.Background(), l.fx.rel, "bab", ltApp, "paul@keymail.dev", trashedAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := l.fx.st.TrashAppRow(OpsAccountID, ltApp, trashedAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + return l |
| +} |
| + |
| +func heldRecordStands(t *testing.T, l lifetimesFx) bool { |
| + t.Helper() |
| + _, _, err := l.fx.rel.Get(context.Background(), provision.RecordKey("bab", ltApp, fleetHeldHost)) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + return err == nil |
| +} |
| + |
| +func shopMarkerStands(t *testing.T, l lifetimesFx) bool { |
| + t.Helper() |
| + tomb, err := release.ReadAppTombstone(context.Background(), l.fx.rel, "bab", ltApp) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return tomb != nil |
| +} |
| + |
| +// browserPurge runs the Trash page's "Delete now" for shop through its |
| +// passkey step-up, and answers the flash it set ("kind|message"). |
| +func browserPurge(t *testing.T, l lifetimesFx, code string) string { |
| + t.Helper() |
| + c := newBrowser(t) |
| + signUp(t, l.fx, c, code) |
| + csrf := sessionToken(t, l.fx, c) |
| + status, loc, _ := postForm(t, c, l.fx.u("/trash/delete"), urlValues("csrf", csrf, "app", ltApp, "confirm", ltApp)) |
| + if status != http.StatusSeeOther { |
| + t.Fatalf("purge = %d", status) |
| + } |
| + if status, _, body := completeStepUp(t, l.fx, c, loc); status != http.StatusSeeOther { |
| + t.Fatalf("resumed purge = %d %s", status, body) |
| + } |
| + u, _ := url.Parse(l.fx.ts.URL) |
| + for _, ck := range c.Jar.Cookies(u) { |
| + if ck.Name == flashCookie { |
| + v, err := url.QueryUnescape(ck.Value) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return v |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +func TestPurgeAppRefusesHeldFleetFileSeed(t *testing.T) { |
| + for _, on := range []bool{false, true} { |
| + name := map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on] |
| + t.Run(name, func(t *testing.T) { |
| + for _, state := range []string{seeds.StateReserving, seeds.StateReady, seeds.StateAborted} { |
| + l := purgeHoldWorld(t, on, state, time.Now()) |
| + want := "err|shop can’t be deleted permanently until its fleet box has cleaned up " + fleetHeldHost + "." |
| + if got := browserPurge(t, l, "code-held-"+state); got != want { |
| + t.Fatalf("%s: flash = %q, want %q", state, got, want) |
| + } |
| + if !heldRecordStands(t, l) || !shopMarkerStands(t, l) { |
| + t.Fatalf("%s: the purge removed something: record %v, marker %v", state, heldRecordStands(t, l), shopMarkerStands(t, l)) |
| + } |
| + if life, _ := l.fx.st.AppLife(OpsAccountID, ltApp); life == nil { |
| + t.Fatalf("%s: the app row went", state) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPurgeAppProceedsAfterRolledBack(t *testing.T) { |
| + for _, on := range []bool{false, true} { |
| + name := map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on] |
| + t.Run(name, func(t *testing.T) { |
| + for _, state := range []string{seeds.StateRolledBack, seeds.StatePlaced} { |
| + l := purgeHoldWorld(t, on, state, time.Now()) |
| + if got := browserPurge(t, l, "code-proceeds-"+state); !strings.HasPrefix(got, "ok|") { |
| + t.Fatalf("%s: flash = %q, want the purge done", state, got) |
| + } |
| + if heldRecordStands(t, l) || shopMarkerStands(t, l) { |
| + t.Fatalf("%s: the purge left the record (%v) or the marker (%v)", state, heldRecordStands(t, l), shopMarkerStands(t, l)) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestTrashExpirySkipsAppWithHeldFleetFileSeed(t *testing.T) { |
| + ctx := context.Background() |
| + for _, on := range []bool{false, true} { |
| + name := map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on] |
| + t.Run(name+", the expiry pass's early purge", func(t *testing.T) { |
| + l := purgeHoldWorld(t, on, seeds.StateAborted, time.Now()) |
| + tomb, _ := release.ReadAppTombstone(ctx, l.fx.rel, "bab", ltApp) |
| + if _, err := l.fx.st.db.Exec(`UPDATE apps SET purge_for = ?, purge_after = ? WHERE app = ?`, tomb.DeletedAt.Unix(), tomb.DeletedAt.Unix()+1, ltApp); err != nil { |
| + t.Fatal(err) |
| + } |
| + now := tomb.DeletedAt.Add(time.Hour) |
| + if !l.fx.srv.lifetimesIteration(ctx, "expiry pass", true, false, func(ctx context.Context) { l.fx.srv.expiryPass(ctx, now) }) { |
| + t.Fatal("the expiry pass did not run") |
| + } |
| + if !heldRecordStands(t, l) || !shopMarkerStands(t, l) { |
| + t.Fatal("the early purge removed something") |
| + } |
| + if life, _ := l.fx.st.AppLife(OpsAccountID, ltApp); life == nil { |
| + t.Fatal("the early purge released the name") |
| + } |
| + }) |
| + t.Run(name+", the trash sweep", func(t *testing.T) { |
| + old := time.Now().Add(-31 * 24 * time.Hour) |
| + l := purgeHoldWorld(t, on, seeds.StateAborted, old) |
| + if err := l.fx.st.PurgeAppRow(OpsAccountID, ltApp); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !l.fx.srv.lifetimesIteration(ctx, "expiry pass", true, false, func(ctx context.Context) { l.fx.srv.expiryPass(ctx, time.Now()) }) { |
| + t.Fatal("the expiry pass did not run") |
| + } |
| + if !heldRecordStands(t, l) || !shopMarkerStands(t, l) { |
| + t.Fatal("the trash sweep removed something") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/seedsweep.go b/internal/console/seedsweep.go| index 0ee41ddbd..da9ec573d 100644 |
| --- a/internal/console/seedsweep.go |
| +++ b/internal/console/seedsweep.go |
| @@ -69,12 +69,18 @@ func (s *Server) StartSeedsPass(ctx context.Context) { |
| log.Printf("console: seeds pass: off on a host-claim console, where every seed door refuses") |
| return |
| } |
| - if s.cfg.Releases == nil || s.cfg.SeedData == nil { |
| + // The region half needs the data bucket; the fleet half (fleet file |
| + // seeds, slice 3) needs only the deployment bucket, so a console with |
| + // no data bucket still sweeps its fleets' seeds. |
| + if s.cfg.Releases == nil { |
| return |
| } |
| - if _, ok := s.cfg.SeedData.(release.ModLister); !ok { |
| + if _, ok := s.cfg.SeedData.(release.ModLister); s.cfg.SeedData != nil && !ok { |
| log.Printf("console: seeds pass: the data bucket cannot list last-modified times, so this sweep deletes no unreferenced snapshot") |
| } |
| + if _, ok := s.cfg.Releases.(release.ModLister); !ok { |
| + log.Printf("console: seeds pass: the deployment bucket cannot list last-modified times, so this sweep deletes no fleet seed's snapshot") |
| + } |
| lifetimesWorker(ctx, seedsPassInterval, s.seedsIteration) |
| } |
| @@ -115,10 +121,12 @@ func seedStale(seed *provision.SeedSource, now time.Time) bool { |
| // seedsPass is one sweep. In order: |
| // |
| -// 1. The snapshots under seeds/, with their last-modified times. Listed |
| -// first: every door writes its record before its snapshot (spec §4 |
| -// step 7, §5.1), so a snapshot in this listing whose seed is live has |
| -// its record in the next one. A seed begun after this listing has no |
| +// 1. The snapshots under seeds/ in the data bucket, and every fleet file |
| +// seed's under apps/<sqid>/<app>/seeds/ in the deployment bucket |
| +// (fleetSeedSnapshots), with their last-modified times. Listed first: |
| +// every door writes its record before its snapshot (spec §4 step 7, |
| +// §5.1), so a snapshot in this listing whose seed is live has its |
| +// record in the next one. A seed begun after this listing has no |
| // snapshot in it, so nothing below can reach it. |
| // 2. Every record, strictly: from the bucket, or, with the record view |
| // armed and step 1 empty (so nothing can be deleted), from the view. |
| @@ -134,8 +142,12 @@ func seedStale(seed *provision.SeedSource, now time.Time) bool { |
| // seed's own once its CAS has landed. |
| // 6. Each rolled-back seed finished (finishSeed re-reads its record). |
| // |
| -// Every delete names one exact seeds/<host>/<id>/snapshot.db, so it never |
| -// reaches another seed's. |
| +// Every delete names one exact seeds/<host>/<id>/snapshot.db, or one |
| +// fleet seed's apps/<sqid>/<app>/seeds/<host>/<id>/snapshot.db, so it never |
| +// reaches another seed's. A fleet file seed is never rolled back here: |
| +// step 4 aborts a stuck one and step 5 deletes its snapshot (R3-3), and the |
| +// record stays, holding the hostname, until its box reports rolledback to |
| +// the fleet seeds door. |
| // |
| // The pass is bounded by seedsPassTimeout. Cutting it anywhere is safe and |
| // the next pass resumes: a listing cut short is an error, so nothing is |
| @@ -145,7 +157,7 @@ func seedStale(seed *provision.SeedSource, now time.Time) bool { |
| // a finish cut short leaves its record rolled-back, and every finish step |
| // is idempotent. |
| func (s *Server) seedsPass(ctx context.Context, now time.Time) { |
| - if s.cfg.HostClaim || s.cfg.Releases == nil || s.cfg.SeedData == nil { |
| + if s.cfg.HostClaim || s.cfg.Releases == nil { |
| return |
| } |
| ctx, cancel := context.WithTimeout(ctx, seedsPassTimeout) |
| @@ -155,16 +167,27 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) { |
| log.Printf("console: seeds pass: cut short: %v (the next pass resumes)", ctx.Err()) |
| } |
| }() |
| - var snaps []release.KeyMod |
| - ml, walk := s.cfg.SeedData.(release.ModLister) |
| - if walk { |
| - var err error |
| - if snaps, err = ml.ListMod(ctx, seeds.Prefix); err != nil { |
| + var snaps []seedSnapshot |
| + if ml, walk := s.cfg.SeedData.(release.ModLister); s.cfg.SeedData != nil && walk { |
| + listed, err := ml.ListMod(ctx, seeds.Prefix) |
| + if err != nil { |
| log.Printf("console: seeds pass: list snapshots: %v (nothing swept this pass)", err) |
| jobFailed(ctx, fmt.Errorf("seeds pass: list snapshots: %w (nothing swept this pass)", err)) |
| return |
| } |
| + for _, o := range listed { |
| + if host, id, ok := seeds.ParseSnapshotKey(o.Key); ok { |
| + snaps = append(snaps, seedSnapshot{store: s.cfg.SeedData, key: o.Key, mod: o.Mod, host: host, id: id}) |
| + } |
| + } |
| + } |
| + fleet, err := s.fleetSeedSnapshots(ctx) |
| + if err != nil { |
| + log.Printf("console: seeds pass: list fleet seed snapshots: %v (nothing swept this pass)", err) |
| + jobFailed(ctx, fmt.Errorf("seeds pass: list fleet seed snapshots: %w (nothing swept this pass)", err)) |
| + return |
| } |
| + snaps = append(snaps, fleet...) |
| if seedsPassBetweenListings != nil { |
| seedsPassBetweenListings() |
| } |
| @@ -207,23 +230,23 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) { |
| return true |
| } |
| - // Step 3: the decisions. |
| - var condemned []string |
| - waiting := map[[2]string]string{} // host, id -> key: deleted only if this pass abandons the seed |
| + // Step 3: the decisions. A fleet snapshot's key names its account and |
| + // app, so only that app's record of the host names it. |
| + var condemned []seedSnapshot |
| + waiting := map[[2]string]seedSnapshot{} // host, id -> snapshot: deleted only if this pass abandons the seed |
| for _, o := range snaps { |
| - host, id, ok := seeds.ParseSnapshotKey(o.Key) |
| - if !ok || held(host) { |
| + if held(o.host) { |
| continue |
| } |
| var rec *provision.Record |
| - if rs := byHost[host]; len(rs) == 1 { |
| + if rs := byHost[o.host]; len(rs) == 1 && (o.acct == "" || rs[0].Account == o.acct && rs[0].App == o.app) { |
| rec = &rs[0] |
| } |
| - switch snapshotDecision(rec, id, now, o.Mod) { |
| + switch snapshotDecision(rec, o.id, now, o.mod) { |
| case snapshotDelete: |
| - condemned = append(condemned, o.Key) |
| + condemned = append(condemned, o) |
| case snapshotIfAbandoned: |
| - waiting[[2]string{host, id}] = o.Key |
| + waiting[[2]string{o.host, o.id}] = o |
| } |
| } |
| @@ -236,24 +259,24 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) { |
| continue |
| } |
| if s.abandonSeed(ctx, rec) { |
| - if key, ok := waiting[[2]string{rec.Host, rec.Seed.ID}]; ok { |
| - condemned = append(condemned, key) |
| + if o, ok := waiting[[2]string{rec.Host, rec.Seed.ID}]; ok { |
| + condemned = append(condemned, o) |
| } |
| } |
| } |
| // Step 5: the snapshot deletes. |
| - sort.Strings(condemned) |
| - for _, key := range condemned { |
| + sort.Slice(condemned, func(i, j int) bool { return condemned[i].key < condemned[j].key }) |
| + for _, o := range condemned { |
| if ctx.Err() != nil { |
| return |
| } |
| - if err := s.cfg.SeedData.Delete(ctx, key); err != nil && !errors.Is(err, os.ErrNotExist) { |
| - log.Printf("console: seeds pass: delete %s: %v", key, err) |
| - jobFailed(ctx, fmt.Errorf("seeds pass: delete %s: %w", key, err)) |
| + if err := o.store.Delete(ctx, o.key); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + log.Printf("console: seeds pass: delete %s: %v", o.key, err) |
| + jobFailed(ctx, fmt.Errorf("seeds pass: delete %s: %w", o.key, err)) |
| continue |
| } |
| - log.Printf("console: seeds pass: deleted %s", key) |
| + log.Printf("console: seeds pass: deleted %s", o.key) |
| } |
| // Step 6: the finishes. |
| @@ -271,6 +294,75 @@ func (s *Server) seedsPass(ctx context.Context, now time.Time) { |
| } |
| } |
| +// seedSnapshot is one listed snapshot: the store it is in, its key and |
| +// last-modified time, and what its key names. acct and app are set only for |
| +// a fleet seed's, whose key names them. |
| +type seedSnapshot struct { |
| + store release.Store |
| + key string |
| + mod time.Time |
| + acct, app string |
| + host, id string |
| +} |
| + |
| +// fleetSeedSnapshots lists every fleet file seed's snapshot in the |
| +// deployment bucket: for each customer fleet, each app of its owning |
| +// account placed on it, trashed apps included (plan R1-4: a trashed app's |
| +// abandoned seed still has its snapshot to go), under |
| +// seeds.FleetSnapshotsPrefix. A key that does not parse as that app's is |
| +// skipped. Any error is the whole listing's: the pass decides nothing on a |
| +// partial set. A deployment bucket that cannot list last-modified times |
| +// gives none (StartSeedsPass logged it), so nothing of the fleet half is |
| +// deleted. |
| +func (s *Server) fleetSeedSnapshots(ctx context.Context) ([]seedSnapshot, error) { |
| + ml, ok := s.cfg.Releases.(release.ModLister) |
| + if !ok { |
| + return nil, nil |
| + } |
| + reg, err := openRegistry(s.cfg.Registry) |
| + if err != nil { |
| + return nil, fmt.Errorf("open the registry: %w", err) |
| + } |
| + owners, err := reg.FleetOwners() |
| + if err != nil { |
| + return nil, fmt.Errorf("list the fleets: %w", err) |
| + } |
| + fleets := make([]string, 0, len(owners)) |
| + for f := range owners { |
| + fleets = append(fleets, f) |
| + } |
| + sort.Strings(fleets) |
| + var out []seedSnapshot |
| + for _, fleet := range fleets { |
| + sqid := owners[fleet] |
| + acct, err := s.store.AccountBySqid(sqid) |
| + if err != nil { |
| + return nil, fmt.Errorf("fleet %s: account %s: %w", fleet, sqid, err) |
| + } |
| + if acct == nil { |
| + continue // an account this console does not hold: no app of it to list |
| + } |
| + apps, err := s.fleetPlacedAppsIn(acct, fleet, true) |
| + if err != nil { |
| + return nil, fmt.Errorf("fleet %s: its apps: %w", fleet, err) |
| + } |
| + for _, app := range apps { |
| + listed, err := ml.ListMod(ctx, seeds.FleetSnapshotsPrefix(sqid, app)) |
| + if err != nil { |
| + return nil, fmt.Errorf("fleet %s: %s/%s: %w", fleet, sqid, app, err) |
| + } |
| + for _, o := range listed { |
| + a, ap, host, id, ok := seeds.ParseFleetSnapshotKey(o.Key) |
| + if !ok || a != sqid || ap != app { |
| + continue |
| + } |
| + out = append(out, seedSnapshot{store: s.cfg.Releases, key: o.Key, mod: o.Mod, acct: a, app: ap, host: host, id: id}) |
| + } |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| type snapshotVerdict int |
| const ( |
diff --git a/internal/provision/fleet_seeded_create_3_census_test.go b/internal/provision/fleet_seeded_create_3_census_test.go| index e27489b4d..22569fd2b 100644 |
| --- a/internal/provision/fleet_seeded_create_3_census_test.go |
| +++ b/internal/provision/fleet_seeded_create_3_census_test.go |
| @@ -6,7 +6,7 @@ package provision |
| // fleetSeededCreate2WriteCensusInventory (main's newest at origin/main |
| // 772aabbb0, the slice 2 merge). |
| // Reviewed by the branch author against the source. No class or site kind |
| -// changes; one unit is new, and two tables are re-pinned. |
| +// changes; one unit is new, two tables and four seed units are re-pinned. |
| // |
| // New (Task 15, the fleet seeds door): |
| // |
| @@ -30,6 +30,32 @@ package provision |
| // - var linkedPolicies: the same three as linkedRefuse, beside the replica |
| // doors' rows. |
| // |
| +// Re-pinned (Task 16, file seeds on a customer fleet): |
| +// - Server.runImportUpload (console): the snapshot's store and key come |
| +// from the record (seedSnapshotTarget, decided before the hand-over): a |
| +// fleet file seed's to the deployment bucket at |
| +// seeds.FleetSnapshotKey, create-only, every other to the data bucket |
| +// as before. The same SetRecordSeed abort and publish writes. |
| +// - Server.importDeleteRule (console): fileSeedUnreadied now takes the |
| +// record, so a fleet file seed that is ready also reaches |
| +// fileSeedDeleteRule. Its own writes are unchanged. |
| +// - Server.fileSeedDeleteRule (console, plan D9, R1-5): a fleet file seed |
| +// reserving or ready is aborted by SetRecordSeed with SeedAbort (from |
| +// either state), a region one as before with SeedAbortFileUploadBecause; |
| +// an aborted fleet one is refused 409 (FS-33, or FS-34 from its held |
| +// place) with no write. Rolled-back still finishes. |
| +// - Server.finishSeedOnce (console): a fleet file seed's snapshot is |
| +// deleted from the deployment bucket at its fleet key (no data bucket |
| +// needed), and its replica is never touched (the fleet's own, proved |
| +// gone by its box). The record delete, by CAS or retirement, as before. |
| +// |
| +// Not in the inventory, because they write no record: seedFleetReady, |
| +// fleetSeedSnapshots (the sweep's fleet listing; the sweep's own record |
| +// write stays in abandonSeed), unfinishedFleetFileSeeds and |
| +// fleetSeedPurgeRefusal (a read and a refusal ahead of every purge |
| +// entrance), and beginFileSeed's fleet branch (its record write is |
| +// createSeedRecord's, as in slice 1). |
| +// |
| // provision.SeedFail gains held (decision D12); it is a transition passed |
| // to SetRecordSeed, not a census unit, and SetRecordSeed's digest stands. |
| func fleetSeededCreate3WriteCensusInventory() []censusEntry { |
| @@ -37,6 +63,10 @@ func fleetSeededCreate3WriteCensusInventory() []censusEntry { |
| for _, r := range []censusEntry{ |
| {"internal/console/routedecls.go", "var routeDecls", "key-site", "lit:instances,lit:sidecars", "e25fb0d3dbac6d7886d05636ae0a3fc09180e3ed699e1a9b2a7dc7b1c8e8d328"}, |
| {"internal/console/linkedpolicy.go", "var linkedPolicies", "key-site", "lit:instances,lit:sidecars", "c4139a1a2795e47d76f3c49bb761c15a849035942a4dcfa5a9ea631be61708b9"}, |
| + {"internal/console/apiinstanceimport.go", "Server.importDeleteRule", "record-writer", "key:SetRecordSeed", "da79f5bcda6ded08d92693d997fa6c8dbe2fe0eedfdd52dbd083f18a184768fe"}, |
| + {"internal/console/apiinstanceimport.go", "Server.runImportUpload", "record-writer", "key:SetRecordSeed", "051483202bca1a0af137b0181cf5c7e59c71c0c79511ef501e0f35ea1428e805"}, |
| + {"internal/console/seedfile.go", "Server.fileSeedDeleteRule", "record-writer", "key:SetRecordSeed", "c3872951d6f0f0a469eb93828843153c023a408df8672a7e11c08cb1c8937d6b"}, |
| + {"internal/console/seedfinish.go", "Server.finishSeedOnce", "key-site", "key:RecordKey", "f5da4e619ec229aef9ae9559cf347b62dbd6e0556b325d5ca6ad8f56c09f859d"}, |
| } { |
| replaced := false |
| for i, e := range entries { |