activator: HA wakes take a generation before serving
Every HA wake whose lock is in storage generations mode (sticky, or the box switch CARLOS_HA_GENERATIONS=on|fast, which the acquire passes as GenerationsOn) runs the take inside the restore, before the spawn: StartGeneration (a first wake creates head.json for an empty g-N), the keep rule (DecideKeep and the take's StartTXID equal to the marker's TXID; the take runs either way), RestoreTake and CheckDB, the files restore, the files fence, then the switch of head.json. - hostfiles: Manifest.lock_generation and FenceManifest (If-Match the restored ETag, or a create-only empty manifest); the wake's publisher continues from the fence's write. - A non-generations lock reads head.json once (none on a first wake): absent is today's wake; present refuses it (lock_not_generations). - A StartRefusal or lock_not_generations logs ha_generation_refused and pages at warning, at most hourly per host. - ErrHeadMoved or a fence conflict gives the lease back settled and doWake retries once from the acquire. - The HA mint guard reads a fence-created empty manifest as none. - replica-generations-1 is always published in the edges file. - locktest: ListObjectVersions and CopyObject over its one version.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
17 files changed,
+1,257
−75
internal/activator/activator.go+23 −0internal/activator/backend_exec.go+1 −1internal/activator/hagenerations_test.go+432 −7internal/activator/haleaseloss_test.go+2 −2internal/activator/harelease_keep_test.go+3 −1internal/activator/harelease_test.go+5 −4internal/activator/hasecrets.go+24 −5internal/activator/hasuspectholder.go+44 −0internal/activator/hawake.go+306 −34internal/host/edgesfile.go+12 −4internal/host/edgesfile_test.go+39 −6internal/host/movesoffline_test.go+6 −6internal/hostfiles/fence_test.go+126 −0internal/hostfiles/manifest.go+7 −0internal/hostfiles/publisher.go+54 −0internal/lease/locktest/fixture.go+139 −5internal/lease/locktest/fixture_test.go+34 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 1aab0b8a5..d60dd356d 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -2610,6 +2610,9 @@ type wokenInstance struct { |
| // them here without a.mu is safe by construction. |
| func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, error) { |
| w, err := a.doWakeOnce(ctx, e) |
| + if takeRaced(err) { |
| + w, err = a.retryTake(ctx, e, w, err) |
| + } |
| var change *wakeModeChange |
| if !errors.As(err, &change) || w == nil { |
| return w, err |
| @@ -2646,6 +2649,26 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| return result, nextErr |
| } |
| +// retryTake is the one retry of a wake whose storage generation take lost |
| +// a conditional write (spec §4 step 5, §7): head.json moved under its |
| +// switch, or the files manifest under its fence. It runs the wake again |
| +// from the acquire, once, only when the failed wake started nothing (its |
| +// restore failed before any spawn) and gave its lease back, as the |
| +// wakeModeChange retry requires; otherwise the failure stands. |
| +func (a *Service) retryTake(ctx context.Context, e *actEntry, w *wokenInstance, err error) (*wokenInstance, error) { |
| + if w == nil || w.proc != nil || w.pend != 0 || w.stopOutcome == nil || !w.stopOutcome.leaseReleased { |
| + return w, err |
| + } |
| + a.mu.Lock() |
| + unproven := a.unprovenWakes[e.host] != nil || len(a.straySidecars[e.host]) > 0 || a.releaseOps[e.host] != nil |
| + a.mu.Unlock() |
| + if unproven { |
| + return w, err |
| + } |
| + log.Printf("activator: %s: %v; the lease is back, retrying the wake once", e.host, err) |
| + return a.doWakeOnce(ctx, e) |
| +} |
| + |
| func (a *Service) doWakeOnce(ctx context.Context, e *actEntry) (*wokenInstance, error) { |
| a.mu.Lock() |
| admissionErr := a.tenantStartRefusal(e.route) |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index 02e019c32..87dce5d19 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -1040,7 +1040,7 @@ func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool |
| if s, ha, err := b.haRestore(ctx, rt); err != nil { |
| return false, err |
| } else if ha { |
| - return b.restoreHA(ctx, rt, s.view, s.view.Absent) |
| + return b.restoreHAWake(ctx, rt, s) |
| } |
| host, dbPath := rt.Host, b.pathsFor(rt).dbPath |
| // A failed seed whose processes were not proven gone left its database |
diff --git a/internal/activator/hagenerations_test.go b/internal/activator/hagenerations_test.go| index 7c6d4e9c4..c819c71a4 100644 |
| --- a/internal/activator/hagenerations_test.go |
| +++ b/internal/activator/hagenerations_test.go |
| @@ -2,16 +2,23 @@ package activator |
| import ( |
| "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/hex" |
| "encoding/json" |
| "errors" |
| + "os" |
| + "path/filepath" |
| "slices" |
| "strings" |
| + "sync" |
| "testing" |
| "time" |
| "github.com/carlosframework/platform/internal/boxchoice" |
| "github.com/carlosframework/platform/internal/edge" |
| "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/hostfiles" |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/replicagen" |
| @@ -287,10 +294,15 @@ func TestHALostLeaseRecoversOverEitherMarkerFormat(t *testing.T) { |
| } |
| } |
| -// The kept wake (hawake.go: stageKeptFiles(rt, Release.FilesGen)) over the |
| -// same clean release record in either format: the local copy is kept, the |
| -// wake is GET and PUT on the lock and nothing else, and the entry's files |
| -// publisher continues from the marker's FilesGen. |
| +// The kept wake over the same clean release record in either format: the |
| +// local copy is kept. Ordinary (switch off): the wake is GET and PUT on |
| +// the lock and one GET of head.json (none there), and the entry's files |
| +// publisher continues from the marker's FilesGen (stageKeptFiles). |
| +// Generations: the take runs all the same (spec §4: the keep rule only |
| +// skips the download), so the wake is the lock's GET and PUT, the take's |
| +// head GET, one version listing of the root and its copies into g-N, the |
| +// files fence (no manifest GET: the kept baseline is the marker's) and |
| +// the switch; the publisher continues from the fence's write. |
| func TestKeptWakeReadsEitherMarkerFormat(t *testing.T) { |
| for _, gen := range []bool{false, true} { |
| t.Run(formatName(gen), func(t *testing.T) { |
| @@ -307,7 +319,9 @@ func TestKeptWakeReadsEitherMarkerFormat(t *testing.T) { |
| t.Fatal(err) |
| } |
| lock := s.lockKey() |
| - if reqs := s.wakePathRequests(s.fx.Requests()[before:]); restoreCalls(s.b) != 0 || strings.Join(reqs, ",") != "GET "+lock+",PUT "+lock { |
| + reqs := s.wakePathRequests(s.fx.Requests()[before:]) |
| + want := "GET " + lock + ",PUT " + lock + ",GET " + s.headKey() |
| + if restoreCalls(s.b) != 0 || !strings.HasPrefix(strings.Join(reqs, ","), want) { |
| t.Fatalf("not kept: %v (%d restores)", reqs, restoreCalls(s.b)) |
| } |
| s.a.mu.Lock() |
| @@ -316,8 +330,32 @@ func TestKeptWakeReadsEitherMarkerFormat(t *testing.T) { |
| staged = e.files.pub.Gen() |
| } |
| s.a.mu.Unlock() |
| - if staged != m.FilesGen { |
| - t.Fatalf("staged files generation %q, want the marker's %q", staged, m.FilesGen) |
| + if !gen { |
| + if len(reqs) != 3 || staged != m.FilesGen { |
| + t.Fatalf("requests %v, staged files generation %q, want the marker's %q", reqs, staged, m.FilesGen) |
| + } |
| + } else { |
| + held := s.lockView(t).Lock |
| + g := s.loc() + "/" + held.GenName + "/" |
| + manifest := hostfiles.ManifestKey(s.b.filesPrefix(s.rt.Host)) |
| + rest := reqs[3:] |
| + if len(rest) < 4 || rest[0] != "LISTV "+s.loc()+"/" || rest[len(rest)-2] != "PUT "+manifest || rest[len(rest)-1] != "PUT "+s.headKey() { |
| + t.Fatalf("the kept take made %v", reqs) |
| + } |
| + for _, r := range rest[1 : len(rest)-2] { |
| + if !strings.HasPrefix(r, "COPY "+g) { |
| + t.Fatalf("the kept take made %v", reqs) |
| + } |
| + } |
| + body, _ := s.fx.Object(manifest) |
| + sum := sha256.Sum256(body) |
| + seq, _, _ := strings.Cut(m.FilesGen, ":") |
| + if staged != seq+":"+hex.EncodeToString(sum[:]) || s.storedManifest(t).LockGeneration != held.Generation { |
| + t.Fatalf("staged files generation %q, want the fence's at seq %s; marker %q", staged, seq, m.FilesGen) |
| + } |
| + if h, _ := s.head(t); h.Generation != held.GenName || h.Predecessor != replicagen.Root || h.StartTXID != m.TXID { |
| + t.Fatalf("head %+v, want %s from the root at TXID %d", h, held.GenName, m.TXID) |
| + } |
| } |
| if readFile(t, s.b, s.rt, "a.txt") != "app file" { |
| t.Fatal("the kept copy's files changed") |
| @@ -329,3 +367,390 @@ func TestKeptWakeReadsEitherMarkerFormat(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// ---- Task 5: the take in the wake (spec §4, §7, §9) ---- |
| + |
| +// genPage is one page the backend sent. |
| +type genPage struct{ level, subject, body string } |
| + |
| +// recordPages makes b's pages land in the returned log. |
| +func recordPages(b *ExecBackend) func() []genPage { |
| + var mu sync.Mutex |
| + var log []genPage |
| + b.Page = func(_ context.Context, level, subject, body string) error { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + log = append(log, genPage{level, subject, body}) |
| + return nil |
| + } |
| + return func() []genPage { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + return slices.Clone(log) |
| + } |
| +} |
| + |
| +func (s *haSvc) loc() string { return s.b.Cfg.hibernatePrefix(s.rt.Host) } |
| + |
| +func (s *haSvc) headKey() string { return s.loc() + "/head.json" } |
| + |
| +// head is the stored head.json, read without a request. |
| +func (s *haSvc) head(t *testing.T) (lease.Head, []byte) { |
| + t.Helper() |
| + body, ok := s.fx.Object(s.headKey()) |
| + if !ok { |
| + t.Fatal("no head.json") |
| + } |
| + var h lease.Head |
| + if err := json.Unmarshal(body, &h); err != nil { |
| + t.Fatal(err) |
| + } |
| + return h, body |
| +} |
| + |
| +// storedManifest is the files manifest, read without a request. |
| +func (s *haSvc) storedManifest(t *testing.T) hostfiles.Manifest { |
| + t.Helper() |
| + body, ok := s.fx.Object(hostfiles.ManifestKey(s.b.filesPrefix(s.rt.Host))) |
| + if !ok { |
| + t.Fatal("no files manifest") |
| + } |
| + var m hostfiles.Manifest |
| + if err := json.Unmarshal(body, &m); err != nil { |
| + t.Fatal(err) |
| + } |
| + return m |
| +} |
| + |
| +// insertRows writes n rows into the host's database. |
| +func (s *haSvc) insertRows(t *testing.T, from, n int) { |
| + t.Helper() |
| + db, err := sql.Open("sqlite", s.b.pathsFor(s.rt).dbPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + for i := from; i < from+n; i++ { |
| + if _, err := db.Exec("insert into t values (?)", i); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// loseLocalDB removes the host's local database, so the next wake cannot |
| +// keep it and restores. |
| +func (s *haSvc) loseLocalDB(t *testing.T) { |
| + t.Helper() |
| + db := s.b.pathsFor(s.rt).dbPath |
| + for _, p := range []string{db, db + "-wal", db + "-shm"} { |
| + if err := os.Remove(p); err != nil && !os.IsNotExist(err) { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +func countReqs(reqs []string, prefix string) int { |
| + n := 0 |
| + for _, r := range reqs { |
| + if strings.HasPrefix(r, prefix) { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// A switch-on wake takes a generation: the first wake creates head.json |
| +// for an empty g-1 and fences an empty manifest; a restoring wake copies |
| +// the predecessor into g-N, restores its rows from there, switches head |
| +// to g-N and replicates only under it; the manifest carries N. |
| +func TestHAWakeTakesAGeneration(t *testing.T) { |
| + t.Setenv("CARLOS_HA_GENERATIONS", "on") |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + if h, _ := s.head(t); h.Generation != replicagen.Name(1) || h.StartTXID != 0 || h.Predecessor != "" { |
| + t.Fatalf("first wake's head %+v", h) |
| + } |
| + if m := s.storedManifest(t); m.LockGeneration != 1 { |
| + t.Fatalf("first wake's manifest %+v, want lock generation 1", m) |
| + } |
| + s.insertRows(t, 0, 5) |
| + s.stopForTest(e) |
| + s.loseLocalDB(t) |
| + |
| + before := len(s.fx.Requests()) |
| + e, err := s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + held := s.lockView(t).Lock |
| + gen := replicagen.Name(held.Generation) |
| + if held.GenName != gen || held.Generation < 2 { |
| + t.Fatalf("the take's lock %+v", held) |
| + } |
| + h, _ := s.head(t) |
| + if h.Generation != gen || h.Predecessor != replicagen.Name(1) || len(h.History) == 0 || h.History[0].Generation != replicagen.Name(1) || h.StartTXID == 0 { |
| + t.Fatalf("head after the take %+v", h) |
| + } |
| + if restoreCalls(s.b) != 0 { |
| + t.Fatalf("the root restore ran %d times", restoreCalls(s.b)) |
| + } |
| + if n := countRows(t, s.b.pathsFor(s.rt).dbPath); n != 5 { |
| + t.Fatalf("restored %d rows, want the predecessor's 5", n) |
| + } |
| + if m := s.storedManifest(t); m.LockGeneration != held.Generation { |
| + t.Fatalf("manifest lock generation %d, want %d", m.LockGeneration, held.Generation) |
| + } |
| + s.insertRows(t, 5, 3) |
| + s.stopForTest(e) |
| + reqs := s.fx.Requests()[before:] |
| + if countReqs(reqs, "COPY "+s.loc()+"/"+gen+"/") == 0 { |
| + t.Fatalf("no copy into %s: %v", gen, reqs) |
| + } |
| + for _, r := range reqs { |
| + key, ok := strings.CutPrefix(r, "PUT ") |
| + if !ok { |
| + key, ok = strings.CutPrefix(r, "COPY ") |
| + } |
| + if ok && strings.HasSuffix(key, ".ltx") && !strings.HasPrefix(key, s.loc()+"/"+gen+"/") { |
| + t.Fatalf("a replica write outside %s: %s", gen, r) |
| + } |
| + } |
| + got := filepath.Join(t.TempDir(), "restored.db") |
| + if ok, err := lease.Restore(context.Background(), got, s.fx.Bucket, s.loc(), ""); err != nil || !ok { |
| + t.Fatalf("restore: %v %v", ok, err) |
| + } |
| + if n := countRows(t, got); n != 8 { |
| + t.Fatalf("the generation holds %d rows, want 8", n) |
| + } |
| +} |
| + |
| +// The migration (spec §9): a host that served in the root layout with the |
| +// switch off is taken in generations mode once the switch is on. Its |
| +// first take starts g-N from the root, restores the root's rows, and |
| +// head.json records the root as predecessor and history. |
| +func TestHAWakeSwitchOnMigratesFromTheRoot(t *testing.T) { |
| + t.Setenv("CARLOS_HA_GENERATIONS", "") |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + s.insertRows(t, 0, 4) |
| + s.stopForTest(e) |
| + if _, ok := s.fx.Object(s.headKey()); ok { |
| + t.Fatal("head.json with the switch off") |
| + } |
| + t.Setenv("CARLOS_HA_GENERATIONS", "fast") |
| + s.loseLocalDB(t) |
| + e, err := s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + held := s.lockView(t).Lock |
| + h, _ := s.head(t) |
| + if held.GenName == "" || h.Generation != held.GenName || h.Predecessor != replicagen.Root || len(h.History) != 1 || h.History[0].Generation != replicagen.Root { |
| + t.Fatalf("head %+v, lock %+v", h, held) |
| + } |
| + if n := countRows(t, s.b.pathsFor(s.rt).dbPath); n != 4 || restoreCalls(s.b) != 0 { |
| + t.Fatalf("restored %d rows (%d root restores), want the root's 4 through the take", n, restoreCalls(s.b)) |
| + } |
| + s.stopForTest(e) |
| + if v := s.lockView(t); v.Lock.Release == nil || !v.Lock.Release.Gen || !v.Lock.Release.Clean { |
| + t.Fatalf("the release %+v, want a clean generations marker", v.Lock.Release) |
| + } |
| +} |
| + |
| +// Switch off, a lock that is not in generations mode and no head.json: |
| +// the wake is today's, plus one GET of head.json (none on a first wake, |
| +// whose acquire proved the prefix empty), kept or restored from the root. |
| +func TestHAWakeSwitchOffNoHeadUnchanged(t *testing.T) { |
| + t.Setenv("CARLOS_HA_GENERATIONS", "") |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + for _, r := range s.fx.Requests() { |
| + if strings.Contains(r, "head.json") || strings.HasPrefix(r, "COPY ") || strings.HasPrefix(r, "LISTV ") || strings.Contains(r, "/g-") { |
| + t.Fatalf("a first wake with the switch off made %s", r) |
| + } |
| + } |
| + s.stopForTest(e) |
| + before := len(s.fx.Requests()) |
| + e, err := s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + lock := s.lockKey() |
| + if reqs := s.wakePathRequests(s.fx.Requests()[before:]); strings.Join(reqs, ",") != "GET "+lock+",PUT "+lock+",GET "+s.headKey() { |
| + t.Fatalf("a kept wake made %v", reqs) |
| + } |
| + s.stopForTest(e) |
| + s.loseLocalDB(t) |
| + before = len(s.fx.Requests()) |
| + e, err = s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + reqs := s.wakePathRequests(s.fx.Requests()[before:]) |
| + if restoreCalls(s.b) != 1 || countReqs(reqs, "GET "+s.headKey()) != 1 { |
| + t.Fatalf("a restoring wake: %d root restores, requests %v", restoreCalls(s.b), reqs) |
| + } |
| + for _, r := range reqs { |
| + if strings.HasPrefix(r, "COPY ") || strings.HasPrefix(r, "LISTV ") || strings.Contains(r, "/g-") || (strings.Contains(r, "head.json") && r != "GET "+s.headKey()) { |
| + t.Fatalf("a restoring wake with the switch off made %s", r) |
| + } |
| + } |
| + if v := s.lockView(t); v.Generations() { |
| + t.Fatalf("the lock turned generations: %+v", v.Lock) |
| + } |
| + if _, ok := s.fx.Object(s.headKey()); ok { |
| + t.Fatal("a head.json was written") |
| + } |
| + s.stopForTest(e) |
| +} |
| + |
| +// A host with head.json is only ever taken in generations mode: a lock |
| +// that is not (switch off, an ordinary marker) refuses the wake, copies |
| +// nothing, leaves head.json as it is, and pages once an hour. |
| +func TestHAWakeNonGenerationsLockWithHeadRefuses(t *testing.T) { |
| + t.Setenv("CARLOS_HA_GENERATIONS", "") |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + s.stopForTest(e) |
| + pages := recordPages(s.b) |
| + head, err := json.Marshal(lease.Head{V: lease.HeadVersion, Generation: replicagen.Name(7), History: []lease.HeadHistory{}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.fx.PutObject(s.headKey(), head) |
| + before := len(s.fx.Requests()) |
| + for i := 0; i < 2; i++ { |
| + _, err := s.wakeForTest(context.Background()) |
| + var re *errLeaseRefused |
| + if !errors.As(err, &re) || !strings.Contains(re.reason, "lock_not_generations") { |
| + t.Fatalf("wake %d: %v, want a lock_not_generations refusal", i, err) |
| + } |
| + } |
| + reqs := s.fx.Requests()[before:] |
| + if countReqs(reqs, "COPY ") != 0 || countReqs(reqs, "LISTV ") != 0 || countReqs(reqs, "PUT "+s.headKey()) != 0 { |
| + t.Fatalf("a refused wake made %v", reqs) |
| + } |
| + if got, _ := s.fx.Object(s.headKey()); string(got) != string(head) { |
| + t.Fatalf("head.json changed: %s", got) |
| + } |
| + if p := pages(); len(p) != 1 || p[0].level != "warning" || !strings.Contains(p[0].body, s.rt.Host) || !strings.Contains(p[0].body, "lock_not_generations") { |
| + t.Fatalf("pages %+v, want one warning naming the host and the reason", p) |
| + } |
| + if v := s.lockView(t); v.Lock.Release == nil || !v.Lock.Release.Settled || v.Generations() { |
| + t.Fatalf("the refused wake's release %+v", v.Lock) |
| + } |
| +} |
| + |
| +// A take that cannot be proved correct refuses the wake: G (head.json's |
| +// generation) holds LTX files but no L0. One page, no copy, head.json |
| +// unchanged. |
| +func TestHAWakeRefusalPages(t *testing.T) { |
| + t.Setenv("CARLOS_HA_GENERATIONS", "on") |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + s.stopForTest(e) |
| + pages := recordPages(s.b) |
| + g := replicagen.Name(5) |
| + head, err := json.Marshal(lease.Head{V: lease.HeadVersion, Generation: g, StartTXID: 10, Predecessor: replicagen.Name(1), History: []lease.HeadHistory{}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.fx.PutObject(s.headKey(), head) |
| + s.fx.PutObject(s.loc()+"/"+g+"/0001/0000000000000001-000000000000000a.ltx", []byte("not an L0")) |
| + before := len(s.fx.Requests()) |
| + for i := 0; i < 2; i++ { |
| + _, err := s.wakeForTest(context.Background()) |
| + var re *errLeaseRefused |
| + if !errors.As(err, &re) || !strings.Contains(re.reason, lease.RefuseNoL0) { |
| + t.Fatalf("wake %d: %v, want a no_l0 refusal", i, err) |
| + } |
| + } |
| + reqs := s.fx.Requests()[before:] |
| + if countReqs(reqs, "COPY ") != 0 || countReqs(reqs, "PUT "+s.headKey()) != 0 { |
| + t.Fatalf("a refused take made %v", reqs) |
| + } |
| + if got, _ := s.fx.Object(s.headKey()); string(got) != string(head) { |
| + t.Fatalf("head.json changed: %s", got) |
| + } |
| + if p := pages(); len(p) != 1 || p[0].level != "warning" || !strings.Contains(p[0].body, s.rt.Host) || !strings.Contains(p[0].body, lease.RefuseNoL0) { |
| + t.Fatalf("pages %+v, want one warning naming the host and the reason", p) |
| + } |
| + if v := s.lockView(t); v.Lock.Release == nil || !v.Lock.Release.Settled || !v.Generations() { |
| + t.Fatalf("the refused wake's release %+v", v.Lock) |
| + } |
| +} |
| + |
| +// A 412 on the switch (head moved) or on the files fence fails the take: |
| +// the wake gives the lease back through a settled marker and retries once |
| +// from the acquire. A second 412 fails the wake. |
| +func TestHAWakeHeadMovedRetriesOnce(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + fails int |
| + fence bool |
| + }{ |
| + {"head moved once", 1, false}, |
| + {"head moved twice", 2, false}, |
| + {"fence conflict once", 1, true}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + t.Setenv("CARLOS_HA_GENERATIONS", "on") |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + s.insertRows(t, 0, 2) |
| + s.stopForTest(e) |
| + key := s.headKey() |
| + if c.fence { |
| + key = hostfiles.ManifestKey(s.b.filesPrefix(s.rt.Host)) |
| + } |
| + for i := 0; i < c.fails; i++ { |
| + s.fx.FailNextMatching("PUT", 412, func(k string, _ []byte) bool { return k == key }) |
| + } |
| + start := len(s.lockWriteLog()) |
| + e, err := s.wakeForTest(context.Background()) |
| + writes := s.lockWriteLog()[start:] |
| + takes := 0 |
| + for _, w := range writes { |
| + if isHAHeld(w, s.b.self()) { |
| + takes++ |
| + } |
| + } |
| + if takes != 2 { |
| + t.Fatalf("%d takes, want 2: %d writes", takes, len(writes)) |
| + } |
| + if c.fails == 2 { |
| + if !errors.Is(err, lease.ErrHeadMoved) { |
| + t.Fatalf("wake: %v, want ErrHeadMoved", err) |
| + } |
| + if v := s.lockView(t); v.Lock.Release == nil || !v.Lock.Release.Settled { |
| + t.Fatalf("the failed wake's release %+v", v.Lock) |
| + } |
| + return |
| + } |
| + if err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + if !isMarker(writes[1]) || genView(t, writes[1].body).Lock.Release.Settled != true { |
| + t.Fatalf("the failed take's release is not a settled marker") |
| + } |
| + held := s.lockView(t).Lock |
| + if h, _ := s.head(t); h.Generation != held.GenName || held.GenName == "" { |
| + t.Fatalf("head %+v, lock %+v", h, held) |
| + } |
| + if n := countRows(t, s.b.pathsFor(s.rt).dbPath); n != 2 { |
| + t.Fatalf("%d rows after the retried take, want 2", n) |
| + } |
| + s.stopForTest(e) |
| + }) |
| + } |
| +} |
| + |
| +// The switch: on for "on" and "fast", fast only for "fast", off for |
| +// anything else. |
| +func TestGenerationsSwitchParse(t *testing.T) { |
| + for v, want := range map[string][2]bool{"": {}, "0": {}, "off": {}, "ON": {}, " on": {}, "1": {}, "on": {true, false}, "fast": {true, true}} { |
| + on, fast := generationsSwitch(func(k string) string { |
| + if k == "CARLOS_HA_GENERATIONS" { |
| + return v |
| + } |
| + return "" |
| + }) |
| + if [2]bool{on, fast} != want { |
| + t.Fatalf("%q: on %v fast %v, want %v", v, on, fast, want) |
| + } |
| + } |
| +} |
diff --git a/internal/activator/haleaseloss_test.go b/internal/activator/haleaseloss_test.go| index 2f289c59d..405f45820 100644 |
| --- a/internal/activator/haleaseloss_test.go |
| +++ b/internal/activator/haleaseloss_test.go |
| @@ -444,7 +444,7 @@ func TestHALostLeaseRecoveryAcquireBudget(t *testing.T) { |
| finishLostTestEntry(t, s, e, r) |
| old := acquireHALease |
| called := false |
| - acquireHALease = func(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs) (*lease.Held, error) { |
| + acquireHALease = func(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs, opts lease.AcquireOptions) (*lease.Held, error) { |
| called = true |
| deadline, ok := ctx.Deadline() |
| if !ok || time.Until(deadline) > 2*time.Second { |
| @@ -510,7 +510,7 @@ func TestHALostRecoveryShutdownDoesNotWaitForWake(t *testing.T) { |
| finishLostTestEntry(t, s, e, r) |
| entered, unblock := make(chan struct{}), make(chan struct{}) |
| old := acquireHALease |
| - acquireHALease = func(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs) (*lease.Held, error) { |
| + acquireHALease = func(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs, opts lease.AcquireOptions) (*lease.Held, error) { |
| close(entered) |
| <-unblock |
| return nil, context.Canceled |
diff --git a/internal/activator/harelease_keep_test.go b/internal/activator/harelease_keep_test.go| index 8788141a9..d0f453ae4 100644 |
| --- a/internal/activator/harelease_keep_test.go |
| +++ b/internal/activator/harelease_keep_test.go |
| @@ -37,7 +37,9 @@ func TestLargeManifestReleaseThenKeep(t *testing.T) { |
| t.Fatal(err) |
| } |
| reqs := s.wakePathRequests(s.fx.Requests()[n:]) |
| - if restoreCalls(s.b) != 0 || strings.Join(reqs, ",") != "GET "+lock+",PUT "+lock { |
| + // The lock's GET and PUT, and head.json's one GET (none there: the |
| + // switch is off, region HA storage generations §9). |
| + if restoreCalls(s.b) != 0 || strings.Join(reqs, ",") != "GET "+lock+",PUT "+lock+",GET "+s.headKey() { |
| t.Fatalf("a kept wake with a large manifest made %v (%d restores)", reqs, restoreCalls(s.b)) |
| } |
| } |
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go| index 87e95ea4d..3ff0cd22f 100644 |
| --- a/internal/activator/harelease_test.go |
| +++ b/internal/activator/harelease_test.go |
| @@ -835,9 +835,10 @@ func TestFinalSyncBudgetStartsAfterTheFilesPublish(t *testing.T) { |
| // §18's budget, through whole wakes: a first wake is GET, LIST and PUT on |
| // the lock and nothing of the files; a kept copy's wake is GET and PUT on |
| -// the lock and nothing else (its publisher continues from the manifest |
| -// its release record keeps); a restore reads the manifest once, the read |
| -// its publisher then continues from. |
| +// the lock and one GET of head.json (region HA storage generations §9, |
| +// switch off: none there), and nothing else (its publisher continues from |
| +// the manifest its release record keeps); a restore reads the manifest |
| +// once, the read its publisher then continues from. |
| func TestHAWakeRequestCounts(t *testing.T) { |
| s := haService(t, "shop.example.com") |
| lock := s.lockKey() |
| @@ -864,7 +865,7 @@ func TestHAWakeRequestCounts(t *testing.T) { |
| writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "app"}) |
| s.stopForTest(e) |
| e, reqs = wake() |
| - if want := []string{"GET " + lock, "PUT " + lock}; restoreCalls(s.b) != 0 || strings.Join(reqs, ",") != strings.Join(want, ",") { |
| + if want := []string{"GET " + lock, "PUT " + lock, "GET " + s.headKey()}; restoreCalls(s.b) != 0 || strings.Join(reqs, ",") != strings.Join(want, ",") { |
| t.Fatalf("a kept wake made %v (%d restores), want %v", reqs, restoreCalls(s.b), want) |
| } |
| s.stopForTest(e) |
diff --git a/internal/activator/hasecrets.go b/internal/activator/hasecrets.go| index 3ad5a1f78..bcac4f039 100644 |
| --- a/internal/activator/hasecrets.go |
| +++ b/internal/activator/hasecrets.go |
| @@ -236,17 +236,36 @@ func (b *ExecBackend) haPublisherNow(host string) *hostFiles { |
| return nil |
| } |
| -// haManifestFound reports whether rt's files manifest exists: from the |
| -// publisher this wake already holds, else by one read. |
| +// haManifestFound reports whether rt's files manifest exists, from the |
| +// publisher this wake already holds, else by one read. A manifest a |
| +// storage generations files fence stamped (region HA storage generations |
| +// §7, hostfiles.FenceManifest) that holds no entry and no platform item |
| +// is the fence's create over an empty tree: nothing was ever published |
| +// beside it, so no launch used a secret, and it answers false as no |
| +// manifest does. |
| func (b *ExecBackend) haManifestFound(ctx context.Context, rt registry.Route) (bool, error) { |
| if f := b.haPublisherNow(rt.Host); f != nil { |
| - return f.pub.Baseline().Found, nil |
| + base := f.pub.Baseline() |
| + if !base.Found { |
| + return false, nil |
| + } |
| + var m hostfiles.Manifest |
| + if err := json.Unmarshal(base.Body, &m); err != nil { |
| + return false, fmt.Errorf("the wake's files manifest: %w", err) |
| + } |
| + return !fencedEmpty(m), nil |
| } |
| if b.FilesStore == nil { |
| return false, errors.New("no files store configured") |
| } |
| - _, found, err := hostfiles.Load(ctx, b.FilesStore, b.filesPrefix(rt.Host)) |
| - return found, err |
| + m, found, err := hostfiles.Load(ctx, b.FilesStore, b.filesPrefix(rt.Host)) |
| + return found && !fencedEmpty(m), err |
| +} |
| + |
| +// fencedEmpty reports a manifest a files fence stamped that holds no |
| +// entry (live, deleted or skipped) and no platform item. |
| +func fencedEmpty(m hostfiles.Manifest) bool { |
| + return m.LockGeneration > 0 && len(m.Entries) == 0 && len(m.Platform) == 0 |
| } |
| // haSecretsReady is the step between an HA host's ensure calls and its |
diff --git a/internal/activator/hasuspectholder.go b/internal/activator/hasuspectholder.go| index 473ecdba6..f5a2171e9 100644 |
| --- a/internal/activator/hasuspectholder.go |
| +++ b/internal/activator/hasuspectholder.go |
| @@ -30,6 +30,10 @@ type suspectHolderState struct { |
| hosts map[string]suspectHolder |
| paged map[string]time.Time |
| now func() time.Time |
| + // genPaged is when each host's refused generation take last paged |
| + // (pageGenerationRefusal): at most once an hour per host, its own |
| + // limit, apart from paged's per-instance one. |
| + genPaged map[string]time.Time |
| } |
| func (s *suspectHolderState) clock() time.Time { |
| @@ -171,3 +175,43 @@ const suspectHolderSubject = "Instance %s is holding hosts it does not serve." |
| const suspectHolderBody = "Instance %s has an expired lease. EC2 has not confirmed that this instance terminated. The leases for these hosts expired at least 10 minutes ago: %s. If the instance is in an Auto Scaling group, terminate it in that group. If it is a fixed box, check its access to S3 and its agent first. This page repeats every hour while takeover remains refused. (ha_suspect_holder)" |
| const suspectHolderSameBoxSubject = "Box %s cannot recover hosts after a restart." |
| const suspectHolderSameBoxBody = "This box could not prove that its earlier processes for these hosts have stopped: %s. Their leases expired at least 10 minutes ago. No other box may take them without proof. If this box is in an Auto Scaling group, terminate it in that group. If it is a fixed box, check the agent's startup sweep and cgroup delegation. This page repeats every hour while takeover remains refused. (ha_suspect_holder_same_box)" |
| + |
| +// generationRefusalEvery is how often one host's refused generation take |
| +// pages at most. |
| +const generationRefusalEvery = time.Hour |
| + |
| +// pageGenerationRefusal pages, at warning level through the suspect-holder |
| +// pager's sink (Page), that host's wake was refused because its |
| +// generation take could not be proved correct (reason: a |
| +// lease.StartRefusal reason, or lock_not_generations): at most once an |
| +// hour per host. Nil Page: nothing. |
| +func (b *ExecBackend) pageGenerationRefusal(host, reason string) { |
| + if b.Page == nil { |
| + return |
| + } |
| + s := &b.suspectHolders |
| + now := s.clock() |
| + s.mu.Lock() |
| + for h, last := range s.genPaged { |
| + if now.Sub(last) >= generationRefusalEvery { |
| + delete(s.genPaged, h) |
| + } |
| + } |
| + if _, already := s.genPaged[host]; already { |
| + s.mu.Unlock() |
| + return |
| + } |
| + if s.genPaged == nil { |
| + s.genPaged = make(map[string]time.Time) |
| + } |
| + s.genPaged[host] = now |
| + s.mu.Unlock() |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + if err := b.Page(ctx, alerting.LevelWarning, fmt.Sprintf(generationRefusedSubject, host), fmt.Sprintf(generationRefusedBody, host, reason)); err != nil { |
| + log.Printf("ha_generation_refused host=%s page failed: %v", host, err) |
| + } |
| +} |
| + |
| +const generationRefusedSubject = "Host %s cannot wake: its replica history was refused." |
| +const generationRefusedBody = "Host %s was refused at wake because its replica could not be carried into a new storage generation (reason: %s). No box serves it until an operator restores it by hand. Nothing was copied and head.json is unchanged. This page repeats every hour while its wakes are refused. (ha_generation_refused reason=%[2]s)" |
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go| index 147892b34..23f840938 100644 |
| --- a/internal/activator/hawake.go |
| +++ b/internal/activator/hawake.go |
| @@ -6,6 +6,7 @@ import ( |
| "fmt" |
| "io/fs" |
| "log" |
| + "os" |
| "path" |
| "path/filepath" |
| "strings" |
| @@ -19,6 +20,7 @@ import ( |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| // Region HA P1a, the wake (spec §5, §7.3): a host born HA (its record's ha, |
| @@ -72,11 +74,37 @@ func (l *execLease) SetMonitorInterval(d time.Duration) { l.held.SetMonitorInter |
| // The lease calls behind seams, so the classification is testable against |
| // the lock fixture with a short-circuit where a test needs one. |
| +// acquireHALease is lease.AcquireHA with the acquire's switches |
| +// (lease.AcquireOptions): AcquireHAForDuty with no refusal callback. |
| var ( |
| acquireLegacyLease = lease.Acquire |
| - acquireHALease = lease.AcquireHA |
| + acquireHALease = func(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs, opts lease.AcquireOptions) (*lease.Held, error) { |
| + return lease.AcquireHAForDuty(ctx, bucket, prefix, region, base, p, nil, opts) |
| + } |
| ) |
| +// generationsSwitchEnv is the box's storage-generations switch (region HA |
| +// storage generations §9): "on" takes every HA wake in generations mode |
| +// (the acquire table unchanged); "fast" is on plus slice 4's table change. |
| +// Unset, "0" or any other value is off. Set per group by the release |
| +// manager, never by default. |
| +const generationsSwitchEnv = "CARLOS_HA_GENERATIONS" |
| + |
| +// haGetenv is the environment the switch is read from, once per wake. |
| +var haGetenv = os.Getenv |
| + |
| +// generationsSwitch parses the switch: on for "on" and "fast", fast for |
| +// "fast" alone, and both false for anything else. |
| +func generationsSwitch(getenv func(string) string) (on, fast bool) { |
| + switch getenv(generationsSwitchEnv) { |
| + case "on": |
| + return true, false |
| + case "fast": |
| + return true, true |
| + } |
| + return false, false |
| +} |
| + |
| // haLegacyRoute reports a route that is legacy before any record lookup |
| // (r3.4): an unstamped sidecar, a route the provision pass did not mint, |
| // or a kind other than an instance or native sidecar. It keeps today's acquire, and an HA-format |
| @@ -177,11 +205,15 @@ func refusedUncontained(err error) error { |
| // haWake is what Acquire classified for a host, for the Restore after it |
| // (and the spawns under that lease): whether it took the HA path, the view |
| -// it classified before its take, and the host's lifetime entry. |
| +// it classified before its take, the host's lifetime entry, and the HA |
| +// lease it holds (nil off the HA path), whose lock is in storage |
| +// generations mode when its GenName is set: the Restore runs the take on |
| +// it (restoreHAGenerations). |
| type haWake struct { |
| ha bool |
| view hafresh.View |
| entry provision.LifetimeEntry |
| + held *lease.Held |
| } |
| // haWakes holds each host's last Acquire classification, and the |
| @@ -420,16 +452,22 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route) |
| } |
| ctx = lease.WithTerminationProof(ctx, &adapter) |
| } |
| + // The switch, read once for this wake: on, the take writes a |
| + // generations lock over any lock; off, only over a generations lock |
| + // (the mode is sticky). Either way the Restore takes a generation on a |
| + // generations lock. |
| + on, _ := generationsSwitch(haGetenv) |
| + opts := lease.AcquireOptions{GenerationsOn: on} |
| var held *lease.Held |
| if duty, ok := ctx.Value(dutyContextKey{}).(dutyRestriction); ok { |
| - held, err = lease.AcquireHAForDuty(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region, hafresh.Marker{Lifetime: entry.ID}, proofs, duty.allow) |
| + held, err = lease.AcquireHAForDuty(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region, hafresh.Marker{Lifetime: entry.ID}, proofs, duty.allow, opts) |
| } else { |
| - held, err = acquireHALease(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region, hafresh.Marker{Lifetime: entry.ID}, proofs) |
| + held, err = acquireHALease(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region, hafresh.Marker{Lifetime: entry.ID}, proofs, opts) |
| } |
| if err != nil { |
| return nil, leaseError(err) |
| } |
| - b.haWakes.set(host, haWake{ha: true, view: held.View(), entry: entry}) |
| + b.haWakes.set(host, haWake{ha: true, view: held.View(), entry: entry, held: held}) |
| if note, ok := ctx.Value(dutyAcquiredKey{}).(func(context.Context, registry.Route, hafresh.Marker)); ok { |
| note(ctx, rt, hafresh.Marker{Lifetime: entry.ID}) |
| } |
| @@ -499,29 +537,54 @@ func (b *ExecBackend) haRestore(ctx context.Context, rt registry.Route) (haWake, |
| return haWake{}, false, nil |
| } |
| -// restoreHA is an HA host's restore, in place of restorePlain (and never |
| -// the staging fallback). first, an absent lock, is a first wake: the |
| -// prefix was proven empty by the acquire, so the local copy is set aside |
| -// and the wake is fresh, with an empty tree. Otherwise the local copy is |
| -// kept only on proof (hafresh.DecideKeep over v, the view the acquire |
| -// classified); anything else sets it aside and restores the database and |
| -// the files into a clean tree. A local state that cannot be read restores. |
| -// Every error fails the wake, and fresh is false on every error path. |
| -func (b *ExecBackend) restoreHA(ctx context.Context, rt registry.Route, v hafresh.View, first bool) (fresh bool, err error) { |
| - host := rt.Host |
| +// restoreHAWake is an HA host's restore for the wake w recorded: the |
| +// generation take when its lock is in storage generations mode |
| +// (restoreHAGenerations), and otherwise restoreHA. |
| +func (b *ExecBackend) restoreHAWake(ctx context.Context, rt registry.Route, w haWake) (bool, error) { |
| + if w.held != nil && w.held.GenName() != "" { |
| + return b.restoreHAGenerations(ctx, rt, w) |
| + } |
| + return b.restoreHA(ctx, rt, w.view, w.view.Absent) |
| +} |
| + |
| +// haRestorePrelude is what every HA restore does first: the containment |
| +// admission, an earlier seed whose processes were not proven gone |
| +// answered (as restorePlain does), and a database a foreign seed left |
| +// purged: neither is a copy this box released. |
| +func (b *ExecBackend) haRestorePrelude(ctx context.Context, rt registry.Route) error { |
| if err := b.haContained(rt); err != nil { |
| - return false, refusedUncontained(err) |
| + return refusedUncontained(err) |
| } |
| p := b.pathsFor(rt) |
| - // An earlier seed whose processes were not proven gone is answered |
| - // first, as restorePlain does, and a database a foreign seed left is |
| - // purged: neither is a copy this box released. |
| if err := b.settleSeedObligation(ctx, rt, p.dbPath); err != nil { |
| - return false, err |
| + return err |
| } |
| - if err := reconcileSeedMarker(rt, p.dbPath); err != nil { |
| + return reconcileSeedMarker(rt, p.dbPath) |
| +} |
| + |
| +// restoreHA is an HA host's restore when its lock is not in storage |
| +// generations mode, in place of restorePlain (and never the staging |
| +// fallback). first, an absent lock, is a first wake: the prefix was |
| +// proven empty by the acquire, so the local copy is set aside and the |
| +// wake is fresh, with an empty tree. Otherwise head.json is read once: a |
| +// host that has one is only ever taken in generations mode, so its wake |
| +// is refused (lock_not_generations, paged); with none, the local copy is |
| +// kept only on proof (hafresh.DecideKeep over v, the view the acquire |
| +// classified), and anything else sets it aside and restores the database |
| +// and the files into a clean tree. A local state that cannot be read |
| +// restores. Every error fails the wake, and fresh is false on every error |
| +// path. |
| +func (b *ExecBackend) restoreHA(ctx context.Context, rt registry.Route, v hafresh.View, first bool) (fresh bool, err error) { |
| + host := rt.Host |
| + if err := b.haRestorePrelude(ctx, rt); err != nil { |
| return false, err |
| } |
| + p := b.pathsFor(rt) |
| + if !first { |
| + if err := b.refuseHeadWithoutGenerations(ctx, rt); err != nil { |
| + return false, err |
| + } |
| + } |
| if first { |
| if err := b.setAside(p, host); err != nil { |
| return false, fmt.Errorf("%s: set aside the local copy: %w", host, err) |
| @@ -555,17 +618,8 @@ func (b *ExecBackend) restoreHA(ctx context.Context, rt registry.Route, v hafres |
| return false, err |
| } |
| if restored { |
| - if err := lease.CheckDB(p.dbPath); err != nil { |
| - // The same rule as restorePlain: a corrupt restore never serves |
| - // and never boots fresh. It is quarantined (one, the newest), |
| - // or removed if it cannot be, and the next wake restores again. |
| - dbDir, dbName := filepath.Dir(p.dbPath), filepath.Base(p.dbPath) |
| - if qerr := errors.Join(removeIfThere(dbDir, dbName+quarantineSuffix), renameIfThere(dbDir, dbName, dbName+quarantineSuffix)); qerr != nil { |
| - _ = removeIfThere(dbDir, dbName) |
| - } |
| - _ = removeIfThere(dbDir, dbName+"-wal") |
| - _ = removeIfThere(dbDir, dbName+"-shm") |
| - return false, fmt.Errorf("restored replica for %s is corrupt: %w", host, err) |
| + if err := checkRestoredDB(p, host); err != nil { |
| + return false, err |
| } |
| } |
| if err := b.restoreFilesClean(ctx, rt); err != nil { |
| @@ -575,6 +629,215 @@ func (b *ExecBackend) restoreHA(ctx context.Context, rt registry.Route, v hafres |
| return !restored, nil |
| } |
| +// checkRestoredDB is restorePlain's rule for a restored database: a |
| +// corrupt restore never serves and never boots fresh. It is quarantined |
| +// (one, the newest), or removed if it cannot be, and the next wake |
| +// restores again. |
| +func checkRestoredDB(p instancePaths, host string) error { |
| + err := lease.CheckDB(p.dbPath) |
| + if err == nil { |
| + return nil |
| + } |
| + dbDir, dbName := filepath.Dir(p.dbPath), filepath.Base(p.dbPath) |
| + if qerr := errors.Join(removeIfThere(dbDir, dbName+quarantineSuffix), renameIfThere(dbDir, dbName, dbName+quarantineSuffix)); qerr != nil { |
| + _ = removeIfThere(dbDir, dbName) |
| + } |
| + _ = removeIfThere(dbDir, dbName+"-wal") |
| + _ = removeIfThere(dbDir, dbName+"-shm") |
| + return fmt.Errorf("restored replica for %s is corrupt: %w", host, err) |
| +} |
| + |
| +// newTakeStore is the hibernate bucket by exact object version, for a |
| +// generation take's listing and copies (lease.NewVersionedS3): a seam so |
| +// a test can count or fail them. |
| +var newTakeStore = func(ctx context.Context, bucket, region string) (lease.VersionedStore, error) { |
| + return lease.NewVersionedS3(ctx, map[string]string{bucket: region}) |
| +} |
| + |
| +// errFilesFenced is a files fence whose conditional write lost (spec §7): |
| +// the manifest changed since this wake read it (a predecessor's late |
| +// commit). The wake fails as on a moved head.json, and retries once. |
| +var errFilesFenced = errors.New("the files manifest changed under the generation take's fence") |
| + |
| +// takeRaced reports a wake that failed because its generation take lost a |
| +// conditional write, head.json's switch (lease.ErrHeadMoved) or the files |
| +// fence (errFilesFenced): doWake retries it once (retryTake). |
| +func takeRaced(err error) bool { |
| + return errors.Is(err, lease.ErrHeadMoved) || errors.Is(err, errFilesFenced) |
| +} |
| + |
| +// lockNotGenerations is the refusal of a wake whose lock is not in |
| +// storage generations mode over a host that has head.json. |
| +const lockNotGenerations = "lock_not_generations" |
| + |
| +// refuseHeadWithoutGenerations is a non-generations wake's one added |
| +// request (spec §9): head.json, read once through the files store (the |
| +// hibernate bucket). None: nil, and today's wake goes on unchanged. One: |
| +// the host is only ever taken in generations mode, so the wake is refused |
| +// and paged. A read that fails fails the wake. |
| +func (b *ExecBackend) refuseHeadWithoutGenerations(ctx context.Context, rt registry.Route) error { |
| + if b.FilesStore == nil { |
| + return errors.New("no files store configured: head.json cannot be read") |
| + } |
| + _, _, found, err := lease.ReadHead(ctx, b.FilesStore, b.Cfg.hibernatePrefix(rt.Host)) |
| + if err != nil { |
| + return fmt.Errorf("%s: %w", rt.Host, err) |
| + } |
| + if found { |
| + return b.refuseGeneration(rt.Host, lockNotGenerations, errors.New("head.json exists and the lock is not a storage generations lock")) |
| + } |
| + return nil |
| +} |
| + |
| +// refuseGeneration fails a wake whose generation take is refused (a |
| +// *lease.StartRefusal's reason, or lockNotGenerations): it is logged as |
| +// ha_generation_refused, paged (pageGenerationRefusal), and answered as a |
| +// refused lease, since the condition outlives the request. |
| +func (b *ExecBackend) refuseGeneration(host, reason string, cause error) error { |
| + log.Printf("ha_generation_refused host=%s reason=%s: %v", host, reason, cause) |
| + b.pageGenerationRefusal(host, reason) |
| + return &errLeaseRefused{reason: "ha_generation_refused reason=" + reason} |
| +} |
| + |
| +// restoreHAGenerations is the restore of an HA wake whose lock is in |
| +// storage generations mode (spec §4, §7), all of it before the spawn: |
| +// |
| +// 1. The take (lease.Held.StartGeneration): a first wake creates head.json |
| +// for an empty g-N; any other copies the predecessor's start into g-N. |
| +// A *lease.StartRefusal refuses the wake and pages. |
| +// 2. The keep rule: the local copy is kept only when hafresh.DecideKeep |
| +// keeps it and the take started exactly at the marker's TXID; the take |
| +// runs either way. Otherwise the copy is set aside and g-N restored |
| +// (lease.RestoreTake, checked as restorePlain checks), and the files |
| +// restored into a clean tree. |
| +// 3. The files fence (hostfiles.FenceManifest) with this lock's |
| +// generation: the publisher continues from its write. A first wake |
| +// fences an empty manifest. |
| +// 4. The switch of head.json to g-N. |
| +// |
| +// A lost condition at 3 or 4 fails the wake (takeRaced); the lease goes |
| +// back settled, since nothing replicated, and doWake retries once. |
| +func (b *ExecBackend) restoreHAGenerations(ctx context.Context, rt registry.Route, w haWake) (fresh bool, err error) { |
| + host := rt.Host |
| + if err := b.haRestorePrelude(ctx, rt); err != nil { |
| + return false, err |
| + } |
| + if b.FilesStore == nil { |
| + return false, errors.New("no files store configured") |
| + } |
| + p := b.pathsFor(rt) |
| + v := w.view |
| + first := v.Absent |
| + lifetime, err := b.haLifetime(ctx, rt) |
| + if err != nil { |
| + return false, err |
| + } |
| + opt := lease.TakeOptions{First: first, Self: b.self(), Lifetime: lifetime} |
| + if m := v.Lock.Release; m != nil && m.Clean { |
| + opt.CleanTXID = m.TXID |
| + } |
| + var vs lease.VersionedStore |
| + if !first { |
| + if vs, err = newTakeStore(ctx, b.Cfg.Bucket, b.Cfg.Region); err != nil { |
| + return false, fmt.Errorf("%s: take a generation: %w", host, err) |
| + } |
| + } |
| + take, err := w.held.StartGeneration(ctx, b.FilesStore, vs, opt) |
| + if err != nil { |
| + var sr *lease.StartRefusal |
| + if errors.As(err, &sr) { |
| + return false, b.refuseGeneration(host, sr.Reason, err) |
| + } |
| + return false, fmt.Errorf("%s: take a generation: %w", host, err) |
| + } |
| + |
| + var base hostfiles.Baseline |
| + keep, restored, reason := false, false, hafresh.KeepNoMarker |
| + switch { |
| + case first: |
| + if err := b.setAside(p, host); err != nil { |
| + return false, fmt.Errorf("%s: set aside the local copy: %w", host, err) |
| + } |
| + // The acquire proved the prefix empty, so there is no manifest. |
| + default: |
| + now, rerr := readLocalNow(p, host) |
| + reason = "local-unreadable" |
| + if rerr == nil { |
| + keep, reason = hafresh.DecideKeep(v, b.self(), lifetime, now) |
| + } else { |
| + log.Printf("activator: %s: %v", host, rerr) |
| + } |
| + if keep && take.StartTXID != v.Lock.Release.TXID { |
| + keep, reason = false, fmt.Sprintf("take-txid %d, marker %d", take.StartTXID, v.Lock.Release.TXID) |
| + } |
| + if keep { |
| + if base, err = b.keptBaseline(ctx, rt, v.Lock.Release.FilesGen); err != nil { |
| + return false, fmt.Errorf("%s: files: %w", host, err) |
| + } |
| + break |
| + } |
| + if err := b.setAside(p, host); err != nil { |
| + return false, fmt.Errorf("%s: set aside the local copy: %w", host, err) |
| + } |
| + if restored, err = lease.RestoreTake(ctx, p.dbPath, take); err != nil { |
| + return false, fmt.Errorf("%s: restore %s: %w", host, take.Generation, err) |
| + } |
| + if restored { |
| + if err := checkRestoredDB(p, host); err != nil { |
| + return false, err |
| + } |
| + } |
| + if err := b.restoreFilesCleanRead(ctx, rt, func(read hostfiles.Baseline) { base = read }); err != nil { |
| + return false, fmt.Errorf("%s: restore files: %w", host, err) |
| + } |
| + } |
| + fenced, err := hostfiles.FenceManifest(ctx, b.FilesStore, b.filesPrefix(host), base, w.held.LockGeneration()) |
| + if errors.Is(err, release.ErrCASConflict) { |
| + return false, fmt.Errorf("%s: %w: %w", host, errFilesFenced, err) |
| + } |
| + if err != nil { |
| + return false, fmt.Errorf("%s: files fence: %w", host, err) |
| + } |
| + if err := take.Switch(ctx); err != nil { |
| + return false, fmt.Errorf("%s: switch head.json to %s: %w", host, take.Generation, err) |
| + } |
| + b.stageWakeFiles(rt, fenced) |
| + switch { |
| + case first: |
| + log.Printf("activator: %s: restored (%s): first wake, the prefix proven empty, booting fresh in %s", host, hafresh.KeepNoMarker, take.Generation) |
| + return true, nil |
| + case keep: |
| + log.Printf("activator: %s: kept local, replicating to %s from TXID %d", host, take.Generation, take.StartTXID) |
| + return false, nil |
| + } |
| + log.Printf("activator: %s: restored (%s) from %s into %s at TXID %d", host, reason, take.Predecessor, take.Generation, take.StartTXID) |
| + return !restored, nil |
| +} |
| + |
| +// keptBaseline is the manifest a kept generations wake fences: the one |
| +// its release kept beside the local record when that is the revision the |
| +// marker names (gen; no request), else the manifest as it is now (one |
| +// GET), as the entry's open would read it for a kept wake. |
| +func (b *ExecBackend) keptBaseline(ctx context.Context, rt registry.Route, gen string) (hostfiles.Baseline, error) { |
| + prefix := b.filesPrefix(rt.Host) |
| + base, err := readFilesBaseline(b.pathsFor(rt)) |
| + if err == nil { |
| + var pub *hostfiles.Publisher |
| + if pub, err = hostfiles.OpenBaseline(b.FilesStore, prefix, base); err == nil { |
| + if pub.Gen() == gen { |
| + return base, nil |
| + } |
| + err = fmt.Errorf("revision %s, the marker names %s", pub.Gen(), gen) |
| + } |
| + } |
| + log.Printf("activator: %s: files: the kept manifest is not the marker's (%v); reading it again", rt.Host, err) |
| + pub, err := hostfiles.Open(ctx, b.FilesStore, prefix) |
| + if err != nil { |
| + return hostfiles.Baseline{}, err |
| + } |
| + return pub.Baseline(), nil |
| +} |
| + |
| // haLifetime is the host's lifetime ID for the keep decision: the one its |
| // Acquire classified with, else the record facts read now. |
| func (b *ExecBackend) haLifetime(ctx context.Context, rt registry.Route) (string, error) { |
| @@ -730,6 +993,16 @@ func sealedShadow(host string) hostfiles.Shadowed { |
| // live: the first sealed commit tombstoned it (DropRawSecrets), so a key |
| // deleted since is never resurrected. |
| func (b *ExecBackend) restoreFilesClean(ctx context.Context, rt registry.Route) error { |
| + // The manifest just read is the one this wake's publisher continues. |
| + return b.restoreFilesCleanRead(ctx, rt, func(base hostfiles.Baseline) { b.stageWakeFiles(rt, base) }) |
| +} |
| + |
| +// restoreFilesCleanRead is restoreFilesClean that hands the manifest it |
| +// read (Found false for none) to read, once it is read and before any of |
| +// it is restored, in place of staging the wake's publisher on it: a |
| +// generations wake fences it first, and its publisher continues from the |
| +// fence's write. |
| +func (b *ExecBackend) restoreFilesCleanRead(ctx context.Context, rt registry.Route, read func(hostfiles.Baseline)) error { |
| host := rt.Host |
| if b.FilesStore == nil { |
| return errors.New("no files store configured") |
| @@ -756,8 +1029,7 @@ func (b *ExecBackend) restoreFilesClean(ctx context.Context, rt registry.Route) |
| if err != nil { |
| return err |
| } |
| - // The manifest just read is the one this wake's publisher continues. |
| - b.stageWakeFiles(rt, base) |
| + read(base) |
| if len(st.Skipped) > 0 { |
| log.Printf("activator: %s: %d file(s) the manifest holds as unpublished were not restored: %s", host, len(st.Skipped), strings.Join(st.Skipped, ", ")) |
| } |
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go| index 72ac2e12f..143653013 100644 |
| --- a/internal/host/edgesfile.go |
| +++ b/internal/host/edgesfile.go |
| @@ -219,11 +219,19 @@ const capRegionHA1 = "region-ha-1" |
| // refuses while any edges file lacks it. |
| const capLifetimes1 = "lifetimes-1" |
| -// edgesFileCapabilities publishes lifetimes-1 always, and region-ha-1 only |
| -// when CARLOS_REGION_HA is set to something other than "" or "0". |
| -// Worker capabilities are added per pass after their readers arm. |
| +// capReplicaGenerations1 is the floor of region HA storage generations |
| +// (spec 2026-11-12 §9): a box at this release reads and writes head.json |
| +// generations and runs the take on every wake of a generations lock. It is |
| +// published always, whatever CARLOS_HA_GENERATIONS says: the gate turns |
| +// generations on for a pool only when every box serving it publishes it. |
| +const capReplicaGenerations1 = "replica-generations-1" |
| + |
| +// edgesFileCapabilities publishes lifetimes-1 and replica-generations-1 |
| +// always, and region-ha-1 only when CARLOS_REGION_HA is set to something |
| +// other than "" or "0". Worker capabilities are added per pass after their |
| +// readers arm. |
| func edgesFileCapabilities(getenv func(string) string) []string { |
| - caps := []string{capLifetimes1} |
| + caps := []string{capLifetimes1, capReplicaGenerations1} |
| if regionHAEnabled(getenv) { |
| caps = append(caps, capRegionHA1) |
| } |
diff --git a/internal/host/edgesfile_test.go b/internal/host/edgesfile_test.go| index cf890e732..240ba815d 100644 |
| --- a/internal/host/edgesfile_test.go |
| +++ b/internal/host/edgesfile_test.go |
| @@ -1346,6 +1346,38 @@ func TestEdgesFileSecretsKeyFingerprint(t *testing.T) { |
| } |
| } |
| +// replica-generations-1 (region HA storage generations, §9): every box at |
| +// this release publishes it, whatever its switches, so the gate can see |
| +// that a pool is ready before generations are turned on for it. |
| +func TestEdgesFilePublishesGenerationsCapability(t *testing.T) { |
| + for _, env := range []map[string]string{ |
| + {}, |
| + {"CARLOS_REGION_HA": "1"}, |
| + {"CARLOS_HA_GENERATIONS": "on"}, |
| + {"CARLOS_HA_GENERATIONS": "0", "CARLOS_REGION_HA": "0"}, |
| + } { |
| + caps := edgesFileCapabilities(func(k string) string { return env[k] }) |
| + if n := slices.Index(caps, "replica-generations-1"); n < 0 || slices.Index(caps[n+1:], "replica-generations-1") >= 0 { |
| + t.Fatalf("%v: capabilities %v, want replica-generations-1 once", env, caps) |
| + } |
| + } |
| + s, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) |
| + seedRoute(t, reg, "app.example.com") |
| + ident := edgesFile{Box: "annie", BoxID: "annie", Capabilities: edgesFileCapabilities(func(string) string { return "" })} |
| + var last []byte |
| + if err := edgesFileWrite(context.Background(), s, reg, ident, "203.0.113.10", &last, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _, err := s.Get(context.Background(), edgesFileKey("annie")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var f edgesfile.PlacementView |
| + if err := json.Unmarshal(body, &f); err != nil || !slices.Contains(f.Capabilities, "replica-generations-1") { |
| + t.Fatalf("published capabilities %v (%v)", f.Capabilities, err) |
| + } |
| +} |
| + |
| func TestEdgesFileCapabilityFollowsTheFlag(t *testing.T) { |
| env := func(v string) func(string) string { |
| return func(k string) string { |
| @@ -1355,14 +1387,15 @@ func TestEdgesFileCapabilityFollowsTheFlag(t *testing.T) { |
| return "" |
| } |
| } |
| - // lifetimes-1 is the lifetimes cutover's box floor, published always. |
| - if got := edgesFileCapabilities(env("")); !slices.Equal(got, []string{"lifetimes-1", "names-2"}) { |
| + // lifetimes-1 is the lifetimes cutover's box floor, published always, |
| + // as is replica-generations-1, the storage generations floor. |
| + if got := edgesFileCapabilities(env("")); !slices.Equal(got, []string{"lifetimes-1", "replica-generations-1", "names-2"}) { |
| t.Fatalf("unset: %v", got) |
| } |
| - if got := edgesFileCapabilities(env("1")); !slices.Equal(got, []string{"lifetimes-1", "region-ha-1", "names-2"}) { |
| + if got := edgesFileCapabilities(env("1")); !slices.Equal(got, []string{"lifetimes-1", "replica-generations-1", "region-ha-1", "names-2"}) { |
| t.Fatalf("set: %v", got) |
| } |
| - if got := edgesFileCapabilities(env("0")); !slices.Equal(got, []string{"lifetimes-1", "names-2"}) { |
| + if got := edgesFileCapabilities(env("0")); !slices.Equal(got, []string{"lifetimes-1", "replica-generations-1", "names-2"}) { |
| t.Fatalf("\"0\" is off: %v", got) |
| } |
| } |
| @@ -1386,8 +1419,8 @@ func TestEdgesFilePublishesTheLifetimesFloor(t *testing.T) { |
| t.Fatal(err) |
| } |
| var f edgesfile.PlacementView |
| - if err := json.Unmarshal(b1, &f); err != nil || !slices.Equal(f.Capabilities, []string{capLifetimes1, edgesfile.NamesCapability}) { |
| - t.Fatalf("capabilities = %v (%v), want [lifetimes-1 names-2]", f.Capabilities, err) |
| + if err := json.Unmarshal(b1, &f); err != nil || !slices.Equal(f.Capabilities, []string{capLifetimes1, capReplicaGenerations1, edgesfile.NamesCapability}) { |
| + t.Fatalf("capabilities = %v (%v), want [lifetimes-1 replica-generations-1 names-2]", f.Capabilities, err) |
| } |
| if err := edgesFileWrite(context.Background(), s, reg, ident, "203.0.113.10", &last, false); err != nil { |
| t.Fatal(err) |
diff --git a/internal/host/movesoffline_test.go b/internal/host/movesoffline_test.go| index 19ba781bf..56a0a019d 100644 |
| --- a/internal/host/movesoffline_test.go |
| +++ b/internal/host/movesoffline_test.go |
| @@ -965,7 +965,7 @@ func TestOfflineCapabilityAndAnIncapableBox(t *testing.T) { |
| if armedOfflineCapable() { |
| t.Fatal("capable with no worker armed") |
| } |
| - if got := withOfflineCapability(edgesFileCapabilities(env()), armedOfflineCapable()); !slices.Equal(got, []string{capLifetimes1, "names-2"}) { |
| + if got := withOfflineCapability(edgesFileCapabilities(env()), armedOfflineCapable()); !slices.Equal(got, []string{capLifetimes1, capReplicaGenerations1, "names-2"}) { |
| t.Fatalf("no worker armed: %v", got) |
| } |
| wdCap := newOffWorld(t) |
| @@ -974,11 +974,11 @@ func TestOfflineCapabilityAndAnIncapableBox(t *testing.T) { |
| if !armedOfflineCapable() { |
| t.Fatal("a capable armed worker does not publish") |
| } |
| - if got := withOfflineCapability(edgesFileCapabilities(env()), armedOfflineCapable()); !slices.Equal(got, []string{capLifetimes1, "names-2", capOfflineMove1, capOfflineStage1}) { |
| + if got := withOfflineCapability(edgesFileCapabilities(env()), armedOfflineCapable()); !slices.Equal(got, []string{capLifetimes1, capReplicaGenerations1, "names-2", capOfflineMove1, capOfflineStage1}) { |
| t.Fatalf("capable box: %v", got) |
| } |
| base := edgesFileCapabilities(env("CARLOS_REGION_HA", "1")) |
| - if got := withOfflineCapability(base, true); !slices.Equal(got, []string{capLifetimes1, capRegionHA1, "names-2", capOfflineMove1, capOfflineStage1}) || !slices.Equal(base, []string{capLifetimes1, capRegionHA1, "names-2"}) { |
| + if got := withOfflineCapability(base, true); !slices.Equal(got, []string{capLifetimes1, capReplicaGenerations1, capRegionHA1, "names-2", capOfflineMove1, capOfflineStage1}) || !slices.Equal(base, []string{capLifetimes1, capReplicaGenerations1, capRegionHA1, "names-2"}) { |
| t.Fatalf("region HA too: %v (base %v)", got, base) |
| } |
| for _, kv := range [][]string{ |
| @@ -1169,11 +1169,11 @@ func TestOfflineDormantIsMain(t *testing.T) { |
| if json.Unmarshal(b1, &m1) != nil || json.Unmarshal(b2, &m2) != nil { |
| t.Fatal("edges files do not parse") |
| } |
| - if caps, _ := m2["capabilities"].([]any); len(caps) != 4 || caps[0] != capLifetimes1 || caps[1] != "names-2" || caps[2] != capOfflineMove1 || caps[3] != capOfflineStage1 { |
| + if caps, _ := m2["capabilities"].([]any); len(caps) != 5 || caps[0] != capLifetimes1 || caps[1] != capReplicaGenerations1 || caps[2] != "names-2" || caps[3] != capOfflineMove1 || caps[4] != capOfflineStage1 { |
| t.Fatalf("capabilities: %v", m2["capabilities"]) |
| } |
| - // The plain file carries the lifetimes floor alone. |
| - if caps, _ := m1["capabilities"].([]any); len(caps) != 2 || caps[0] != capLifetimes1 || caps[1] != "names-2" { |
| + // The plain file carries the lifetimes and generations floors alone. |
| + if caps, _ := m1["capabilities"].([]any); len(caps) != 3 || caps[0] != capLifetimes1 || caps[1] != capReplicaGenerations1 || caps[2] != "names-2" { |
| t.Fatalf("fixture: the plain file's capabilities are %v", m1["capabilities"]) |
| } |
| delete(m1, "capabilities") |
diff --git a/internal/hostfiles/fence_test.go b/internal/hostfiles/fence_test.go| new file mode 100644 |
| index 000000000..59385d248 |
| --- /dev/null |
| +++ b/internal/hostfiles/fence_test.go |
| @@ -0,0 +1,126 @@ |
| +package hostfiles |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The files fence (spec 2026-11-12 region HA storage generations, §7): a |
| +// successor stamps the manifest with its lock generation before it serves, |
| +// so a predecessor's late compare-and-swap, made against the manifest it |
| +// last saw, fails its condition. |
| +func TestFenceManifestStampsAndBlocksALateWrite(t *testing.T) { |
| + ctx := context.Background() |
| + |
| + t.Run("manifest present", func(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + p := open(t, s) |
| + stage(t, p, "a.txt", "one") |
| + if _, err := p.Commit(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + pre := p.Baseline() |
| + fenced, err := FenceManifest(ctx, s, pfx, pre, 42) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !fenced.Found || fenced.ETag == "" || fenced.ETag == pre.ETag { |
| + t.Fatalf("fenced baseline %+v", fenced) |
| + } |
| + raw, etag, err := s.Get(ctx, ManifestKey(pfx)) |
| + if err != nil || etag != fenced.ETag || string(raw) != string(fenced.Body) { |
| + t.Fatalf("stored manifest %q %q %v, fenced %q", raw, etag, err, fenced.ETag) |
| + } |
| + var was, now Manifest |
| + if err := json.Unmarshal(pre.Body, &was); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := json.Unmarshal(raw, &now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if now.LockGeneration != 42 || now.Seq != was.Seq || now.Entries["a.txt"] != was.Entries["a.txt"] || len(now.Entries) != len(was.Entries) { |
| + t.Fatalf("fenced manifest %+v, was %+v", now, was) |
| + } |
| + // The predecessor's late commit, against the pre-fence ETag, fails. |
| + if _, err := s.Put(ctx, ManifestKey(pfx), pre.Body, pre.ETag); !errors.Is(err, release.ErrCASConflict) { |
| + t.Fatalf("late CAS: %v, want ErrCASConflict", err) |
| + } |
| + stage(t, p, "b.txt", "late") |
| + if _, err := p.Commit(ctx); !errors.Is(err, ErrSuperseded) { |
| + t.Fatalf("late publisher commit: %v, want ErrSuperseded", err) |
| + } |
| + // The successor's publisher continues from the fence's own write. |
| + next, err := OpenBaseline(s, pfx, fenced) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + stage(t, next, "c.txt", "successor") |
| + if _, err := next.Commit(ctx); err != nil { |
| + t.Fatalf("first commit after the fence: %v", err) |
| + } |
| + m, _, err := Load(ctx, s, pfx) |
| + if err != nil || m.LockGeneration != 42 || m.Entries["c.txt"].Object == "" || m.Entries["b.txt"].Object != "" { |
| + t.Fatalf("after the successor's commit: %+v %v", m, err) |
| + } |
| + // A stale baseline never fences. |
| + if _, err := FenceManifest(ctx, s, pfx, pre, 43); !errors.Is(err, release.ErrCASConflict) { |
| + t.Fatalf("fence on a moved manifest: %v, want ErrCASConflict", err) |
| + } |
| + }) |
| + |
| + t.Run("no manifest", func(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + fenced, err := FenceManifest(ctx, s, pfx, Baseline{}, 7) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + m, found, err := Load(ctx, s, pfx) |
| + if err != nil || !found || m.LockGeneration != 7 || m.V != ManifestVersion || len(m.Entries) != 0 || len(m.Platform) != 0 || m.Seq != 0 { |
| + t.Fatalf("created manifest %+v %v %v", m, found, err) |
| + } |
| + // A predecessor that saw no manifest makes a create-only write: it |
| + // conflicts. |
| + late, err := OpenBaseline(s, pfx, Baseline{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + stage(t, late, "a.txt", "late") |
| + if _, err := late.Commit(ctx); !errors.Is(err, ErrSuperseded) { |
| + t.Fatalf("late create: %v, want ErrSuperseded", err) |
| + } |
| + if _, err := s.Put(ctx, ManifestKey(pfx), []byte(`{"v":2}`), ""); !errors.Is(err, release.ErrCASConflict) { |
| + t.Fatalf("late create-only PUT: %v, want ErrCASConflict", err) |
| + } |
| + next, err := OpenBaseline(s, pfx, fenced) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + stage(t, next, "b.txt", "successor") |
| + if _, err := next.Commit(ctx); err != nil { |
| + t.Fatalf("first commit after the fence: %v", err) |
| + } |
| + if _, err := FenceManifest(ctx, s, pfx, Baseline{}, 8); !errors.Is(err, release.ErrCASConflict) { |
| + t.Fatalf("a second create fence: %v, want ErrCASConflict", err) |
| + } |
| + }) |
| + |
| + t.Run("refusals", func(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + if _, err := FenceManifest(ctx, s, pfx, Baseline{}, 0); err == nil { |
| + t.Fatal("lock generation 0 fenced") |
| + } |
| + if _, err := FenceManifest(ctx, s, pfx, Baseline{Found: true, Body: []byte(`{"v":2}`)}, 1); err == nil { |
| + t.Fatal("a baseline without its ETag fenced") |
| + } |
| + if _, err := FenceManifest(ctx, s, pfx, Baseline{Found: true, Body: []byte(`{"v":1}`), ETag: `"x"`}, 1); err == nil { |
| + t.Fatal("a version 1 manifest fenced") |
| + } |
| + if _, _, err := s.Get(ctx, ManifestKey(pfx)); err == nil { |
| + t.Fatal("a refused fence wrote") |
| + } |
| + }) |
| +} |
diff --git a/internal/hostfiles/manifest.go b/internal/hostfiles/manifest.go| index 8a4046362..594aaba59 100644 |
| --- a/internal/hostfiles/manifest.go |
| +++ b/internal/hostfiles/manifest.go |
| @@ -77,6 +77,13 @@ type Manifest struct { |
| // format before this) carries none, and a reader falls back to the |
| // admitted chain alone. Additive: every other field is as before. |
| Origins []string `json:"origins,omitempty"` |
| + // LockGeneration is the lock generation of the HA take that fenced |
| + // the manifest last (FenceManifest, region HA storage generations |
| + // §7): the successor stamps it before it serves, so a predecessor's |
| + // late compare-and-swap fails its condition. A publisher continuing |
| + // from the fenced manifest carries it forward. Additive: 0 (absent) on |
| + // a manifest no take has fenced. |
| + LockGeneration int64 `json:"lock_generation,omitempty"` |
| } |
| func ManifestKey(prefix string) string { return prefix + "manifest.json" } |
diff --git a/internal/hostfiles/publisher.go b/internal/hostfiles/publisher.go| index 1ad4d12a7..92a489baf 100644 |
| --- a/internal/hostfiles/publisher.go |
| +++ b/internal/hostfiles/publisher.go |
| @@ -178,6 +178,60 @@ func OpenBaseline(s release.Store, prefix string, b Baseline) (*Publisher, error |
| return &Publisher{s: s, prefix: prefix, man: Manifest{V: ManifestVersion, Entries: map[string]Entry{}, Platform: map[string]Entry{}}}, nil |
| } |
| +// FenceManifest is the files fence of an HA take (region HA storage |
| +// generations §7), made before the wake serves. With a manifest (b.Found) |
| +// it rewrites b's manifest unchanged but for lock_generation = lockGen, |
| +// If-Match b.ETag: every other field, unknown ones included, is kept |
| +// byte for byte. With none it creates an empty manifest stamped with |
| +// lockGen, If-None-Match: *. Either way a predecessor's late write, made |
| +// against the manifest it last saw (or create-only, when it saw none), |
| +// then fails its condition. A lost race is release.ErrCASConflict and |
| +// writes nothing. The result is the fence's own write as a Baseline: the |
| +// wake's publisher continues from it (OpenBaseline), with no read. |
| +func FenceManifest(ctx context.Context, s release.Store, prefix string, b Baseline, lockGen int64) (Baseline, error) { |
| + if s == nil { |
| + return Baseline{}, errors.New("hostfiles: fence: no store") |
| + } |
| + if err := checkPrefix(prefix); err != nil { |
| + return Baseline{}, err |
| + } |
| + if lockGen <= 0 { |
| + return Baseline{}, fmt.Errorf("hostfiles: fence %s: lock generation %d", prefix, lockGen) |
| + } |
| + var body []byte |
| + if b.Found { |
| + if b.ETag == "" { |
| + return Baseline{}, fmt.Errorf("hostfiles: fence %s: a manifest without its token", prefix) |
| + } |
| + if _, err := decode(prefix, b.Body); err != nil { |
| + return Baseline{}, fmt.Errorf("hostfiles: fence: %w", err) |
| + } |
| + var fields map[string]json.RawMessage |
| + if err := json.Unmarshal(b.Body, &fields); err != nil { |
| + return Baseline{}, fmt.Errorf("hostfiles: fence %s: %w", prefix, err) |
| + } |
| + stamp, err := json.Marshal(lockGen) |
| + if err != nil { |
| + return Baseline{}, err |
| + } |
| + fields["lock_generation"] = stamp |
| + if body, err = json.Marshal(fields); err != nil { |
| + return Baseline{}, fmt.Errorf("hostfiles: fence %s: %w", prefix, err) |
| + } |
| + } else { |
| + var err error |
| + body, err = json.Marshal(Manifest{V: ManifestVersion, Entries: map[string]Entry{}, Platform: map[string]Entry{}, LockGeneration: lockGen}) |
| + if err != nil { |
| + return Baseline{}, err |
| + } |
| + } |
| + etag, err := s.Put(ctx, ManifestKey(prefix), body, b.ETag) // "" when absent: create-only |
| + if err != nil { |
| + return Baseline{}, fmt.Errorf("hostfiles: fence %s: %w", ManifestKey(prefix), err) |
| + } |
| + return Baseline{Found: true, Body: body, ETag: etag}, nil |
| +} |
| + |
| // Baseline is the manifest last committed (or opened on), as OpenBaseline |
| // takes it: Found false while there is none. |
| func (p *Publisher) Baseline() Baseline { |
diff --git a/internal/lease/locktest/fixture.go b/internal/lease/locktest/fixture.go| index 6005233ee..c842a0e33 100644 |
| --- a/internal/lease/locktest/fixture.go |
| +++ b/internal/lease/locktest/fixture.go |
| @@ -2,7 +2,10 @@ |
| // bucket of plain (unversioned) objects, served path-style over HTTP on |
| // 127.0.0.1, with ETags, conditional PUT and DELETE (If-Match, |
| // If-None-Match: *), ListObjectsV2, a request log, fault injection and a |
| -// hook before each write. |
| +// hook before each write. Each object also carries the id of its one |
| +// version, so a storage-generations take runs against it through the |
| +// production clients: ListObjectVersions lists every object as its only, |
| +// current version, and CopyObject copies the current version it names. |
| // |
| // It imports nothing from the platform, so package lease's own tests, as |
| // well as anyone else's, can use it without an import cycle (leasetest |
| @@ -14,6 +17,7 @@ import ( |
| "encoding/hex" |
| "encoding/json" |
| "encoding/xml" |
| + "html" |
| "io" |
| "net/http" |
| "net/http/httptest" |
| @@ -33,6 +37,7 @@ type object struct { |
| body []byte |
| etag string // quoted, as S3 sends it |
| modified time.Time |
| + version string // a new id at every write; no older version is kept |
| } |
| // LockFixture is the endpoint and its state. Its methods are safe to call |
| @@ -53,6 +58,7 @@ type LockFixture struct { |
| // its prefix. |
| replicaFaults map[int]string |
| nextFault int |
| + versions int // the last version id handed out |
| } |
| // matchFault fails the next request of verb whose key and body match. |
| @@ -112,6 +118,18 @@ func (f *LockFixture) LockBody(prefix string) []byte { |
| return append([]byte(nil), o.body...) |
| } |
| +// Object is key's body as stored now, without a request; false when there |
| +// is none. |
| +func (f *LockFixture) Object(key string) ([]byte, bool) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + o, ok := f.objects[key] |
| + if !ok { |
| + return nil, false |
| + } |
| + return append([]byte(nil), o.body...), true |
| +} |
| + |
| // LockOwner is the "owner" field of prefix's lock.json, "" when there is |
| // no lock or it is not JSON. |
| func (f *LockFixture) LockOwner(prefix string) string { |
| @@ -123,7 +141,8 @@ func (f *LockFixture) LockOwner(prefix string) string { |
| } |
| // Requests is every request served, in order: "GET key", "HEAD key", |
| -// "PUT key", "DELETE key" or "LIST prefix". A request a fault failed is |
| +// "PUT key", "DELETE key", "LIST prefix", "LISTV prefix" (a |
| +// ListObjectVersions) or "COPY key" (a CopyObject, its destination). A request a fault failed is |
| // listed too. The SDK retries 5xx answers by itself, so a retried request |
| // appears once per attempt. |
| func (f *LockFixture) Requests() []string { |
| @@ -132,8 +151,8 @@ func (f *LockFixture) Requests() []string { |
| return append([]string(nil), f.log...) |
| } |
| -// FailNext fails the next request of verb ("GET", "HEAD", "PUT", "DELETE" |
| -// or "LIST") with status, before it touches any object. |
| +// FailNext fails the next request of verb ("GET", "HEAD", "PUT", "DELETE", |
| +// "LIST", "LISTV" or "COPY") with status, before it touches any object. |
| func (f *LockFixture) FailNext(verb string, status int) { f.FailNth(verb, 1, status) } |
| // FailNth fails the n-th request of verb from now (n from 1) with status. |
| @@ -210,7 +229,9 @@ func (f *LockFixture) replicaFaultLocked(key string) bool { |
| func (f *LockFixture) storeLocked(key string, body []byte) object { |
| sum := md5.Sum(body) |
| - o := object{body: append([]byte(nil), body...), etag: `"` + hex.EncodeToString(sum[:]) + `"`, modified: time.Now().UTC()} |
| + f.versions++ |
| + o := object{body: append([]byte(nil), body...), etag: `"` + hex.EncodeToString(sum[:]) + `"`, modified: time.Now().UTC(), |
| + version: "v" + strconv.Itoa(f.versions)} |
| f.objects[key] = o |
| return o |
| } |
| @@ -253,6 +274,12 @@ func (f *LockFixture) serve(w http.ResponseWriter, r *http.Request) { |
| verb, subject := r.Method, key |
| if r.Method == http.MethodGet && key == "" { |
| verb, subject = "LIST", q.Get("prefix") |
| + if q.Has("versions") { |
| + verb = "LISTV" |
| + } |
| + } |
| + if r.Method == http.MethodPut && r.Header.Get("x-amz-copy-source") != "" { |
| + verb = "COPY" |
| } |
| var body []byte |
| if r.Method == http.MethodPut { |
| @@ -305,11 +332,20 @@ func (f *LockFixture) serve(w http.ResponseWriter, r *http.Request) { |
| switch { |
| case verb == "LIST": |
| f.listLocked(w, q) |
| + case verb == "LISTV": |
| + f.listVersionsLocked(w, q) |
| + case verb == "COPY" && key != "": |
| + f.copyLocked(w, r, key, exists) |
| case (r.Method == http.MethodGet || r.Method == http.MethodHead) && key != "": |
| if !exists { |
| s3error(w, http.StatusNotFound, "NoSuchKey") |
| return |
| } |
| + if v := q.Get("versionId"); v != "" && v != cur.version { |
| + s3error(w, http.StatusNotFound, "NoSuchVersion") |
| + return |
| + } |
| + w.Header().Set("x-amz-version-id", cur.version) |
| w.Header().Set("ETag", cur.etag) |
| w.Header().Set("Content-Type", "application/json") |
| w.Header().Set("Last-Modified", cur.modified.Format(http.TimeFormat)) |
| @@ -337,6 +373,7 @@ func (f *LockFixture) serve(w http.ResponseWriter, r *http.Request) { |
| } |
| o := f.storeLocked(key, body) |
| w.Header().Set("ETag", o.etag) |
| + w.Header().Set("x-amz-version-id", o.version) |
| case r.Method == http.MethodDelete && key != "": |
| if m := r.Header.Get("If-Match"); m != "" { |
| if !exists { |
| @@ -433,3 +470,100 @@ func (f *LockFixture) listLocked(w http.ResponseWriter, q url.Values) { |
| io.WriteString(w, xml.Header) |
| xml.NewEncoder(w).Encode(res) |
| } |
| + |
| +// copyLocked is CopyObject onto key (present or not): the source is |
| +// "<bucket>/<key>[?versionId=<id>]", which must name the source's current |
| +// version (no other is kept); If-None-Match: * refuses a present |
| +// destination. The caller holds f.mu. |
| +func (f *LockFixture) copyLocked(w http.ResponseWriter, r *http.Request, key string, exists bool) { |
| + src := strings.TrimPrefix(r.Header.Get("x-amz-copy-source"), "/") |
| + srcPath, rawQ, _ := strings.Cut(src, "?") |
| + sq, err := url.ParseQuery(rawQ) |
| + if err != nil { |
| + s3error(w, http.StatusBadRequest, "InvalidArgument") |
| + return |
| + } |
| + unesc, err := url.PathUnescape(srcPath) |
| + if err != nil { |
| + s3error(w, http.StatusBadRequest, "InvalidArgument") |
| + return |
| + } |
| + sb, sk, _ := strings.Cut(unesc, "/") |
| + from, ok := f.objects[sk] |
| + if sb != f.Bucket || !ok { |
| + s3error(w, http.StatusNotFound, "NoSuchKey") |
| + return |
| + } |
| + if v := sq.Get("versionId"); v != "" && v != from.version { |
| + s3error(w, http.StatusNotFound, "NoSuchVersion") |
| + return |
| + } |
| + if r.Header.Get("If-None-Match") == "*" && exists { |
| + s3error(w, http.StatusPreconditionFailed, "PreconditionFailed") |
| + return |
| + } |
| + o := f.storeLocked(key, from.body) |
| + w.Header().Set("x-amz-version-id", o.version) |
| + w.Header().Set("Content-Type", "application/xml") |
| + io.WriteString(w, "<CopyObjectResult><ETag>"+html.EscapeString(o.etag)+"</ETag><LastModified>"+o.modified.Format(time.RFC3339)+"</LastModified></CopyObjectResult>") |
| +} |
| + |
| +type listVersion struct { |
| + XMLName xml.Name `xml:"Version"` |
| + Key string |
| + VersionId string |
| + IsLatest bool |
| + LastModified string |
| + ETag string |
| + Size int |
| +} |
| + |
| +type listVersionsResult struct { |
| + XMLName xml.Name `xml:"ListVersionsResult"` |
| + Name string |
| + Prefix string |
| + KeyMarker string |
| + NextKeyMarker string `xml:",omitempty"` |
| + NextVersionIdMarker string `xml:",omitempty"` |
| + MaxKeys int |
| + IsTruncated bool |
| + Versions []listVersion |
| +} |
| + |
| +// listVersionsLocked is ListObjectVersions: every object under prefix as |
| +// its one, current version, in key order, at most max-keys (default 1000) |
| +// a page, resuming after key-marker. The caller holds f.mu. |
| +func (f *LockFixture) listVersionsLocked(w http.ResponseWriter, q url.Values) { |
| + prefix := q.Get("prefix") |
| + max := 1000 |
| + if s := q.Get("max-keys"); s != "" { |
| + n, err := strconv.Atoi(s) |
| + if err != nil || n <= 0 { |
| + s3error(w, http.StatusBadRequest, "InvalidArgument") |
| + return |
| + } |
| + max = n |
| + } |
| + after := q.Get("key-marker") |
| + var keys []string |
| + for k := range f.objects { |
| + if strings.HasPrefix(k, prefix) && k > after { |
| + keys = append(keys, k) |
| + } |
| + } |
| + sort.Strings(keys) |
| + res := listVersionsResult{Name: f.Bucket, Prefix: prefix, KeyMarker: after, MaxKeys: max} |
| + if len(keys) > max { |
| + keys, res.IsTruncated = keys[:max], true |
| + res.NextKeyMarker = keys[max-1] |
| + res.NextVersionIdMarker = f.objects[keys[max-1]].version |
| + } |
| + for _, k := range keys { |
| + o := f.objects[k] |
| + res.Versions = append(res.Versions, listVersion{Key: k, VersionId: o.version, IsLatest: true, |
| + LastModified: o.modified.Format(time.RFC3339), ETag: o.etag, Size: len(o.body)}) |
| + } |
| + w.Header().Set("Content-Type", "application/xml") |
| + io.WriteString(w, xml.Header) |
| + xml.NewEncoder(w).Encode(res) |
| +} |
diff --git a/internal/lease/locktest/fixture_test.go b/internal/lease/locktest/fixture_test.go| index 24c7b2aa4..3a3da83e0 100644 |
| --- a/internal/lease/locktest/fixture_test.go |
| +++ b/internal/lease/locktest/fixture_test.go |
| @@ -110,3 +110,37 @@ func TestLockFixtureMatchingFaultAndLateAck(t *testing.T) { |
| t.Fatalf("after-write hook: %d, write visible %v", st, visible) |
| } |
| } |
| + |
| +// Every object lists as its one current version, and a copy names the |
| +// source's current version: a storage-generations take's listing and |
| +// copies run against the fixture. |
| +func TestLockFixtureListsVersionsAndCopies(t *testing.T) { |
| + f := NewLockFixture(t) |
| + f.PutObject("p/0000/a.ltx", []byte("one")) |
| + f.PutObject("p/0000/b.ltx", []byte("two")) |
| + f.PutObject("q/x", []byte("other")) |
| + st, body, _ := do(t, f, "GET", "/locks?versions&prefix=p/", nil, "") |
| + if st != 200 || !strings.Contains(body, "<ListVersionsResult") || strings.Count(body, "<Version>") != 2 || strings.Contains(body, "q/x") || !strings.Contains(body, "<IsLatest>true</IsLatest>") { |
| + t.Fatalf("list versions %d %s", st, body) |
| + } |
| + if st, body, _ := do(t, f, "GET", "/locks?versions&prefix=p/&max-keys=1", nil, ""); st != 200 || strings.Count(body, "<Version>") != 1 || !strings.Contains(body, "<IsTruncated>true</IsTruncated>") || !strings.Contains(body, "<NextKeyMarker>p/0000/a.ltx</NextKeyMarker>") { |
| + t.Fatalf("a page %d %s", st, body) |
| + } |
| + if st, body, _ := do(t, f, "GET", "/locks?versions&prefix=p/&key-marker=p/0000/a.ltx", nil, ""); st != 200 || !strings.Contains(body, "p/0000/b.ltx") || strings.Contains(body, "p/0000/a.ltx</Key>") { |
| + t.Fatalf("the next page %d %s", st, body) |
| + } |
| + v := f.objects["p/0000/a.ltx"].version |
| + if st, _, _ := do(t, f, "PUT", "/locks/g/0000/a.ltx", map[string]string{"x-amz-copy-source": "locks/p/0000/a.ltx?versionId=v0"}, ""); st != 404 { |
| + t.Fatalf("a copy of a version that is not current: %d", st) |
| + } |
| + if st, _, _ := do(t, f, "PUT", "/locks/g/0000/a.ltx", map[string]string{"x-amz-copy-source": "locks/p/0000/a.ltx?versionId=" + v, "If-None-Match": "*"}, ""); st != 200 || string(f.objects["g/0000/a.ltx"].body) != "one" { |
| + t.Fatalf("copy %d", st) |
| + } |
| + if st, _, _ := do(t, f, "PUT", "/locks/g/0000/a.ltx", map[string]string{"x-amz-copy-source": "locks/p/0000/b.ltx?versionId=" + f.objects["p/0000/b.ltx"].version, "If-None-Match": "*"}, ""); st != 412 || string(f.objects["g/0000/a.ltx"].body) != "one" { |
| + t.Fatalf("a create-only copy over a present key: %d", st) |
| + } |
| + reqs := strings.Join(f.Requests(), ",") |
| + if !strings.Contains(reqs, "LISTV p/") || !strings.Contains(reqs, "COPY g/0000/a.ltx") { |
| + t.Fatalf("request log %s", reqs) |
| + } |
| +} |