oficina / equipo Public

hostedops: Task 33 review 2, Astra N1 to N6

Fix round 2 of the run kit (t33-r2.md, rulings in task-33-fix2.md), red
first. N1: one recovery unit runs section S for every requester (a
failed block, an expired watchdog, an operator), under an exclusive lock,
with a stop timeout above its 30-minute bound; membership is read from
/proc/self/cgroup with INVOCATION_ID. N2: a tag-filtered miss is never
proof; absence only from a verified-deleted parent or an unfiltered
listing under the recorded parent holding only accounted IDs. N3: a
second fence invalidates every earlier settlement. N4: IAM action
matching (case-insensitive, wildcards; odd forms fail closed). N5: a
launch is bound to its image when its intent is replayed. N6: adoption
through a run-local import block and a plan plan-check --adopt checks,
rebuilt from durable records, state read before any retry. Extras: plan
and Task 34 invocations through the real parsers, Network pagination,
SDK shapes over two pages, F4's covered-parent mutation. Account plan rev
4.2. Mutations S1 to S26 are in the progress file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 80801ccb74436c265fd1da9eeba5de757e9e470a parent 187ded6
25 files changed, +1,416 −275
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md +12 −7
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +84 −0
  • infra/hosted/README.md +3 −1
  • infra/hosted/scripts/plan-check.py +48 −4
  • infra/hosted/scripts/plan_check_test.py +46 −2
  • internal/hostedops/cloud.go +4 −0
  • internal/hostedops/fake_test.go +50 −8
  • internal/hostedops/fix1_test.go +93 −71
  • internal/hostedops/fix2_test.go +296 −0
  • internal/hostedops/ledger.go +10 −11
  • internal/hostedops/ledger_test.go +0 −27
  • internal/hostedops/ledgercmd.go +5 −5
  • internal/hostedops/lock_other.go +10 −0
  • internal/hostedops/lock_unix.go +26 −0
  • internal/hostedops/ops.go +5 −2
  • internal/hostedops/ops_test.go +4 −2
  • internal/hostedops/singleton.go +36 −4
  • internal/hostedops/stop.go +73 −4
  • internal/hostedops/tf.go +177 −36
  • internal/hostedops/units.go +47 −14
  • internal/isolatedjob/awsjob/opsaws/cloud.go +30 −16
  • internal/isolatedjob/awsjob/opsaws/fix1_test.go +5 −3
  • internal/isolatedjob/awsjob/opsaws/fix2_test.go +279 −0
  • internal/isolatedjob/awsjob/opsaws/lookup.go +72 −57

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 1.8s
ci-box: codex: fetched and verified in 3.5s
ci-box: codex-code-mode-host: fetched and verified in 1.4s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.3s
ci-box: tofu: fetched and verified in 1.6s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 9.8s
ci-box: pi: installed and verified in 7.5s
ci-box: opencode: installed and verified in 2.4s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 8.9s
ci-box: clone deepened in 5.8s
ci-box: file times set from content: 4034 files, 302 directories
ci-box: ready in 19.6s
=== 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 90ms
FAIL	amadan.net/oficina/equipo/internal/equipotest	0.239s
FAIL
make: *** [Makefile:322: 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 b71cf956..39298f2f 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 plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. Task 5 review round 1: the reload fetches through an injected Deps.Fetcher first (ctlops.FetchAndReload; the S3 fetcher is in the command), the status reads the audit under one lock, and operator_test.go gains a fake config bucket and the fetch, failure and snapshot tests; measured 5954/9907. Slice 2 Task 13 wires certification reports (logic in ctlcert/report.go and hostedcert): the cert-report proxy route, its transaction and the controller's own stop of the reported VM (proxy.go), the operator evidence route, the proxy header check and two error codes (http.go), the Handler's signing key kept for evidence (controller.go), the stop reason, and schema version 5; measured 6022/9907. Task 13 review round 1: the report's stop is recorded in the transaction that keeps its evidence (recordStop, split out of requestStop so both share it) and driven on a context the request's end does not cancel; measured 6037/9907. Round 2: the stop rule moves to schema version 6 (the migration list line wraps) with TestUpgradeFromVersion5 upgrading a database made at bec02feb; measured 6038/9990. Round 3: the upgrade test also starts from a116d330's version 5; measured 6038/9996. Task 21 ruling: Get and Admission answer a signed 404 absent for an attempt with no record at all (ErrAbsent), keeping the 403 for another key's attempt, and the tests that pin it; measured 6049/10016. Task 22 review 2: Admission answers the job's current deadline (DeadlineInMS, counted from the answer) so the instance caps hosted credentials by a deadline moved earlier after launch, and its assertion; measured 6050/10017. Task 29: healthz.go, the metrics listener's GET /healthz (Controller.Healthz, a store read; the command mounts it beside /metrics and the API has no such route); wiring only, the CloudWatch publisher and Litestream lag live in the command; measured 6079/10017.
-size internal/hostedops 6258 - Hosted slice 2 Task 33: equipo-hosted-ops, the dev drill's and production bring-up's run kit; every subcommand the account plan uses (ledger, guard, estimate, VM settlement, connector, buckets, singletons, units, block and safe stop, tf and its reconcile, tfvars, named assertions, report and bundle) shares one journal and one Ops, so it is one package; measured 5499. Task 33 fix round 1 (Astra t33-r1 F1 to F18): the wait-human watchdog unit, unit wait into safe-stop, safe-stop's own context and unit, creation identity on intents, verify-gone's declared parents, fence by identity, MFA policy evaluation, connector identity, the release AMI, litestream-install, import-block adoption, decoded trail records, usage errors and the unit probe; 6258.
+size internal/hostedops 6575 - Hosted slice 2 Task 33: equipo-hosted-ops, the dev drill's and production bring-up's run kit; every subcommand the account plan uses (ledger, guard, estimate, VM settlement, connector, buckets, singletons, units, block and safe stop, tf and its reconcile, tfvars, named assertions, report and bundle) shares one journal and one Ops, so it is one package; measured 5499. Task 33 fix round 1 (Astra t33-r1 F1 to F18): the wait-human watchdog unit, unit wait into safe-stop, safe-stop's own context and unit, creation identity on intents, verify-gone's declared parents, fence by identity, MFA policy evaluation, connector identity, the release AMI, litestream-install, import-block adoption, decoded trail records, usage errors and the unit probe; 6258. Fix round 2 (t33-r2 N1 to N6): the one recovery unit and its lock, cgroup membership, identity lookups that prove absence only under the recorded parent, settlement after a second fence, IAM action matching, launches bound at their intent, and adoption through a checked import plan rebuilt from durable records; 6575.
diff --git a/docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md b/docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md
index c6d2068e..fd92141d 100644
--- a/docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md
+++ b/docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md
@@ -1,6 +1,7 @@
# Hosted runners: production account bring-up (149757027610, `equipo-hosted`)
-**Revision:** 4.1 (2026-12-01): slice 2 Task 33 fix round 1 brought the `ops` steps into line with
+**Revision:** 4.2 (2026-12-01): Task 33 fix round 2: one recovery unit for section S, and
+adoption through a checked import plan. Revision 4.1 (2026-12-01): slice 2 Task 33 fix round 1 brought the `ops` steps into line with
the tool (0.2's unit probe, the AMI from the release, 3.5's certification key ID, 4.1's Litestream
install, 7.1's instance notes, the wait-human watchdog, unit wait and safe-stop rules). Revision 4 (2026-11-30). Astra round 3 (`acct-r3.md`, the last) found two blocking items, both fixed
here (rollback ordering; hand-over failure fences launches); its non-blocking items are carried into slice 2
@@ -143,14 +144,18 @@ Sections R (rollback), T (full teardown) and S (safe stop) run only when called.
the unit ends or its bound passes; a failure or an expired bound runs `ops safe-stop` and exits 99.
`ops wait-human <name> --max <bound> --background` starts a journalled watchdog unit
(`hprod-<RUN>-wait-<name>`) that runs `ops safe-stop` at the deadline with no further command;
- `ops wait-human <name> --done`, run when Paul confirms, records it and stops the watchdog. `ops
- safe-stop` runs under its own 30-minute bound, whatever interrupted its caller, and never stops the
- unit it runs in.
+ `ops wait-human <name> --done`, run when Paul confirms, records it and stops the watchdog. Section S
+ has one owner: every request for it (`ops safe-stop`, a failed block, an expired watchdog) starts the
+ one recovery unit `hprod-<RUN>-recovery` unless it is already running, and waits for it. That unit
+ holds an exclusive lock for its whole run (a second one stands aside), stops every other journalled
+ unit, runs under its own 30-minute bound, and has a stop timeout above it.
- **Ledger.** Every create, in OpenTofu or not, has a durable intent before it. `ops tf` journals an
intent for each planned create address before `apply`; after a failed or interrupted apply,
- `ops tf reconcile ROOT` runs `tofu plan -refresh-only` and lists this run's tagged resources through
- the tagging API, and records each as in state, imported, or created outside state (deleted by `ops`,
- or adopted only with Paul's word). `img publish` and `cert launch` take `-ledger "$P"` and journal
+ `ops tf reconcile ROOT` runs `tofu plan -refresh-only`, looks up each intent not in state by its creation identity (the tag index
+ is only a cross-check), and records each as in state, never created, or created outside state. A
+ resource created outside state is adopted: a run-local import block, and at the next `ops tf` a plan
+ targeting it that `plan-check.py --adopt` checks (imports of exactly those IDs, no change), then the
+ normal destroy removes it. `img publish` and `cert launch` take `-ledger "$P"` and journal
their client token or attempt ID before the create call. Other `ops` subcommands that create things
journal intent and record themselves. Every VM ID seen anywhere (provider scan, controller
`GET /v1/vms`, logs) is recorded with its source, and its charge is kept after it leaves the
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index afc81047..756089c6 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -2983,3 +2983,87 @@ Mutation checks (each applied alone, `CGO_ENABLED=0 go test ./<pkg> -run '^<Test
- R34 X1 a malformed invocation an ordinary failure. `TestPlanInvocationsParseFlags`: exit 1 | fix1_test.go:599: a malformed invocation is not a usage error: vms settle --image ARN [--terminate] --max D | restored
- R35 X2 no retry within --max. `TestVMsScanMax`: exit 1 | fix1_test.go:557: ops vms scan --image arn:aws:lambda:eu-west-1:149757027610:microvm-image:equipo-hosted-prod-r1 --max 1m = 99, want 0: | restored
- R36 X4 the probe accepts a credential. `TestUnitProbe`: exit 1 | fix1_test.go:574: ops unit probe = 0, want 99: | restored
+
+### Task 33 fix round 2
+
+Findings: `t33-r2.md` (Astra round 2, changes requested); rulings: `task-33-fix2.md`. The base is `187ded68`.
+
+This round was red-first. The only changes made before the red run were a compile skeleton:
+- `Deps.SelfUnit`;
+- `LookupKey.Accounted`;
+- a stop-timeout parameter on `Systemd.Start`;
+- a `unitFromCgroup` stub;
+- plan-check's `check(..., adopt=None)`, so its new tests fail on assertions and not on a TypeError.
+
+RED (Go: `CGO_ENABLED=0 go test ./internal/hostedops ./internal/isolatedjob/awsjob/opsaws -count=1 -run '<the new tests>'`):
+- TestOneRecoveryOwner: fix2_test.go:44: the recovery unit was started 0 times, want once: [hprod-r1-wait-sns-confirmed.service]
+- TestRecoveryStartsAfterCancellation: fix2_test.go:84: a cancelled requester started no recovery unit: []
+- TestSelfUnitFromCgroup: fix2_test.go:92: unit ""
+- TestParentDeletionResolves: fix2_test.go:116: a child of a verified-deleted VPC was not resolved absent
+- TestSecondFenceSettlesAgain: fix2_test.go:150: no scan and termination after the second fence: [StopInstance i-0late InstanceState i-0late]
+- TestMFAActionSemantics: fix2_test.go:176: ops mfa-check = 0, want 99:
+- TestLaunchBoundAtIntent: fix2_test.go:188: settling the digest's new image resolved a launch of its old one
+- TestAdoptionThroughCheckedPlan: fix2_test.go:259: the adoption was not journalled before the intent was resolved
+- TestAdoptionAfterCrashBeforeAdopt: fix2_test.go:268: the adoption did not go plan, plan-check --adopt, apply, then destroy:
+- TestAdoptionAfterCrashBeforeImported: fix2_test.go:278: a standalone tofu import ran:
+- TestLookupMatchesIdentity: fix1_test.go:109: lookup after a partial creation = {IDs:[] Definitive:true}, <nil>; want a miss that is not definitive
+- TestUntaggedSurvivorStaysUnresolved: fix2_test.go:54: an untagged survivor under the parent read as {IDs:[] Definitive:true}, <nil>; want not definitive
+- TestSDKShapesAndPages: fix2_test.go:154: network over two pages: {DNSSupport:false DNSHostnames:false VMRoutes:[] ServicesRoutes:[] VMSGRules:[] PeeringState:}, DescribeRouteTables: 0 tables, want one
+
+RED (plan-check: `python3 -I infra/hosted/scripts/plan_check_test.py`, the new `Adopt` class):
+- FAIL: test_adopt_in_a_destroy_phase_refused (__main__.Adopt.test_adopt_in_a_destroy_phase_refused)
+- FAIL: test_import_of_another_id_refused (__main__.Adopt.test_import_of_another_id_refused)
+- FAIL: test_matching_import_accepted (__main__.Adopt.test_matching_import_accepted)
+- FAIL: test_missing_import_refused (__main__.Adopt.test_missing_import_refused)
+
+Not red-first, and recorded as such:
+- Four `Adopt` tests passed on the old code, because it refused those plans for other reasons (only `create` was allowed): `test_import_that_changes_the_resource_refused`, `test_anything_beside_the_imports_refused`, `test_unlisted_address_refused` and `test_import_without_adopt_refused`. The mutations below show the first now holds by the adopt checks themselves.
+- `TestVerifyGoneCoveredParentStillThere` covers F4's covered-parent path, which already behaved; it exists for that path's missing mutation (S24).
+- `TestPlanInvocationsParse` was rewritten to the extra's ruling and replaces the old name-only test. Its first run failed on its own bug (it read the account plan after `t.Chdir`), and its second on a classification gap (`ops tf reconcile` named in prose). No tool defect was found: every invocation parses.
+- `TestSDKShapesAndPages` is coverage. Its Network part was red (route tables and security-group rules were not paginated), and that red is listed above.
+
+Round-1 tests changed to the rulings:
+- `TestSafeStopSparesItsOwnUnit` now follows N1: the recovery unit stops every other unit.
+- `TestLookupMatchesIdentity`'s partial-creation case follows N2: a filtered miss is not definitive.
+- `TestAdoptedResourceTornDown` is removed; N6's three adoption tests replace it.
+
+A real bug surfaced while turning N6 green: an adoption in a fresh run directory had no `tf/` directory yet. It is fixed.
+
+GREEN:
+- `CGO_ENABLED=0 go test ./internal/hostedops/... ./internal/isolatedjob/... ./cmd/equipo-hosted-ops ./internal/hostedclient -count=1`: all ok.
+- `make build vet govulncheck budget lanes-check fmt-check hosted-infra-check` ok; the budget record is now `size internal/hostedops 6575`, with its reason.
+- `python3 -I infra/hosted/scripts/plan_check_test.py`: 109 tests ok.
+- staticcheck v0.7.0 is clean; the darwin and windows builds succeed (the lock is `//go:build unix`, with a stub otherwise); `git diff --check` is clean.
+
+Mutation checks (each applied alone, restored byte for byte and checked):
+- S1 survived, because a second guard holds the property: `startUnit` refuses a journalled unit that is still running. S1b turns both guards off and fails.
+- The first tries of S3 (a nil release, an artefact of the mutation), S5 and S24 (did not compile) were rewritten; the results below are the rewritten ones.
+- One run of S1b was invalid, because the script truncated `stop.go` before reading it. The file was restored, and the result below is the re-run.
+
+- S1 N1 a second recovery unit started. `TestOneRecoveryOwner`: exit 0 | ok amadan.net/oficina/equipo/internal/hostedops 0.069s | restored
+- S1b N1 a second recovery unit started, startUnit's guard off too. `TestOneRecoveryOwner`: exit 1 | fix2_test.go:44: the recovery unit was started 2 times, want once: [hprod-r1-wait-sns-confirmed.service hprod-r1-recovery.service hprod-r1-recovery.service] | restored
+- S2 N1 a requester runs recovery itself. `TestOneRecoveryOwner`: exit 1 | fix2_test.go:44: the recovery unit was started 0 times, want once: [hprod-r1-wait-sns-confirmed.service] | restored
+- S3 N1 no recovery lock. `TestOneRecoveryOwner`: exit 1 | fix2_test.go:71: a second recovery exited 0, journalled false, made 11 calls | restored
+- S4 N1 the recovery unit's stop timeout at 45 s. `TestOneRecoveryOwner`: exit 1 | fix2_test.go:50: the recovery unit's stop timeout 45s is not above the 30m0s bound | restored
+- S5 N1 recovery stops its own unit. `TestOneRecoveryOwner`: exit 1 | fix2_test.go:57: recovery did not stop the others, spare itself and settle: stopped [hprod-r1-6.2.service hprod-r1-wait-sns-confirmed.service hprod-r1-recovery.service] | restored
+- S6 N1 a cancelled requester gives up. `TestRecoveryStartsAfterCancellation`: exit 1 | fix2_test.go:84: a cancelled requester started no recovery unit: [] | restored
+- S7 N1 membership without INVOCATION_ID. `TestSelfUnitFromCgroup`: exit 1 | fix2_test.go:95: without INVOCATION_ID: "hprod-r1-6.2.service" | restored
+- S8 N2 no parent taken as proof. `TestUntaggedSurvivorStaysUnresolved`: exit 1 | fix2_test.go:65: a miss with no recorded parent was definitive | restored
+- S9 N2 an unaccounted survivor ignored. `TestUntaggedSurvivorStaysUnresolved`: exit 1 | fix2_test.go:54: an untagged survivor under the parent read as {IDs:[] Definitive:true}, <nil>; want not definitive | restored
+- S10 N2 a deleted parent not consulted. `TestParentDeletionResolves`: exit 1 | fix2_test.go:116: a child of a verified-deleted VPC was not resolved absent | restored
+- S11 N2 no accounted IDs passed. `TestParentDeletionResolves`: exit 1 | fix2_test.go:119: lookups [{Type:aws_subnet ID: Name: Run:r1 NameTag:equipo-hosted-services-b Parent:vpc-0svc Token:- Accounted:[]}]; want one, carrying the recorded subnet IDs | restored
+- S12 N3 earlier proofs kept. `TestSecondFenceSettlesAgain`: exit 1 | fix2_test.go:150: no scan and termination after the second fence: [StopInstance i-0late InstanceState i-0late] | restored
+- S13 N4 case-sensitive actions. `TestMFAActionSemantics`: exit 1 | fix2_test.go:176: ops mfa-check = 99, want 0: | restored
+- S14 N4 no wildcard. `TestMFAActionSemantics`: exit 1 | fix2_test.go:176: ops mfa-check = 0, want 99: | restored
+- S15 N4 an odd Effect skipped. `TestMFAActionSemantics`: exit 1 | fix2_test.go:176: ops mfa-check = 0, want 99: | restored
+- S16 N5 the image read from the current mapping. `TestLaunchBoundAtIntent`: exit 1 | fix2_test.go:188: settling the digest's new image resolved a launch of its old one | restored
+- S17 N6 ADOPT after the record. `TestAdoptionThroughCheckedPlan`: exit 1 | fix2_test.go:259: the adoption was not journalled before the intent was resolved | restored
+- S18 N6 an outside-state record not pending. `TestAdoptionAfterCrashBeforeAdopt`: exit 1 | fix2_test.go:268: the adoption did not go plan, plan-check --adopt, apply, then destroy: | restored
+- S19 N6 state not read before the import. `TestAdoptionAfterCrashBeforeImported`: exit 1 | fix2_test.go:278: an address already in state was imported again: | restored
+- S20 N6 the adoption plan unchecked. `TestAdoptionThroughCheckedPlan`: exit 1 | fix2_test.go:261: the adoption did not go plan, plan-check --adopt, apply, then destroy: | restored
+- S21 N6 plan-check: any import ID. `Adopt.test_import_of_another_id_refused`: exit 1 | AssertionError: [] is not true : the plan was accepted | restored
+- S22 N6 plan-check: a missing import passes. `Adopt.test_missing_import_refused`: exit 1 | AssertionError: [] is not true : the plan was accepted | restored
+- S23 N6 plan-check: an import that changes passes. `Adopt.test_import_that_changes_the_resource_refused`: exit 1 | AssertionError: [] is not true : the plan was accepted | restored
+- S24 F4 a covered type passes with its parent present. `TestVerifyGoneCoveredParentStillThere`: exit 1 | fix2_test.go:294: the covered policy was not reported with its parent: | restored
+- S25 Network: one page of security group rules. `TestSDKShapesAndPages`: exit 1 | fix2_test.go:154: network over two pages: {DNSSupport:false DNSHostnames:false VMRoutes:[{Destination:10.43.0.0/16 Target:local}] ServicesRoutes:[{Destination:10.43.0.0/16 Target:local}] VMSGRules:[{Egress:true Protocol:tcp FromPort:8443 ToPort:8443 CIDR:10.42 | restored
+- S26 Network: one page of route tables. `TestSDKShapesAndPages`: exit 1 | fix2_test.go:154: network over two pages: {DNSSupport:false DNSHostnames:false VMRoutes:[] ServicesRoutes:[] VMSGRules:[] PeeringState:}, DescribeRouteTables: 0 tables, want one | restored
diff --git a/infra/hosted/README.md b/infra/hosted/README.md
index d4a0d106..63cf4b44 100644
--- a/infra/hosted/README.md
+++ b/infra/hosted/README.md
@@ -7,7 +7,9 @@ account plan (`docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md`,
sections 2 to 5), and `scripts/phases.json` restates it as the list
`plan-check.py` enforces.
-Nothing here is applied by hand. `equipo-hosted-ops tf ROOT PHASE` (slice 2
+Nothing here is applied by hand. A resource a run created outside state is
+adopted through a run-local `ops_imports_<RUN>.tf` and a plan that
+`plan-check.py --adopt` checks; that file never enters the repository. `equipo-hosted-ops tf ROOT PHASE` (slice 2
Task 33) does it: init with the S3 backend, `plan -out`, `show -json`,
`plan-check.py`, then apply the checked plan.
diff --git a/infra/hosted/scripts/plan-check.py b/infra/hosted/scripts/plan-check.py
index 2da72820..f93b0e8a 100644
--- a/infra/hosted/scripts/plan-check.py
+++ b/infra/hosted/scripts/plan-check.py
@@ -1,7 +1,13 @@
#!/usr/bin/env python3
"""plan-check: refuse an OpenTofu plan that is not exactly what phases.json allows.
- python3 -I plan-check.py --phase P --account A --region R [--phases F] plan.json
+ python3 -I plan-check.py --phase P --account A --region R [--phases F] [--adopt FILE] plan.json
+
+--adopt FILE (a JSON object of address to ID) checks an adoption plan
+instead: equipo-hosted-ops imports a resource it found outside state
+through a run-local import block and a plan that targets it, and that plan
+may only import exactly those addresses at those IDs, each listed for the
+create phase P and planned with no change.
plan.json is `tofu show -json` of a saved plan. equipo-hosted-ops tf runs this
between `tofu plan -out` and `tofu apply` (account plan, "Rules for every
@@ -928,7 +934,7 @@ def describe(node):
# ---- The check -------------------------------------------------------------------
-def check(plan, phase_name, account, region, phases, hosted=None):
+def check(plan, phase_name, account, region, phases, hosted=None, adopt=None):
"""Every reason to refuse the plan; empty if it is accepted."""
out = []
ph = phase(phases, phase_name)
@@ -951,7 +957,14 @@ def check(plan, phase_name, account, region, phases, hosted=None):
out += check_providers(p, account, region)
out += check_configuration(p)
listed = ph.get("resources") or {}
- if ph["kind"] == "create":
+ if adopt is not None:
+ # An adoption plan (equipo-hosted-ops, Task 33 fix round 2): only
+ # imports of the listed IDs, each with no change, in a create phase.
+ if ph["kind"] != "create":
+ out.append("adopt: phase %s is not a create phase" % phase_name)
+ out += check_adopt(p, listed, adopt)
+ values = [rc.get("change", {}).get("after") for rc in p.changes.values()]
+ elif ph["kind"] == "create":
out += check_creates(p, listed, region)
out += check_pins(p, listed)
values = [rc.get("change", {}).get("after") for rc in p.changes.values()]
@@ -1056,6 +1069,30 @@ def check_creates(p, listed, region):
return out
+def check_adopt(p, listed, adopt):
+ """An adoption plan imports exactly adopt's addresses, each at its ID,
+ each listed for the phase and planned with no change; nothing else."""
+ out = []
+ for address, rc in sorted(p.changes.items()):
+ change = rc.get("change") or {}
+ actions = change.get("actions")
+ got = (change.get("importing") or {}).get("id")
+ if address not in adopt:
+ out.append("%s is in an adoption plan but is not an adoption" % address)
+ continue
+ if address not in listed:
+ out.append("%s is not listed for this phase" % address)
+ if got != adopt[address]:
+ out.append("%s imports %s, not the adopted %s" % (address, got, adopt[address]))
+ if actions != ["no-op"]:
+ out.append("%s has actions %s; an adoption allows only an import with no change" % (address, "+".join(actions or [])))
+ if "deposed" in rc or "previous_address" in rc:
+ out.append("%s is deposed or moved" % address)
+ for address in sorted(set(adopt) - set(p.changes)):
+ out.append("%s is adopted but not imported by the plan" % address)
+ return out
+
+
def prior_resources(plan):
def visit(module):
for r in module.get("resources") or []:
@@ -1420,16 +1457,23 @@ def main(argv):
ap.add_argument("--account", required=True)
ap.add_argument("--region", required=True)
ap.add_argument("--phases", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "phases.json"))
+ ap.add_argument("--adopt", help="a JSON object of address to ID: check an adoption plan (imports only)")
ap.add_argument("plan")
args = ap.parse_args(argv)
try:
phases = load_phases(args.phases)
with open(args.plan) as f:
plan = json.load(f)
+ adopt = None
+ if args.adopt:
+ with open(args.adopt) as f:
+ adopt = json.load(f)
+ if not isinstance(adopt, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in adopt.items()):
+ raise ValueError("--adopt must be a JSON object of address to ID")
except (OSError, ValueError) as e:
print("plan-check: %s" % e, file=sys.stderr)
return 2
- refusals = check(plan, args.phase, args.account, args.region, phases)
+ refusals = check(plan, args.phase, args.account, args.region, phases, adopt=adopt)
if refusals:
for r in refusals:
print("plan-check: refused: %s" % r)
diff --git a/infra/hosted/scripts/plan_check_test.py b/infra/hosted/scripts/plan_check_test.py
index aff74d0d..5f01e527 100644
--- a/infra/hosted/scripts/plan_check_test.py
+++ b/infra/hosted/scripts/plan_check_test.py
@@ -114,8 +114,8 @@ def add_resource(plan, address, rtype, after, expressions, module="network"):
"provider_config_key": "aws", "expressions": expressions, "schema_version": 0})
-def check(plan, phase="network", account=ACCOUNT, region=REGION, hosted=HOSTED):
- return pc.check(plan, phase, account, region, PHASES, hosted)
+def check(plan, phase="network", account=ACCOUNT, region=REGION, hosted=HOSTED, adopt=None):
+ return pc.check(plan, phase, account, region, PHASES, hosted, adopt)
class Source:
@@ -216,6 +216,50 @@ class Addresses(Base):
self.assertRefused(check(FRESH, region="us-east-1"), "us-east-1", "region")
+class Adopt(Base):
+ """equipo-hosted-ops adopts a resource found outside state through an
+ import block and a checked plan (Task 33 fix round 2, N6): --adopt lists
+ the addresses and IDs; the plan may only import exactly those, each a
+ no-op, in its create phase."""
+
+ def adopt_plan(self, address=NET + "aws_vpc.vm", rid="vpc-0abc", actions=("no-op",)):
+ p = copy.deepcopy(FRESH)
+ rc = copy.deepcopy(change(p, address))
+ rc["change"]["actions"] = list(actions)
+ rc["change"]["importing"] = {"id": rid}
+ p["resource_changes"] = [rc]
+ return p
+
+ def test_matching_import_accepted(self):
+ self.assertEqual(check(self.adopt_plan(), adopt={NET + "aws_vpc.vm": "vpc-0abc"}), [])
+
+ def test_import_of_another_id_refused(self):
+ self.assertRefused(check(self.adopt_plan(rid="vpc-0other"), adopt={NET + "aws_vpc.vm": "vpc-0abc"}), "aws_vpc.vm", "vpc-0other")
+
+ def test_import_that_changes_the_resource_refused(self):
+ self.assertRefused(check(self.adopt_plan(actions=("update",)), adopt={NET + "aws_vpc.vm": "vpc-0abc"}), "aws_vpc.vm", "update")
+
+ def test_anything_beside_the_imports_refused(self):
+ p = self.adopt_plan()
+ p["resource_changes"].append(copy.deepcopy(change(FRESH, NET + "aws_subnet.vm")))
+ self.assertRefused(check(p, adopt={NET + "aws_vpc.vm": "vpc-0abc"}), "aws_subnet.vm")
+
+ def test_missing_import_refused(self):
+ self.assertRefused(check(self.adopt_plan(), adopt={NET + "aws_vpc.vm": "vpc-0abc", NET + "aws_subnet.vm": "subnet-0abc"}),
+ "aws_subnet.vm", "not imported")
+
+ def test_unlisted_address_refused(self):
+ p = self.adopt_plan()
+ p["resource_changes"][0]["address"] = NET + "aws_vpc.other"
+ self.assertRefused(check(p, adopt={NET + "aws_vpc.other": "vpc-0abc"}), "aws_vpc.other", "not listed")
+
+ def test_adopt_in_a_destroy_phase_refused(self):
+ self.assertRefused(check(self.adopt_plan(), "destroy-network", adopt={NET + "aws_vpc.vm": "vpc-0abc"}), "adopt")
+
+ def test_import_without_adopt_refused(self):
+ self.assertRefused(check(self.adopt_plan()), "aws_vpc.vm")
+
+
class Actions(Base):
def test_update_refused(self):
p = copy.deepcopy(FRESH)
diff --git a/internal/hostedops/cloud.go b/internal/hostedops/cloud.go
index fc970f81..b37eee28 100644
--- a/internal/hostedops/cloud.go
+++ b/internal/hostedops/cloud.go
@@ -163,6 +163,10 @@ type LookupKey struct {
// the intent: the resource's Name tag, its parent's ID (a VPC for a
// subnet), and the client token where the API takes one.
NameTag, Parent, Token string
+ // Accounted are the IDs of this type the ledger already holds for other
+ // intents: an unfiltered listing under the parent that finds only these
+ // proves absence (fix round 2, N2).
+ Accounted []string
}
// LookupResult is a direct read's answer. Definitive is false when the read
diff --git a/internal/hostedops/fake_test.go b/internal/hostedops/fake_test.go
index 401fff53..ee34a6b1 100644
--- a/internal/hostedops/fake_test.go
+++ b/internal/hostedops/fake_test.go
@@ -9,6 +9,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "slices"
"sort"
"strings"
"sync"
@@ -321,18 +322,37 @@ func (o *fakeOpener) Open(context.Context, Target) (Cloud, error) {
// fakeSystemd keeps unit states in a map.
type fakeSystemd struct {
- mu sync.Mutex
- states map[string]string
- started []string
- stopped []string
- argv map[string][]string
- status map[string]string // unit -> its status file
+ mu sync.Mutex
+ states map[string]string
+ started []string
+ stopped []string
+ argv map[string][]string
+ status map[string]string // unit -> its status file
+ timeouts map[string]time.Duration
+ run func(unit string, argv []string) (int, bool)
}
-func (s *fakeSystemd) Start(unit, wd, out, status, ep string, argv []string) error {
+func (s *fakeSystemd) Start(unit, wd, out, status, ep string, stopTimeout time.Duration, argv []string) error {
s.mu.Lock()
- defer s.mu.Unlock()
+ run := s.run
+ defer func() {
+ s.mu.Unlock()
+ // A unit the test asks to run (the recovery unit, by default) runs
+ // in-process, as systemd would, then is done with its status.
+ if run != nil {
+ if code, ran := run(unit, argv); ran {
+ s.mu.Lock()
+ s.states[unit] = "done"
+ s.mu.Unlock()
+ os.WriteFile(status, []byte(fmt.Sprint(code)+"\n"), 0o600)
+ }
+ }
+ }()
s.started = append(s.started, unit)
+ if s.timeouts == nil {
+ s.timeouts = map[string]time.Duration{}
+ }
+ s.timeouts[unit] = stopTimeout
s.states[unit] = "running"
if s.argv == nil {
s.argv, s.status = map[string][]string{}, map[string]string{}
@@ -392,6 +412,8 @@ type rig struct {
deps Deps
out bytes.Buffer
ctx context.Context
+ // autoRecover runs a started recovery unit at once (most tests).
+ autoRecover bool
}
func newRig(t *testing.T, lines ...string) *rig {
@@ -405,10 +427,30 @@ func newRig(t *testing.T, lines ...string) *rig {
t.Error("the controller was dialled")
return nil, errors.New("no controller in this test")
}}
+ r.deps.Self = "OPS"
+ r.deps.SelfUnit = func() string { return "" }
+ r.systemd.run = func(unit string, argv []string) (int, bool) {
+ if !slices.Contains(argv, "--recovery") || !r.autoRecover {
+ return 0, false
+ }
+ return r.runUnitArgv(unit, argv), true
+ }
+ r.autoRecover = true
r.journal(append([]string{"INIT run=r1"}, lines...)...)
return r
}
+// runUnitArgv runs a unit's argv after the binary, as that unit.
+func (r *rig) runUnitArgv(unit string, argv []string) int {
+ i := slices.Index(argv, "OPS")
+ if i < 0 {
+ r.t.Fatalf("unit %s does not run ops: %v", unit, argv)
+ }
+ d := r.deps
+ d.SelfUnit = func() string { return unit }
+ return Main(r.ctx, argv[i+1:], d)
+}
+
// journal appends lines, stamped a second apart before t0.
func (r *rig) journal(lines ...string) {
f, err := os.OpenFile(filepath.Join(r.dir, JournalFile), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
diff --git a/internal/hostedops/fix1_test.go b/internal/hostedops/fix1_test.go
index a60dfba7..74a7d84c 100644
--- a/internal/hostedops/fix1_test.go
+++ b/internal/hostedops/fix1_test.go
@@ -32,15 +32,8 @@ import (
// would: its argv after the binary, with its unit name in the environment.
func (r *rig) runUnit(unit string) int {
r.t.Helper()
- argv := r.systemd.argv[unit]
- i := slices.Index(argv, "OPS")
- if i < 0 {
- r.t.Fatalf("unit %s does not run ops: %v", unit, argv)
- }
- r.t.Setenv("EQUIPO_HOSTED_OPS_UNIT", unit)
- defer os.Unsetenv("EQUIPO_HOSTED_OPS_UNIT")
r.out.Reset()
- return Main(r.ctx, argv[i+1:], r.deps)
+ return r.runUnitArgv(unit, r.systemd.argv[unit])
}
// F1: a background wait starts a journalled watchdog unit; at the deadline
@@ -114,15 +107,16 @@ func TestSafeStopSurvivesCancellation(t *testing.T) {
}
}
-// F2: safe-stop never stops the unit it runs in; it stops the others.
+// F2, as N1 rules it: safe-stop's recovery unit stops every journalled
+// unit but itself.
func TestSafeStopSparesItsOwnUnit(t *testing.T) {
r := newRig(t, "UNIT hprod-r1-wait-sns.service", "UNIT hprod-r1-4.3.service")
r.systemd.states["hprod-r1-wait-sns.service"] = "running"
r.systemd.states["hprod-r1-4.3.service"] = "running"
- t.Setenv("EQUIPO_HOSTED_OPS_UNIT", "hprod-r1-wait-sns.service")
- r.want(0, "safe-stop")
- if slices.Contains(r.systemd.stopped, "hprod-r1-wait-sns.service") || !slices.Contains(r.systemd.stopped, "hprod-r1-4.3.service") {
- t.Fatalf("stopped %v; want the other unit and never its own", r.systemd.stopped)
+ r.ops("safe-stop")
+ if slices.Contains(r.systemd.stopped, "hprod-r1-recovery.service") || !slices.Contains(r.systemd.stopped, "hprod-r1-4.3.service") ||
+ !slices.Contains(r.systemd.stopped, "hprod-r1-wait-sns.service") {
+ t.Fatalf("stopped %v; want every unit but the recovery unit", r.systemd.stopped)
}
}
@@ -467,37 +461,9 @@ func TestEstimateStopsOnUnresolvedHost(t *testing.T) {
}
}
-// F15: a resource reconciliation found outside state is adopted by an
-// import block and removed by the normal destroy path, then verified gone.
-func TestAdoptedResourceTornDown(t *testing.T) {
- r, fake := tfRig(t, "INTENT tf network/module.network.aws_vpc.vm - type=aws_vpc nametag=equipo-hosted-vm run=r1", "TF-APPLY network start network")
- os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"planned_values":{"root_module":{}}}`), 0o600)
- gone := false
- r.cloud.lookup = func(k LookupKey) (LookupResult, error) {
- if k.Type == "aws_vpc" && !gone {
- return LookupResult{IDs: []string{"vpc-0orphan"}, Definitive: true}, nil
- }
- return LookupResult{Definitive: true}, nil
- }
- r.want(0, "tf", "reconcile", "network")
- imports := filepath.Join(r.dir, "repo", "infra", "hosted", "envs", "prod", "network", "ops_imports_r1.tf")
- b, err := os.ReadFile(imports)
- if err != nil || !strings.Contains(string(b), `to = module.network.aws_vpc.vm`) || !strings.Contains(string(b), `id = "vpc-0orphan"`) {
- t.Fatalf("no import block written: %v\n%s", err, b)
- }
- os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"resource_changes":[{"address":"module.network.aws_vpc.vm","type":"aws_vpc","change":{"actions":["delete"],"before":{"id":"vpc-0orphan"}}}]}`), 0o600)
- os.WriteFile(filepath.Join(fake, "state.json"), []byte(`{"values":{"root_module":{}}}`), 0o600)
- r.want(0, "tf", "network", "destroy-network")
- log := calls(t, fake)
- if i, j := strings.Index(log, " import "), strings.Index(log, " -destroy"); i < 0 || j < i || !strings.Contains(log, "module.network.aws_vpc.vm vpc-0orphan") {
- t.Fatalf("the adoption was not imported before the destroy plan:\n%s", log)
- }
- if _, err := os.Stat(imports); err == nil {
- t.Fatal("the import block stayed in the root after the import")
- }
- gone = true
- r.want(0, "verify-gone")
-}
+// F15's round-1 test (a standalone tofu import) is superseded by N6's
+// TestAdoptionThroughCheckedPlan, TestAdoptionAfterCrashBeforeAdopt and
+// TestAdoptionAfterCrashBeforeImported (fix2_test.go).
// F16: with a controller recorded and no instance notes, safe-stop cannot
// prove the instance flag is off: unresolved, 99.
@@ -574,17 +540,47 @@ func TestUnitProbe(t *testing.T) {
r.want(ExitStop, "unit", "probe")
}
-// Extra: every ops invocation in the account plan passes the real flag
-// parsers; a malformed one is reported as a usage error.
-func TestPlanInvocationsParseFlags(t *testing.T) {
- b, err := os.ReadFile(filepath.Join("..", "..", "docs", "superpowers", "plans", "2026-11-30-hosted-prod-account-plan.md"))
- if err != nil {
- t.Fatal(err)
+// Extra (round 2): every ops invocation in the account plan and in Task
+// 34's text passes the real parsers, flags included; nothing is skipped. A
+// span that is only a command's name (prose such as "`ops assert`") has no
+// flags to parse, so its name must resolve; every other span is expanded
+// (a|b alternatives, the plan's upper-case placeholders) and run.
+func TestPlanInvocationsParse(t *testing.T) {
+ read := func(name string) string {
+ b, err := os.ReadFile(filepath.Join("..", "..", "docs", "superpowers", "plans", name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
}
+ slice2 := read("2026-11-30-hosted-runners-slice-2.md")
+ task34 := slice2[strings.Index(slice2, "### Task 34"):strings.Index(slice2, "### Task 35")]
+ account := read("2026-11-30-hosted-prod-account-plan.md")
t.Chdir(t.TempDir()) // the plan writes some files by relative path (9.4's bundle)
- invs := planInvocations(string(b))
- if len(invs) < 40 {
- t.Fatalf("only %d invocations found", len(invs))
+ var invs [][]string
+ names := 0
+ for _, src := range []string{account, task34} {
+ for _, inv := range planInvocations(src) {
+ if strings.Join(inv, " ") == "tf reconcile" { // the documented subform, named in prose
+ names++
+ continue
+ }
+ if len(inv) <= 2 {
+ if name, _, rest, ok := lookup(inv); ok && len(rest) == 0 && (len(inv) == 1 || strings.Contains(name, " ")) && commands[name].run != nil {
+ if needsArgs(name) {
+ names++
+ continue
+ }
+ } else if len(inv) == 1 && isGroup(inv[0]) {
+ names++
+ continue
+ }
+ }
+ invs = append(invs, inv)
+ }
+ }
+ if len(invs) < 60 || names < 10 {
+ t.Fatalf("only %d invocations and %d name references found", len(invs), names)
}
for _, inv := range invs {
r := newRig(t, "REC microvm-image "+image1)
@@ -601,38 +597,64 @@ func TestPlanInvocationsParseFlags(t *testing.T) {
}
}
-// planInvocations extracts every ops invocation from the plan's code and
-// inline spans, with placeholders filled.
+// needsArgs: a command that cannot run bare (so a bare mention is prose).
+func needsArgs(name string) bool {
+ switch name {
+ case "guard", "inventory", "quota", "mfa-check", "fence", "safe-stop", "verify-gone", "report", "estimate",
+ "vms reconcile", "ledger reconcile", "cloudtrail stop-logging", "connector delete", "unit probe", "status", "vms adopt", "ledger show":
+ return false
+ }
+ return true
+}
+
+func isGroup(word string) bool {
+ for name := range commands {
+ if strings.HasPrefix(name, word+" ") {
+ return true
+ }
+ }
+ return false
+}
+
+// placeholders fills the plan's upper-case placeholders.
+var placeholders = strings.NewReplacer("ROOT PHASE", "network network", "reconcile ROOT", "reconcile network")
+
+// planInvocations extracts every ops invocation from the plan's inline
+// spans and code blocks (backslash-continued lines joined), each a|b
+// alternative separately, placeholders filled.
func planInvocations(plan string) [][]string {
fill := strings.NewReplacer("$P", "p", "$IMAGE_DIGEST", "sha256:"+strings.Repeat("a", 64), "$RUN", "r1", "$K", "p/keys")
var out [][]string
add := func(s string) {
+ s = placeholders.Replace(s)
s = regexp.MustCompile(`--max <[^>]*>`).ReplaceAllString(s, "--max 1m")
s = regexp.MustCompile(`\$\([^)]*\)`).ReplaceAllString(s, "x")
s = regexp.MustCompile(`<[^>]*>`).ReplaceAllString(s, "x")
f := shellWords(fill.Replace(s))
- if len(f) > 1 && f[0] == "ops" {
- out = append(out, f[1:])
+ if len(f) < 2 || f[0] != "ops" {
+ return
}
+ alts := [][]string{nil}
+ for _, w := range f[1:] {
+ var next [][]string
+ for _, a := range alts {
+ for _, alt := range strings.Split(w, "|") {
+ next = append(next, append(append([]string{}, a...), alt))
+ }
+ }
+ alts = next
+ }
+ out = append(out, alts...)
}
for _, m := range regexp.MustCompile("`(ops [^`]+)`").FindAllStringSubmatch(plan, -1) {
- s := m[1]
- if strings.ContainsAny(s, "|") || regexp.MustCompile(`\b(ROOT|PHASE|ID|NAME|CMD)\b`).MatchString(s) {
- continue // a pattern, not an invocation
- }
- bare := len(strings.Fields(s)) <= 3 && !strings.Contains(s, "<")
- for _, f := range strings.Fields(s) {
- bare = bare && !strings.HasPrefix(f, "-")
- }
- if bare {
- continue // a command named in prose
- }
- add(s)
+ add(m[1])
}
for _, block := range regexp.MustCompile("(?s)```sh\n(.*?)```").FindAllStringSubmatch(plan, -1) {
for _, line := range strings.Split(strings.ReplaceAll(block[1], "\\\n", " "), "\n") {
- if i := strings.Index(line, "ops "); i >= 0 && (i == 0 || line[i-1] == ' ' || line[i-1] == ';') && !strings.Contains(line, "ops()") {
- add(strings.SplitN(line[i:], "#", 2)[0])
+ for _, part := range strings.Split(strings.SplitN(line, "#", 2)[0], ";") {
+ if i := strings.Index(part, "ops "); i >= 0 && (i == 0 || part[i-1] == ' ') && !strings.Contains(part, "ops()") {
+ add(part[i:])
+ }
}
}
}
diff --git a/internal/hostedops/fix2_test.go b/internal/hostedops/fix2_test.go
new file mode 100644
index 00000000..7e821e62
--- /dev/null
+++ b/internal/hostedops/fix2_test.go
@@ -0,0 +1,296 @@
+package hostedops
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// Fix round 2 (t33-r2.md, task-33-fix2.md): each test written and seen
+// failing before its fix.
+
+const recoveryUnit = "hprod-r1-recovery.service"
+
+// N1: the watchdog expires during an active block; both ask for recovery;
+// exactly one recovery unit runs, outside both, stops them, and fences and
+// settles. A second recovery that finds the lock held stands aside.
+func TestOneRecoveryOwner(t *testing.T) {
+ r := settleRig(t, nil, "VM microvm-a source=controller", "UNIT hprod-r1-6.2.service")
+ r.systemd.states["hprod-r1-6.2.service"] = "running"
+ r.autoRecover = false // the recovery unit runs when the test says
+ r.want(0, "wait-human", "sns-confirmed", "--max", "1h", "--background")
+ watchdog := "hprod-r1-wait-sns-confirmed.service"
+ r.clock.Sleep(context.Background(), 2*time.Hour)
+ if code := r.runUnit(watchdog); code != ExitStop {
+ t.Fatalf("the watchdog exited %d, want 99", code)
+ }
+ // The block, stopped by recovery's S.0 or failing on its own, asks too.
+ blockReq := r.deps
+ blockReq.SelfUnit = func() string { return "hprod-r1-6.2.service" }
+ blockReq.Exec = func(ctxT, []string, []string, wT, wT) int { return 99 }
+ Main(r.ctx, []string{"-dir", r.dir, "-run", "r1", "-profile", "p", "-account", ProdAccount, "-region", testRegion, "safe-stop"}, blockReq)
+ n := 0
+ for _, u := range r.systemd.started {
+ if u == recoveryUnit {
+ n++
+ }
+ }
+ if n != 1 {
+ t.Fatalf("the recovery unit was started %d times, want once: %v", n, r.systemd.started)
+ }
+ if r.has("SAFE-STOP", "S.2") {
+ t.Fatal("a requester ran safe-stop's cloud steps itself")
+ }
+ if to := r.systemd.timeouts[recoveryUnit]; to <= SafeStopBound {
+ t.Fatalf("the recovery unit's stop timeout %v is not above the %v bound", to, SafeStopBound)
+ }
+ if code := r.runUnit(recoveryUnit); code != 0 {
+ t.Fatalf("the recovery unit exited %d:\n%s", code, r.out.String())
+ }
+ if !r.has("SETTLED", "repeat=done") || !slices.Contains(r.systemd.stopped, "hprod-r1-6.2.service") || !slices.Contains(r.systemd.stopped, watchdog) ||
+ slices.Contains(r.systemd.stopped, recoveryUnit) {
+ t.Fatalf("recovery did not stop the others, spare itself and settle: stopped %v", r.systemd.stopped)
+ }
+ // A second recovery while the lock is held stands aside.
+ lock := filepath.Join(r.dir, "r1", "recovery.lock")
+ f, err := os.OpenFile(lock, os.O_CREATE|os.O_RDWR, 0o600)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
+ t.Fatal(err)
+ }
+ before := len(r.cloud.log())
+ if code := r.runUnit(recoveryUnit); code != 0 || !r.has("RECOVERY", "already owned") || len(r.cloud.log()) != before {
+ t.Fatalf("a second recovery exited %d, journalled %t, made %d calls", code, r.has("RECOVERY", "already owned"), len(r.cloud.log())-before)
+ }
+}
+
+// N1: a cancelled requester still starts the recovery unit.
+func TestRecoveryStartsAfterCancellation(t *testing.T) {
+ r := newRig(t)
+ r.autoRecover = false
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ r.ctx = ctx
+ r.ops("safe-stop")
+ if !slices.Contains(r.systemd.started, recoveryUnit) {
+ t.Fatalf("a cancelled requester started no recovery unit: %v", r.systemd.started)
+ }
+}
+
+// N1: own membership comes from the cgroup, under systemd only.
+func TestSelfUnitFromCgroup(t *testing.T) {
+ cg := "0::/user.slice/user-1001.slice/user@1001.service/app.slice/hprod-r1-6.2.service\n"
+ if got := unitFromCgroup(cg, "inv-1"); got != "hprod-r1-6.2.service" {
+ t.Fatalf("unit %q", got)
+ }
+ if got := unitFromCgroup(cg, ""); got != "" {
+ t.Fatalf("without INVOCATION_ID: %q", got)
+ }
+ if got := unitFromCgroup("0::/user.slice/user-1001.slice/session-3.scope\n", "inv-1"); got != "" {
+ t.Fatalf("a session scope: %q", got)
+ }
+}
+
+// N2: a parent's verified deletion resolves its children's intents; the
+// lookups carry the IDs the ledger already accounts for.
+func TestParentDeletionResolves(t *testing.T) {
+ r, fake := tfRig(t, "REC tf network/module.network.aws_vpc.vm id=vpc-0vm type=aws_vpc source=state",
+ "REC tf network/module.network.aws_subnet.services_a id=subnet-0a type=aws_subnet source=state",
+ "DELETED tf network/module.network.aws_vpc.vm read-gone",
+ "INTENT tf network/module.network.aws_subnet.vm - type=aws_subnet run=r1 nametag=equipo-hosted-vm parent=vpc-0vm",
+ "INTENT tf network/module.network.aws_subnet.services_b - type=aws_subnet run=r1 nametag=equipo-hosted-services-b parent=vpc-0svc")
+ os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"planned_values":{"root_module":{}}}`), 0o600)
+ var keys []LookupKey
+ r.cloud.lookup = func(k LookupKey) (LookupResult, error) { keys = append(keys, k); return LookupResult{}, nil }
+ r.ops("tf", "reconcile", "network")
+ l := r.ledger()
+ if l.CreationState("tf", "network/module.network.aws_subnet.vm") != StateAbsent {
+ t.Fatal("a child of a verified-deleted VPC was not resolved absent")
+ }
+ if len(keys) != 1 || !slices.Contains(keys[0].Accounted, "subnet-0a") {
+ t.Fatalf("lookups %+v; want one, carrying the recorded subnet IDs", keys)
+ }
+}
+
+// N3: when reconciliation makes safe-stop fence again, every image is
+// settled again after that fence.
+func TestSecondFenceSettlesAgain(t *testing.T) {
+ r, _ := tfRig(t, "REC microvm-image "+image1, "VM microvm-a source=controller", "TF-APPLY network start network",
+ "INTENT tf services/module.controller.aws_instance.controller - type=aws_instance nametag=equipo-hosted-controller run=r1")
+ os.WriteFile(filepath.Join(os.Getenv("FAKE_TOFU"), "plan.json"), []byte(`{"planned_values":{"root_module":{}}}`), 0o600)
+ looked := 0
+ r.cloud.lookup = func(k LookupKey) (LookupResult, error) {
+ if k.Type == "aws_instance" {
+ looked++
+ if looked > 1 {
+ return LookupResult{IDs: []string{"i-0late"}, Definitive: true}, nil
+ }
+ }
+ return LookupResult{}, nil
+ }
+ r.ops("safe-stop")
+ stop := r.cloud.index("StopInstance i-0late")
+ if stop < 0 {
+ t.Fatalf("no second fence: %v", r.cloud.log())
+ }
+ var scan, term bool
+ for _, c := range r.cloud.log()[stop:] {
+ scan = scan || strings.HasPrefix(c, "ListVMs")
+ term = term || c == "TerminateVM microvm-a"
+ }
+ if !scan || !term {
+ t.Fatalf("no scan and termination after the second fence: %v", r.cloud.log()[stop:])
+ }
+}
+
+// N4: assume-role actions match as IAM matches them.
+func TestMFAActionSemantics(t *testing.T) {
+ protected := `{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111111111111:root"},"Action":"sts:AssumeRole","Condition":{"Bool":{"aws:MultiFactorAuthPresent":"true"}}}`
+ open := func(action string) string {
+ return `{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111111111111:root"},"Action":` + action + `}`
+ }
+ for _, c := range []struct {
+ name, doc string
+ code int
+ }{
+ {"lower case beside", `{"Statement":[` + protected + `,` + open(`"sts:assumerole"`) + `]}`, ExitStop},
+ {"wildcard beside", `{"Statement":[` + protected + `,` + open(`"sts:Assume*"`) + `]}`, ExitStop},
+ {"star beside", `{"Statement":[` + protected + `,` + open(`["s3:GetObject","*"]`) + `]}`, ExitStop},
+ {"question mark", `{"Statement":[` + protected + `,` + open(`"sts:AssumeRol?"`) + `]}`, ExitStop},
+ {"NotAction", `{"Statement":[` + protected + `,{"Effect":"Allow","Principal":"*","NotAction":"s3:*"}]}`, ExitStop},
+ {"odd effect", `{"Statement":[` + protected + `,{"Effect":"allow","Principal":"*","Action":"sts:AssumeRole"}]}`, ExitStop},
+ {"upper case, protected", `{"Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111111111111:root"},"Action":"STS:ASSUMEROLE","Condition":{"Bool":{"aws:MultiFactorAuthPresent":"true"}}}]}`, 0},
+ {"other service only beside", `{"Statement":[` + protected + `,` + open(`"s3:GetObject"`) + `]}`, 0},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ r := newRig(t)
+ r.cloud.trust = c.doc
+ r.want(c.code, "mfa-check")
+ })
+ }
+}
+
+// N5: a launch is bound to the image its digest named when it was made.
+func TestLaunchBoundAtIntent(t *testing.T) {
+ imageB := strings.Replace(image1, "prod-r1", "prod-r1-b", 1)
+ d := "sha256:" + strings.Repeat("a", 64)
+ r := newRig(t, "IMAGE-DIGEST "+d+" "+image1, "INTENT cert-launch "+d+" large 1 att-a", "IMAGE-DIGEST "+d+" "+imageB,
+ "SETTLED "+imageB+" repeat=done")
+ if len(r.ledger().Open("cert-launch")) != 1 {
+ t.Fatal("settling the digest's new image resolved a launch of its old one")
+ }
+ r.journal("SETTLED " + image1 + " repeat=done")
+ if len(r.ledger().Open("cert-launch")) != 0 {
+ t.Fatal("settling the launch's own image did not resolve it")
+ }
+}
+
+// adoptRig is a run whose reconcile finds the VM VPC outside state.
+func adoptRig(t *testing.T, lines ...string) (*rig, string) {
+ r, fake := tfRig(t, lines...)
+ os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"planned_values":{"root_module":{}}}`), 0o600)
+ os.WriteFile(filepath.Join(fake, "plan-adopt-network.json"), []byte(`{"resource_changes":[{"address":"module.network.aws_vpc.vm","type":"aws_vpc",
+"change":{"actions":["no-op"],"importing":{"id":"vpc-0orphan"},"after":{"id":"vpc-0orphan"}}}]}`), 0o600)
+ os.WriteFile(filepath.Join(fake, "plan-destroy-network.json"), []byte(`{"resource_changes":[{"address":"module.network.aws_vpc.vm","type":"aws_vpc",
+"change":{"actions":["delete"],"before":{"id":"vpc-0orphan"}}}]}`), 0o600)
+ os.WriteFile(filepath.Join(fake, "state.json"), []byte(`{"values":{"root_module":{}}}`), 0o600)
+ return r, fake
+}
+
+// teardown runs destroy-network and verify-gone, and checks the adoption
+// went through a checked plan, never a standalone import.
+func teardown(t *testing.T, r *rig, fake string, wantAdoptPlan bool) {
+ t.Helper()
+ gone := false
+ r.cloud.lookup = func(k LookupKey) (LookupResult, error) {
+ if k.Type == "aws_vpc" && k.ID == "vpc-0orphan" && !gone {
+ return LookupResult{IDs: []string{"vpc-0orphan"}, Definitive: true}, nil
+ }
+ return LookupResult{Definitive: true}, nil
+ }
+ r.want(0, "tf", "network", "destroy-network")
+ log := calls(t, fake)
+ if strings.Contains(log, " import -input") {
+ t.Fatalf("a standalone tofu import ran:\n%s", log)
+ }
+ adopt := strings.Index(log, "-out="+filepath.Join(r.dir, "tf", "adopt-network.tfplan"))
+ if wantAdoptPlan {
+ if adopt < 0 || !strings.Contains(log, "-target=module.network.aws_vpc.vm") || !strings.Contains(log, "--adopt") ||
+ strings.Index(log, " apply -input=false -no-color "+filepath.Join(r.dir, "tf", "adopt-network.tfplan")) < adopt ||
+ strings.Index(log, "-destroy") < adopt {
+ t.Fatalf("the adoption did not go plan, plan-check --adopt, apply, then destroy:\n%s", log)
+ }
+ } else if adopt >= 0 {
+ t.Fatalf("an address already in state was imported again:\n%s", log)
+ }
+ if !r.has("IMPORTED", "network/module.network.aws_vpc.vm") {
+ t.Fatal("no IMPORTED record")
+ }
+ gone = true
+ r.want(0, "verify-gone")
+}
+
+// N6: discovery journals the adoption before it resolves the intent, and
+// the import runs through plan, plan-check and apply.
+func TestAdoptionThroughCheckedPlan(t *testing.T) {
+ r, fake := adoptRig(t, "INTENT tf network/module.network.aws_vpc.vm - type=aws_vpc nametag=equipo-hosted-vm run=r1")
+ r.cloud.lookup = func(k LookupKey) (LookupResult, error) {
+ return LookupResult{IDs: []string{"vpc-0orphan"}, Definitive: true}, nil
+ }
+ r.want(0, "tf", "reconcile", "network")
+ var adopt, rec int
+ for i, e := range r.ledger().Entries {
+ if e.Verb == "ADOPT" {
+ adopt = i
+ }
+ if e.Verb == "REC" && e.Field(0) == "tf" {
+ rec = i
+ }
+ }
+ if adopt == 0 || adopt > rec {
+ t.Fatal("the adoption was not journalled before the intent was resolved")
+ }
+ teardown(t, r, fake, true)
+}
+
+// N6: a crash after the record and before ADOPT still adopts.
+func TestAdoptionAfterCrashBeforeAdopt(t *testing.T) {
+ r, fake := adoptRig(t, "INTENT tf network/module.network.aws_vpc.vm - type=aws_vpc nametag=equipo-hosted-vm run=r1",
+ "REC tf network/module.network.aws_vpc.vm id=vpc-0orphan type=aws_vpc source=outside-state")
+ teardown(t, r, fake, true)
+}
+
+// N6: a crash after the import and before IMPORTED does not import again:
+// state already holds the address.
+func TestAdoptionAfterCrashBeforeImported(t *testing.T) {
+ r, fake := adoptRig(t, "INTENT tf network/module.network.aws_vpc.vm - type=aws_vpc nametag=equipo-hosted-vm run=r1",
+ "ADOPT network/module.network.aws_vpc.vm vpc-0orphan",
+ "REC tf network/module.network.aws_vpc.vm id=vpc-0orphan type=aws_vpc source=outside-state")
+ os.WriteFile(filepath.Join(fake, "state.list"), []byte("module.network.aws_vpc.vm\n"), 0o600)
+ teardown(t, r, fake, false)
+}
+
+// F4's covered-parent path: a covered type whose parent is still there is
+// reported, not passed.
+func TestVerifyGoneCoveredParentStillThere(t *testing.T) {
+ r := newRig(t, "REC tf config/module.config.aws_iam_role.image_build id=arn:aws:iam::149757027610:role/equipo-hosted-image-build type=aws_iam_role source=state",
+ "REC tf config/module.config.aws_iam_role_policy.image_build id=equipo-hosted-image-build:image-build type=aws_iam_role_policy source=state parent=equipo-hosted-image-build")
+ r.cloud.lookup = func(k LookupKey) (LookupResult, error) {
+ if k.Type == "aws_iam_role" {
+ return LookupResult{}, nil // not definitive: the role is not proved gone
+ }
+ return LookupResult{}, nil
+ }
+ r.ops("verify-gone")
+ if !strings.Contains(r.out.String(), "aws_iam_role_policy.image_build (its parent") {
+ t.Fatalf("the covered policy was not reported with its parent:\n%s", r.out.String())
+ }
+}
diff --git a/internal/hostedops/ledger.go b/internal/hostedops/ledger.go
index 54dc52a6..f4ee7d26 100644
--- a/internal/hostedops/ledger.go
+++ b/internal/hostedops/ledger.go
@@ -127,8 +127,11 @@ func (j *Journal) Entries() ([]Entry, error) {
type Intent struct {
Entry
Kind, Name, Token string
- State string // open, confirmed, absent
- Value string // the REC value that confirmed it
+ // Image is the image ARN a VM launch is bound to, fixed when the
+ // intent is replayed (N5): the digest's mapping at that line.
+ Image string
+ State string // open, confirmed, absent
+ Value string // the REC value that confirmed it
}
// Rec is one REC line.
@@ -204,6 +207,10 @@ func (l *Ledger) apply(e Entry) {
in := &Intent{Entry: e, Kind: e.Field(0), Name: e.Field(1), Token: e.Field(2), State: "open"}
if in.Kind == "cert-launch" { // equipo-hosted-certify: IMAGE SIZE LAUNCHBY ATTEMPT
in.Token = e.Field(4)
+ in.Image = l.ImageOf[in.Name]
+ }
+ if a := in.Attr("image"); in.Kind == "vm-launch" && strings.HasPrefix(a, "arn:") {
+ in.Image = a
}
if in.Kind == "microvm-image" {
l.Builds++
@@ -367,15 +374,7 @@ func (l *Ledger) resolve(kind, name, value, state string, oldestToo bool) *Inten
// intentImage is the image ARN a VM launch intent is bound to: a
// cert-launch names its image digest (IMAGE-DIGEST maps it), a vm-launch
// its image=ARN; "" when the ledger cannot name it.
-func (l *Ledger) intentImage(in *Intent) string {
- if a := in.Attr("image"); strings.HasPrefix(a, "arn:") {
- return a
- }
- if in.Kind == "cert-launch" {
- return l.ImageOf[in.Name]
- }
- return ""
-}
+func (l *Ledger) intentImage(in *Intent) string { return in.Image }
func (l *Ledger) recIndex(kind, value string) int {
for i, r := range l.Recs {
diff --git a/internal/hostedops/ledger_test.go b/internal/hostedops/ledger_test.go
index 589809b8..fe535a42 100644
--- a/internal/hostedops/ledger_test.go
+++ b/internal/hostedops/ledger_test.go
@@ -6,7 +6,6 @@ import (
"os"
"path/filepath"
"reflect"
- "regexp"
"slices"
"strings"
"testing"
@@ -176,32 +175,6 @@ func TestBundleReopenRoundTrip(t *testing.T) {
r.want(ExitStop, "bundle", "--out", out)
}
-// TestPlanInvocationsParse: every "ops SUBCOMMAND" the account plan uses is
-// a command (the plan is the acceptance list).
-func TestPlanInvocationsParse(t *testing.T) {
- b, err := os.ReadFile(filepath.Join("..", "..", "docs", "superpowers", "plans", "2026-11-30-hosted-prod-account-plan.md"))
- if err != nil {
- t.Fatal(err)
- }
- re := regexp.MustCompile("`ops ([a-z-]+)(?: ([a-z-]+))?")
- seen := map[string]bool{}
- for _, m := range re.FindAllStringSubmatch(string(b), -1) {
- group := false
- for name := range commands {
- group = group || (m[2] == "" && strings.HasPrefix(name, m[1]+" "))
- }
- if _, _, _, ok := lookup([]string{m[1], m[2]}); !ok && !group {
- if _, _, _, ok := lookup([]string{m[1]}); !ok {
- t.Errorf("the plan's `ops %s %s` is not a command", m[1], m[2])
- }
- }
- seen[m[1]] = true
- }
- if len(seen) < 25 {
- t.Fatalf("only %d subcommands found in the plan; the pattern is wrong", len(seen))
- }
-}
-
// TestSingletonNeverTurnsOff: ensure turns a setting on only when it is
// off, and nothing in ops can turn one off.
func TestSingletonNeverTurnsOff(t *testing.T) {
diff --git a/internal/hostedops/ledgercmd.go b/internal/hostedops/ledgercmd.go
index 5e299765..e5a8144e 100644
--- a/internal/hostedops/ledgercmd.go
+++ b/internal/hostedops/ledgercmd.go
@@ -252,7 +252,7 @@ func cmdWaitHuman(o *Ops, args []string) error {
if err := o.jw("HUMAN-DONE", "%s", name); err != nil {
return err
}
- if slices.Contains(l.Units, unit) && unit != os.Getenv("EQUIPO_HOSTED_OPS_UNIT") {
+ if slices.Contains(l.Units, unit) && unit != o.selfUnit() {
if err := o.Systemd.Stop(unit); err != nil {
return failf("the watchdog %s was not proved stopped: %v", unit, err)
}
@@ -274,7 +274,7 @@ func cmdWaitHuman(o *Ops, args []string) error {
}
if *bg {
if !slices.Contains(l.Units, unit) {
- if err := o.startUnit("wait-"+name, o.selfArgv("wait-human", name, "--watch")); err != nil {
+ if err := o.startUnit("wait-"+name, o.selfArgv("wait-human", name, "--watch"), 45*time.Second, false); err != nil {
return err
}
}
@@ -292,9 +292,9 @@ func cmdWaitHuman(o *Ops, args []string) error {
}
if !o.Clock.Now().Before(w.Deadline) {
_ = o.jw("WAIT-EXPIRED", "%s", name)
- o.out("ABORT: wait-human %s: not done by %s; running safe-stop", name, w.Deadline.UTC().Format(time.RFC3339))
- if err := o.safeStop(); err != nil {
- o.out("safe-stop: %v", err)
+ o.out("ABORT: wait-human %s: not done by %s; asking for recovery", name, w.Deadline.UTC().Format(time.RFC3339))
+ if err := o.requestRecovery(); err != nil {
+ o.out("recovery: %v", err)
}
return stopf("wait-human %s: not done by %s", name, w.Deadline.UTC().Format(time.RFC3339))
}
diff --git a/internal/hostedops/lock_other.go b/internal/hostedops/lock_other.go
new file mode 100644
index 00000000..853fc650
--- /dev/null
+++ b/internal/hostedops/lock_other.go
@@ -0,0 +1,10 @@
+//go:build !unix
+
+package hostedops
+
+import "errors"
+
+// tryLock: recovery runs only under systemd on Linux.
+func tryLock(string) (func(), bool, error) {
+ return nil, false, errors.New("the recovery lock needs a unix system")
+}
diff --git a/internal/hostedops/lock_unix.go b/internal/hostedops/lock_unix.go
new file mode 100644
index 00000000..a43449f1
--- /dev/null
+++ b/internal/hostedops/lock_unix.go
@@ -0,0 +1,26 @@
+//go:build unix
+
+package hostedops
+
+import (
+ "errors"
+ "os"
+ "syscall"
+)
+
+// tryLock takes an exclusive, non-blocking flock on path. held reports
+// that another process holds it.
+func tryLock(path string) (release func(), held bool, err error) {
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
+ if err != nil {
+ return nil, false, err
+ }
+ if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
+ f.Close()
+ if errors.Is(err, syscall.EWOULDBLOCK) {
+ return nil, true, nil
+ }
+ return nil, false, err
+ }
+ return func() { _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN); f.Close() }, false, nil
+}
diff --git a/internal/hostedops/ops.go b/internal/hostedops/ops.go
index ef98a9b9..861d5e13 100644
--- a/internal/hostedops/ops.go
+++ b/internal/hostedops/ops.go
@@ -100,8 +100,11 @@ type Deps struct {
Litestream string // <dir>/bin/litestream
Carlos string // "carlos"
Self string // this binary, for the units ops starts; os.Executable()
- Stdout io.Writer
- Stderr io.Writer
+ // SelfUnit names the systemd unit this process runs in, or "";
+ // nil reads /proc/self/cgroup (with INVOCATION_ID).
+ SelfUnit func() string
+ Stdout io.Writer
+ Stderr io.Writer
// 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 4d6c8143..dbd89632 100644
--- a/internal/hostedops/ops_test.go
+++ b/internal/hostedops/ops_test.go
@@ -202,9 +202,10 @@ const fakeTofu = `#!/bin/sh
log="$FAKE_TOFU/calls.log"
echo "ARGS $*" >> "$log"
env | grep -E '^(AWS_|TF_CLI_ARGS|TF_VAR_)' | sort | sed 's/^/ENV /' >> "$log"
-for a in "$@"; do case "$a" in -out=*) echo saved-plan > "${a#-out=}";; esac; done
+for a in "$@"; do last="$a"; case "$a" in -out=*) echo saved-plan > "${a#-out=}";; esac; done
case " $* " in
- *" show -json -no-color "*.tfplan*) cat "$FAKE_TOFU/plan.json";;
+ *" show -json -no-color "*.tfplan*) b=$(basename "$last" .tfplan); if [ -f "$FAKE_TOFU/plan-$b.json" ]; then cat "$FAKE_TOFU/plan-$b.json"; else cat "$FAKE_TOFU/plan.json"; fi;;
+ *" state list "*) [ ! -f "$FAKE_TOFU/state.list" ] || cat "$FAKE_TOFU/state.list";;
*" show -json -no-color "*) cat "$FAKE_TOFU/state.json";;
*" output -json "*) echo '{"vm_vpc_id":{"value":"vpc-0vm"}}';;
esac
@@ -213,6 +214,7 @@ exit 0
`
const fakeCheck = `#!/bin/sh
+echo "CHECK $*" >> "$FAKE_TOFU/calls.log"
for a in "$@"; do last="$a"; done
[ -f "$FAKE_TOFU/tamper" ] && echo tampered >> "${last%.plan.json}.tfplan"
[ -f "$FAKE_TOFU/refuse" ] && exit 1
diff --git a/internal/hostedops/singleton.go b/internal/hostedops/singleton.go
index 485324fc..ce5bcb1e 100644
--- a/internal/hostedops/singleton.go
+++ b/internal/hostedops/singleton.go
@@ -6,6 +6,7 @@ import (
"flag"
"fmt"
"net/url"
+ "regexp"
"slices"
"strings"
"time"
@@ -156,8 +157,12 @@ func TrustRequiresMFA(doc string) (bool, string) {
if json.Unmarshal(st["Effect"], &effect) != nil {
return false, fmt.Sprintf("statement %d has no Effect", i)
}
- if effect != "Allow" {
+ switch effect {
+ case "Deny":
continue
+ case "Allow":
+ default: // IAM knows only Allow and Deny: an unclassifiable statement fails closed (N4)
+ return false, fmt.Sprintf("statement %d has Effect %q", i, effect)
}
if _, bad := st["NotAction"]; bad {
return false, fmt.Sprintf("statement %d uses NotAction", i)
@@ -175,8 +180,11 @@ func TrustRequiresMFA(doc string) (bool, string) {
}
assume := false
for _, a := range actions {
- if a == "*" || a == "sts:*" || strings.HasPrefix(a, "sts:AssumeRole") {
- assume = true
+ if a != "*" && !strings.Contains(a, ":") {
+ return false, fmt.Sprintf("statement %d has an action %q IAM would not read", i, a)
+ }
+ for _, verb := range assumeActions {
+ assume = assume || iamMatch(a, verb)
}
}
if !assume {
@@ -194,6 +202,29 @@ func TrustRequiresMFA(doc string) (bool, string) {
return true, ""
}
+// assumeActions are the actions that assume a role.
+var assumeActions = []string{"sts:AssumeRole", "sts:AssumeRoleWithSAML", "sts:AssumeRoleWithWebIdentity"}
+
+// iamMatch matches an IAM action pattern as IAM does (N4):
+// case-insensitive, * any run of characters, ? any one.
+func iamMatch(pattern, action string) bool {
+ var re strings.Builder
+ re.WriteString("^")
+ for _, r := range strings.ToLower(pattern) {
+ switch r {
+ case '*':
+ re.WriteString(".*")
+ case '?':
+ re.WriteString(".")
+ default:
+ re.WriteString(regexp.QuoteMeta(string(r)))
+ }
+ }
+ re.WriteString("$")
+ ok, err := regexp.MatchString(re.String(), strings.ToLower(action))
+ return err == nil && ok
+}
+
func mfaTrue(v json.RawMessage) bool {
var s string
if json.Unmarshal(v, &s) == nil {
@@ -269,7 +300,8 @@ func (o *Ops) fence() error {
if !strings.HasSuffix(in.Name, "aws_instance.controller") {
continue
}
- res, err := o.cloud.Lookup(o.ctx, LookupKey{Type: "aws_instance", NameTag: in.Attr("nametag"), Run: o.Run, Parent: in.Attr("parent")})
+ res, err := o.cloud.Lookup(o.ctx, LookupKey{Type: "aws_instance", NameTag: in.Attr("nametag"), Run: o.Run, Parent: in.Attr("parent"),
+ Accounted: accounted(l, "aws_instance")})
switch {
case err != nil:
problems = append(problems, fmt.Sprintf("the controller intent %s could not be looked up: %v", in.Name, err))
diff --git a/internal/hostedops/stop.go b/internal/hostedops/stop.go
index e9f025ad..28e1a06d 100644
--- a/internal/hostedops/stop.go
+++ b/internal/hostedops/stop.go
@@ -31,9 +31,9 @@ func cmdBlock(o *Ops, args []string) error {
}
hard := func(why string) error {
_ = o.jw("ABORT", "block %s: %s", id, why)
- o.out("ABORT: block %s: %s; running safe-stop", id, why)
- if err := o.safeStop(); err != nil {
- o.out("safe-stop: %v", err)
+ o.out("ABORT: block %s: %s; asking for recovery", id, why)
+ if err := o.requestRecovery(); err != nil {
+ o.out("recovery: %v", err)
}
return stopf("block %s: %s", id, why)
}
@@ -91,10 +91,78 @@ func runChild(ctx context.Context, argv, env []string, stdout, stderr io.Writer)
// SafeStopBound bounds one safe stop, whatever the invocation's context.
const SafeStopBound = 30 * time.Minute
+// RecoveryBlock names the one recovery unit, h<env>-<RUN>-recovery.
+const RecoveryBlock = "recovery"
+
+// cmdSafeStop asks for recovery (N1): one dedicated unit runs section S's
+// steps, outside every block and watchdog unit, and every requester (an
+// operator, a failed block, a watchdog) waits for it. --recovery is that
+// unit's own command.
func cmdSafeStop(o *Ops, args []string) error {
- if len(args) != 0 {
+ switch {
+ case len(args) == 1 && args[0] == "--recovery":
+ return o.recover()
+ case len(args) != 0:
return usagef("safe-stop takes no arguments")
}
+ return o.requestRecovery()
+}
+
+// requestRecovery starts the recovery unit unless it is already running,
+// then waits for it, under a context no interruption cancels. Its result
+// is the recovery's.
+func (o *Ops) requestRecovery() error {
+ outer := o.ctx
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(outer), SafeStopBound+5*time.Minute)
+ o.ctx = ctx
+ defer func() { cancel(); o.ctx = outer }()
+ u := o.unitName(RecoveryBlock)
+ if o.selfUnit() == u {
+ return o.recover()
+ }
+ if o.Systemd.State(u) == "running" {
+ _ = o.jw("RECOVERY", "requested; %s is already running", u)
+ } else {
+ _ = o.jw("RECOVERY", "requested; starting %s", u)
+ if err := o.startUnit(RecoveryBlock, o.selfArgv("safe-stop", "--recovery"), SafeStopBound+5*time.Minute, true); err != nil {
+ return stopf("the recovery unit did not start: %v", err)
+ }
+ }
+ end := o.Clock.Now().Add(SafeStopBound + 5*time.Minute)
+ for {
+ switch o.Systemd.State(u) {
+ case "done":
+ st, _ := os.ReadFile(o.path("units", RecoveryBlock+".status"))
+ status := strings.TrimSpace(string(st))
+ if status == "0" {
+ o.out("recovery done; the run waits for Paul")
+ return nil
+ }
+ return stopf("recovery ended with status %s; waiting for Paul", status)
+ case "unresolved":
+ return stopf("the recovery unit's state cannot be established")
+ }
+ if err := o.Clock.Sleep(o.ctx, 5*time.Second); err != nil || !o.Clock.Now().Before(end) {
+ return stopf("recovery did not finish within %s; it runs on in %s", SafeStopBound+5*time.Minute, u)
+ }
+ }
+}
+
+// recover is the recovery unit's work: section S under an exclusive lock;
+// a second holder stands aside.
+func (o *Ops) recover() error {
+ if err := os.MkdirAll(o.path(o.Run), 0o700); err != nil {
+ return failf("%v", err)
+ }
+ release, held, err := tryLock(o.path(o.Run, "recovery.lock"))
+ switch {
+ case err != nil:
+ return stopf("the recovery lock: %v", err)
+ case held:
+ o.out("recovery already owned")
+ return o.jw("RECOVERY", "already owned; standing aside")
+ }
+ defer release()
return o.safeStop()
}
@@ -159,6 +227,7 @@ func (o *Ops) safeStop() error {
// and settle again (F5).
if fenceErr != nil || o.knownResources() != before {
note("S.4 fence again", o.fence())
+ settled = map[string]bool{} // the new fence invalidates every earlier proof (N3)
settleAll()
}
}
diff --git a/internal/hostedops/tf.go b/internal/hostedops/tf.go
index 1f6de866..3c3aea39 100644
--- a/internal/hostedops/tf.go
+++ b/internal/hostedops/tf.go
@@ -249,7 +249,7 @@ func cmdTf(o *Ops, args []string) error {
if err := o.tofuInit(root, dir); err != nil {
return err
}
- if err := o.importAdopted(root, dir, vars); err != nil {
+ if err := o.adoptPending(root, dir, vars); err != nil {
return err
}
td := o.path("tf")
@@ -541,18 +541,27 @@ func (o *Ops) tfReconcile(root string) error {
}
continue
}
+ if p := in.Attr("parent"); p != "" && parentDeleted(l, p) {
+ // The parent's verified deletion took its children with it (N2).
+ if err := o.jw("NOTCREATED", "tf %s parent-deleted %s", in.Name, p); err != nil {
+ return err
+ }
+ continue
+ }
res, err := o.cloud.Lookup(o.ctx, LookupKey{Type: in.Attr("type"), Name: in.Attr("name"), Run: o.Run,
- NameTag: in.Attr("nametag"), Parent: in.Attr("parent"), Token: in.Token})
+ NameTag: in.Attr("nametag"), Parent: in.Attr("parent"), Token: in.Token, Accounted: accounted(l, in.Attr("type"))})
switch {
case err != nil:
left = append(left, in.Name)
_ = o.finding("tf reconcile %s: the direct read failed: %v", in.Name, err)
case len(res.IDs) == 1:
id := res.IDs[0]
- if err := o.rec("tf", in.Name, "id="+id, "type="+in.Attr("type"), "source=outside-state"); err != nil {
+ // The adoption is durable before the discovery resolves the
+ // intent (N6): a crash between them leaves work to resume.
+ if err := o.adopt(root, in.Name, id); err != nil {
return err
}
- if err := o.adopt(root, in.Name, id); err != nil {
+ if err := o.rec("tf", in.Name, "id="+id, "type="+in.Attr("type"), "source=outside-state"); err != nil {
return err
}
case len(res.IDs) > 1:
@@ -672,79 +681,211 @@ func cmdLedgerReconcile(o *Ops, args []string) error {
return o.reconcileLedger()
}
+// parentDeleted reports whether the ledger holds a verified deletion of
+// the resource whose ID is id.
+func parentDeleted(l *Ledger, id string) bool {
+ for _, r := range l.Recorded("tf") {
+ if r.Attr("id") == id && l.Deleted["tf "+r.Value] {
+ return true
+ }
+ }
+ return false
+}
+
+// accounted are the IDs of typ the ledger already holds.
+func accounted(l *Ledger, typ string) []string {
+ var ids []string
+ for _, r := range l.Recorded("tf") {
+ if r.Attr("type") == typ && r.Attr("id") != "" {
+ ids = append(ids, r.Attr("id"))
+ }
+ }
+ return ids
+}
+
// importsFile is a root's run-local import blocks (F15): the run's own
// worktree of the release, never the repository's tree.
func (o *Ops) importsFile(dir string) string { return filepath.Join(dir, "ops_imports_"+o.Run+".tf") }
// adopt records a resource tf reconcile found outside state (ADOPT) and
-// writes the root's import blocks, so the next tf ROOT PHASE imports it and
-// the normal plan, plan-check and apply (or destroy) path handles it.
+// writes the root's import blocks; the next tf ROOT PHASE imports it
+// through a checked plan (adoptPending) before its own plan.
func (o *Ops) adopt(root, name, id string) error {
if err := o.jw("ADOPT", "%s %s", name, id); err != nil {
return err
}
- if err := o.finding("tf reconcile: %s exists as %s outside state; adopted by an import block, removed by the next destroy", name, id); err != nil {
+ if err := o.finding("tf reconcile: %s exists as %s outside state; adopted by an import block, imported by the next ops tf through a checked plan", name, id); err != nil {
return err
}
- return o.writeImports(root)
+ return o.writeImports(root, nil)
}
-// pendingImports are root's adoptions not yet imported, address to ID.
+// pendingImports are root's adoptions not yet imported, address to ID,
+// rebuilt from the durable records (N6): each ADOPT, and each record of a
+// resource found outside state (a crash may have come before its ADOPT),
+// less each IMPORTED.
func (o *Ops) pendingImports(root string) ([][2]string, error) {
l, err := o.ledger()
if err != nil {
return nil, err
}
- done := map[string]bool{}
- var out [][2]string
- for i := len(l.Entries) - 1; i >= 0; i-- {
- e := l.Entries[i]
- addr, ok := strings.CutPrefix(e.Field(0), root+"/")
- if !ok || done[addr] {
+ ids := map[string]string{}
+ var order []string
+ for _, e := range l.Entries {
+ var addr, id string
+ var ok bool
+ switch {
+ case e.Verb == "ADOPT":
+ addr, ok = strings.CutPrefix(e.Field(0), root+"/")
+ id = e.Field(1)
+ case e.Verb == "REC" && e.Field(0) == "tf" && e.Attr("source") == "outside-state":
+ addr, ok = strings.CutPrefix(e.Field(1), root+"/")
+ id = e.Attr("id")
+ case e.Verb == "IMPORTED":
+ if a, found := strings.CutPrefix(e.Field(0), root+"/"); found {
+ delete(ids, a)
+ }
+ continue
+ default:
continue
}
- switch e.Verb {
- case "IMPORTED":
- done[addr] = true
- case "ADOPT":
- done[addr] = true
- out = append(out, [2]string{addr, e.Field(1)})
+ if !ok || id == "" {
+ continue
+ }
+ if _, seen := ids[addr]; !seen {
+ order = append(order, addr)
+ }
+ ids[addr] = id
+ }
+ var out [][2]string
+ for _, a := range order {
+ if id, ok := ids[a]; ok {
+ out = append(out, [2]string{a, id})
}
}
return out, nil
}
-func (o *Ops) writeImports(root string) error {
- pend, err := o.pendingImports(root)
- if err != nil {
- return err
+func (o *Ops) writeImports(root string, only [][2]string) error {
+ pend := only
+ if pend == nil {
+ var err error
+ if pend, err = o.pendingImports(root); err != nil {
+ return err
+ }
}
var b strings.Builder
- b.WriteString("# Written by equipo-hosted-ops tf reconcile: resources this run created outside\n# OpenTofu's state, adopted here and imported by the next ops tf.\n")
+ b.WriteString("# Written by equipo-hosted-ops: resources this run created outside OpenTofu's\n# state, adopted here and imported by a checked plan.\n")
for _, p := range pend {
fmt.Fprintf(&b, "\nimport {\n to = %s\n id = %q\n}\n", p[0], p[1])
}
return writeFileAtomic(o.importsFile(o.rootDir(root)), []byte(b.String()), 0o600)
}
-// importAdopted imports each pending adoption into state with tofu import
-// (state only; no resource changes), then removes the import file before
-// the plan, so plan-check reads the release's root unchanged.
-func (o *Ops) importAdopted(root, dir, vars string) error {
+// adoptPending imports the root's pending adoptions through the normal
+// path (N6, as F15 rules): state is read first and an address it already
+// manages is recorded IMPORTED, not imported again; the rest go in the
+// run-local import blocks, and a plan targeting exactly them is checked by
+// plan-check --adopt (imports of those IDs, each with no change), verified
+// again and applied. The import file is removed before the phase's own
+// plan.
+func (o *Ops) adoptPending(root, dir, vars string) error {
pend, err := o.pendingImports(root)
if err != nil {
return err
}
+ clear := func() error {
+ if err := os.Remove(o.importsFile(dir)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return failf("%v", err)
+ }
+ return nil
+ }
+ if len(pend) == 0 {
+ return clear()
+ }
+ listed, err := o.tofu("-chdir="+dir, "state", "list", "-no-color")
+ if err != nil {
+ return failf("%v", err)
+ }
+ managed := map[string]bool{}
+ for _, a := range strings.Fields(string(listed)) {
+ managed[a] = true
+ }
+ var todo [][2]string
for _, p := range pend {
- if _, err := o.tofu("-chdir="+dir, "import", "-input=false", "-no-color", "-var-file="+vars, "-var=run="+o.Run, p[0], p[1]); err != nil {
- return stopf("importing the adopted %s (%s) failed: %v", p[0], p[1], err)
+ if managed[p[0]] {
+ if err := o.jw("IMPORTED", "%s/%s %s state-read", root, p[0], p[1]); err != nil {
+ return err
+ }
+ continue
}
- if err := o.jw("IMPORTED", "%s/%s %s", root, p[0], p[1]); err != nil {
+ todo = append(todo, p)
+ }
+ if len(todo) == 0 {
+ return clear()
+ }
+ if err := o.writeImports(root, todo); err != nil {
+ return err
+ }
+ base := root
+ if o.env() == "dev" {
+ base = "dev-" + root
+ }
+ td := o.path("tf")
+ if err := os.MkdirAll(td, 0o700); err != nil {
+ return failf("%v", err)
+ }
+ planFile := filepath.Join(td, "adopt-"+root+".tfplan")
+ _ = os.Remove(planFile)
+ args := []string{"-chdir=" + dir, "plan", "-input=false", "-no-color", "-out=" + planFile, "-var-file=" + vars, "-var=run=" + o.Run}
+ adopt := map[string]string{}
+ for _, p := range todo {
+ args = append(args, "-target="+p[0])
+ adopt[p[0]] = p[1]
+ }
+ if _, err := o.tofu(args...); err != nil {
+ return failf("%v", err)
+ }
+ js, err := o.tofu("-chdir="+dir, "show", "-json", "-no-color", planFile)
+ if err != nil {
+ return failf("%v", err)
+ }
+ planJSON := filepath.Join(td, "adopt-"+root+".plan.json")
+ adoptJSON := filepath.Join(td, "adopt-"+root+".json")
+ ab, _ := json.Marshal(adopt)
+ if err := writeFileAtomic(planJSON, js, 0o600); err != nil {
+ return failf("%v", err)
+ }
+ if err := writeFileAtomic(adoptJSON, ab, 0o600); err != nil {
+ return failf("%v", err)
+ }
+ checked, err := fileHash(planFile)
+ if err != nil {
+ return failf("%v", err)
+ }
+ pc := append(append([]string{}, o.PlanCheck...), "--phase", base, "--account", o.Account, "--region", o.Region, "--adopt", adoptJSON, planJSON)
+ cmd := exec.CommandContext(o.ctx, pc[0], pc[1:]...)
+ cmd.Stdout, cmd.Stderr = o.Stdout, o.Stderr
+ if err := cmd.Run(); err != nil {
+ _ = o.jw("ABORT", "plan-check refused the adoption plan of %s: %v", root, err)
+ return stopf("plan-check.py refused the adoption plan (%v); nothing imported", err)
+ }
+ if err := o.cloud.Reverify(o.ctx); err != nil {
+ if IsStop(err) {
return err
}
+ return stopf("the credentials could not be verified again before the import: %v", err)
}
- if err := os.Remove(o.importsFile(dir)); err != nil && !errors.Is(err, os.ErrNotExist) {
- return failf("%v", err)
+ if now, err := fileHash(planFile); err != nil || now != checked {
+ return stopf("the saved adoption plan is not the one plan-check accepted; nothing imported")
}
- return nil
+ if _, err := o.tofu("-chdir="+dir, "apply", "-input=false", "-no-color", planFile); err != nil {
+ return stopf("the adoption apply failed: %v; tf %s again reads state before retrying", err, root)
+ }
+ for _, p := range todo {
+ if err := o.jw("IMPORTED", "%s/%s %s checked-plan", root, p[0], p[1]); err != nil {
+ return err
+ }
+ }
+ return clear()
}
diff --git a/internal/hostedops/units.go b/internal/hostedops/units.go
index 60ae62ad..1bf4df05 100644
--- a/internal/hostedops/units.go
+++ b/internal/hostedops/units.go
@@ -9,6 +9,7 @@ import (
"io"
"os"
"os/exec"
+ "path"
"regexp"
"slices"
"strconv"
@@ -26,7 +27,7 @@ import (
type Systemd interface {
// Start runs argv as unit, output appended to out, its exit status
// written to status by exitpost (ExecStopPost).
- Start(unit, workdir, out, status, exitpost string, argv []string) error
+ Start(unit, workdir, out, status, exitpost string, stopTimeout time.Duration, argv []string) error
// State is running, done or unresolved (R44's unit_state).
State(unit string) string
// Stop stops unit (TERM, KILL after 45 s) and waits for done.
@@ -82,7 +83,7 @@ func cmdUnitStart(o *Ops, args []string) error {
if b := o.busy(l, ""); len(b) > 0 {
return failf("REFUSED: a block is not finished: %s", strings.Join(b, ", "))
}
- if err := o.startUnit(args[0], args[2:]); err != nil {
+ if err := o.startUnit(args[0], args[2:], 45*time.Second, false); err != nil {
return err
}
o.out("block %s started as unit %s", args[0], o.unitName(args[0]))
@@ -92,7 +93,7 @@ func cmdUnitStart(o *Ops, args []string) error {
// startUnit journals the unit's name, then runs argv as the transient user
// unit for block, under /usr/bin/env -i with the allowlist and the unit's
// own name (EQUIPO_HOSTED_OPS_UNIT, so a safe-stop inside it can spare it).
-func (o *Ops) startUnit(block string, argv []string) error {
+func (o *Ops) startUnit(block string, argv []string, stopTimeout time.Duration, again bool) error {
if strings.ContainsAny(o.Dir, " \t\n\"'\\$") {
return failf("the run directory has characters a systemd command line could misread")
}
@@ -101,9 +102,10 @@ func (o *Ops) startUnit(block string, argv []string) error {
return err
}
u := o.unitName(block)
- if slices.Contains(l.Units, u) {
+ if slices.Contains(l.Units, u) && !(again && o.Systemd.State(u) == "done") {
return failf("block %s was already started as %s", block, u)
}
+ _ = os.Remove(o.path("units", block+".status"))
ep := o.path("bin", "exitpost.sh")
if err := writeFileAtomic(ep, []byte(exitPost), 0o755); err != nil {
return failf("%v", err)
@@ -117,7 +119,7 @@ func (o *Ops) startUnit(block string, argv []string) error {
full = append(full, v+"="+val)
}
}
- full = append(full, "EQUIPO_HOSTED_OPS_BLOCK="+block, "EQUIPO_HOSTED_OPS_UNIT="+u)
+ full = append(full, "EQUIPO_HOSTED_OPS_BLOCK="+block)
full = append(full, argv...)
if err := o.jw("UNIT", "%s", u); err != nil { // journalled before systemd-run (R45)
return err
@@ -125,7 +127,7 @@ func (o *Ops) startUnit(block string, argv []string) error {
if err := writeFileAtomic(o.path("units", block+".start"), []byte(strconv.FormatInt(o.Clock.Now().Unix(), 10)+"\n"), 0o600); err != nil {
return failf("%v", err)
}
- if err := o.Systemd.Start(u, o.Dir, o.path("units", block+".out"), o.path("units", block+".status"), ep, full); err != nil {
+ if err := o.Systemd.Start(u, o.Dir, o.path("units", block+".out"), o.path("units", block+".status"), ep, stopTimeout, full); err != nil {
return failf("systemd-run could not start %s: %v", u, err)
}
return nil
@@ -175,9 +177,9 @@ func cmdUnitWait(o *Ops, args []string) error {
start := time.Unix(sec, 0)
hard := func(why string) error {
_ = o.jw("ABORT", "unit %s: %s", u, why)
- o.out("ABORT: block %s: %s; running safe-stop", block, why)
- if err := o.safeStop(); err != nil {
- o.out("safe-stop: %v", err)
+ o.out("ABORT: block %s: %s; asking for recovery", block, why)
+ if err := o.requestRecovery(); err != nil {
+ o.out("recovery: %v", err)
}
return stopf("block %s: %s", block, why)
}
@@ -219,12 +221,12 @@ func (o *Ops) stopUnits(only string) error {
return err
}
var failed []string
- own := os.Getenv("EQUIPO_HOSTED_OPS_UNIT")
+ own := o.selfUnit()
for _, u := range l.Units {
if only != "" && u != only {
continue
}
- if u == own { // never the unit this process runs in (F2); it ends when this does
+ if u == own || (only == "" && u == o.unitName(RecoveryBlock)) { // never the recovery unit, nor this process's own (N1)
if err := o.jw("UNIT-SPARED", "%s: this process runs in it", u); err != nil {
return err
}
@@ -284,11 +286,11 @@ func sc(args ...string) (string, error) {
return out.String(), err
}
-func (realSystemd) Start(unit, workdir, out, status, exitpost string, argv []string) error {
+func (realSystemd) Start(unit, workdir, out, status, exitpost string, stopTimeout time.Duration, argv []string) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
args := []string{"--user", "--quiet", "--collect", "--expand-environment=no", "--unit=" + unit,
- "-p", "KillMode=control-group", "-p", "TimeoutStopSec=45", "-p", "WorkingDirectory=" + workdir,
+ "-p", "KillMode=control-group", "-p", fmt.Sprintf("TimeoutStopSec=%d", int(stopTimeout.Seconds())), "-p", "WorkingDirectory=" + workdir,
"-p", "StandardInput=null", "-p", "StandardOutput=append:" + out, "-p", "StandardError=append:" + out,
"-p", "ExecStopPost=" + exitpost + " " + status, "--"}
cmd := exec.CommandContext(ctx, "systemd-run", append(args, argv...)...)
@@ -394,7 +396,7 @@ func cmdUnitProbe(o *Ops, args []string) error {
u := o.unitName(block)
envFile := o.path("units", block+".env")
_ = os.Remove(envFile)
- if err := o.startUnit(block, []string{"/bin/sh", "-c", `env > "$0"; exec sleep 60`, envFile}); err != nil {
+ if err := o.startUnit(block, []string{"/bin/sh", "-c", `env > "$0"; exec sleep 60`, envFile}, 45*time.Second, false); err != nil {
return err
}
fail := func(why string) error {
@@ -437,3 +439,34 @@ func cmdUnitProbe(o *Ops, args []string) error {
o.out("unit probe: %s ran with only allowlisted names and stopped by TERM", u)
return o.jw("UNIT-PROBE", "ok %s", u)
}
+
+// unitFromCgroup is the service unit /proc/self/cgroup's content places
+// this process in, under systemd (INVOCATION_ID set); "" otherwise (N1).
+func unitFromCgroup(cgroup, invocation string) string {
+ if invocation == "" {
+ return ""
+ }
+ for _, line := range strings.Split(strings.TrimSpace(cgroup), "\n") {
+ i := strings.LastIndex(line, ":")
+ if i < 0 {
+ continue
+ }
+ base := path.Base(line[i+1:])
+ if strings.HasSuffix(base, ".service") {
+ return base
+ }
+ }
+ return ""
+}
+
+// selfUnit is the unit this process runs in, or "".
+func (o *Ops) selfUnit() string {
+ if o.SelfUnit != nil {
+ return o.SelfUnit()
+ }
+ b, err := os.ReadFile("/proc/self/cgroup")
+ if err != nil {
+ return ""
+ }
+ return unitFromCgroup(string(b), os.Getenv("INVOCATION_ID"))
+}
diff --git a/internal/isolatedjob/awsjob/opsaws/cloud.go b/internal/isolatedjob/awsjob/opsaws/cloud.go
index 3f0ff36a..87f4e93f 100644
--- a/internal/isolatedjob/awsjob/opsaws/cloud.go
+++ b/internal/isolatedjob/awsjob/opsaws/cloud.go
@@ -527,15 +527,23 @@ func (c *cloud) Network(ctx context.Context, ids hostedops.NetworkIDs) (hostedop
}
}
routes := func(filter ec2types.Filter) ([]hostedops.Route, error) {
- r, err := c.cl.ec2.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{Filters: []ec2types.Filter{filter}})
- if err != nil {
- return nil, fmt.Errorf("DescribeRouteTables: %w", err)
+ var tables []ec2types.RouteTable
+ p := ec2.NewDescribeRouteTablesPaginator(c.cl.ec2, &ec2.DescribeRouteTablesInput{Filters: []ec2types.Filter{filter}})
+ for n := 0; p.HasMorePages(); n++ {
+ if n >= maxPages {
+ return nil, errors.New("DescribeRouteTables: too many pages")
+ }
+ r, err := p.NextPage(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("DescribeRouteTables: %w", err)
+ }
+ tables = append(tables, r.RouteTables...)
}
- if len(r.RouteTables) != 1 {
- return nil, fmt.Errorf("DescribeRouteTables: %d tables, want one", len(r.RouteTables))
+ if len(tables) != 1 {
+ return nil, fmt.Errorf("DescribeRouteTables: %d tables, want one", len(tables))
}
var out []hostedops.Route
- for _, rt := range r.RouteTables[0].Routes {
+ for _, rt := range tables[0].Routes {
t := aws.ToString(rt.GatewayId)
if p := aws.ToString(rt.VpcPeeringConnectionId); p != "" {
t = p
@@ -554,18 +562,24 @@ func (c *cloud) Network(ctx context.Context, ids hostedops.NetworkIDs) (hostedop
if f.ServicesRoutes, err = routes(ec2types.Filter{Name: aws.String("route-table-id"), Values: []string{ids.ServicesRouteTable}}); err != nil {
return f, err
}
- rules, err := c.cl.ec2.DescribeSecurityGroupRules(ctx, &ec2.DescribeSecurityGroupRulesInput{
+ rp := ec2.NewDescribeSecurityGroupRulesPaginator(c.cl.ec2, &ec2.DescribeSecurityGroupRulesInput{
Filters: []ec2types.Filter{{Name: aws.String("group-id"), Values: []string{ids.VMSecurityGroup}}}})
- if err != nil {
- return f, fmt.Errorf("DescribeSecurityGroupRules: %w", err)
- }
- for _, r := range rules.SecurityGroupRules {
- cidr := aws.ToString(r.CidrIpv4) + aws.ToString(r.CidrIpv6) + aws.ToString(r.PrefixListId)
- if r.ReferencedGroupInfo != nil {
- cidr += "group:" + aws.ToString(r.ReferencedGroupInfo.GroupId)
+ for n := 0; rp.HasMorePages(); n++ {
+ if n >= maxPages {
+ return f, errors.New("DescribeSecurityGroupRules: too many pages")
+ }
+ rules, err := rp.NextPage(ctx)
+ if err != nil {
+ return f, fmt.Errorf("DescribeSecurityGroupRules: %w", err)
+ }
+ for _, r := range rules.SecurityGroupRules {
+ cidr := aws.ToString(r.CidrIpv4) + aws.ToString(r.CidrIpv6) + aws.ToString(r.PrefixListId)
+ if r.ReferencedGroupInfo != nil {
+ cidr += "group:" + aws.ToString(r.ReferencedGroupInfo.GroupId)
+ }
+ f.VMSGRules = append(f.VMSGRules, hostedops.SGRule{Egress: aws.ToBool(r.IsEgress), Protocol: aws.ToString(r.IpProtocol),
+ FromPort: aws.ToInt32(r.FromPort), ToPort: aws.ToInt32(r.ToPort), CIDR: cidr})
}
- f.VMSGRules = append(f.VMSGRules, hostedops.SGRule{Egress: aws.ToBool(r.IsEgress), Protocol: aws.ToString(r.IpProtocol),
- FromPort: aws.ToInt32(r.FromPort), ToPort: aws.ToInt32(r.ToPort), CIDR: cidr})
}
p, err := c.cl.ec2.DescribeVpcPeeringConnections(ctx, &ec2.DescribeVpcPeeringConnectionsInput{VpcPeeringConnectionIds: []string{ids.Peering}})
if err != nil {
diff --git a/internal/isolatedjob/awsjob/opsaws/fix1_test.go b/internal/isolatedjob/awsjob/opsaws/fix1_test.go
index b9cee497..9e17c558 100644
--- a/internal/isolatedjob/awsjob/opsaws/fix1_test.go
+++ b/internal/isolatedjob/awsjob/opsaws/fix1_test.go
@@ -85,7 +85,7 @@ func TestLookupMatchesIdentity(t *testing.T) {
out := &ec2.DescribeVpcsOutput{}
if page < len(ids) {
id := ids[page]
- if fl["tag:Name"] == vpcs[id] && fl["tag:run"] == "r1" {
+ if (fl["tag:Name"] == "" || fl["tag:Name"] == vpcs[id]) && (fl["tag:run"] == "" || fl["tag:run"] == "r1") {
out.Vpcs = []ec2types.Vpc{{VpcId: aws.String(id), Tags: tagged(vpcs[id], "r1")}}
}
if page+1 < len(ids) {
@@ -103,8 +103,10 @@ func TestLookupMatchesIdentity(t *testing.T) {
t.Fatalf("filters %v", fl)
}
delete(vpcs, "vpc-0vm") // partial creation: only the services VPC exists
- if res, err := cl.Lookup(ctx, hostedops.LookupKey{Type: "aws_vpc", NameTag: "equipo-hosted-vm", Run: "r1"}); err != nil || len(res.IDs) != 0 || !res.Definitive {
- t.Fatalf("lookup after a partial creation = %+v, %v; want a definitive miss", res, err)
+ // A filtered miss is not proof (round 2, N2), and a VPC records no
+ // parent to list under: the intent stays unresolved.
+ if res, err := cl.Lookup(ctx, hostedops.LookupKey{Type: "aws_vpc", NameTag: "equipo-hosted-vm", Run: "r1"}); err != nil || len(res.IDs) != 0 || res.Definitive {
+ t.Fatalf("lookup after a partial creation = %+v, %v; want a miss that is not definitive", res, err)
}
before := len(f.ops())
if res, _ := cl.Lookup(ctx, hostedops.LookupKey{Type: "aws_vpc", Run: "r1"}); res.Definitive || len(res.IDs) != 0 {
diff --git a/internal/isolatedjob/awsjob/opsaws/fix2_test.go b/internal/isolatedjob/awsjob/opsaws/fix2_test.go
new file mode 100644
index 00000000..e7bd6d76
--- /dev/null
+++ b/internal/isolatedjob/awsjob/opsaws/fix2_test.go
@@ -0,0 +1,279 @@
+package opsaws
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "slices"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/hostedops"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/budgets"
+ budgettypes "github.com/aws/aws-sdk-go-v2/service/budgets/types"
+ "github.com/aws/aws-sdk-go-v2/service/cloudtrail"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+ "github.com/aws/aws-sdk-go-v2/service/iam"
+ "github.com/aws/aws-sdk-go-v2/service/lambdacore"
+ vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ vmtypes "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+ tagging "github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi"
+ tagtypes "github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi/types"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
+)
+
+// Fix round 2: written and seen failing before the fixes.
+
+// N2: a fully identified intent whose resource survives untagged under its
+// parent stays unresolved; an unfiltered listing under the parent that
+// finds only resources the ledger accounts for is a definitive miss.
+func TestUntaggedSurvivorStaysUnresolved(t *testing.T) {
+ under := []string{"subnet-0untagged"}
+ var calls []map[string]string
+ cl, _ := openFake(t, func(c call) (any, error) {
+ in, ok := c.In.(*ec2.DescribeSubnetsInput)
+ if !ok {
+ return nil, fmt.Errorf("unexpected %s", c.Op)
+ }
+ fl := filters(in.Filters)
+ calls = append(calls, fl)
+ if fl["tag:Name"] != "" { // the survivor carries no tags
+ return &ec2.DescribeSubnetsOutput{}, nil
+ }
+ var out []ec2types.Subnet
+ for _, id := range under {
+ out = append(out, ec2types.Subnet{SubnetId: aws.String(id)})
+ }
+ return &ec2.DescribeSubnetsOutput{Subnets: out}, nil
+ })
+ k := hostedops.LookupKey{Type: "aws_subnet", NameTag: "equipo-hosted-vm", Run: "r1", Parent: "vpc-0vm"}
+ res, err := cl.Lookup(context.Background(), k)
+ if err != nil || res.Definitive {
+ t.Fatalf("an untagged survivor under the parent read as %+v, %v; want not definitive", res, err)
+ }
+ if len(calls) != 2 || calls[1]["vpc-id"] != "vpc-0vm" || calls[1]["tag:Name"] != "" {
+ t.Fatalf("calls %v; want the filtered listing, then every subnet in the parent VPC", calls)
+ }
+ k.Accounted = []string{"subnet-0untagged"}
+ if res, err := cl.Lookup(context.Background(), k); err != nil || !res.Definitive || len(res.IDs) != 0 {
+ t.Fatalf("with every subnet accounted for: %+v, %v; want a definitive miss", res, err)
+ }
+ k.Parent, k.Accounted = "", nil // no parent recorded: no listing can prove absence
+ if res, _ := cl.Lookup(context.Background(), k); res.Definitive {
+ t.Fatal("a miss with no recorded parent was definitive")
+ }
+}
+
+// Round 2 extras: argument shapes, connector delete, Network's and every
+// listing's pagination.
+func TestSDKShapesAndPages(t *testing.T) {
+ ctx := context.Background()
+ two := func(tok *string) (bool, *string) { // first page?, next token
+ if tok == nil {
+ return true, aws.String("p2")
+ }
+ return false, nil
+ }
+ t.Run("trail arguments", func(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch in := c.In.(type) {
+ case *cloudtrail.GetTrailStatusInput:
+ if aws.ToString(in.Name) != "equipo-hosted" {
+ t.Errorf("status of %q", aws.ToString(in.Name))
+ }
+ return &cloudtrail.GetTrailStatusOutput{IsLogging: aws.Bool(true)}, nil
+ case *cloudtrail.GetEventSelectorsInput:
+ if aws.ToString(in.TrailName) != "equipo-hosted" {
+ t.Errorf("selectors of %q", aws.ToString(in.TrailName))
+ }
+ return &cloudtrail.GetEventSelectorsOutput{}, nil
+ case *cloudtrail.StopLoggingInput:
+ if aws.ToString(in.Name) != "equipo-hosted" {
+ t.Errorf("stop of %q", aws.ToString(in.Name))
+ }
+ return &cloudtrail.StopLoggingOutput{}, nil
+ }
+ return nil, fmt.Errorf("unexpected %s", c.Op)
+ })
+ if _, err := cl.Trail(ctx, "equipo-hosted"); err != nil {
+ t.Fatal(err)
+ }
+ if err := cl.StopTrailLogging(ctx, "equipo-hosted"); err != nil {
+ t.Fatal(err)
+ }
+ })
+ t.Run("connector delete and IAM attach", func(t *testing.T) {
+ var deleted, attached string
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch in := c.In.(type) {
+ case *lambdacore.DeleteNetworkConnectorInput:
+ deleted = aws.ToString(in.Identifier)
+ return &lambdacore.DeleteNetworkConnectorOutput{}, nil
+ case *iam.AttachRolePolicyInput:
+ attached = aws.ToString(in.RoleName) + " " + aws.ToString(in.PolicyArn)
+ return &iam.AttachRolePolicyOutput{}, nil
+ }
+ return nil, fmt.Errorf("unexpected %s", c.Op)
+ })
+ if err := cl.DeleteConnector(ctx, "arn:c"); err != nil || deleted != "arn:c" {
+ t.Fatalf("delete %q %v", deleted, err)
+ }
+ if err := cl.AttachRolePolicy(ctx, "r", "arn:deny"); err != nil || attached != "r arn:deny" {
+ t.Fatalf("attach %q %v", attached, err)
+ }
+ })
+ t.Run("network pages", func(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch in := c.In.(type) {
+ case *ec2.DescribeVpcAttributeInput:
+ f := &ec2types.AttributeBooleanValue{Value: aws.Bool(false)}
+ return &ec2.DescribeVpcAttributeOutput{EnableDnsSupport: f, EnableDnsHostnames: f}, nil
+ case *ec2.DescribeRouteTablesInput:
+ first, next := two(in.NextToken)
+ if first {
+ return &ec2.DescribeRouteTablesOutput{NextToken: next}, nil
+ }
+ return &ec2.DescribeRouteTablesOutput{RouteTables: []ec2types.RouteTable{{Routes: []ec2types.Route{{DestinationCidrBlock: aws.String("10.43.0.0/16"), GatewayId: aws.String("local")}}}}}, nil
+ case *ec2.DescribeSecurityGroupRulesInput:
+ first, next := two(in.NextToken)
+ rule := ec2types.SecurityGroupRule{IsEgress: aws.Bool(true), IpProtocol: aws.String("tcp"), FromPort: aws.Int32(8443), ToPort: aws.Int32(8443), CidrIpv4: aws.String("10.42.1.10/32")}
+ if first {
+ return &ec2.DescribeSecurityGroupRulesOutput{SecurityGroupRules: []ec2types.SecurityGroupRule{rule}, NextToken: next}, nil
+ }
+ rule.CidrIpv4 = aws.String("0.0.0.0/0") // a rule on page two must be seen
+ return &ec2.DescribeSecurityGroupRulesOutput{SecurityGroupRules: []ec2types.SecurityGroupRule{rule}}, nil
+ case *ec2.DescribeVpcPeeringConnectionsInput:
+ return &ec2.DescribeVpcPeeringConnectionsOutput{}, nil
+ }
+ return nil, fmt.Errorf("unexpected %s", c.Op)
+ })
+ nf, err := cl.Network(ctx, hostedops.NetworkIDs{VMVPC: "v", VMSubnet: "s", VMSecurityGroup: "g", ServicesRouteTable: "r", Peering: "p"})
+ if err != nil || len(nf.VMRoutes) != 1 || len(nf.VMSGRules) != 2 {
+ t.Fatalf("network over two pages: %+v, %v", nf, err)
+ }
+ })
+ t.Run("listings over two pages", func(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch in := c.In.(type) {
+ case *ec2.DescribeNetworkInterfacesInput:
+ first, next := two(in.NextToken)
+ id := "eni-2"
+ if first {
+ id = "eni-1"
+ }
+ return &ec2.DescribeNetworkInterfacesOutput{NetworkInterfaces: []ec2types.NetworkInterface{{NetworkInterfaceId: aws.String(id)}}, NextToken: next}, nil
+ case *s3.ListObjectsV2Input:
+ first, next := two(in.ContinuationToken)
+ k := "b"
+ if first {
+ k = "a"
+ }
+ return &s3.ListObjectsV2Output{Contents: []s3types.Object{{Key: aws.String(k)}}, NextContinuationToken: next, IsTruncated: aws.Bool(next != nil)}, nil
+ case *tagging.GetResourcesInput:
+ first, next := two(in.PaginationToken)
+ a := "arn:2"
+ if first {
+ a = "arn:1"
+ }
+ if next == nil {
+ next = aws.String("")
+ }
+ return &tagging.GetResourcesOutput{ResourceTagMappingList: []tagtypes.ResourceTagMapping{{ResourceARN: aws.String(a)}}, PaginationToken: next}, nil
+ case *vms.ListMicrovmImagesInput:
+ first, next := two(in.NextToken)
+ n := "equipo-hosted-prod-r1"
+ if first {
+ n = "other"
+ }
+ return &vms.ListMicrovmImagesOutput{Items: []vmtypes.MicrovmImageSummary{{Name: aws.String(n), ImageArn: aws.String("arn:" + n)}}, NextToken: next}, nil
+ case *budgets.DescribeBudgetActionsForBudgetInput:
+ first, next := two(in.NextToken)
+ id := "act-2"
+ if first {
+ id = "act-1"
+ }
+ return &budgets.DescribeBudgetActionsForBudgetOutput{Actions: []budgettypes.Action{{ActionId: aws.String(id)}}, NextToken: next}, nil
+ }
+ return nil, fmt.Errorf("unexpected %s", c.Op)
+ })
+ if e, err := cl.SubnetInterfaces(ctx, "s"); err != nil || !slices.Equal(e, []string{"eni-1", "eni-2"}) {
+ t.Errorf("interfaces %v %v", e, err)
+ }
+ if k, err := cl.ListKeys(ctx, "b", prod, "p/"); err != nil || !slices.Equal(k, []string{"a", "b"}) {
+ t.Errorf("keys %v %v", k, err)
+ }
+ if a, err := cl.TaggedARNs(ctx, "r1"); err != nil || !slices.Equal(a, []string{"arn:1", "arn:2"}) {
+ t.Errorf("tagged %v %v", a, err)
+ }
+ if r, err := cl.Lookup(ctx, hostedops.LookupKey{Type: "microvm-image", Name: "equipo-hosted-prod-r1"}); err != nil || !slices.Equal(r.IDs, []string{"arn:equipo-hosted-prod-r1"}) {
+ t.Errorf("image by name %+v %v", r, err)
+ }
+ if r, err := cl.Lookup(ctx, hostedops.LookupKey{Type: "aws_budgets_budget_action", ID: prod + ":act-2:equipo-hosted-monthly"}); err != nil || len(r.IDs) != 1 {
+ t.Errorf("budget action on page two %+v %v", r, err)
+ }
+ })
+ t.Run("identity lookups over two pages, every type", func(t *testing.T) {
+ page := func(tok *string) (*string, bool) {
+ if tok == nil {
+ return aws.String("p2"), false
+ }
+ return nil, true
+ }
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch in := c.In.(type) {
+ case *ec2.DescribeVpcsInput:
+ if next, last := page(in.NextToken); !last {
+ return &ec2.DescribeVpcsOutput{NextToken: next}, nil
+ }
+ return &ec2.DescribeVpcsOutput{Vpcs: []ec2types.Vpc{{VpcId: aws.String("vpc-x")}}}, nil
+ case *ec2.DescribeSubnetsInput:
+ if next, last := page(in.NextToken); !last {
+ return &ec2.DescribeSubnetsOutput{NextToken: next}, nil
+ }
+ return &ec2.DescribeSubnetsOutput{Subnets: []ec2types.Subnet{{SubnetId: aws.String("subnet-x")}}}, nil
+ case *ec2.DescribeSecurityGroupsInput:
+ if next, last := page(in.NextToken); !last {
+ return &ec2.DescribeSecurityGroupsOutput{NextToken: next}, nil
+ }
+ return &ec2.DescribeSecurityGroupsOutput{SecurityGroups: []ec2types.SecurityGroup{{GroupId: aws.String("sg-x")}}}, nil
+ case *ec2.DescribeRouteTablesInput:
+ if next, last := page(in.NextToken); !last {
+ return &ec2.DescribeRouteTablesOutput{NextToken: next}, nil
+ }
+ return &ec2.DescribeRouteTablesOutput{RouteTables: []ec2types.RouteTable{{RouteTableId: aws.String("rtb-x")}}}, nil
+ case *ec2.DescribeInternetGatewaysInput:
+ if next, last := page(in.NextToken); !last {
+ return &ec2.DescribeInternetGatewaysOutput{NextToken: next}, nil
+ }
+ return &ec2.DescribeInternetGatewaysOutput{InternetGateways: []ec2types.InternetGateway{{InternetGatewayId: aws.String("igw-x")}}}, nil
+ case *ec2.DescribeNetworkAclsInput:
+ if next, last := page(in.NextToken); !last {
+ return &ec2.DescribeNetworkAclsOutput{NextToken: next}, nil
+ }
+ return &ec2.DescribeNetworkAclsOutput{NetworkAcls: []ec2types.NetworkAcl{{NetworkAclId: aws.String("acl-x")}}}, nil
+ case *ec2.DescribeVpcPeeringConnectionsInput:
+ if next, last := page(in.NextToken); !last {
+ return &ec2.DescribeVpcPeeringConnectionsOutput{NextToken: next}, nil
+ }
+ return &ec2.DescribeVpcPeeringConnectionsOutput{VpcPeeringConnections: []ec2types.VpcPeeringConnection{{VpcPeeringConnectionId: aws.String("pcx-x")}}}, nil
+ case *ec2.DescribeInstancesInput:
+ if next, last := page(in.NextToken); !last {
+ return &ec2.DescribeInstancesOutput{NextToken: next}, nil
+ }
+ return &ec2.DescribeInstancesOutput{Reservations: []ec2types.Reservation{{Instances: []ec2types.Instance{{InstanceId: aws.String("i-x")}}}}}, nil
+ case *ec2.DescribeAddressesInput:
+ return &ec2.DescribeAddressesOutput{Addresses: []ec2types.Address{{AllocationId: aws.String("eipalloc-x")}}}, nil
+ }
+ return nil, errors.New("unexpected " + c.Op)
+ })
+ for typ, want := range map[string]string{"aws_vpc": "vpc-x", "aws_subnet": "subnet-x", "aws_security_group": "sg-x", "aws_route_table": "rtb-x",
+ "aws_internet_gateway": "igw-x", "aws_network_acl": "acl-x", "aws_vpc_peering_connection": "pcx-x", "aws_instance": "i-x", "aws_eip": "eipalloc-x"} {
+ r, err := cl.Lookup(ctx, hostedops.LookupKey{Type: typ, NameTag: "n", Run: "r1", Parent: "vpc-0p"})
+ if err != nil || !slices.Equal(r.IDs, []string{want}) {
+ t.Errorf("%s: %+v %v; want %s from page two", typ, r, err, want)
+ }
+ }
+ })
+}
diff --git a/internal/isolatedjob/awsjob/opsaws/lookup.go b/internal/isolatedjob/awsjob/opsaws/lookup.go
index f01f8aa7..77d0309c 100644
--- a/internal/isolatedjob/awsjob/opsaws/lookup.go
+++ b/internal/isolatedjob/awsjob/opsaws/lookup.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "slices"
"strings"
"amadan.net/oficina/equipo/internal/hostedops"
@@ -250,27 +251,65 @@ func (c *cloud) ec2ByID(ctx context.Context, typ, id string) (hostedops.LookupRe
// ec2ByIdentity finds a resource of typ by its creation identity (F3): its
// Name tag and the run's tag, and its parent VPC when known, over every
-// page. The stacks tag every EC2 resource when they create it (Name and
-// the provider's default run tag), so a complete listing with no match is
-// a definitive miss. With no Name tag the identity is not enough: not
-// definitive, and no call is made.
+// page. A filtered miss is never proof of absence (N2): an untagged
+// survivor would not match. Absence is proved only by an unfiltered
+// listing under the recorded parent that holds nothing of the type but the
+// IDs the ledger accounts to other intents. With no Name tag, or no
+// recorded parent to list under, the answer is not definitive.
func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.LookupKey) (hostedops.LookupResult, error) {
if k.NameTag == "" || k.Run == "" {
return hostedops.LookupResult{}, nil
}
+ pf := parentFilter(typ, k.Parent)
f := []ec2types.Filter{{Name: aws.String("tag:Name"), Values: []string{k.NameTag}}, {Name: aws.String("tag:run"), Values: []string{k.Run}}}
- if k.Parent != "" && strings.HasPrefix(k.Parent, "vpc-") {
- switch typ {
- case "aws_subnet", "aws_security_group", "aws_route_table", "aws_network_acl", "aws_instance":
- f = append(f, ec2types.Filter{Name: aws.String("vpc-id"), Values: []string{k.Parent}})
- case "aws_internet_gateway":
- f = append(f, ec2types.Filter{Name: aws.String("attachment.vpc-id"), Values: []string{k.Parent}})
+ if pf != nil {
+ f = append(f, *pf)
+ }
+ ids, ok, err := c.listEC2(ctx, typ, f)
+ if err != nil || !ok {
+ return hostedops.LookupResult{}, err
+ }
+ if len(ids) > 0 {
+ return hostedops.LookupResult{IDs: ids, Definitive: true}, nil
+ }
+ if pf == nil {
+ return hostedops.LookupResult{}, nil
+ }
+ all, _, err := c.listEC2(ctx, typ, []ec2types.Filter{*pf})
+ if err != nil {
+ return hostedops.LookupResult{}, err
+ }
+ for _, id := range all {
+ if !slices.Contains(k.Accounted, id) {
+ return hostedops.LookupResult{}, nil // something unaccounted under the parent: perhaps this one, untagged
}
}
- var ids []string
- page := func(n int) error {
- if n >= maxPages {
- return errors.New("too many pages")
+ return hostedops.LookupResult{Definitive: true}, nil
+}
+
+// parentFilter lists a type's resources under a recorded parent VPC.
+func parentFilter(typ, parent string) *ec2types.Filter {
+ if !strings.HasPrefix(parent, "vpc-") {
+ return nil
+ }
+ switch typ {
+ case "aws_subnet", "aws_security_group", "aws_route_table", "aws_network_acl", "aws_instance":
+ return &ec2types.Filter{Name: aws.String("vpc-id"), Values: []string{parent}}
+ case "aws_internet_gateway":
+ return &ec2types.Filter{Name: aws.String("attachment.vpc-id"), Values: []string{parent}}
+ }
+ return nil
+}
+
+// listEC2 lists the live resources of typ matching f, over every page;
+// ok is false for a type it cannot list.
+func (c *cloud) listEC2(ctx context.Context, typ string, f []ec2types.Filter) (ids []string, ok bool, err error) {
+ more := func(n int, err error, op string) error {
+ if err == nil && n >= maxPages {
+ err = errors.New("too many pages")
+ }
+ if err != nil {
+ return fmt.Errorf("%s: %w", op, err)
}
return nil
}
@@ -279,11 +318,8 @@ func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.Looku
p := ec2.NewDescribeVpcsPaginator(c.cl.ec2, &ec2.DescribeVpcsInput{Filters: f})
for n := 0; p.HasMorePages(); n++ {
r, err := p.NextPage(ctx)
- if err == nil {
- err = page(n)
- }
- if err != nil {
- return hostedops.LookupResult{}, fmt.Errorf("DescribeVpcs: %w", err)
+ if err := more(n, err, "DescribeVpcs"); err != nil {
+ return nil, true, err
}
for _, x := range r.Vpcs {
ids = append(ids, aws.ToString(x.VpcId))
@@ -293,11 +329,8 @@ func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.Looku
p := ec2.NewDescribeSubnetsPaginator(c.cl.ec2, &ec2.DescribeSubnetsInput{Filters: f})
for n := 0; p.HasMorePages(); n++ {
r, err := p.NextPage(ctx)
- if err == nil {
- err = page(n)
- }
- if err != nil {
- return hostedops.LookupResult{}, fmt.Errorf("DescribeSubnets: %w", err)
+ if err := more(n, err, "DescribeSubnets"); err != nil {
+ return nil, true, err
}
for _, x := range r.Subnets {
ids = append(ids, aws.ToString(x.SubnetId))
@@ -307,11 +340,8 @@ func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.Looku
p := ec2.NewDescribeSecurityGroupsPaginator(c.cl.ec2, &ec2.DescribeSecurityGroupsInput{Filters: f})
for n := 0; p.HasMorePages(); n++ {
r, err := p.NextPage(ctx)
- if err == nil {
- err = page(n)
- }
- if err != nil {
- return hostedops.LookupResult{}, fmt.Errorf("DescribeSecurityGroups: %w", err)
+ if err := more(n, err, "DescribeSecurityGroups"); err != nil {
+ return nil, true, err
}
for _, x := range r.SecurityGroups {
ids = append(ids, aws.ToString(x.GroupId))
@@ -321,11 +351,8 @@ func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.Looku
p := ec2.NewDescribeRouteTablesPaginator(c.cl.ec2, &ec2.DescribeRouteTablesInput{Filters: f})
for n := 0; p.HasMorePages(); n++ {
r, err := p.NextPage(ctx)
- if err == nil {
- err = page(n)
- }
- if err != nil {
- return hostedops.LookupResult{}, fmt.Errorf("DescribeRouteTables: %w", err)
+ if err := more(n, err, "DescribeRouteTables"); err != nil {
+ return nil, true, err
}
for _, x := range r.RouteTables {
ids = append(ids, aws.ToString(x.RouteTableId))
@@ -335,11 +362,8 @@ func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.Looku
p := ec2.NewDescribeInternetGatewaysPaginator(c.cl.ec2, &ec2.DescribeInternetGatewaysInput{Filters: f})
for n := 0; p.HasMorePages(); n++ {
r, err := p.NextPage(ctx)
- if err == nil {
- err = page(n)
- }
- if err != nil {
- return hostedops.LookupResult{}, fmt.Errorf("DescribeInternetGateways: %w", err)
+ if err := more(n, err, "DescribeInternetGateways"); err != nil {
+ return nil, true, err
}
for _, x := range r.InternetGateways {
ids = append(ids, aws.ToString(x.InternetGatewayId))
@@ -349,11 +373,8 @@ func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.Looku
p := ec2.NewDescribeNetworkAclsPaginator(c.cl.ec2, &ec2.DescribeNetworkAclsInput{Filters: f})
for n := 0; p.HasMorePages(); n++ {
r, err := p.NextPage(ctx)
- if err == nil {
- err = page(n)
- }
- if err != nil {
- return hostedops.LookupResult{}, fmt.Errorf("DescribeNetworkAcls: %w", err)
+ if err := more(n, err, "DescribeNetworkAcls"); err != nil {
+ return nil, true, err
}
for _, x := range r.NetworkAcls {
ids = append(ids, aws.ToString(x.NetworkAclId))
@@ -363,11 +384,8 @@ func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.Looku
p := ec2.NewDescribeVpcPeeringConnectionsPaginator(c.cl.ec2, &ec2.DescribeVpcPeeringConnectionsInput{Filters: f})
for n := 0; p.HasMorePages(); n++ {
r, err := p.NextPage(ctx)
- if err == nil {
- err = page(n)
- }
- if err != nil {
- return hostedops.LookupResult{}, fmt.Errorf("DescribeVpcPeeringConnections: %w", err)
+ if err := more(n, err, "DescribeVpcPeeringConnections"); err != nil {
+ return nil, true, err
}
for _, x := range r.VpcPeeringConnections {
if x.Status == nil || (x.Status.Code != ec2types.VpcPeeringConnectionStateReasonCodeDeleted && x.Status.Code != ec2types.VpcPeeringConnectionStateReasonCodeRejected) {
@@ -380,11 +398,8 @@ func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.Looku
p := ec2.NewDescribeInstancesPaginator(c.cl.ec2, &ec2.DescribeInstancesInput{Filters: f})
for n := 0; p.HasMorePages(); n++ {
r, err := p.NextPage(ctx)
- if err == nil {
- err = page(n)
- }
- if err != nil {
- return hostedops.LookupResult{}, fmt.Errorf("DescribeInstances: %w", err)
+ if err := more(n, err, "DescribeInstances"); err != nil {
+ return nil, true, err
}
for _, res := range r.Reservations {
for _, x := range res.Instances {
@@ -395,15 +410,15 @@ func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.Looku
case "aws_eip":
r, err := c.cl.ec2.DescribeAddresses(ctx, &ec2.DescribeAddressesInput{Filters: f}) // one page by design
if err != nil {
- return hostedops.LookupResult{}, fmt.Errorf("DescribeAddresses: %w", err)
+ return nil, true, fmt.Errorf("DescribeAddresses: %w", err)
}
for _, x := range r.Addresses {
ids = append(ids, aws.ToString(x.AllocationId))
}
default:
- return hostedops.LookupResult{}, nil
+ return nil, false, nil
}
- return hostedops.LookupResult{IDs: ids, Definitive: true}, nil
+ return ids, true, nil
}
// Inventory is 0.5's read-only sweep.