hosted: deadline stops the group before reconcile, own locks only
Fixes from the scoped review of the after-cap change (p34-r4 findings 16 to 19), rulings K14 to K17: - the block's process group is stopped synchronously at its deadline: TERM, up to 90 s, KILL, up to 30 s; not proved gone is a stop. - a state lock is force-unlocked only when this block's killed tofu left it (this user@host, created in the block's window). - the command's 99 and safety errors in the reconcile stay 99; only ordinary tofu failures become FINDINGs. - the reconcile covers only roots the block touched (TF-START).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+643
−56
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+62 −0infra/hosted/README.md+11 −4internal/hostedops/kit34r3_test.go+4 −3internal/hostedops/kit34r4_test.go+262 −0internal/hostedops/ops.go+3 −0internal/hostedops/ops_test.go+4 −0internal/hostedops/proc_other.go+24 −2internal/hostedops/proc_unix.go+55 −11internal/hostedops/stop.go+127 −32internal/hostedops/tf.go+90 −3
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 13c00730..661d4a3c 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 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. |
| +size internal/hostedops 8304 - 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); scoped review K14 to K17 (synchronous group stop, own stale lock release, safety kept, touched roots); measured 8304. |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 3c262c08..f06392ba 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -3984,3 +3984,65 @@ Green: the three plan-parse tests, `make budget`, `bash -n` on all 32 `sh` block |
| `run.env`. Stub run: teardown in order (eight blocks); 8.3a past its deadline once, then |
| `8.3a.retry1` and on; 8.3a past it twice, `escalate`, exit 99; 8.5 past its deadline, `escalate` |
| with no retry, exit 99; the watcher's plain scenario settled at `ended_at` and judged. |
| + |
| +### Task 34 kit, scoped review (Astra p34-r4 findings 16 to 19, rulings K14 to K17, 2026-12-02) |
| + |
| +No AWS call. House rule now followed: the tests kill only the PIDs their commands recorded |
| +(`recordedPIDs`); no pattern or user kills. |
| + |
| +- **K14** `runGroup` (`proc_unix.go`) replaces the scheduled KILL: the block's command leads its own |
| + process group; at the deadline the group gets TERM, the group is probed every 100 ms for up to |
| + `BlockKillGrace` (now 90 s, above `TofuStopGrace` 60 s), then KILL and probes for up to |
| + `GroupKillWait` (30 s); the leader is reaped by `Wait` so a dead leader is not counted. Nothing is |
| + left scheduled. `DEADLINE ... term= kill= gone=` records it. A group not proved gone is a stop |
| + (99, through the block's hard path), with nothing reconciled. |
| +- **K15** `tofu` keeps its stderr; a refresh plan that fails on a state lock is a `LockError` with |
| + the lock's ID, Who, Operation and Created. After a deadline, with the group proved gone, the lock is |
| + released (`tofu force-unlock -force ID`, `FORCE-UNLOCK root id= who= operation= created=`) only |
| + when Who is this user@host (`lockWho`, as OpenTofu writes it) and Created lies after the block's |
| + start and before its deadline; then the reconcile runs once more. Any other lock, a failed |
| + force-unlock, or a lock still there: a stop (99). |
| +- **K16** the command's own 99 stays 99 when the deadline also passed; in the reconcile after a |
| + deadline a stop error (ownership, malformed state, unresolved intents, a lock not released) stops |
| + at once with 99 and no further root; a ledger that does not read is 99; only ordinary failures are |
| + FINDINGs (the next root is still reconciled), and the block exits 1. |
| +- **K17** the reconcile after a deadline covers only the roots this block touched: `ops tf` and `tf |
| + reconcile` now journal `TF-START ROOT PHASE|reconcile` before their tofu work, and the roots with a |
| + `TF-START` since the block's last `BLOCK ID start` are reconciled. `TF-RECONCILED` does not clear |
| + `TFApplying` (safe-stop's S.4 still reconciles a root left applying). |
| + |
| +Tests: `internal/hostedops/kit34r4_test.go` (unix: `TestDeadlineStopsTheGroupSynchronously`, a real |
| +`sh` whose grandchild ignores TERM and outlives it; `TestDeadlineGroupNotProvedGoneStops`, the probe |
| +seam `signalGroup` reporting a member always there; `TestDeadlineReleasesOnlyOurStaleLock`; |
| +`TestDeadlineKeepsSafetyRefusals`; `TestDeadlineReconcilesOnlyTouchedRoots`). The fake tofu prints a |
| +lock on `-refresh-only` while `$FAKE_TOFU/lock` exists, removes it on `force-unlock -force`, and fails |
| +a refresh on `fail-refresh`. The K12 test's command now journals its root's `TF-START`. Test |
| +deadlines are 50 to 500 ms; the package runs in about 6.5 s, and the deadline tests passed ten runs |
| +in a row. |
| + |
| +Red first (a `signalGroup` var, `Deps.groupGrace/groupKillWait` and an empty `lockWho` only): |
| +`kit34r4_test.go:81 the DEADLINE line does not say the group was killed and is gone`, `:105 ... = |
| +1, want 99` (not proved gone), `:147 after the deadline: block = 1, want 99`, `:152 ours: force-unlock |
| +ran false`, `:180 ops block 8.3 --teardown --max 1s -- x = 1, want 99` (a 99 downgraded), `:247 |
| +reconciled the wrong roots`. |
| + |
| +Mutation checks, each restored and green again (`go test ./internal/hostedops -count=1 -run <test>`): |
| +- **K14a** no KILL after the grace: `TestDeadlineStopsTheGroupSynchronously` FAILED `:70 ops block 8.4 |
| + ... = 99, want 1` (the TERM-ignoring grandchild kept the group, not proved gone). |
| +- **K14b** no wait after KILL (`gone = true`): against `TestDeadlineStopsTheGroupSynchronously` it |
| + SURVIVED (KILL takes effect at once there); `TestDeadlineGroupNotProvedGoneStops`, which guards |
| + that wait, FAILED `:105 ... = 1, want 99`. |
| +- **K14c** a group not proved gone accepted: `TestDeadlineGroupNotProvedGoneStops` FAILED `:105 ... = 1, want 99`. |
| +- **K14d** `BlockKillGrace` back to 30 s: FAILED `:84 BlockKillGrace 30s does not exceed tofu's own grace 1m0s by 30 s`. |
| +- **K15a** any Who released: `TestDeadlineReleasesOnlyOurStaleLock` FAILED `:147 another who: block = 1, want 99`. |
| +- **K15b** a lock from before the block released: FAILED `:147 before the block: block = 1, want 99`. |
| +- **K15c** a lock from after the deadline released: FAILED `:147 after the deadline: block = 1, want 99`. |
| +- **K15d** our own lock not released: FAILED `:147 ours: block = 99, want 1`. |
| +- **K15e** the lock not parsed: FAILED `:147 before the block: block = 1, want 99`. |
| +- **K16a** the command's 99 downgraded: `TestDeadlineKeepsSafetyRefusals` FAILED `:180 ... = 1, want 99`. |
| +- **K16b** safety errors made FINDINGs: FAILED `:206 ownership: block = 1, want 99` and `malformed state`. |
| +- **K16c** a ledger that does not read made ordinary: FAILED `:221 ... = 1, want 99`. |
| +- **K16d** an ordinary failure made a stop: FAILED `:227 ... = 99, want 1`. |
| +- **K17a** every TF-START counted, not only this block's (the first form, an unused variable, was a |
| + build error and not counted): `TestDeadlineReconcilesOnlyTouchedRoots` FAILED `:247 reconciled the wrong roots`. |
| +- **K17b** `ops tf` not journalling TF-START: FAILED `:260 1 TF-START lines for network, want 2`. |
diff --git a/infra/hosted/README.md b/infra/hosted/README.md| index d84ceb26..a3e54025 100644 |
| --- a/infra/hosted/README.md |
| +++ b/infra/hosted/README.md |
| @@ -206,10 +206,17 @@ 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 |
| +`ops block ID [--teardown] --max D -- CMD` gives CMD a deadline. Past it |
| +the whole process group is stopped before anything else: TERM, up to 90 s |
| +for it to go (more than tofu's own 60 s), then KILL and up to 30 s more. |
| +The block journals `DEADLINE`; a group not proved gone, or the command's |
| +own 99, is a stop. Otherwise it reconciles the roots it touched |
| +(`TF-START` since its start), releasing with `force-unlock` only a state |
| +lock its own killed tofu left (this user@host, created inside the block's |
| +window; `FORCE-UNLOCK`), stops on any safety error, and exits 1 for the |
| +plan's retry. Worst case, a deadline adds 18 min 30 s (2 min 30 s for the |
| +group, 15 min for the reconcile, 60 s for its last tofu), and 35 min 45 s |
| +more when it ends in a stop and asks for recovery. `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. |
diff --git a/internal/hostedops/kit34r3_test.go b/internal/hostedops/kit34r3_test.go| index 2ccbca9a..76a23722 100644 |
| --- a/internal/hostedops/kit34r3_test.go |
| +++ b/internal/hostedops/kit34r3_test.go |
| @@ -42,7 +42,8 @@ func TestBlockDeadlineKillsAndReconciles(t *testing.T) { |
| {"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`) |
| + touch := `printf '2026-12-01T10:00:00.000Z\tTF-START network destroy-network\n' >> ` + filepath.Join(r.dir, JournalFile) + `; ` |
| + r.want(ExitFail, "block", "8.3", "--teardown", "--max", "500ms", "--", "sh", "-c", touch+`"$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) |
| } |
| @@ -51,7 +52,7 @@ func TestBlockDeadlineKillsAndReconciles(t *testing.T) { |
| 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") { |
| + if !r.has("DEADLINE", "block=8.3 max=500ms") { |
| t.Fatalf("no DEADLINE line:\n%s", journalText(r)) |
| } |
| if !strings.Contains(calls(t, fake), "-refresh-only") || !r.has("TF-RECONCILED", "network") { |
| @@ -88,7 +89,7 @@ func TestTofuGetsTheInheritedDeadline(t *testing.T) { |
| } |
| } |
| }) |
| - t.Setenv(DeadlineEnv, strconv.FormatInt(time.Now().Add(2*time.Second).UnixNano(), 10)) |
| + t.Setenv(DeadlineEnv, strconv.FormatInt(time.Now().Add(time.Second).UnixNano(), 10)) |
| start := time.Now() |
| r.want(ExitFail, "tf", "network", "network") |
| if d := time.Since(start); d > 30*time.Second { |
diff --git a/internal/hostedops/kit34r4_test.go b/internal/hostedops/kit34r4_test.go| new file mode 100644 |
| index 00000000..d2910648 |
| --- /dev/null |
| +++ b/internal/hostedops/kit34r4_test.go |
| @@ -0,0 +1,262 @@ |
| +//go:build unix |
| + |
| +package hostedops |
| + |
| +import ( |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// Fixes from the scoped review of the after-cap change (p34-r4.md |
| +// findings 16 to 19), rulings K14 to K17. |
| + |
| +// pidGone reports whether pid has ended: no such process, or a zombie |
| +// waiting for its reaper. |
| +func pidGone(pid int) bool { |
| + if err := syscall.Kill(pid, 0); err == syscall.ESRCH { |
| + return true |
| + } |
| + b, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) |
| + if err != nil { |
| + return true |
| + } |
| + s := string(b) |
| + i := strings.LastIndex(s, ")") |
| + return i > 0 && len(s) > i+2 && s[i+2] == 'Z' |
| +} |
| + |
| +// recordedPIDs reads the PIDs a test's command wrote, one file each, and |
| +// kills only those at cleanup (house rule: never by pattern or user). |
| +func recordedPIDs(t *testing.T, files ...string) func() []int { |
| + read := func() []int { |
| + var pids []int |
| + for _, f := range files { |
| + if b, err := os.ReadFile(f); err == nil { |
| + if pid, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil && pid > 1 { |
| + pids = append(pids, pid) |
| + } |
| + } |
| + } |
| + return pids |
| + } |
| + t.Cleanup(func() { |
| + for _, pid := range read() { |
| + _ = syscall.Kill(pid, syscall.SIGKILL) |
| + } |
| + }) |
| + return read |
| +} |
| + |
| +// stubborn is a command whose grandchild ignores TERM and outlives the |
| +// direct child, which ends on TERM. Each writes its PID. |
| +func stubborn(dir string) []string { |
| + return []string{"sh", "-c", `echo $$ > "` + dir + `/leader.pid"; (trap "" TERM; exec sleep 120) & echo $! > "` + dir + `/grand.pid"; sleep 120`} |
| +} |
| + |
| +// K14: at a block's deadline the whole group is stopped before anything |
| +// else: TERM, a wait for the group to go, KILL when a member ignores TERM, |
| +// and a wait until the group is gone. Only then the block returns (1). |
| +func TestDeadlineStopsTheGroupSynchronously(t *testing.T) { |
| + r := newRig(t) |
| + d := t.TempDir() |
| + pids := recordedPIDs(t, filepath.Join(d, "leader.pid"), filepath.Join(d, "grand.pid")) |
| + r.deps.groupGrace, r.deps.groupKillWait = 300*time.Millisecond, 5*time.Second |
| + r.want(ExitFail, "block", "8.4", "--teardown", "--max", "300ms", "--", stubborn(d)[0], stubborn(d)[1], stubborn(d)[2]) |
| + got := pids() |
| + if len(got) != 2 { |
| + t.Fatalf("the command did not record its PIDs: %v", got) |
| + } |
| + for _, pid := range got { // checked at once: the block returned only after the group was gone |
| + if !pidGone(pid) { |
| + t.Fatalf("pid %d still runs after the block returned", pid) |
| + } |
| + } |
| + if !r.has("DEADLINE", "block=8.4") || !r.has("DEADLINE", "kill=yes gone=yes") { |
| + t.Fatalf("the DEADLINE line does not say the group was killed and is gone:\n%s", journalText(r)) |
| + } |
| + if BlockKillGrace < TofuStopGrace+30*time.Second { |
| + t.Fatalf("BlockKillGrace %v does not exceed tofu's own grace %v by 30 s", BlockKillGrace, TofuStopGrace) |
| + } |
| +} |
| + |
| +// K14: a group that cannot be proved gone is a stop (99), with no |
| +// reconcile: the run cannot claim its processes stopped. |
| +func TestDeadlineGroupNotProvedGoneStops(t *testing.T) { |
| + r, fake := tfRig(t) |
| + d := t.TempDir() |
| + recordedPIDs(t, filepath.Join(d, "leader.pid"), filepath.Join(d, "grand.pid")) |
| + r.deps.groupGrace, r.deps.groupKillWait = 200*time.Millisecond, 300*time.Millisecond |
| + saved := signalGroup |
| + signalGroup = func(pgid int, sig syscall.Signal) error { |
| + if sig == 0 { |
| + return nil // every probe says a member is still there |
| + } |
| + return saved(pgid, sig) |
| + } |
| + t.Cleanup(func() { signalGroup = saved }) |
| + cmd := stubborn(d) |
| + cmd[2] = `printf '2026-12-01T10:00:00.000Z\tTF-START network network\n' >> ` + filepath.Join(r.dir, JournalFile) + `; ` + cmd[2] |
| + r.want(ExitStop, append([]string{"block", "8.4", "--teardown", "--max", "300ms", "--"}, cmd...)...) |
| + if !r.has("DEADLINE", "gone=no") || !r.has("ABORT", "not proved gone") { |
| + t.Fatalf("no record that the group was not proved gone:\n%s", journalText(r)) |
| + } |
| + if strings.Contains(calls(t, fake), "-refresh-only") { |
| + t.Fatal("a reconcile ran while the group was not proved gone") |
| + } |
| +} |
| + |
| +// lockText is OpenTofu's lock error for who, created at. |
| +func lockText(id, who string, at time.Time) string { |
| + return "Error: Error acquiring the state lock\n\nError message: operation error S3: PutObject, https response error StatusCode: 412\nLock Info:\n" + |
| + " ID: " + id + "\n Path: equipo-hosted-tfstate-149757027610/prod/network.tfstate\n Operation: OperationTypeApply\n" + |
| + " Who: " + who + "\n Version: 1.12.5\n Created: " + at.UTC().Format("2006-01-02 15:04:05.999999999 -0700 MST") + "\n Info:\n" |
| +} |
| + |
| +// K15: after the group is proved gone, a state lock this block's killed |
| +// tofu left (this user@host, created inside the block's window) is |
| +// released with force-unlock, journalled, and the reconcile goes on; any |
| +// other lock is a stop, never released. |
| +func TestDeadlineReleasesOnlyOurStaleLock(t *testing.T) { |
| + who := lockWho() |
| + for name, c := range map[string]struct { |
| + who string |
| + at func(start time.Time) time.Time |
| + exit int |
| + released bool |
| + }{ |
| + "ours": {who, func(s time.Time) time.Time { return s.Add(10 * time.Millisecond) }, ExitFail, true}, |
| + "another who": {"someone@elsewhere", func(s time.Time) time.Time { return s.Add(10 * time.Millisecond) }, ExitStop, false}, |
| + "before the block": {who, func(s time.Time) time.Time { return s.Add(-time.Hour) }, ExitStop, false}, |
| + "after the deadline": {who, func(s time.Time) time.Time { return s.Add(time.Hour) }, ExitStop, false}, |
| + } { |
| + r, fake := tfRig(t) |
| + lock := filepath.Join(fake, "lock") |
| + r.deps.Exec = func(ctx ctxT, _ []string, _ []string, _, _ wT) int { |
| + r.journal("TF-START network destroy-network") |
| + os.WriteFile(lock, []byte(lockText("lock-0abc", c.who, c.at(time.Now()))), 0o600) |
| + <-ctx.Done() |
| + return 143 |
| + } |
| + if got := r.ops("block", "8.3", "--teardown", "--max", "50ms", "--", "x"); got != c.exit { |
| + t.Errorf("%s: block = %d, want %d:\n%s", name, got, c.exit, r.out.String()) |
| + continue |
| + } |
| + unlocked := strings.Contains(calls(t, fake), "force-unlock -force lock-0abc") |
| + if unlocked != c.released || r.has("FORCE-UNLOCK", "network") != c.released { |
| + t.Errorf("%s: force-unlock ran %t, journalled %t; want %t\n%s", name, unlocked, r.has("FORCE-UNLOCK", ""), c.released, journalText(r)) |
| + } |
| + if c.released && (!r.has("FORCE-UNLOCK", "id=lock-0abc who="+who) || !r.has("TF-RECONCILED", "network")) { |
| + t.Errorf("%s: the release or the reconcile after it is not journalled:\n%s", name, journalText(r)) |
| + } |
| + } |
| +} |
| + |
| +// withServices gives a tfRig the services root too, so reconciling it |
| +// would reach tofu. |
| +func withServices(r *rig) { |
| + root := filepath.Join(r.dir, "repo", "infra", "hosted", "envs", "prod", "services") |
| + os.MkdirAll(root, 0o700) |
| + os.WriteFile(filepath.Join(root, "main.tf"), []byte("terraform {\n backend \"s3\" {}\n}\n"), 0o600) |
| +} |
| + |
| +// K16: a child's 99 stays 99 when its deadline passed too; in the |
| +// reconcile after a deadline, a safety error stops at once (99, the next |
| +// root untouched) and only ordinary tofu failures become FINDINGs. |
| +func TestDeadlineKeepsSafetyRefusals(t *testing.T) { |
| + waitThen := func(code int) func(ctxT, []string, []string, wT, wT) int { |
| + return func(ctx ctxT, _ []string, _ []string, _, _ wT) int { |
| + <-ctx.Done() |
| + return code |
| + } |
| + } |
| + r := newRig(t) |
| + r.deps.Exec = waitThen(ExitStop) |
| + r.want(ExitStop, "block", "8.3", "--teardown", "--max", "50ms", "--", "x") |
| + |
| + touch := func(r *rig, extra ...string) { |
| + r.deps.Exec = func(ctx ctxT, _ []string, _ []string, _, _ wT) int { |
| + r.journal(append([]string{"TF-START network destroy-network", "TF-START services destroy-services"}, extra...)...) |
| + <-ctx.Done() |
| + return 143 |
| + } |
| + } |
| + for name, setup := range map[string]func(r *rig, fake string){ |
| + "ownership": func(r *rig, fake string) { |
| + r.cloud.headBucket = func(string) error { return stopf("the state bucket is owned by another account") } |
| + }, |
| + "malformed state": func(r *rig, fake string) { |
| + os.WriteFile(filepath.Join(fake, "plan-network-refresh.json"), []byte("not json"), 0o600) |
| + }, |
| + "unresolved intents": func(r *rig, fake string) { |
| + r.journal("INTENT tf network/module.network.aws_vpc.vm - type=aws_vpc") |
| + r.cloud.lookup = func(LookupKey) (LookupResult, error) { return LookupResult{}, nil } |
| + }, |
| + } { |
| + r, fake := tfRig(t) |
| + withServices(r) |
| + setup(r, fake) |
| + touch(r) |
| + if got := r.ops("block", "8.3", "--teardown", "--max", "50ms", "--", "x"); got != ExitStop { |
| + t.Errorf("%s: block = %d, want 99:\n%s", name, got, r.out.String()) |
| + } |
| + if strings.Contains(calls(t, fake), "envs/prod/services") { |
| + t.Errorf("%s: the next root was reconciled after a safety error", name) |
| + } |
| + } |
| + // The ledger not reading is a stop. |
| + r, _ = tfRig(t) |
| + r.deps.Exec = func(ctx ctxT, _ []string, _ []string, _, _ wT) int { |
| + f, _ := os.OpenFile(filepath.Join(r.dir, JournalFile), os.O_APPEND|os.O_WRONLY, 0o600) |
| + f.WriteString("a line with no tab\n") |
| + f.Close() |
| + <-ctx.Done() |
| + return 143 |
| + } |
| + r.want(ExitStop, "block", "8.3", "--teardown", "--max", "50ms", "--", "x") |
| + // An ordinary tofu failure is a FINDING, the next root is still reconciled, exit 1. |
| + r, fake := tfRig(t) |
| + withServices(r) |
| + os.WriteFile(filepath.Join(fake, "fail-refresh"), nil, 0o600) |
| + touch(r) |
| + r.want(ExitFail, "block", "8.3", "--teardown", "--max", "50ms", "--", "x") |
| + if !r.has("FINDING", "tf reconcile network") || !strings.Contains(calls(t, fake), "envs/prod/services") { |
| + t.Fatalf("an ordinary reconcile failure: want a FINDING and the next root reconciled:\n%s", journalText(r)) |
| + } |
| +} |
| + |
| +// K17: the reconcile after a deadline covers only the roots this block |
| +// touched (TF-START since its BLOCK start), not every root left applying |
| +// by earlier work. |
| +func TestDeadlineReconcilesOnlyTouchedRoots(t *testing.T) { |
| + r, fake := tfRig(t, "TF-APPLY services start destroy-services", "TF-START services destroy-services") |
| + withServices(r) |
| + r.deps.Exec = func(ctx ctxT, _ []string, _ []string, _, _ wT) int { |
| + r.journal("TF-START network destroy-network") |
| + <-ctx.Done() |
| + return 143 |
| + } |
| + r.want(ExitFail, "block", "8.3", "--teardown", "--max", "50ms", "--", "x") |
| + log := calls(t, fake) |
| + if !strings.Contains(log, "envs/prod/network plan -refresh-only") || strings.Contains(log, "envs/prod/services") { |
| + t.Fatalf("reconciled the wrong roots:\n%s", log) |
| + } |
| + // ops tf and tf reconcile journal TF-START before their tofu work. |
| + r, _ = tfRig(t) |
| + r.want(0, "tf", "network", "network") |
| + r.want(0, "tf", "reconcile", "network") |
| + n := 0 |
| + for _, e := range r.ledger().Entries { |
| + if e.Verb == "TF-START" && e.Field(0) == "network" { |
| + n++ |
| + } |
| + } |
| + if n != 2 { |
| + t.Fatalf("%d TF-START lines for network, want 2:\n%s", n, journalText(r)) |
| + } |
| +} |
diff --git a/internal/hostedops/ops.go b/internal/hostedops/ops.go| index 6f0a5f84..9c346271 100644 |
| --- a/internal/hostedops/ops.go |
| +++ b/internal/hostedops/ops.go |
| @@ -146,6 +146,9 @@ type Deps struct { |
| SelfUnit func() string |
| Stdout io.Writer |
| Stderr io.Writer |
| + // groupGrace and groupKillWait replace BlockKillGrace and GroupKillWait |
| + // in tests. |
| + groupGrace, groupKillWait time.Duration |
| // noSync: tests skip the journal's fsync (it is the only reason they |
| // are slow); production always syncs. |
| noSync bool |
diff --git a/internal/hostedops/ops_test.go b/internal/hostedops/ops_test.go| index db1a8c01..06bb414f 100644 |
| --- a/internal/hostedops/ops_test.go |
| +++ b/internal/hostedops/ops_test.go |
| @@ -210,6 +210,10 @@ case " $* " in |
| *" show -json -no-color "*) cat "$FAKE_TOFU/state.json";; |
| *" output -json "*) echo '{"vm_vpc_id":{"value":"vpc-0vm"}}';; |
| esac |
| +case " $* " in |
| + *" force-unlock -force "*) rm -f "$FAKE_TOFU/lock";; |
| + *" -refresh-only "*) if [ -f "$FAKE_TOFU/lock" ]; then cat "$FAKE_TOFU/lock" >&2; exit 1; fi; [ -f "$FAKE_TOFU/fail-refresh" ] && exit 1;; |
| +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| index e5a4e7b8..a652929d 100644 |
| --- a/internal/hostedops/proc_other.go |
| +++ b/internal/hostedops/proc_other.go |
| @@ -3,12 +3,34 @@ |
| package hostedops |
| import ( |
| + "context" |
| "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 } |
| +type groupEnd struct{ stopped, killed, gone bool } |
| + |
| +// runGroup: no process groups here (the run kit runs on Linux); the |
| +// command is killed when ctx ends, and counts as gone once it is reaped. |
| +func runGroup(ctx context.Context, cmd *exec.Cmd, grace, killWait time.Duration) (groupEnd, error) { |
| + if err := cmd.Start(); err != nil { |
| + return groupEnd{gone: true}, err |
| + } |
| + done := make(chan error, 1) |
| + go func() { done <- cmd.Wait() }() |
| + select { |
| + case err := <-done: |
| + return groupEnd{gone: true}, err |
| + case <-ctx.Done(): |
| + } |
| + _ = cmd.Process.Kill() |
| + select { |
| + case err := <-done: |
| + return groupEnd{stopped: true, killed: true, gone: true}, err |
| + case <-time.After(killWait): |
| + return groupEnd{stopped: true, killed: true}, nil |
| + } |
| +} |
| // 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| index 555dbd0d..a251307d 100644 |
| --- a/internal/hostedops/proc_unix.go |
| +++ b/internal/hostedops/proc_unix.go |
| @@ -3,24 +3,68 @@ |
| package hostedops |
| import ( |
| + "context" |
| "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) { |
| +// signalGroup signals a process group; tests replace it. |
| +var signalGroup = func(pgid int, sig syscall.Signal) error { return syscall.Kill(-pgid, sig) } |
| + |
| +// groupEnd is how a command's process group ended. |
| +type groupEnd struct { |
| + stopped bool // its context ended first: the group was told to stop |
| + killed bool // a member outlived TERM by grace: the group got KILL |
| + gone bool // the group was proved gone (or never needed stopping) |
| +} |
| + |
| +// runGroup runs cmd as the leader of its own process group (K14, |
| +// p34-r4 finding 16). If it ends first, that is its result. If ctx ends |
| +// first, the group is stopped synchronously: TERM, then a wait (probing |
| +// the group every 100 ms) of up to grace for it to go; then KILL and a |
| +// wait of up to killWait. gone says whether it was proved gone; nothing |
| +// is left scheduled. Descendants that left the group (setsid) are not |
| +// covered. |
| +func runGroup(ctx context.Context, cmd *exec.Cmd, grace, killWait time.Duration) (groupEnd, error) { |
| 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 |
| + if err := cmd.Start(); err != nil { |
| + return groupEnd{gone: true}, err |
| + } |
| + pgid := cmd.Process.Pid |
| + done := make(chan error, 1) |
| + go func() { done <- cmd.Wait() }() // reaps the leader, so a dead leader is not counted alive |
| + select { |
| + case err := <-done: |
| + return groupEnd{gone: true}, err |
| + case <-ctx.Done(): |
| + } |
| + end := groupEnd{stopped: true} |
| + waitGone := func(d time.Duration) bool { |
| + until := time.Now().Add(d) |
| + for { |
| + if err := signalGroup(pgid, 0); err == syscall.ESRCH { |
| + return true |
| + } |
| + if time.Now().After(until) { |
| + return false |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + } |
| + _ = signalGroup(pgid, syscall.SIGTERM) |
| + if end.gone = waitGone(grace); !end.gone { |
| + end.killed = true |
| + _ = signalGroup(pgid, syscall.SIGKILL) |
| + end.gone = waitGone(killWait) |
| + } |
| + var err error |
| + select { |
| + case err = <-done: |
| + case <-time.After(killWait): // pipes still held: the group is not gone |
| + end.gone = false |
| } |
| - cmd.WaitDelay = grace + 5*time.Second |
| + return end, err |
| } |
| // termCmd stops cmd with TERM when its context ends (tofu then stops |
diff --git a/internal/hostedops/stop.go b/internal/hostedops/stop.go| index f85f7805..1253fc33 100644 |
| --- a/internal/hostedops/stop.go |
| +++ b/internal/hostedops/stop.go |
| @@ -106,15 +106,20 @@ func cmdBlock(o *Ops, args []string) error { |
| } |
| } |
| ctx, cancel := o.ctx, context.CancelFunc(func() {}) |
| + began := time.Now() |
| if *maxD > 0 { |
| ctx, cancel = context.WithTimeout(o.ctx, *maxD) |
| } |
| - code := o.execBlock(ctx, argv, id, *teardown) |
| + code, end := 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) |
| + err := o.blockDeadline(id, *maxD, code, end, began) |
| + if IsStop(err) { |
| + return hard(err.Error()) |
| + } |
| + return err |
| } |
| switch { |
| case code == 0: |
| @@ -127,7 +132,7 @@ func cmdBlock(o *Ops, args []string) error { |
| return &exitError{code: code, msg: "block " + id + " exited " + itoa(code)} |
| } |
| -func (o *Ops) execBlock(ctx context.Context, argv []string, id string, teardown bool) int { |
| +func (o *Ops) execBlock(ctx context.Context, argv []string, id string, teardown bool) (int, groupEnd) { |
| env := append(os.Environ(), "EQUIPO_HOSTED_OPS_BLOCK="+id) |
| if teardown { |
| env = append(env, TeardownEnv+"="+id) |
| @@ -135,59 +140,149 @@ func (o *Ops) execBlock(ctx context.Context, argv []string, id string, teardown |
| if d, ok := ctx.Deadline(); ok { |
| env = append(env, DeadlineEnv+"="+strconv.FormatInt(d.UnixNano(), 10)) |
| } |
| - if o.Exec != nil { |
| - return o.Exec(ctx, argv, env, o.Stdout, o.Stderr) |
| + if o.Exec != nil { // a test's command: no process group to stop |
| + return o.Exec(ctx, argv, env, o.Stdout, o.Stderr), groupEnd{stopped: ctx.Err() != nil, gone: true} |
| + } |
| + grace, killWait := BlockKillGrace, GroupKillWait |
| + if o.groupGrace > 0 { |
| + grace = o.groupGrace |
| + } |
| + if o.groupKillWait > 0 { |
| + killWait = o.groupKillWait |
| } |
| - return runChild(ctx, argv, env, o.Stdout, o.Stderr) |
| + return runChild(ctx, argv, env, o.Stdout, o.Stderr, grace, killWait) |
| } |
| -// Block deadlines (K12, p34-r3 finding 1). |
| +// Block deadlines (K12, p34-r3 finding 1; K14 to K17, p34-r4). |
| const ( |
| MaxBlock = 24 * time.Hour // --max's ceiling |
| - BlockKillGrace = 30 * time.Second // TERM to KILL for a block's process group |
| + BlockKillGrace = 90 * time.Second // TERM to KILL for a block's process group: above tofu's own grace |
| + GroupKillWait = 30 * time.Second // after KILL, the longest wait for the group to be gone |
| 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) |
| +// blockDeadline is a block past its --max. runChild has already stopped |
| +// its process group, synchronously (K14). In order: |
| +// - DEADLINE is journalled with how the group ended; |
| +// - the command's own 99 stays 99 (K16); |
| +// - a group not proved gone is a stop: the run cannot claim its |
| +// processes stopped, and nothing is reconciled (K14); |
| +// - each root this block touched (a TF-START line since its BLOCK |
| +// start; K17) is reconciled under a fresh context, so what state holds |
| +// is recorded. A state lock the killed tofu left is released only when |
| +// it is provably this block's (K15). A safety error stops at once (99, |
| +// no further root); an ordinary tofu failure is a FINDING (K16); |
| +// - exit 1: the plan may retry within its budget. |
| +// |
| +// A stop error returned here goes through the block's hard path. |
| +func (o *Ops) blockDeadline(id string, maxD time.Duration, code int, end groupEnd, began time.Time) error { |
| + deadline := began.Add(maxD) |
| + _ = o.jw("DEADLINE", "block=%s max=%s exit=%d term=%s kill=%s gone=%s", id, maxD, code, yesNo(end.stopped), yesNo(end.killed), yesNo(end.gone)) |
| + o.out("block %s passed its %s deadline", id, maxD) |
| + if code == ExitStop { |
| + return stopf("exit 99 (its %s deadline passed too)", maxD) |
| + } |
| + if !end.gone { |
| + return stopf("past its %s deadline its process group was not proved gone; nothing reconciled", 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) |
| + l, err := o.ledger() |
| + if err != nil { |
| + return stopf("after its deadline the ledger does not read: %v", err) |
| + } |
| + for _, root := range touchedRoots(l, id) { |
| + err := o.reconcileAfterKill(root, began, deadline) |
| + switch { |
| + case err == nil: |
| + case IsStop(err): |
| + return stopf("after its deadline, tf reconcile %s: %v", root, err) |
| + default: |
| + if ferr := o.finding("block %s: after its deadline, tf reconcile %s: %v", id, root, err); ferr != nil { |
| + return ferr |
| } |
| } |
| } |
| - 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) |
| + return failf("block %s passed its %s deadline: its process group was stopped and proved gone, and the roots it touched reconciled; a retry is the plan's", id, maxD) |
| +} |
| + |
| +func yesNo(b bool) string { |
| + if b { |
| + return "yes" |
| + } |
| + return "no" |
| +} |
| + |
| +// touchedRoots are the roots with a TF-START line since block id's last |
| +// BLOCK start line, in roots order (K17). |
| +func touchedRoots(l *Ledger, id string) []string { |
| + start := 0 |
| + for _, e := range l.Entries { |
| + if e.Verb == "BLOCK" && e.Field(0) == id && e.Field(1) == "start" { |
| + start = e.Line |
| + } |
| + } |
| + seen := map[string]bool{} |
| + for _, e := range l.Entries { |
| + if e.Line > start && e.Verb == "TF-START" { |
| + seen[e.Field(0)] = true |
| + } |
| + } |
| + var out []string |
| + for _, r := range roots { |
| + if seen[r] { |
| + out = append(out, r) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// reconcileAfterKill is tf reconcile ROOT after a block's group was |
| +// proved gone. A state lock (K15, p34-r4 finding 17) is released with |
| +// force-unlock only when this block's killed tofu provably left it: Who is |
| +// this user@host and Created lies between the block's start and its |
| +// deadline. Then the reconcile runs once more. Any other lock, or a lock |
| +// still there, is a stop: locking is never bypassed. |
| +func (o *Ops) reconcileAfterKill(root string, began, deadline time.Time) error { |
| + err := o.tfReconcile(root) |
| + var le *LockError |
| + if !errors.As(err, &le) { |
| + return err |
| + } |
| + in := le.Info |
| + if in.Who != lockWho() || !in.Created.After(began) || !in.Created.Before(deadline) { |
| + _ = o.jw("ABORT", "state lock on %s not released: id=%s who=%s operation=%s created=%s (this block: %s, %s to %s)", root, in.ID, in.Who, in.Operation, |
| + in.Created.UTC().Format(time.RFC3339Nano), lockWho(), began.UTC().Format(time.RFC3339Nano), deadline.UTC().Format(time.RFC3339Nano)) |
| + return stopf("the state of %s is locked by %s since %s, not provably by this block's killed tofu; not released", root, in.Who, in.Created.UTC().Format(time.RFC3339)) |
| + } |
| + if _, err := o.tofu("-chdir="+o.rootDir(root), "force-unlock", "-force", in.ID); err != nil { |
| + return stopf("force-unlock of %s (%s) failed: %v", root, in.ID, err) |
| + } |
| + if err := o.jw("FORCE-UNLOCK", "%s id=%s who=%s operation=%s created=%s", root, in.ID, in.Who, in.Operation, in.Created.UTC().Format(time.RFC3339Nano)); err != nil { |
| + return err |
| + } |
| + err = o.tfReconcile(root) |
| + if errors.As(err, &le) { |
| + return stopf("the state of %s is still locked after force-unlock: %v", root, err) |
| + } |
| + return err |
| } |
| -func runChild(ctx context.Context, argv, env []string, stdout, stderr io.Writer) int { |
| - cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) |
| - groupCmd(cmd, BlockKillGrace) |
| +func runChild(ctx context.Context, argv, env []string, stdout, stderr io.Writer, grace, killWait time.Duration) (int, groupEnd) { |
| + cmd := exec.Command(argv[0], argv[1:]...) |
| cmd.Env, cmd.Stdout, cmd.Stderr, cmd.Stdin = env, stdout, stderr, nil |
| - err := cmd.Run() |
| + end, err := runGroup(ctx, cmd, grace, killWait) |
| var x *exec.ExitError |
| switch { |
| case err == nil: |
| - return 0 |
| + return 0, end |
| case errors.As(err, &x) && x.ExitCode() >= 0: |
| - return x.ExitCode() |
| + return x.ExitCode(), end |
| } |
| - return ExitFail |
| + return ExitFail, end |
| } |
| // SafeStopBound bounds one safe stop, whatever the invocation's context. |
diff --git a/internal/hostedops/tf.go b/internal/hostedops/tf.go| index 869b24d1..74086b30 100644 |
| --- a/internal/hostedops/tf.go |
| +++ b/internal/hostedops/tf.go |
| @@ -7,13 +7,16 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| + "io" |
| "os" |
| "os/exec" |
| + "os/user" |
| "path/filepath" |
| "regexp" |
| "slices" |
| "sort" |
| "strings" |
| + "time" |
| ) |
| // ops tf ROOT PHASE (account plan, "Rules for every block"): the state |
| @@ -124,10 +127,10 @@ 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 |
| + var out, errOut bytes.Buffer |
| + cmd.Stdout, cmd.Stderr = &out, io.MultiWriter(o.Stderr, &errOut) |
| if err := cmd.Run(); err != nil { |
| - return out.Bytes(), fmt.Errorf("tofu %s: %w", args[1], err) |
| + return out.Bytes(), &tofuError{err: fmt.Errorf("tofu %s: %w", args[1], err), stderr: errOut.String()} |
| } |
| return out.Bytes(), nil |
| } |
| @@ -260,6 +263,11 @@ func cmdTf(o *Ops, args []string) error { |
| if err := o.tofuInit(root, dir); err != nil { |
| return err |
| } |
| + // TF-START: this root's tofu work begins (a lock may be taken); a |
| + // block's deadline reconciles the roots it touched (K17). |
| + if err := o.jw("TF-START", "%s %s", root, phase); err != nil { |
| + return err |
| + } |
| if err := o.adoptPending(root, dir, vars); err != nil { |
| return err |
| } |
| @@ -522,7 +530,16 @@ func (o *Ops) tfReconcile(root string) error { |
| if err := os.MkdirAll(o.path("tf"), 0o700); err != nil { |
| return failf("%v", err) |
| } |
| + if err := o.jw("TF-START", "%s reconcile", root); err != nil { |
| + return err |
| + } |
| if _, err := o.tofu("-chdir="+dir, "plan", "-refresh-only", "-input=false", "-no-color", "-out="+planFile, "-var-file="+vars, "-var=run="+o.Run); err != nil { |
| + var te *tofuError |
| + if errors.As(err, &te) { |
| + if in, ok := parseLock(te.stderr); ok { |
| + return &LockError{Root: root, Info: in, Err: err} |
| + } |
| + } |
| return failf("%v", err) |
| } |
| js, err := o.tofu("-chdir="+dir, "show", "-json", "-no-color", planFile) |
| @@ -1081,3 +1098,73 @@ func (o *Ops) adoptPending(root, dir, vars string) error { |
| // verified VPC deletion proves it gone. A gateway, an Elastic IP or an |
| // instance can outlive or leave a VPC, and is not here (after-cap fix 2). |
| var containedTypes = []string{"aws_subnet", "aws_route_table", "aws_security_group", "aws_network_acl"} |
| + |
| +// LockInfo is OpenTofu's description of a state lock. |
| +type LockInfo struct { |
| + ID, Who, Operation string |
| + Created time.Time |
| +} |
| + |
| +// LockError is a tofu call that failed on a state lock. It is an ordinary |
| +// failure (1) wherever nothing handles it; after a block's deadline, |
| +// reconcileAfterKill decides (K15). |
| +type LockError struct { |
| + Root string |
| + Info LockInfo |
| + Err error |
| +} |
| + |
| +func (e *LockError) Error() string { |
| + return fmt.Sprintf("the state of %s is locked: ID %s, Who %s, Operation %s, Created %s (%v)", e.Root, e.Info.ID, e.Info.Who, |
| + e.Info.Operation, e.Info.Created.UTC().Format(time.RFC3339Nano), e.Err) |
| +} |
| + |
| +var lockField = regexp.MustCompile(`(?m)^\s*(ID|Who|Operation|Created):\s*(.*?)\s*$`) |
| + |
| +// parseLock reads the Lock Info block of tofu's "Error acquiring the |
| +// state lock"; ok only with an ID, a Who and a Created that parses. |
| +func parseLock(stderr string) (LockInfo, bool) { |
| + if !strings.Contains(stderr, "Error acquiring the state lock") { |
| + return LockInfo{}, false |
| + } |
| + var in LockInfo |
| + var created string |
| + for _, m := range lockField.FindAllStringSubmatch(stderr, -1) { |
| + switch m[1] { |
| + case "ID": |
| + in.ID = m[2] |
| + case "Who": |
| + in.Who = m[2] |
| + case "Operation": |
| + in.Operation = m[2] |
| + case "Created": |
| + created = m[2] |
| + } |
| + } |
| + t, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", created) |
| + if err != nil || in.ID == "" || in.Who == "" || strings.ContainsAny(in.ID, " \t") { |
| + return LockInfo{}, false |
| + } |
| + in.Created = t |
| + return in, true |
| +} |
| + |
| +// lockWho is the Who OpenTofu writes into a lock this process's tofu |
| +// takes: the user's name, "@", the host name (its statemgr.NewLockInfo). |
| +func lockWho() string { |
| + name := "" |
| + if u, err := user.Current(); err == nil { |
| + name = u.Username |
| + } |
| + host, _ := os.Hostname() |
| + return name + "@" + host |
| +} |
| + |
| +// tofuError is a failed tofu call, with what it wrote to stderr. |
| +type tofuError struct { |
| + err error |
| + stderr string |
| +} |
| + |
| +func (e *tofuError) Error() string { return e.err.Error() } |
| +func (e *tofuError) Unwrap() error { return e.err } |