region HA P1a Task 10: entry-owned files publisher; marker only after a proven stop and an empty host slice
An HA wake opens the host's files publisher once its replica runs (a failure fails the wake, releasing an unclean marker) and runs it on the service's lifetime: the trio and wake state every second, app files as a 15-minute snapshot. finishStop's HA arm (releaseHAClean) needs an empty host slice, then stops and joins the publisher, makes the final publish, the final sync, the local record and the marker, clean only when all held. A stream-class HA host captures its WAL every second. The sweep retries owed markers through lease.RetryPending. cleanupFailedWake stops the publisher first.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+1,410
−8
internal/activator/activator.go+52 −6internal/activator/backend_unit.go+37 −0internal/activator/hafiles.go+316 −0internal/activator/hafiles_test.go+68 −0internal/activator/harelease.go+216 −0internal/activator/harelease_test.go+713 −0internal/activator/maintenance.go+8 −2
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 22ce0d155..7e0571bdf 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -539,6 +539,16 @@ type actEntry struct { |
| rep Rep |
| proc Proc |
| + // files is an HA host's files publisher (region HA P1a, hafiles.go), |
| + // opened by the wake once its replica runs, and run on the service's |
| + // lifetime until filesStop cancels it and filesDone closes. The stop |
| + // stops and joins it before its final publish (releaseHAClean), and a |
| + // failed wake before its replica is closed (cleanupFailedWake). All |
| + // three are written under a.mu; nil for every other host. |
| + files *hostFiles |
| + filesStop context.CancelFunc |
| + filesDone chan struct{} |
| + |
| // Convergence: the `live/<host>` symlink target this child was spawned |
| // against. A running process never re-reads the symlink, so once a ship |
| // repoints it, an awake child keeps serving the old build until it's |
| @@ -1219,6 +1229,9 @@ type Service struct { |
| // is the wrong trade there. |
| lifeCtx context.Context |
| lifeStop context.CancelFunc |
| + // markers is the sweep's retry of owed region HA release markers |
| + // (retryOwedMarkers). |
| + markers markerRetry |
| mu sync.Mutex |
| entries map[string]*actEntry |
| @@ -2620,7 +2633,7 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| w.legacyUncertain = legacyStartMayRun(err) |
| switch { |
| case proc != nil || w.genUnproven || w.legacyUncertain: |
| - a.cleanupFailedWake(ctx, rt, w, lease) |
| + a.cleanupFailedWake(ctx, e, rt, w, lease) |
| case launchNotStarted(err) && wakeStartedNothing(w): |
| // A start its pre-exec gate refused ran nothing, and this wake |
| // has started nothing else: its seed (step 3) has finished, and |
| @@ -2632,7 +2645,7 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| case launchNotStarted(err): |
| // Something of this wake is running after all: it goes through |
| // the failed wake's cleanup and its proofs, not the shortcut. |
| - a.cleanupFailedWake(ctx, rt, w, lease) |
| + a.cleanupFailedWake(ctx, e, rt, w, lease) |
| default: |
| w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease) |
| } |
| @@ -2653,14 +2666,14 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| // (plannedWorkerReady, spec §6.5). |
| if e.worker && !plan.planned() { |
| if serr := a.awaitWorkerSettle(ctx, e, proc); serr != nil { |
| - a.cleanupFailedWake(ctx, rt, w, lease) |
| + a.cleanupFailedWake(ctx, e, rt, w, lease) |
| return w, fmt.Errorf("start %s: %w", host, serr) |
| } |
| w.steps.mark(a.now(), "settle") |
| } |
| if ctx.Err() != nil || !a.wakeAllowed(host) { |
| - a.cleanupFailedWake(ctx, rt, w, lease) |
| + a.cleanupFailedWake(ctx, e, rt, w, lease) |
| return w, ErrFenced |
| } |
| // 5. Trade the held lease for running replication, at the route's |
| @@ -2668,12 +2681,29 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| // The DB path rides the route; when empty the backend defaults it to |
| // <DataDir>/<host>.db internally (Eleven defaulted here via a package |
| // global — base dirs are backend fields now). |
| + // |
| + // An HA host of the stream class captures its WAL every second (the |
| + // global cadence, A16), not litestream's 10 s monitor default. |
| + if hl, ok := lease.(haLease); ok && hl.HA() && replicationSyncInterval(rt.Replication) == 0 { |
| + hl.SetMonitorInterval(time.Second) |
| + } |
| rep, err := lease.Replicate(ctx, rt.DBPath, replicationSyncInterval(rt.Replication)) |
| w.rep = rep |
| if err != nil { |
| - a.cleanupFailedWake(ctx, rt, w, lease) |
| + a.cleanupFailedWake(ctx, e, rt, w, lease) |
| return w, fmt.Errorf("replicate %s: %w", host, err) |
| } |
| + // 5a. An HA host's files publisher, owned by the entry and run on the |
| + // service's lifetime (region HA P1a): an HA host never serves without |
| + // its files published, so a publisher that will not open fails the |
| + // wake, and its release is an unclean marker. |
| + if hr, ok := rep.(haRep); ok && hr.HA() { |
| + if err := a.openEntryFiles(ctx, e, rt); err != nil { |
| + a.cleanupFailedWake(ctx, e, rt, w, lease) |
| + return w, fmt.Errorf("files %s: %w", host, err) |
| + } |
| + a.startFiles(e) |
| + } |
| // 5b. A seeded row's first upload, then its record (spec §3.4 step 5). |
| // A failure here does not fail the wake: the instance is serving from |
| @@ -4450,7 +4480,20 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| defer cancel() |
| repErr := ErrStopUnproven |
| - if e.rep != nil { |
| + if _, ha := haEntryRep(e); ha { |
| + // An HA host releases with a marker, written last and only over a |
| + // proven stop and an empty host slice (releaseHAClean, r3.2). |
| + // Unproven, nothing is written: the stop stays pending, with the |
| + // lease held and renewing, and the sweep finishes it once proven. |
| + repErr = a.releaseHAClean(ctx, e) |
| + if errors.Is(repErr, errHostSliceUnproven) { |
| + log.Printf("activator: stop %s: %v; keeping replication and the lease until it is", e.host, repErr) |
| + a.mu.Lock() |
| + a.keepPendingLocked(e, outcome) |
| + a.mu.Unlock() |
| + return |
| + } |
| + } else if e.rep != nil { |
| repErr = e.rep.Close(ctx) |
| } |
| outcome.replicaClosed = repErr == nil |
| @@ -4585,6 +4628,9 @@ func (a *Service) markCleanParkLocked(e *actEntry) { |
| // delivery has come due. |
| func (a *Service) sweepOnce() { |
| now := a.now() |
| + // Owed release markers (region HA P1a): lease retries each on its own |
| + // spacing; one retry pass at a time, off a.mu. |
| + a.retryOwedMarkers() |
| // The due query runs before the lock — it's a registry read, and nothing |
| // under a.mu should wait on SQLite. |
| dueRoutes, err := a.due.DueInstances(now.Unix()) |
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go| index ef1128995..dea58c65e 100644 |
| --- a/internal/activator/backend_unit.go |
| +++ b/internal/activator/backend_unit.go |
| @@ -57,6 +57,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -342,6 +343,42 @@ func (b *SplitBackend) restoredReplication(rt registry.Route) (string, bool) { |
| } |
| return "", false |
| } |
| + |
| +// openHostFiles, hostSliceEmpty, haReleaseBase and writeHARecord dispatch |
| +// like Restore (region HA P1a, hafiles.go and harelease.go). A half that |
| +// cannot answer refuses: a unit row is never HA. |
| +func (b *SplitBackend) openHostFiles(ctx context.Context, rt registry.Route) (*hostFiles, error) { |
| + if o, ok := b.pick(rt).(haFilesOpener); ok { |
| + return o.openHostFiles(ctx, rt) |
| + } |
| + return nil, errors.New("this row's backend cannot publish an HA host's files") |
| +} |
| +func (b *SplitBackend) hostSliceEmpty(rt registry.Route) (bool, error) { |
| + if r, ok := b.pick(rt).(haReleaser); ok { |
| + return r.hostSliceEmpty(rt) |
| + } |
| + return false, errors.New("this row's backend has no host slice to read") |
| +} |
| +func (b *SplitBackend) haReleaseBase(rt registry.Route) hafresh.Marker { |
| + if r, ok := b.pick(rt).(haReleaser); ok { |
| + return r.haReleaseBase(rt) |
| + } |
| + return hafresh.Marker{V: 1} |
| +} |
| +func (b *SplitBackend) writeHARecord(rt registry.Route, m hafresh.Marker) error { |
| + if r, ok := b.pick(rt).(haReleaser); ok { |
| + return r.writeHARecord(rt, m) |
| + } |
| + return errors.New("this row's backend keeps no release record") |
| +} |
| + |
| +var ( |
| + _ haFilesOpener = (*SplitBackend)(nil) |
| + _ haReleaser = (*SplitBackend)(nil) |
| + _ haFilesOpener = (*ExecBackend)(nil) |
| + _ haReleaser = (*ExecBackend)(nil) |
| +) |
| + |
| func (b *SplitBackend) Seed(ctx context.Context, rt registry.Route) error { |
| return b.pick(rt).Seed(ctx, rt) |
| } |
diff --git a/internal/activator/hafiles.go b/internal/activator/hafiles.go| new file mode 100644 |
| index 000000000..cc090f94c |
| --- /dev/null |
| +++ b/internal/activator/hafiles.go |
| @@ -0,0 +1,316 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io/fs" |
| + "log" |
| + "os" |
| + "path/filepath" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hostfiles" |
| + "github.com/carlosframework/platform/internal/instancefs" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Region HA P1a, files publication (spec §8.2): while an HA host is awake |
| +// its entry owns one publisher of the host's files, under its hibernate |
| +// prefix's files/0/. The H6 trio (instance.key and report.token at the |
| +// root of the files directory, and <host>.env as the manifest's env item) |
| +// and the wake state publish within about a second of a change, on every |
| +// plan; the app's files publish as a snapshot every |
| +// files_snapshot_interval (snapshot only in P1a). At sleep the entry stops |
| +// the publisher, joins it, and makes one final full publish (Final), whose |
| +// completeness decides whether the release marker can say clean. |
| + |
| +const ( |
| + // haPlatformEvery is the trio's and the wake state's cadence. |
| + haPlatformEvery = time.Second |
| + // haSnapshotEvery is files_snapshot_interval's default (spec §8.3): |
| + // a full publish of the app's files, when the tree changed. |
| + haSnapshotEvery = 15 * time.Minute |
| + // haEnvReadLimit bounds the env file read: it is tenant-writable. |
| + haEnvReadLimit = 1 << 20 |
| +) |
| + |
| +// haTrio is the H6 trio's members inside the files directory: the instance |
| +// key and the report token, at its root (hostrelocate.InstanceKeyPath). |
| +// The third, <host>.env, lives beside the directory and publishes as the |
| +// env item. |
| +var haTrio = map[string]bool{"instance.key": true, "report.token": true} |
| + |
| +// trioOnly is the platform pass's skip: everything but the trio, so a pass |
| +// lists the files directory's root and reads nothing else. |
| +func trioOnly(rel string, isDir bool) bool { return isDir || !haTrio[rel] } |
| + |
| +// hostFiles is one HA host's files publisher, owned by its awake entry. |
| +// Every pass holds mu, so Run's passes, PublishPlatformNow and Final never |
| +// interleave. |
| +type hostFiles struct { |
| + pub *hostfiles.Publisher |
| + paths instancePaths |
| + host string |
| + reg *registry.Registry |
| + |
| + platformEvery, snapshotEvery time.Duration |
| + |
| + mu sync.Mutex |
| + lastDigest string // the tree digest the last full publish committed |
| + final bool // Final has run: no pass publishes again |
| +} |
| + |
| +// errFilesFinal refuses a pass after Final: the release marker is the |
| +// last write, so nothing publishes once the final publish has been made. |
| +var errFilesFinal = errors.New("the host's files were published for the last time") |
| + |
| +// openHostFiles opens rt's files publisher over the manifest under |
| +// filesPrefix (one GET). The store is FilesStore, the one the HA restore |
| +// reads (lease.NewFilesStore in production). Only an HA host in the nested |
| +// layout has one. |
| +func (b *ExecBackend) openHostFiles(ctx context.Context, rt registry.Route) (*hostFiles, error) { |
| + if b.FilesStore == nil { |
| + return nil, errors.New("no files store configured") |
| + } |
| + p := b.pathsFor(rt) |
| + if p.layout != LayoutNested { |
| + return nil, fmt.Errorf("the row's layout is %s, not nested", p.layout) |
| + } |
| + pub, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &hostFiles{pub: pub, paths: p, host: rt.Host, reg: b.Registry, |
| + platformEvery: haPlatformEvery, snapshotEvery: haSnapshotEvery}, nil |
| +} |
| + |
| +// Run publishes until ctx ends: the trio and the wake state every |
| +// platformEvery when they changed, the whole tree every snapshotEvery when |
| +// its digest changed. A failed pass is logged and retried at the next |
| +// tick; a superseded manifest (another writer) stops Run, and Final then |
| +// fails, so the release is not clean. |
| +func (f *hostFiles) Run(ctx context.Context) { |
| + platform := time.NewTicker(f.platformEvery) |
| + defer platform.Stop() |
| + snapshot := time.NewTicker(f.snapshotEvery) |
| + defer snapshot.Stop() |
| + failing := "" |
| + for { |
| + var err error |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-platform.C: |
| + err = f.PublishPlatformNow(ctx) |
| + case <-snapshot.C: |
| + err = f.publishSnapshot(ctx) |
| + } |
| + if ctx.Err() != nil || errors.Is(err, errFilesFinal) { |
| + return |
| + } |
| + if errors.Is(err, hostfiles.ErrSuperseded) { |
| + log.Printf("activator: %s: files: %v; publishing stops, and this release will not be clean", f.host, err) |
| + return |
| + } |
| + switch { |
| + case err != nil && err.Error() != failing: |
| + failing = err.Error() |
| + log.Printf("activator: %s: files publish failing, retrying: %v", f.host, err) |
| + case err == nil && failing != "": |
| + failing = "" |
| + log.Printf("activator: %s: files publish recovered", f.host) |
| + } |
| + } |
| +} |
| + |
| +// PublishPlatformNow publishes the trio, the env item and the wake state |
| +// now, and commits if anything changed (nothing changed, no request). |
| +func (f *hostFiles) PublishPlatformNow(ctx context.Context) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.final { |
| + return errFilesFinal |
| + } |
| + if _, _, err := f.syncLocked(ctx, trioOnly); err != nil { |
| + return err |
| + } |
| + if err := f.stageItemsLocked(ctx); err != nil { |
| + return err |
| + } |
| + _, err := f.pub.Commit(ctx) |
| + return err |
| +} |
| + |
| +// publishSnapshot is the snapshot pass: the whole tree and the platform |
| +// items, skipped when the tree's metadata digest is the one the last full |
| +// publish committed (where the digest cannot be read, it always runs). |
| +func (f *hostFiles) publishSnapshot(ctx context.Context) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.final { |
| + return errFilesFinal |
| + } |
| + digest, derr := treeDigest(hostFilesDir(f.paths, f.host), f.paths.envFile) |
| + if derr == nil && digest != "" && digest == f.lastDigest { |
| + return nil |
| + } |
| + if _, _, err := f.syncLocked(ctx, nil); err != nil { |
| + return err |
| + } |
| + if err := f.stageItemsLocked(ctx); err != nil { |
| + return err |
| + } |
| + if _, err := f.pub.Commit(ctx); err != nil { |
| + return err |
| + } |
| + if derr == nil { |
| + f.lastDigest = digest |
| + } |
| + return nil |
| +} |
| + |
| +// Final is the last publish: the whole tree and the platform items, |
| +// committed. gen is the committed revision (Publisher.Gen), the marker's |
| +// files_gen. complete holds only when the pass was complete |
| +// (SyncStats.Complete), the platform items were read and the commit |
| +// landed. A files directory that is absent is complete only while the |
| +// manifest holds no file, since absence proves nothing about one it does. |
| +// After Final no pass publishes. |
| +func (f *hostFiles) Final(ctx context.Context) (gen string, complete bool, err error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.final = true |
| + st, present, err := f.syncLocked(ctx, nil) |
| + if err != nil { |
| + return f.pub.Gen(), false, err |
| + } |
| + complete = st.Complete() |
| + if !present && len(f.pub.Paths()) > 0 { |
| + complete = false |
| + log.Printf("activator: %s: files: the files directory is gone while the manifest holds %d file(s); the release is not clean", f.host, len(f.pub.Paths())) |
| + } |
| + if !st.Complete() { |
| + log.Printf("activator: %s: files: the final publish is not complete (too large %q, not regular %q, unreadable %q, replaced %q, torn %q); the release is not clean", |
| + f.host, st.TooLarge, st.NotRegular, st.Unreadable, st.Retry, st.Torn) |
| + } |
| + if err := f.stageItemsLocked(ctx); err != nil { |
| + return f.pub.Gen(), false, err |
| + } |
| + if _, err := f.pub.Commit(ctx); err != nil { |
| + return f.pub.Gen(), false, err |
| + } |
| + return f.pub.Gen(), complete, nil |
| +} |
| + |
| +// syncLocked syncs the files directory (skip as SyncDirAt takes it), |
| +// opened beneath the instance directory without following a link: the |
| +// directory is the tenant's to write. present is false when there is no |
| +// files directory, and nothing is staged then. f.mu is held. |
| +func (f *hostFiles) syncLocked(ctx context.Context, skip func(string, bool) bool) (hostfiles.SyncStats, bool, error) { |
| + root, err := instancefs.OpenDirBeneath(f.paths.dataDir, f.host) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + return hostfiles.SyncStats{}, false, nil |
| + } |
| + if err != nil { |
| + return hostfiles.SyncStats{}, false, fmt.Errorf("open the files directory: %w", err) |
| + } |
| + defer root.Close() |
| + st, err := hostfiles.SyncDirAt(ctx, f.pub, root, skip) |
| + return st, true, err |
| +} |
| + |
| +// stageItemsLocked stages the env item (<host>.env, read beneath its |
| +// directory; absent, the item is deleted) and the wake state from the |
| +// registry. f.mu is held. |
| +func (f *hostFiles) stageItemsLocked(ctx context.Context) error { |
| + dir, name := filepath.Dir(f.paths.envFile), filepath.Base(f.paths.envFile) |
| + env, absent, err := instancefs.ReadBeneathLimitOrAbsent(dir, name, haEnvReadLimit) |
| + switch { |
| + case err != nil && !errors.Is(err, os.ErrNotExist): |
| + return fmt.Errorf("read %s: %w", name, err) |
| + case absent || err != nil: |
| + if err := f.pub.StagePlatformDelete(hostfiles.EnvItem); err != nil { |
| + return err |
| + } |
| + default: |
| + if err := f.pub.StagePlatform(ctx, hostfiles.EnvItem, env); err != nil { |
| + return err |
| + } |
| + } |
| + if f.reg == nil { |
| + return nil |
| + } |
| + ws, err := hostfiles.ExportWake(f.reg, f.host) |
| + if err != nil { |
| + return fmt.Errorf("wake state: %w", err) |
| + } |
| + return hostfiles.StageWake(ctx, f.pub, ws) |
| +} |
| + |
| +// haFilesOpener is the Backend capability doWake asks for an HA host's |
| +// files publisher (ExecBackend's; SplitBackend dispatches it). |
| +type haFilesOpener interface { |
| + openHostFiles(ctx context.Context, rt registry.Route) (*hostFiles, error) |
| +} |
| + |
| +// openEntryFiles opens and attaches e's files publisher, for a wake that |
| +// replicates an HA lease. A backend that cannot open one fails the wake: |
| +// an HA host never serves without its files published. |
| +func (a *Service) openEntryFiles(ctx context.Context, e *actEntry, rt registry.Route) error { |
| + o, ok := a.backend.(haFilesOpener) |
| + if !ok { |
| + return errors.New("this backend cannot publish an HA host's files") |
| + } |
| + f, err := o.openHostFiles(ctx, rt) |
| + if err != nil { |
| + return err |
| + } |
| + a.mu.Lock() |
| + e.files = f |
| + a.mu.Unlock() |
| + return nil |
| +} |
| + |
| +// startFiles runs e's files publisher on the service's lifetime context |
| +// until stopFiles. A second call, or an entry with no publisher, does |
| +// nothing. |
| +func (a *Service) startFiles(e *actEntry) { |
| + a.mu.Lock() |
| + f := e.files |
| + if f == nil || e.filesDone != nil { |
| + a.mu.Unlock() |
| + return |
| + } |
| + ctx, cancel := context.WithCancel(a.life()) |
| + done := make(chan struct{}) |
| + e.filesStop, e.filesDone = cancel, done |
| + a.mu.Unlock() |
| + go func() { |
| + defer close(done) |
| + f.Run(ctx) |
| + }() |
| +} |
| + |
| +// stopFiles cancels e's files publisher and waits until it has returned, |
| +// so no pass of it runs after this. With none running it returns at once. |
| +func (a *Service) stopFiles(e *actEntry) { |
| + a.mu.Lock() |
| + cancel, done := e.filesStop, e.filesDone |
| + a.mu.Unlock() |
| + if cancel == nil { |
| + return |
| + } |
| + cancel() |
| + <-done |
| +} |
| + |
| +// life is the service's lifetime context; Background for a Service not |
| +// built by New. |
| +func (a *Service) life() context.Context { |
| + if a.lifeCtx == nil { |
| + return context.Background() |
| + } |
| + return a.lifeCtx |
| +} |
diff --git a/internal/activator/hafiles_test.go b/internal/activator/hafiles_test.go| new file mode 100644 |
| index 000000000..e8e944439 |
| --- /dev/null |
| +++ b/internal/activator/hafiles_test.go |
| @@ -0,0 +1,68 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hostfiles" |
| +) |
| + |
| +// The trio and the wake state publish within about a second; the app's |
| +// files wait for the snapshot interval. |
| +func TestTrioPublishedWithinOneSecond(t *testing.T) { |
| + b, rt := haBackend(t, "shop.example.com") |
| + f, err := b.openHostFiles(context.Background(), rt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.snapshotEvery = time.Hour |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + go f.Run(ctx) |
| + p := b.pathsFor(rt) |
| + writeFiles(t, b, rt, map[string]string{"a.txt": "app", "instance.key": "k1"}) |
| + if err := os.WriteFile(p.envFile, []byte("CARLOS_INSTANCE_KEY=k1\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + load := func() hostfiles.Manifest { |
| + m, _, err := hostfiles.Load(context.Background(), b.FilesStore, b.filesPrefix(rt.Host)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return m |
| + } |
| + deadline := time.Now().Add(2 * time.Second) |
| + for { |
| + m := load() |
| + _, env := m.Platform[hostfiles.EnvItem] |
| + _, wake := m.Platform[hostfiles.WakeItem] |
| + if env && wake && m.Entries["instance.key"].Object != "" { |
| + body, err := hostfiles.ReadPlatform(context.Background(), b.FilesStore, b.filesPrefix(rt.Host), m, hostfiles.EnvItem, nil) |
| + if err != nil || string(body) != "CARLOS_INSTANCE_KEY=k1\n" { |
| + t.Fatalf("env item %q, %v", body, err) |
| + } |
| + if _, ok := m.Entries["a.txt"]; ok { |
| + t.Fatal("an app file published on the trio's cadence") |
| + } |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("the trio and wake state were not published within the deadline: %+v", m) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + |
| + // The snapshot cadence publishes the app's files. |
| + f2, err := b.openHostFiles(context.Background(), rt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cancel() |
| + f2.platformEvery, f2.snapshotEvery = time.Hour, 200*time.Millisecond |
| + ctx2, cancel2 := context.WithCancel(context.Background()) |
| + defer cancel2() |
| + go f2.Run(ctx2) |
| + waitFor(t, "the snapshot of a.txt", func() bool { return load().Entries["a.txt"].Object != "" }) |
| +} |
diff --git a/internal/activator/harelease.go b/internal/activator/harelease.go| new file mode 100644 |
| index 000000000..e18a843fe |
| --- /dev/null |
| +++ b/internal/activator/harelease.go |
| @@ -0,0 +1,216 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Region HA P1a, the clean release (spec §5.2, r3.2): an HA entry's stop |
| +// ends with a release marker, never a delete, and the marker is the last |
| +// write the box makes for the host. It is written only after the entry's |
| +// stop has been proven (finishStop runs only then) and the host's slice is |
| +// read empty, and after the files publisher has stopped and made its final |
| +// publish and the replica its final sync. |
| + |
| +// errHostSliceUnproven is a release held back because the host's slice was |
| +// not read empty: something of the host may still run. The stop stays |
| +// pending, with the lease held and renewing, and the sweep tries again. |
| +var errHostSliceUnproven = errors.New("the host's slice is not proven empty") |
| + |
| +// The release's budgets beside finishStop's own: the final files publish, |
| +// and the marker's PUT. |
| +const ( |
| + haFinalFilesBudget = 2 * time.Minute |
| + haMarkerBudget = 10 * time.Second |
| +) |
| + |
| +// haReleaser is the backend half of an HA release (ExecBackend's; |
| +// SplitBackend dispatches it). |
| +type haReleaser interface { |
| + hostSliceEmpty(rt registry.Route) (bool, error) |
| + haReleaseBase(rt registry.Route) hafresh.Marker |
| + writeHARecord(rt registry.Route, m hafresh.Marker) error |
| +} |
| + |
| +// hostSliceEmpty reads the host slice's cgroup.events |
| +// (CgroupEvents(instancectl.SliceName(host), "")): every nested unit of the |
| +// host, of every role, runs under that slice, and root checks systemd |
| +// placed it there before it starts anything, so one read covers them all. |
| +// An absent slice holds nothing: systemd removes a slice once its last unit |
| +// is gone. A read error is not empty. A row outside the nested layout has |
| +// no slice that proves anything, and is an error. |
| +func (b *ExecBackend) hostSliceEmpty(rt registry.Route) (bool, error) { |
| + if rt.Backing == registry.BackingUnit { |
| + return false, errors.New("the row is unit-backed") |
| + } |
| + if p := b.pathsFor(rt); p.layout != LayoutNested { |
| + return false, fmt.Errorf("the row's layout is %s, not nested", p.layout) |
| + } |
| + events := b.CgroupEvents |
| + if events == nil { |
| + events = cgroupEventsUnder(b.cgroupRoot()) |
| + } |
| + exists, populated, err := events(instancectl.SliceName(rt.Host), "") |
| + if err != nil { |
| + return false, err |
| + } |
| + return !exists || !populated, nil |
| +} |
| + |
| +// haReleaseBase is the marker's identity for rt: this box (its reference |
| +// and instance id now) and the lifetime the host's HA acquire classified |
| +// with. An empty field is filled from the lease's own base by |
| +// ReleaseMarker. |
| +func (b *ExecBackend) haReleaseBase(rt registry.Route) hafresh.Marker { |
| + self := b.self() |
| + m := hafresh.Marker{V: 1, Box: self.Ref, IID: self.IID} |
| + if s, ok := b.haAcquired(rt.Host); ok { |
| + m.Lifetime = s.entry.ID |
| + } |
| + return m |
| +} |
| + |
| +// writeHARecord writes the host's local release record for m: the marker, |
| +// and the database, WAL and files tree as they are now (readLocalNow). A |
| +// clean release first checkpoints the WAL into the database and truncates |
| +// it (lease.TruncateWAL; every writer is proven stopped and the replica |
| +// closed by now), so the record can show it empty, as a keep needs. A |
| +// checkpoint that fails is logged and the record says the WAL is not |
| +// empty: that copy is never kept. |
| +func (b *ExecBackend) writeHARecord(rt registry.Route, m hafresh.Marker) error { |
| + p := b.pathsFor(rt) |
| + if m.Clean { |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| + err := lease.TruncateWAL(ctx, p.dbPath) |
| + cancel() |
| + if err != nil { |
| + log.Printf("activator: %s: checkpoint the database before its release record: %v (this copy will not be kept)", rt.Host, err) |
| + } |
| + } |
| + now, err := readLocalNow(p, rt.Host) |
| + if err != nil { |
| + return err |
| + } |
| + return writeReleaseRecord(p, rt.Host, hafresh.LocalRecord{Marker: m, DB: now.DB, WALEmpty: now.WALEmpty, TreeDigest: now.TreeDigest}) |
| +} |
| + |
| +// haEntryRep is e's replica as an HA one, if it is. |
| +func haEntryRep(e *actEntry) (haRep, bool) { |
| + r, ok := e.rep.(haRep) |
| + return r, ok && r.HA() |
| +} |
| + |
| +// releaseHAClean is an HA entry's release, in this order (r3.2): |
| +// |
| +// 1. the entry's stop has returned nil: finishStop runs only then; |
| +// 2. hostSliceEmpty is true. If not, or on a read error, nothing is |
| +// written and errHostSliceUnproven is returned: the lease stays held |
| +// and renewing, and the stop stays pending; |
| +// 3. stopFiles, then Final; |
| +// 4. Finish, then the local release record; |
| +// 5. ReleaseMarker, clean only when Final was complete, Finish succeeded |
| +// and the record was written. |
| +// |
| +// Any other error is returned for the log: the marker was still written, |
| +// or, if its PUT failed, lease has persisted the obligation |
| +// (*lease.ObligationError) and retries it. |
| +func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error { |
| + a.mu.Lock() |
| + rt, rep := e.route, e.rep |
| + a.mu.Unlock() |
| + hr, ok := rep.(haRep) |
| + if !ok || !hr.HA() { |
| + return errors.New("not an HA replica") |
| + } |
| + hb, ok := a.backend.(haReleaser) |
| + if !ok { |
| + return fmt.Errorf("%w: this backend cannot read it", errHostSliceUnproven) |
| + } |
| + empty, err := hb.hostSliceEmpty(rt) |
| + if err != nil { |
| + return fmt.Errorf("%w: %v", errHostSliceUnproven, err) |
| + } |
| + if !empty { |
| + return fmt.Errorf("%w: it holds a process", errHostSliceUnproven) |
| + } |
| + a.stopFiles(e) |
| + a.mu.Lock() |
| + f := e.files |
| + a.mu.Unlock() |
| + gen, complete, ferr := "", false, errors.New("the entry has no files publisher") |
| + if f != nil { |
| + // A budget of its own: a large tree's final read must not eat the |
| + // final sync's. |
| + fctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), haFinalFilesBudget) |
| + gen, complete, ferr = f.Final(fctx) |
| + cancel() |
| + } |
| + txid, finErr := hr.Finish(ctx) |
| + m := hb.haReleaseBase(rt) |
| + m.TXID, m.FilesGen, m.At = txid, gen, time.Now().UTC() |
| + m.Clean = complete && ferr == nil && finErr == nil |
| + rerr := hb.writeHARecord(rt, m) |
| + if rerr != nil { |
| + // Without the record nothing could keep on this copy: the marker |
| + // says so too. |
| + m.Clean = false |
| + rerr = fmt.Errorf("release record: %w", rerr) |
| + } |
| + // The marker's PUT gets its own budget too, as Close's release does: |
| + // a final sync that ran long must not leave it a dead context. |
| + mctx, mcancel := context.WithTimeout(context.WithoutCancel(ctx), haMarkerBudget) |
| + merr := hr.ReleaseMarker(mctx, m) |
| + mcancel() |
| + if merr == nil { |
| + log.Printf("activator: %s: released with a marker (clean %v, txid %d, files %s)", rt.Host, m.Clean, txid, gen) |
| + } |
| + if ferr != nil { |
| + ferr = fmt.Errorf("files: %w", ferr) |
| + } |
| + if finErr != nil { |
| + finErr = fmt.Errorf("final sync: %w", finErr) |
| + } |
| + return errors.Join(ferr, finErr, rerr, merr) |
| +} |
| + |
| +// retryPendingMarkers is the sweep's retry of every owed release marker |
| +// (lease.RetryPending: one PUT each, a minute after its failure, doubling |
| +// to ten minutes apart, the in-memory-only ones written to disk first). |
| +// A seam, so a test can see the sweep call it. |
| +var retryPendingMarkers = lease.RetryPending |
| + |
| +// markerRetry is the sweep's one RetryPending in flight, and when it last |
| +// logged a failure. |
| +type markerRetry struct { |
| + running atomic.Bool |
| + lastLog atomic.Int64 |
| +} |
| + |
| +// retryOwedMarkers starts one RetryPending off the sweep, unless one is |
| +// still running. Never called with a.mu held. |
| +func (a *Service) retryOwedMarkers() { |
| + if !a.markers.running.CompareAndSwap(false, true) { |
| + return |
| + } |
| + go func() { |
| + defer a.markers.running.Store(false) |
| + ctx, cancel := context.WithTimeout(a.life(), time.Minute) |
| + defer cancel() |
| + if err := retryPendingMarkers(ctx); err != nil { |
| + now := time.Now().UnixNano() |
| + if last := a.markers.lastLog.Load(); now-last >= int64(time.Minute) { |
| + a.markers.lastLog.Store(now) |
| + log.Printf("activator: owed release markers: %v", err) |
| + } |
| + } |
| + }() |
| +} |
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go| new file mode 100644 |
| index 000000000..06e407ead |
| --- /dev/null |
| +++ b/internal/activator/harelease_test.go |
| @@ -0,0 +1,713 @@ |
| +package activator |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/hostfiles" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// haUnit is the nested host as systemd and cgroupfs would show it: the |
| +// instance unit's state and cgroup, and the host slice's cgroup, behind |
| +// the UnitState and CgroupEvents seams the real unitProc observer reads. |
| +type haUnit struct { |
| + mu sync.Mutex |
| + active, inv string |
| + unitPop bool |
| + sliceExists bool |
| + slicePop bool |
| + sliceErr error |
| + // stuck: a stop leaves the unit active (the observer never proves it). |
| + stuck bool |
| + // sliceHeld: a stop leaves the host slice populated (a descendant |
| + // outlived the unit). |
| + sliceHeld bool |
| +} |
| + |
| +func (u *haUnit) state(context.Context, string) (string, string, error) { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + return u.active, u.inv, nil |
| +} |
| + |
| +func (u *haUnit) events(slice, unit string) (bool, bool, error) { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + if unit == "" { |
| + if u.sliceErr != nil { |
| + return true, true, u.sliceErr |
| + } |
| + return u.sliceExists, u.slicePop, nil |
| + } |
| + return u.active != "inactive", u.unitPop, nil |
| +} |
| + |
| +func (u *haUnit) started(inv string) { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + u.active, u.inv, u.unitPop, u.sliceExists, u.slicePop = "active", inv, true, true, true |
| +} |
| + |
| +func (u *haUnit) stopped() { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + if u.stuck { |
| + return |
| + } |
| + u.active, u.unitPop = "inactive", false |
| + if !u.sliceHeld { |
| + u.slicePop = false |
| + } |
| +} |
| + |
| +func (u *haUnit) set(f func(u *haUnit)) { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + f(u) |
| +} |
| + |
| +// haControl is root's control channel for the fixture: identityControl, |
| +// whose every stop (a generation's too) runs the stop hook. |
| +type haControl struct{ identityControl } |
| + |
| +func (c haControl) StopGen(ctx context.Context, host string, n uint64, kill bool) error { |
| + if err := c.identityControl.StopGen(ctx, host, n, kill); err != nil { |
| + return err |
| + } |
| + if c.stopHook != nil { |
| + c.stopHook(host, instancectl.RoleRun) |
| + } |
| + return nil |
| +} |
| + |
| +// lockWrite is one write that changed the lock: its method and the body |
| +// it left (nil after a delete). |
| +type lockWrite struct { |
| + method string |
| + body []byte |
| +} |
| + |
| +// haSvc is one box serving an HA host through the production wake and |
| +// stop: haBackend's real lease against the lock fixture, the files store |
| +// built by lease.NewFilesStore on the same fixture, the nested layout with |
| +// a fake root, and the real unitProc and observer under the UnitState and |
| +// CgroupEvents seams. |
| +type haSvc struct { |
| + t *testing.T |
| + a *Service |
| + b *ExecBackend |
| + rt registry.Route |
| + fx *locktest.LockFixture |
| + ctl *fakeControl |
| + unit *haUnit |
| + owedDir string |
| + |
| + mu sync.Mutex |
| + lockLog []lockWrite |
| +} |
| + |
| +func haService(t *testing.T, host string) *haSvc { |
| + t.Helper() |
| + b, rt := haBackend(t, host) |
| + h := haFixOf(b) |
| + // A short run directory, so the unix sockets beneath it fit whatever |
| + // the test's name. |
| + run, err := os.MkdirTemp("", "ha") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(run) }) |
| + b.RunDirOverride = run |
| + rt.Socket = nestedRoute(b, host).Socket |
| + if err := b.Registry.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + s := &haSvc{t: t, b: b, rt: rt, fx: h.fx, ctl: h.ctl, unit: &haUnit{}, owedDir: t.TempDir()} |
| + if err := lease.RestartObligationsForTest(s.owedDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + fs, err := lease.NewFilesStore(context.Background(), s.fx.Bucket, "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b.FilesStore = fs |
| + s.wire(b) |
| + stageLive(t, b, rt.Host, "v1") |
| + s.ctl.inv = "inv1" |
| + var serving []func() |
| + s.ctl.onStart = func() { |
| + if err := ensureDB(b.pathsFor(rt).dbPath); err != nil { |
| + t.Error(err) |
| + } |
| + s.unit.started("inv1") |
| + serving = append(serving, serveOK(t, rt.Socket)) |
| + } |
| + s.ctl.stopHook = func(string, instancectl.Role) { s.unit.stopped() } |
| + t.Cleanup(func() { |
| + for _, stop := range serving { |
| + stop() |
| + } |
| + }) |
| + // The lock's writes, in order, as they changed it (a fault-failed or |
| + // refused write changes nothing), kept beside haFix's count. |
| + key := lockKeyOf(b, rt) |
| + var before []byte |
| + s.fx.BeforeWrite(func(_, k string) { |
| + if k == key { |
| + s.mu.Lock() |
| + before = s.fx.LockBody(b.Cfg.hibernatePrefix(rt.Host)) |
| + s.mu.Unlock() |
| + } |
| + }) |
| + s.fx.AfterWrite(func(method, k string) { |
| + if k != key { |
| + return |
| + } |
| + after := s.fx.LockBody(b.Cfg.hibernatePrefix(rt.Host)) |
| + s.mu.Lock() |
| + changed := !bytes.Equal(after, before) |
| + if changed { |
| + s.lockLog = append(s.lockLog, lockWrite{method: method, body: after}) |
| + } |
| + s.mu.Unlock() |
| + if changed { |
| + h.mu.Lock() |
| + h.applied[k]++ |
| + h.mu.Unlock() |
| + } |
| + }) |
| + s.a = New(Config{Bucket: b.Cfg.Bucket, Idle: time.Hour}, b, b.Registry) |
| + return s |
| +} |
| + |
| +// wire gives b the fixture's nested seams. |
| +func (s *haSvc) wire(b *ExecBackend) { |
| + b.UnitState, b.CgroupEvents, b.ObservePoll = s.unit.state, s.unit.events, 20*time.Millisecond |
| + b.Control = haControl{identityControl{s.ctl}} |
| +} |
| + |
| +// ensureDB is the app's database, as a booting app leaves it. |
| +func ensureDB(path string) error { |
| + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { |
| + return err |
| + } |
| + db, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + return err |
| + } |
| + defer db.Close() |
| + _, err = db.Exec("create table if not exists t(x)") |
| + return err |
| +} |
| + |
| +// haServiceEntry is haService with the host woken: the awake entry. |
| +func haServiceEntry(t *testing.T, host string) (*haSvc, *actEntry) { |
| + t.Helper() |
| + s := haService(t, host) |
| + e, err := s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatalf("wake: %v\nroot was asked:\n%s", err, s.ctl.joined()) |
| + } |
| + return s, e |
| +} |
| + |
| +func (s *haSvc) wakeForTest(ctx context.Context) (*actEntry, error) { |
| + done, err := s.a.beginRequest(ctx, s.rt) |
| + if err != nil { |
| + return nil, err |
| + } |
| + done() |
| + s.a.mu.Lock() |
| + defer s.a.mu.Unlock() |
| + return s.a.entries[s.rt.Host], nil |
| +} |
| + |
| +// stopForTest stops e (an awake entry), or retries its pending stop, and |
| +// waits until the stop has finished or is pending. |
| +func (s *haSvc) stopForTest(e *actEntry) { |
| + s.t.Helper() |
| + s.a.mu.Lock() |
| + if e.state == actAwake { |
| + s.a.beginStopLocked(e, StopIdle) |
| + } else if e.pendingStop { |
| + e.pendingStop = false // finishPendingStops' own reap clears it; the wait below needs a fresh answer |
| + e.genReaping = true |
| + s.a.mu.Unlock() |
| + s.a.reapCurrentGen(e) |
| + s.a.mu.Lock() |
| + } |
| + s.a.mu.Unlock() |
| + deadline := time.Now().Add(30 * time.Second) |
| + for time.Now().Before(deadline) { |
| + select { |
| + case <-e.stopped: |
| + return |
| + default: |
| + } |
| + s.a.mu.Lock() |
| + pending := e.pendingStop && !e.genReaping |
| + s.a.mu.Unlock() |
| + if pending { |
| + return |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + s.t.Fatal("the stop neither finished nor went pending") |
| +} |
| + |
| +func (s *haSvc) stoppedFor(e *actEntry) bool { |
| + select { |
| + case <-e.stopped: |
| + return true |
| + default: |
| + return false |
| + } |
| +} |
| + |
| +// restart is the agent restarted on the same box: a new backend and |
| +// Service over the same data, registry, index and fixture, and lease's |
| +// obligation store loaded again from its directory (memory dropped). |
| +func (s *haSvc) restart(t *testing.T) *haSvc { |
| + t.Helper() |
| + if err := lease.RestartObligationsForTest(s.owedDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + old := s.b |
| + b := testExecBackend(t) |
| + b.Cfg = old.Cfg |
| + b.OptDir, b.DataDir, b.RunDirOverride = old.OptDir, old.DataDir, old.RunDirOverride |
| + b.StartupSwept, b.FilesStore, b.Lifetimes, b.Registry = old.StartupSwept, old.FilesStore, old.Lifetimes, old.Registry |
| + haFixtures.Store(b, haFixOf(old)) |
| + t.Cleanup(func() { haFixtures.Delete(b) }) |
| + s2 := &haSvc{t: t, b: b, rt: s.rt, fx: s.fx, ctl: s.ctl, unit: s.unit, owedDir: s.owedDir} |
| + s2.wire(b) |
| + s2.a = New(Config{Bucket: b.Cfg.Bucket, Idle: time.Hour}, b, b.Registry) |
| + return s2 |
| +} |
| + |
| +func (s *haSvc) lockKey() string { return lockKeyOf(s.b, s.rt) } |
| + |
| +// lockWriteLog is every write that changed the host's lock, in order. |
| +func (s *haSvc) lockWriteLog() []lockWrite { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return append([]lockWrite(nil), s.lockLog...) |
| +} |
| + |
| +// lockWriteLogOf is lockWriteLog across a restart: both services share |
| +// the first one's log. |
| +func lockWriteLogOf(s *haSvc) []lockWrite { return s.lockWriteLog() } |
| + |
| +func (s *haSvc) lockView(t *testing.T) hafresh.View { |
| + t.Helper() |
| + body := s.fx.LockBody(s.b.Cfg.hibernatePrefix(s.rt.Host)) |
| + if body == nil { |
| + return hafresh.View{Absent: true} |
| + } |
| + v, err := hafresh.DecodeLock(body, "x") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return v |
| +} |
| + |
| +// storeWrites is every write request the store saw, in order: "PUT key" |
| +// or "DELETE key". |
| +func (s *haSvc) storeWrites() []string { |
| + var out []string |
| + for _, r := range s.fx.Requests() { |
| + if strings.HasPrefix(r, "PUT ") || strings.HasPrefix(r, "DELETE ") { |
| + out = append(out, r) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// failMarkerPuts fails the next n marker PUTs on the lock with a 403 (the |
| +// SDK does not retry it), matched on the body so no renewal uses one up. |
| +func (s *haSvc) failMarkerPuts(n int) { |
| + key := s.lockKey() |
| + for i := 0; i < n; i++ { |
| + s.fx.FailNextMatching("PUT", 403, func(k string, body []byte) bool { |
| + return k == key && bytes.Contains(body, []byte(`"carlos_release"`)) |
| + }) |
| + } |
| +} |
| + |
| +// failAfterReplicate makes the wake fail once its replica runs: the files |
| +// publisher's manifest read fails, so the publisher cannot open. |
| +func (s *haSvc) failAfterReplicate() { |
| + key := hostfiles.ManifestKey(s.b.filesPrefix(s.rt.Host)) |
| + s.fx.FailNextMatching("GET", 403, func(k string, _ []byte) bool { return k == key }) |
| +} |
| + |
| +func isMarker(w lockWrite) bool { |
| + v, err := hafresh.DecodeLock(w.body, "x") |
| + return err == nil && v.Lock.Release != nil |
| +} |
| + |
| +func isHAHeld(w lockWrite, self hafresh.Self) bool { |
| + v, err := hafresh.DecodeLock(w.body, "x") |
| + if err != nil || v.Lock.Release != nil || !v.HAOn() { |
| + return false |
| + } |
| + o, ok := hafresh.ParseOwner(v.Lock.Owner) |
| + return ok && o.HA && o.Ref == self.Ref && o.IID == self.IID |
| +} |
| + |
| +func (s *haSvc) manifest(t *testing.T) (hostfiles.Manifest, bool) { |
| + t.Helper() |
| + m, found, err := hostfiles.Load(context.Background(), s.b.FilesStore, s.b.filesPrefix(s.rt.Host)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return m, found |
| +} |
| + |
| +// r2.1: a wake that fails once its replica runs releases with an unclean |
| +// marker through the replica's close, never a delete. |
| +func TestFailedWakeAfterReplicationLeavesUncleanMarker(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.failAfterReplicate() |
| + if _, err := s.wakeForTest(context.Background()); err == nil { |
| + t.Fatal("the wake should fail when its files publisher cannot open") |
| + } |
| + if v := s.lockView(t); v.Absent || v.Lock.Release == nil || v.Lock.Release.Clean { |
| + t.Fatalf("want an unclean marker, the lock is %+v", v) |
| + } |
| + for _, w := range s.storeWrites() { |
| + if strings.HasPrefix(w, "DELETE ") { |
| + t.Fatalf("a delete went out: %v", s.storeWrites()) |
| + } |
| + } |
| +} |
| + |
| +// The marker is the last write: nothing of the host (its files, its |
| +// replica) is written after it, however busy the app's tree is. |
| +func TestNoWriteAfterMarker(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + dir := filesDirOf(s.b, s.rt) |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + stop := make(chan struct{}) |
| + var writer sync.WaitGroup |
| + writer.Add(1) |
| + go func() { // keepWriting: the trio, an app file and the database |
| + defer writer.Done() |
| + db, _ := sql.Open("sqlite", s.b.pathsFor(s.rt).dbPath) |
| + defer db.Close() |
| + for i := 0; ; i++ { |
| + select { |
| + case <-stop: |
| + return |
| + case <-time.After(5 * time.Millisecond): |
| + } |
| + _ = os.WriteFile(filepath.Join(dir, "instance.key"), []byte(time.Now().String()), 0o600) |
| + _ = os.WriteFile(filepath.Join(dir, "a.txt"), []byte(time.Now().String()), 0o600) |
| + _, _ = db.Exec("insert into t values (?)", i) |
| + } |
| + }() |
| + time.Sleep(1500 * time.Millisecond) // the publisher's platform pass has run |
| + s.unit.set(func(u *haUnit) { u.active, u.unitPop, u.slicePop = "inactive", false, false }) |
| + if err := s.a.releaseHAClean(context.Background(), e); err != nil { |
| + t.Logf("release: %v", err) |
| + } |
| + time.Sleep(1500 * time.Millisecond) // anything still running would publish now |
| + close(stop) |
| + writer.Wait() |
| + w := s.storeWrites() |
| + if len(w) == 0 || w[len(w)-1] != "PUT "+s.lockKey() || !isMarker(s.lockWriteLog()[len(s.lockWriteLog())-1]) { |
| + t.Fatalf("a write after the marker: %v", w) |
| + } |
| +} |
| + |
| +// Review Focus 2: a marker whose PUT failed is persisted by lease, and the |
| +// restarted agent's next acquire of the host writes it first, then takes |
| +// the lock. |
| +func TestOwedMarkerRetriedBeforeAcquire(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + s.unit.set(func(u *haUnit) { u.slicePop = false }) |
| + s.failMarkerPuts(1) |
| + var oe *lease.ObligationError |
| + if err := s.a.releaseHAClean(context.Background(), e); !errors.As(err, &oe) { |
| + t.Fatalf("release: %v, want the persisted obligation", err) |
| + } |
| + if n := len(lease.PendingObligations()); n != 1 { |
| + t.Fatalf("%d obligations pending", n) |
| + } |
| + s2 := s.restart(t) |
| + if n := len(lease.PendingObligations()); n != 1 { |
| + t.Fatalf("after the restart, %d obligations pending: it was not on disk", n) |
| + } |
| + if _, err := s2.b.Acquire(context.Background(), s2.rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := lockWriteLogOf(s) |
| + if len(w) < 2 || !isMarker(w[len(w)-2]) || !isHAHeld(w[len(w)-1], s2.b.self()) || len(lease.PendingObligations()) != 0 { |
| + t.Fatalf("writes %d, pending %d", len(w), len(lease.PendingObligations())) |
| + } |
| +} |
| + |
| +// r3.3, path 2: a failed wake retained because its stop was unproven, |
| +// with replication started; its reaper's close writes the unclean marker, |
| +// whose PUT fails. The obligation survives a restart and is written before |
| +// the next acquire. |
| +func TestReapedWakeObligationSurvivesRestart(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + s.unit.set(func(u *haUnit) { u.stuck = true }) |
| + s.failAfterReplicate() |
| + if _, err := s.wakeForTest(context.Background()); err == nil { |
| + t.Fatal("the wake should fail") |
| + } |
| + s.a.mu.Lock() |
| + u := s.a.unprovenWakes[s.rt.Host] |
| + s.a.mu.Unlock() |
| + if u == nil || u.rep == nil { |
| + t.Fatalf("no retained wake with a replica: %+v", u) |
| + } |
| + s.failMarkerPuts(1) |
| + s.unit.set(func(u *haUnit) { u.stuck = false; u.active, u.unitPop, u.slicePop = "inactive", false, false }) |
| + s.a.mu.Lock() |
| + s.a.reapUnprovenWakesLocked() |
| + s.a.mu.Unlock() |
| + waitFor(t, "the reaper", func() bool { |
| + s.a.mu.Lock() |
| + defer s.a.mu.Unlock() |
| + return s.a.unprovenWakes[s.rt.Host] == nil |
| + }) |
| + s2 := s.restart(t) |
| + if n := len(lease.PendingObligations()); n != 1 { |
| + t.Fatalf("the reaper's obligation was dropped: %d pending", n) |
| + } |
| + if _, err := s2.b.Acquire(context.Background(), s2.rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := lockWriteLogOf(s) |
| + if len(w) < 2 || !isMarker(w[len(w)-2]) || !isHAHeld(w[len(w)-1], s2.b.self()) || len(lease.PendingObligations()) != 0 { |
| + t.Fatalf("writes %d, pending %d", len(w), len(lease.PendingObligations())) |
| + } |
| +} |
| + |
| +// Review Focus 7, r3.2: a descendant outlives the unit's stop. No marker |
| +// goes out while the host slice holds anything, or cannot be read; the |
| +// lease stays held and renewing, and the stop pending. Once the slice is |
| +// empty, the retried stop writes it. |
| +func TestNoMarkerWhileHostSlicePopulated(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + s.unit.set(func(u *haUnit) { u.sliceHeld = true }) |
| + before := len(s.lockWriteLog()) |
| + s.stopForTest(e) |
| + if s.stoppedFor(e) || len(s.lockWriteLog()) != before { |
| + t.Fatal("a marker went out while the host's slice was populated") |
| + } |
| + if v := s.lockView(t); v.Lock.Release != nil || !v.HAOn() || e.rep.Err() != nil { |
| + t.Fatalf("the lease is not held: %+v, %v", v, e.rep.Err()) |
| + } |
| + s.unit.set(func(u *haUnit) { u.sliceErr = errors.New("cgroup.events: permission denied") }) |
| + s.stopForTest(e) |
| + if s.stoppedFor(e) || len(s.lockWriteLog()) != before { |
| + t.Fatal("a marker went out over an unreadable host slice") |
| + } |
| + s.unit.set(func(u *haUnit) { u.sliceErr, u.sliceHeld, u.slicePop = nil, false, false }) |
| + s.stopForTest(e) |
| + if !s.stoppedFor(e) { |
| + t.Fatal("the stop did not finish once the slice was empty") |
| + } |
| + if v := s.lockView(t); v.Lock.Release == nil { |
| + t.Fatal("no marker after the proof") |
| + } |
| +} |
| + |
| +// The observer never sees the unit stop: unitProc.Stop answers |
| +// ErrStillRunning, the stop stays pending, and no marker goes out. |
| +func TestNoMarkerWhileUnitStopUnproven(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + // The slice reads empty throughout, so this isolates the observer's |
| + // proof: the unit's own unproven stop is what holds the marker back. |
| + s.unit.set(func(u *haUnit) { u.stuck, u.slicePop = true, false }) |
| + before := len(s.lockWriteLog()) |
| + s.stopForTest(e) // unitProc.Stop waits actStopTimeout |
| + if s.stoppedFor(e) || len(s.lockWriteLog()) != before { |
| + t.Fatal("a marker before the observer's proof") |
| + } |
| +} |
| + |
| +// A clean release: the marker is clean, the local record carries its txid |
| +// and files generation (the manifest's, as committed), and the same box's |
| +// next wake keeps its local copy. |
| +func TestCleanReleaseRecordMatchesMarkerAndKeeps(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "app file", "instance.key": "k1"}) |
| + s.stopForTest(e) |
| + if !s.stoppedFor(e) { |
| + t.Fatal("the stop did not finish") |
| + } |
| + v := s.lockView(t) |
| + if v.Lock.Release == nil || !v.Lock.Release.Clean { |
| + t.Fatalf("want a clean marker: %+v", v.Lock.Release) |
| + } |
| + now, err := readLocalNow(s.b.pathsFor(s.rt), s.rt.Host) |
| + if err != nil || !now.HaveRecord || now.Record.Marker.TXID != v.Lock.Release.TXID || now.Record.Marker.FilesGen != v.Lock.Release.FilesGen { |
| + t.Fatalf("the record %+v does not match the marker %+v (%v)", now.Record.Marker, v.Lock.Release, err) |
| + } |
| + m, found := s.manifest(t) |
| + if !found || !strings.HasPrefix(v.Lock.Release.FilesGen, strconv.FormatInt(m.Seq, 10)+":") || m.Entries["a.txt"].Object == "" || m.Entries["instance.key"].Object == "" { |
| + t.Fatalf("files gen %q, manifest %+v", v.Lock.Release.FilesGen, m) |
| + } |
| + e, err = s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if restoreCalls(s.b) != 0 || readFile(t, s.b, s.rt, "a.txt") != "app file" { |
| + t.Fatalf("the clean release was not kept: %d restores", restoreCalls(s.b)) |
| + } |
| + // Litestream resumes over the WAL the release truncated: rows written |
| + // on the kept copy reach the replica, and a restore holds them. |
| + db, err := sql.Open("sqlite", s.b.pathsFor(s.rt).dbPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 3; i++ { |
| + if _, err := db.Exec("insert into t values (?)", i); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + db.Close() |
| + first := v.Lock.Release.TXID |
| + s.stopForTest(e) |
| + if v := s.lockView(t); !s.stoppedFor(e) || v.Lock.Release == nil || !v.Lock.Release.Clean || v.Lock.Release.TXID <= first { |
| + t.Fatalf("the second release: %+v", v.Lock.Release) |
| + } |
| + got := filepath.Join(t.TempDir(), "restored.db") |
| + if ok, err := lease.Restore(context.Background(), got, s.fx.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), ""); err != nil || !ok { |
| + t.Fatalf("restore: %v, %v", ok, err) |
| + } |
| + rdb, err := sql.Open("sqlite", got) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rdb.Close() |
| + var n int |
| + if err := rdb.QueryRow("select count(*) from t").Scan(&n); err != nil || n != 3 { |
| + t.Fatalf("the replica holds %d rows (%v), want 3", n, err) |
| + } |
| +} |
| + |
| +// r2.8: a final publish that is not complete (here something that is not |
| +// a regular file in the tree) releases with an unclean marker. |
| +func TestReleaseUncleanWhenFinalPublishIncomplete(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "x"}) |
| + if err := syscall.Mkfifo(filepath.Join(filesDirOf(s.b, s.rt), "pipe"), 0o600); err != nil { |
| + t.Skipf("no FIFOs here: %v", err) |
| + } |
| + s.stopForTest(e) |
| + if v := s.lockView(t); !s.stoppedFor(e) || v.Lock.Release == nil || v.Lock.Release.Clean { |
| + t.Fatalf("want an unclean marker: %+v", v.Lock.Release) |
| + } |
| +} |
| + |
| +// The stream class captures every second for an HA host (the global |
| +// cadence): the wake sets it on the lease before Replicate, and the |
| +// replicator runs at it. Another class keeps litestream's default. |
| +func TestHAStreamClassCapturesEverySecond(t *testing.T) { |
| + for class, want := range map[string]time.Duration{"": time.Second, replicationStream: time.Second, replicationDaily: 10 * time.Second} { |
| + s := haService(t, "shop.example.com") |
| + s.rt.Replication = class |
| + if err := s.b.Registry.SetReplication(s.rt.Host, class); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r, ok := e.rep.(*lease.Replicator) |
| + if !ok || r.MonitorInterval() != want { |
| + t.Errorf("class %q: the replicator captures every %v, want %v", class, r.MonitorInterval(), want) |
| + } |
| + } |
| +} |
| + |
| +// The sleep's budget: one PUT on the lock (the marker, in place of a |
| +// delete), nothing else of the lock, and a files publish only if the tree |
| +// changed: nothing when it did not, one object and the manifest when one |
| +// file did. |
| +func TestHASleepRequestCounts(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + waitFor(t, "the platform pass's first commit", func() bool { _, found := s.manifest(t); return found }) |
| + time.Sleep(1200 * time.Millisecond) // a pass that committed nothing new |
| + lockReqs, filesReqs := s.sleepRequests(t, e) |
| + if strings.Join(lockReqs, ",") != "PUT "+s.lockKey() || len(filesReqs) != 0 { |
| + t.Fatalf("an unchanged sleep: lock %v, files %v", lockReqs, filesReqs) |
| + } |
| + e, err := s.wakeForTest(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "changed"}) |
| + lockReqs, filesReqs = s.sleepRequests(t, e) |
| + prefix := s.b.filesPrefix(s.rt.Host) |
| + if strings.Join(lockReqs, ",") != "PUT "+s.lockKey() || len(filesReqs) != 2 || |
| + !strings.HasPrefix(filesReqs[0], "PUT "+prefix+"objects/") || filesReqs[1] != "PUT "+hostfiles.ManifestKey(prefix) { |
| + t.Fatalf("a sleep with one file changed: lock %v, files %v", lockReqs, filesReqs) |
| + } |
| +} |
| + |
| +// sleepRequests stops e and returns the requests the stop made on the |
| +// lock and on the files prefix. |
| +func (s *haSvc) sleepRequests(t *testing.T, e *actEntry) (lockReqs, filesReqs []string) { |
| + t.Helper() |
| + n := len(s.fx.Requests()) |
| + s.stopForTest(e) |
| + if !s.stoppedFor(e) { |
| + t.Fatal("the stop did not finish") |
| + } |
| + prefix := s.b.filesPrefix(s.rt.Host) |
| + for _, r := range s.fx.Requests()[n:] { |
| + _, key, _ := strings.Cut(r, " ") |
| + switch { |
| + case key == s.lockKey(): |
| + lockReqs = append(lockReqs, r) |
| + case strings.HasPrefix(key, prefix): |
| + filesReqs = append(filesReqs, r) |
| + case strings.HasPrefix(r, "DELETE "): |
| + t.Fatalf("a delete in the sleep: %s", r) |
| + } |
| + } |
| + return lockReqs, filesReqs |
| +} |
| + |
| +// The sweep retries owed markers through lease.RetryPending, one pass at a |
| +// time. |
| +func TestSweepRetriesOwedMarkers(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + var calls atomic.Int32 |
| + release := make(chan struct{}) |
| + prev := retryPendingMarkers |
| + retryPendingMarkers = func(context.Context) error { calls.Add(1); <-release; return nil } |
| + t.Cleanup(func() { retryPendingMarkers = prev }) |
| + s.a.sweepOnce() |
| + s.a.sweepOnce() // the first is still running: no second pass |
| + waitFor(t, "the retry", func() bool { return calls.Load() == 1 }) |
| + close(release) |
| + waitFor(t, "the retry to finish", func() bool { return !s.a.markers.running.Load() }) |
| + s.a.sweepOnce() |
| + waitFor(t, "the next sweep's retry", func() bool { return calls.Load() == 2 }) |
| +} |
diff --git a/internal/activator/maintenance.go b/internal/activator/maintenance.go| index ce8d24ee3..b43fd0703 100644 |
| --- a/internal/activator/maintenance.go |
| +++ b/internal/activator/maintenance.go |
| @@ -347,7 +347,8 @@ func maintenanceResponse(w http.ResponseWriter, r *http.Request) { |
| // cleanupFailedWake stops a failed wake's process and gives its lease back, |
| // recording the outcome on w.stopOutcome. rt is the route the wake spawned |
| -// against, which the termination proof needs. |
| +// against, which the termination proof needs; e is the wake's entry, whose |
| +// files publisher (an HA host's) is stopped first. |
| // |
| // The lease is given back only over a generation proven terminated (spec |
| // §7.4) whenever that proof is asked for: with generations on, when the |
| @@ -357,7 +358,12 @@ func maintenanceResponse(w http.ResponseWriter, r *http.Request) { |
| // ownership and the lease are kept in unprovenWakes, the sweep retries the |
| // stop and the proof (reapUnprovenWakesLocked), and no new wake of the host |
| // starts until it holds. |
| -func (a *Service) cleanupFailedWake(ctx context.Context, rt registry.Route, w *wokenInstance, lease Lease) { |
| +func (a *Service) cleanupFailedWake(ctx context.Context, e *actEntry, rt registry.Route, w *wokenInstance, lease Lease) { |
| + // An HA host's files publisher stops first, and is joined: nothing of |
| + // it may publish after the release marker the replica's close writes. |
| + if e != nil { |
| + a.stopFiles(e) |
| + } |
| stopCtx, cancel := context.WithTimeout(context.Background(), actStopTimeout) |
| defer cancel() |
| // A wake that left a process is proven stopped before its lease goes, |