oficina / equipo Public

hosted: ops teardown blocks, exit classes, VM accounting (Task 34 kit)

The run kit's side of Astra's plan review r1, rulings K1 to K5, K7, K8:
- block --teardown: guard and ledger ownership, no spend gate; nothing
  inside it may create or admit spend (99).
- exit classes: 99 only for safety refusals; ordinary failures a
  fallback may retry are 1. Table in ops.go and infra/hosted/README.md.
- verify-gone stops on a tagged resource the ledger does not hold
  unless a direct read proves it absent; opsaws reads EBS volumes.
- vms scan checks live VMs against the controller's table and recorded
  launches; vms settle --step proves one step's VMs ended in a bound.
- unit status (read only), unit start BLOCK.retryN, ops finding.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f0056f0a5065b57aab14966fefdee9b5f3f578de parent f384ee2
26 files changed, +1,597 −120
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +143 −0
  • infra/hosted/README.md +22 −0
  • internal/hostedops/buckets.go +16 −5
  • internal/hostedops/cloud.go +3 −0
  • internal/hostedops/connector.go +46 −21
  • internal/hostedops/drill_test.go +1 −1
  • internal/hostedops/estimate.go +15 −4
  • internal/hostedops/fake_test.go +15 −5
  • internal/hostedops/fix1_test.go +2 −2
  • internal/hostedops/kit34_test.go +598 −0
  • internal/hostedops/ledger.go +8 −2
  • internal/hostedops/ledgercmd.go +14 −0
  • internal/hostedops/ops.go +76 −9
  • internal/hostedops/report.go +16 −8
  • internal/hostedops/singleton.go +4 −4
  • internal/hostedops/stop.go +60 −16
  • internal/hostedops/t32_test.go +1 −1
  • internal/hostedops/tf.go +190 −19
  • internal/hostedops/unfence.go +8 −4
  • internal/hostedops/units.go +102 −3
  • internal/hostedops/vms.go +185 −11
  • internal/hostedops/vms_test.go +2 −2
  • internal/isolatedjob/awsjob/opsaws/cloud.go +1 −1
  • internal/isolatedjob/awsjob/opsaws/kit34_test.go +55 −0
  • internal/isolatedjob/awsjob/opsaws/lookup.go +13 −1

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 2.1s
ci-box: codex: fetched and verified in 4.5s
ci-box: codex-code-mode-host: fetched and verified in 1.5s
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 2.0s
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.4s
ci-box: opencode: installed and verified in 2.3s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 8.7s
ci-box: clone deepened in 6.1s
ci-box: file times set from content: 4061 files, 303 directories
ci-box: ready in 20.8s
=== copy ===
EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$' -count=1
--- FAIL: TestReleaseCopyReviewed (0.09s)
    task_pages_test.go:236: COPY REVIEW REQUIRED: copy-status.py verify found copy pending review or stale bookkeeping
FAIL
rastrillo-budget/v1 ran 89ms
FAIL	amadan.net/oficina/equipo/internal/equipotest	0.242s
FAIL
make: *** [Makefile:324: copy-release-check] Error 1

amadan: step copy failed: exit status 2

