hosted: ops block --max deadlines, reboot --not-after (Task 34 kit)
After-cap fixes from Astra's plan review r3, rulings K12 and K13: - block --max D: the command runs as its own process group under a deadline that every ops inside inherits (tofu gets TERM, then KILL). Past it the group is stopped, DEADLINE journalled, roots left applying reconciled, exit 1. unit start --max D sets RuntimeMaxSec. - controller reboot --not-after T: judged right before the reboot call; late is REBOOT-LATE, no call, exit 1. REBOOT-SENT records the provider's acceptance.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+383
−15
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+41 −0infra/hosted/README.md+8 −0internal/hostedops/kit34r3_test.go+180 −0internal/hostedops/ops.go+10 −3internal/hostedops/ops_test.go+1 −0internal/hostedops/proc_other.go+14 −0internal/hostedops/proc_unix.go+31 −0internal/hostedops/stop.go+64 −7internal/hostedops/tf.go+1 −0internal/hostedops/unfence.go+19 −2internal/hostedops/units.go+13 −2
CI failed — run details
CI log
=== prepare ===
ci-box: machine: aarch64, 32 CPUs, 62 GiB memory, kernel 7.0.0-1017-aws
ci-box: python 3.12.3; Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2
ci-box: user namespaces allowed: 233151
ci-box: cgroup: cgroup2fs
ci-box: disk /home/ci/work/repos/oficina__equipo/wt/hosted-runners-2: Type Size Avail | ext4 96G 84G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type Size Avail | ext4 96G 84G
ci-box: bwrap: fetched and verified in 0.3s
ci-box: claude: fetched and verified in 3.4s
ci-box: codex: fetched and verified in 4.5s
ci-box: codex-code-mode-host: fetched and verified in 1.9s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.4s
ci-box: tofu: fetched and verified in 1.8s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 9.9s
ci-box: pi: installed and verified in 7.4s
ci-box: opencode: installed and verified in 2.3s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 9.4s
ci-box: clone deepened in 6.1s
ci-box: file times set from content: 4066 files, 303 directories
ci-box: ready in 20.8s
=== copy ===
EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$' -count=1
--- FAIL: TestReleaseCopyReviewed (0.09s)
task_pages_test.go:236: COPY REVIEW REQUIRED: copy-status.py verify found copy pending review or stale bookkeeping
FAIL
rastrillo-budget/v1 ran 89ms
FAIL amadan.net/oficina/equipo/internal/equipotest 0.246s
FAIL
make: *** [Makefile:324: copy-release-check] Error 1
amadan: step copy failed: exit status 2
amadan: job failed at step copy — its output is above, not at the tail of this log
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index e458901a..13c00730 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -88,4 +88,4 @@ perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin, |
| # and the same bounded cardView as the snapshot; no list scan or new route. |
| perf GET /api/v1/tasks/{id}/changes/diff skip Device-only bounded display patch JSON: indexed step/attempt lookup, 64 KiB patch and 128 KiB response, no Git or network work at read time; not an HTML screen. |
| size internal/hostedctl 6079 10017 Hosted controller core and its lifecycle simulation; split planned for slice 1b; slice 2: egress snapshot, admission, deadlines, healthz; measured 6079/10017. |
| -size internal/hostedops 7915 - Hosted slice 2 Task 33: equipo-hosted-ops, one journal and one Ops shared by every run kit subcommand, so one package; dev drill run-kit fixes 2 and 5 to 7 (fence record, reboot waits, scan retry, S.1 argv); Task 34 kit K1 to K8 (teardown blocks, exit classes, tag cross-check, VM accounting and step settle, unit status and retries, finding); round 2 K9 to K11 (recovery-to-teardown continuation, settle --ended-at, resumable bucket teardown); measured 7915. |
| +size internal/hostedops 8053 - Hosted slice 2 Task 33: equipo-hosted-ops, one journal and one Ops shared by every run kit subcommand, so one package; dev drill run-kit fixes 2 and 5 to 7 (fence record, reboot waits, scan retry, S.1 argv); Task 34 kit K1 to K8 (teardown blocks, exit classes, tag cross-check, VM accounting and step settle, unit status and retries, finding); round 2 K9 to K11 (recovery-to-teardown continuation, settle --ended-at, resumable bucket teardown); after cap K12 and K13 (block deadlines with process groups, reboot --not-after); measured 8053. |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 3018e1e0..71274a8f 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -3889,3 +3889,44 @@ judged; two live VMs with unknown IDs were "missed window" with no reboot; `tear |
| steps in the ruled order, and an ordinary image-delete failure took `8.4.1.retry1`. The stub run |
| found one real race, fixed in the plan: when `HOSTED-CHECKS-END` and `HOSTED-SUITE` land between two |
| reads, the watcher now reads the checks-end line once more before settling from now. |
| + |
| +### Task 34 kit, after cap (Astra's plan review r3 findings 1 and 10, rulings K12 and K13, 2026-12-02) |
| + |
| +No AWS call of any kind. |
| + |
| +- **K12** `ops block ID [--teardown] --max D` (D at most 24h): the command runs as the leader of its |
| + own process group (`proc_unix.go`; elsewhere the context kills the command) under a context with |
| + that deadline, which also reaches every `ops` inside it as `EQUIPO_HOSTED_OPS_DEADLINE` (Main |
| + takes it as its context's deadline). tofu now gets TERM when its context ends and KILL 60 s later. |
| + Past the deadline the group gets TERM, then KILL after 30 s; the block journals `DEADLINE |
| + block=ID max=D exit=N`, reconciles (`tf reconcile`, 15 min for all, a fresh context) every root |
| + whose last `TF-APPLY` started and did not finish, FINDINGs for any reconcile that fails, and exits |
| + 1, never 99, asking for no recovery. `ops unit start BLOCK --max D -- CMD` sets RuntimeMaxSec. |
| +- **K13** `ops controller reboot --not-after RFC3339`: judged after the guard, the policy and host |
| + reads, the controller dial and the `REBOOT` intent, immediately before RebootInstances. Late: |
| + `REBOOT-LATE ID now= not-after=`, no reboot call, exit 1. Sent: `REBOOT-SENT ID at=<the time the |
| + call returned>`, whether or not `--not-after` was given. |
| + |
| +Tests: `internal/hostedops/kit34r3_test.go` (unix only: `TestBlockDeadlineKillsAndReconciles`, a |
| +real `sh` running the fake tofu stalled in apply with a grandchild `sleep`; |
| +`TestTofuGetsTheInheritedDeadline`; `TestUnitStartMax`; `TestRebootNotAfter`, with the provider fake; |
| +`TestRound3InvocationsParse`). The fake tofu stalls on `stall-apply`. Red first (only the |
| +`DeadlineEnv` constant, so failures are assertions): `kit34r3_test.go:52: the stalled grandchild "" |
| +survived the deadline` (the block refused `--max`), `:86: ops tf network network = 0, want 1` (the |
| +stall ran its full 120 s), `:98: ops unit start 8.6 --max 70m ... = 1, want 0`, `:121: a late reboot: |
| +calls []`, `:164: ops block 8.4 --teardown --max 30m ...: usage: ...`. Green: `./internal/hostedops/...`, |
| +`./cmd/equipo-hosted-ops`, `./cmd/equipo-hosted-image`, `./internal/isolatedjob/awsjob/opsaws`. |
| + |
| +Mutation checks, each restored and green again (`go test ./internal/hostedops -count=1 -run <test>`): |
| +- **K12a** no process group (`groupCmd` dropped): `TestBlockDeadlineKillsAndReconciles` FAILED |
| + `:47 the block ran 2m0.01s past a 2s deadline`. |
| +- **K12b** no reconcile: FAILED `:58 no reconcile after the deadline`. |
| +- **K12c** the deadline treated as a failed required block: FAILED `:45 ... = 99, want 1`. |
| +- **K12d** no DEADLINE line: FAILED `:55 no DEADLINE line`. |
| +- **K12g** the reconcile run under an already-ended context: FAILED `:58 no reconcile after the deadline`. |
| +- **K12e** the inherited deadline ignored: `TestTofuGetsTheInheritedDeadline` FAILED `:93 ops tf network |
| + network = 0, want 1`. |
| +- **K12f** `unit start --max` not passed on: the first form made the variable unused (a build error, |
| + not counted); as `0*d`, `TestUnitStartMax` FAILED `:107 RuntimeMaxSec 0s, want 70m`. |
| +- **K13a** a late reboot sent: `TestRebootNotAfter` FAILED `:126 ... --not-after 2026-12-01T09:59:59Z = 0, want 1`. |
| +- **K13b** REBOOT-SENT without its time: FAILED `:136 an in-time reboot: calls [RolePolicyAttached ... RebootInstance i-0ctl]`. |
diff --git a/infra/hosted/README.md b/infra/hosted/README.md| index 47ff99ea..d84ceb26 100644 |
| --- a/infra/hosted/README.md |
| +++ b/infra/hosted/README.md |
| @@ -206,6 +206,14 @@ teardown the recovery unit starts by itself once a safe stop has finished |
| unless a guard failure caused the stop, the file changed since the arm, |
| or it already ran once. `ops continuation disarm` withdraws it. |
| +`ops block ID [--teardown] --max D -- CMD` gives CMD a deadline: past it |
| +its whole process group is stopped (TERM, then KILL after 30 s), the |
| +block journals `DEADLINE`, reconciles every root it left applying (state |
| +is recorded as it stands) and exits 1, for the plan's retry. `ops unit |
| +start BLOCK --max D` sets the unit's `RuntimeMaxSec`. `ops controller |
| +reboot --not-after T` sends nothing after T (`REBOOT-LATE`, 1) and |
| +journals `REBOOT-SENT at=` when the provider accepted the reboot. |
| + |
| ## Checks |
| ``` |
diff --git a/internal/hostedops/kit34r3_test.go b/internal/hostedops/kit34r3_test.go| new file mode 100644 |
| index 00000000..2ccbca9a |
| --- /dev/null |
| +++ b/internal/hostedops/kit34r3_test.go |
| @@ -0,0 +1,180 @@ |
| +//go:build unix |
| + |
| +package hostedops |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| +) |
| + |
| +// After-cap kit fixes from the dev drill plan's review round 3 (p34-r3.md |
| +// findings 1 and 10), rulings K12 and K13. |
| + |
| +// gone reports whether the process pid no longer runs (within 3 s). |
| +func gone(pid int) bool { |
| + for i := 0; i < 60; i++ { |
| + if err := syscall.Kill(pid, 0); err == syscall.ESRCH { |
| + return true |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + return false |
| +} |
| + |
| +// K12: a block's --max kills its whole process group at the deadline, |
| +// journals DEADLINE, reconciles every root whose apply did not finish (so |
| +// what state holds is recorded) and exits 1, never 99, asking for no |
| +// recovery. |
| +func TestBlockDeadlineKillsAndReconciles(t *testing.T) { |
| + r, fake := tfRig(t, |
| + "REC tf network/module.network.aws_vpc.vm id=vpc-0vm type=aws_vpc source=state", |
| + "INTENT tf network/module.network.aws_iam_role.connector_operator - type=aws_iam_role name=equipo-hosted-connector-operator", |
| + "TF-APPLY network start destroy-network") |
| + os.WriteFile(filepath.Join(fake, "stall-apply"), nil, 0o600) |
| + os.WriteFile(filepath.Join(fake, "plan-network-refresh.json"), []byte(`{"planned_values":{"root_module":{"child_modules":[{"resources":[ |
| +{"address":"module.network.aws_vpc.vm","type":"aws_vpc","values":{"id":"vpc-0vm"}}, |
| +{"address":"module.network.aws_iam_role.connector_operator","type":"aws_iam_role","values":{"id":"equipo-hosted-connector-operator","arn":"arn:aws:iam::149757027610:role/equipo-hosted-connector-operator","name":"equipo-hosted-connector-operator"}}]}]}}}`), 0o600) |
| + start := time.Now() |
| + r.want(ExitFail, "block", "8.3", "--teardown", "--max", "2s", "--", "sh", "-c", `"$FAKE_TOFU/tofu" -chdir=x apply x.tfplan`) |
| + if d := time.Since(start); d > 30*time.Second { |
| + t.Fatalf("the block ran %v past a 2s deadline", d) |
| + } |
| + raw, _ := os.ReadFile(filepath.Join(fake, "sleep.pid")) |
| + pid, err := strconv.Atoi(strings.TrimSpace(string(raw))) |
| + if err != nil || !gone(pid) { |
| + t.Fatalf("the stalled grandchild %q survived the deadline (%v)", raw, err) |
| + } |
| + if !r.has("DEADLINE", "block=8.3 max=2s") { |
| + t.Fatalf("no DEADLINE line:\n%s", journalText(r)) |
| + } |
| + if !strings.Contains(calls(t, fake), "-refresh-only") || !r.has("TF-RECONCILED", "network") { |
| + t.Fatalf("no reconcile after the deadline:\n%s\n%s", calls(t, fake), journalText(r)) |
| + } |
| + l := r.ledger() |
| + if l.RecValue("tf", "network/module.network.aws_vpc.vm") == "" || l.Deleted["tf network/module.network.aws_vpc.vm"] { |
| + t.Fatal("a resource state still holds is not recorded present") |
| + } |
| + if l.RecValue("tf", "network/module.network.aws_iam_role.connector_operator") == "" || len(l.Open("tf")) != 0 { |
| + t.Fatalf("the reconcile did not record what state holds: open %d", len(l.Open("tf"))) |
| + } |
| + if r.has("SAFE-STOP", "") || r.has("RECOVERY", "") { |
| + t.Fatal("a deadline asked for recovery") |
| + } |
| + // A block that ends in time is untouched by --max. |
| + r = newRig(t) |
| + r.want(0, "block", "8.4", "--max", "1m", "--", "true") |
| + if r.has("DEADLINE", "") { |
| + t.Fatal("a block that ended in time journalled DEADLINE") |
| + } |
| + r.want(ExitFail, "block", "8.5", "--max", "25h", "--", "true") |
| +} |
| + |
| +// K12: ops gives tofu the deadline it inherits (EQUIPO_HOSTED_OPS_DEADLINE) |
| +// through its context: a stalled apply is stopped there, an ordinary 1. |
| +func TestTofuGetsTheInheritedDeadline(t *testing.T) { |
| + r, fake := tfRig(t) |
| + os.WriteFile(filepath.Join(fake, "stall-apply"), nil, 0o600) |
| + t.Cleanup(func() { // tofu alone is stopped here; its stray sleep is the test's to end |
| + if raw, err := os.ReadFile(filepath.Join(fake, "sleep.pid")); err == nil { |
| + if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil { |
| + _ = syscall.Kill(pid, syscall.SIGKILL) |
| + } |
| + } |
| + }) |
| + t.Setenv(DeadlineEnv, strconv.FormatInt(time.Now().Add(2*time.Second).UnixNano(), 10)) |
| + start := time.Now() |
| + r.want(ExitFail, "tf", "network", "network") |
| + if d := time.Since(start); d > 30*time.Second { |
| + t.Fatalf("tofu ran %v past the inherited deadline", d) |
| + } |
| + if !r.has("FINDING", "apply of network failed") { |
| + t.Fatalf("the stopped apply is not a FINDING:\n%s", journalText(r)) |
| + } |
| +} |
| + |
| +// K12: unit start --max sets the unit's RuntimeMaxSec. |
| +func TestUnitStartMax(t *testing.T) { |
| + r := newRig(t) |
| + r.want(0, "unit", "start", "8.6", "--max", "70m", "--", "bash", "x") |
| + if got := r.systemd.runtimes["hprod-r1-8.6.service"]; got != 70*time.Minute { |
| + t.Fatalf("RuntimeMaxSec %v, want 70m", got) |
| + } |
| + r.systemd.states["hprod-r1-8.6.service"] = "done" |
| + r.want(0, "unit", "start", "8.7", "--", "bash", "x") |
| + if got := r.systemd.runtimes["hprod-r1-8.7.service"]; got != 0 { |
| + t.Fatalf("a unit without --max got RuntimeMaxSec %v", got) |
| + } |
| + r.systemd.states["hprod-r1-8.7.service"] = "done" |
| + r.want(ExitFail, "unit", "start", "8.8", "--max", "0s", "--", "bash", "x") |
| + r.want(ExitFail, "unit", "start", "8.8", "--max", "25h", "--", "bash", "x") |
| +} |
| + |
| +// K13: reboot --not-after checks the deadline after its reads, right |
| +// before the reboot call: late, it journals REBOOT-LATE, makes no reboot |
| +// call and exits 1; in time, REBOOT-SENT records when the provider |
| +// accepted it, after the REBOOT intent. |
| +func TestRebootNotAfter(t *testing.T) { |
| + on, off := hostedwire.StatusResponse{Enabled: true}, hostedwire.StatusResponse{Enabled: false} |
| + r, _ := rebootRig(t, off, on) |
| + r.want(ExitFail, "controller", "reboot", "--enabled", "1", "--controller", "https://198.51.100.7", "--not-after", t0.Add(-time.Second).Format(time.RFC3339)) |
| + if r.cloud.count("RebootInstance") != 0 || !r.has("REBOOT-LATE", "i-0ctl") || r.has("REBOOT-SENT", "") { |
| + t.Fatalf("a late reboot: calls %v\n%s", r.cloud.log(), journalText(r)) |
| + } |
| + if r.cloud.index("RolePolicyAttached") < 0 { |
| + t.Fatal("the deadline was judged before the policy read") |
| + } |
| + r, _ = rebootRig(t, off, on) |
| + r.want(0, "controller", "reboot", "--enabled", "1", "--controller", "https://198.51.100.7", "--not-after", t0.Add(time.Minute).Format(time.RFC3339)) |
| + if r.cloud.count("RebootInstance") != 1 || !r.has("REBOOT-SENT", "i-0ctl at="+t0.Format(time.RFC3339Nano)) { |
| + t.Fatalf("an in-time reboot: calls %v\n%s", r.cloud.log(), journalText(r)) |
| + } |
| + var intent, sent int |
| + for _, e := range r.ledger().Entries { |
| + switch e.Verb { |
| + case "REBOOT": |
| + intent = e.Line |
| + case "REBOOT-SENT": |
| + sent = e.Line |
| + } |
| + } |
| + if intent == 0 || sent < intent { |
| + t.Fatalf("REBOOT at line %d, REBOOT-SENT at %d", intent, sent) |
| + } |
| + r, _ = rebootRig(t, off, on) |
| + r.want(ExitFail, "controller", "reboot", "--enabled", "1", "--controller", "https://198.51.100.7", "--not-after", "soon") |
| +} |
| + |
| +// The new forms through the plan-parse machinery. |
| +func TestRound3InvocationsParse(t *testing.T) { |
| + plan := "```sh\n" + strings.Join([]string{ |
| + `ops block 8.4 --teardown --max 30m -- bash "$P/blocks/8.4.sh"`, |
| + `ops block 1.1 --stop 40 --max 10m -- bash "$P/blocks/1.1.sh"`, |
| + `ops unit start 8.6 --max 70m -- bash "$P/blocks/8.6.sh"`, |
| + `ops controller reboot --enabled 1 --max 10m --not-after 2026-12-01T10:05:00Z`, |
| + }, "\n") + "\n```\n" |
| + invs := planInvocations(plan) |
| + if len(invs) != 4 { |
| + t.Fatalf("%d invocations: %q", len(invs), invs) |
| + } |
| + for _, inv := range invs { |
| + r := newRig(t, "REC microvm-image "+image1) |
| + r.deps.Exec = func(ctxT, []string, []string, wT, wT) int { return 0 } |
| + r.ops(inv...) |
| + if out := r.out.String(); strings.Contains(out, "unknown command") || strings.Contains(out, "usage:") { |
| + t.Errorf("ops %s: %s", strings.Join(inv, " "), out) |
| + } |
| + } |
| + u := usageText() |
| + for _, want := range []string{"block ID [--stop USD | --teardown] [--max D] [--optional] -- CMD...", "unit start BLOCK[.retry1|.retry2] [--max D] -- CMD...", "--not-after RFC3339"} { |
| + if !strings.Contains(u, want) { |
| + t.Errorf("the usage lacks %q", want) |
| + } |
| + } |
| +} |
diff --git a/internal/hostedops/ops.go b/internal/hostedops/ops.go| index 2cc3831c..6f0a5f84 100644 |
| --- a/internal/hostedops/ops.go |
| +++ b/internal/hostedops/ops.go |
| @@ -67,6 +67,7 @@ import ( |
| "path/filepath" |
| "regexp" |
| "sort" |
| + "strconv" |
| "strings" |
| "time" |
| ) |
| @@ -314,8 +315,8 @@ func init() { |
| "bucket create": {true, cmdBucketCreate, "--name N --versioning --sse AES256 --block-public --expected-owner A"}, |
| "bucket empty": {true, cmdBucketEmpty, "--name N [--expected-owner A]"}, |
| "bucket delete": {true, cmdBucketDelete, "--name N [--expected-owner A]"}, |
| - "block": {false, cmdBlock, "ID [--stop USD | --teardown] [--optional] -- CMD..."}, |
| - "unit start": {false, cmdUnitStart, "BLOCK[.retry1|.retry2] -- CMD..."}, |
| + "block": {false, cmdBlock, "ID [--stop USD | --teardown] [--max D] [--optional] -- CMD..."}, |
| + "unit start": {false, cmdUnitStart, "BLOCK[.retry1|.retry2] [--max D] -- CMD..."}, |
| "unit wait": {false, cmdUnitWait, "BLOCK --max D"}, |
| "continuation arm": {false, cmdContinuationArm, "FILE --max D: after any safe stop but a guard failure, the recovery unit runs FILE (sha256 checked) as h<env>-<RUN>-teardown"}, |
| "continuation disarm": {false, cmdContinuationDisarm, ""}, |
| @@ -344,7 +345,7 @@ func init() { |
| "fence": {true, cmdFence, ""}, |
| "unfence": {true, cmdUnfence, ""}, |
| "controller terminate": {true, cmdControllerTerminate, ""}, |
| - "controller reboot": {true, cmdControllerReboot, "--enabled 1|0 [--max D] [controller flags]"}, |
| + "controller reboot": {true, cmdControllerReboot, "--enabled 1|0 [--max D] [--not-after RFC3339] [controller flags]"}, |
| "cloudtrail stop-logging": {true, cmdTrailStop, ""}, |
| } |
| } |
| @@ -366,6 +367,12 @@ func lookup(args []string) (string, command, []string, bool) { |
| // Main runs one invocation and returns its exit code. |
| func Main(ctx context.Context, args []string, d Deps) int { |
| + // A block's deadline, inherited (K12): every call, and tofu, ends by it. |
| + if n, err := strconv.ParseInt(os.Getenv(DeadlineEnv), 10, 64); err == nil && n > 0 { |
| + var cancel context.CancelFunc |
| + ctx, cancel = context.WithDeadline(ctx, time.Unix(0, n)) |
| + defer cancel() |
| + } |
| o := &Ops{Deps: d, ctx: ctx} |
| if o.Stdout == nil { |
| o.Stdout = os.Stdout |
diff --git a/internal/hostedops/ops_test.go b/internal/hostedops/ops_test.go| index ff9c25cc..db1a8c01 100644 |
| --- a/internal/hostedops/ops_test.go |
| +++ b/internal/hostedops/ops_test.go |
| @@ -210,6 +210,7 @@ case " $* " in |
| *" show -json -no-color "*) cat "$FAKE_TOFU/state.json";; |
| *" output -json "*) echo '{"vm_vpc_id":{"value":"vpc-0vm"}}';; |
| esac |
| +case " $* " in *" apply "*) if [ -f "$FAKE_TOFU/stall-apply" ]; then sleep 120 >/dev/null 2>&1 & echo $! > "$FAKE_TOFU/sleep.pid"; wait; fi;; esac |
| case " $* " in *" apply "*) [ -f "$FAKE_TOFU/fail-apply" ] && exit 1;; esac |
| exit 0 |
| ` |
diff --git a/internal/hostedops/proc_other.go b/internal/hostedops/proc_other.go| new file mode 100644 |
| index 00000000..e5a4e7b8 |
| --- /dev/null |
| +++ b/internal/hostedops/proc_other.go |
| @@ -0,0 +1,14 @@ |
| +//go:build !unix |
| + |
| +package hostedops |
| + |
| +import ( |
| + "os/exec" |
| + "time" |
| +) |
| + |
| +// groupCmd: no process groups here; the context's end kills the command. |
| +func groupCmd(cmd *exec.Cmd, grace time.Duration) { cmd.WaitDelay = grace } |
| + |
| +// termCmd: the context's end kills the command. |
| +func termCmd(cmd *exec.Cmd, grace time.Duration) { cmd.WaitDelay = grace } |
diff --git a/internal/hostedops/proc_unix.go b/internal/hostedops/proc_unix.go| new file mode 100644 |
| index 00000000..555dbd0d |
| --- /dev/null |
| +++ b/internal/hostedops/proc_unix.go |
| @@ -0,0 +1,31 @@ |
| +//go:build unix |
| + |
| +package hostedops |
| + |
| +import ( |
| + "os/exec" |
| + "syscall" |
| + "time" |
| +) |
| + |
| +// groupCmd runs cmd as the leader of its own process group: when its |
| +// context ends (a block's --max, or ops itself told to stop) the whole |
| +// group gets TERM, then KILL after grace, so no grandchild (tofu, a |
| +// provider plugin, a sleep) outlives it (K12). |
| +func groupCmd(cmd *exec.Cmd, grace time.Duration) { |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
| + cmd.Cancel = func() error { |
| + pid := cmd.Process.Pid |
| + err := syscall.Kill(-pid, syscall.SIGTERM) |
| + time.AfterFunc(grace, func() { _ = syscall.Kill(-pid, syscall.SIGKILL) }) |
| + return err |
| + } |
| + cmd.WaitDelay = grace + 5*time.Second |
| +} |
| + |
| +// termCmd stops cmd with TERM when its context ends (tofu then stops |
| +// cleanly and releases its state lock), and kills it after grace. |
| +func termCmd(cmd *exec.Cmd, grace time.Duration) { |
| + cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) } |
| + cmd.WaitDelay = grace |
| +} |
diff --git a/internal/hostedops/stop.go b/internal/hostedops/stop.go| index d29543d2..f85f7805 100644 |
| --- a/internal/hostedops/stop.go |
| +++ b/internal/hostedops/stop.go |
| @@ -9,10 +9,15 @@ import ( |
| "os" |
| "os/exec" |
| "slices" |
| + "strconv" |
| "strings" |
| "time" |
| ) |
| +// DeadlineEnv carries a block's deadline (Unix nanoseconds) to its |
| +// command; ops takes it as its context's deadline (K12). |
| +const DeadlineEnv = "EQUIPO_HOSTED_OPS_DEADLINE" |
| + |
| // TeardownEnv names the teardown block a command runs in: block |
| // --teardown sets it in its command's environment. |
| const TeardownEnv = "EQUIPO_HOSTED_OPS_TEARDOWN" |
| @@ -47,14 +52,19 @@ func cmdBlock(o *Ops, args []string) error { |
| stop := fs.Float64("stop", DefaultStop, "the run's own spend stop") |
| optional := fs.Bool("optional", false, "a non-zero exit other than 99 is not a hard stop") |
| teardown := fs.Bool("teardown", false, "a teardown block: the guard and the ledger's ownership, no spend gate; nothing in it may create") |
| + maxD := fs.Duration("max", 0, "the command's deadline: past it its process group is killed, roots reconciled, exit 1") |
| pos, err := parseFlags(fs, args) |
| stopSet := false |
| fs.Visit(func(f *flag.Flag) { stopSet = stopSet || f.Name == "stop" }) |
| - if err != nil || len(pos) < 2 || !blockPattern.MatchString(pos[0]) || (*teardown && stopSet) { |
| - return usagef("block ID [--stop USD | --teardown] [--optional] -- CMD...") |
| + if err != nil || len(pos) < 2 || !blockPattern.MatchString(pos[0]) || (*teardown && stopSet) || *maxD < 0 || *maxD > MaxBlock { |
| + return usagef("block ID [--stop USD | --teardown] [--max D] [--optional] -- CMD...") |
| } |
| id, argv := pos[0], pos[1:] |
| - if err := o.jw("BLOCK", "%s start", id); err != nil { |
| + start := "%s start" |
| + if *maxD > 0 { |
| + start += " max=" + maxD.String() |
| + } |
| + if err := o.jw("BLOCK", start, id); err != nil { |
| return err |
| } |
| hard := func(why string) error { |
| @@ -95,8 +105,17 @@ func cmdBlock(o *Ops, args []string) error { |
| return hard("the estimate $" + ftoa(e.Total) + " reaches the stop $" + ftoa(*stop)) |
| } |
| } |
| - code := o.execBlock(argv, id, *teardown) |
| + ctx, cancel := o.ctx, context.CancelFunc(func() {}) |
| + if *maxD > 0 { |
| + ctx, cancel = context.WithTimeout(o.ctx, *maxD) |
| + } |
| + code := o.execBlock(ctx, argv, id, *teardown) |
| + expired := ctx.Err() == context.DeadlineExceeded |
| + cancel() |
| _ = o.jw("BLOCK", "%s exit=%d", id, code) |
| + if expired { |
| + return o.blockDeadline(id, *maxD, code) |
| + } |
| switch { |
| case code == 0: |
| return nil |
| @@ -108,19 +127,57 @@ func cmdBlock(o *Ops, args []string) error { |
| return &exitError{code: code, msg: "block " + id + " exited " + itoa(code)} |
| } |
| -func (o *Ops) execBlock(argv []string, id string, teardown bool) int { |
| +func (o *Ops) execBlock(ctx context.Context, argv []string, id string, teardown bool) int { |
| env := append(os.Environ(), "EQUIPO_HOSTED_OPS_BLOCK="+id) |
| if teardown { |
| env = append(env, TeardownEnv+"="+id) |
| } |
| + if d, ok := ctx.Deadline(); ok { |
| + env = append(env, DeadlineEnv+"="+strconv.FormatInt(d.UnixNano(), 10)) |
| + } |
| if o.Exec != nil { |
| - return o.Exec(o.ctx, argv, env, o.Stdout, o.Stderr) |
| + return o.Exec(ctx, argv, env, o.Stdout, o.Stderr) |
| + } |
| + return runChild(ctx, argv, env, o.Stdout, o.Stderr) |
| +} |
| + |
| +// Block deadlines (K12, p34-r3 finding 1). |
| +const ( |
| + MaxBlock = 24 * time.Hour // --max's ceiling |
| + BlockKillGrace = 30 * time.Second // TERM to KILL for a block's process group |
| + TofuStopGrace = 60 * time.Second // TERM to KILL for tofu |
| + DeadlineReconcile = 15 * time.Minute // the reconcile after a deadline, all roots together |
| +) |
| + |
| +// blockDeadline is a block past its --max: its process group was killed |
| +// (runChild). DEADLINE is journalled; each root whose apply or destroy |
| +// started and did not finish is reconciled, so what state holds is |
| +// recorded (a killed apply's creates, a killed destroy's survivors stay |
| +// recorded present); exit 1, ordinary: the plan may retry within its own |
| +// budget. Never 99, and no recovery is asked for. |
| +func (o *Ops) blockDeadline(id string, maxD time.Duration, code int) error { |
| + _ = o.jw("DEADLINE", "block=%s max=%s exit=%d: its process group was killed", id, maxD, code) |
| + o.out("block %s passed its %s deadline; its processes were killed; reconciling", id, maxD) |
| + outer := o.ctx |
| + ctx, cancel := context.WithTimeout(context.WithoutCancel(outer), DeadlineReconcile) |
| + o.ctx = ctx |
| + defer func() { cancel(); o.ctx = outer }() |
| + if l, err := o.ledger(); err == nil { |
| + for _, root := range roots { |
| + if !l.TFApplying[root] { |
| + continue |
| + } |
| + if err := o.tfReconcile(root); err != nil { |
| + _ = o.finding("block %s: after its deadline, tf reconcile %s: %v", id, root, err) |
| + } |
| + } |
| } |
| - return runChild(o.ctx, argv, env, o.Stdout, o.Stderr) |
| + return failf("block %s passed its %s deadline: its processes were killed and the roots it left applying reconciled; a retry is the plan's", id, maxD) |
| } |
| func runChild(ctx context.Context, argv, env []string, stdout, stderr io.Writer) int { |
| cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) |
| + groupCmd(cmd, BlockKillGrace) |
| cmd.Env, cmd.Stdout, cmd.Stderr, cmd.Stdin = env, stdout, stderr, nil |
| err := cmd.Run() |
| var x *exec.ExitError |
diff --git a/internal/hostedops/tf.go b/internal/hostedops/tf.go| index ba8cb5cd..869b24d1 100644 |
| --- a/internal/hostedops/tf.go |
| +++ b/internal/hostedops/tf.go |
| @@ -122,6 +122,7 @@ func (o *Ops) tofuEnv(k Keys) []string { |
| // tofu runs one tofu command and returns its stdout. |
| func (o *Ops) tofu(args ...string) ([]byte, error) { |
| cmd := exec.CommandContext(o.ctx, o.Tofu, args...) |
| + termCmd(cmd, TofuStopGrace) // the context's deadline (a block's --max) stops tofu cleanly first |
| cmd.Env = o.tofuEnv(o.cloud.Keys()) |
| var out bytes.Buffer |
| cmd.Stdout, cmd.Stderr = &out, o.Stderr |
diff --git a/internal/hostedops/unfence.go b/internal/hostedops/unfence.go| index 6149bcde..da5afcfc 100644 |
| --- a/internal/hostedops/unfence.go |
| +++ b/internal/hostedops/unfence.go |
| @@ -189,9 +189,15 @@ func cmdControllerReboot(o *Ops, args []string) error { |
| fs := flag.NewFlagSet("controller reboot", flag.ContinueOnError) |
| enabled := fs.String("enabled", "", "1 or 0: the launch switch controller/env now holds") |
| maxD := fs.Duration("max", hostWait, "the bound for the controller to answer again") |
| + notAfter := fs.String("not-after", "", "RFC 3339: no reboot call after this (a drill's strike window)") |
| ca := controllerFlags(fs) |
| - if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || (*enabled != "1" && *enabled != "0") { |
| - return usagef("controller reboot --enabled 1|0 [--max D] [--controller URL --pin HEX --operator-key FILE]") |
| + var deadline time.Time |
| + pos, err := parseFlags(fs, args) |
| + if err == nil && *notAfter != "" { |
| + deadline, err = time.Parse(time.RFC3339, *notAfter) |
| + } |
| + if err != nil || len(pos) != 0 || (*enabled != "1" && *enabled != "0") { |
| + return usagef("controller reboot --enabled 1|0 [--max D] [--not-after RFC3339] [--controller URL --pin HEX --operator-key FILE]") |
| } |
| if *maxD <= 0 || *maxD > 30*time.Minute { |
| return failf("--max must be positive and at most 30m") |
| @@ -215,9 +221,20 @@ func cmdControllerReboot(o *Ops, args []string) error { |
| if err := o.jw("REBOOT", "%s enabled=%s", ids[0], *enabled); err != nil { |
| return err |
| } |
| + // --not-after (K13, p34-r3 finding 10) is judged here, after the |
| + // guard, the policy and host reads and the dial, immediately before |
| + // the call: late, nothing is sent (1). REBOOT-SENT, not the REBOOT |
| + // intent above, says when the provider accepted the reboot. |
| + if now := o.Clock.Now(); !deadline.IsZero() && now.After(deadline) { |
| + _ = o.jw("REBOOT-LATE", "%s now=%s not-after=%s: no reboot sent", ids[0], now.UTC().Format(time.RFC3339Nano), deadline.UTC().Format(time.RFC3339)) |
| + return failf("the reboot of %s would be sent at %s, after --not-after %s; nothing sent", ids[0], now.UTC().Format(time.RFC3339), deadline.UTC().Format(time.RFC3339)) |
| + } |
| if err := o.cloud.RebootInstance(o.ctx, ids[0]); err != nil { |
| return failf("rebooting %s failed: %v", ids[0], err) |
| } |
| + if err := o.jw("REBOOT-SENT", "%s at=%s", ids[0], o.Clock.Now().UTC().Format(time.RFC3339Nano)); err != nil { |
| + return err |
| + } |
| want := *enabled == "1" |
| end := o.Clock.Now().Add(*maxD) |
| away := false |
diff --git a/internal/hostedops/units.go b/internal/hostedops/units.go| index 460eafae..bc92d99d 100644 |
| --- a/internal/hostedops/units.go |
| +++ b/internal/hostedops/units.go |
| @@ -89,9 +89,20 @@ const MaxRetries = 2 |
| // started only once BLOCK (and BLOCK.retry1 .. N-1) were journalled and |
| // read done, failed or not; the link is journalled (UNIT-RETRY). Any other |
| // reuse, a retry out of order, or a busy run is refused (1). |
| +// |
| +// --max D (K12, p34-r3 finding 1) is the unit's RuntimeMaxSec: systemd |
| +// stops a unit run by hand past it, as unit wait would. |
| func cmdUnitStart(o *Ops, args []string) error { |
| + var runtimeMax time.Duration |
| + if len(args) >= 3 && args[1] == "--max" { |
| + d, err := time.ParseDuration(args[2]) |
| + if err != nil || d <= 0 || d > MaxBlock { |
| + return usagef("unit start BLOCK[.retry1|.retry2] [--max D] -- CMD... (D at most %s)", MaxBlock) |
| + } |
| + runtimeMax, args = d, append([]string{args[0]}, args[3:]...) |
| + } |
| if len(args) < 3 || args[1] != "--" || !blockPattern.MatchString(args[0]) { |
| - return usagef("unit start BLOCK[.retry1|.retry2] -- CMD...") |
| + return usagef("unit start BLOCK[.retry1|.retry2] [--max D] -- CMD...") |
| } |
| l, err := o.ledger() |
| if err != nil { |
| @@ -131,7 +142,7 @@ func cmdUnitStart(o *Ops, args []string) error { |
| return err |
| } |
| } |
| - if err := o.startUnit(block, args[2:], 45*time.Second, false); err != nil { |
| + if err := o.startUnitBounded(block, args[2:], 45*time.Second, runtimeMax, false); err != nil { |
| return err |
| } |
| o.out("block %s started as unit %s", block, o.unitName(block)) |