| new file mode 100644 |
| index 000000000..96dba118c |
| --- /dev/null |
| +++ b/internal/activator/pendingwake_linux_test.go |
| @@ -0,0 +1,414 @@ |
| +//go:build linux |
| + |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// A pending wake and the start rule (managed fleets 1b, branch review R1 |
| +// P1-1). A wake reads its route, then waits for the instance lease. If the |
| +// record moves to another box while it waits, that box can take the lease, |
| +// write and release before the wait ends. The waiting wake must then judge |
| +// the route as it is under the lease, not as it was before: the row it |
| +// began from may be gone, retired or reassigned, and its local copy is |
| +// then not the newest data. |
| + |
| +const assignC = "2026-10-30T12:00:00.000000003Z" |
| + |
| +// sharedLock is the one instance lease two boxes contend for: the fleet |
| +// bucket's lock.json, held by at most one box at a time. |
| +type sharedLock struct { |
| + mu sync.Mutex |
| + holder string |
| +} |
| + |
| +func (l *sharedLock) take(who string) error { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + if l.holder != "" { |
| + return fmt.Errorf("lease held by %s", l.holder) |
| + } |
| + l.holder = who |
| + return nil |
| +} |
| + |
| +func (l *sharedLock) drop(who string) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + if l.holder == who { |
| + l.holder = "" |
| + } |
| +} |
| + |
| +func (l *sharedLock) heldBy() string { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return l.holder |
| +} |
| + |
| +// fleetBucket is the fleet bucket's replica of the host's database: a |
| +// restore copies it down, a final sync copies the box's database up. |
| +type fleetBucket struct { |
| + mu sync.Mutex |
| + path string |
| + has bool |
| +} |
| + |
| +func (fb *fleetBucket) upload(t *testing.T, from string) { |
| + t.Helper() |
| + fb.mu.Lock() |
| + defer fb.mu.Unlock() |
| + copyFile(t, from, fb.path) |
| + fb.has = true |
| +} |
| + |
| +func (fb *fleetBucket) restoreTo(t *testing.T, dbPath string) bool { |
| + t.Helper() |
| + fb.mu.Lock() |
| + defer fb.mu.Unlock() |
| + if !fb.has { |
| + return false |
| + } |
| + copyFile(t, fb.path, dbPath) |
| + return true |
| +} |
| + |
| +func copyFile(t *testing.T, from, to string) { |
| + t.Helper() |
| + src, err := os.Open(from) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer src.Close() |
| + dst, err := os.OpenFile(to, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := io.Copy(dst, src); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := dst.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// leasedBox is one fleet box: the real start rule (ruleBackend over an |
| +// ExecBackend) under the shared lock. gate, when set, holds the box's |
| +// Acquire before it takes the lock; entered is closed once the Acquire is |
| +// waiting there. |
| +type leasedBox struct { |
| + *ruleBackend |
| + t *testing.T |
| + name string |
| + lock *sharedLock |
| + bucket *fleetBucket |
| + dbPath string |
| + gate chan struct{} |
| + entered chan struct{} |
| + once sync.Once |
| +} |
| + |
| +func (b *leasedBox) Acquire(ctx context.Context, rt registry.Route) (Lease, error) { |
| + if b.entered != nil { |
| + b.once.Do(func() { close(b.entered) }) |
| + } |
| + if b.gate != nil { |
| + <-b.gate |
| + } |
| + if err := b.lock.take(b.name); err != nil { |
| + return nil, err |
| + } |
| + l, err := b.ruleBackend.Acquire(ctx, rt) |
| + if err != nil { |
| + b.lock.drop(b.name) |
| + return nil, err |
| + } |
| + return &boxLease{inner: l.(*fakeLease), box: b}, nil |
| +} |
| + |
| +// boxLease drops the shared lock when it is released or when its |
| +// replication closes; the close is the final sync, so the box's database |
| +// goes up to the bucket first. |
| +type boxLease struct { |
| + inner *fakeLease |
| + box *leasedBox |
| +} |
| + |
| +func (l *boxLease) Err() error { return l.inner.Err() } |
| + |
| +func (l *boxLease) Replicate(ctx context.Context, dbPath string, iv time.Duration) (Rep, error) { |
| + r, err := l.inner.Replicate(ctx, dbPath, iv) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &boxRep{Rep: r, box: l.box}, nil |
| +} |
| + |
| +func (l *boxLease) Release(ctx context.Context) error { |
| + err := l.inner.Release(ctx) |
| + l.box.lock.drop(l.box.name) |
| + return err |
| +} |
| + |
| +type boxRep struct { |
| + Rep |
| + box *leasedBox |
| +} |
| + |
| +func (r *boxRep) Close(ctx context.Context) error { |
| + r.box.bucket.upload(r.box.t, r.box.dbPath) |
| + err := r.Rep.Close(ctx) |
| + r.box.lock.drop(r.box.name) |
| + return err |
| +} |
| + |
| +// fleetBox is a box's Service over its own registry, holding rt. |
| +func fleetBox(t *testing.T, name string, lock *sharedLock, bucket *fleetBucket, eb *ExecBackend, rt registry.Route) (*Service, *leasedBox, *registry.Registry) { |
| + t.Helper() |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + box := &leasedBox{ruleBackend: &ruleBackend{fakeBackend: &fakeBackend{}, eb: eb, t: t}, |
| + t: t, name: name, lock: lock, bucket: bucket, dbPath: rt.DBPath} |
| + a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, box, reg) |
| + a.Routes = reg |
| + return a, box, reg |
| +} |
| + |
| +// The review's interleaving, at the Service: box A's wake reads its route |
| +// and stalls before its lease; the record moves to box B (A's row goes, and |
| +// in the first case A retires it); B takes the lease, restores, writes and |
| +// sleeps, releasing it; then A's acquisition resumes and succeeds. A must |
| +// not boot the copy it kept under its old assignment: it refuses and gives |
| +// the lease back. The other cases change A's row without a retirement (the |
| +// row gone before A's reconcile retires it; the record moved away and back |
| +// so A's row names a newer assignment): the check under the lease refuses |
| +// those too, and the next wake judges the current route. |
| +func TestPendingWakeDoesNotBootAStaleCopy(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + // change is what happens to A's row while A's wake waits. |
| + change func(t *testing.T, a *Service, reg *registry.Registry, host string) |
| + gone bool |
| + }{ |
| + { |
| + name: "retired and gone", |
| + change: func(t *testing.T, a *Service, reg *registry.Registry, host string) { |
| + if err := reg.Delete(host); err != nil { |
| + t.Fatal(err) |
| + } |
| + a.RetireExcept(map[string]bool{}) |
| + }, |
| + gone: true, |
| + }, |
| + { |
| + name: "gone before the retirement", |
| + change: func(t *testing.T, _ *Service, reg *registry.Registry, host string) { |
| + if err := reg.Delete(host); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + gone: true, |
| + }, |
| + { |
| + name: "moved away and back", |
| + change: func(t *testing.T, _ *Service, reg *registry.Registry, host string) { |
| + if err := reg.SetFleetAssignment(host, assignC, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + }, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + lock := &sharedLock{} |
| + bucket := &fleetBucket{path: filepath.Join(t.TempDir(), "replica.db")} |
| + swapRestoreReplica(t, func(_ context.Context, dbPath, _, _, _ string) (bool, error) { |
| + return bucket.restoreTo(t, dbPath), nil |
| + }) |
| + |
| + // A served the instance under assignA and slept: its local copy |
| + // (one row) is kept under assignA, and the bucket holds the same. |
| + ebA := testExecBackend(t) |
| + rtA := fleetRoute(ebA, assignA, false) |
| + writeUsableDB(t, rtA.DBPath) |
| + writeAssignedMarker(t, rtA.DBPath, assignA) |
| + bucket.upload(t, rtA.DBPath) |
| + aSvc, boxA, regA := fleetBox(t, "pi-1", lock, bucket, ebA, rtA) |
| + boxA.gate, boxA.entered = make(chan struct{}), make(chan struct{}) |
| + |
| + // A's wake reads its route and waits for the lease. |
| + woke := make(chan error, 1) |
| + go func() { |
| + release, err := aSvc.beginRequest(context.Background(), rtA) |
| + if err == nil { |
| + release() |
| + } |
| + woke <- err |
| + }() |
| + select { |
| + case <-boxA.entered: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("A's wake never reached its lease") |
| + } |
| + |
| + // The record moves to B: A's row changes. |
| + tc.change(t, aSvc, regA, rtA.Host) |
| + |
| + // B takes the lease, restores the replica, writes a second row |
| + // and sleeps: its final sync puts two rows in the bucket and |
| + // releases the lease. |
| + ebB := testExecBackend(t) |
| + rtB := fleetRoute(ebB, assignB, true) |
| + bSvc, boxB, _ := fleetBox(t, "pi-2", lock, bucket, ebB, rtB) |
| + release, err := bSvc.beginRequest(context.Background(), rtB) |
| + if err != nil { |
| + t.Fatalf("B's wake: %v", err) |
| + } |
| + release() |
| + boxB.fakeBackend.mu.Lock() |
| + bStarts := boxB.starts |
| + boxB.fakeBackend.mu.Unlock() |
| + if bStarts != 1 { |
| + t.Fatalf("B started %d times, want 1", bStarts) |
| + } |
| + appendRow(t, rtB.DBPath) |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + bSvc.Shutdown(ctx) |
| + if h := lock.heldBy(); h != "" { |
| + t.Fatalf("B's sleep left the lease held by %s", h) |
| + } |
| + |
| + // A's acquisition resumes and takes the free lease. |
| + close(boxA.gate) |
| + var wakeErr error |
| + select { |
| + case wakeErr = <-woke: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("A's wake never finished") |
| + } |
| + boxA.fakeBackend.mu.Lock() |
| + starts := boxA.starts |
| + boxA.fakeBackend.mu.Unlock() |
| + if starts != 0 || wakeErr == nil { |
| + t.Fatalf("A started %d times (wake error %v): it booted the copy kept under its old assignment, one row behind the bucket's %d", starts, wakeErr, countRows(t, bucket.path)) |
| + } |
| + if h := lock.heldBy(); h != "" { |
| + t.Fatalf("A's refused wake left the lease held by %s", h) |
| + } |
| + if n := countRows(t, rtA.DBPath); n != 1 { |
| + t.Fatalf("A's kept copy has %d rows; the refusal must leave it as it was", n) |
| + } |
| + row, err := regA.Get(rtA.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if tc.gone { |
| + if row != nil { |
| + t.Fatalf("A's row is back: %+v", row) |
| + } |
| + return |
| + } |
| + // The next wake judges the current route: the copy kept under |
| + // assignA is set aside and the bucket's two rows restored. |
| + release, err = aSvc.beginRequest(context.Background(), *row) |
| + if err != nil { |
| + t.Fatalf("A's next wake: %v", err) |
| + } |
| + release() |
| + if n := countRows(t, rtA.DBPath); n != 2 { |
| + t.Fatalf("A's next wake runs %d rows, want the bucket's 2", n) |
| + } |
| + if got, _ := markerAt(t, rtA.DBPath); got != assignC { |
| + t.Fatalf("marker = %q, want %q", got, assignC) |
| + } |
| + assertOneSetAside(t, ebA, rtA.Host) |
| + }) |
| + } |
| +} |
| + |
| +// RetireExcept fences a wake that has not yet taken its lease: once the |
| +// lease comes, the wake gives it back and starts nothing, even when its |
| +// row is still there (a retirement that is not a removal: the hibernate |
| +// flag turned off). |
| +func TestRetirementFencesAPendingWake(t *testing.T) { |
| + lock := &sharedLock{} |
| + bucket := &fleetBucket{path: filepath.Join(t.TempDir(), "replica.db")} |
| + swapRestoreReplica(t, func(_ context.Context, dbPath, _, _, _ string) (bool, error) { |
| + return bucket.restoreTo(t, dbPath), nil |
| + }) |
| + eb := testExecBackend(t) |
| + rt := fleetRoute(eb, assignA, false) |
| + writeUsableDB(t, rt.DBPath) |
| + writeAssignedMarker(t, rt.DBPath, assignA) |
| + a, box, _ := fleetBox(t, "pi-1", lock, bucket, eb, rt) |
| + box.gate, box.entered = make(chan struct{}), make(chan struct{}) |
| + woke := make(chan error, 1) |
| + go func() { |
| + release, err := a.beginRequest(context.Background(), rt) |
| + if err == nil { |
| + release() |
| + } |
| + woke <- err |
| + }() |
| + <-box.entered |
| + a.RetireExcept(map[string]bool{}) |
| + close(box.gate) |
| + var err error |
| + select { |
| + case err = <-woke: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the wake never finished") |
| + } |
| + box.fakeBackend.mu.Lock() |
| + starts, restores := box.starts, box.restores |
| + box.fakeBackend.mu.Unlock() |
| + if err == nil || starts != 0 || restores != 0 { |
| + t.Fatalf("a wake retired while it waited for its lease: err %v, %d restores, %d starts; want a refusal before both", err, restores, starts) |
| + } |
| + if !errors.Is(err, ErrFenced) && !errors.Is(err, context.Canceled) { |
| + t.Fatalf("err = %v, want the fence", err) |
| + } |
| + if h := lock.heldBy(); h != "" { |
| + t.Fatalf("the lease is still held by %s", h) |
| + } |
| +} |
| + |
| +// appendRow adds one row to a database writeUsableDB made. |
| +func appendRow(t *testing.T, dbPath string) { |
| + t.Helper() |
| + db, err := sql.Open("sqlite", dbPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + if _, err := db.Exec("INSERT INTO t DEFAULT VALUES"); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// assertOneSetAside checks there is exactly one complete set-aside entry. |
| +func assertOneSetAside(t *testing.T, b *ExecBackend, host string) { |
| + t.Helper() |
| + names := supersededEntries(t, b, host) |
| + if len(names) != 1 { |
| + t.Fatalf("set-aside entries %q, want one", names) |
| + } |
| +} |