Add a real EC2 termination witness for HA lease release
Run the production agent with a nested generation under the embedded units. Keep the S3 fixture alive through edge shutdown and synchronously mirror lease writes, heartbeats and the final journal to the runner evidence prefix. The main baseline held its lease through EC2 termination and wrote no release marker. The observer survived the edge and recorded its stop after 64.79s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/host/haplacement_root_linux_test.go+39 −7internal/host/haterminate_rootrunner_linux_test.go+392 −0internal/host/plan14_generation_registry_root_linux_test.go+2 −0
Intent
<task-notification> <task-id>bhpfixhbb</task-id> <tool-use-id>toolu_011FH8maGkdYwtz3sgkAAmN4</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/c23f0319-4761-45f6-bac7-f9471c7b9ab1/tasks/bhpfixhbb.output</output-file> <status>completed</status> <summary>Background command "W=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-graceful/.superpowers/sdd/2026-11-08-region-ha-graceful-terminate; echo "Task 2: dispatched (Astra) at base $(cat $W/task-2-base) while Task 1 fix-round re-review runs (read-only; T2 touches different files)" >> $W/progress.md; until [ -f $W/task-2-report.md.done ]; do sleep 30; done; echo task2 done" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a87b5cc9df2dfcca5</task-id> <tool-use-id>toolu_01NhY7As1KVpfvEd4kzwaE3C</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/c23f0319-4761-45f6-bac7-f9471c7b9ab1/tasks/a87b5cc9df2dfcca5.output</output-file> <status>completed</status> <summary>Agent "Review Task 2 shutdown path" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Spec Compliance - ✅ Spec compliant. Every file the brief lists has its hunk, and the four requested tests plus the mutation run are present. - **Item 1 (one deadline from the signal).** The deadline is set where the edge's `<-stop` fires, on both paths: `internal/edge/edge.go:4637` (dev) and `:4837` (TLS), through `beginShutdown` at `internal/edge/shutdown.go:10-14`. It is set before admission closes. The agent derives `at + agentShutdownBudget` at `internal/host/agent.go:1128`. The constant is 90 s, at `claimfilesseed_shutdown.go:11`. - **Item 1, every path the agent shuts down by.** I checked whether `RunWithActivatorReady` can return without passing `beginShutdown`, which would leave a zero `shutdownDeadline` and an already-expired shutdown context. It cannot. Both `return` points come after `<-stop`, and every other exit is `log.Fatal*`. The call at `agent.go:1176` is synchronous, so the unsynchronised `shutdownDeadline` write at :1128 and the reads at :1294/:1303 happen on the same goroutine. There is no data race. - **Item 1, the seed path.** I checked whether `activator.CleanupContext`'s `WithoutCancel` drops the deadline D. It does not: `internal/activator/cleanup.go:59-62` re-applies the parent's deadline. So `base` stays bounded by D on the seed path (`claimfilesseed_shutdown.go:767`). The seed close is bounded at :774, the no-seed 60 s context is now derived from `base` at :790, and the departure stop is bounded at `agent.go:1294-1295`. Existing shorter caps (5 s / 30 s / 60 s) are kept. - **Item 2 (release budgets).** `haReleaseContext` (`internal/activator/harelease.go:240-260`) does what the brief asks: - It reads `shuttingDown` and `shutdownCtx` under `a.mu`. - Each step gets the minimum of its cap and `D - reserve`, with a floor of `now + 1 s`. - `WithoutCancel` is kept. - The reserves are 30+10 s for Final (:189), 10 s for Finish (:198) and 0 for the marker (:214). - Final, then Finish, then the record, then `ReleaseMarker` still run synchronously in that order. Nothing is wrapped in a goroutine or a select. - **Item 3 (Shutdown joins a marker in flight).** `finishStop` calls `releaseHAClean` synchronously (`activator.go:5266`). Its early return keeps the stop pending (:5272), the entry is deleted at :5291, and `close(e.stopped)` is at :5332, so a marker in flight is joined until D. The exit line is added beside `logUnresolvedAtExit` (`activator.go:116-137`, deferred at :94) with the exact wording the brief asks for. - ⚠️ Cannot verify from the diff: - The admission close, the files/sweeper joins and `writeHARecord`'s separate 30 s allowance are still not bounded by D. The report says so itself (its concerns 1-2), so the process can still run past sigterm+90 s. The controller should confirm that Task 1's `TimeoutStopSec=120` really is the backstop it is counted on to be. - Whether the next holder's takeover rules (`hafresh/acquire.go`) are untouched. They are not in the diff, so presumably yes. ### Strengths - The deadline seam is small and sits at the right place: a synchronous `RunOption` hook at the single signal-receive point. It adds no new goroutine and no atomic state. - In normal (not-shutdown) operation, the budgets come out identical to before (`now + cap` via `WithDeadline`). `TestHANormalReleaseBudgetsUnchanged` (`harelease_shutdown_test.go:454`) pins this within 1 s of each cap. - The single-writer invariant is kept by construction: no step is detached, and a stuck Finish leaves the stop pending and writes no marker. `TestHAShutdownStuckFinishWritesNoMarker` (:389) checks the marker fake, the store and that `e.stopped` is still open. - The tests use the real files publisher and the real lease store through the existing fixtures. They wrap only seams that already exist (`stageEscrow`, the replica's methods), and no production test hook was added. - The mutation check was run in a scratch copy, and the first test fails as expected. - The new `a.mu` uses are safe. No caller of `haReleaseContext` holds `a.mu` (`releaseHAClean` already locks and unlocks around it). Every `return` in `Shutdown` happens with `a.mu` released (activator.go:6242, 6256, 6291, 6296), so the deferred `logHAUnreleasedAtExit` cannot self-deadlock on a normal return. `haReleased` is written (harelease.go:225-227) and read (activator.go:117-120) only under `a.mu`. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) None. #### Minor (Nice to Have) 1. **`internal/activator/activator.go:94` (a panic can now hang shutdown).** The deferred `logHAUnreleasedAtExit` takes `a.mu`. If `Shutdown` panics while holding `a.mu` (for example inside `finishPendingStops` at :6190 or :6229), the deferred call blocks on the mutex. The agent would then hang until systemd kills it at the stop timeout, where before it crashed straight away. This is unlikely, but it is a new hang mode. Fix: take the snapshot and log only on the normal return paths, or use `TryLock` in the deferred helper. 2. **`internal/activator/activator.go:130` (some lines repeat).** A marker PUT that failed already appears in `logUnresolvedAtExit`'s owed list. With this change it can also get a "frees at expiry" line, which `TestHAShutdownLogsFailedMarkerAfterEntryRemoved` (:540) confirms. The lines are accurate, just repeated in two wordings. Merging the two would be cleaner. 3. **`internal/activator/harelease_shutdown_test.go:442` (healthy-budget check is one-sided).** It only checks upper bounds. A regression that handed out near-zero budgets would still pass. With D = 60 s only Final is actually capped, while Finish and the marker sit at their caps. Adding a lower bound, or picking a D where Finish's cut-off D - 10 s binds below 30 s, would make it a real witness for all three steps. 4. **`internal/activator/harelease_shutdown_test.go:396-412` (wall-clock margins).** The test uses D = 1.5 s, a 2 s wait for return and a 500 ms slack. On a loaded CI worker that could flake. Widening D to 3-5 s would keep the test fast. 5. **`internal/edge/shutdown.go:5` (doc comment).** The exported `WithShutdownStarted` has no doc comment. Say that the hook runs synchronously on the `RunWithActivatorReady` goroutine; the agent's unsynchronised `shutdownDeadline` write depends on that. ### Assessment **Task quality:** Approved **Reasoning:** The deadline starts at the one signal-receive point on both edge paths, is never zero after `RunWithActivatorReady` returns, and bounds every join `joinAgentShutdown` controls. The HA release only shortens the deadlines of the contexts it already passes, with the synchronous Final, Finish, marker order kept, so a marker is never written over a step that has not returned. The remaining items are a panic-time hang mode and test-strength polish.</result> <usage><subagent_tokens>102333</subagent_tokens><tool_uses>14</tool_uses><duration_ms>137968</duration_ms></usage> </task-notification>
<task-notification> <task-id>b9m9we6zy</task-id> <tool-use-id>toolu_011UBvWhiywFU3JtimE2ScHA</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/c23f0319-4761-45f6-bac7-f9471c7b9ab1/tasks/b9m9we6zy.output</output-file> <status>completed</status> <summary>Background command "W=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/ha-graceful/.superpowers/sdd/2026-11-08-region-ha-graceful-terminate; until [ -f $W/task-3-report.md.done ]; do sleep 30; done; echo task3 done" completed (exit code 0)</summary> </task-notification>
diff --git a/internal/host/haplacement_root_linux_test.go b/internal/host/haplacement_root_linux_test.go| index 036175c58..232d1ab4a 100644 |
| --- a/internal/host/haplacement_root_linux_test.go |
| +++ b/internal/host/haplacement_root_linux_test.go |
| @@ -116,6 +116,10 @@ func TestColdPlacementRootGuardArm(t *testing.T) { |
| } |
| func TestColdPlacementRootAgent(t *testing.T) { |
| + if os.Getenv("COLD_ROOT_MODE") == "terminate" { |
| + terminateRootAgent(t) |
| + return |
| + } |
| ref := os.Getenv("COLD_ROOT_BOX") |
| if ref == "" { |
| t.Skip("installed edge child payload") |
| @@ -593,9 +597,13 @@ type coldRootHarness struct { |
| sophieEndpoint string |
| } |
| -func newColdRootHarness(t *testing.T, mode string) *coldRootHarness { |
| +func newColdRootHarness(t *testing.T, mode string, wrapS3 ...func(http.Handler) http.Handler) *coldRootHarness { |
| egressRootPrereqs(t) |
| uid, gid := generationRunnerRegistryUser(t) |
| + deploymentDir := lifecycleHome + "/deployment" |
| + if mode == "terminate" { |
| + deploymentDir = "/data/terminate-deployment" |
| + } |
| 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)) }) |
| @@ -613,12 +621,12 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness { |
| t.Logf("root fixture journal:\n%s", out) |
| }) |
| 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"} { |
| + for _, path := range []string{deploymentDir, "/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)) |
| } |
| // openServiceRegistry creates the database as carlos. Match bootstrap and |
| // the lifecycle fixture before that first open, not only after staging. |
| - for _, path := range []string{lifecycleHome, lifecycleHome + "/deployment", "/data", "/data/.instances", "/data/instances", "/run/carlos", "/run/carlos/.instances", "/run/carlos/instances", "/run/carlos/.logs", "/run/carlos/logs"} { |
| + for _, path := range []string{lifecycleHome, deploymentDir, "/data", "/data/.instances", "/data/instances", "/run/carlos", "/run/carlos/.instances", "/run/carlos/instances", "/run/carlos/.logs", "/run/carlos/logs"} { |
| lifecycleCheck(t, "bootstrap service owner "+path, os.Chown(path, uid, gid)) |
| } |
| for _, path := range []string{"/data/.instances", "/data/instances", "/run/carlos/.logs", "/run/carlos/logs"} { |
| @@ -628,6 +636,9 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness { |
| model.AddBucket("data") |
| s3, _ := leasetest.NewS3Server(model) |
| var s3Handler http.Handler = lifecycleS3(s3, model) |
| + for _, wrap := range wrapS3 { |
| + s3Handler = wrap(s3Handler) |
| + } |
| if mode == "competing" { |
| s3Handler = coldRootRaceS3(s3Handler) |
| } |
| @@ -637,12 +648,13 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness { |
| t.Cleanup(receiverServer.Close) |
| t.Cleanup(server.Close) |
| lifecycleEnvironment(t, server.URL) |
| + t.Setenv("CARLOS_DEPLOYMENT_DIR", deploymentDir) |
| t.Setenv("CARLOS_HOST_CLAIM", "") |
| t.Setenv("CARLOS_REGION_HA", "true") |
| t.Setenv("AWS_REGION", "eu-west-1") |
| t.Setenv("AWS_DEFAULT_REGION", "eu-west-1") |
| key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize)) |
| - store := release.NewDirStore(lifecycleHome + "/deployment") |
| + store := release.NewDirStore(deploymentDir) |
| 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()) |
| @@ -693,7 +705,11 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness { |
| out, err := exec.Command("systemctl", args...).CombinedOutput() |
| return string(out), err |
| } |
| - for _, name := range []string{"carlos-edge.service", "carlos-instance-probe.service"} { |
| + units := []string{"carlos-edge.service", "carlos-instance-probe.service"} |
| + if mode == "terminate" { |
| + units = append(units, "carlos-instance-gen@.service") |
| + } |
| + for _, name := range units { |
| raw, err := unitsFS.ReadFile("units/" + name) |
| lifecycleCheck(t, "production unit", err) |
| path := filepath.Join("/etc/systemd/system", name) |
| @@ -709,7 +725,7 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness { |
| 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")} |
| + 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": deploymentDir, "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) |
| @@ -745,6 +761,17 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness { |
| 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")) |
| + if mode == "terminate" { |
| + for _, host := range []string{lifecycleHost, lifecycleSibling} { |
| + lifecycleCheck(t, "install managed fixture build", release.MaterializeHost(t.Context(), reg, store, key.Public().(ed25519.PublicKey), "/opt/carlos", "/data", host)) |
| + row, err := reg.Get(host) |
| + lifecycleCheck(t, "installed fixture row", err) |
| + if row == nil || row.Version != "v1" { |
| + t.Fatalf("fixture build was not adopted: %+v", row) |
| + } |
| + } |
| + } |
| + |
| if mode == "departure-sidecar" { |
| lifecycleCheck(t, "point sidecar live", release.PointLive("/opt/carlos", departureSidecarHost, "bab", "v1", "lifecycle")) |
| } |
| @@ -797,7 +824,7 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness { |
| if strings.HasPrefix(mode, "departure-") { |
| departureRootIdentities(t, store) |
| } |
| - lifecycleCheck(t, "fault publication owner", filepath.Walk(lifecycleHome+"/deployment/control", func(path string, _ os.FileInfo, err error) error { |
| + lifecycleCheck(t, "fault publication owner", filepath.Walk(deploymentDir+"/control", func(path string, _ os.FileInfo, err error) error { |
| if err != nil { |
| return err |
| } |
| @@ -816,6 +843,11 @@ func newColdRootHarness(t *testing.T, mode string) *coldRootHarness { |
| 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) |
| + if mode == "terminate" { |
| + f := &coldRootHarness{t: t, model: model, store: store, reg: reg, ctl: ctl, env: env} |
| + f.waitLeo() |
| + return f |
| + } |
| ingress := "/data/cold-sophie" |
| lifecycleCheck(t, "ingress dir", os.Mkdir(ingress, 0755)) |
| lifecycleCheck(t, "ingress owner", os.Chown(ingress, uid, gid)) |
diff --git a/internal/host/haterminate_rootrunner_linux_test.go b/internal/host/haterminate_rootrunner_linux_test.go| new file mode 100644 |
| index 000000000..936af81f5 |
| --- /dev/null |
| +++ b/internal/host/haterminate_rootrunner_linux_test.go |
| @@ -0,0 +1,392 @@ |
| +//go:build linux && rootrunner |
| + |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "os/signal" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + "github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds" |
| + "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "golang.org/x/crypto/acme/autocert" |
| +) |
| + |
| +const terminateWitnessUnit = "ha-terminate-witness.service" |
| +const terminateWitnessRoot = "/var/lib/ha-terminate-witness" |
| +const terminateWitnessBucket = "carlos-dev-640012953448" |
| +const terminateLockPath = "/data/instances/" + lifecycleHost + "/lock.json" |
| + |
| +// The fixture tenant accepts the production generation socket as well as the |
| +// legacy socket handled by the lifecycle fixture. It keeps SQLite open until |
| +// the installed instance unit terminates it. |
| +func init() { |
| + if len(os.Args) != 5 || os.Args[1] != "--socket" || os.Args[3] != "--db" || os.Args[4] != provision.NestedDBPath("/data", lifecycleHost) { |
| + return |
| + } |
| + pattern := "^" + regexp.QuoteMeta(provision.InstanceRunDir(lifecycleHost)) + `/g[1-9][0-9]*/app\.sock$` |
| + if !regexp.MustCompile(pattern).MatchString(os.Args[2]) { |
| + return |
| + } |
| + db, err := sql.Open("sqlite", os.Args[4]) |
| + if err != nil { |
| + panic(err) |
| + } |
| + if _, err = db.Exec("PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS lifecycle (value TEXT)"); err != nil { |
| + panic(err) |
| + } |
| + listener, err := net.Listen("unix", os.Args[2]) |
| + if err != nil { |
| + panic(err) |
| + } |
| + if err = http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "lifecycle tenant") })); err != nil { |
| + panic(err) |
| + } |
| + os.Exit(0) |
| +} |
| + |
| +// This payload uses the agent entry and shutdown code, including its generation |
| +// arming checks. The cold placement payload normally composes a smaller service. |
| +func terminateRootAgent(t *testing.T) { |
| + store := release.NewDirStore(os.Getenv("CARLOS_DEPLOYMENT_DIR")) |
| + t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "") |
| + t.Setenv("CARLOS_S3_ENDPOINT", os.Getenv("COLD_ROOT_DATA_ENDPOINT")) |
| + t.Setenv("AWS_ENDPOINT_URL_S3", os.Getenv("COLD_ROOT_DATA_ENDPOINT")) |
| + t.Setenv("CARLOS_SWAP", "overlap") |
| + t.Setenv("CARLOS_REGION", "ie") |
| + t.Setenv("CARLOS_AWS_REGION", "eu-west-1") |
| + t.Setenv("CARLOS_HIBERNATE_IDLE", "1h") |
| + t.Setenv("CARLOS_PUBLIC_IP", "127.0.0.1") |
| + t.Setenv("CARLOS_PRIVATE_IP", "127.0.0.1") |
| + coldRootSeedCertificates(t, store, autocert.DirCache("/data/acme")) |
| + for _, ref := range []string{"leo", "sophie"} { |
| + lifecycleCheck(t, "remove unused logical peer", store.Delete(t.Context(), edgesFileKey(ref))) |
| + } |
| + RunAgent([]string{"--registry", "/data/registry.db", "--https", "127.0.0.1:443", "--http", "127.0.0.1:80"}) |
| +} |
| + |
| +type terminateEvent struct { |
| + At time.Time `json:"at"` |
| + Kind string `json:"kind"` |
| + Lock json.RawMessage `json:"lock,omitempty"` |
| + Error string `json:"error,omitempty"` |
| + Units string `json:"units,omitempty"` |
| +} |
| + |
| +type terminateMirror struct { |
| + client *s3.Client |
| + prefix string |
| + mu sync.Mutex |
| + failure string |
| +} |
| + |
| +func newTerminateMirror(t *testing.T, run string) *terminateMirror { |
| + // No default config chain: the fixture installs fake credentials and S3 |
| + // overrides. This client always uses IMDSv2 and the regional HTTPS endpoint. |
| + transport := &http.Transport{Proxy: nil} |
| + client := &http.Client{Transport: transport, Timeout: 15 * time.Second} |
| + metadata := imds.New(imds.Options{HTTPClient: client, Endpoint: "http://169.254.169.254", ClientEnableState: imds.ClientEnabled}) |
| + creds := aws.NewCredentialsCache(ec2rolecreds.New(func(o *ec2rolecreds.Options) { o.Client = metadata })) |
| + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) |
| + defer cancel() |
| + _, err := creds.Retrieve(ctx) |
| + lifecycleCheck(t, "runner role credentials", err) |
| + return &terminateMirror{client: s3.NewFromConfig(aws.Config{Region: "eu-west-1", Credentials: creds, HTTPClient: client, RetryMaxAttempts: 2}, func(o *s3.Options) { |
| + o.BaseEndpoint = aws.String("https://s3.eu-west-1.amazonaws.com") |
| + o.UsePathStyle = true |
| + }), prefix: "root-runner/" + run + "/"} |
| +} |
| + |
| +func (m *terminateMirror) put(key string, raw []byte) error { |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + defer cancel() |
| + _, err := m.client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(terminateWitnessBucket), Key: aws.String(m.prefix + key), Body: bytes.NewReader(raw)}) |
| + return err |
| +} |
| + |
| +func (m *terminateMirror) event(e terminateEvent) error { |
| + raw, err := json.Marshal(e) |
| + if err != nil { |
| + return err |
| + } |
| + return m.put(fmt.Sprintf("events/%d-%s.json", e.At.UnixNano(), e.Kind), raw) |
| +} |
| + |
| +func (m *terminateMirror) wrap(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method != http.MethodPut || r.URL.Path != terminateLockPath { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + raw, err := io.ReadAll(r.Body) |
| + if err != nil { |
| + http.Error(w, err.Error(), 500) |
| + return |
| + } |
| + r.Body = io.NopCloser(bytes.NewReader(raw)) |
| + // Serialize lock mutation and its mirror; never acknowledge a successful |
| + // fixture PUT until its exact bytes have been stored off the runner. |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + rec := httptest.NewRecorder() |
| + next.ServeHTTP(rec, r) |
| + if rec.Code >= 200 && rec.Code < 300 { |
| + err = m.event(terminateEvent{At: time.Now().UTC(), Kind: "lock-write", Lock: json.RawMessage(raw)}) |
| + if err != nil { |
| + m.failure = err.Error() |
| + fmt.Fprintf(os.Stderr, "lock mirror failed: %v\n", err) |
| + http.Error(w, "lock mirror failed", 500) |
| + return |
| + } |
| + } |
| + for k, v := range rec.Header() { |
| + w.Header()[k] = v |
| + } |
| + w.WriteHeader(rec.Code) |
| + _, _ = w.Write(rec.Body.Bytes()) |
| + }) |
| +} |
| + |
| +func (m *terminateMirror) finish(at time.Time) error { |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + journal, err := exec.CommandContext(ctx, "journalctl", "-u", "carlos-edge.service", "-u", "carlos-instance-control.service", "-u", "carlos-instance*", "-u", terminateWitnessUnit, "-b", "--no-pager", "-o", "short-iso-precise").CombinedOutput() |
| + if err != nil { |
| + return fmt.Errorf("journal: %w: %s", err, journal) |
| + } |
| + if err := m.put("journal.txt", journal); err != nil { |
| + return err |
| + } |
| + units, err := exec.CommandContext(ctx, "systemctl", "show", "carlos-edge.service", "carlos-instance-control.service", "-p", "Id", "-p", "ActiveState", "-p", "SubState", "-p", "MainPID").CombinedOutput() |
| + m.mu.Lock() |
| + failure := m.failure |
| + m.mu.Unlock() |
| + if err != nil { |
| + failure += fmt.Sprintf(" unit state: %v", err) |
| + } |
| + return m.event(terminateEvent{At: at, Kind: "unit-stop", Error: failure, Units: string(units)}) |
| +} |
| + |
| +func TestRootHATerminateRelease(t *testing.T) { |
| + run := os.Getenv("HA_TERMINATE_RUN") |
| + if !regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9-]{0,79}$`).MatchString(run) { |
| + t.Fatal("HA_TERMINATE_RUN must name this driver's isolated root-runner prefix") |
| + } |
| + if os.Geteuid() != 0 { |
| + t.Fatal("requires the designated throwaway root runner") |
| + } |
| + if os.Getenv("HA_TERMINATE_PAYLOAD") != "1" { |
| + terminateRootLaunch(t, run) |
| + return |
| + } |
| + stopped := make(chan os.Signal, 1) |
| + signal.Notify(stopped, syscall.SIGTERM, syscall.SIGINT) |
| + defer signal.Stop(stopped) |
| + mirror := newTerminateMirror(t, run) |
| + f := newColdRootHarness(t, "terminate", mirror.wrap) |
| + // An HTTP wake must succeed through the real agent before the driver can |
| + // terminate. The active gen unit below also rules out silently declined swap. |
| + deadline := time.Now().Add(2 * time.Minute) |
| + var code int |
| + var body string |
| + for time.Now().Before(deadline) { |
| + code, body, _ = f.request("leo", lifecycleHost) |
| + if code == 200 && body == "lifecycle tenant" { |
| + break |
| + } |
| + time.Sleep(time.Second) |
| + } |
| + if code != 200 || body != "lifecycle tenant" { |
| + t.Fatalf("real agent wake: %d %q", code, body) |
| + } |
| + units, err := f.ctl("list-units", "--all", "--plain", "--no-legend", "carlos-instance-gen@*.service") |
| + lifecycleCheck(t, "generation units", err) |
| + running := false |
| + for _, line := range strings.Split(units, "\n") { |
| + fields := strings.Fields(line) |
| + if len(fields) >= 4 && strings.Contains(fields[0], lifecycleHost) && fields[2] == "active" && fields[3] == "running" { |
| + running = true |
| + } |
| + } |
| + if !running { |
| + t.Fatalf("no running generation unit: %s", units) |
| + } |
| + t.Logf("generation unit: %s", units) |
| + view, err := lease.ReadLock(t.Context(), "data", "instances/"+lifecycleHost, "eu-west-1") |
| + lifecycleCheck(t, "held lock", err) |
| + iid, account, region, err := readIdentity(&http.Client{Timeout: 5 * time.Second}, imdsBase) |
| + lifecycleCheck(t, "runner identity", err) |
| + owner, ok := hafresh.ParseOwner(view.Lock.Owner) |
| + if !ok || !owner.HA || owner.IID != iid || iid == "" || account != "640012953448" || region != "eu-west-1" || view.Absent || view.Lock.Release != nil || !view.Lock.ExpiresAt.After(time.Now()) { |
| + t.Fatalf("lock not held by this runner: %+v identity=%s/%s/%s", view, iid, account, region) |
| + } |
| + raw, err := json.Marshal(view.Lock) |
| + lifecycleCheck(t, "ready lock encode", err) |
| + mirror.mu.Lock() |
| + failure := mirror.failure |
| + mirror.mu.Unlock() |
| + if failure != "" { |
| + t.Fatal("mirror failed before ready: " + failure) |
| + } |
| + lifecycleCheck(t, "initial heartbeat", mirror.event(terminateEvent{At: time.Now().UTC(), Kind: "heartbeat"})) |
| + lifecycleCheck(t, "off-box ready", mirror.put("ready.json", raw)) |
| + lifecycleCheck(t, "local ready", os.WriteFile(filepath.Join(terminateWitnessRoot, "ready"), raw, 0600)) |
| + ticker := time.NewTicker(10 * time.Second) |
| + defer ticker.Stop() |
| + for { |
| + select { |
| + case <-stopped: |
| + err := mirror.finish(time.Now().UTC()) |
| + if err != nil { |
| + fmt.Fprintf(os.Stderr, "final mirror: %v\n", err) |
| + os.Exit(1) |
| + } |
| + // Shutdown owns the machine now. Avoid test cleanups that would start |
| + // systemctl jobs or unmount fixtures during the poweroff transaction. |
| + os.Exit(0) |
| + case <-ticker.C: |
| + mirror.mu.Lock() |
| + failure := mirror.failure |
| + mirror.mu.Unlock() |
| + lifecycleCheck(t, "heartbeat", mirror.event(terminateEvent{At: time.Now().UTC(), Kind: "heartbeat", Error: failure})) |
| + } |
| + } |
| +} |
| + |
| +func terminateRootLaunch(t *testing.T, run string) { |
| + lifecycleCheck(t, "exclusive witness state", os.Mkdir(terminateWitnessRoot, 0700)) |
| + exe, err := os.Executable() |
| + lifecycleCheck(t, "witness executable", err) |
| + // Default dependencies retain shutdown.target Conflicts/Before. Startup |
| + // Before=edge reverses at shutdown: edge stops first. After=network.target |
| + // keeps network teardown behind the fixture's final S3 writes. |
| + out, err := exec.Command("systemd-run", "--unit="+terminateWitnessUnit, "--property=Type=exec", "--property=Before=carlos-edge.service", "--property=After=network.target network-online.target", "--property=DefaultDependencies=yes", "--property=TimeoutStopSec=90s", "--setenv=HA_TERMINATE_PAYLOAD=1", "--setenv=HA_TERMINATE_RUN="+run, "--setenv=TMPDIR=/var/tmp", exe, "-test.run=^TestRootHATerminateRelease$", "-test.v", "-test.timeout=30m").CombinedOutput() |
| + lifecycleCheck(t, string(out), err) |
| + out, err = exec.Command("systemctl", "show", terminateWitnessUnit, "-p", "Before", "-p", "After", "-p", "Conflicts", "-p", "DefaultDependencies", "-p", "TimeoutStopUSec").CombinedOutput() |
| + lifecycleCheck(t, "effective witness properties", err) |
| + t.Logf("effective witness properties:\n%s", out) |
| + props := map[string]string{} |
| + for _, line := range strings.Split(string(out), "\n") { |
| + k, v, _ := strings.Cut(line, "=") |
| + props[k] = v |
| + } |
| + has := func(key, value string) bool { |
| + for _, word := range strings.Fields(props[key]) { |
| + if word == value { |
| + return true |
| + } |
| + } |
| + return false |
| + } |
| + if !has("Before", "carlos-edge.service") || !has("Before", "shutdown.target") || !has("Conflicts", "shutdown.target") || !has("After", "network.target") || props["DefaultDependencies"] != "yes" { |
| + t.Fatalf("unsafe witness shutdown ordering: %s", out) |
| + } |
| + deadline := time.Now().Add(5 * time.Minute) |
| + for time.Now().Before(deadline) { |
| + if raw, err := os.ReadFile(filepath.Join(terminateWitnessRoot, "ready")); err == nil { |
| + t.Logf("READY lock=%s", raw) |
| + return |
| + } |
| + out, err := exec.Command("systemctl", "is-active", terminateWitnessUnit).CombinedOutput() |
| + if err != nil { |
| + journal, _ := exec.Command("journalctl", "-u", terminateWitnessUnit, "-u", "carlos-edge.service", "-u", "carlos-instance-control.service", "-b", "--no-pager", "-n", "150").CombinedOutput() |
| + t.Fatalf("witness stopped: %s\n%s", out, journal) |
| + } |
| + time.Sleep(time.Second) |
| + } |
| + out, _ = exec.Command("journalctl", "-u", terminateWitnessUnit, "-u", "carlos-edge.service", "-u", "carlos-instance-control.service", "-b", "--no-pager", "-n", "150").CombinedOutput() |
| + t.Fatalf("witness readiness timeout:\n%s", out) |
| +} |
| + |
| +func TestHATerminateMirror(t *testing.T) { |
| + for _, status := range []int{http.StatusOK, http.StatusServiceUnavailable} { |
| + t.Run(fmt.Sprint(status), func(t *testing.T) { |
| + entered, allow := make(chan []byte, 1), make(chan struct{}) |
| + remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + body, err := io.ReadAll(r.Body) |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + entered <- body |
| + <-allow |
| + w.WriteHeader(status) |
| + })) |
| + defer remote.Close() |
| + mirror := &terminateMirror{prefix: "root-runner/test/", client: s3.NewFromConfig(aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("fake", "fake", ""), RetryMaxAttempts: 1}, func(o *s3.Options) { |
| + o.BaseEndpoint = aws.String(remote.URL) |
| + o.UsePathStyle = true |
| + })} |
| + lock := `{"generation":1,"owner":"held"}` |
| + fixture := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("ETag", `"fixture"`); w.WriteHeader(200) }) |
| + handler := mirror.wrap(fixture) |
| + reply := httptest.NewRecorder() |
| + done := make(chan struct{}) |
| + go func() { |
| + handler.ServeHTTP(reply, httptest.NewRequest("PUT", terminateLockPath, strings.NewReader(lock))) |
| + close(done) |
| + }() |
| + var raw []byte |
| + select { |
| + case raw = <-entered: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("mirror never started") |
| + } |
| + select { |
| + case <-done: |
| + t.Error("fixture replied before mirror completed") |
| + default: |
| + } |
| + close(allow) |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("mirror never completed") |
| + } |
| + var event terminateEvent |
| + if err := json.Unmarshal(raw, &event); err != nil || string(event.Lock) != lock || event.Kind != "lock-write" { |
| + t.Fatalf("wrong event %s: %v", raw, err) |
| + } |
| + if status == 200 { |
| + if reply.Code != 200 || reply.Header().Get("ETag") != `"fixture"` || mirror.failure != "" { |
| + t.Fatalf("successful mirror: %v failure=%s", reply, mirror.failure) |
| + } |
| + } else if reply.Code != 500 || mirror.failure == "" { |
| + t.Fatal("mirror failure was acknowledged as a successful lock write") |
| + } |
| + rejected := mirror.wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(412) })) |
| + rejectedReply := httptest.NewRecorder() |
| + rejected.ServeHTTP(rejectedReply, httptest.NewRequest("PUT", terminateLockPath, strings.NewReader(lock))) |
| + select { |
| + case <-entered: |
| + t.Fatal("rejected PUT was mirrored") |
| + default: |
| + } |
| + if rejectedReply.Code != 412 { |
| + t.Fatal(rejectedReply.Code) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/plan14_generation_registry_root_linux_test.go b/internal/host/plan14_generation_registry_root_linux_test.go| index 8b0114686..20de50ce6 100644 |
| --- a/internal/host/plan14_generation_registry_root_linux_test.go |
| +++ b/internal/host/plan14_generation_registry_root_linux_test.go |
| @@ -5,6 +5,7 @@ package host |
| import ( |
| "flag" |
| "fmt" |
| + "github.com/carlosframework/platform/internal/cgroup" |
| "github.com/carlosframework/platform/internal/instanceexec" |
| "github.com/carlosframework/platform/internal/version" |
| "os" |
| @@ -16,6 +17,7 @@ import ( |
| // The test binary must take the same private registry entrypoint as carlos. |
| func TestMain(m *testing.M) { |
| + cgroup.RunShimIfRequested() |
| // The installed carlos-dbread@ unit runs this binary as |
| // /opt/carlos/carlos system db-worker (dbreads_rootrunner_linux_test.go). |
| if len(os.Args) == 3 && os.Args[1] == "system" && os.Args[2] == "db-worker" { |