region-ha p1b-3a: complete cold-wake production witnesses
Cover separate-process placement, sealed keep and restore, competing views, owner recovery, switch-off and failed or unusable peers on the root runner. Count request, publication and fold budgets locally, including a pending wake. Preserve the installed nested units and production authority paths in fixtures.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+1,852
−238
internal/host/haplacement_budget_test.go+333 −0internal/host/haplacement_fold_test.go+93 −0internal/host/haplacement_root_linux_test.go+391 −228internal/host/haplacement_scenarios_root_linux_test.go+952 −0internal/host/haplacement_wiring_test.go+83 −10
diff --git a/internal/host/haplacement_budget_test.go b/internal/host/haplacement_budget_test.go| new file mode 100644 |
| index 000000000..8650350a7 |
| --- /dev/null |
| +++ b/internal/host/haplacement_budget_test.go |
| @@ -0,0 +1,333 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/release" |
| + "strings" |
| +) |
| + |
| +func (f *coldPlacementProcesses) marker(ref string) { |
| + f.t.Helper() |
| + raw, err := hafresh.MarkerBody(1, hafresh.Marker{V: 1, Box: ref, IID: "i-" + ref, Clean: true}) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + f.fixture.PutLock("instances/"+coldPlacementHost, raw) |
| +} |
| +func (f *coldPlacementProcesses) held(ref string) { |
| + f.t.Helper() |
| + raw, err := json.Marshal(hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(hafresh.Self{Ref: ref, IID: "i-" + ref}, 123, true), ExpiresAt: time.Now().Add(time.Hour)}) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + f.fixture.PutLock("instances/"+coldPlacementHost, raw) |
| +} |
| +func coldBudget(t *testing.T, b *coldPlacementProcess, g, p, l int64) { |
| + t.Helper() |
| + if b.reads() != g || b.putCount.Load() != p || b.listCount.Load() != l { |
| + t.Fatalf("G/P/L=%d/%d/%d, want %d/%d/%d", b.reads(), b.putCount.Load(), b.listCount.Load(), g, p, l) |
| + } |
| +} |
| +func testColdPlacementBudgetRows(t *testing.T) { |
| + t.Run("waking-zero", testColdPlacementWakingBudget) |
| + t.Run("legacy-zero", func(t *testing.T) { |
| + f := newColdPlacementProcesses(t) |
| + a := f.box("leo") |
| + a.call(coldCommand{Op: "forward", Legacy: true, Snapshot: f.snapshot("leo", "sophie")}) |
| + coldBudget(t, a, 0, 0, 0) |
| + }) |
| + for _, row := range []string{"local-marker", "forwarded-marker", "cached-marker", "absent-prefix", "no-snapshot", "local-denied", "probe-error", "probe-malformed", "acquire-error", "cas-one-conflict", "cas-three-conflicts", "leftover-prefix"} { |
| + t.Run(row, func(t *testing.T) { |
| + f := newColdPlacementProcesses(t) |
| + a, b := f.box("leo"), f.box("sophie") |
| + s := f.snapshot("leo", "sophie") |
| + if row != "absent-prefix" && row != "leftover-prefix" { |
| + f.marker("sophie") |
| + } |
| + switch row { |
| + case "local-marker": |
| + s.Serving[0].MemFreeMiB = 900 |
| + f.marker("leo") |
| + case "no-snapshot": |
| + s.Usable = false |
| + case "local-denied": |
| + s.LocalDenied = true |
| + s.Serving = nil |
| + case "probe-error": |
| + f.fixture.FailNext("GET", 400) |
| + case "probe-malformed": |
| + f.fixture.PutLock("instances/"+coldPlacementHost, []byte(`{"generation":1}`)) |
| + case "leftover-prefix": |
| + f.fixture.PutObject("instances/"+coldPlacementHost+"/unowned", []byte("data")) |
| + } |
| + d := a.call(coldCommand{Op: "forward", Snapshot: s}).Decision |
| + if row == "local-denied" { |
| + if !d.Unavailable { |
| + t.Fatal("non-serving ingress not refused", d) |
| + } |
| + coldBudget(t, a, 1, 0, 0) |
| + coldBudget(t, b, 0, 0, 0) |
| + return |
| + } |
| + target := b |
| + if row == "local-marker" || row == "no-snapshot" || row == "probe-error" || row == "probe-malformed" { |
| + target = a |
| + if d.Ref != "" { |
| + t.Fatal("expected Base/local", d) |
| + } |
| + } else if d.Ref != "sophie" { |
| + t.Fatal("expected peer", d) |
| + } |
| + if row == "cached-marker" { |
| + a.call(coldCommand{Op: "forward", Snapshot: s}) |
| + coldBudget(t, a, 1, 0, 0) |
| + } |
| + switch row { |
| + case "acquire-error": |
| + f.fixture.FailNext("GET", 400) |
| + case "cas-one-conflict": |
| + f.fixture.FailNext("PUT", 412) |
| + case "cas-three-conflicts": |
| + for i := 1; i <= 3; i++ { |
| + f.fixture.FailNth("PUT", i, 412) |
| + } |
| + } |
| + answer := target.call(coldCommand{Op: "acquire"}) |
| + refuse := row == "probe-malformed" || row == "acquire-error" || row == "cas-three-conflicts" || row == "leftover-prefix" |
| + if (answer.Error != "") != refuse { |
| + t.Fatalf("acquire=%+v row=%s", answer, row) |
| + } |
| + if !refuse && !answer.HA { |
| + t.Fatal("acquire used legacy lease") |
| + } |
| + switch row { |
| + case "local-marker", "no-snapshot", "probe-error": |
| + coldBudget(t, a, 2, 1, 0) |
| + coldBudget(t, b, 0, 0, 0) |
| + case "probe-malformed": |
| + coldBudget(t, a, 2, 0, 0) |
| + coldBudget(t, b, 0, 0, 0) |
| + case "absent-prefix": |
| + coldBudget(t, a, 1, 0, 0) |
| + coldBudget(t, b, 1, 1, 1) |
| + case "leftover-prefix": |
| + coldBudget(t, a, 1, 0, 0) |
| + coldBudget(t, b, 1, 0, 1) |
| + case "acquire-error": |
| + coldBudget(t, a, 1, 0, 0) |
| + coldBudget(t, b, 1, 0, 0) |
| + case "cas-one-conflict": |
| + coldBudget(t, a, 1, 0, 0) |
| + coldBudget(t, b, 2, 2, 0) |
| + case "cas-three-conflicts": |
| + coldBudget(t, a, 1, 0, 0) |
| + coldBudget(t, b, 3, 3, 0) |
| + default: |
| + coldBudget(t, a, 1, 0, 0) |
| + coldBudget(t, b, 1, 1, 0) |
| + } |
| + }) |
| + } |
| + t.Run("true-holder-positive-and-suspect", func(t *testing.T) { |
| + f := newColdPlacementProcesses(t) |
| + f.held("sophie") |
| + a := f.box("leo") |
| + s := f.snapshot("leo", "sophie") |
| + d := a.call(coldCommand{Op: "forward", Snapshot: s}).Decision |
| + if d.Kind != edge.Holder || d.Ref != "sophie" { |
| + t.Fatal(d) |
| + } |
| + a.call(coldCommand{Op: "forward", Snapshot: s}) |
| + coldBudget(t, a, 1, 0, 0) |
| + a.call(coldCommand{Op: "note", Result: edge.ForwardResult{Ref: d.Ref, Gen: d.Gen, PeerGen: d.PeerGen, Kind: d.Kind, Outcome: edge.ForwardUnreachable}}) |
| + d = a.call(coldCommand{Op: "forward", Snapshot: s}).Decision |
| + if !d.Refuse { |
| + t.Fatal("true holder suspect did not refuse", d) |
| + } |
| + coldBudget(t, a, 1, 0, 0) |
| + }) |
| + t.Run("recovery-suspect-keeps-negative", func(t *testing.T) { |
| + f := newColdPlacementProcesses(t) |
| + f.expiredOwner("sophie", "i-sophie") |
| + a := f.box("leo") |
| + s := f.snapshot("leo", "sophie") |
| + d := a.call(coldCommand{Op: "forward", Snapshot: s}).Decision |
| + if d.Kind != edge.Recovery || d.Ref != "sophie" { |
| + t.Fatal(d) |
| + } |
| + a.call(coldCommand{Op: "note", Result: edge.ForwardResult{Ref: d.Ref, Gen: d.Gen, PeerGen: d.PeerGen, Kind: d.Kind, Outcome: edge.ForwardUnreachable}}) |
| + d = a.call(coldCommand{Op: "forward", Snapshot: s}).Decision |
| + if d.Ref != "" || d.Refuse || d.Unavailable { |
| + t.Fatal("failed Recovery stranded Base", d) |
| + } |
| + if a.call(coldCommand{Op: "acquire"}).Error == "" { |
| + t.Fatal("unconfirmed takeover") |
| + } |
| + coldBudget(t, a, 2, 0, 0) |
| + }) |
| + t.Run("expiry-equality-and-missing-proof", testColdPlacementExpiryEquality) |
| + t.Run("publication-and-awake-projection", testColdPlacementPublicationBudget) |
| + t.Run("publication-S3-index-and-retries", testColdPlacementPublicationS3Budget) |
| + t.Run("full-fold-and-projection", testColdPlacementFoldBudget) |
| +} |
| + |
| +type coldBudgetStore struct { |
| + release.Store |
| + g, p, l, d int |
| +} |
| + |
| +func (s *coldBudgetStore) Get(ctx context.Context, k string) ([]byte, string, error) { |
| + s.g++ |
| + return s.Store.Get(ctx, k) |
| +} |
| +func (s *coldBudgetStore) Put(ctx context.Context, k string, b []byte, m string) (string, error) { |
| + s.p++ |
| + return s.Store.Put(ctx, k, b, m) |
| +} |
| +func (s *coldBudgetStore) List(ctx context.Context, k string) ([]string, error) { |
| + s.l++ |
| + return s.Store.List(ctx, k) |
| +} |
| +func (s *coldBudgetStore) Delete(ctx context.Context, k string) error { |
| + s.d++ |
| + return s.Store.Delete(ctx, k) |
| +} |
| +func testColdPlacementPublicationBudget(t *testing.T) { |
| + reg, _, svc, _ := wakeFixture(t, coldPlacementHost, time.Hour, nil) |
| + armHAPlacementWitness(svc, func(context.Context, string, string, string) error { return nil }) |
| + t.Cleanup(func() { setHAAwakeApps(nil) }) |
| + base := release.NewDirStore(t.TempDir()) |
| + base.EnableChangeIndex() |
| + store := &coldBudgetStore{Store: base} |
| + ident := edgesFile{Box: "leo", Capabilities: []string{capRegionHA1}, Headroom: headroomFor([]string{capRegionHA1}, t.TempDir(), reg)} |
| + var last []byte |
| + if err := edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + store.g, store.p, store.l, store.d = 0, 0, 0, 0 |
| + _ = svc.AwakeApps() |
| + _ = headroomFor([]string{capRegionHA1}, t.TempDir(), reg) |
| + // A changing apps map alone is outside the two-second write gate. |
| + ident.Headroom.Apps = map[string]int{"bab/shop": 17} |
| + if err := edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + if store.g+store.p+store.l+store.d != 0 { |
| + t.Fatalf("no-op/projection calls: %+v", store) |
| + } |
| + if err := edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + // DirStore's index calls happen inside Put; these two calls are counted |
| + // by the separate S3 transport test below, never called zero. |
| + if store.g != 1 || store.p != 1 || store.l != 0 || store.d != 0 { |
| + t.Fatalf("timed replacement wrapper calls: %+v", store) |
| + } |
| +} |
| + |
| +func testColdPlacementPublicationS3Budget(t *testing.T) { |
| + for _, row := range []string{"normal", "max-retries", "failed-replacement"} { |
| + t.Run(row, func(t *testing.T) { |
| + fixture := locktest.NewLockFixture(t) |
| + store, err := release.NewDeploymentS3StoreIn(t.Context(), fixture.Bucket, "eu-west-1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + reg := edgesTestRegistry(t) |
| + seedRoute(t, reg, coldPlacementHost) |
| + ident := edgesFile{Box: "leo", Capabilities: []string{capRegionHA1}, Headroom: &edgeHeadroom{MemFreeMiB: 100}} |
| + var last []byte |
| + if err := edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + begin := len(fixture.Requests()) |
| + if row != "normal" { |
| + n := 2 |
| + if row == "failed-replacement" { |
| + n = 3 |
| + } |
| + for i := 0; i < n; i++ { |
| + fixture.FailNextMatching("PUT", 412, func(key string, _ []byte) bool { return key == edgesFileKey("leo") }) |
| + } |
| + } |
| + if row == "max-retries" { |
| + for i := 0; i < 3; i++ { |
| + fixture.FailNextMatching("PUT", 412, func(key string, _ []byte) bool { return key == release.ChangeIndexKey }) |
| + } |
| + } |
| + err = edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, true) |
| + if (err != nil) != (row == "failed-replacement") { |
| + t.Fatalf("%s: %v", row, err) |
| + } |
| + g, p, l, d := 0, 0, 0, 0 |
| + for _, r := range fixture.Requests()[begin:] { |
| + switch { |
| + case strings.HasPrefix(r, "GET "): |
| + g++ |
| + case strings.HasPrefix(r, "PUT "): |
| + p++ |
| + case strings.HasPrefix(r, "LIST "): |
| + l++ |
| + case strings.HasPrefix(r, "DELETE "): |
| + d++ |
| + } |
| + } |
| + want := 2 |
| + if row == "max-retries" { |
| + want = 7 |
| + } |
| + if row == "failed-replacement" { |
| + want = 3 |
| + } |
| + if g != want || p != want || l != 0 || d != 0 { |
| + t.Fatalf("%s G/P/L/D=%d/%d/%d/%d, want %d/%d/0/0", row, g, p, l, d, want, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func testColdPlacementWakingBudget(t *testing.T) { |
| + f := newColdPlacementProcesses(t) |
| + f.marker("leo") |
| + a := f.box("leo") |
| + paused := &coldGetPause{began: make(chan struct{}), release: make(chan struct{})} |
| + a.pause.Store(paused) |
| + t.Cleanup(func() { paused.once.Do(func() { close(paused.release) }) }) |
| + if answer := a.call(coldCommand{Op: "begin"}); answer.Error != "" { |
| + t.Fatal(answer.Error) |
| + } |
| + select { |
| + case <-paused.began: |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("real Service never entered acquire") |
| + } |
| + before := a.reads() |
| + decision := a.call(coldCommand{Op: "forward", Snapshot: f.snapshot("leo", "sophie")}).Decision |
| + if decision.Ref != "" || decision.Refuse || decision.Unavailable || a.reads() != before { |
| + t.Fatalf("waking request re-probed: %+v, GET %d->%d", decision, before, a.reads()) |
| + } |
| + paused.once.Do(func() { close(paused.release) }) |
| + if answer := a.call(coldCommand{Op: "wait-wake"}); answer.Status != 503 { |
| + t.Fatalf("injected acquire failure: %+v", answer) |
| + } |
| + coldBudget(t, a, 1, 0, 0) |
| +} |
| + |
| +func testColdPlacementExpiryEquality(t *testing.T) { |
| + now := time.Now() |
| + self := hafresh.Self{Ref: "leo", IID: "i-leo", Account: "111122223333", Region: "eu-west-1"} |
| + view := hafresh.View{Lock: hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(self, 123, true), ExpiresAt: now}} |
| + if d := hafresh.DecideAcquire(view, self, now, hafresh.Proofs{SameBoxEmpty: func() (bool, error) { t.Error("equality requested proof"); return true, nil }}); d.Action != hafresh.ActHeld { |
| + t.Fatal("equality was not held", d) |
| + } |
| + if d := hafresh.DecideAcquire(view, self, now.Add(time.Nanosecond), hafresh.Proofs{}); d.Action != hafresh.ActRefuse { |
| + t.Fatal("missing proof did not refuse", d) |
| + } |
| +} |
diff --git a/internal/host/haplacement_fold_test.go b/internal/host/haplacement_fold_test.go| new file mode 100644 |
| index 000000000..bc0d9476c |
| --- /dev/null |
| +++ b/internal/host/haplacement_fold_test.go |
| @@ -0,0 +1,93 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "strings" |
| + "testing" |
| + "time" |
| + "unsafe" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// These test-only declarations call the production map's private constructor |
| +// and methods. No parser, projection, fold, forwarder or chooser is substituted. |
| +// Keeping them here avoids adding a production API solely for a host witness. |
| +// |
| +//go:linkname coldEdgeHomeMap github.com/carlosframework/platform/internal/edge.(*Edge).newHomeMap |
| +func coldEdgeHomeMap(*edge.Edge) unsafe.Pointer |
| + |
| +//go:linkname coldHomeRefresh github.com/carlosframework/platform/internal/edge.(*homeMap).Refresh |
| +func coldHomeRefresh(unsafe.Pointer, context.Context) error |
| + |
| +//go:linkname coldHomeSnapshot github.com/carlosframework/platform/internal/edge.(*homeMap).wakeSnapshot |
| +func coldHomeSnapshot(unsafe.Pointer, registry.Route, time.Time) boxchoice.WakeSnapshot |
| + |
| +func testColdPlacementFoldBudget(t *testing.T) { |
| + fixture := locktest.NewLockFixture(t) |
| + t.Setenv("CARLOS_REGION_HA", "1") |
| + store, err := release.NewS3StoreIn(t.Context(), fixture.Bucket, "eu-west-1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + reg, _, svc, _ := wakeFixture(t, coldPlacementHost, time.Hour, nil) |
| + for _, ref := range []string{"leo", "sophie"} { |
| + var last []byte |
| + ident := edgesFile{Box: ref, Region: "eu-west-1", Placement: "ie", DataBucket: fixture.Bucket, SecretsKeyFP: "shared", HibernationConfigured: true, Capabilities: []string{capRegionHA1}, Headroom: &edgeHeadroom{MemFreeMiB: 300, MemTotalMiB: 1000, DiskFreeMiB: 300, DiskTotalMiB: 1000}} |
| + if err := edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, err := store.Put(t.Context(), "control/edge-mesh-key", []byte(strings.Repeat("a", 64)), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := edge.New(reg, svc) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + edge.WithBoxLabel("leo")(e) |
| + e.EnableStatic(store, ed25519.NewKeyFromSeed(make([]byte, 32)).Public().(ed25519.PublicKey), t.TempDir()) |
| + m := coldEdgeHomeMap(e) |
| + if m == nil { |
| + t.Fatal("production map not armed") |
| + } |
| + before := len(fixture.Requests()) |
| + if err := coldHomeRefresh(m, t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + requests := fixture.Requests()[before:] |
| + edgeGets, lists, keyGets := 0, 0, 0 |
| + for _, r := range requests { |
| + switch { |
| + case strings.HasPrefix(r, "GET control/edges/"): |
| + edgeGets++ |
| + case strings.HasPrefix(r, "LIST control/edges/"): |
| + lists++ |
| + case strings.HasPrefix(r, "GET control/edge-mesh-key"): |
| + keyGets++ |
| + default: |
| + t.Fatalf("unexpected fold call: %s", r) |
| + } |
| + } |
| + if edgeGets != 2 || lists != 1 || keyGets != 2 { |
| + t.Fatalf("full B=2 fold: %v", requests) |
| + } |
| + rt, err := reg.Get(coldPlacementHost) |
| + if err != nil || rt == nil { |
| + t.Fatal(rt, err) |
| + } |
| + before = len(fixture.Requests()) |
| + snapshot := coldHomeSnapshot(m, *rt, time.Now()) |
| + _ = svc.AwakeApps() |
| + if !snapshot.Enabled || !snapshot.Usable || len(snapshot.Serving) != 2 { |
| + t.Fatalf("actual projection not usable: %+v", snapshot) |
| + } |
| + if got := fixture.Requests()[before:]; len(got) != 0 { |
| + t.Fatalf("projection read storage: %v", got) |
| + } |
| +} |
diff --git a/internal/host/haplacement_root_linux_test.go b/internal/host/haplacement_root_linux_test.go| index 8ba104ddb..60c0d6a13 100644 |
| --- a/internal/host/haplacement_root_linux_test.go |
| +++ b/internal/host/haplacement_root_linux_test.go |
| @@ -18,6 +18,7 @@ import ( |
| "encoding/json" |
| "encoding/pem" |
| "io" |
| + "log" |
| "math/big" |
| "net" |
| "net/http" |
| @@ -27,12 +28,15 @@ import ( |
| "path/filepath" |
| "runtime" |
| "strings" |
| + "sync" |
| "sync/atomic" |
| + "syscall" |
| "testing" |
| "time" |
| "github.com/carlosframework/platform/internal/activator" |
| "github.com/carlosframework/platform/internal/analytics" |
| + "github.com/carlosframework/platform/internal/boxid" |
| "github.com/carlosframework/platform/internal/cgroup" |
| "github.com/carlosframework/platform/internal/controlsock" |
| "github.com/carlosframework/platform/internal/edge" |
| @@ -50,16 +54,28 @@ import ( |
| "github.com/carlosframework/platform/internal/rollout" |
| "github.com/carlosframework/platform/internal/rootparticipation" |
| "github.com/carlosframework/platform/internal/rootstate" |
| + "github.com/carlosframework/platform/internal/termfence" |
| "github.com/carlosframework/platform/internal/usage" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| func init() { |
| + if lifecyclePayloadArgs(os.Args) { |
| + f, err := os.OpenFile(filepath.Join(filepath.Dir(os.Args[4]), "cold-starts"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) |
| + if err != nil { |
| + panic(err) |
| + } |
| + if _, err = f.WriteString("start\n"); err != nil { |
| + panic(err) |
| + } |
| + f.Close() |
| + } |
| + coldPlacementProductionLaunch = coldRootProductionWiring |
| if os.Getenv("COLD_ROOT_BOX") != "" { |
| version.Build = "v2.0.0" |
| } |
| if os.Getenv("COLD_ROOT_BOX") != "" && len(os.Args) == 2 && os.Args[1] == "agent" { |
| - os.Args = []string{os.Args[0], "-test.run=^TestColdPlacementRootAgent$", "-test.v", "-test.timeout=5m"} |
| + os.Args = []string{os.Args[0], "-test.run=^TestColdPlacementRootAgent$", "-test.v", "-test.timeout=15m"} |
| } |
| if os.Getenv("COLD_ROOT_BOX") != "" && len(os.Args) >= 2 && os.Args[1] == "instance-control" { |
| RunInstanceControl(os.Args[2:]) |
| @@ -72,8 +88,12 @@ type coldRootStats struct { |
| Apps map[string]int |
| Meter usage.EdgeFlush |
| Analytics int64 |
| + Pages []coldRootPage |
| + Dials int64 |
| } |
| +type coldRootPage struct{ Level, Subject, Body string } |
| + |
| type coldRootAnalytics struct{ n atomic.Int64 } |
| func (a *coldRootAnalytics) Observe(analytics.Obs) { a.n.Add(1) } |
| @@ -84,6 +104,12 @@ func TestColdPlacementRootAgent(t *testing.T) { |
| t.Skip("installed edge child payload") |
| } |
| version.Build = "v2.0.0" |
| + var dialCount atomic.Int64 |
| + originalDial := coldRootDial |
| + coldRootDial = func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + dialCount.Add(1) |
| + return originalDial(ctx, network, addr) |
| + } |
| t.Setenv("CARLOS_S3_ENDPOINT", os.Getenv("COLD_ROOT_DATA_ENDPOINT")) |
| t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "") |
| data := os.Getenv("CARLOS_DATA_DIR") |
| @@ -107,8 +133,8 @@ func TestColdPlacementRootAgent(t *testing.T) { |
| lifecycleCheck(t, "files store", err) |
| ctl := instancectl.NewClient(controlsock.Path) |
| manager := cgroup.SetupRetaining(t.Logf) |
| - eb := &activator.ExecBackend{Cfg: cfg, Registry: reg, DataDir: data, OptDir: "/opt/carlos", FilesStore: files, EscrowKey: haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), Control: ctl, Cgroups: manager} |
| - if ref == "leo" { |
| + eb := &activator.ExecBackend{Cfg: cfg, Registry: reg, DataDir: "/data", OptDir: "/opt/carlos", FilesStore: files, EscrowKey: haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), Control: ctl, Cgroups: manager} |
| + if os.Getenv("COLD_ROOT_NO_PROOF") != "1" { |
| deadline := time.Now().Add(time.Minute) |
| for { |
| err := ctl.Ready(t.Context()) |
| @@ -123,10 +149,40 @@ func TestColdPlacementRootAgent(t *testing.T) { |
| swept, err := ctl.Sweep(t.Context()) |
| lifecycleCheck(t, "startup stop-and-prove", err) |
| eb.StartupSwept = func() bool { return len(swept.Failed) == 0 } |
| - eb.NestedOK = func() error { return ctl.Ready(t.Context()) } |
| } |
| + eb.NestedOK = func() error { return ctl.Ready(t.Context()) } |
| + confirmer := &termfence.Confirmer{Self: func() boxid.Cloud { |
| + return boxid.Cloud{Provider: "aws", Account: "111122223333", Region: "eu-west-1", InstanceID: "i-" + ref} |
| + }, API: func(context.Context, string) (termfence.EC2, error) { |
| + return coldRootEC2{dir: os.Getenv("COLD_ROOT_SHARED")}, nil |
| + }} |
| + eb.OwnerTerminated = confirmer.Terminated |
| svc := activator.New(cfg, &activator.SplitBackend{Exec: eb, Unit: &activator.UnitBackend{}}, reg) |
| - armHAPlacementWitness(svc, func(context.Context, string, string, string) error { return nil }) |
| + var activeEdge *edge.Edge |
| + if ref == "sophie" && (os.Getenv("COLD_ROOT_MODE") == "out-of-view" || os.Getenv("COLD_ROOT_MODE") == "key-lost") { |
| + log.SetOutput(&coldRootProjectionLog{out: os.Stderr, after: func() { |
| + faultKey := edgesFileKey("leo") |
| + if os.Getenv("COLD_ROOT_MODE") == "key-lost" { |
| + faultKey = "control/edge-mesh-key" |
| + } |
| + raw, _, err := store.Get(t.Context(), faultKey) |
| + lifecycleCheck(t, "projection peer", err) |
| + lifecycleCheck(t, "peer leaves forwarding view", store.Delete(t.Context(), faultKey)) |
| + coldRootKeysOnly.Store(os.Getenv("COLD_ROOT_MODE") == "key-lost") |
| + coldRootRefresh(t, activeEdge) |
| + coldRootKeysOnly.Store(false) |
| + _, err = store.Put(t.Context(), faultKey, raw, "") |
| + lifecycleCheck(t, "fresh peer publication retained", err) |
| + }}) |
| + } |
| + var pageMu sync.Mutex |
| + var pages []coldRootPage |
| + armHAPlacementWitness(svc, func(_ context.Context, level, subject, body string) error { |
| + pageMu.Lock() |
| + defer pageMu.Unlock() |
| + pages = append(pages, coldRootPage{level, subject, body}) |
| + return nil |
| + }) |
| svc.Start() |
| defer func() { |
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| @@ -136,239 +192,54 @@ func TestColdPlacementRootAgent(t *testing.T) { |
| meter := edge.NewUsageMeter() |
| observer := &coldRootAnalytics{} |
| admin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - _ = json.NewEncoder(w).Encode(coldRootStats{Owned: svc.Owns(lifecycleHost), Apps: svc.AwakeApps(), Meter: meter.Drain(), Analytics: observer.n.Load()}) |
| + switch r.URL.Path { |
| + case "/refresh": |
| + coldRootRefresh(t, activeEdge) |
| + w.WriteHeader(204) |
| + return |
| + case "/publish": |
| + var last []byte |
| + ident := coldRootIdentity(ref, 800) |
| + ident.Headroom.Apps = haAwakeApps() |
| + if err := edgesFileWrite(r.Context(), store, reg, ident, coldRootIP(ref), &last, true); err != nil { |
| + http.Error(w, err.Error(), 500) |
| + return |
| + } |
| + w.WriteHeader(204) |
| + return |
| + case "/shutdown": |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| + defer cancel() |
| + svc.Shutdown(ctx) |
| + w.WriteHeader(204) |
| + return |
| + } |
| + pageMu.Lock() |
| + defer pageMu.Unlock() |
| + _ = json.NewEncoder(w).Encode(coldRootStats{Dials: dialCount.Load(), Pages: append([]coldRootPage(nil), pages...), Owned: svc.Owns(lifecycleHost), Apps: svc.AwakeApps(), Meter: meter.Drain(), Analytics: observer.n.Load()}) |
| })) |
| defer admin.Close() |
| lifecycleCheck(t, "admin address", os.WriteFile(filepath.Join(data, "cold-root-admin"), []byte(admin.URL), 0600)) |
| edge.RunWithActivatorReady([]string{"--registry", filepath.Join(data, "registry.db"), "--https", os.Getenv("COLD_ROOT_HTTPS"), "--http", "127.0.0.1:0"}, svc, nil, func(e *edge.Edge) { |
| + activeEdge = e |
| e.EnableUsage(meter) |
| e.EnableAnalytics(observer) |
| e.SetAnalyticsOn(map[string]bool{"bab/lifecycle": true}) |
| }, edge.WithBoxLabel(ref)) |
| } |
| -func TestColdPlacementRootRunner(t *testing.T) { |
| - egressRootPrereqs(t) |
| - uid, gid := generationRunnerRegistryUser(t) |
| - for _, path := range []string{lifecycleHome, "/data", "/opt/carlos", "/run/carlos", "/run/carlos-control", "/etc/carlos", "/var/lib/carlos-claims", "/var/lib/carlos-release"} { |
| - lifecycleCheck(t, "exclusive root "+path, os.Mkdir(path, 0755)) |
| - t.Cleanup(func() { lifecycleCheck(t, "remove owned root "+path, os.RemoveAll(path)) }) |
| - } |
| - lifecycleCheck(t, "private root authority", os.Chmod("/var/lib/carlos-claims", 0700)) |
| - for _, path := range []string{lifecycleHome + "/deployment", "/data/.instances", "/data/instances", "/run/carlos/.instances", "/run/carlos/instances", "/run/carlos/.logs", "/run/carlos/logs", "/opt/carlos/versions"} { |
| - lifecycleCheck(t, "tree", os.MkdirAll(path, 0755)) |
| - } |
| - model := leasetest.NewVersionedBucket() |
| - model.AddBucket("data") |
| - s3, _ := leasetest.NewS3Server(model) |
| - server := httptest.NewServer(lifecycleS3(s3, model)) |
| - defer server.Close() |
| - lifecycleEnvironment(t, server.URL) |
| - t.Setenv("CARLOS_HOST_CLAIM", "") |
| - t.Setenv("CARLOS_REGION_HA", "true") |
| - key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize)) |
| - store := release.NewDirStore(lifecycleHome + "/deployment") |
| - identity := handoverRecoveryIdentity(t, hostbox.Actor{Box: "box", Enrollment: strings.Repeat("a", 32), Revision: 1, Binding: "1", Region: "ie", FleetHomeRegion: "ie", ControlBucket: "deployment"}) |
| - identity.HomeRegion = "ie" |
| - actor, err := identity.Verify(t.Context()) |
| - lifecycleCheck(t, "guard fixture identity", err) |
| - binary, err := os.Executable() |
| - lifecycleCheck(t, "binary", err) |
| - image, err := os.ReadFile(binary) |
| - lifecycleCheck(t, "binary bytes", err) |
| - lifecycleCheck(t, "executor", os.WriteFile("/opt/carlos/carlos", image, 0755)) |
| - lifecycleCheck(t, "previous executor", os.WriteFile("/opt/carlos/carlos.prev", image, 0755)) |
| - sum := sha256.Sum256(image) |
| - platform := runtime.GOOS + "-" + runtime.GOARCH |
| - pointer := release.SystemPointer{Schema: 1, Component: "router", Channel: "stable", Spread: "0s", PromotedAt: time.Now(), Current: release.SystemRelease{Version: "v2.0.0", ReleaseTag: "v2.0.0", MovesProtocol: 1, Artifacts: map[string]release.SystemArtifact{platform: {Key: release.SystemArtifactKey("v2.0.0", platform), SHA256: hex.EncodeToString(sum[:])}}}} |
| - identityBytes, err := release.SignRootEnvelope(release.RootSigner(key), pointer) |
| - lifecycleCheck(t, "executor identity", err) |
| - identities, err := rootstate.Open("/opt/carlos/system/guard/identities", false, true) |
| - lifecycleCheck(t, "executor identities", err) |
| - lifecycleCheck(t, "executor identity persistence", identities.Write("v2.0.0.json", identityBytes)) |
| - identities.Close() |
| - roster := hostactors.Roster{V: 1, HomeRegion: "ie", DeploymentBucket: actor.ControlBucket, Revision: 1, RequestLimitNS: int64(hostbox.RequestLimit), Boxes: map[string]hostactors.Box{actor.Box: {BoxID: actor.Box, Enrollment: actor.Enrollment, Namespace: actor.Namespace, Label: actor.Box, Region: actor.Region, Pool: "default", Cloud: hostactors.Cloud{Provider: actor.Cloud.Provider, Account: actor.Cloud.Account, Region: actor.Cloud.Region, InstanceID: actor.Cloud.InstanceID}, EvidenceSHA256: strings.Repeat("c", 64), CensusPublicKey: ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2}, ed25519.SeedSize)).Public().(ed25519.PublicKey), State: "active"}}, Consoles: map[string]hostactors.Console{}, Holds: map[string]hostactors.Reservation{}, Activations: map[string]hostactors.Reservation{}} |
| - rosterBytes, err := release.SignRootEnvelope(release.RootSigner(key), roster) |
| - lifecycleCheck(t, "guard roster", err) |
| - _, err = store.Put(t.Context(), hostactors.Key, rosterBytes, "") |
| - lifecycleCheck(t, "guard roster persistence", err) |
| - filesSeedConstructionMigration(t, "/opt/carlos", actor.ControlBucket, actor.Box, actor.Enrollment) |
| - coldRootArmGuard(t, store, key, actor, pointer) |
| - censusState, err := rootstate.Open(rootparticipation.Namespace, true, false) |
| - lifecycleCheck(t, "census store", err) |
| - census := rootparticipation.Census{Schema: 1, Box: actor.Box, Enrollment: actor.Enrollment, Migration: 1, Revision: 1, LaunchRevision: 1, Complete: true} |
| - censusBytes, err := json.Marshal(census) |
| - lifecycleCheck(t, "census fixture", err) |
| - lifecycleCheck(t, "census persistence", censusState.Write("census.json", censusBytes)) |
| - censusState.Close() |
| - failures, err := rootstate.Open(rollout.RootFailuresDir, true, false) |
| - lifecycleCheck(t, "failures store", err) |
| - _, err = rollout.InitializeRootFailures(failures, rootUpdatesMigration(census), nil) |
| - lifecycleCheck(t, "failure migration", err) |
| - failures.Close() |
| - pins, err := rootstate.Open(release.RootGenerationsDir, true, false) |
| - lifecycleCheck(t, "generation pins", err) |
| - pins.Close() |
| - lifecycleInstallUnits(t) |
| - ctl := func(args ...string) (string, error) { |
| - out, err := exec.Command("systemctl", args...).CombinedOutput() |
| - return string(out), err |
| - } |
| - for _, name := range []string{"carlos-edge.service", "carlos-instance-probe.service"} { |
| - raw, err := unitsFS.ReadFile("units/" + name) |
| - lifecycleCheck(t, "production unit", err) |
| - path := filepath.Join("/etc/systemd/system", name) |
| - f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644) |
| - lifecycleCheck(t, "exclusive production unit", err) |
| - _, err = f.Write(raw) |
| - lifecycleCheck(t, "write production unit", err) |
| - lifecycleCheck(t, "close production unit", f.Close()) |
| - t.Cleanup(func() { _, _ = ctl("stop", name); _ = os.Remove(path); _, _ = ctl("daemon-reload") }) |
| - } |
| - secret := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)) |
| - caFile := lifecycleHome + "/root-ca.pem" |
| - coldRootCertificate(t, store, caFile) |
| - _, err = store.Put(t.Context(), "control/edge-mesh-key", []byte(strings.Repeat("a", 64)), "") |
| - lifecycleCheck(t, "mesh key", err) |
| - env := map[string]string{"COLD_ROOT_BOX": "leo", "COLD_ROOT_HTTPS": "127.0.0.1:443", "PLAN14_LIFECYCLE_GUARD": "1", "CARLOS_HOST_CLAIM": "", "CARLOS_REGION_HA": "true", "CARLOS_HIBERNATE_BUCKET": "data", "CARLOS_HIBERNATE_REGION": "eu-west-1", "CARLOS_HIBERNATE_PREFIX": "instances", "CARLOS_DATA_DIR": "/data", "CARLOS_OPT_DIR": "/opt/carlos", "CARLOS_DEPLOYMENT_DIR": lifecycleHome + "/deployment", "CARLOS_DEPLOYMENT_BUCKET": actor.ControlBucket, "CARLOS_RELEASE_PUBKEY": base64.StdEncoding.EncodeToString(key.Public().(ed25519.PublicKey)), "CARLOS_SECRETS_KEY": secret, "CARLOS_S3_ENDPOINT": activationS3Fixture(t, store), "COLD_ROOT_DATA_ENDPOINT": server.URL, "AWS_ACCESS_KEY_ID": "test-key", "AWS_SECRET_ACCESS_KEY": "test-secret", "AWS_EC2_METADATA_DISABLED": "true", "AWS_CONFIG_FILE": "/nonexistent", "AWS_SHARED_CREDENTIALS_FILE": "/nonexistent", "AWS_REGION": "eu-west-1", "SSL_CERT_FILE": caFile, "TMPDIR": "/run/carlos", "PATH": os.Getenv("PATH")} |
| - var lines []string |
| - for name, value := range env { |
| - lines = append(lines, name+"="+value) |
| - } |
| - lifecycleCheck(t, "host environment", os.WriteFile("/etc/carlos/host.env", []byte(strings.Join(lines, "\n")+"\n"), 0600)) |
| - reg, err := openServiceRegistry("/data/registry.db") |
| - lifecycleCheck(t, "registry", err) |
| - defer reg.Close() |
| - gateHash, err := gate.Hash("cold-root-password") |
| - lifecycleCheck(t, "selected gate", err) |
| - rec := provision.Record{Gate: gateHash, Schema: 1, Host: lifecycleHost, Account: "bab", App: "lifecycle", Channel: "stable", HA: true, CreatedAt: time.Now().UTC()} |
| - raw, err := json.Marshal(rec) |
| - lifecycleCheck(t, "record encode", err) |
| - _, err = store.Put(t.Context(), provision.RecordKey(rec.Account, rec.App, rec.Host), raw, "") |
| - lifecycleCheck(t, "record", err) |
| - cfg := provision.ReconcileConfig{DataDir: "/data", Layout: func(context.Context, release.Store) (string, error) { return release.LayoutModeNested, nil }} |
| - lifecycleCheck(t, "provision real HA record", provision.Reconcile(t.Context(), store, reg, cfg)) |
| +func TestColdPlacementSealedWake(t *testing.T) { coldRootSealedWake(t) } |
| +func TestColdPlacementCompetingViews(t *testing.T) { coldRootCompetingViews(t) } |
| +func TestColdPlacementExpiredOwnerRecovery(t *testing.T) { coldRootExpiredOwner(t) } |
| +func TestColdPlacementSwitchOff(t *testing.T) { coldRootSwitchOff(t) } |
| +func TestColdPlacementDeadChoice(t *testing.T) { coldRootDeadChoice(t) } |
| +func TestColdPlacementUnusableChoice(t *testing.T) { coldRootUnusableChoice(t) } |
| +func TestColdPlacementNewHostNoFold(t *testing.T) { coldRootNewHost(t) } |
| - manifest := release.Manifest{App: "lifecycle", Version: "v1", Kind: "binary", Artifacts: map[string]release.Artifact{release.AdoptPlatform(): {}}} |
| - lifecycleCheck(t, "ship", release.Ship(t.Context(), store, "bab", manifest, map[string][]byte{release.AdoptPlatform(): image})) |
| - lifecycleCheck(t, "promote", release.Promote(t.Context(), store, key, "bab", "lifecycle", "stable", "v1")) |
| - _, _, err = release.StageSignedHead(t.Context(), store, key.Public().(ed25519.PublicKey), nil, "/opt/carlos", registry.Route{Host: lifecycleHost, Account: "bab", App: "lifecycle", Channel: "stable"}) |
| - |
| - lifecycleCheck(t, "stage signed app", err) |
| - lifecycleCheck(t, "point live", release.PointLive("/opt/carlos", lifecycleHost, "bab", "v1", "lifecycle")) |
| - for _, path := range []string{"/data", "/run/carlos", lifecycleHome} { |
| - lifecycleCheck(t, "fixture service owner", filepath.Walk(path, func(path string, _ os.FileInfo, err error) error { |
| - if err != nil { |
| - return err |
| - } |
| - return os.Chown(path, uid, gid) |
| - })) |
| - } |
| - var last []byte |
| - ident := edgesFile{Box: "leo", Region: "eu-west-1", Placement: "ie", DataBucket: "data", SecretsKeyFP: "shared", HibernationConfigured: true, Capabilities: []string{capRegionHA1}, Headroom: &edgeHeadroom{MemFreeMiB: 800, MemTotalMiB: 1000, DiskFreeMiB: 500, DiskTotalMiB: 1000}} |
| - lifecycleCheck(t, "selected publication", edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, true)) |
| - ident.Box, ident.Headroom.MemFreeMiB = "sophie", 300 |
| - last = nil |
| - lifecycleCheck(t, "ingress publication", edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, true)) |
| - for _, name := range systemUnitFiles { |
| - path := filepath.Join("/etc/systemd/system", name) |
| - if _, e := os.Lstat(path); os.IsNotExist(e) { |
| - t.Cleanup(func() { _, _ = ctl("disable", "--now", name); _ = os.Remove(path); _, _ = ctl("daemon-reload") }) |
| - } |
| - } |
| +func TestColdPlacementRootRunner(t *testing.T) { |
| + f := newColdRootHarness(t, "normal") |
| + model, client, ctl, ingress := f.model, f.client, f.ctl, f.ingress |
| - controlDropin := "/etc/systemd/system/carlos-instance-control.service.d" |
| - lifecycleCheck(t, "exclusive control fixture environment", os.Mkdir(controlDropin, 0755)) |
| - lifecycleCheck(t, "control fixture environment", os.WriteFile(filepath.Join(controlDropin, "10-cold-root.conf"), []byte("[Service]\nEnvironmentFile=/etc/carlos/host.env\n"), 0644)) |
| - t.Cleanup(func() { |
| - _, _ = ctl("stop", "carlos-instance-control.service") |
| - _ = os.RemoveAll(controlDropin) |
| - _, _ = ctl("daemon-reload") |
| - }) |
| - ensureSystemUnits("/etc", "/opt/carlos/system/router/lock", ctl, ctl, t.Logf) |
| - out, err := ctl("daemon-reload") |
| - lifecycleCheck(t, out, err) |
| - out, err = ctl("start", "data-instances.mount", "run-carlos-instances.mount", "run-carlos-logs.mount") |
| - lifecycleCheck(t, out, err) |
| - dropin := "/run/systemd/system/carlos-edge.service.d" |
| - lifecycleCheck(t, "exclusive edge fixture drop-in", os.Mkdir(dropin, 0755)) |
| - lifecycleCheck(t, "disable fixture automatic restart", os.WriteFile(filepath.Join(dropin, "10-cold-root.conf"), []byte("[Service]\nRestart=no\n"), 0644)) |
| - t.Cleanup(func() { |
| - _, _ = ctl("stop", "carlos-edge.service") |
| - _ = os.RemoveAll(dropin) |
| - _, _ = ctl("daemon-reload") |
| - }) |
| - _, err = ctl("daemon-reload") |
| - lifecycleCheck(t, "fixture daemon reload", err) |
| - coldRootProbeFixtures(t, uid, gid) |
| - out, err = ctl("start", "carlos-edge.service") |
| - lifecycleCheck(t, out, err) |
| - ingress := t.TempDir() |
| - ingressReg, err := registry.Open(filepath.Join(ingress, "registry.db")) |
| - lifecycleCheck(t, "ingress registry", err) |
| - route, err := reg.Get(lifecycleHost) |
| - lifecycleCheck(t, "provisioned row", err) |
| - if route == nil || !route.HA { |
| - t.Fatal("provisioning did not produce an HA route") |
| - } |
| - ingressRoute := *route |
| - ingressRoute.Gate, err = gate.Hash("ingress-must-not-run-this-gate") |
| - lifecycleCheck(t, "ingress gate", err) |
| - lifecycleCheck(t, "ingress row", ingressReg.Upsert(ingressRoute)) |
| - ingressReg.Close() |
| - listener, err := net.Listen("tcp", "127.0.0.1:0") |
| - lifecycleCheck(t, "reserve ingress address", err) |
| - addr := listener.Addr().String() |
| - listener.Close() |
| - cmd := exec.Command(binary, "-test.run=^TestColdPlacementRootAgent$", "-test.v", "-test.timeout=5m") |
| - cmd.Dir = ingress |
| - for name, value := range env { |
| - switch name { |
| - case "COLD_ROOT_BOX": |
| - value = "sophie" |
| - case "COLD_ROOT_HTTPS": |
| - value = addr |
| - case "CARLOS_DATA_DIR": |
| - value = ingress |
| - case "TMPDIR": |
| - value = ingress |
| - } |
| - cmd.Env = append(cmd.Env, name+"="+value) |
| - } |
| - log, err := os.Create(filepath.Join(ingress, "edge.log")) |
| - lifecycleCheck(t, "ingress log", err) |
| - cmd.Stdout, cmd.Stderr = log, log |
| - lifecycleCheck(t, "start ingress process", cmd.Start()) |
| - t.Cleanup(func() { |
| - _ = cmd.Process.Signal(os.Interrupt) |
| - timer := time.AfterFunc(15*time.Second, func() { _ = cmd.Process.Kill() }) |
| - _ = cmd.Wait() |
| - timer.Stop() |
| - log.Close() |
| - }) |
| - caBytes, err := os.ReadFile(caFile) |
| - lifecycleCheck(t, "parent CA", err) |
| - pool := x509.NewCertPool() |
| - if !pool.AppendCertsFromPEM(caBytes) { |
| - t.Fatal("invalid fixture CA") |
| - } |
| - client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}, DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { |
| - return (&net.Dialer{}).DialContext(ctx, network, addr) |
| - }}, Timeout: 45 * time.Second} |
| - defer client.CloseIdleConnections() |
| - deadline := time.Now().Add(2 * time.Minute) |
| - for { |
| - conn, err := net.DialTimeout("tcp", addr, time.Second) |
| - if err == nil { |
| - conn.Close() |
| - break |
| - } |
| - if time.Now().After(deadline) { |
| - raw, _ := os.ReadFile(log.Name()) |
| - t.Fatalf("ingress never listened: %s", raw) |
| - } |
| - time.Sleep(100 * time.Millisecond) |
| - } |
| response, err := coldRootGET(client) |
| lifecycleCheck(t, "non-choice request", err) |
| body, err := io.ReadAll(response.Body) |
| @@ -418,7 +289,7 @@ func TestColdPlacementRootRunner(t *testing.T) { |
| } |
| time.Sleep(100 * time.Millisecond) |
| } |
| - out, err = ctl("kill", "--kill-whom=main", "--signal=KILL", "carlos-edge.service") |
| + out, err := ctl("kill", "--kill-whom=main", "--signal=KILL", "carlos-edge.service") |
| lifecycleCheck(t, "crash selected edge: "+out, err) |
| out, err = ctl("stop", "carlos-edge.service") |
| lifecycleCheck(t, "stop and prove edge: "+out, err) |
| @@ -504,7 +375,7 @@ func coldRootCertificate(t *testing.T, store release.Store, caFile string) { |
| lifecycleCheck(t, "CA trust", os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0644)) |
| leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| lifecycleCheck(t, "leaf key", err) |
| - leaf := &x509.Certificate{SerialNumber: big.NewInt(2), DNSNames: []string{lifecycleHost}, NotBefore: ca.NotBefore, NotAfter: ca.NotAfter, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| + leaf := &x509.Certificate{SerialNumber: big.NewInt(2), DNSNames: []string{lifecycleHost, lifecycleSibling}, NotBefore: ca.NotBefore, NotAfter: ca.NotAfter, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| der, err = x509.CreateCertificate(rand.Reader, leaf, ca, &leafKey.PublicKey, key) |
| lifecycleCheck(t, "leaf", err) |
| priv, err := x509.MarshalECPrivateKey(leafKey) |
| @@ -512,6 +383,8 @@ func coldRootCertificate(t *testing.T, store release.Store, caFile string) { |
| bundle := append(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: priv}), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})...) |
| _, err = store.Put(t.Context(), "control/certs/"+lifecycleHost, bundle, "") |
| lifecycleCheck(t, "certificate publication", err) |
| + _, err = store.Put(t.Context(), "control/certs/"+lifecycleSibling, bundle, "") |
| + lifecycleCheck(t, "sibling certificate publication", err) |
| } |
| func coldRootReadStats(t *testing.T, data string) coldRootStats { |
| @@ -581,3 +454,293 @@ func coldRootArmGuard(t *testing.T, store release.Store, key ed25519.PrivateKey, |
| t.Fatal("guard must be an independent copy") |
| } |
| } |
| + |
| +type coldRootHarness struct { |
| + t *testing.T |
| + model *leasetest.VersionedBucket |
| + store *release.DirStore |
| + reg *registry.Registry |
| + client *http.Client |
| + ingress string |
| + cmd *exec.Cmd |
| + ctl func(...string) (string, error) |
| + env map[string]string |
| + leoS3, sophieS3 *coldRootS3Counts |
| + sophieEndpoint string |
| +} |
| + |
| +func newColdRootHarness(t *testing.T, mode string) *coldRootHarness { |
| + egressRootPrereqs(t) |
| + uid, gid := generationRunnerRegistryUser(t) |
| + for _, path := range []string{lifecycleHome, "/data", "/opt/carlos", "/run/carlos", "/run/carlos-control", "/etc/carlos", "/var/lib/carlos-claims", "/var/lib/carlos-release"} { |
| + lifecycleCheck(t, "exclusive root "+path, os.Mkdir(path, 0755)) |
| + t.Cleanup(func() { lifecycleCheck(t, "remove owned root "+path, os.RemoveAll(path)) }) |
| + } |
| + lifecycleCheck(t, "private root authority", os.Chmod("/var/lib/carlos-claims", 0700)) |
| + for _, path := range []string{lifecycleHome + "/deployment", "/data/.instances", "/data/instances", "/run/carlos/.instances", "/run/carlos/instances", "/run/carlos/.logs", "/run/carlos/logs", "/opt/carlos/versions"} { |
| + lifecycleCheck(t, "tree", os.MkdirAll(path, 0755)) |
| + } |
| + model := leasetest.NewVersionedBucket() |
| + model.AddBucket("data") |
| + s3, _ := leasetest.NewS3Server(model) |
| + var s3Handler http.Handler = lifecycleS3(s3, model) |
| + if mode == "competing" { |
| + s3Handler = coldRootRaceS3(s3Handler) |
| + } |
| + leoS3, sophieS3 := &coldRootS3Counts{}, &coldRootS3Counts{} |
| + server := httptest.NewServer(leoS3.handler(s3Handler)) |
| + receiverServer := httptest.NewServer(sophieS3.handler(s3Handler)) |
| + t.Cleanup(receiverServer.Close) |
| + t.Cleanup(server.Close) |
| + lifecycleEnvironment(t, server.URL) |
| + t.Setenv("CARLOS_HOST_CLAIM", "") |
| + t.Setenv("CARLOS_REGION_HA", "true") |
| + key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize)) |
| + store := release.NewDirStore(lifecycleHome + "/deployment") |
| + identity := handoverRecoveryIdentity(t, hostbox.Actor{Box: "box", Enrollment: strings.Repeat("a", 32), Revision: 1, Binding: "1", Region: "ie", FleetHomeRegion: "ie", ControlBucket: "deployment"}) |
| + identity.HomeRegion = "ie" |
| + actor, err := identity.Verify(t.Context()) |
| + lifecycleCheck(t, "guard fixture identity", err) |
| + binary, err := os.Executable() |
| + lifecycleCheck(t, "binary", err) |
| + image, err := os.ReadFile(binary) |
| + lifecycleCheck(t, "binary bytes", err) |
| + lifecycleCheck(t, "executor", os.WriteFile("/opt/carlos/carlos", image, 0755)) |
| + lifecycleCheck(t, "previous executor", os.WriteFile("/opt/carlos/carlos.prev", image, 0755)) |
| + sum := sha256.Sum256(image) |
| + platform := runtime.GOOS + "-" + runtime.GOARCH |
| + pointer := release.SystemPointer{Schema: 1, Component: "router", Channel: "stable", Spread: "0s", PromotedAt: time.Now(), Current: release.SystemRelease{Version: "v2.0.0", ReleaseTag: "v2.0.0", MovesProtocol: 1, Artifacts: map[string]release.SystemArtifact{platform: {Key: release.SystemArtifactKey("v2.0.0", platform), SHA256: hex.EncodeToString(sum[:])}}}} |
| + identityBytes, err := release.SignRootEnvelope(release.RootSigner(key), pointer) |
| + lifecycleCheck(t, "executor identity", err) |
| + identities, err := rootstate.Open("/opt/carlos/system/guard/identities", false, true) |
| + lifecycleCheck(t, "executor identities", err) |
| + lifecycleCheck(t, "executor identity persistence", identities.Write("v2.0.0.json", identityBytes)) |
| + identities.Close() |
| + roster := hostactors.Roster{V: 1, HomeRegion: "ie", DeploymentBucket: actor.ControlBucket, Revision: 1, RequestLimitNS: int64(hostbox.RequestLimit), Boxes: map[string]hostactors.Box{actor.Box: {BoxID: actor.Box, Enrollment: actor.Enrollment, Namespace: actor.Namespace, Label: actor.Box, Region: actor.Region, Pool: "default", Cloud: hostactors.Cloud{Provider: actor.Cloud.Provider, Account: actor.Cloud.Account, Region: actor.Cloud.Region, InstanceID: actor.Cloud.InstanceID}, EvidenceSHA256: strings.Repeat("c", 64), CensusPublicKey: ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2}, ed25519.SeedSize)).Public().(ed25519.PublicKey), State: "active"}}, Consoles: map[string]hostactors.Console{}, Holds: map[string]hostactors.Reservation{}, Activations: map[string]hostactors.Reservation{}} |
| + rosterBytes, err := release.SignRootEnvelope(release.RootSigner(key), roster) |
| + lifecycleCheck(t, "guard roster", err) |
| + _, err = store.Put(t.Context(), hostactors.Key, rosterBytes, "") |
| + lifecycleCheck(t, "guard roster persistence", err) |
| + filesSeedConstructionMigration(t, "/opt/carlos", actor.ControlBucket, actor.Box, actor.Enrollment) |
| + coldRootArmGuard(t, store, key, actor, pointer) |
| + censusState, err := rootstate.Open(rootparticipation.Namespace, true, false) |
| + lifecycleCheck(t, "census store", err) |
| + census := rootparticipation.Census{Schema: 1, Box: actor.Box, Enrollment: actor.Enrollment, Migration: 1, Revision: 1, LaunchRevision: 1, Complete: true} |
| + censusBytes, err := json.Marshal(census) |
| + lifecycleCheck(t, "census fixture", err) |
| + lifecycleCheck(t, "census persistence", censusState.Write("census.json", censusBytes)) |
| + censusState.Close() |
| + failures, err := rootstate.Open(rollout.RootFailuresDir, true, false) |
| + lifecycleCheck(t, "failures store", err) |
| + _, err = rollout.InitializeRootFailures(failures, rootUpdatesMigration(census), nil) |
| + lifecycleCheck(t, "failure migration", err) |
| + failures.Close() |
| + pins, err := rootstate.Open(release.RootGenerationsDir, true, false) |
| + lifecycleCheck(t, "generation pins", err) |
| + pins.Close() |
| + lifecycleInstallUnits(t) |
| + ctl := func(args ...string) (string, error) { |
| + out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + return string(out), err |
| + } |
| + for _, name := range []string{"carlos-edge.service", "carlos-instance-probe.service"} { |
| + raw, err := unitsFS.ReadFile("units/" + name) |
| + lifecycleCheck(t, "production unit", err) |
| + path := filepath.Join("/etc/systemd/system", name) |
| + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644) |
| + lifecycleCheck(t, "exclusive production unit", err) |
| + _, err = f.Write(raw) |
| + lifecycleCheck(t, "write production unit", err) |
| + lifecycleCheck(t, "close production unit", f.Close()) |
| + t.Cleanup(func() { _, _ = ctl("stop", name); _ = os.Remove(path); _, _ = ctl("daemon-reload") }) |
| + } |
| + secret := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)) |
| + caFile := lifecycleHome + "/root-ca.pem" |
| + coldRootCertificate(t, store, caFile) |
| + _, err = store.Put(t.Context(), "control/edge-mesh-key", []byte(strings.Repeat("a", 64)), "") |
| + lifecycleCheck(t, "mesh key", err) |
| + env := map[string]string{"COLD_ROOT_SHARED": lifecycleHome, "RHASIM_MUTATE": os.Getenv("RHASIM_MUTATE"), "COLD_ROOT_MODE": mode, "COLD_ROOT_BOX": "leo", "COLD_ROOT_HTTPS": "127.0.0.1:443", "PLAN14_LIFECYCLE_GUARD": "1", "CARLOS_HOST_CLAIM": "", "CARLOS_REGION_HA": "true", "CARLOS_HIBERNATE_BUCKET": "data", "CARLOS_HIBERNATE_REGION": "eu-west-1", "CARLOS_HIBERNATE_PREFIX": "instances", "CARLOS_DATA_DIR": "/data", "CARLOS_OPT_DIR": "/opt/carlos", "CARLOS_DEPLOYMENT_DIR": lifecycleHome + "/deployment", "CARLOS_DEPLOYMENT_BUCKET": actor.ControlBucket, "CARLOS_RELEASE_PUBKEY": base64.StdEncoding.EncodeToString(key.Public().(ed25519.PublicKey)), "CARLOS_SECRETS_KEY": secret, "CARLOS_S3_ENDPOINT": activationS3Fixture(t, store), "COLD_ROOT_DATA_ENDPOINT": server.URL, "AWS_ACCESS_KEY_ID": "test-key", "AWS_SECRET_ACCESS_KEY": "test-secret", "AWS_EC2_METADATA_DISABLED": "true", "AWS_CONFIG_FILE": "/nonexistent", "AWS_SHARED_CREDENTIALS_FILE": "/nonexistent", "AWS_REGION": "eu-west-1", "SSL_CERT_FILE": caFile, "TMPDIR": "/run/carlos", "PATH": os.Getenv("PATH")} |
| + var lines []string |
| + for name, value := range env { |
| + lines = append(lines, name+"="+value) |
| + } |
| + lifecycleCheck(t, "host environment", os.WriteFile("/etc/carlos/host.env", []byte(strings.Join(lines, "\n")+"\n"), 0600)) |
| + reg, err := openServiceRegistry("/data/registry.db") |
| + lifecycleCheck(t, "registry", err) |
| + t.Cleanup(func() { reg.Close() }) |
| + gateHash, err := gate.Hash("cold-root-password") |
| + lifecycleCheck(t, "selected gate", err) |
| + rec := provision.Record{Gate: gateHash, Schema: 1, Host: lifecycleHost, Account: "bab", App: "lifecycle", Channel: "stable", HA: true, CreatedAt: time.Now().UTC()} |
| + raw, err := json.Marshal(rec) |
| + lifecycleCheck(t, "record encode", err) |
| + _, err = store.Put(t.Context(), provision.RecordKey(rec.Account, rec.App, rec.Host), raw, "") |
| + lifecycleCheck(t, "record", err) |
| + sibling := rec |
| + sibling.Host = lifecycleSibling |
| + siblingRaw, err := json.Marshal(sibling) |
| + lifecycleCheck(t, "sibling record encode", err) |
| + _, err = store.Put(t.Context(), provision.RecordKey(sibling.Account, sibling.App, sibling.Host), siblingRaw, "") |
| + lifecycleCheck(t, "sibling record", err) |
| + cfg := provision.ReconcileConfig{DataDir: "/data", Layout: func(context.Context, release.Store) (string, error) { return release.LayoutModeNested, nil }} |
| + lifecycleCheck(t, "provision real HA record", provision.Reconcile(t.Context(), store, reg, cfg)) |
| + |
| + manifest := release.Manifest{App: "lifecycle", Version: "v1", Kind: "binary", Artifacts: map[string]release.Artifact{release.AdoptPlatform(): {}}} |
| + lifecycleCheck(t, "ship", release.Ship(t.Context(), store, "bab", manifest, map[string][]byte{release.AdoptPlatform(): image})) |
| + lifecycleCheck(t, "promote", release.Promote(t.Context(), store, key, "bab", "lifecycle", "stable", "v1")) |
| + _, _, err = release.StageSignedHead(t.Context(), store, key.Public().(ed25519.PublicKey), nil, "/opt/carlos", registry.Route{Host: lifecycleHost, Account: "bab", App: "lifecycle", Channel: "stable"}) |
| + |
| + lifecycleCheck(t, "stage signed app", err) |
| + lifecycleCheck(t, "point live", release.PointLive("/opt/carlos", lifecycleHost, "bab", "v1", "lifecycle")) |
| + lifecycleCheck(t, "point sibling live", release.PointLive("/opt/carlos", lifecycleSibling, "bab", "v1", "lifecycle")) |
| + for _, path := range []string{"/data", "/run/carlos", lifecycleHome} { |
| + lifecycleCheck(t, "fixture service owner", filepath.Walk(path, func(path string, _ os.FileInfo, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + return os.Chown(path, uid, gid) |
| + })) |
| + } |
| + var last []byte |
| + ident := edgesFile{Box: "leo", Region: "eu-west-1", Placement: "ie", DataBucket: "data", SecretsKeyFP: "shared", HibernationConfigured: true, Capabilities: []string{capRegionHA1}, Headroom: &edgeHeadroom{MemFreeMiB: 800, MemTotalMiB: 1000, DiskFreeMiB: 500, DiskTotalMiB: 1000}} |
| + lifecycleCheck(t, "selected publication", edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.1", &last, true)) |
| + ident.Box, ident.Headroom.MemFreeMiB = "sophie", 300 |
| + last = nil |
| + lifecycleCheck(t, "ingress publication", edgesFileWrite(t.Context(), store, reg, ident, "127.0.0.2", &last, true)) |
| + for _, name := range systemUnitFiles { |
| + path := filepath.Join("/etc/systemd/system", name) |
| + if _, e := os.Lstat(path); os.IsNotExist(e) { |
| + t.Cleanup(func() { _, _ = ctl("disable", "--now", name); _ = os.Remove(path); _, _ = ctl("daemon-reload") }) |
| + } |
| + } |
| + |
| + controlDropin := "/etc/systemd/system/carlos-instance-control.service.d" |
| + lifecycleCheck(t, "exclusive control fixture environment", os.Mkdir(controlDropin, 0755)) |
| + lifecycleCheck(t, "control fixture environment", os.WriteFile(filepath.Join(controlDropin, "10-cold-root.conf"), []byte("[Service]\nEnvironmentFile=/etc/carlos/host.env\n"), 0644)) |
| + t.Cleanup(func() { |
| + _, _ = ctl("stop", "carlos-instance-control.service") |
| + _ = os.RemoveAll(controlDropin) |
| + _, _ = ctl("daemon-reload") |
| + }) |
| + ensureSystemUnits("/etc", "/opt/carlos/system/router/lock", ctl, ctl, t.Logf) |
| + out, err := ctl("daemon-reload") |
| + lifecycleCheck(t, out, err) |
| + out, err = ctl("start", "data-instances.mount", "run-carlos-instances.mount", "run-carlos-logs.mount") |
| + lifecycleCheck(t, out, err) |
| + dropin := "/run/systemd/system/carlos-edge.service.d" |
| + lifecycleCheck(t, "exclusive edge fixture drop-in", os.Mkdir(dropin, 0755)) |
| + lifecycleCheck(t, "disable fixture automatic restart", os.WriteFile(filepath.Join(dropin, "10-cold-root.conf"), []byte("[Service]\nRestart=no\n"), 0644)) |
| + t.Cleanup(func() { |
| + _, _ = ctl("stop", "carlos-edge.service") |
| + _ = os.RemoveAll(dropin) |
| + _, _ = ctl("daemon-reload") |
| + }) |
| + _, err = ctl("daemon-reload") |
| + lifecycleCheck(t, "fixture daemon reload", err) |
| + coldRootProbeFixtures(t, uid, gid) |
| + coldRootPrepareView(t, store, mode) |
| + if mode == "switch-off" { |
| + env["CARLOS_REGION_HA"] = "0" |
| + } |
| + if mode == "missing-proof" { |
| + env["COLD_ROOT_NO_PROOF"] = "1" |
| + } |
| + var envLines []string |
| + for k, v := range env { |
| + envLines = append(envLines, k+"="+v) |
| + } |
| + lifecycleCheck(t, "scenario environment", os.WriteFile("/etc/carlos/host.env", []byte(strings.Join(envLines, "\n")+"\n"), 0600)) |
| + out, err = ctl("start", "carlos-edge.service") |
| + lifecycleCheck(t, out, err) |
| + ingress := "/data/cold-sophie" |
| + lifecycleCheck(t, "ingress dir", os.Mkdir(ingress, 0755)) |
| + lifecycleCheck(t, "ingress owner", os.Chown(ingress, uid, gid)) |
| + ingressReg, err := registry.Open(filepath.Join(ingress, "registry.db")) |
| + lifecycleCheck(t, "ingress registry", err) |
| + route, err := reg.Get(lifecycleHost) |
| + lifecycleCheck(t, "provisioned row", err) |
| + if route == nil || !route.HA { |
| + t.Fatal("provisioning did not produce an HA route") |
| + } |
| + ingressRoute := *route |
| + if mode == "production" { |
| + ingressRoute.Gate, err = gate.Hash("ingress-must-not-run-this-gate") |
| + } |
| + lifecycleCheck(t, "ingress gate", err) |
| + lifecycleCheck(t, "ingress row", ingressReg.Upsert(ingressRoute)) |
| + siblingRoute, err := reg.Get(lifecycleSibling) |
| + lifecycleCheck(t, "sibling route", err) |
| + if siblingRoute == nil { |
| + t.Fatal("missing provisioned sibling") |
| + } |
| + lifecycleCheck(t, "ingress sibling row", ingressReg.Upsert(*siblingRoute)) |
| + ingressReg.Close() |
| + lifecycleCheck(t, "ingress registry owner", filepath.Walk(ingress, func(p string, _ os.FileInfo, e error) error { |
| + if e != nil { |
| + return e |
| + } |
| + return os.Chown(p, uid, gid) |
| + })) |
| + addr := "127.0.0.2:443" |
| + cmd := exec.Command(binary, "-test.run=^TestColdPlacementRootAgent$", "-test.v", "-test.timeout=15m") |
| + cmd.Dir = ingress |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}} |
| + for name, value := range env { |
| + switch name { |
| + case "COLD_ROOT_DATA_ENDPOINT": |
| + value = receiverServer.URL |
| + case "CARLOS_DEPLOYMENT_DIR": |
| + if mode == "competing" { |
| + value = coldRootDivergentView(t, ingress) |
| + } |
| + case "COLD_ROOT_NO_PROOF": |
| + value = "" |
| + case "COLD_ROOT_BOX": |
| + value = "sophie" |
| + case "COLD_ROOT_HTTPS": |
| + value = addr |
| + case "CARLOS_DATA_DIR": |
| + value = ingress |
| + case "TMPDIR": |
| + value = ingress |
| + } |
| + cmd.Env = append(cmd.Env, name+"="+value) |
| + } |
| + log, err := os.Create(filepath.Join(ingress, "edge.log")) |
| + lifecycleCheck(t, "ingress log", err) |
| + cmd.Stdout, cmd.Stderr = log, log |
| + lifecycleCheck(t, "start ingress process", cmd.Start()) |
| + t.Cleanup(func() { |
| + _ = cmd.Process.Signal(os.Interrupt) |
| + timer := time.AfterFunc(15*time.Second, func() { _ = cmd.Process.Kill() }) |
| + _ = cmd.Wait() |
| + timer.Stop() |
| + log.Close() |
| + }) |
| + caBytes, err := os.ReadFile(caFile) |
| + lifecycleCheck(t, "parent CA", err) |
| + pool := x509.NewCertPool() |
| + if !pool.AppendCertsFromPEM(caBytes) { |
| + t.Fatal("invalid fixture CA") |
| + } |
| + client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}, DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, network, addr) |
| + }}, Timeout: 45 * time.Second} |
| + t.Cleanup(client.CloseIdleConnections) |
| + deadline := time.Now().Add(2 * time.Minute) |
| + for { |
| + conn, err := net.DialTimeout("tcp", addr, time.Second) |
| + if err == nil { |
| + conn.Close() |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + raw, _ := os.ReadFile(log.Name()) |
| + t.Fatalf("ingress never listened: %s", raw) |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + |
| + f := &coldRootHarness{t: t, model: model, store: store, reg: reg, client: client, ingress: ingress, cmd: cmd, ctl: ctl, env: env, leoS3: leoS3, sophieS3: sophieS3, sophieEndpoint: receiverServer.URL} |
| + f.waitLeo() |
| + return f |
| +} |
diff --git a/internal/host/haplacement_scenarios_root_linux_test.go b/internal/host/haplacement_scenarios_root_linux_test.go| new file mode 100644 |
| index 000000000..08ab9e848 |
| --- /dev/null |
| +++ b/internal/host/haplacement_scenarios_root_linux_test.go |
| @@ -0,0 +1,952 @@ |
| +//go:build linux && rootrunner |
| + |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "encoding/json" |
| + "fmt" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "io" |
| + "log" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "syscall" |
| + "testing" |
| + "time" |
| + "unsafe" |
| + |
| + "encoding/base64" |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/ec2" |
| + "github.com/aws/aws-sdk-go-v2/service/ec2/types" |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "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/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Only EC2's response is substituted. Confirmer still validates the account, |
| +// region, instance ID, state and cache before AcquireHA can use the proof. |
| +type coldRootEC2 struct{ dir string } |
| + |
| +func (f coldRootEC2) DescribeInstances(_ context.Context, in *ec2.DescribeInstancesInput, _ ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) { |
| + count, err := os.OpenFile(filepath.Join(f.dir, "ec2-describes"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666) |
| + if err != nil { |
| + return nil, err |
| + } |
| + _, err = count.WriteString(in.InstanceIds[0] + "\n") |
| + count.Close() |
| + if err != nil { |
| + return nil, err |
| + } |
| + raw, err := os.ReadFile(filepath.Join(f.dir, "ec2-state")) |
| + if os.IsNotExist(err) { |
| + raw = []byte("running") |
| + } else if err != nil { |
| + return nil, err |
| + } |
| + if strings.TrimSpace(string(raw)) == "error" { |
| + return nil, fmt.Errorf("fixture describe unavailable") |
| + } |
| + return &ec2.DescribeInstancesOutput{Reservations: []types.Reservation{{OwnerId: aws.String("111122223333"), Instances: []types.Instance{{InstanceId: aws.String(in.InstanceIds[0]), State: &types.InstanceState{Name: types.InstanceStateName(strings.TrimSpace(string(raw)))}}}}}}, nil |
| +} |
| + |
| +//go:linkname coldRootHomeRefreshKeys github.com/carlosframework/platform/internal/edge.(*homeMap).refreshKeys |
| +func coldRootHomeRefreshKeys(unsafe.Pointer, context.Context) error |
| + |
| +//go:linkname coldRootDial github.com/carlosframework/platform/internal/edge.forwardDial |
| +var coldRootDial func(context.Context, string, string) (net.Conn, error) |
| + |
| +func coldRootIP(ref string) string { |
| + if ref == "leo" { |
| + return "127.0.0.1" |
| + } |
| + return "127.0.0.2" |
| +} |
| +func coldRootIdentity(ref string, free int64) edgesFile { |
| + return edgesFile{Box: ref, Region: "eu-west-1", Placement: "ie", DataBucket: "data", SecretsKeyFP: "shared", HibernationConfigured: true, Capabilities: []string{capRegionHA1}, Headroom: &edgeHeadroom{MemFreeMiB: free, MemTotalMiB: 1000, DiskFreeMiB: 500, DiskTotalMiB: 1000}} |
| +} |
| +func coldRootPrepareView(t *testing.T, store release.Store, mode string) { |
| + for _, ref := range []string{"leo", "sophie"} { |
| + raw, etag, err := store.Get(t.Context(), edgesFileKey(ref)) |
| + lifecycleCheck(t, "published view", err) |
| + var view map[string]json.RawMessage |
| + lifecycleCheck(t, "decode view", json.Unmarshal(raw, &view)) |
| + switch mode { |
| + case "production": |
| + var hr edgeHeadroom |
| + lifecycleCheck(t, "headroom", json.Unmarshal(view["headroom"], &hr)) |
| + hr.MemFreeMiB /= 10 |
| + view["headroom"], _ = json.Marshal(hr) |
| + case "switch-off": |
| + view["capabilities"] = json.RawMessage(`[]`) |
| + case "new-host": |
| + view["hosts"] = json.RawMessage(`[]`) |
| + case "stale-own": |
| + if ref == "sophie" { |
| + view["generation"], _ = json.Marshal(time.Now().Add(-16 * time.Minute).UTC().Format(time.RFC3339)) |
| + } |
| + case "competing": |
| + // Leo's immutable fold chooses sophie; sophie's independent fold below |
| + // chooses leo. Both receivers must still race the same conditional lock. |
| + if ref == "leo" { |
| + var hr edgeHeadroom |
| + lifecycleCheck(t, "headroom", json.Unmarshal(view["headroom"], &hr)) |
| + hr.MemFreeMiB = 200 |
| + view["headroom"], _ = json.Marshal(hr) |
| + } |
| + case "no-key": |
| + } |
| + raw, err = json.Marshal(view) |
| + lifecycleCheck(t, "encode view", err) |
| + _, err = store.Put(t.Context(), edgesFileKey(ref), raw, etag) |
| + lifecycleCheck(t, "scenario publication", err) |
| + } |
| + if mode == "no-key" { |
| + lifecycleCheck(t, "remove mirrored key", store.Delete(t.Context(), "control/edge-mesh-key")) |
| + } |
| +} |
| +func coldRootDivergentView(t *testing.T, root string) string { |
| + dst := filepath.Join(root, "view") |
| + // Immutable release artifacts are hardlinked, not copied. Only edges files |
| + // are copied, so the two children can retain deliberately different folds. |
| + src := lifecycleHome + "/deployment" |
| + lifecycleCheck(t, "independent fold", filepath.Walk(src, func(p string, info os.FileInfo, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + rel, err := filepath.Rel(src, p) |
| + if err != nil { |
| + return err |
| + } |
| + target := filepath.Join(dst, rel) |
| + if info.IsDir() { |
| + return os.MkdirAll(target, 0755) |
| + } |
| + if strings.Contains(rel, "edges/") { |
| + raw, err := os.ReadFile(p) |
| + if err != nil { |
| + return err |
| + } |
| + return os.WriteFile(target, raw, 0644) |
| + } |
| + return os.Link(p, target) |
| + })) |
| + ds := release.NewDirStore(dst) |
| + raw, etag, err := ds.Get(t.Context(), edgesFileKey("leo")) |
| + lifecycleCheck(t, "divergent file", err) |
| + var view edgesFile |
| + lifecycleCheck(t, "divergent decode", json.Unmarshal(raw, &view)) |
| + view.Headroom.MemFreeMiB = 900 |
| + raw, err = json.Marshal(view) |
| + lifecycleCheck(t, "divergent encode", err) |
| + _, err = ds.Put(t.Context(), edgesFileKey("leo"), raw, etag) |
| + lifecycleCheck(t, "divergent put", err) |
| + return dst |
| +} |
| +func (f *coldRootHarness) request(ref, host string) (int, string, http.Header) { |
| + f.t.Helper() |
| + client := f.client |
| + if ref == "leo" { |
| + client = coldRootClient(f.t, "127.0.0.1:443") |
| + defer client.CloseIdleConnections() |
| + } |
| + req, err := http.NewRequest("GET", "https://"+host+"/", nil) |
| + lifecycleCheck(f.t, "request", err) |
| + req.SetBasicAuth("", "cold-root-password") |
| + response, err := client.Do(req) |
| + lifecycleCheck(f.t, "request "+ref, err) |
| + defer response.Body.Close() |
| + raw, err := io.ReadAll(response.Body) |
| + lifecycleCheck(f.t, "response", err) |
| + return response.StatusCode, string(raw), response.Header |
| +} |
| +func (f *coldRootHarness) served(ref string) { |
| + f.t.Helper() |
| + code, body, _ := f.request(ref, lifecycleHost) |
| + if code != 200 || body != "lifecycle tenant" { |
| + f.t.Fatalf("%s: %d %q", ref, code, body) |
| + } |
| +} |
| +func (f *coldRootHarness) refused(ref string) { |
| + f.t.Helper() |
| + code, body, h := f.request(ref, lifecycleHost) |
| + if code != 503 || h.Get("Retry-After") == "" { |
| + f.t.Fatalf("%s: expected retryable refusal, got %d %q %v", ref, code, body, h) |
| + } |
| +} |
| +func (f *coldRootHarness) owner() string { |
| + f.t.Helper() |
| + v, err := lease.ReadLock(f.t.Context(), "data", "instances/"+lifecycleHost, "eu-west-1") |
| + lifecycleCheck(f.t, "owner read", err) |
| + o, ok := hafresh.ParseOwner(v.Lock.Owner) |
| + if !ok { |
| + f.t.Fatalf("not an HA writer: %+v", v) |
| + } |
| + return o.Ref |
| +} |
| +func (f *coldRootHarness) admin(ref, path string) { |
| + f.t.Helper() |
| + dir := "/data" |
| + if ref == "sophie" { |
| + dir = f.ingress |
| + } |
| + raw, err := os.ReadFile(filepath.Join(dir, "cold-root-admin")) |
| + lifecycleCheck(f.t, "admin address", err) |
| + client := &http.Client{Timeout: 40 * time.Second} |
| + defer client.CloseIdleConnections() |
| + response, err := client.Get(string(raw) + path) |
| + lifecycleCheck(f.t, "admin "+path, err) |
| + defer response.Body.Close() |
| + if response.StatusCode != 204 { |
| + body, _ := io.ReadAll(response.Body) |
| + f.t.Fatalf("admin %s: %d %s", path, response.StatusCode, body) |
| + } |
| +} |
| +func coldRootProductionWiring(t *testing.T) { |
| + f := newColdRootHarness(t, "production") |
| + f.served("sophie") |
| + if got := f.sophieS3.values(); got != [4]int64{1, 0, 0, 0} { |
| + t.Fatalf("ingress placement S3: %v", got) |
| + } |
| + if got := f.leoS3.values(); got != [4]int64{1, 1, 1, 0} { |
| + t.Fatalf("selected absent acquire S3: %v", got) |
| + } |
| + selected, ingress := coldRootReadStats(t, "/data"), coldRootReadStats(t, f.ingress) |
| + if !selected.Owned || ingress.Owned || selected.Apps["bab/lifecycle"] != 1 { |
| + t.Fatalf("writer/arming selected=%+v ingress=%+v", selected, ingress) |
| + } |
| + selectedChecks, ingressChecks := int64(0), int64(0) |
| + for _, g := range selected.Meter.Guard { |
| + selectedChecks += g.Checked |
| + } |
| + for _, g := range ingress.Meter.Guard { |
| + ingressChecks += g.Checked |
| + } |
| + if row := selected.Meter.Rows[lifecycleHost]; row.Requests != 1 || row.HopRequests != 1 || ingress.Meter.Rows[lifecycleHost].Requests != 0 || selectedChecks != 1 || ingressChecks != 0 || selected.Analytics != 1 || ingress.Analytics != 0 { |
| + t.Fatalf("accounting selected=%+v ingress=%+v", selected, ingress) |
| + } |
| + deadline := time.Now().Add(5 * time.Second) |
| + for len(ingress.Pages) == 0 && time.Now().Before(deadline) { |
| + time.Sleep(20 * time.Millisecond) |
| + ingress = coldRootReadStats(t, f.ingress) |
| + } |
| + want := coldRootPage{"warning", "Region eu-west-1 needs more capacity", "Region eu-west-1 is short on spare capacity. Instance " + lifecycleHost + " is waking on leo. Add capacity to the region."} |
| + if len(ingress.Pages) != 1 || ingress.Pages[0] != want { |
| + t.Fatalf("capacity page: %+v, want %+v", ingress.Pages, want) |
| + } |
| + f.admin("leo", "/publish") |
| + raw, _, err := f.store.Get(t.Context(), edgesFileKey("leo")) |
| + lifecycleCheck(t, "owned Apps publication", err) |
| + var published edgesFile |
| + lifecycleCheck(t, "Apps decode", json.Unmarshal(raw, &published)) |
| + if published.Headroom == nil || published.Headroom.Apps["bab/lifecycle"] != 1 { |
| + t.Fatalf("published Apps: %s", raw) |
| + } |
| + if f.owner() != "leo" { |
| + t.Fatal("non-choice ingress acquired") |
| + } |
| + beforeA, beforeB := f.leoS3.values(), f.sophieS3.values() |
| + f.served("sophie") |
| + f.served("leo") |
| + if f.leoS3.values() != beforeA || f.sophieS3.values() != beforeB { |
| + t.Fatal("awake or positive-holder request added lease calls") |
| + } |
| +} |
| +func coldRootCompetingViews(t *testing.T) { |
| + f := newColdRootHarness(t, "competing") |
| + start := make(chan struct{}) |
| + var wg sync.WaitGroup |
| + codes := make(chan int, 2) |
| + for _, ref := range []string{"leo", "sophie"} { |
| + wg.Add(1) |
| + go func(ref string) { |
| + defer wg.Done() |
| + <-start |
| + code, _, h := f.request(ref, lifecycleHost) |
| + if code != 200 && (code != 503 || h.Get("Retry-After") == "") { |
| + t.Errorf("loser %d %v", code, h) |
| + } |
| + codes <- code |
| + }(ref) |
| + } |
| + close(start) |
| + wg.Wait() |
| + close(codes) |
| + wins, losses := 0, 0 |
| + for code := range codes { |
| + if code == 200 { |
| + wins++ |
| + } else if code == 503 { |
| + losses++ |
| + } |
| + } |
| + if wins != 1 || losses != 1 { |
| + t.Fatalf("competing choices: successes=%d retryable=%d", wins, losses) |
| + } |
| + a, b := coldRootReadStats(t, "/data"), coldRootReadStats(t, f.ingress) |
| + if a.Dials != 1 || b.Dials != 1 { |
| + t.Fatalf("receiver forwarded onward: dials=%d/%d", a.Dials, b.Dials) |
| + } |
| + starts, err := os.ReadFile(filepath.Join(provision.InstanceDir("/data", lifecycleHost), "cold-starts")) |
| + lifecycleCheck(t, "actual starts", err) |
| + if string(starts) != "start\n" { |
| + t.Fatalf("conditional race launched more than once: %q", starts) |
| + } |
| + if a.Owned == b.Owned { |
| + t.Fatalf("expected one started owner: %+v %+v", a, b) |
| + } |
| + for _, s := range []coldRootStats{a, b} { |
| + for _, row := range s.Meter.Rows { |
| + if row.HopRequests > row.Requests || row.HopRequests > 1 { |
| + t.Fatalf("onward hop/accounting: %+v", s) |
| + } |
| + } |
| + } |
| +} |
| +func coldRootSwitchOff(t *testing.T) { |
| + f := newColdRootHarness(t, "switch-off") |
| + f.served("leo") |
| + if f.owner() != "leo" { |
| + t.Fatal("switch-off did not use local HA acquire") |
| + } |
| + f.served("sophie") |
| + if coldRootReadStats(t, f.ingress).Owned { |
| + t.Fatal("switch-off stopped following the true holder") |
| + } |
| +} |
| +func coldRootNewHost(t *testing.T) { |
| + for _, mode := range []string{"new-host", "stale-own"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f := newColdRootHarness(t, mode) |
| + f.served("sophie") |
| + if f.owner() != "sophie" { |
| + t.Fatal("missing/stale placement forced peer instead of Base") |
| + } |
| + }) |
| + } |
| +} |
| +func (f *coldRootHarness) crashLeo() { |
| + out, err := f.ctl("kill", "--kill-whom=main", "--signal=KILL", "carlos-edge.service") |
| + lifecycleCheck(f.t, "crash: "+out, err) |
| + out, err = f.ctl("stop", "carlos-edge.service") |
| + lifecycleCheck(f.t, "stop-and-prove: "+out, err) |
| + if state, _ := f.ctl("show", instancectl.UnitName(instancectl.RoleRun, lifecycleHost), "-p", "ActiveState", "--value"); strings.TrimSpace(state) == "active" { |
| + f.t.Fatal("writer survived stop-and-prove") |
| + } |
| + v, err := lease.ReadLock(f.t.Context(), "data", "instances/"+lifecycleHost, "eu-west-1") |
| + lifecycleCheck(f.t, "crash lock", err) |
| + if v.Lock.Release != nil { |
| + f.t.Fatal("crash fabricated marker") |
| + } |
| +} |
| +func (f *coldRootHarness) expireOwner() { |
| + v, err := lease.ReadLock(f.t.Context(), "data", "instances/"+lifecycleHost, "eu-west-1") |
| + lifecycleCheck(f.t, "expired fixture", err) |
| + v.Lock.ExpiresAt = time.Now().Add(-time.Minute) |
| + raw, err := json.Marshal(v.Lock) |
| + lifecycleCheck(f.t, "expired encode", err) |
| + f.model.Put("data", "instances/"+lifecycleHost+"/lock.json", raw) |
| +} |
| +func coldRootExpiredOwner(t *testing.T) { |
| + t.Run("expiry-equality", testColdPlacementExpiryEquality) |
| + t.Run("pre-expiry", func(t *testing.T) { |
| + f := newColdRootHarness(t, "normal") |
| + f.served("sophie") |
| + f.crashLeo() |
| + f.restartLeo() |
| + f.refused("leo") |
| + f.refused("sophie") |
| + }) |
| + t.Run("two-ingresses", func(t *testing.T) { |
| + for _, ingress := range []string{"leo", "sophie"} { |
| + t.Run(ingress, func(t *testing.T) { |
| + f := newColdRootHarness(t, "normal") |
| + f.served("sophie") |
| + f.crashLeo() |
| + f.expireOwner() |
| + // Sophie has more published memory, but neither ingress may place around |
| + // a living expired owner. Restart's production sweep supplies the proof. |
| + raw, etag, err := f.store.Get(t.Context(), edgesFileKey("sophie")) |
| + lifecycleCheck(t, "roomier peer", err) |
| + var view edgesFile |
| + lifecycleCheck(t, "peer", json.Unmarshal(raw, &view)) |
| + view.Headroom.MemFreeMiB = 950 |
| + raw, _ = json.Marshal(view) |
| + _, err = f.store.Put(t.Context(), edgesFileKey("sophie"), raw, etag) |
| + lifecycleCheck(t, "peer publish", err) |
| + out, err := f.ctl("reset-failed", "carlos-edge.service") |
| + lifecycleCheck(t, out, err) |
| + out, err = f.ctl("start", "carlos-edge.service") |
| + lifecycleCheck(t, out, err) |
| + f.waitLeo() |
| + f.restartSophie() |
| + f.served(ingress) |
| + f.served("leo") |
| + f.served("sophie") |
| + if f.owner() != "leo" || coldRootReadStats(t, f.ingress).Owned { |
| + t.Fatal("placement displaced living expired owner") |
| + } |
| + }) |
| + } |
| + }) |
| + t.Run("missing-proof", func(t *testing.T) { |
| + f := newColdRootHarness(t, "missing-proof") |
| + f.served("sophie") |
| + f.crashLeo() |
| + f.expireOwner() |
| + out, err := f.ctl("reset-failed", "carlos-edge.service") |
| + lifecycleCheck(t, out, err) |
| + out, err = f.ctl("start", "carlos-edge.service") |
| + lifecycleCheck(t, out, err) |
| + f.waitLeo() |
| + f.refused("leo") |
| + f.refused("sophie") |
| + if coldRootReadStats(t, f.ingress).Owned { |
| + t.Fatal("missing emptiness proof permitted peer start") |
| + } |
| + }) |
| + t.Run("terminated-after-failed-recovery", func(t *testing.T) { |
| + f := newColdRootHarness(t, "normal") |
| + f.served("sophie") |
| + f.crashLeo() |
| + f.expireOwner() |
| + // Reset sophie's positive holder cache with a new process after the crash. |
| + f.keepControlHost() |
| + f.restartSophie() |
| + f.refused("sophie") |
| + lifecycleCheck(t, "termination evidence", os.WriteFile(filepath.Join(lifecycleHome, "ec2-state"), []byte("terminated"), 0644)) |
| + // No describe has run on the failed Recovery dial. The next Base request |
| + // must obtain real confirmation from the low-level EC2 response now. |
| + f.served("sophie") |
| + if f.owner() != "sophie" { |
| + t.Fatal("confirmed termination stranded behind fresh owner file") |
| + } |
| + describes, err := os.ReadFile(filepath.Join(lifecycleHome, "ec2-describes")) |
| + lifecycleCheck(t, "describe budget", err) |
| + if string(describes) != "i-leo\n" { |
| + t.Fatalf("describe attempts: %q", describes) |
| + } |
| + }) |
| +} |
| +func coldRootDeadChoice(t *testing.T) { |
| + for _, marker := range []bool{false, true} { |
| + t.Run(fmt.Sprint(marker), func(t *testing.T) { |
| + f := newColdRootHarness(t, "normal") |
| + if marker { |
| + raw, err := hafresh.MarkerBody(1, hafresh.Marker{V: 1, Box: "leo", IID: "i-leo", Clean: true}) |
| + lifecycleCheck(t, "marker", err) |
| + f.model.Put("data", "instances/"+lifecycleHost+"/lock.json", raw) |
| + } |
| + out, err := f.ctl("stop", "carlos-edge.service") |
| + lifecycleCheck(t, out, err) |
| + f.keepControlHost() |
| + f.refused("sophie") |
| + if coldRootReadStats(t, f.ingress).Owned { |
| + t.Fatal("failed choice fell back within same request") |
| + } |
| + started := time.Now() |
| + f.servedHost("sophie", lifecycleSibling) |
| + f.served("sophie") |
| + if stats := coldRootReadStats(t, f.ingress); stats.Dials != 1 { |
| + t.Fatalf("dead target redial: %d", stats.Dials) |
| + } |
| + if time.Since(started) >= 10*time.Second || f.owner() != "sophie" { |
| + t.Fatal("suspect choice did not recover within ten seconds") |
| + } |
| + }) |
| + } |
| +} |
| +func coldRootUnusableChoice(t *testing.T) { |
| + t.Run("no-mirrored-key", func(t *testing.T) { |
| + f := newColdRootHarness(t, "no-key") |
| + f.served("sophie") |
| + if f.owner() != "sophie" { |
| + t.Fatal("no-key projection attempted a peer") |
| + } |
| + if stats := coldRootReadStats(t, f.ingress); stats.Dials != 0 { |
| + t.Fatalf("keyless peer dial: %d", stats.Dials) |
| + } |
| + }) |
| + for _, mode := range []string{"none", "headerless", "hang", "out-of-view", "key-lost"} { |
| + t.Run(mode, func(t *testing.T) { coldRootFaultWake(t, mode) }) |
| + } |
| +} |
| +func coldRootSealedWake(t *testing.T) { |
| + f := newColdRootHarness(t, "normal") |
| + f.served("sophie") |
| + root := provision.InstanceDir("/data", lifecycleHost) |
| + // The tenant-owned trio is changed through the real files publisher, then |
| + // stopped through Service.Shutdown and root's stop-and-prove. |
| + lifecycleCheck(t, "tenant files directory", os.MkdirAll(filepath.Join(root, lifecycleHost), 0700)) |
| + lifecycleCheck(t, "tenant key", os.WriteFile(filepath.Join(root, lifecycleHost, "instance.key"), []byte("original-instance-key"), 0600)) |
| + lifecycleCheck(t, "tenant token", os.WriteFile(filepath.Join(root, lifecycleHost, "report.token"), []byte("original-report-token"), 0600)) |
| + uid, gid := generationRunnerRegistryUser(t) |
| + lifecycleCheck(t, "tenant trio ownership", filepath.Walk(filepath.Join(root, lifecycleHost), func(p string, _ os.FileInfo, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + return os.Chown(p, uid, gid) |
| + })) |
| + f.waitReplica() |
| + f.admin("leo", "/shutdown") |
| + v, err := lease.ReadLock(t.Context(), "data", "instances/"+lifecycleHost, "eu-west-1") |
| + lifecycleCheck(t, "clean marker", err) |
| + if v.Lock.Release == nil || !v.Lock.Release.Clean { |
| + t.Fatalf("not a real clean release: %+v", v) |
| + } |
| + before := coldRootSecrets(t, root) |
| + beforeDB, err := os.Stat(provision.NestedDBPath("/data", lifecycleHost)) |
| + lifecycleCheck(t, "kept DB inode", err) |
| + // Restart leo to serve again; the eligible releaser must retain its local |
| + // DB and secrets, even though the request enters on sophie. |
| + f.restartLeo() |
| + f.restartSophie() |
| + f.served("sophie") |
| + if f.owner() != "leo" { |
| + t.Fatal("eligible clean releaser not preferred") |
| + } |
| + if got := coldRootSecrets(t, root); !bytes.Equal(before, got) { |
| + t.Fatal("kept wake changed sealed secrets") |
| + } |
| + keptDB, err := os.Stat(provision.NestedDBPath("/data", lifecycleHost)) |
| + lifecycleCheck(t, "kept inode", err) |
| + if !os.SameFile(beforeDB, keptDB) { |
| + t.Fatal("eligible releaser restored instead of keeping local DB") |
| + } |
| + f.admin("leo", "/shutdown") |
| + f.restartSophie() |
| + // Make releaser ineligible before the new fold. No running tenant remains. |
| + raw, etag, err := f.store.Get(t.Context(), edgesFileKey("leo")) |
| + lifecycleCheck(t, "releaser file", err) |
| + var view edgesFile |
| + lifecycleCheck(t, "releaser decode", json.Unmarshal(raw, &view)) |
| + view.Headroom.MemFreeMiB = 1 |
| + raw, _ = json.Marshal(view) |
| + _, err = f.store.Put(t.Context(), edgesFileKey("leo"), raw, etag) |
| + lifecycleCheck(t, "ineligible releaser", err) |
| + f.restartSophie() |
| + f.served("sophie") |
| + if f.owner() != "sophie" { |
| + t.Fatal("ineligible releaser retained affinity") |
| + } |
| + if got := coldRootSecrets(t, root); !bytes.Equal(before, got) { |
| + t.Fatal("restore reminted key/token/env") |
| + } |
| + restoredDB, err := os.Stat(provision.NestedDBPath("/data", lifecycleHost)) |
| + lifecycleCheck(t, "restored DB inode", err) |
| + if os.SameFile(keptDB, restoredDB) { |
| + t.Fatal("cross-box wake retained local DB instead of real restore") |
| + } |
| + files, err := newProductionFilesStore(t.Context(), "data", "eu-west-1") |
| + lifecycleCheck(t, "files store", err) |
| + m, _, err := hostfiles.Load(t.Context(), files, "instances/"+lifecycleHost+"/files/0/") |
| + lifecycleCheck(t, "sealed manifest", err) |
| + for _, item := range []string{hostfiles.SealedEnvItem, "instance.key.sealed", "report.token.sealed"} { |
| + e, ok := m.Platform[item] |
| + if !ok || e.Sealed == "" { |
| + t.Fatalf("missing sealed %s: %+v", item, m) |
| + } |
| + } |
| + if e, ok := m.Platform[hostfiles.EnvItem]; ok && !e.Deleted { |
| + t.Fatalf("raw env published: %+v", e) |
| + } |
| + for _, item := range []string{"instance.key", "report.token"} { |
| + if e, ok := m.Entries[item]; ok && !e.Deleted { |
| + t.Fatalf("raw secret published %s: %+v", item, e) |
| + } |
| + } |
| + // Force a changed env publish after restore. The existing minted variables |
| + // must be retained while stageEscrowReads validates the held sealed baseline. |
| + env := filepath.Join(root, lifecycleHost+".env") |
| + raw, err = os.ReadFile(env) |
| + lifecycleCheck(t, "env", err) |
| + raw = append(raw, []byte("EXTRA=after-restore\n")...) |
| + lifecycleCheck(t, "env update", os.WriteFile(env, raw, 0600)) |
| + deadline := time.Now().Add(5 * time.Second) |
| + sealer, err := hostfiles.NewItemSealer(haEscrowKey(base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))), appconfig.Binding{Account: "bab", App: "lifecycle"}, lifecycleHost) |
| + lifecycleCheck(t, "original binding", err) |
| + var restoredEnv []byte |
| + for time.Now().Before(deadline) { |
| + m, _, err = hostfiles.Load(t.Context(), files, "instances/"+lifecycleHost+"/files/0/") |
| + lifecycleCheck(t, "escrow publication", err) |
| + restoredEnv, err = hostfiles.ReadSealed(t.Context(), files, "instances/"+lifecycleHost+"/files/0/", m, hostfiles.SealedEnvItem, nil, sealer) |
| + lifecycleCheck(t, "open sealed env", err) |
| + if bytes.Contains(restoredEnv, []byte("EXTRA=after-restore")) { |
| + break |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + if !bytes.Equal(restoredEnv, raw) { |
| + t.Fatal("stageEscrowReads did not retain original minted variables while publishing edited env") |
| + } |
| + versions, err := f.model.ListVersions(t.Context(), "data", "instances/"+lifecycleHost+"/files/0/") |
| + lifecycleCheck(t, "raw secret audit", err) |
| + for _, v := range versions { |
| + if v.DeleteMarker { |
| + continue |
| + } |
| + body, err := f.model.GetVersion(t.Context(), "data", v.Key, v.VersionID) |
| + lifecycleCheck(t, "published object", err) |
| + if bytes.Contains(body, []byte("original-instance-key")) || bytes.Contains(body, []byte("original-report-token")) { |
| + t.Fatalf("raw trio uploaded at %s", v.Key) |
| + } |
| + } |
| + f.served("sophie") |
| +} |
| +func coldRootSecrets(t *testing.T, root string) []byte { |
| + var out []byte |
| + for _, rel := range []string{lifecycleHost + ".env", lifecycleHost + "/instance.key", lifecycleHost + "/report.token"} { |
| + raw, err := os.ReadFile(filepath.Join(root, rel)) |
| + lifecycleCheck(t, "secret "+rel, err) |
| + out = append(out, raw...) |
| + out = append(out, 0) |
| + } |
| + return out |
| +} |
| + |
| +func coldRootClient(t *testing.T, addr string) *http.Client { |
| + raw, err := os.ReadFile(lifecycleHome + "/root-ca.pem") |
| + lifecycleCheck(t, "client CA", err) |
| + pool := x509.NewCertPool() |
| + if !pool.AppendCertsFromPEM(raw) { |
| + t.Fatal("invalid fixture CA") |
| + } |
| + return &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}, DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, network, addr) |
| + }}, Timeout: 45 * time.Second} |
| +} |
| +func (f *coldRootHarness) waitLeo() { |
| + f.t.Helper() |
| + deadline := time.Now().Add(time.Minute) |
| + for time.Now().Before(deadline) { |
| + conn, err := net.DialTimeout("tcp", "127.0.0.1:443", time.Second) |
| + if err == nil { |
| + conn.Close() |
| + return |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + out, _ := f.ctl("status", "carlos-edge.service") |
| + f.t.Fatal("leo did not listen", out) |
| +} |
| +func (f *coldRootHarness) restartLeo() { |
| + out, err := f.ctl("restart", "carlos-edge.service") |
| + lifecycleCheck(f.t, "restart leo "+out, err) |
| + f.waitLeo() |
| +} |
| +func (f *coldRootHarness) restartSophie() { |
| + f.t.Helper() |
| + if f.cmd != nil { |
| + _ = f.cmd.Process.Signal(os.Interrupt) |
| + timer := time.AfterFunc(15*time.Second, func() { _ = f.cmd.Process.Kill() }) |
| + _ = f.cmd.Wait() |
| + timer.Stop() |
| + f.cmd = nil |
| + } |
| + // A fresh OS process, with an independent lease identity and cache. The |
| + // root control sweep is real; callers restart only after stopping writers. |
| + cmd := exec.Command(os.Args[0], "-test.run=^TestColdPlacementRootAgent$", "-test.v", "-test.timeout=15m") |
| + cmd.Dir = f.ingress |
| + uid, gid := generationRunnerRegistryUser(f.t) |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}} |
| + for name, value := range f.env { |
| + switch name { |
| + case "COLD_ROOT_DATA_ENDPOINT": |
| + value = f.sophieEndpoint |
| + case "COLD_ROOT_BOX": |
| + value = "sophie" |
| + case "COLD_ROOT_HTTPS": |
| + value = "127.0.0.2:443" |
| + case "CARLOS_DATA_DIR", "TMPDIR": |
| + value = f.ingress |
| + case "COLD_ROOT_NO_PROOF": |
| + value = "" |
| + } |
| + cmd.Env = append(cmd.Env, name+"="+value) |
| + } |
| + file, err := os.OpenFile(filepath.Join(f.ingress, "restart.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) |
| + lifecycleCheck(f.t, "restart log", err) |
| + cmd.Stdout, cmd.Stderr = file, file |
| + lifecycleCheck(f.t, "restart sophie", cmd.Start()) |
| + f.cmd = cmd |
| + f.t.Cleanup(func() { |
| + _ = cmd.Process.Signal(os.Interrupt) |
| + timer := time.AfterFunc(15*time.Second, func() { _ = cmd.Process.Kill() }) |
| + _ = cmd.Wait() |
| + timer.Stop() |
| + file.Close() |
| + }) |
| + deadline := time.Now().Add(time.Minute) |
| + for time.Now().Before(deadline) { |
| + conn, err := net.DialTimeout("tcp", "127.0.0.2:443", time.Second) |
| + if err == nil { |
| + conn.Close() |
| + return |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + raw, _ := os.ReadFile(file.Name()) |
| + f.t.Fatalf("sophie did not restart: %s", raw) |
| +} |
| +func (f *coldRootHarness) waitReplica() { |
| + f.t.Helper() |
| + deadline := time.Now().Add(30 * time.Second) |
| + for time.Now().Before(deadline) { |
| + versions, err := f.model.ListVersions(f.t.Context(), "data", "instances/"+lifecycleHost+"/") |
| + lifecycleCheck(f.t, "replica list", err) |
| + for _, v := range versions { |
| + if strings.HasSuffix(v.Key, ".ltx") { |
| + return |
| + } |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + f.t.Fatal("real replication did not persist database") |
| +} |
| + |
| +// Pause each pair of GET responses after reading the store. This forces both |
| +// front observations, then both receiver observations, to precede either CAS. |
| +func coldRootRaceS3(next http.Handler) http.Handler { |
| + var n atomic.Int64 |
| + front, acquire := make(chan struct{}), make(chan struct{}) |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method != "GET" || !strings.HasSuffix(r.URL.Path, "/lock.json") { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + i := n.Add(1) |
| + if i > 4 { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + rec := httptest.NewRecorder() |
| + next.ServeHTTP(rec, r) |
| + barrier := front |
| + if i > 2 { |
| + barrier = acquire |
| + } |
| + if i == 2 || i == 4 { |
| + close(barrier) |
| + } |
| + select { |
| + case <-barrier: |
| + case <-r.Context().Done(): |
| + return |
| + } |
| + for k, v := range rec.Header() { |
| + w.Header()[k] = v |
| + } |
| + w.WriteHeader(rec.Code) |
| + _, _ = w.Write(rec.Body.Bytes()) |
| + }) |
| +} |
| + |
| +// Keep the synchronization outside production. Read the already armed home |
| +// map through its exported Refresh method, without replacing the fold, chooser, |
| +// forwarder or acquire. Reflection is limited to the private atomic handle. |
| +var coldRootKeysOnly atomic.Bool |
| + |
| +func coldRootRefresh(t *testing.T, e *edge.Edge) { |
| + t.Helper() |
| + if e == nil { |
| + t.Fatal("edge not ready") |
| + } |
| + field := reflect.ValueOf(e).Elem().FieldByName("homes") |
| + exported := reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())) |
| + result := exported.MethodByName("Load").Call(nil)[0] |
| + if result.IsNil() { |
| + t.Fatal("home map not armed") |
| + } |
| + if coldRootKeysOnly.Load() { |
| + lifecycleCheck(t, "production key refresh", coldRootHomeRefreshKeys(result.UnsafePointer(), t.Context())) |
| + return |
| + } |
| + m, ok := result.Interface().(interface{ Refresh(context.Context) error }) |
| + if !ok { |
| + t.Fatal("home map cannot refresh") |
| + } |
| + lifecycleCheck(t, "production fold refresh", m.Refresh(t.Context())) |
| +} |
| + |
| +type coldRootProjectionLog struct { |
| + out io.Writer |
| + once sync.Once |
| + after func() |
| +} |
| + |
| +func (w *coldRootProjectionLog) Write(p []byte) (int, error) { |
| + if bytes.Contains(p, []byte("HA placement host=")) && bytes.Contains(p, []byte("ref=leo")) { |
| + w.once.Do(w.after) |
| + } |
| + return w.out.Write(p) |
| +} |
| +func coldRootFaultWake(t *testing.T, mode string) { |
| + f := newColdRootHarness(t, mode) |
| + if mode == "out-of-view" || mode == "key-lost" { |
| + f.refused("sophie") |
| + if coldRootReadStats(t, f.ingress).Owned { |
| + t.Fatal("out-of-view fell back in request") |
| + } |
| + f.admin("sophie", "/refresh") // fresh unusable peer is again in the real fold. |
| + f.servedHost("sophie", lifecycleSibling) |
| + f.served("sophie") |
| + if f.owner() != "sophie" { |
| + t.Fatal("out-of-view choice was retried while suspect") |
| + } |
| + if stats := coldRootReadStats(t, f.ingress); stats.Dials != 0 { |
| + t.Fatalf("out-of-view/key-lost peer dial: %d", stats.Dials) |
| + } |
| + return |
| + } |
| + // Return a wire-level fault on the selected peer's address. Neither Service |
| + // nor Edge is replaced. The peer publication and its generation remain fresh. |
| + out, err := f.ctl("stop", "carlos-edge.service") |
| + lifecycleCheck(t, out, err) |
| + f.keepControlHost() |
| + raw, _, err := f.store.Get(t.Context(), "control/certs/"+lifecycleHost) |
| + lifecycleCheck(t, "fault TLS identity", err) |
| + cert, err := tls.X509KeyPair(raw, raw) |
| + lifecycleCheck(t, "fault certificate", err) |
| + var attempts atomic.Int64 |
| + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + attempts.Add(1) |
| + switch mode { |
| + case "none": |
| + w.Header().Set("X-Carlos-Holder", "none") |
| + w.WriteHeader(503) |
| + case "headerless": |
| + w.WriteHeader(503) |
| + case "hang": |
| + <-r.Context().Done() |
| + } |
| + })) |
| + server.Listener.Close() |
| + server.Listener, err = net.Listen("tcp", "127.0.0.1:443") |
| + lifecycleCheck(t, "fault listener", err) |
| + server.TLS = &tls.Config{Certificates: []tls.Certificate{cert}} |
| + server.Config.ErrorLog = log.New(io.Discard, "", 0) |
| + server.StartTLS() |
| + t.Cleanup(server.Close) |
| + code, _, h := f.request("sophie", lifecycleHost) |
| + want := 503 |
| + if mode == "hang" { |
| + want = 502 |
| + } |
| + if code != want { |
| + t.Fatalf("first fault %d, want %d, headers %v", code, want, h) |
| + } |
| + if coldRootReadStats(t, f.ingress).Owned { |
| + t.Fatal("fault fell back within request") |
| + } |
| + start := time.Now() |
| + f.servedHost("sophie", lifecycleSibling) |
| + f.served("sophie") |
| + if time.Since(start) >= 10*time.Second { |
| + t.Fatal("survivor recovery exceeded suspicion window") |
| + } |
| + if f.owner() != "sophie" || attempts.Load() != 1 { |
| + t.Fatalf("unusable target retried: owner=%s attempts=%d", f.owner(), attempts.Load()) |
| + } |
| +} |
| + |
| +func (f *coldRootHarness) servedHost(ref, host string) { |
| + f.t.Helper() |
| + code, body, _ := f.request(ref, host) |
| + if code != 200 || body != "lifecycle tenant" { |
| + f.t.Fatalf("%s %s: %d %q", ref, host, code, body) |
| + } |
| +} |
| + |
| +// The installed instance template binds to carlos-edge.service. On this one |
| +// isolated machine a third, idle logical box keeps that real dependency active |
| +// after leo's listener/process is gone. It starts no tenant and publishes no |
| +// placement evidence. This preserves the production unit rather than replacing |
| +// its BindsTo dependency with a stand-in. |
| +func (f *coldRootHarness) keepControlHost() { |
| + f.t.Helper() |
| + dir := "/data/cold-control-host" |
| + lifecycleCheck(f.t, "control host dir", os.MkdirAll(dir, 0755)) |
| + reg, err := registry.Open(filepath.Join(dir, "registry.db")) |
| + lifecycleCheck(f.t, "control host registry", err) |
| + rows, err := f.reg.List() |
| + lifecycleCheck(f.t, "control host routes", err) |
| + for _, rt := range rows { |
| + lifecycleCheck(f.t, "control host route", reg.Upsert(rt)) |
| + } |
| + reg.Close() |
| + uid, gid := generationRunnerRegistryUser(f.t) |
| + lifecycleCheck(f.t, "control host owner", filepath.Walk(dir, func(p string, _ os.FileInfo, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + return os.Chown(p, uid, gid) |
| + })) |
| + var lines []string |
| + for name, value := range f.env { |
| + switch name { |
| + case "COLD_ROOT_BOX": |
| + value = "control-host" |
| + case "COLD_ROOT_HTTPS": |
| + value = "127.0.0.4:443" |
| + case "CARLOS_DATA_DIR": |
| + value = dir |
| + } |
| + lines = append(lines, name+"="+value) |
| + } |
| + lifecycleCheck(f.t, "control host environment", os.WriteFile("/etc/carlos/host.env", []byte(strings.Join(lines, "\n")+"\n"), 0600)) |
| + out, err := f.ctl("reset-failed", "carlos-edge.service") |
| + lifecycleCheck(f.t, out, err) |
| + out, err = f.ctl("start", "carlos-edge.service") |
| + lifecycleCheck(f.t, "start real control host: "+out, err) |
| + deadline := time.Now().Add(time.Minute) |
| + for time.Now().Before(deadline) { |
| + conn, err := net.DialTimeout("tcp", "127.0.0.4:443", time.Second) |
| + if err == nil { |
| + conn.Close() |
| + return |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + f.t.Fatal("control host did not listen") |
| +} |
| + |
| +type coldRootS3Counts struct{ g, p, l, d atomic.Int64 } |
| + |
| +func (c *coldRootS3Counts) values() [4]int64 { |
| + return [4]int64{c.g.Load(), c.p.Load(), c.l.Load(), c.d.Load()} |
| +} |
| +func (c *coldRootS3Counts) handler(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if strings.HasSuffix(r.URL.Path, "/"+lifecycleHost+"/lock.json") { |
| + switch r.Method { |
| + case "GET": |
| + c.g.Add(1) |
| + case "PUT": |
| + c.p.Add(1) |
| + case "DELETE": |
| + c.d.Add(1) |
| + } |
| + } |
| + if r.Method == "GET" && r.URL.Query().Get("list-type") == "2" && r.URL.Query().Get("max-keys") == "1" && r.URL.Query().Get("prefix") == "instances/"+lifecycleHost+"/" { |
| + c.l.Add(1) |
| + } |
| + next.ServeHTTP(w, r) |
| + }) |
| +} |
diff --git a/internal/host/haplacement_wiring_test.go b/internal/host/haplacement_wiring_test.go| index cdc11ed97..682e72561 100644 |
| --- a/internal/host/haplacement_wiring_test.go |
| +++ b/internal/host/haplacement_wiring_test.go |
| @@ -9,6 +9,7 @@ import ( |
| "net/url" |
| "os/exec" |
| "path/filepath" |
| + "sync" |
| "sync/atomic" |
| "github.com/carlosframework/platform/internal/activator" |
| @@ -122,7 +123,19 @@ func armHAPlacementWitness(svc *activator.Service, sink func(context.Context, st |
| }) |
| } |
| +// The ordinary fixture checks registration and accepted page copy. The rootrunner |
| +// build additionally executes the complete nested-launch witness in this test. |
| +var coldPlacementProductionLaunch func(*testing.T) |
| + |
| +func TestColdPlacementProductionWiring(t *testing.T) { |
| + TestHAPlacementPageWiring(t) |
| + if coldPlacementProductionLaunch != nil { |
| + coldPlacementProductionLaunch(t) |
| + } |
| +} |
| + |
| func TestColdPlacementRequestBudget(t *testing.T) { |
| + testColdPlacementBudgetRows(t) |
| for _, holder := range []string{"none", ""} { |
| t.Run("holder="+holder, func(t *testing.T) { testColdPlacementRequestBudget(t, holder) }) |
| } |
| @@ -184,6 +197,7 @@ const coldPlacementHost = "shop.example.com" |
| type coldCommand struct { |
| Op string |
| + Legacy bool |
| Snapshot boxchoice.WakeSnapshot |
| Result edge.ForwardResult |
| } |
| @@ -191,18 +205,28 @@ type coldAnswer struct { |
| Decision edge.ForwardDecision |
| Error string |
| HA bool |
| + Status int |
| } |
| type coldPlacementProcesses struct { |
| - t *testing.T |
| - store string |
| - fixture *locktest.LockFixture |
| - putCount atomic.Int64 |
| + t *testing.T |
| + store string |
| + fixture *locktest.LockFixture |
| + putCount atomic.Int64 |
| + listCount atomic.Int64 |
| +} |
| +type coldGetPause struct { |
| + began, release chan struct{} |
| + once sync.Once |
| } |
| + |
| type coldPlacementProcess struct { |
| - t *testing.T |
| - input io.WriteCloser |
| - output *json.Decoder |
| - getCount atomic.Int64 |
| + pause atomic.Pointer[coldGetPause] |
| + t *testing.T |
| + input io.WriteCloser |
| + output *json.Decoder |
| + getCount atomic.Int64 |
| + putCount atomic.Int64 |
| + listCount atomic.Int64 |
| } |
| func newColdPlacementProcesses(t *testing.T) *coldPlacementProcesses { |
| @@ -246,11 +270,28 @@ func (f *coldPlacementProcesses) box(ref string) *coldPlacementProcess { |
| if strings.HasSuffix(r.URL.Path, "/lock.json") { |
| if r.Method == "GET" { |
| b.getCount.Add(1) |
| + if paused := b.pause.Swap(nil); paused != nil { |
| + close(paused.began) |
| + select { |
| + case <-paused.release: |
| + case <-r.Context().Done(): |
| + return |
| + } |
| + w.Header().Set("Content-Type", "application/xml") |
| + w.WriteHeader(400) |
| + _, _ = io.WriteString(w, "<Error><Code>InvalidRequest</Code></Error>") |
| + return |
| + } |
| } |
| if r.Method == "PUT" { |
| f.putCount.Add(1) |
| + b.putCount.Add(1) |
| } |
| } |
| + if r.Method == "GET" && r.URL.Query().Get("list-type") == "2" { |
| + b.listCount.Add(1) |
| + f.listCount.Add(1) |
| + } |
| proxy.ServeHTTP(w, r) |
| })) |
| t.Cleanup(server.Close) |
| @@ -341,6 +382,7 @@ func TestColdPlacementProcess(t *testing.T) { |
| } |
| armHAPlacementWitness(svc, func(context.Context, string, string, string) error { return nil }) |
| decoder, encoder := json.NewDecoder(os.Stdin), json.NewEncoder(os.Stdout) |
| + var wakeDone chan coldAnswer |
| var held activator.Lease |
| defer func() { |
| if held != nil { |
| @@ -357,12 +399,43 @@ func TestColdPlacementProcess(t *testing.T) { |
| var answer coldAnswer |
| switch command.Op { |
| case "ready": |
| + case "begin": |
| + wakeDone = make(chan coldAnswer, 1) |
| + go func() { |
| + recorder := httptest.NewRecorder() |
| + request := httptest.NewRequest("GET", "http://"+rt.Host+"/", nil) |
| + svc.ServeHTTP(recorder, request.WithContext(t.Context()), rt, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) })) |
| + wakeDone <- coldAnswer{Status: recorder.Code} |
| + }() |
| + case "wait-wake": |
| + if wakeDone == nil { |
| + answer.Error = "no pending wake" |
| + } else { |
| + answer = <-wakeDone |
| + wakeDone = nil |
| + } |
| case "forward": |
| - answer.Decision = svc.ForwardTarget(t.Context(), rt, func() boxchoice.WakeSnapshot { return command.Snapshot }) |
| + requestRoute := rt |
| + if command.Legacy { |
| + requestRoute.HA = false |
| + } |
| + answer.Decision = svc.ForwardTarget(t.Context(), requestRoute, func() boxchoice.WakeSnapshot { return command.Snapshot }) |
| case "note": |
| svc.NoteForward(rt.Host, command.Result) |
| + case "release": |
| + if held != nil { |
| + err = held.Release(t.Context()) |
| + held = nil |
| + if err != nil { |
| + answer.Error = err.Error() |
| + } |
| + } |
| case "acquire": |
| - held, err = backend.Acquire(t.Context(), rt) |
| + var acquired activator.Lease |
| + acquired, err = backend.Acquire(t.Context(), rt) |
| + if err == nil { |
| + held = acquired |
| + } |
| if err != nil { |
| answer.Error = err.Error() |
| } else if ha, ok := held.(interface{ HA() bool }); ok { |