amadan: job failed at step copy — its output is above, not at the tail of this log
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 17dde392..a948d15d 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -88,4 +88,4 @@ perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin,
# and the same bounded cardView as the snapshot; no list scan or new route.
perf GET /api/v1/tasks/{id}/changes/diff skip Device-only bounded display patch JSON: indexed step/attempt lookup, 64 KiB patch and 128 KiB response, no Git or network work at read time; not an HTML screen.
size internal/hostedctl 6079 10017 Hosted controller core and its lifecycle simulation; split planned for slice 1b; slice 2: egress snapshot, admission, deadlines, healthz; measured 6079/10017.
-size internal/hostedops 7017 - Hosted slice 2 Task 33: equipo-hosted-ops, one journal and one Ops shared by every run kit subcommand, so one package; dev drill run-kit fixes 2 and 5 to 7 (fence record, reboot waits, scan retry, S.1 argv); measured 7017.
+size internal/hostedops 7654 - Hosted slice 2 Task 33: equipo-hosted-ops, one journal and one Ops shared by every run kit subcommand, so one package; dev drill run-kit fixes 2 and 5 to 7 (fence record, reboot waits, scan retry, S.1 argv); Task 34 kit K1 to K8 (teardown blocks, exit classes, tag cross-check, VM accounting and step settle, unit status and retries, finding); measured 7654.
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 261b038e..eed7769e 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -3598,3 +3598,146 @@ Mutation checks, each restored:
`status=suite_failed`, for a refused mode.
- **H10** a drill mode allowed on any scenario: `TestHostedGate` FAILED `a drill mode on a check:
skip "" fail ""`.
+
+## Task 34 kit (Astra's plan review r1, rulings K1 to K8, 2026-12-02)
+
+Run-kit changes so the dev drill plan can meet `p34-r1.md`; the plan itself is revised after. No AWS
+call of any kind. Brief: `kit-p34-brief.md`; report: `kit-p34-report.md` (same directory).
+
+- **K1** `ops block ID --teardown -- CMD`: the guard and the ledger's ownership run, the estimate is
+ computed from the ledger and journalled (`ESTIMATE ... stop=none teardown=yes`), never compared.
+ The command runs with `EQUIPO_HOSTED_OPS_TEARDOWN=ID`; inside it `reserve`, `bucket create`,
+ `connector create`, `object put`, `keys upload` and a create phase of `tf` refuse with 99.
+ `--teardown` with `--stop` is a usage error. Teardown commands never looked at spend; a test now
+ holds them to it with the estimate past $50.
+- **K2** exit classes: 99 only for safety refusals; ordinary failures a fallback may retry are 1
+ (tofu apply after plan-check accepted, the adoption apply, connector create refused/FAILED/not
+ ACTIVE, connector delete while still recorded, reboot timeout or refused reboot call, a
+ reservation the estimate cannot admit, a VM scan or vms reconcile still incomplete, bucket create
+ and object put refused, bucket listing anomalies, Litestream restore unreadable, inventory,
+ singleton and MFA trust reads). Still 99: plan-check, guard, collisions, foreign ARNs, a
+ reservation asked at the stop, connector interfaces not proved gone once the connector is
+ deleted, a provider binding of another account. The table is in `ops.go`'s package comment and
+ `infra/hosted/README.md`; `equipo-hosted-image`'s codes are documented there and in its command
+ comment (4 is the safety refusal).
+- **K3** `verify-gone`'s tag cross-check is strict: a tagged ARN the ledger does not hold is read
+ directly by its type (`arnLookupKey`: S3, IAM role/policy/profile, SNS, CloudTrail, alarms, log
+ groups, budgets, EC2 VPC/subnet/SG/route table/gateway/peering/instance/EIP/NACL/volume, ENIs
+ through `InterfaceExists`, connectors, images); proved absent is a lag FINDING, anything else 99.
+ A held record read deleted that the index still lists is a lag FINDING. An unreadable index fails
+ verification (1). `tf reconcile` (which gates nothing) keeps FINDINGs. `opsaws` reads EBS volumes
+ by ID (`InvalidVolume.NotFound`, `deleted` gone; `deleting` still there).
+- **K4** `vms scan` reads the provider, then (only when a live VM is not a recorded launch) the
+ controller's `GET /v1/vms`; controller VMs are recorded with `attempt=`. A live VM neither the
+ controller's (an attempt) nor a recorded launch, still live by a direct read and seen for at least
+ `AdoptGrace` (2 min, by the ledger's first sighting or the controller's age) is 99; younger, a
+ FINDING; the controller not answering while one is unexplained, 1. `vms settle --step ID --image
+ ARN --max D`: the step's end is its first `STEP-END`, the bound runs from it (a re-run gets no fresh
+ bound); the step's VMs are those first recorded since the image's last `STEP-SETTLED`; clean scans
+ plus a direct read of each; `STEP-SETTLED ID image= vms= ended= after=`; never terminates; a step
+ settled twice is refused (1).
+- **K5** `ops unit status BLOCK`: one JSON line (`state`, `status`, `result`, `started_unix`,
+ `elapsed_seconds`, `waited`), 0 on a read, 1 when the unit is not journalled or unresolved. No
+ journal line, no stop, no recovery.
+- **K6** `img delete -arn ARN -ledger DIR`: only an image the journal records (else exit 4); one
+ already absent or `DELETED` is success, journalled `DELETED microvm-image ARN read-gone` once; a
+ deletion it makes is journalled `img-delete`. Without `-ledger`, as before.
+- **K7** `ops unit start BLOCK.retryN -- CMD`, N 1 or 2, once BLOCK (and the earlier retries) are
+ journalled and done, failed or not: `UNIT-RETRY <unit> of=<previous unit> status=<its status>`.
+ Any other reuse, a retry out of order, a third retry, a block never started: refused (1).
+- **K8** `ops finding TEXT...` journals a FINDING (the report lists it); a private key is refused (99).
+- `ops` with no command, or `ops help`, prints the whole usage (`usageText`).
+
+Tests: `internal/hostedops/kit34_test.go` (`TestTeardownBlockSkipsSpendGate`,
+`TestTeardownBlockRefusesCreates`, `TestOrdinaryFailuresExitOne`, `TestLitestreamCheckClasses`,
+`TestVerifyGoneUnknownTagged`, `TestARNLookupKey`, `TestVMsScanAccountsForLiveVMs`, `TestSettleStep`,
+`TestUnitStatus`, `TestUnitRetry`, `TestFindingCommand`, `TestNewInvocationsParse`),
+`internal/hostedimage/delete_test.go` (`TestDeleteResumable`), `opsaws/kit34_test.go`
+(`TestLookupVolumeByID`). Changed expectations (K2): `TestTfIntentCarriesIdentity` (failed apply 1),
+`TestVMsScanMax` (incomplete scan 1), `TestReservationAdmittedAndConsumed` (`reserve vm 20` 1),
+`TestConnectorDeleteFallback` (second failure 1), `TestRebootWaitsForTheHostToGo` and
+`TestControllerReboot` (timeout 1).
+
+Red first (compile stubs only, so failures are assertions): `go test ./internal/hostedops -run
+'<the tests above>'` FAILED, among others, `drill_test.go:105: up all along: reboot = 99, want 1`,
+`fix1_test.go:131: ops tf network network = 99, want 1`, `kit34_test.go:39: ops block 8.2 --teardown
+-- true = 1, want 0`, `kit34_test.go:83: [bucket create ...] under a teardown block called HeadBucket`,
+`kit34_test.go:225: restore failed: litestream-check = 99, want 1`, `kit34_test.go:270: unknown, no
+direct read: verify-gone = 0, want 99`, `kit34_test.go:382: the controller's attempt was not
+recorded`, `kit34_test.go:431: ops vms settle --step 6.2-pass ... = 1, want 0`, `kit34_test.go:493:
+ops unit status 2.3 = 1, want 0`, `kit34_test.go:524: ops unit start 2.3.retry2 -- bash x = 0, want
+1`, `kit34_test.go:543: ops finding ... = 1, want 0`, `kit34_test.go:579: ops finding: usage: unknown
+command "finding"`, `vms_test.go:95: ops reserve vm 20 = 99, want 1`. `go test ./internal/hostedimage
+-run TestDeleteResumable` FAILED `delete_test.go:48: run 1: an absent recorded image: ... api:
+GetMicrovmImage failed`. `go test ./internal/isolatedjob/awsjob/opsaws -run TestLookupVolumeByID`
+FAILED `volume lookup {IDs:[] Definitive:false}` (five cases).
+
+Green: `go test -count=1` of `./internal/hostedops/...`, `./internal/hostedimage`,
+`./internal/isolatedjob/awsjob/opsaws`, `./cmd/equipo-hosted-ops`, `./cmd/equipo-hosted-image`,
+`./cmd/equipo-hosted-certify`: all ok (the plan parse tests included). `make fmt-check vet build
+lanes-check budget hosted-infra-check`: ok (`internal/hostedops` raised to 7654). darwin and windows,
+arm64 and amd64: `go build` of the three hosted commands and the three changed packages, ok.
+
+Mutation checks, each with `go test <pkg> -count=1 -run <test>`, each restored (the file rewritten
+from memory) and the test green again:
+- **K1a** the teardown branch never taken (`*teardown && false`): `TestTeardownBlockSkipsSpendGate`
+ FAILED `kit34_test.go:39: ops block 8.2 --teardown -- true = 99, want 0`.
+- **K1b** the guard's refusal ignored in a teardown block: same test FAILED `kit34_test.go:51: ops
+ block 8.3 --teardown -- true = 0, want 99`.
+- **K1c** `refuseInTeardown` always passes: `TestTeardownBlockRefusesCreates` FAILED
+ `kit34_test.go:83: [bucket create ...] under a teardown block called HeadBucket ...` and
+ `kit34_test.go:80: ops connector create ... = 1, want 99`.
+- **K1d** `EQUIPO_HOSTED_OPS_TEARDOWN` not set for the command: `TestTeardownBlockSkipsSpendGate`
+ FAILED `kit34_test.go:41: ... (ran 1, env has teardown false)`.
+- **K2a** a failed apply back to 99: `TestOrdinaryFailuresExitOne` FAILED `kit34_test.go:113: ops tf
+ network network = 99, want 1`.
+- **K2b** reserve's spend gate dropped: same test FAILED `kit34_test.go:164: ops reserve vm 1 = 1, want 99`.
+- **K2c** connector delete's after-deletion conversion dropped: first SURVIVED (the "interfaces
+ left" path already ended in a stop); the test gained the fallback-policy-refused cases (1 while
+ recorded, 99 once deleted, fake `putPolicyErr`), then FAILED `kit34_test.go:158: ops connector
+ delete = 1, want 99`.
+- **K2d** a provider binding of another account as 1: `TestLitestreamCheckClasses` FAILED
+ `kit34_test.go:225: another account: litestream-check = 1, want 99`.
+- **K2e** the reboot timeout back to 99: `TestOrdinaryFailuresExitOne` FAILED `kit34_test.go:153: ops
+ controller reboot ... --max 2m = 99, want 1`.
+- **K3a** strict ignored (`case true:`): `TestVerifyGoneUnknownTagged` FAILED `kit34_test.go:274:
+ unknown, read gone: want a FINDING "a direct read proves it absent" and VERIFIED-GONE` (and the 99
+ cases returning 0).
+- **K3b** a present read taken as absent: same test FAILED `kit34_test.go:270: unknown, read present:
+ verify-gone = 0, want 99`.
+- **K3c** an unreadable index passes verification: same test FAILED `kit34_test.go:282: ops
+ verify-gone = 0, want 1`.
+- **K3d** a `deleting` volume taken as gone: `TestLookupVolumeByID` FAILED `kit34_test.go:48: volume
+ lookup {IDs:[] Definitive:true}`.
+- **K4a** the grace never ends: `TestVMsScanAccountsForLiveVMs` FAILED `kit34_test.go:406: ops vms
+ scan ... = 0, want 99`.
+- **K4b** the controller's attempt ignored: first SURVIVED (the case's VM was a minute old, so it
+ passed as in flight); the case now ages it 10 minutes, then FAILED `kit34_test.go:393: ops vms scan
+ ... = 99, want 0`.
+- **K4c** no direct read of a suspect: FAILED `kit34_test.go:427: ops vms scan ... = 99, want 0`.
+- **K4d** the controller read before the provider: FAILED `kit34_test.go:398: the controller was read
+ before the provider: [ControllerVMs ListVMs ...]`.
+- **K4e** a silent controller passes: FAILED `kit34_test.go:430: ops vms scan ... = 0, want 1`.
+- **K4i** a recorded launch not trusted (always dial): FAILED `vms_test.go:281: the controller was
+ dialled at https://203.0.113.7` and `kit34_test.go:402: ... = 1, want 0`.
+- **K4f** the step's bound renewed on a re-run: `TestSettleStep` FAILED `kit34_test.go:478: a re-run
+ got a fresh bound: 4 more scans`.
+- **K4g** the step's VMs not read directly: FAILED `kit34_test.go:458: a step settle terminated, or did
+ not read its VM directly: [ListVMs ...]`.
+- **K4h** a step settled twice: FAILED `kit34_test.go:460: ops vms settle --step 6.2-pass ... = 0, want 1`.
+- **K5a** unresolved read as success: `TestUnitStatus` FAILED `kit34_test.go:519: ops unit status 2.3
+ = 0, want 1`.
+- **K5b** unit status journals: FAILED `kit34_test.go:523: unit status acted: journal 6 lines (was 2)`.
+- **K5c** a failed unit read as succeeded: FAILED `kit34_test.go:512: a failed unit: map[... result:succeeded ...]`.
+- **K6a** an absent recorded image not accepted: `TestDeleteResumable` FAILED `delete_test.go:48: run 1:
+ an absent recorded image: ... GetMicrovmImage failed`.
+- **K6b** the record check dropped: FAILED `delete_test.go:77: an image the ledger does not record
+ (there true): <nil>, calls [... DeleteImage ...]`.
+- **K6c** journalled on every run: FAILED `delete_test.go:52: 2 DELETED read-gone lines, want 1`.
+- **K7a** three retries: `TestUnitRetry` FAILED `kit34_test.go:548: ops unit start 2.3.retry3 -- bash x = 0, want 1`.
+- **K7b** retries out of order: FAILED `kit34_test.go:537: ops unit start 2.3.retry2 -- bash x = 0, want 1`.
+- **K7d** a retry of a block never started: FAILED `kit34_test.go:537: ops unit start 2.3.retry2 ... = 0, want 1`.
+- **K7c** the retry chain's "done" check off: SURVIVED, and is not counted: `busy()` refuses a run
+ with an unfinished unit before the chain is read, so the check is a second guard no test can
+ reach without removing the first.
+- **K8** `finding` journalling FACT: `TestFindingCommand` FAILED `kit34_test.go:559: no FINDING lines`.
diff --git a/infra/hosted/README.md b/infra/hosted/README.md
index 83a92a91..f9fbff70 100644
--- a/infra/hosted/README.md
+++ b/infra/hosted/README.md
@@ -177,6 +177,28 @@ certificates, the intercept CA's pin and the egress services. `ops
tfvars` writes these. `tests/user_data.tftest.hcl` checks what each host
receives.
+## Exit codes the plans branch on
+
+A plan's fallback may retry or skip past an ordinary failure, never a
+safety refusal, so it branches on the exit code, not on "non-zero".
+`internal/hostedops`'s package comment keeps the same list.
+
+| Tool | Code | Class | Examples |
+| --- | --- | --- | --- |
+| `equipo-hosted-ops` | 0 | done | |
+| `equipo-hosted-ops` | 1 | ordinary: a fallback may retry or skip | usage; a failed read (status, a VM scan still incomplete at `--max`, the tag index, the inventory); `tofu` apply or destroy failing after `plan-check.py` accepted the plan (`tf reconcile ROOT` next); a connector create refused, `FAILED` or not `ACTIVE` in time; a connector delete not done while the connector is still recorded; a controller reboot not seen down and back within `--max`; a reservation the estimate cannot admit; `wait object` past `--max`; a bucket create or object put the provider refused; a Litestream restore that could not be read; `unit start` refusing; `unit status` unable to read |
+| `equipo-hosted-ops` | 99 | safety refusal: a hard stop, section S follows | the guard (account, caller, region); a `plan-check.py` refusal; ownership and ledger (a name collision, another account's ARN, an unresolved intent blocking teardown, another run's directory); the spend gate (`--stop` reached, a reservation asked at the stop, an estimate that does not compute, a create inside a teardown block); a live VM neither the controller's nor a recorded launch; an image not proved clear; fence, terminate, unfence, and reboot while fenced; `verify-gone`; settings or checksums not reading back; a secret where none may be; a failed `assert`; a failed unit (`unit wait`); an expired human wait; safe-stop with problems; connector interfaces not proved gone once the connector is deleted |
+| `equipo-hosted-image` | 4 | safety refusal | a guard: caller, account, region, prefix, an image `-ledger` does not record |
+| `equipo-hosted-image` | 1, 2, 5, 6 | ordinary | other, an AWS call failed, a wait ran out, a failed state |
+| `equipo-hosted-image` | 3 | usage | |
+
+`ops block ID --teardown -- CMD` is the teardown block: the guard and the
+ledger's ownership run, the spend gate does not, and every command that
+creates or admits spend refuses inside it (99). Teardown commands (`tf
+ROOT destroy-*`, `controller terminate`, `unfence`, `bucket empty` and
+`delete`, `connector delete`, `img delete`, `verify-gone`, `vms settle`)
+never look at spend.
+
## Checks
```
diff --git a/internal/hostedops/buckets.go b/internal/hostedops/buckets.go
index ed0f702b..48ea75eb 100644
--- a/internal/hostedops/buckets.go
+++ b/internal/hostedops/buckets.go
@@ -58,6 +58,9 @@ func cmdBucketCreate(o *Ops, args []string) error {
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *b.name == "" {
return usagef("bucket create --name N [--versioning] [--sse AES256] [--block-public] --expected-owner A")
}
+ if err := o.refuseInTeardown("bucket create"); err != nil {
+ return err
+ }
if *sse != "" && *sse != "AES256" {
return failf("--sse must be AES256")
}
@@ -94,7 +97,9 @@ func cmdBucketCreate(o *Ops, args []string) error {
if herr := c.HeadBucket(o.ctx, name, o.Account); errors.Is(herr, ErrNotFound) {
_ = o.jw("NOTCREATED", "s3-bucket %s", name)
}
- return stopf("bucket create %s: %v", name, err)
+ // Ordinary (K2): the intent is resolved by the read above, or by
+ // ledger reconcile; nothing exists unproved.
+ return failf("bucket create %s: %v", name, err)
}
if err := o.checkOwner(name, o.Account); err != nil {
return err
@@ -179,7 +184,7 @@ func (o *Ops) emptyBucket(name string) (int, error) {
key, ver, seen := "", "", 0
for page := 0; ; page++ {
if page > 100000 {
- return n, stopf("bucket %s: too many pages", name)
+ return n, failf("bucket %s: too many pages", name)
}
p, err := c.ListVersions(o.ctx, name, o.Account, key, ver)
if err != nil {
@@ -197,7 +202,7 @@ func (o *Ops) emptyBucket(name string) (int, error) {
break
}
if p.NextKey == key && p.NextVersion == ver {
- return n, stopf("bucket %s: the listing repeated its marker", name)
+ return n, failf("bucket %s: the listing repeated its marker", name)
}
key, ver = p.NextKey, p.NextVersion
}
@@ -205,7 +210,7 @@ func (o *Ops) emptyBucket(name string) (int, error) {
return n, nil
}
}
- return n, stopf("bucket %s is still not empty", name)
+ return n, failf("bucket %s is still not empty", name)
}
func cmdBucketEmpty(o *Ops, args []string) error {
@@ -269,7 +274,7 @@ func (o *Ops) putObject(bucket, key string, body []byte) error {
return err
}
if err := o.cloud.PutObject(o.ctx, bucket, o.Account, key, body); err != nil {
- return stopf("put %s: %v", id, err)
+ return failf("put %s: %v", id, err) // ordinary (K2); the intent stays for ledger reconcile
}
sum := sha256.Sum256(body)
want := base64.StdEncoding.EncodeToString(sum[:])
@@ -289,6 +294,9 @@ func cmdObjectPut(o *Ops, args []string) error {
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *bucket == "" || *key == "" || *file == "" {
return usagef("object put --bucket B --key K --file F [--expected-owner A]")
}
+ if err := o.refuseInTeardown("object put"); err != nil {
+ return err
+ }
abs, _ := filepath.Abs(*file)
keysDir, _ := filepath.Abs(o.path("keys"))
if strings.HasPrefix(abs, keysDir+string(filepath.Separator)) && strings.HasSuffix(abs, ".key") {
@@ -333,6 +341,9 @@ func cmdKeysUpload(o *Ops, args []string) error {
if !kindPattern.MatchString(*certID) {
return usagef("--cert-key-id %q is not an ID", *certID)
}
+ if err := o.refuseInTeardown("keys upload"); err != nil {
+ return err
+ }
l, err := o.ledger()
if err != nil {
return err
diff --git a/internal/hostedops/cloud.go b/internal/hostedops/cloud.go
index d305e157..41f5f674 100644
--- a/internal/hostedops/cloud.go
+++ b/internal/hostedops/cloud.go
@@ -48,6 +48,9 @@ var ErrNotFound = errors.New("not found")
type VM struct {
ID, Image, State string
Started time.Time
+ // Attempt is the controller's job attempt owning the VM, on a VM the
+ // controller listed (GET /v1/vms); "" for the provider's own list.
+ Attempt string
}
// Live reports whether a VM in state s may still run or cost: everything
diff --git a/internal/hostedops/connector.go b/internal/hostedops/connector.go
index 74b75c0b..1630d52c 100644
--- a/internal/hostedops/connector.go
+++ b/internal/hostedops/connector.go
@@ -29,6 +29,9 @@ func cmdConnectorCreate(o *Ops, args []string) error {
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *subnet == "" || *sg == "" || *role == "" {
return usagef("connector create --subnet S --security-group G --role ARN [--max D]")
}
+ if err := o.refuseInTeardown("connector create"); err != nil {
+ return err
+ }
l, err := o.ledger()
if err != nil {
return err
@@ -56,8 +59,10 @@ func cmdConnectorCreate(o *Ops, args []string) error {
if _, gerr := c.GetConnector(o.ctx, name); errors.Is(gerr, ErrNotFound) {
_ = o.jw("NOTCREATED", "connector %s", name)
}
- _ = o.jw("ABORT", "connector create: %v", err)
- return stopf("connector create failed (3.4 onwards needs it): %v", err)
+ if ferr := o.finding("connector create: %v", err); ferr != nil {
+ return ferr
+ }
+ return failf("connector create failed (3.4 onwards needs it): %v", err)
}
if err := o.rec("connector", got.ARN, "name="+name); err != nil {
return err
@@ -69,8 +74,10 @@ func cmdConnectorCreate(o *Ops, args []string) error {
break
}
if err == nil && cur.State != "PENDING" {
- _ = o.jw("ABORT", "connector %s state %s %s", got.ARN, cur.State, cur.StateReason)
- return stopf("connector %s reached %s: %s", got.ARN, cur.State, cur.StateReason)
+ if ferr := o.finding("connector %s state %s %s", got.ARN, cur.State, cur.StateReason); ferr != nil {
+ return ferr
+ }
+ return failf("connector %s reached %s: %s", got.ARN, cur.State, cur.StateReason)
}
if err != nil {
if ferr := o.finding("connector read: %v", err); ferr != nil {
@@ -78,18 +85,20 @@ func cmdConnectorCreate(o *Ops, args []string) error {
}
}
if !o.Clock.Now().Add(ConnectorPoll).Before(deadline) {
- _ = o.jw("ABORT", "connector %s not ACTIVE within %s", got.ARN, *maxD)
- return stopf("connector %s not ACTIVE within %s", got.ARN, *maxD)
+ if ferr := o.finding("connector %s not ACTIVE within %s", got.ARN, *maxD); ferr != nil {
+ return ferr
+ }
+ return failf("connector %s not ACTIVE within %s", got.ARN, *maxD)
}
if err := o.Clock.Sleep(o.ctx, ConnectorPoll); err != nil {
- return stopf("connector wait interrupted: %v", err)
+ return failf("connector wait interrupted: %v", err)
}
}
q := got.ARN + ":1"
v1, err := c.GetConnector(o.ctx, q)
switch {
case err != nil:
- return stopf("the version-1 read of %s failed: %v", q, err)
+ return failf("the version-1 read of %s failed: %v", q, err)
case v1.Version != 1 || v1.VersionARN != q || v1.State != "ACTIVE" ||
strings.Join(v1.Subnets, ",") != *subnet || strings.Join(v1.SecurityGroups, ",") != *sg:
return stopf("the version-1 read does not show this run's ACTIVE connector: %+v", v1)
@@ -115,10 +124,22 @@ func cmdConnectorCreate(o *Ops, args []string) error {
// DELETE_FAILED, or interfaces still there after ConnectorGoneBound, the
// pre-approved fallback replaces the operator role's delete policy with
// one that keeps only the subnet condition, waits for IAM, and deletes
-// once more. A second failure, or interfaces left, is a hard stop. One
-// budget of ConnectorBudget covers it all. Interfaces are never deleted by
-// hand: each recorded one must be read gone.
-func cmdConnectorDelete(o *Ops, args []string) error {
+// once more. One budget of ConnectorBudget covers it all. Interfaces are
+// never deleted by hand: each recorded one must be read gone.
+//
+// Exit classes (K2): a failure while the connector is still recorded (the
+// first interface list, a refused delete, a delete not done within its
+// bound, a refused fallback policy, a second failure) is 1, since a re-run
+// deletes it again; once it is journalled DELETED, interfaces not proved
+// gone are 99, since a re-run would skip the deleted connector.
+func cmdConnectorDelete(o *Ops, args []string) (err error) {
+ deleted := false // the connector is journalled DELETED: what fails after is 99
+ defer func() {
+ if err != nil && deleted && !IsStop(err) {
+ _ = o.jw("ABORT", "connector delete: %v; the connector is deleted, its interfaces not proved gone", err)
+ err = stopf("%v; the connector is deleted, so its interfaces are not proved gone", err)
+ }
+ }()
if len(args) != 0 {
return usagef("connector delete takes no arguments")
}
@@ -150,13 +171,13 @@ func cmdConnectorDelete(o *Ops, args []string) error {
bound := func(d time.Duration) (time.Duration, error) {
left := budgetEnd.Sub(o.Clock.Now())
if left <= 0 {
- return 0, stopf("10.2's shared %s budget is spent", ConnectorBudget)
+ return 0, failf("10.2's shared %s budget is spent", ConnectorBudget)
}
return min(d, left), nil
}
enis, err := c.SubnetInterfaces(o.ctx, subnet)
if err != nil {
- return stopf("the interface list before the connector delete failed: %v", err)
+ return failf("the interface list before the connector delete failed: %v", err)
}
for _, e := range enis {
if err := o.jw("SERVICE-ENI", "%s", e); err != nil {
@@ -165,7 +186,7 @@ func cmdConnectorDelete(o *Ops, args []string) error {
}
attempt := func() (string, error) {
if err := c.DeleteConnector(o.ctx, arn); err != nil && !errors.Is(err, ErrNotFound) {
- return "", stopf("connector delete: %v", err)
+ return "", failf("connector delete: %v", err)
}
d, err := bound(ConnectorGoneBound)
if err != nil {
@@ -188,7 +209,7 @@ func cmdConnectorDelete(o *Ops, args []string) error {
return "timeout", nil
}
if err := o.Clock.Sleep(o.ctx, ConnectorPoll); err != nil {
- return "", stopf("interrupted: %v", err)
+ return "", failf("interrupted: %v", err)
}
}
}
@@ -224,12 +245,13 @@ func cmdConnectorDelete(o *Ops, args []string) error {
if err := o.jw("DELETED", "connector %s", arn); err != nil {
return err
}
+ deleted = true
if ok, err = interfacesGone(); err != nil {
return err
}
case "DELETE_FAILED":
default:
- return stopf("connector %s not gone within %s (%s)", arn, ConnectorGoneBound, res)
+ return failf("connector %s not gone within %s (%s); it stays recorded, so a re-run deletes it again", arn, ConnectorGoneBound, res)
}
if !ok {
if err := o.finding("connector teardown needs the pre-approved fallback (%s, or interfaces left)", res); err != nil {
@@ -239,20 +261,22 @@ func cmdConnectorDelete(o *Ops, args []string) error {
a := "arn:aws:ec2:" + o.Region + ":" + o.Account
doc := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Sid":"DeleteEniInThisSubnet","Effect":"Allow","Action":"ec2:DeleteNetworkInterface","Resource":"%s:network-interface/*","Condition":{"ArnEquals":{"ec2:Subnet":"%s:subnet/%s"}}}]}`, a, a, subnet)
if err := c.PutRolePolicy(o.ctx, role, "connector-delete-eni", doc); err != nil {
- return stopf("the fallback policy was refused: %v", err)
+ return failf("the fallback policy was refused: %v", err)
}
if err := o.jw("FALLBACK", "connector-delete-eni on %s: subnet condition only (Paul, 2026-11-28)", role); err != nil {
return err
}
if err := o.Clock.Sleep(o.ctx, IAMPropagation); err != nil {
- return stopf("interrupted: %v", err)
+ return failf("interrupted: %v", err)
}
if res, err = attempt(); err != nil {
return err
}
if res != "gone" {
- _ = o.jw("ABORT", "the connector delete failed again after the fallback (%s)", res)
- return stopf("the connector delete failed again after the fallback (%s)", res)
+ if ferr := o.finding("the connector delete failed again after the fallback (%s)", res); ferr != nil {
+ return ferr
+ }
+ return failf("the connector delete failed again after the fallback (%s); it stays recorded", res)
}
l, err := o.ledger()
if err != nil {
@@ -263,6 +287,7 @@ func cmdConnectorDelete(o *Ops, args []string) error {
return err
}
}
+ deleted = true
if ok, err = interfacesGone(); err != nil {
return err
}
diff --git a/internal/hostedops/drill_test.go b/internal/hostedops/drill_test.go
index 1db011a8..2550602f 100644
--- a/internal/hostedops/drill_test.go
+++ b/internal/hostedops/drill_test.go
@@ -96,7 +96,7 @@ func TestRebootWaitsForTheHostToGo(t *testing.T) {
exit int
reads int // status reads by the end, when it succeeds
}{
- "up all along": {[]any{on}, ExitStop, 0},
+ "up all along": {[]any{on}, ExitFail, 0}, // a timeout (Task 34 kit, K2)
"down, then back": {[]any{on, on, down, on}, 0, 4},
"old switch, then new": {[]any{off, on}, 0, 2},
} {
diff --git a/internal/hostedops/estimate.go b/internal/hostedops/estimate.go
index 036c6c90..196365e5 100644
--- a/internal/hostedops/estimate.go
+++ b/internal/hostedops/estimate.go
@@ -204,7 +204,9 @@ func cmdEstimate(o *Ops, args []string) error {
// cmdReserve admits N VM launches or image builds: their worst case joins
// the estimate until a recorded VM (or a build's intent) uses each. A
// reservation that would bring the estimate to the run's stop (the last
-// estimate --stop, else $25) is refused with 99 and not recorded.
+// estimate --stop, else $25) is refused and not recorded: 1 and a FINDING,
+// an admission refusal a plan may skip past (K2); 99 when the estimate
+// already reaches the stop (the spend gate), or cannot be computed.
func cmdReserve(o *Ops, args []string) error {
if len(args) != 2 || (args[0] != "vm" && args[0] != "build") {
return failf("reserve vm|build N")
@@ -213,6 +215,9 @@ func cmdReserve(o *Ops, args []string) error {
if err != nil {
return err
}
+ if err := o.refuseInTeardown("reserve"); err != nil {
+ return err
+ }
e, err := o.estimate()
if err != nil {
return err
@@ -229,9 +234,15 @@ func cmdReserve(o *Ops, args []string) error {
if args[0] == "build" {
per = BuildCharge
}
- if after := e.Total + float64(n)*per; after >= stop {
- _ = o.jw("ABORT", "reserve %s %d: the estimate would be $%.2f, at or past the stop $%.2f", args[0], n, after, stop)
- return stopf("reserve %s %d: the estimate would be $%.2f, at or past the stop $%.2f", args[0], n, after, stop)
+ if e.Total >= stop { // the spend gate itself
+ _ = o.jw("ABORT", "reserve %s %d: the estimate $%.2f is already at or past the stop $%.2f", args[0], n, e.Total, stop)
+ return stopf("reserve %s %d: the estimate $%.2f is already at or past the stop $%.2f", args[0], n, e.Total, stop)
+ }
+ if after := e.Total + float64(n)*per; after >= stop { // an admission refusal: nothing is spent, nothing admitted
+ if err := o.finding("reserve %s %d: the estimate would be $%.2f, at or past the stop $%.2f; not admitted", args[0], n, after, stop); err != nil {
+ return err
+ }
+ return failf("reserve %s %d: the estimate would be $%.2f, at or past the stop $%.2f; not admitted", args[0], n, after, stop)
}
if err := o.jw("RESERVE", "%s %d", args[0], n); err != nil {
return err
diff --git a/internal/hostedops/fake_test.go b/internal/hostedops/fake_test.go
index f7db405d..edca84cc 100644
--- a/internal/hostedops/fake_test.go
+++ b/internal/hostedops/fake_test.go
@@ -76,6 +76,10 @@ type fakeCloud struct {
attached map[string]bool
attachedErr error // RolePolicyAttached's error, with attached set
detachSticks bool // a detach that answers but leaves it attached
+
+ // Failures for the exit-class tests (Task 34 kit, K2 and K3).
+ createConnErr, createBucketErr, putErr, invErr, taggedErr, putPolicyErr error
+ eniThere map[string]bool // InterfaceExists answers
}
func newCloud(clock *fakeClock) *fakeCloud {
@@ -147,6 +151,9 @@ func (f *fakeCloud) TerminateVM(_ context.Context, id string) error {
}
func (f *fakeCloud) CreateConnector(_ context.Context, s ConnectorSpec) (Connector, error) {
f.rec("CreateConnector %s", s.Name)
+ if f.createConnErr != nil {
+ return Connector{}, f.createConnErr
+ }
return Connector{ARN: "arn:aws:lambda:eu-west-1:" + f.account + ":network-connector:nc-1", Name: s.Name, State: "PENDING"}, nil
}
func (f *fakeCloud) GetConnector(_ context.Context, id string) (Connector, error) {
@@ -172,11 +179,11 @@ func (f *fakeCloud) SubnetInterfaces(_ context.Context, subnet string) ([]string
}
func (f *fakeCloud) InterfaceExists(_ context.Context, id string) (bool, error) {
f.rec("InterfaceExists %s", id)
- return false, nil
+ return f.eniThere[id], nil
}
func (f *fakeCloud) PutRolePolicy(_ context.Context, role, name, doc string) error {
f.rec("PutRolePolicy %s %s %s", role, name, doc)
- return nil
+ return f.putPolicyErr
}
func (f *fakeCloud) RoleTrustPolicy(_ context.Context, role string) (string, error) {
f.rec("RoleTrustPolicy %s", role)
@@ -232,7 +239,7 @@ func (f *fakeCloud) HeadBucket(_ context.Context, b, owner string) error {
}
func (f *fakeCloud) CreateBucket(_ context.Context, b string) error {
f.rec("CreateBucket %s", b)
- return nil
+ return f.createBucketErr
}
func (f *fakeCloud) ConfigureBucket(_ context.Context, b, o, sse string, v, bl bool, t map[string]string) error {
f.rec("ConfigureBucket %s", b)
@@ -255,6 +262,9 @@ func (f *fakeCloud) DeleteBucket(_ context.Context, b, o string) error {
}
func (f *fakeCloud) PutObject(_ context.Context, b, o, k string, body []byte) error {
f.rec("PutObject %s/%s", b, k)
+ if f.putErr != nil {
+ return f.putErr
+ }
f.mu.Lock()
defer f.mu.Unlock()
if f.objects == nil {
@@ -325,7 +335,7 @@ func (f *fakeCloud) AlarmStates(context.Context, []string) (map[string]string, e
return map[string]string{}, nil
}
func (f *fakeCloud) Quotas(context.Context) ([]Quota, error) { return nil, nil }
-func (f *fakeCloud) Inventory(context.Context) (Inventory, error) { return f.inv, nil }
+func (f *fakeCloud) Inventory(context.Context) (Inventory, error) { return f.inv, f.invErr }
func (f *fakeCloud) Lookup(_ context.Context, k LookupKey) (LookupResult, error) {
f.rec("Lookup %s %s %s", k.Type, k.ID, k.Name)
if f.lookup == nil {
@@ -335,7 +345,7 @@ func (f *fakeCloud) Lookup(_ context.Context, k LookupKey) (LookupResult, error)
}
func (f *fakeCloud) TaggedARNs(context.Context, string) ([]string, error) {
f.rec("TaggedARNs")
- return f.tagged, nil
+ return f.tagged, f.taggedErr
}
// opener hands out one fake cloud, or refuses.
diff --git a/internal/hostedops/fix1_test.go b/internal/hostedops/fix1_test.go
index b083a4cb..9dbe1917 100644
--- a/internal/hostedops/fix1_test.go
+++ b/internal/hostedops/fix1_test.go
@@ -128,7 +128,7 @@ func TestTfIntentCarriesIdentity(t *testing.T) {
os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"resource_changes":[
{"address":"module.network.aws_subnet.vm","type":"aws_subnet","change":{"actions":["create"],"after":{"vpc_id":"vpc-0parent","tags":{"Name":"equipo-hosted-vm"}}}}]}`), 0o600)
os.WriteFile(filepath.Join(fake, "fail-apply"), nil, 0o600)
- r.want(ExitStop, "tf", "network", "network")
+ r.want(ExitFail, "tf", "network", "network") // a failed apply is ordinary (Task 34 kit, K2)
l := r.ledger()
in := l.Open("tf")
if len(in) != 1 || in[0].Attr("nametag") != "equipo-hosted-vm" || in[0].Attr("parent") != "vpc-0parent" || in[0].Attr("run") != "r1" {
@@ -524,7 +524,7 @@ func TestVMsScanMax(t *testing.T) {
r.want(0, "vms", "scan", "--image", image1, "--max", "1m")
r = newRig(t, "REC microvm-image "+image1)
r.cloud.listVMs = func(int, string) ([]VM, error) { return nil, errors.New("throttled") }
- r.want(ExitStop, "vms", "scan", "--image", image1, "--max", "1m")
+ r.want(ExitFail, "vms", "scan", "--image", image1, "--max", "1m") // a read failure (Task 34 kit, K2)
}
// Extra: the probe unit (Task 17b's unit_probe, ported).
diff --git a/internal/hostedops/kit34_test.go b/internal/hostedops/kit34_test.go
new file mode 100644
index 00000000..20cf45c2
--- /dev/null
+++ b/internal/hostedops/kit34_test.go
@@ -0,0 +1,598 @@
+package hostedops
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// The run kit's changes for the dev drill plan's review (p34-r1.md), the
+// coordinator's rulings K1 to K8 (kit-p34-brief.md).
+
+// overSpend is a ledger whose estimate is past the $50 ceiling: 30 VMs at
+// $1.86.
+func overSpend() []string { return append([]string{"REC microvm-image " + image1}, vmLines(30)...) }
+
+// K1: a teardown block runs the guard and the ledger's ownership check but
+// never refuses on spend; a normal block still does. The block's command
+// learns it runs in a teardown block.
+func TestTeardownBlockSkipsSpendGate(t *testing.T) {
+ r := newRig(t, overSpend()...)
+ var env []string
+ ran := 0
+ r.deps.Exec = func(_ ctxT, _ []string, e []string, _, _ wT) int { ran++; env = e; return 0 }
+ r.want(ExitStop, "block", "8.1", "--stop", "50", "--", "true")
+ if ran != 0 {
+ t.Fatal("a normal block ran past the spend stop")
+ }
+ scans := r.cloud.count("ListVMs")
+ r.want(0, "block", "8.2", "--teardown", "--", "true")
+ if ran != 1 || !slices.Contains(env, "EQUIPO_HOSTED_OPS_TEARDOWN=8.2") {
+ t.Fatalf("the teardown block did not run, or its command was not told (ran %d, env has teardown %t)", ran, slices.Contains(env, "EQUIPO_HOSTED_OPS_TEARDOWN=8.2"))
+ }
+ if r.cloud.count("ListVMs") != scans {
+ t.Fatal("the teardown block ran the provider estimate")
+ }
+ if !r.has("ESTIMATE", "block=8.2 teardown=yes") || !r.has("GUARD", "") {
+ t.Fatalf("the teardown block did not journal its guard and ledger estimate:\n%s", journalText(r))
+ }
+ // The guard still runs first: a refused guard is 99 and nothing runs.
+ r.opener.refuse = stopf("the caller changed")
+ r.want(ExitStop, "block", "8.3", "--teardown", "--", "true")
+ if ran != 1 {
+ t.Fatal("a teardown block ran after its guard refused")
+ }
+ // The ledger's ownership: another run's directory is refused.
+ r = newRig(t)
+ r.deps.Exec = func(ctxT, []string, []string, wT, wT) int { ran++; return 0 }
+ r.out.Reset()
+ if code := Main(r.ctx, []string{"-dir", r.dir, "-run", "r2", "-profile", "p", "-account", ProdAccount, "-region", testRegion,
+ "block", "8.4", "--teardown", "--", "true"}, r.deps); code != ExitStop || ran != 1 {
+ t.Fatalf("a teardown block in another run's directory = %d (ran %d), want 99", code, ran)
+ }
+ // --teardown and --stop together make no sense.
+ r = newRig(t)
+ r.want(ExitFail, "block", "8.5", "--teardown", "--stop", "50", "--", "true")
+}
+
+// K1: under a teardown block (EQUIPO_HOSTED_OPS_TEARDOWN set) nothing that
+// creates or admits spend runs: those commands refuse with 99 before any
+// provider call. Teardown commands never look at spend.
+func TestTeardownBlockRefusesCreates(t *testing.T) {
+ t.Setenv("EQUIPO_HOSTED_OPS_TEARDOWN", "8.2")
+ for _, args := range [][]string{
+ {"reserve", "vm", "1"},
+ {"bucket", "create", "--name", "equipo-hosted-x-" + ProdAccount, "--versioning", "--sse", "AES256", "--block-public", "--expected-owner", ProdAccount},
+ {"connector", "create", "--subnet", "subnet-0vm", "--security-group", "sg-0vm", "--role", "arn:aws:iam::149757027610:role/equipo-hosted-connector-operator"},
+ {"object", "put", "--bucket", "equipo-hosted-config-" + ProdAccount, "--key", "k", "--file", "/dev/null"},
+ } {
+ r := newRig(t, overSpend()...)
+ r.want(ExitStop, args...)
+ for _, c := range r.cloud.log() {
+ if !strings.HasPrefix(c, "ListVMs") {
+ t.Errorf("%v under a teardown block called %s", args, c)
+ break
+ }
+ }
+ }
+ r, fake := tfRig(t)
+ r.want(ExitStop, "tf", "network", "network")
+ if strings.Contains(calls(t, fake), "plan") {
+ t.Fatal("a create phase planned under a teardown block")
+ }
+ // A destroy phase is teardown.
+ r, _ = tfRig(t)
+ r.want(0, "tf", "network", "destroy-network")
+
+ // Teardown commands, with the estimate past the ceiling.
+ r = settleRig(t, nil, vmLines(30)...)
+ r.want(0, "vms", "settle", "--image", image1, "--terminate", "--max", "15m")
+ r.want(0, "verify-gone")
+ r.want(0, "bucket", "empty", "--name", "equipo-hosted-config-"+ProdAccount)
+ r.want(0, "connector", "delete")
+ if r.cloud.count("ListVMs") > 0 && r.has("ABORT", "estimate") {
+ t.Fatal("a teardown command refused on spend")
+ }
+}
+
+// K2: ordinary failures a fallback may retry are 1, never 99.
+func TestOrdinaryFailuresExitOne(t *testing.T) {
+ // tofu apply fails after plan-check accepted the plan.
+ r, fake := tfRig(t)
+ os.WriteFile(filepath.Join(fake, "fail-apply"), nil, 0o600)
+ r.want(ExitFail, "tf", "network", "network")
+ if !r.has("FINDING", "apply of network failed") || !r.ledger().TFApplying["network"] || r.has("ABORT", "") {
+ t.Fatalf("a failed apply: want a FINDING, the root left applying and no ABORT:\n%s", journalText(r))
+ }
+ // A plan-check refusal is still 99.
+ r, fake = tfRig(t)
+ os.WriteFile(filepath.Join(fake, "refuse"), nil, 0o600)
+ r.want(ExitStop, "tf", "network", "network")
+
+ // The connector: the create call refused, and ACTIVE not reached in time.
+ role := "arn:aws:iam::149757027610:role/equipo-hosted-connector-operator"
+ create := []string{"connector", "create", "--subnet", "subnet-0vm", "--security-group", "sg-0vm", "--role", role, "--max", "1m"}
+ r = newRig(t)
+ r.cloud.createConnErr = errors.New("AccessDeniedException: lambda:PassNetworkConnector")
+ r.want(ExitFail, create...)
+ r = newRig(t)
+ r.cloud.getConn = func(int, string) (Connector, error) { return Connector{State: "PENDING"}, nil }
+ r.want(ExitFail, create...)
+ r = newRig(t)
+ r.cloud.getConn = func(int, string) (Connector, error) { return Connector{State: "FAILED", StateReason: "subnet"}, nil }
+ r.want(ExitFail, create...)
+ // A role in another account is still 99.
+ r = newRig(t)
+ r.want(ExitStop, "connector", "create", "--subnet", "subnet-0vm", "--security-group", "sg-0vm", "--role", "arn:aws:iam::640012953448:role/x")
+
+ // The connector delete's timeout is 1; interfaces not proved gone after
+ // the connector went are 99 (a re-run would skip the deleted connector).
+ const arn = "arn:aws:lambda:eu-west-1:149757027610:network-connector:nc-1"
+ conn := []string{"INTENT connector equipo-hosted-prod-r1-egress t1", "REC connector " + arn + " name=equipo-hosted-prod-r1-egress", "NOTE connector-subnet subnet-0vm"}
+ r = newRig(t, conn...)
+ r.cloud.getConn = func(int, string) (Connector, error) { return Connector{ARN: arn, State: "DELETING"}, nil }
+ r.want(ExitFail, "connector", "delete")
+ r = newRig(t, conn...)
+ r.cloud.enis = func(int) []string { return []string{"eni-1"} }
+ r.cloud.eniThere = map[string]bool{"eni-1": true}
+ r.want(ExitStop, "connector", "delete")
+ // The fallback's policy refused: 1 while the connector is recorded
+ // (DELETE_FAILED), 99 once it is deleted and interfaces stay.
+ r = newRig(t, conn...)
+ r.cloud.getConn = func(int, string) (Connector, error) { return Connector{ARN: arn, State: "DELETE_FAILED"}, nil }
+ r.cloud.putPolicyErr = errors.New("AccessDenied")
+ r.want(ExitFail, "connector", "delete")
+ r = newRig(t, conn...)
+ r.cloud.enis = func(int) []string { return []string{"eni-1"} }
+ r.cloud.putPolicyErr = errors.New("AccessDenied")
+ r.want(ExitStop, "connector", "delete")
+ if !r.has("DELETED", "connector "+arn) {
+ t.Fatal("the connector read gone was not recorded deleted")
+ }
+
+ // A reboot that never sees the host go and come back is 1; a fenced
+ // controller is still 99.
+ r, _ = rebootRig(t, hostedwire.StatusResponse{Enabled: true})
+ r.want(ExitFail, "controller", "reboot", "--enabled", "1", "--controller", "https://198.51.100.7", "--max", "2m")
+
+ // A reservation that would reach the stop is refused with 1 and not
+ // recorded; one asked when the estimate is already at the stop is the
+ // spend gate, 99.
+ r = newRig(t, "REC microvm-image "+image1)
+ r.want(ExitFail, "reserve", "vm", "20")
+ if r.ledger().VMReserved != 0 || !r.has("FINDING", "reserve vm 20") {
+ t.Fatalf("a refused reservation: reserved %d\n%s", r.ledger().VMReserved, journalText(r))
+ }
+ r = newRig(t, overSpend()...)
+ r.want(ExitStop, "reserve", "vm", "1")
+
+ // A VM scan still incomplete after its bound is a read failure.
+ r = newRig(t, "REC microvm-image "+image1)
+ r.cloud.listVMs = func(int, string) ([]VM, error) { return nil, errors.New("throttled") }
+ r.want(ExitFail, "vms", "scan", "--image", image1, "--max", "1m")
+ r.want(ExitFail, "vms", "reconcile")
+
+ // Buckets and objects: a refused create or put is 1; a collision is 99.
+ r = newRig(t)
+ r.cloud.headBucket = func(string) error { return ErrNotFound }
+ r.cloud.createBucketErr = errors.New("OperationAborted")
+ r.want(ExitFail, "bucket", "create", "--name", "equipo-hosted-tfstate-"+ProdAccount, "--versioning", "--sse", "AES256", "--block-public", "--expected-owner", ProdAccount)
+ r = newRig(t)
+ r.want(ExitStop, "bucket", "create", "--name", "equipo-hosted-tfstate-"+ProdAccount, "--versioning", "--sse", "AES256", "--block-public", "--expected-owner", ProdAccount)
+ r = newRig(t)
+ r.cloud.putErr = errors.New("SlowDown")
+ f := filepath.Join(r.dir, "pin.txt")
+ os.WriteFile(f, []byte("x"), 0o600)
+ r.want(ExitFail, "object", "put", "--bucket", "equipo-hosted-config-"+ProdAccount, "--key", "proxy/a/controller.json", "--file", f)
+
+ // The inventory's read failing is 1; a name collision is 99.
+ r = newRig(t)
+ r.cloud.invErr = errors.New("throttled")
+ r.want(ExitFail, "inventory")
+ r = newRig(t)
+ r.cloud.inv = Inventory{Roles: []string{"equipo-hosted-controller"}}
+ r.want(ExitStop, "inventory")
+}
+
+// K2: litestream-check is 1 when the restore cannot be done or read, and
+// 99 only when the restored database is bound to another account or
+// region.
+func TestLitestreamCheckClasses(t *testing.T) {
+ bin := t.TempDir()
+ good := filepath.Join(bin, "good.db")
+ other := filepath.Join(bin, "other.db")
+ for p, ns := range map[string]string{good: "aws:149757027610:eu-west-1", other: "aws:640012953448:eu-west-1"} {
+ h, err := sql.Open("sqlite", "file:"+p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := h.Exec(`CREATE TABLE provider_binding (id INTEGER PRIMARY KEY, namespace TEXT); INSERT INTO provider_binding VALUES (1, '` + ns + `')`); err != nil {
+ t.Fatal(err)
+ }
+ h.Close()
+ }
+ for name, c := range map[string]struct {
+ script string
+ exit int
+ }{
+ "restored": {`cp "` + good + `" "$3"`, 0},
+ "restore failed": {`exit 1`, ExitFail},
+ "no binding row": {`: > "$3"`, ExitFail},
+ "another account": {`cp "` + other + `" "$3"`, ExitStop},
+ } {
+ r := newRig(t)
+ ls := filepath.Join(t.TempDir(), "litestream")
+ os.WriteFile(ls, []byte("#!/bin/sh\n"+c.script+"\n"), 0o755)
+ r.deps.Litestream = ls
+ if got := r.ops("litestream-check", "--bucket", "equipo-hosted-litestream-"+ProdAccount); got != c.exit {
+ t.Errorf("%s: litestream-check = %d, want %d:\n%s", name, got, c.exit, r.out.String())
+ }
+ }
+}
+
+// K3: verify-gone stops on a resource the tag index lists for this run
+// that the ledger does not hold, unless a direct read proves it absent; a
+// recorded resource read deleted that the index still lists is a lag
+// FINDING; an unreadable index fails verification (1).
+func TestVerifyGoneUnknownTagged(t *testing.T) {
+ const vpcARN = "arn:aws:ec2:eu-west-1:149757027610:vpc/vpc-0stray"
+ for name, c := range map[string]struct {
+ tagged []string
+ lookup func(LookupKey) (LookupResult, error)
+ eni bool
+ exit int
+ finding string
+ }{
+ "unknown, no direct read": {tagged: []string{"arn:aws:ec2:eu-west-1:149757027610:launch-template/lt-0x"}, exit: ExitStop},
+ "unknown, read present": {tagged: []string{vpcARN}, exit: ExitStop,
+ lookup: func(k LookupKey) (LookupResult, error) {
+ if k.Type == "aws_vpc" && k.ID == "vpc-0stray" {
+ return LookupResult{IDs: []string{"vpc-0stray"}, Definitive: true}, nil
+ }
+ return LookupResult{Definitive: true}, nil
+ }},
+ "unknown, read unreadable": {tagged: []string{vpcARN}, exit: ExitStop,
+ lookup: func(k LookupKey) (LookupResult, error) {
+ if k.Type == "aws_vpc" && k.ID == "vpc-0stray" {
+ return LookupResult{}, errors.New("throttled")
+ }
+ return LookupResult{Definitive: true}, nil
+ }},
+ "unknown, read gone": {tagged: []string{vpcARN}, exit: 0, finding: "a direct read proves it absent"},
+ "unknown interface, gone": {tagged: []string{"arn:aws:ec2:eu-west-1:149757027610:network-interface/eni-0x"}, exit: 0, finding: "a direct read proves it absent"},
+ "unknown interface, there": {tagged: []string{"arn:aws:ec2:eu-west-1:149757027610:network-interface/eni-0x"}, eni: true, exit: ExitStop},
+ "known, read deleted": {tagged: []string{"arn:aws:ec2:eu-west-1:149757027610:vpc/vpc-0vm"}, exit: 0, finding: "recorded deleted"},
+ } {
+ r := newRig(t, "REC tf network/module.network.aws_vpc.vm id=vpc-0vm type=aws_vpc source=state")
+ r.cloud.tagged = c.tagged
+ r.cloud.lookup = c.lookup
+ if c.eni {
+ r.cloud.eniThere = map[string]bool{"eni-0x": true}
+ }
+ if got := r.ops("verify-gone"); got != c.exit {
+ t.Errorf("%s: verify-gone = %d, want %d:\n%s", name, got, c.exit, r.out.String())
+ continue
+ }
+ if c.exit == 0 && (!r.has("FINDING", c.finding) || !r.has("VERIFIED-GONE", "")) {
+ t.Errorf("%s: want a FINDING %q and VERIFIED-GONE:\n%s", name, c.finding, journalText(r))
+ }
+ if c.exit == ExitStop && r.has("VERIFIED-GONE", "") {
+ t.Errorf("%s: verified gone with an unknown resource", name)
+ }
+ }
+ r := newRig(t)
+ r.cloud.taggedErr = errors.New("throttled")
+ r.want(ExitFail, "verify-gone")
+ if r.has("VERIFIED-GONE", "") {
+ t.Fatal("verified gone without the tag index's cross-check")
+ }
+ // tf reconcile does not gate teardown's completion: an unknown tagged
+ // resource is a FINDING there, as before.
+ r, fake := tfRig(t)
+ os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"planned_values":{"root_module":{}}}`), 0o600)
+ r.cloud.tagged = []string{"arn:aws:ec2:eu-west-1:149757027610:launch-template/lt-0x"}
+ r.want(0, "tf", "reconcile", "network")
+ if !r.has("FINDING", "lt-0x") {
+ t.Fatal("tf reconcile did not record the unknown tagged resource")
+ }
+}
+
+// TestARNLookupKey: the tag index's ARNs map to the direct read of their
+// type.
+func TestARNLookupKey(t *testing.T) {
+ for arn, want := range map[string]LookupKey{
+ "arn:aws:s3:::equipo-hosted-dev-config-640012953448": {Type: "aws_s3_bucket", ID: "equipo-hosted-dev-config-640012953448"},
+ "arn:aws:iam::640012953448:role/equipo-hosted-dev-controller": {Type: "aws_iam_role", ID: "arn:aws:iam::640012953448:role/equipo-hosted-dev-controller"},
+ "arn:aws:iam::640012953448:policy/equipo-hosted-dev-deny-launches": {Type: "aws_iam_policy", ID: "arn:aws:iam::640012953448:policy/equipo-hosted-dev-deny-launches"},
+ "arn:aws:iam::640012953448:instance-profile/equipo-hosted-dev-proxy": {Type: "aws_iam_instance_profile", ID: "equipo-hosted-dev-proxy"},
+ "arn:aws:sns:eu-west-1:640012953448:equipo-hosted-dev-alerts": {Type: "aws_sns_topic", ID: "arn:aws:sns:eu-west-1:640012953448:equipo-hosted-dev-alerts"},
+ "arn:aws:cloudwatch:eu-west-1:640012953448:alarm:equipo-hosted-dev-x": {Type: "aws_cloudwatch_metric_alarm", ID: "equipo-hosted-dev-x"},
+ "arn:aws:logs:eu-west-1:640012953448:log-group:/aws/lambda-microvms/x:*": {Type: "aws_cloudwatch_log_group", ID: "/aws/lambda-microvms/x"},
+ "arn:aws:budgets::640012953448:budget/equipo-hosted-dev-monthly": {Type: "aws_budgets_budget", ID: "equipo-hosted-dev-monthly"},
+ "arn:aws:ec2:eu-west-1:640012953448:vpc/vpc-1": {Type: "aws_vpc", ID: "vpc-1"},
+ "arn:aws:ec2:eu-west-1:640012953448:elastic-ip/eipalloc-1": {Type: "aws_eip", ID: "eipalloc-1"},
+ "arn:aws:ec2:eu-west-1:640012953448:instance/i-1": {Type: "aws_instance", ID: "i-1"},
+ "arn:aws:ec2:eu-west-1:640012953448:volume/vol-1": {Type: "aws_ebs_volume", ID: "vol-1"},
+ "arn:aws:lambda:eu-west-1:640012953448:network-connector:nc-1": {Type: "connector", ID: "arn:aws:lambda:eu-west-1:640012953448:network-connector:nc-1"},
+ "arn:aws:lambda:eu-west-1:640012953448:microvm-image:equipo-hosted-dev-r1": {Type: "microvm-image", ID: "arn:aws:lambda:eu-west-1:640012953448:microvm-image:equipo-hosted-dev-r1"},
+ } {
+ got, ok := arnLookupKey(arn)
+ if !ok || got.Type != want.Type || got.ID != want.ID {
+ t.Errorf("%s: %+v %t, want %+v", arn, got, ok, want)
+ }
+ }
+ for _, arn := range []string{"arn:aws:ec2:eu-west-1:640012953448:launch-template/lt-1", "arn:aws:budgets::640012953448:budget/b/action/a", "not-an-arn"} {
+ if k, ok := arnLookupKey(arn); ok {
+ t.Errorf("%s mapped to %+v; it has no direct read", arn, k)
+ }
+ }
+}
+
+// vmsCtl answers GET /v1/vms; each call is logged in the cloud's log, so a
+// test sees its order against the provider's calls.
+type vmsCtl struct {
+ r *rig
+ list []hostedwire.VMView
+ err error
+}
+
+func (c *vmsCtl) Status(context.Context) (hostedwire.StatusResponse, error) {
+ return hostedwire.StatusResponse{}, errors.New("not in this test")
+}
+func (c *vmsCtl) VMs(context.Context) (hostedwire.VMListResponse, error) {
+ c.r.cloud.rec("ControllerVMs")
+ return hostedwire.VMListResponse{VMs: c.list}, c.err
+}
+func (c *vmsCtl) Certs(context.Context) (hostedwire.CertsResponse, error) {
+ return hostedwire.CertsResponse{}, errors.New("not in this test")
+}
+
+func scanRig(t *testing.T, live []VM, ctl *vmsCtl, lines ...string) *rig {
+ r := newRig(t, append([]string{"REC microvm-image " + image1, "REC controller-pin " + strings.Repeat("ab", 32)}, lines...)...)
+ controllerReachable(t, r)
+ if ctl != nil {
+ ctl.r = r
+ r.deps.Controller = func(ControllerArgs) (ControllerClient, error) { return ctl, nil }
+ }
+ r.cloud.listVMs = func(int, string) ([]VM, error) { return live, nil }
+ r.cloud.getVM = func(id string) (VM, error) {
+ for _, v := range live {
+ if v.ID == id {
+ return v, nil
+ }
+ }
+ return VM{}, ErrNotFound
+ }
+ return r
+}
+
+func view(id, attempt string, age time.Duration) hostedwire.VMView {
+ return hostedwire.VMView{VMRef: isolatedjob.Ref(id), State: "RUNNING", AttemptID: attempt, AgeKnown: age > 0, AgeMS: age.Milliseconds()}
+}
+
+// K4: vms scan compares the provider's live VMs with the controller's
+// table (GET /v1/vms) and the ledger's recorded launches; a live VM neither
+// explains is a hard stop. The provider is read before the controller, so
+// a VM the controller launches in between is never taken for an orphan.
+func TestVMsScanAccountsForLiveVMs(t *testing.T) {
+ vm := VM{ID: "microvm-a", Image: image1, State: "RUNNING"}
+ scan := []string{"vms", "scan", "--image", image1, "--max", "2m"}
+
+ // The controller's job, however old: explained, and its attempt recorded.
+ r := scanRig(t, []VM{vm}, &vmsCtl{list: []hostedwire.VMView{view("microvm-a", "att-1", 10*time.Minute)}})
+ r.want(0, scan...)
+ if l := r.ledger(); l.VMs["microvm-a"] == nil || l.VMs["microvm-a"].Attempt != "att-1" {
+ t.Fatalf("the controller's attempt was not recorded:\n%s", journalText(r))
+ }
+ if r.cloud.index("ListVMs") > r.cloud.index("ControllerVMs") {
+ t.Fatalf("the controller was read before the provider: %v", r.cloud.log())
+ }
+ // A recorded launch needs no controller read.
+ r = scanRig(t, []VM{vm}, nil, "VM microvm-a source=controller attempt=att-1 state=RUNNING")
+ r.want(0, scan...)
+
+ // Listed by the controller as no job's, and old: a hard stop.
+ r = scanRig(t, []VM{vm}, &vmsCtl{list: []hostedwire.VMView{view("microvm-a", "", 10*time.Minute)}})
+ r.want(ExitStop, scan...)
+ if !r.has("ABORT", "microvm-a") || r.ledger().VMs["microvm-a"] == nil {
+ t.Fatalf("the orphan was not recorded and stopped on:\n%s", journalText(r))
+ }
+ // Young and no job's yet (a launch whose Ref is not saved): a FINDING;
+ // still no job's past the grace, a hard stop.
+ r = scanRig(t, []VM{vm}, &vmsCtl{list: []hostedwire.VMView{view("microvm-a", "", 0)}})
+ r.want(0, scan...)
+ if !r.has("FINDING", "microvm-a") {
+ t.Fatalf("an in-flight VM was not noted:\n%s", journalText(r))
+ }
+ r.clock.Sleep(context.Background(), AdoptGrace+time.Second)
+ r.want(ExitStop, scan...)
+ // Not in the controller's table at all, past the grace: a hard stop.
+ r = scanRig(t, []VM{vm}, &vmsCtl{}, "VM microvm-a source=scan image="+image1+" state=RUNNING")
+ r.clock.Sleep(context.Background(), AdoptGrace+time.Second)
+ r.want(ExitStop, scan...)
+ // Not in the table, but a direct read shows it ended: no stop.
+ r = scanRig(t, []VM{vm}, &vmsCtl{}, "VM microvm-a source=scan image="+image1+" state=RUNNING")
+ r.cloud.getVM = func(id string) (VM, error) { return VM{ID: id, State: "TERMINATED"}, nil }
+ r.clock.Sleep(context.Background(), AdoptGrace+time.Second)
+ r.want(0, scan...)
+ // The controller does not answer: the live VM cannot be judged (1).
+ r = scanRig(t, []VM{vm}, &vmsCtl{err: errors.New("connection refused")})
+ r.want(ExitFail, scan...)
+ // Nothing live: the controller is not dialled (the rig fails on a dial).
+ r = newRig(t, "REC microvm-image "+image1)
+ r.cloud.listVMs = func(int, string) ([]VM, error) {
+ return []VM{{ID: "microvm-b", Image: image1, State: "TERMINATED"}}, nil
+ }
+ r.want(0, scan...)
+}
+
+// K4: vms settle --step proves one step's VMs ended within a bound counted
+// from the step's end (its first STEP-END), journals the step's VMs and
+// when they were proved, and refuses to settle a step twice.
+func TestSettleStep(t *testing.T) {
+ r := settleRig(t, nil, "VM microvm-a source=controller attempt=att-1 image="+image1+" state=RUNNING")
+ r.want(0, "vms", "settle", "--step", "6.2-pass", "--image", image1, "--max", "10m")
+ var end, settled Entry
+ for _, e := range r.ledger().Entries {
+ switch e.Verb {
+ case "STEP-END":
+ end = e
+ case "STEP-SETTLED":
+ settled = e
+ }
+ }
+ if end.Field(0) != "6.2-pass" || settled.Field(0) != "6.2-pass" || settled.Attr("vms") != "microvm-a" || settled.Attr("image") != image1 {
+ t.Fatalf("STEP-END %+v, STEP-SETTLED %+v", end, settled)
+ }
+ if r.cloud.count("TerminateVM") != 0 || r.cloud.index("GetVM microvm-a") < 0 {
+ t.Fatalf("a step settle terminated, or did not read its VM directly: %v", r.cloud.log())
+ }
+ r.want(ExitFail, "vms", "settle", "--step", "6.2-pass", "--image", image1, "--max", "10m")
+ // The next step's VMs are only those seen since.
+ r.journal("VM microvm-b source=scan image=" + image1 + " state=RUNNING")
+ r.want(0, "vms", "settle", "--step", "6.2-fail", "--image", image1, "--max", "10m")
+ if !r.has("STEP-SETTLED", "6.2-fail image="+image1+" vms=microvm-b ") {
+ t.Fatalf("the second step's VMs:\n%s", journalText(r))
+ }
+
+ // A VM still running past the bound: a hard stop, measured from the
+ // step's first end; a re-run gets no fresh bound.
+ r = settleRig(t, []string{"microvm-x", "microvm-x", "microvm-x", "microvm-x", "microvm-x", "microvm-x", "microvm-x", "microvm-x"})
+ r.want(ExitStop, "vms", "settle", "--step", "7.1", "--image", image1, "--max", "2m")
+ if !r.has("ABORT", "7.1") {
+ t.Fatalf("no ABORT naming the step:\n%s", journalText(r))
+ }
+ scans := r.cloud.count("ListVMs")
+ r.want(ExitStop, "vms", "settle", "--step", "7.1", "--image", image1, "--max", "2m")
+ if r.cloud.count("ListVMs") > scans+1 {
+ t.Fatalf("a re-run got a fresh bound: %d more scans", r.cloud.count("ListVMs")-scans)
+ }
+ // Clean scans but a direct read of the step's VM shows it running.
+ r = settleRig(t, nil, "VM microvm-c source=scan image="+image1+" state=RUNNING")
+ r.cloud.getVM = func(id string) (VM, error) { return VM{ID: id, State: "RUNNING"}, nil }
+ r.want(ExitStop, "vms", "settle", "--step", "7.2", "--image", image1, "--max", "3m")
+ // A step settle never terminates.
+ r = settleRig(t, nil)
+ r.want(ExitFail, "vms", "settle", "--step", "7.3", "--image", image1, "--terminate", "--max", "3m")
+}
+
+// K5: unit status reads one unit's state and result as JSON: exit 0 on a
+// read, 1 when the read fails; it never stops a unit, never asks for
+// recovery and writes nothing to the journal.
+func TestUnitStatus(t *testing.T) {
+ r := newRig(t)
+ r.want(0, "unit", "start", "2.3", "--", "bash", "x")
+ lines := len(r.ledger().Entries)
+ read := func(want int) map[string]any {
+ t.Helper()
+ r.want(want, "unit", "status", "2.3")
+ var m map[string]any
+ if err := json.Unmarshal([]byte(r.out.String()[:strings.LastIndex(r.out.String(), "}")+1]), &m); err != nil {
+ t.Fatalf("unit status printed %q: %v", r.out.String(), err)
+ }
+ return m
+ }
+ r.clock.Sleep(context.Background(), 90*time.Second)
+ if m := read(0); m["state"] != "running" || m["result"] != "running" || m["elapsed_seconds"] != float64(90) || m["unit"] != "hprod-r1-2.3.service" {
+ t.Fatalf("a running unit: %v", m)
+ }
+ r.systemd.states["hprod-r1-2.3.service"] = "done"
+ os.WriteFile(filepath.Join(r.dir, "units", "2.3.status"), []byte("1\n"), 0o600)
+ if m := read(0); m["state"] != "done" || m["status"] != "1" || m["result"] != "failed" {
+ t.Fatalf("a failed unit: %v", m)
+ }
+ os.WriteFile(filepath.Join(r.dir, "units", "2.3.status"), []byte("0\n"), 0o600)
+ if m := read(0); m["result"] != "succeeded" {
+ t.Fatalf("a finished unit: %v", m)
+ }
+ r.systemd.states["hprod-r1-2.3.service"] = "unresolved"
+ if m := read(ExitFail); m["state"] != "unresolved" || m["result"] != "unknown" {
+ t.Fatalf("an unresolved unit: %v", m)
+ }
+ if len(r.ledger().Entries) != lines || len(r.systemd.stopped) != 0 || r.has("RECOVERY", "") || slices.Contains(r.systemd.started, "hprod-r1-recovery.service") {
+ t.Fatalf("unit status acted: journal %d lines (was %d), stopped %v, started %v", len(r.ledger().Entries), lines, r.systemd.stopped, r.systemd.started)
+ }
+ r.want(ExitFail, "unit", "status", "9.9")
+ r.want(ExitFail, "unit", "status")
+}
+
+// K7: a finished block's unit may be started again as BLOCK.retry1, then
+// BLOCK.retry2, each linked in the journal; any other reuse is refused.
+func TestUnitRetry(t *testing.T) {
+ r := newRig(t)
+ r.want(0, "unit", "start", "2.3", "--", "bash", "x")
+ r.want(ExitFail, "unit", "start", "2.3.retry1", "--", "bash", "x") // 2.3 still runs
+ r.systemd.states["hprod-r1-2.3.service"] = "done"
+ os.WriteFile(filepath.Join(r.dir, "units", "2.3.status"), []byte("1\n"), 0o600)
+ r.want(ExitFail, "unit", "start", "2.3.retry2", "--", "bash", "x") // retry1 first
+ r.want(0, "unit", "start", "2.3.retry1", "--", "bash", "x")
+ if !r.has("UNIT-RETRY", "hprod-r1-2.3.retry1.service of=hprod-r1-2.3.service status=1") {
+ t.Fatalf("the retry is not linked:\n%s", journalText(r))
+ }
+ r.systemd.states["hprod-r1-2.3.retry1.service"] = "done"
+ r.want(ExitFail, "unit", "start", "2.3.retry1", "--", "bash", "x")
+ r.want(ExitFail, "unit", "start", "2.3", "--", "bash", "x")
+ r.want(0, "unit", "start", "2.3.retry2", "--", "bash", "x")
+ r.systemd.states["hprod-r1-2.3.retry2.service"] = "done"
+ os.WriteFile(filepath.Join(r.dir, "units", "2.3.retry2.status"), []byte("0\n"), 0o600)
+ r.want(ExitFail, "unit", "start", "2.3.retry3", "--", "bash", "x")
+ r.want(ExitFail, "unit", "start", "2.4.retry1", "--", "bash", "x") // 2.4 never ran
+ r.want(0, "unit", "wait", "2.3.retry2", "--max", "10m")
+}
+
+// K8: ops finding journals a FINDING line, which the report lists.
+func TestFindingCommand(t *testing.T) {
+ r := newRig(t)
+ r.want(0, "finding", "the network apply failed twice")
+ r.want(0, "finding", "skip", "to", "teardown:", "no pin")
+ if !r.has("FINDING", "the network apply failed twice") || !r.has("FINDING", "skip to teardown: no pin") {
+ t.Fatalf("no FINDING lines:\n%s", journalText(r))
+ }
+ r.want(ExitFail, "finding")
+ r.want(ExitStop, "finding", "-----BEGIN PRIVATE KEY-----")
+ r.want(0, "report")
+ b, _ := os.ReadFile(filepath.Join(r.dir, "report.md"))
+ if !strings.Contains(string(b), "FINDING skip to teardown: no pin") {
+ t.Fatalf("the report omits the finding:\n%s", b)
+ }
+}
+
+// The new forms, as the revised plan will write them, through the same
+// extraction and dispatcher as TestPlanInvocationsParse.
+func TestNewInvocationsParse(t *testing.T) {
+ plan := "```sh\n" + strings.Join([]string{
+ `ops block 8.2 --teardown -- bash "$P/blocks/8.2.sh"`,
+ `ops block 8.7 --teardown --optional -- bash "$P/blocks/8.7.sh"`,
+ `ops unit status 2.3`,
+ `ops unit start 2.3.retry1 -- bash "$P/blocks/2.3.sh"`,
+ `ops vms settle --step 6.2-pass --image arn:aws:lambda:eu-west-1:149757027610:microvm-image:equipo-hosted-prod-r1 --max 10m`,
+ `ops vms scan --image arn:aws:lambda:eu-west-1:149757027610:microvm-image:equipo-hosted-prod-r1 --max 2m`,
+ `ops finding "skip to teardown: the controller wrote no pin"`,
+ }, "\n") + "\n```\nProse: `ops unit status`, `ops finding`, `ops vms settle --step <id> --image <image ARN> --max 10m`.\n"
+ invs := planInvocations(plan)
+ if len(invs) != 10 {
+ t.Fatalf("%d invocations: %q", len(invs), invs)
+ }
+ for _, inv := range invs {
+ r := newRig(t, "REC microvm-image "+image1)
+ r.deps.Exec = func(ctxT, []string, []string, wT, wT) int { return 0 }
+ r.ops(inv...)
+ out := r.out.String()
+ if strings.Contains(out, "unknown command") || !bare(inv) && strings.Contains(out, "usage:") {
+ t.Errorf("ops %s: %s", strings.Join(inv, " "), out)
+ }
+ }
+ if !strings.Contains(usageText(), "unit status BLOCK") || !strings.Contains(usageText(), "finding TEXT") {
+ t.Fatalf("the command list does not name the new commands:\n%s", usageText())
+ }
+}
diff --git a/internal/hostedops/ledger.go b/internal/hostedops/ledger.go
index a74b134a..1a4acead 100644
--- a/internal/hostedops/ledger.go
+++ b/internal/hostedops/ledger.go
@@ -143,8 +143,11 @@ type Rec struct {
// VMSeen is a VM ID recorded anywhere, with every source.
type VMSeen struct {
ID, Image string
- First time.Time
- Sources []string
+ // Attempt is the controller's job attempt that owns the VM, from a
+ // controller listing (vms adopt, vms scan): a recorded launch.
+ Attempt string
+ First time.Time
+ Sources []string
}
// Host is an EC2 host the run created (from tofu state).
@@ -288,6 +291,9 @@ func (l *Ledger) apply(e Entry) {
}
case "VM":
l.seeVM(e.Field(0), e.Attr("image"), e.Attr("source"), e.At)
+ if a := e.Attr("attempt"); a != "" && l.VMs[e.Field(0)].Attempt == "" {
+ l.VMs[e.Field(0)].Attempt = a
+ }
case "LAUNCHED": // equipo-hosted-certify: ATTEMPT LAUNCHID
case "RESERVE":
n, _ := strconv.Atoi(e.Field(1))
diff --git a/internal/hostedops/ledgercmd.go b/internal/hostedops/ledgercmd.go
index e5a8144e..afba5ed5 100644
--- a/internal/hostedops/ledgercmd.go
+++ b/internal/hostedops/ledgercmd.go
@@ -131,6 +131,20 @@ func cmdLedgerShow(o *Ops, args []string) error {
return nil
}
+// cmdFinding journals one FINDING line (K8, p34-r1 finding 12): what the
+// plan's skip_to_teardown records, and anything else the run observes that
+// the record must list. The report and grep FINDING read it.
+func cmdFinding(o *Ops, args []string) error {
+ text := strings.TrimSpace(strings.Join(args, " "))
+ if text == "" {
+ return usagef("finding TEXT...")
+ }
+ if looksSecret(text) {
+ return stopf("finding: the text looks like a private key; secrets never enter the journal")
+ }
+ return o.finding("%s", text)
+}
+
// ---- assert and fact --------------------------------------------------
// cmdAssert: "assert WHAT GOT WANT" compares two strings; a named check
diff --git a/internal/hostedops/ops.go b/internal/hostedops/ops.go
index e2bf8d15..617662e8 100644
--- a/internal/hostedops/ops.go
+++ b/internal/hostedops/ops.go
@@ -5,11 +5,51 @@
//
// equipo-hosted-ops -dir P -run RUN [-profile PR -account A -region R [-role ROLE[/SESSION]]] COMMAND ...
//
-// Exit status: 0 success, 1 an ordinary failure, 99 a safety failure (a
-// hard stop; the account plan's section S follows). "unit wait" has no
-// code of its own: it waits until its unit is done (0) or past its bound,
-// and a failed, killed or unresolved unit is 99. Every action writes one
-// journal line.
+// Exit status: 0 success; 1 an ordinary failure, one a pre-approved
+// fallback may retry or skip past; 99 only a safety refusal (a hard stop;
+// the plan's section S follows). A plan branches on the code, never on
+// "non-zero". The classes (Task 34 kit, K2; infra/hosted/README.md keeps
+// the same table):
+//
+// 99 the guard: account, caller, region, identity, frozen credentials
+// a plan-check.py refusal, or a saved plan changed after the check
+// ownership and ledger: a name collision, an ARN of another account,
+// an unresolved intent blocking a teardown, a run directory of
+// another run, a write to the journal failing
+// the spend gate: estimate --stop reached, a block's estimate, a
+// reservation asked for when the estimate is already at the stop,
+// an estimate that cannot be computed, anything that creates
+// inside a teardown block
+// VMs: a live VM neither the controller's nor a recorded launch (vms
+// scan), an image not proved clear (vms settle), a VM ID of an
+// unexpected form
+// fence, controller terminate, unfence and reboot-while-fenced proofs
+// verify-gone: a recorded resource not read gone, or a tagged one the
+// ledger does not hold and no direct read proves absent
+// a bucket or object not reading back as set (settings, checksum)
+// a secret where none may be (journal, report, bundle, variables)
+// named assertions that do not hold (assert), a failed unit (unit
+// wait), an expired human wait, safe-stop with problems
+// 1 usage errors; a read that failed (status, a VM scan still
+// incomplete at its bound, the tag index, the inventory); a tofu
+// plan, apply or destroy that failed after plan-check accepted it
+// (tf reconcile ROOT, then a re-run); a connector create refused,
+// FAILED or not ACTIVE in time; a connector delete not done within
+// its budget while the connector is still recorded; a controller
+// reboot not seen down and back within --max; a reservation the
+// estimate cannot admit; wait object past --max; a bucket create
+// or object put the provider refused; a Litestream restore that
+// could not be read; unit start refusing a busy run or a reused
+// name; unit status unable to read its unit
+//
+// equipo-hosted-image has its own codes: 4 (a guard refused) is a safety
+// refusal; 2 (an AWS call failed), 5 (a wait ran out), 6 (a failed state)
+// and 1 are ordinary; 3 is usage.
+//
+// "unit wait" has no code of its own: it waits until its unit is done (0)
+// or past its bound, and a failed, killed or unresolved unit is 99 (after
+// asking for recovery). "unit status" only reads: 0, or 1 when the read
+// fails. Every action writes one journal line; reads write none.
//
// Every command that calls the provider opens it once (Opener): the
// credentials are resolved once, frozen for the process and verified
@@ -259,8 +299,8 @@ func init() {
"ledger note": {false, cmdLedgerNote, "KEY VALUE..."},
"ledger show": {false, cmdLedgerShow, ""},
"object put": {true, cmdObjectPut, "--bucket B --key K --file F [--expected-owner A]"},
- "vms scan": {true, cmdVMsScan, "--image ARN"},
- "vms settle": {true, cmdVMsSettle, "--image ARN [--terminate] --max D"},
+ "vms scan": {true, cmdVMsScan, "--image ARN [--max D] [controller flags]: 99 on a live VM neither the controller's nor a recorded launch"},
+ "vms settle": {true, cmdVMsSettle, "--image ARN [--terminate | --step ID] --max D"},
"vms reconcile": {true, cmdVMsReconcile, ""},
"vms adopt": {false, cmdVMsAdopt, "[controller flags]"},
"tfvars": {false, cmdTfvars, "--out F ... | --add-image FILE --add-connector"},
@@ -270,9 +310,11 @@ func init() {
"bucket create": {true, cmdBucketCreate, "--name N --versioning --sse AES256 --block-public --expected-owner A"},
"bucket empty": {true, cmdBucketEmpty, "--name N [--expected-owner A]"},
"bucket delete": {true, cmdBucketDelete, "--name N [--expected-owner A]"},
- "block": {false, cmdBlock, "ID [--stop USD] [--optional] -- CMD..."},
- "unit start": {false, cmdUnitStart, "BLOCK -- CMD..."},
+ "block": {false, cmdBlock, "ID [--stop USD | --teardown] [--optional] -- CMD..."},
+ "unit start": {false, cmdUnitStart, "BLOCK[.retry1|.retry2] -- CMD..."},
"unit wait": {false, cmdUnitWait, "BLOCK --max D"},
+ "unit status": {false, cmdUnitStatus, "BLOCK: the unit's state and result as JSON; never stops or recovers"},
+ "finding": {false, cmdFinding, "TEXT...: journal a FINDING line"},
"unit stop": {false, cmdUnitStop, "BLOCK | --all"},
"unit probe": {false, cmdUnitProbe, ""},
"litestream-install": {false, cmdLitestreamInstall, "--file TARBALL"},
@@ -381,6 +423,13 @@ func (o *Ops) main(args []string) int {
o.PlanCheck = []string{"python3", "-I", filepath.Join(o.Repo, "infra", "hosted", "scripts", "plan-check.py")}
}
o.j = &Journal{Path: o.path(JournalFile), Now: o.Clock.Now, noSync: o.noSync}
+ if len(fs.Args()) == 0 || fs.Args()[0] == "help" {
+ fmt.Fprint(o.Stdout, usageText())
+ if len(fs.Args()) == 0 {
+ return ExitFail
+ }
+ return ExitOK
+ }
name, c, rest, ok := lookup(fs.Args())
if !ok && len(fs.Args()) >= 1 {
var subs []string
@@ -410,6 +459,24 @@ func (o *Ops) main(args []string) int {
return o.report(c.run(o, rest))
}
+// usageText is the whole usage: the global flags, every command with its
+// arguments, and the exit classes.
+func usageText() string {
+ var b strings.Builder
+ b.WriteString("usage: equipo-hosted-ops -dir P -run RUN [-profile PR -account A -region R [-role ROLE[/SESSION]]] [-repo DIR] COMMAND ...\n\ncommands:\n")
+ var names []string
+ for n := range commands {
+ names = append(names, n)
+ }
+ sort.Strings(names)
+ for _, n := range names {
+ fmt.Fprintf(&b, " %s %s\n", n, commands[n].help)
+ }
+ b.WriteString("\nexit status: 0 done; 1 an ordinary failure a pre-approved fallback may retry or skip past;\n" +
+ "99 a safety refusal (a hard stop: safe-stop follows). The classes: internal/hostedops's package comment.\n")
+ return b.String()
+}
+
func commandNames() string {
var n []string
for k := range commands {
diff --git a/internal/hostedops/report.go b/internal/hostedops/report.go
index 1d5e0726..4aa324d3 100644
--- a/internal/hostedops/report.go
+++ b/internal/hostedops/report.go
@@ -296,7 +296,7 @@ var coveredBy = map[string]string{
var DirectReadTypes = []string{"aws_s3_bucket", "aws_iam_role", "aws_iam_policy", "aws_iam_instance_profile", "aws_sns_topic",
"aws_cloudtrail", "aws_cloudwatch_metric_alarm", "aws_cloudwatch_log_group", "aws_budgets_budget", "aws_budgets_budget_action",
"aws_vpc", "aws_subnet", "aws_security_group", "aws_route_table", "aws_internet_gateway", "aws_vpc_peering_connection",
- "aws_instance", "aws_eip", "aws_network_acl"}
+ "aws_instance", "aws_eip", "aws_network_acl", "aws_ebs_volume"}
// parentMatches reports whether p is the parent a child names by ID, name
// or ARN.
@@ -387,7 +387,7 @@ func cmdVerifyGone(o *Ops, args []string) error {
}
}
}
- if err := o.tagCrossCheck(); err != nil {
+ if err := o.tagCrossCheck(true); err != nil {
return err
}
if len(present) > 0 {
@@ -412,8 +412,10 @@ func contains(xs []string, s string) bool {
// cmdLitestreamCheck is 5.4: restore the latest generation of
// s3://BUCKET/controller (the controller's replica path) into scratch under
// -dir with the pinned Litestream, under the frozen keys, open it and find
-// the provider_binding row for this account and region. A failure is a
-// hard stop: launches stay off until the database is durable.
+// the provider_binding row for this account and region. A restore that
+// fails or does not read is 1 (the plan decides: production stops on it,
+// the dev drill records a FINDING); a binding to another account or region
+// is 99.
func cmdLitestreamCheck(o *Ops, args []string) error {
fs := flag.NewFlagSet("litestream-check", flag.ContinueOnError)
bucket := fs.String("bucket", "", "the Litestream bucket")
@@ -437,20 +439,26 @@ func cmdLitestreamCheck(o *Ops, args []string) error {
cmd := exec.CommandContext(ctx, o.Litestream, "restore", "-o", db, "s3://"+*bucket+"/controller")
cmd.Env = o.tofuEnv(o.cloud.Keys())
cmd.Stdout, cmd.Stderr = o.Stdout, o.Stderr
+ // Not restored, or not readable: 1 (K2), the database is not shown
+ // durable and the plan decides. Bound to another account or region:
+ // 99, an identity failure.
if err := cmd.Run(); err != nil {
- _ = o.jw("ABORT", "litestream restore failed: %v", err)
- return stopf("the database could not be restored: %v", err)
+ if ferr := o.finding("litestream restore failed: %v", err); ferr != nil {
+ return ferr
+ }
+ return failf("the database could not be restored: %v", err)
}
h, err := sql.Open("sqlite", "file:"+db+"?mode=ro")
if err != nil {
- return stopf("the restored database does not open: %v", err)
+ return failf("the restored database does not open: %v", err)
}
defer h.Close()
var ns string
if err := h.QueryRowContext(ctx, `SELECT namespace FROM provider_binding WHERE id = 1`).Scan(&ns); err != nil {
- return stopf("the restored database holds no provider_binding row: %v", err)
+ return failf("the restored database holds no provider_binding row: %v", err)
}
if want := "aws:" + o.Account + ":" + o.Region; ns != want {
+ _ = o.jw("ABORT", "litestream-check: the restored provider_binding is %q, want %q", ns, want)
return stopf("the restored provider_binding is %q, want %q", ns, want)
}
o.out("litestream-check: restored and opened; provider_binding %s", ns)
diff --git a/internal/hostedops/singleton.go b/internal/hostedops/singleton.go
index 93121feb..8df9f3a4 100644
--- a/internal/hostedops/singleton.go
+++ b/internal/hostedops/singleton.go
@@ -56,7 +56,7 @@ func cmdSingletonEnsure(o *Ops, args []string) error {
name := args[0]
on, prior, err := o.readSingleton(name)
if err != nil {
- return stopf("singleton %s: the read failed: %v", name, err)
+ return failf("singleton %s: the read failed: %v", name, err)
}
if err := o.jw("SINGLETON", "%s prior on=%t %s", name, on, prior); err != nil {
return err
@@ -72,7 +72,7 @@ func cmdSingletonEnsure(o *Ops, args []string) error {
err = o.cloud.EnableEBSDefaultEncryption(o.ctx)
}
if err != nil {
- return stopf("singleton %s: turning it on failed: %v", name, err)
+ return failf("singleton %s: turning it on failed: %v", name, err)
}
on, now, err := o.readSingleton(name)
if err != nil || !on {
@@ -102,7 +102,7 @@ func cmdMFACheck(o *Ops, args []string) error {
}
doc, err := o.cloud.RoleTrustPolicy(o.ctx, name)
if err != nil {
- return stopf("mfa-check: the trust policy of %s did not read: %v", name, err)
+ return failf("mfa-check: the trust policy of %s did not read: %v", name, err)
}
if d, err := url.QueryUnescape(doc); err == nil {
doc = d
@@ -435,7 +435,7 @@ func cmdInventory(o *Ops, args []string) error {
}
inv, err := o.cloud.Inventory(o.ctx)
if err != nil {
- return stopf("inventory: %v", err)
+ return failf("inventory: %v", err) // a read failure: 1 (K2)
}
b, _ := json.MarshalIndent(inv, "", " ")
if err := writeFileAtomic(o.path("inventory.json"), append(b, '\n'), 0o600); err != nil {
diff --git a/internal/hostedops/stop.go b/internal/hostedops/stop.go
index ea46417d..50d0da74 100644
--- a/internal/hostedops/stop.go
+++ b/internal/hostedops/stop.go
@@ -13,18 +13,45 @@ import (
"time"
)
+// TeardownEnv names the teardown block a command runs in: block
+// --teardown sets it in its command's environment.
+const TeardownEnv = "EQUIPO_HOSTED_OPS_TEARDOWN"
+
+// refuseInTeardown is every creating or spend-admitting command's first
+// check: a teardown block skips the spend gate, so nothing inside one may
+// create (K1). 99.
+func (o *Ops) refuseInTeardown(what string) error {
+ b := os.Getenv(TeardownEnv)
+ if b == "" {
+ return nil
+ }
+ _ = o.jw("ABORT", "%s inside teardown block %s", what, b)
+ return stopf("%s refused inside teardown block %s: a teardown block skips the spend gate, so nothing in it creates or admits spend", what, b)
+}
+
// cmdBlock runs one plan block: the guard and the estimate first (99 at the
// stop), then the command. Exit 99 from it, or any non-zero exit of a
// required block (every block is required unless --optional), including a
// failed unit or an expired wait, becomes a hard stop: safe-stop runs here,
// and the block exits 99.
+//
+// --teardown (K1, p34-r1 finding 1) is a teardown block: the guard
+// (account, caller, region) and the ledger's ownership (main refuses
+// another run's directory) run as always, but spend never refuses it: the
+// estimate is computed from the ledger alone, journalled, and not
+// compared; teardown is the safe direction, and waiting costs money. Its
+// command runs with EQUIPO_HOSTED_OPS_TEARDOWN set, and every command that
+// creates or admits spend refuses inside it (refuseInTeardown).
func cmdBlock(o *Ops, args []string) error {
fs := flag.NewFlagSet("block", flag.ContinueOnError)
stop := fs.Float64("stop", DefaultStop, "the run's own spend stop")
optional := fs.Bool("optional", false, "a non-zero exit other than 99 is not a hard stop")
+ teardown := fs.Bool("teardown", false, "a teardown block: the guard and the ledger's ownership, no spend gate; nothing in it may create")
pos, err := parseFlags(fs, args)
- if err != nil || len(pos) < 2 || !blockPattern.MatchString(pos[0]) {
- return usagef("block ID [--stop USD] [--optional] -- CMD...")
+ stopSet := false
+ fs.Visit(func(f *flag.Flag) { stopSet = stopSet || f.Name == "stop" })
+ if err != nil || len(pos) < 2 || !blockPattern.MatchString(pos[0]) || (*teardown && stopSet) {
+ return usagef("block ID [--stop USD | --teardown] [--optional] -- CMD...")
}
id, argv := pos[0], pos[1:]
if err := o.jw("BLOCK", "%s start", id); err != nil {
@@ -41,20 +68,34 @@ func cmdBlock(o *Ops, args []string) error {
if _, err := o.open(); err != nil {
return hard("the guard failed: " + err.Error())
}
- e, err := o.estimate()
- if err != nil {
- return hard("the estimate failed: " + err.Error())
- }
- if err := o.jw("ESTIMATE", "total=%.2f stop=%.2f block=%s", e.Total, *stop, id); err != nil {
- return err
- }
- if err := o.jw("NOTE", "spend-stop %.2f", *stop); err != nil {
- return err
- }
- if e.Total >= *stop {
- return hard("the estimate $" + ftoa(e.Total) + " reaches the stop $" + ftoa(*stop))
+ if *teardown {
+ l, err := o.ledger()
+ if err != nil {
+ return hard("the ledger: " + err.Error())
+ }
+ if e, err := Compute(l, o.Clock.Now()); err != nil {
+ if err := o.finding("block %s: the ledger's estimate does not compute (%v); a teardown block runs regardless", id, err); err != nil {
+ return err
+ }
+ } else if err := o.jw("ESTIMATE", "total=%.2f stop=none block=%s teardown=yes", e.Total, id); err != nil {
+ return err
+ }
+ } else {
+ e, err := o.estimate()
+ if err != nil {
+ return hard("the estimate failed: " + err.Error())
+ }
+ if err := o.jw("ESTIMATE", "total=%.2f stop=%.2f block=%s", e.Total, *stop, id); err != nil {
+ return err
+ }
+ if err := o.jw("NOTE", "spend-stop %.2f", *stop); err != nil {
+ return err
+ }
+ if e.Total >= *stop {
+ return hard("the estimate $" + ftoa(e.Total) + " reaches the stop $" + ftoa(*stop))
+ }
}
- code := o.execBlock(argv, id)
+ code := o.execBlock(argv, id, *teardown)
_ = o.jw("BLOCK", "%s exit=%d", id, code)
switch {
case code == 0:
@@ -67,8 +108,11 @@ func cmdBlock(o *Ops, args []string) error {
return &exitError{code: code, msg: "block " + id + " exited " + itoa(code)}
}
-func (o *Ops) execBlock(argv []string, id string) int {
+func (o *Ops) execBlock(argv []string, id string, teardown bool) int {
env := append(os.Environ(), "EQUIPO_HOSTED_OPS_BLOCK="+id)
+ if teardown {
+ env = append(env, TeardownEnv+"="+id)
+ }
if o.Exec != nil {
return o.Exec(o.ctx, argv, env, o.Stdout, o.Stderr)
}
diff --git a/internal/hostedops/t32_test.go b/internal/hostedops/t32_test.go
index fbb9eada..bcf7597c 100644
--- a/internal/hostedops/t32_test.go
+++ b/internal/hostedops/t32_test.go
@@ -354,7 +354,7 @@ func TestControllerReboot(t *testing.T) {
t.Fatalf("reboot: calls %v, %d status reads:\n%s", r.cloud.log(), ctl.n, journalText(r))
}
r, _ = rebootRig(t, off)
- r.want(ExitStop, "controller", "reboot", "--enabled", "1", "--controller", "https://198.51.100.7", "--max", "2m")
+ r.want(ExitFail, "controller", "reboot", "--enabled", "1", "--controller", "https://198.51.100.7", "--max", "2m") // a timeout (Task 34 kit, K2)
if r.has("REBOOTED", "") {
t.Fatal("a controller that never answered enabled was journalled rebooted")
}
diff --git a/internal/hostedops/tf.go b/internal/hostedops/tf.go
index bdc2e3ce..ba8cb5cd 100644
--- a/internal/hostedops/tf.go
+++ b/internal/hostedops/tf.go
@@ -231,6 +231,11 @@ func cmdTf(o *Ops, args []string) error {
if err != nil {
return err
}
+ if !destroy {
+ if err := o.refuseInTeardown("tf " + root + " " + phase); err != nil {
+ return err
+ }
+ }
l, err := o.ledger()
if err != nil {
return err
@@ -328,8 +333,13 @@ func cmdTf(o *Ops, args []string) error {
return err
}
if _, err := o.tofu("-chdir="+dir, "apply", "-input=false", "-no-color", planFile); err != nil {
- _ = o.jw("ABORT", "apply %s failed: %v", phase, err)
- return stopf("apply of %s failed: %v; run tf reconcile %s", phase, err, root)
+ // An ordinary failure (K2): the plan was the checked one, so
+ // whatever the apply did is within it. The root stays applying
+ // (TF-APPLY start, no done) until tf reconcile ROOT.
+ if ferr := o.finding("apply of %s failed: %v; tf reconcile %s before anything else", phase, err, root); ferr != nil {
+ return ferr
+ }
+ return failf("apply of %s failed: %v; run tf reconcile %s", phase, err, root)
}
if err := o.recordState(root, dir, deletes); err != nil {
return err
@@ -581,7 +591,7 @@ func (o *Ops) tfReconcile(root string) error {
_ = o.finding("tf reconcile %s: no direct read can prove it absent", in.Name)
}
}
- if err := o.tagCrossCheck(); err != nil {
+ if err := o.tagCrossCheck(false); err != nil {
return err
}
if len(left) > 0 {
@@ -591,39 +601,196 @@ func (o *Ops) tfReconcile(root string) error {
return o.jw("TF-RECONCILED", "%s", root)
}
-// tagCrossCheck lists the run's tagged resources and makes a FINDING of
-// each one the ledger does not hold (the index omits untagged resources
-// and lags; it never resolves or deletes anything).
-func (o *Ops) tagCrossCheck() error {
+// tagCrossCheck lists the run's tagged resources (the index omits
+// untagged resources and lags) and compares them with the ledger. A
+// resource the ledger holds and records deleted is a lag FINDING; one it
+// holds otherwise is accounted for. One it does not hold is, with strict
+// (verify-gone, which gates teardown's completion; K3, p34-r1 finding 3),
+// read directly by its ARN: proved absent, a lag FINDING; present, not
+// readable, or of a type with no direct read, a hard stop (99). Without
+// strict (tf reconcile, which gates nothing) it is a FINDING. An index
+// that does not read is a FINDING, and with strict a failure (1):
+// verification cannot pass without its cross-check. It never deletes.
+func (o *Ops) tagCrossCheck(strict bool) error {
arns, err := o.cloud.TaggedARNs(o.ctx, o.Run)
if err != nil {
- return o.finding("tag index unreadable: %v", err)
+ if ferr := o.finding("tag index unreadable: %v", err); ferr != nil {
+ return ferr
+ }
+ if strict {
+ return failf("the tag index did not read (%v); verify-gone cannot pass without its cross-check", err)
+ }
+ return nil
}
l, err := o.ledger()
if err != nil {
return err
}
- known := map[string]bool{}
- for _, r := range l.Recs {
- known[r.Value], known[r.Attr("id")] = true, true
- }
sort.Strings(arns)
+ var unknown []string
for _, a := range arns {
- hit := known[a]
- for k := range known {
- if k != "" && strings.HasSuffix(a, "/"+k) || strings.HasSuffix(a, ":"+k) {
- hit = true
+ r, ok := ledgerHolds(l, a)
+ switch {
+ case ok && l.Deleted[r.Kind+" "+r.Value]:
+ if err := o.finding("the tag index still lists %s, recorded deleted (%s %s): index lag", a, r.Kind, r.Value); err != nil {
+ return err
}
- }
- if !hit {
+ continue
+ case ok:
+ continue
+ case !strict:
if err := o.finding("the tag index lists %s, which the ledger does not hold", a); err != nil {
return err
}
+ continue
}
+ gone, why := o.readAbsent(a)
+ if gone {
+ if err := o.finding("the tag index lists %s, which the ledger does not hold; a direct read proves it absent: index lag", a); err != nil {
+ return err
+ }
+ continue
+ }
+ unknown = append(unknown, a+" ("+why+")")
+ }
+ if len(unknown) > 0 {
+ _ = o.jw("ABORT", "tag index: resources of run %s the ledger does not hold, not proved absent: %s", o.Run, strings.Join(unknown, "; "))
+ return stopf("the tag index lists resources of run %s the ledger does not hold and no direct read proves absent: %s", o.Run, strings.Join(unknown, "; "))
}
return nil
}
+// ledgerHolds finds the record a tagged ARN is: by its value or ID, the
+// ARN itself or its last part, or by the type and name the ARN names.
+func ledgerHolds(l *Ledger, arn string) (Rec, bool) {
+ key, typed := arnLookupKey(arn)
+ for _, r := range l.Recs {
+ for _, k := range []string{r.Value, r.Attr("id")} {
+ if k != "" && (arn == k || strings.HasSuffix(arn, "/"+k) || strings.HasSuffix(arn, ":"+k)) {
+ return r, true
+ }
+ }
+ if typed && r.Kind == "tf" && r.Attr("type") == key.Type {
+ last := key.ID[strings.LastIndexAny(key.ID, "/:")+1:]
+ if id := r.Attr("id"); id == key.ID || id == last || strings.HasSuffix(id, ":"+last) || r.Attr("rname") == last {
+ return r, true
+ }
+ }
+ }
+ return Rec{}, false
+}
+
+// readAbsent reads a tagged ARN directly: true when the read proves it
+// absent; otherwise why not.
+func (o *Ops) readAbsent(arn string) (bool, string) {
+ if id, ok := strings.CutPrefix(arnResource(arn), "network-interface/"); ok && strings.HasPrefix(arn, "arn:aws:ec2:") {
+ there, err := o.cloud.InterfaceExists(o.ctx, id)
+ switch {
+ case err != nil:
+ return false, "unreadable: " + err.Error()
+ case there:
+ return false, "present"
+ }
+ return true, ""
+ }
+ key, ok := arnLookupKey(arn)
+ if !ok {
+ return false, "no direct read for its type"
+ }
+ key.Run = o.Run
+ res, err := o.cloud.Lookup(o.ctx, key)
+ switch {
+ case err != nil:
+ return false, "unreadable: " + err.Error()
+ case len(res.IDs) > 0:
+ return false, "present"
+ case !res.Definitive:
+ return false, "no direct read proves it absent"
+ }
+ return true, ""
+}
+
+// arnResource is an ARN's resource part ("" when it is not an ARN).
+func arnResource(arn string) string {
+ p := strings.SplitN(arn, ":", 6)
+ if len(p) != 6 || p[0] != "arn" {
+ return ""
+ }
+ return p[5]
+}
+
+// ec2ARNTypes are the EC2 resource types of an ARN and their direct read
+// (Lookup) types.
+var ec2ARNTypes = map[string]string{"vpc": "aws_vpc", "subnet": "aws_subnet", "security-group": "aws_security_group",
+ "route-table": "aws_route_table", "internet-gateway": "aws_internet_gateway", "vpc-peering-connection": "aws_vpc_peering_connection",
+ "instance": "aws_instance", "elastic-ip": "aws_eip", "network-acl": "aws_network_acl", "volume": "aws_ebs_volume"}
+
+// arnLookupKey maps a tagged ARN to the direct read of its type (Lookup's
+// key): false when there is none.
+func arnLookupKey(arn string) (LookupKey, bool) {
+ p := strings.SplitN(arn, ":", 6)
+ if len(p) != 6 || p[0] != "arn" || p[1] != "aws" {
+ return LookupKey{}, false
+ }
+ service, res := p[2], p[5]
+ typ, id, ok := "", "", false
+ cut := func(prefix string) string {
+ v, found := strings.CutPrefix(res, prefix)
+ if found && v != "" {
+ ok = true
+ }
+ return v
+ }
+ switch service {
+ case "s3":
+ if res != "" && !strings.Contains(res, "/") {
+ typ, id, ok = "aws_s3_bucket", res, true
+ }
+ case "iam":
+ switch {
+ case strings.HasPrefix(res, "role/"):
+ typ, id, ok = "aws_iam_role", arn, true
+ case strings.HasPrefix(res, "policy/"):
+ typ, id, ok = "aws_iam_policy", arn, true
+ case strings.HasPrefix(res, "instance-profile/"):
+ typ, id = "aws_iam_instance_profile", res[strings.LastIndex(res, "/")+1:]
+ ok = id != ""
+ }
+ case "sns":
+ if res != "" && !strings.Contains(res, ":") {
+ typ, id, ok = "aws_sns_topic", arn, true
+ }
+ case "cloudtrail":
+ typ, id = "aws_cloudtrail", cut("trail/")
+ case "cloudwatch":
+ typ, id = "aws_cloudwatch_metric_alarm", cut("alarm:")
+ case "logs":
+ typ, id = "aws_cloudwatch_log_group", strings.TrimSuffix(cut("log-group:"), ":*")
+ case "budgets":
+ if v := cut("budget/"); !strings.Contains(v, "/") {
+ typ, id = "aws_budgets_budget", v
+ } else {
+ ok = false
+ }
+ case "ec2":
+ if kind, v, found := strings.Cut(res, "/"); found && ec2ARNTypes[kind] != "" && v != "" && !strings.Contains(v, "/") {
+ typ, id, ok = ec2ARNTypes[kind], v, true
+ }
+ case "lambda":
+ if v := cut("network-connector:"); v != "" && !strings.Contains(v, ":") {
+ typ, id = "connector", arn
+ } else if v := cut("microvm-image:"); v != "" && !strings.Contains(v, ":") {
+ typ, id = "microvm-image", arn
+ } else {
+ ok = false
+ }
+ }
+ if !ok || id == "" {
+ return LookupKey{}, false
+ }
+ return LookupKey{Type: typ, ID: id}, true
+}
+
// reconcileLedger is ledger reconcile: every open intent but OpenTofu's
// (tf reconcile) and the VM launches' (settle) is looked up directly.
func (o *Ops) reconcileLedger() error {
@@ -894,7 +1061,11 @@ func (o *Ops) adoptPending(root, dir, vars string) error {
return stopf("the saved adoption plan is not the one plan-check accepted; nothing imported")
}
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)
+ // Ordinary (K2): the checked adoption plan only imports.
+ if ferr := o.finding("the adoption apply of %s failed: %v", root, err); ferr != nil {
+ return ferr
+ }
+ return failf("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 {
diff --git a/internal/hostedops/unfence.go b/internal/hostedops/unfence.go
index c016ef39..6149bcde 100644
--- a/internal/hostedops/unfence.go
+++ b/internal/hostedops/unfence.go
@@ -216,7 +216,7 @@ func cmdControllerReboot(o *Ops, args []string) error {
return err
}
if err := o.cloud.RebootInstance(o.ctx, ids[0]); err != nil {
- return stopf("rebooting %s failed: %v", ids[0], err)
+ return failf("rebooting %s failed: %v", ids[0], err)
}
want := *enabled == "1"
end := o.Clock.Now().Add(*maxD)
@@ -230,11 +230,15 @@ func cmdControllerReboot(o *Ops, args []string) error {
return o.jw("REBOOTED", "%s enabled=%t", ids[0], st.Enabled)
}
if !o.Clock.Now().Add(15 * time.Second).Before(end) {
- _ = o.jw("ABORT", "controller reboot: %s did not go away and answer with enabled %t within %s (went away %t, %v)", ids[0], want, *maxD, away, err)
- return stopf("the controller did not go away and answer with launches enabled %t within %s after its reboot (went away %t, %v)", want, *maxD, away, err)
+ // Ordinary (K2): a timeout. A plan whose VMs may run treats it
+ // as its own stop.
+ if ferr := o.finding("controller reboot: %s did not go away and answer with enabled %t within %s (went away %t, %v)", ids[0], want, *maxD, away, err); ferr != nil {
+ return ferr
+ }
+ return failf("the controller did not go away and answer with launches enabled %t within %s after its reboot (went away %t, %v)", want, *maxD, away, err)
}
if err := o.Clock.Sleep(o.ctx, 15*time.Second); err != nil {
- return stopf("interrupted: %v", err)
+ return failf("interrupted: %v", err)
}
}
}
diff --git a/internal/hostedops/units.go b/internal/hostedops/units.go
index 763fe32b..8a055dd4 100644
--- a/internal/hostedops/units.go
+++ b/internal/hostedops/units.go
@@ -3,6 +3,7 @@ package hostedops
import (
"bytes"
"context"
+ "encoding/json"
"errors"
"flag"
"fmt"
@@ -76,9 +77,20 @@ func (o *Ops) busy(l *Ledger, except string) []string {
return b
}
+// retryPattern is a retry's block name, BLOCK.retryN (K7).
+var retryPattern = regexp.MustCompile(`^(.+)\.retry([0-9]+)$`)
+
+// MaxRetries is how many times a finished block's unit may run again.
+const MaxRetries = 2
+
+// cmdUnitStart starts a block's unit. A block name is used once; the one
+// reuse (K7, p34-r1 finding 9) is BLOCK.retryN, N from 1 to MaxRetries,
+// started only once BLOCK (and BLOCK.retry1 .. N-1) were journalled and
+// read done, failed or not; the link is journalled (UNIT-RETRY). Any other
+// reuse, a retry out of order, or a busy run is refused (1).
func cmdUnitStart(o *Ops, args []string) error {
if len(args) < 3 || args[1] != "--" || !blockPattern.MatchString(args[0]) {
- return usagef("unit start BLOCK -- CMD...")
+ return usagef("unit start BLOCK[.retry1|.retry2] -- CMD...")
}
l, err := o.ledger()
if err != nil {
@@ -87,10 +99,97 @@ 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:], 45*time.Second, false); err != nil {
+ block := args[0]
+ var link string
+ if m := retryPattern.FindStringSubmatch(block); m != nil {
+ n, _ := strconv.Atoi(m[2])
+ if n < 1 || n > MaxRetries {
+ return failf("REFUSED: %s: a block runs again at most %d times (%s.retry1 to .retry%d)", block, MaxRetries, m[1], MaxRetries)
+ }
+ prev := m[1]
+ for i := 1; i <= n; i++ {
+ u := o.unitName(prev)
+ if !slices.Contains(l.Units, u) {
+ return failf("REFUSED: %s: %s was never started", block, u)
+ }
+ if st := o.Systemd.State(u); st != "done" {
+ return failf("REFUSED: %s: %s is %s, not finished", block, u, st)
+ }
+ if i < n {
+ prev = fmt.Sprintf("%s.retry%d", m[1], i)
+ }
+ }
+ st, _ := os.ReadFile(o.path("units", prev+".status"))
+ link = fmt.Sprintf("%s of=%s status=%s", o.unitName(block), o.unitName(prev), strings.TrimSpace(string(st)))
+ }
+ if slices.Contains(l.Units, o.unitName(block)) {
+ return failf("REFUSED: block %s was already started as %s; a finished block runs again only as %s.retry1 or .retry2", block, o.unitName(block), block)
+ }
+ if link != "" {
+ if err := o.jw("UNIT-RETRY", "%s", link); err != nil {
+ return err
+ }
+ }
+ if err := o.startUnit(block, args[2:], 45*time.Second, false); err != nil {
return err
}
- o.out("block %s started as unit %s", args[0], o.unitName(args[0]))
+ o.out("block %s started as unit %s", block, o.unitName(block))
+ return nil
+}
+
+// cmdUnitStatus reads one block's unit (K5, p34-r1 finding 5): its state
+// (running, done or unresolved), its exit status once done, a result
+// (running, succeeded, failed or unknown), its start and how long it has
+// run, and whether unit wait has seen it end, as one JSON line. It never
+// stops the unit, never asks for recovery, never waits and writes nothing
+// to the journal. Exit 0 on a read; 1 when the block was not started or
+// its state cannot be established. A plan polls it in short calls; unit
+// wait, once status reads done, applies the bound and the stop rules.
+func cmdUnitStatus(o *Ops, args []string) error {
+ if len(args) != 1 || !blockPattern.MatchString(args[0]) {
+ return usagef("unit status BLOCK")
+ }
+ block := args[0]
+ l, err := o.ledger()
+ if err != nil {
+ return err
+ }
+ u := o.unitName(block)
+ if !slices.Contains(l.Units, u) {
+ return failf("block %s was not started", block)
+ }
+ raw, err := os.ReadFile(o.path("units", block+".start"))
+ if err != nil {
+ return failf("block %s has no start time", block)
+ }
+ sec, _ := strconv.ParseInt(strings.TrimSpace(string(raw)), 10, 64)
+ start := time.Unix(sec, 0)
+ state := o.Systemd.State(u)
+ st := map[string]any{"block": block, "unit": u, "state": state, "status": "", "result": "unknown",
+ "started_unix": sec, "elapsed_seconds": int64(o.Clock.Now().Sub(start).Seconds()), "waited": false}
+ for _, e := range l.Entries {
+ if e.Verb == "UNIT-DONE" && e.Field(0) == u {
+ st["waited"] = true
+ }
+ }
+ switch state {
+ case "running":
+ st["result"] = "running"
+ case "done":
+ b, _ := os.ReadFile(o.path("units", block+".status"))
+ status := strings.TrimSpace(string(b))
+ st["status"] = status
+ if status == "0" {
+ st["result"] = "succeeded"
+ } else if status != "" {
+ st["result"] = "failed"
+ }
+ }
+ js, _ := json.Marshal(st)
+ o.out("%s", js)
+ if state != "running" && state != "done" {
+ return failf("unit %s: its state cannot be established (%s)", u, state)
+ }
return nil
}
diff --git a/internal/hostedops/vms.go b/internal/hostedops/vms.go
index 6f5103ff..e9636a1c 100644
--- a/internal/hostedops/vms.go
+++ b/internal/hostedops/vms.go
@@ -6,8 +6,11 @@ import (
"flag"
"fmt"
"slices"
+ "strconv"
"strings"
"time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
)
// VM settlement is provider-level and image-scoped: the provider's own list
@@ -21,19 +24,27 @@ const (
defaultSettle = 15 * time.Minute
)
-// recordVMs writes a VM line for each ID not yet recorded from source.
+// recordVMs writes a VM line for each ID not yet recorded from source (or
+// recorded without the attempt the controller now names).
func (o *Ops) recordVMs(l *Ledger, vms []VM, source string) error {
for _, v := range vms {
if !strings.HasPrefix(v.ID, "microvm-") && !strings.HasPrefix(v.ID, "vm-") {
return stopf("the provider listed a VM with an unexpected ID %q", v.ID)
}
- if s := l.VMs[v.ID]; s != nil && slices.Contains(s.Sources, source) {
+ if s := l.VMs[v.ID]; s != nil && slices.Contains(s.Sources, source) && (v.Attempt == "" || s.Attempt != "") {
continue
}
- if err := o.jw("VM", "%s source=%s image=%s state=%s", v.ID, source, v.Image, v.State); err != nil {
+ text := fmt.Sprintf("%s source=%s image=%s state=%s", v.ID, source, v.Image, v.State)
+ if v.Attempt != "" {
+ text += " attempt=" + v.Attempt
+ }
+ if err := o.jw("VM", "%s", text); err != nil {
return err
}
l.seeVM(v.ID, v.Image, source, o.Clock.Now())
+ if s := l.VMs[v.ID]; v.Attempt != "" && s.Attempt == "" {
+ s.Attempt = v.Attempt
+ }
}
return nil
}
@@ -53,12 +64,32 @@ func (o *Ops) runImage(l *Ledger, image string) error {
return stopf("image %s is not one of this run's recorded images", image)
}
+// AdoptGrace is how long a live VM may stay unexplained before vms scan
+// stops on it: a launch's VM shows no attempt in the controller's table
+// until its Ref is saved (hostedctl ListVMs), which takes seconds.
+const AdoptGrace = 2 * time.Minute
+
+// cmdVMsScan is the VM accounting check (K4, p34-r1 finding 4). It lists
+// the image's VMs from the provider first; then, only if a live VM is not
+// already a recorded launch (a ledger VM with a controller attempt), it
+// reads the controller's table through the pin (GET /v1/vms, vms adopt's
+// route). A VM the provider lists before the controller's read was
+// launched before it, so the controller knows it. Each live VM must be the
+// controller's (an attempt) or a recorded launch. One that is neither is
+// read directly: ended, it is nothing; still live, and seen for at least
+// AdoptGrace (by the ledger's first sighting or the controller's age), it
+// is a hard stop (99), recorded first so settle and the estimate keep it;
+// younger, it is a FINDING, judged at the next scan. Every VM is recorded
+// after the comparison. A scan still incomplete at --max, or a controller
+// that does not answer while a live VM is unexplained, is 1: the read
+// failed, and settle stays the backstop.
func cmdVMsScan(o *Ops, args []string) error {
fs := flag.NewFlagSet("vms scan", flag.ContinueOnError)
image := imageFlag(fs)
maxD := fs.Duration("max", 0, "how long an incomplete scan may be retried (0: one attempt)")
+ ca := controllerFlags(fs)
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *maxD < 0 || *maxD > MaxSettle {
- return usagef("vms scan --image ARN [--max D]")
+ return usagef("vms scan --image ARN [--max D] [controller flags]")
}
l, err := o.ledger()
if err != nil {
@@ -69,14 +100,77 @@ func cmdVMsScan(o *Ops, args []string) error {
}
vms, err := o.scanVMs(o.cloud, *image, *maxD, "vms scan")
if err != nil {
- return stopf("the VM scan is incomplete: %v", err)
+ return failf("the VM scan is incomplete: %v", err)
+ }
+ var suspects []VM
+ for _, v := range vms {
+ if s := l.VMs[v.ID]; Live(v.State) && (s == nil || s.Attempt == "") {
+ suspects = append(suspects, v)
+ }
+ }
+ ctl := map[string]hostedwire.VMView{}
+ var ctlErr error
+ if len(suspects) > 0 {
+ var cl ControllerClient
+ if cl, ctlErr = o.controller(ca); ctlErr == nil {
+ var list hostedwire.VMListResponse
+ if list, ctlErr = cl.VMs(o.ctx); ctlErr == nil {
+ var seen []VM
+ for _, v := range list.VMs {
+ ctl[string(v.VMRef)] = v
+ seen = append(seen, VM{ID: string(v.VMRef), State: string(v.State), Attempt: v.AttemptID})
+ }
+ if err := o.recordVMs(l, seen, "controller"); err != nil {
+ return err
+ }
+ }
+ }
}
if err := o.recordVMs(l, vms, "scan"); err != nil {
return err
}
+ var unexplained, pending []string
+ for _, v := range suspects {
+ cv, listed := ctl[v.ID]
+ if listed && cv.AttemptID != "" {
+ continue // the controller's job
+ }
+ if g, err := o.cloud.GetVM(o.ctx, v.ID); errors.Is(err, ErrNotFound) || err == nil && !Live(g.State) {
+ continue // it ended since the scan
+ }
+ if ctlErr != nil {
+ pending = append(pending, v.ID)
+ continue
+ }
+ age := o.Clock.Now().Sub(l.VMs[v.ID].First)
+ if listed && cv.AgeKnown && time.Duration(cv.AgeMS)*time.Millisecond > age {
+ age = time.Duration(cv.AgeMS) * time.Millisecond
+ }
+ if age >= AdoptGrace {
+ unexplained = append(unexplained, v.ID)
+ } else {
+ pending = append(pending, v.ID)
+ }
+ }
b, _ := json.Marshal(vms)
o.out("%s", b)
- return o.jw("SCAN", "image=%s listed=%d live=%d", *image, len(vms), countLive(vms))
+ if err := o.jw("SCAN", "image=%s listed=%d live=%d unexplained=%d pending=%d", *image, len(vms), countLive(vms), len(unexplained), len(pending)); err != nil {
+ return err
+ }
+ if len(unexplained) > 0 {
+ _ = o.jw("ABORT", "vms scan: live VMs of %s neither the controller's nor a recorded launch: %s", *image, strings.Join(unexplained, " "))
+ return stopf("live VMs of %s are neither the controller's (a job's attempt) nor a recorded launch: %s (hard stop)", *image, strings.Join(unexplained, " "))
+ }
+ if ctlErr != nil && len(pending) > 0 {
+ if err := o.finding("vms scan: %d live VMs cannot be accounted for, the controller did not answer: %v (%s)", len(pending), ctlErr, strings.Join(pending, " ")); err != nil {
+ return err
+ }
+ return failf("vms scan: the controller's table did not read (%v); %s not accounted for", ctlErr, strings.Join(pending, " "))
+ }
+ if len(pending) > 0 {
+ return o.finding("vms scan: live VMs no job owns yet, under %s old: %s; the next scan judges them", AdoptGrace, strings.Join(pending, " "))
+ }
+ return nil
}
// The waits before an incomplete scan is tried again: the first, doubling
@@ -246,9 +340,10 @@ func cmdVMsSettle(o *Ops, args []string) error {
fs := flag.NewFlagSet("vms settle", flag.ContinueOnError)
image := imageFlag(fs)
terminate := fs.Bool("terminate", false, "terminate every target and live VM first")
+ step := fs.String("step", "", "prove the VMs of this plan step ended, within --max of the step's end")
maxD := fs.Duration("max", defaultSettle, "the bound")
- if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 {
- return usagef("vms settle --image ARN [--terminate] --max D")
+ if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || (*step != "" && (*terminate || !blockPattern.MatchString(*step))) {
+ return usagef("vms settle --image ARN [--terminate | --step ID] --max D")
}
if *maxD <= 0 || *maxD > MaxSettle {
return failf("--max must be positive and at most %s", MaxSettle)
@@ -260,9 +355,87 @@ func cmdVMsSettle(o *Ops, args []string) error {
if err := o.runImage(l, *image); err != nil {
return err
}
+ if *step != "" {
+ return o.settleStep(l, *step, *image, *maxD)
+ }
return o.settleImage(*image, *terminate, *maxD)
}
+// settleStep is vms settle --step (K4, p34-r1 finding 4): the plan calls it
+// when a step (one hosted check, one drill) has ended, before the next
+// begins. The step's end is its first STEP-END line; a re-run keeps it, so
+// the bound is never renewed. Its VMs are the image's VMs first recorded
+// since the image's last STEP-SETTLED. It proves, within max of the end,
+// that no VM of the image is live (CleanScans clean scans) and that a
+// direct read shows each of the step's VMs ended; it terminates nothing.
+// Proved: STEP-SETTLED STEP image= vms= ended= after=. Not proved by the
+// bound: 99, hard stop 3 (a VM live 10 minutes after its step ended). A
+// step already settled is refused (1).
+func (o *Ops) settleStep(l *Ledger, step, image string, maxD time.Duration) error {
+ var ended time.Time
+ var since int // the line after the image's last STEP-SETTLED
+ for _, e := range l.Entries {
+ switch {
+ case e.Verb == "STEP-SETTLED" && e.Attr("image") == image:
+ if e.Field(0) == step {
+ return failf("step %s was already settled", step)
+ }
+ since = e.Line
+ case e.Verb == "STEP-END" && e.Field(0) == step && ended.IsZero():
+ if sec, err := strconv.ParseInt(e.Attr("at"), 10, 64); err == nil {
+ ended = time.Unix(sec, 0)
+ }
+ }
+ }
+ if ended.IsZero() {
+ ended = o.Clock.Now()
+ if err := o.jw("STEP-END", "%s image=%s at=%d max=%s", step, image, ended.Unix(), maxD); err != nil {
+ return err
+ }
+ }
+ var vms []string
+ for _, e := range l.Entries {
+ if e.Verb == "VM" && e.Line > since && (e.Attr("image") == "" || e.Attr("image") == image) && !slices.Contains(vms, e.Field(0)) {
+ if v := l.VMs[e.Field(0)]; v != nil && v.First.Equal(e.At) {
+ vms = append(vms, e.Field(0))
+ }
+ }
+ }
+ deadline := ended.Add(maxD)
+ stop := func(why string) error {
+ _ = o.jw("ABORT", "settle --step %s: %s; image %s not proved clear within %s of the step's end", step, why, image, maxD)
+ return stopf("a VM of image %s may be live %s after step %s ended (hard stop 3): %s", image, maxD, step, why)
+ }
+ for {
+ left := deadline.Sub(o.Clock.Now())
+ if left <= 0 {
+ return stop("the bound has passed")
+ }
+ if err := o.settle(image, false, left); err != nil {
+ if IsStop(err) {
+ return stop(err.Error())
+ }
+ return err
+ }
+ live, err := o.liveByDirectRead(vms, true)
+ if err != nil {
+ return err
+ }
+ if len(live) == 0 {
+ break
+ }
+ if err := o.finding("settle --step %s: clean scans, but a direct read shows %s not ended", step, strings.Join(live, " ")); err != nil {
+ return err
+ }
+ if err := o.Clock.Sleep(o.ctx, ScanGap); err != nil {
+ return stop(fmt.Sprintf("interrupted: %v", err))
+ }
+ }
+ after := o.Clock.Now().Sub(ended).Round(time.Second)
+ o.out("step %s: its VMs (%s) ended; image %s clear %s after the step's end", step, strings.Join(vms, " "), image, after)
+ return o.jw("STEP-SETTLED", "%s image=%s vms=%s ended=%d after=%s", step, image, strings.Join(vms, ","), ended.Unix(), after)
+}
+
// settleImage is settle, and with terminate R.4's repeat: after the proof,
// RepeatAfter later, the scan again, settling anything a launch already in
// flight started.
@@ -308,7 +481,7 @@ func cmdVMsReconcile(o *Ops, args []string) error {
for _, r := range l.Recorded("microvm-image") {
vms, err := o.cloud.ListVMs(o.ctx, r.Value)
if err != nil {
- return stopf("vms reconcile: the scan of %s is incomplete: %v", r.Value, err)
+ return failf("vms reconcile: the scan of %s is incomplete: %v", r.Value, err) // a read failure (K2)
}
if err := o.recordVMs(l, vms, "scan"); err != nil {
return err
@@ -336,7 +509,8 @@ func cmdVMsReconcile(o *Ops, args []string) error {
}
// cmdVMsAdopt records every VM the controller's GET /v1/vms lists, with
-// source controller (account plan 8.2).
+// source controller and the attempt that owns it (account plan 8.2): an
+// owned VM is a recorded launch for vms scan.
func cmdVMsAdopt(o *Ops, args []string) error {
fs := flag.NewFlagSet("vms adopt", flag.ContinueOnError)
ca := controllerFlags(fs)
@@ -357,7 +531,7 @@ func cmdVMsAdopt(o *Ops, args []string) error {
}
var vms []VM
for _, v := range list.VMs {
- vms = append(vms, VM{ID: string(v.VMRef), State: string(v.State)})
+ vms = append(vms, VM{ID: string(v.VMRef), State: string(v.State), Attempt: v.AttemptID})
}
if err := o.recordVMs(l, vms, "controller"); err != nil {
return err
diff --git a/internal/hostedops/vms_test.go b/internal/hostedops/vms_test.go
index 9a8b9ca9..d2d2e860 100644
--- a/internal/hostedops/vms_test.go
+++ b/internal/hostedops/vms_test.go
@@ -92,7 +92,7 @@ func TestReservationAdmittedAndConsumed(t *testing.T) {
t.Fatalf("after one VM: reserved %d, lines %+v", l.VMReserved, e.Lines)
}
r.want(0, "reserve", "build", "1")
- r.want(ExitStop, "reserve", "vm", "20")
+ r.want(ExitFail, "reserve", "vm", "20") // an admission refusal, not the spend gate (Task 34 kit, K2)
if l := r.ledger(); l.VMReserved != 1 {
t.Fatalf("a refused reservation was recorded: %d", l.VMReserved)
}
@@ -262,7 +262,7 @@ func TestConnectorDeleteFallback(t *testing.T) {
t.Fatal("the connector or its interface was not recorded deleted")
}
r = setup(t, true)
- r.want(ExitStop, "connector", "delete")
+ r.want(ExitFail, "connector", "delete") // the connector is still recorded: a re-run retries (Task 34 kit, K2)
if r.cloud.nDeleteConn != 2 || r.cloud.count("PutRolePolicy") != 1 {
t.Fatalf("after a second failure: %d deletes, %d policy writes; want 2 and 1", r.cloud.nDeleteConn, r.cloud.count("PutRolePolicy"))
}
diff --git a/internal/isolatedjob/awsjob/opsaws/cloud.go b/internal/isolatedjob/awsjob/opsaws/cloud.go
index 6176996c..42f6d5ca 100644
--- a/internal/isolatedjob/awsjob/opsaws/cloud.go
+++ b/internal/isolatedjob/awsjob/opsaws/cloud.go
@@ -50,7 +50,7 @@ type cloud struct {
var notFoundCodes = []string{"ResourceNotFoundException", "NotFound", "NoSuchBucket", "NoSuchKey", "NoSuchEntity",
"InvalidInstanceID.NotFound", "InvalidNetworkInterfaceID.NotFound", "InvalidVpcID.NotFound", "InvalidSubnetID.NotFound",
"InvalidGroup.NotFound", "InvalidRouteTableID.NotFound", "InvalidInternetGatewayID.NotFound",
- "InvalidVpcPeeringConnectionID.NotFound", "InvalidAllocationID.NotFound", "InvalidNetworkAclID.NotFound",
+ "InvalidVpcPeeringConnectionID.NotFound", "InvalidAllocationID.NotFound", "InvalidNetworkAclID.NotFound", "InvalidVolume.NotFound",
"TrailNotFoundException", "NotFoundException", "NoSuchPublicAccessBlockConfiguration", "ResourceNotFound"}
func httpStatus(err error) int {
diff --git a/internal/isolatedjob/awsjob/opsaws/kit34_test.go b/internal/isolatedjob/awsjob/opsaws/kit34_test.go
new file mode 100644
index 00000000..aca8e919
--- /dev/null
+++ b/internal/isolatedjob/awsjob/opsaws/kit34_test.go
@@ -0,0 +1,55 @@
+package opsaws
+
+import (
+ "context"
+ "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/ec2"
+ ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+ "github.com/aws/smithy-go"
+)
+
+// Task 34 kit, K3: verify-gone may meet a host's root volume in the tag
+// index after the host is gone (the index lags). A direct read by ID
+// proves it absent: not found, or deleted. A volume still deleting, or in
+// use, is there.
+func TestLookupVolumeByID(t *testing.T) {
+ vol := func(st ec2types.VolumeState) (any, error) {
+ return &ec2.DescribeVolumesOutput{Volumes: []ec2types.Volume{{VolumeId: aws.String("vol-1"), State: st}}}, nil
+ }
+ for name, c := range map[string]struct {
+ answer func() (any, error)
+ ids []string
+ definite bool
+ err bool
+ }{
+ "in use": {answer: func() (any, error) { return vol(ec2types.VolumeStateInUse) }, ids: []string{"vol-1"}, definite: true},
+ "deleting": {answer: func() (any, error) { return vol(ec2types.VolumeStateDeleting) }, ids: []string{"vol-1"}, definite: true},
+ "deleted": {answer: func() (any, error) { return vol(ec2types.VolumeStateDeleted) }, definite: true},
+ "not found": {answer: func() (any, error) { return nil, &smithy.GenericAPIError{Code: "InvalidVolume.NotFound"} }, definite: true},
+ "throttled": {answer: func() (any, error) { return nil, &smithy.GenericAPIError{Code: "RequestLimitExceeded"} }, err: true},
+ } {
+ t.Run(name, func(t *testing.T) {
+ var asked []string
+ cl, _ := openFake(t, func(c2 call) (any, error) {
+ in, ok := c2.In.(*ec2.DescribeVolumesInput)
+ if !ok {
+ return nil, fmt.Errorf("unexpected %s", c2.Op)
+ }
+ asked = in.VolumeIds
+ return c.answer()
+ })
+ res, err := cl.Lookup(context.Background(), hostedops.LookupKey{Type: "aws_ebs_volume", ID: "vol-1", Run: "r1"})
+ if (err != nil) != c.err || res.Definitive != c.definite || !slices.Equal(res.IDs, c.ids) {
+ t.Fatalf("volume lookup %+v, %v", res, err)
+ }
+ if !slices.Equal(asked, []string{"vol-1"}) {
+ t.Fatalf("asked for %v, want vol-1 by ID", asked)
+ }
+ })
+ }
+}
diff --git a/internal/isolatedjob/awsjob/opsaws/lookup.go b/internal/isolatedjob/awsjob/opsaws/lookup.go
index 5f7bcf53..17b337be 100644
--- a/internal/isolatedjob/awsjob/opsaws/lookup.go
+++ b/internal/isolatedjob/awsjob/opsaws/lookup.go
@@ -169,7 +169,7 @@ func (c *cloud) Lookup(ctx context.Context, k hostedops.LookupKey) (hostedops.Lo
_, err := c.cl.budgets.DescribeBudget(ctx, &budgets.DescribeBudgetInput{AccountId: aws.String(c.want.account), BudgetName: aws.String(id)})
return found(err, id)
case "aws_vpc", "aws_subnet", "aws_security_group", "aws_route_table", "aws_internet_gateway",
- "aws_vpc_peering_connection", "aws_instance", "aws_eip", "aws_network_acl":
+ "aws_vpc_peering_connection", "aws_instance", "aws_eip", "aws_network_acl", "aws_ebs_volume":
if k.ID == "" {
return c.ec2ByIdentity(ctx, k.Type, k)
}
@@ -228,6 +228,18 @@ func (c *cloud) ec2ByID(ctx context.Context, typ, id string) (hostedops.LookupRe
}
}
}
+ case "aws_ebs_volume":
+ // A host's root volume, which verify-gone may meet in the tag
+ // index after the host is gone (K3): deleted counts as gone; a
+ // volume still deleting is there.
+ var r *ec2.DescribeVolumesOutput
+ if r, err = c.cl.ec2.DescribeVolumes(ctx, &ec2.DescribeVolumesInput{VolumeIds: []string{id}}); err == nil {
+ for _, v := range r.Volumes {
+ if v.State != ec2types.VolumeStateDeleted {
+ n++
+ }
+ }
+ }
case "aws_instance":
st, ierr := c.InstanceState(ctx, id)
if ierr == nil && st != "terminated" {