| 1 | # Hosted runners 1a, Task 17b: live plan for sections 7 and 8 (for Paul's approval) |
| 2 | |
| 3 | **Revision:** 1 (2026-11-30), derived from the Task 17 plan revision 5 |
| 4 | (`docs/superpowers/plans/2026-11-23-hosted-1a-task17-live-plan.md`, `52a771ad`), which attempt 4 |
| 5 | ran to completion on 2026-11-28 with sections 7 and 8 skipped by a plan defect (evidence |
| 6 | `f0e0b525`). **Status:** draft for approval. No AWS command or SDK call of any kind was made while |
| 7 | writing it. This plan is self-contained: the executor runs it alone, block by block, and never |
| 8 | needs revision 5. |
| 9 | |
| 10 | ## What Paul approves |
| 11 | |
| 12 | One run in account `640012953448` (profile `kass`), region `eu-west-1`, every call behind the |
| 13 | account and region guard; IAM is the one global-endpoint exception (R37) and there is no billing |
| 14 | call (R33). Nothing touches account `149757027610` (equipo-hosted): the guard aborts on any other |
| 15 | account, and any ARN naming `149757027610` is a hard stop. The run builds only what sections 7 and |
| 16 | 8 need (network, connector, one Small image version, SNS topic, keys and config), re-runs one live |
| 17 | contract subtest (`ChangedSpecConflicts`, expected to pass now), then runs the controller on docs-t1: |
| 18 | the driver sequence (launch, drain, quiescent, suspend, resume, stop with proof), the crash between |
| 19 | the provider call and transaction 2 with Replay claiming the one VM, and a planted orphan the reaper |
| 20 | must stop. Then it tears everything down and verifies it gone. Every Lambda MicroVMs and Lambda core |
| 21 | call goes through `livectl`, the pinned Go SDK tool (R40), which refuses any other account, region |
| 22 | or name outside the run; EC2, IAM, S3, SNS, CloudWatch Logs and STS stay on the CLI. Every taggable |
| 23 | resource carries `purpose=equipo-hosted-dev` and `run=<RUN>`; MicroVMs (no tag field) and the |
| 24 | connector's Lambda-managed interfaces are recorded by ID and proven gone (R34). The code is the |
| 25 | exact revision `PIN_SHA` `bf29344a` (R35), and the controller's reaper sees only this run's image |
| 26 | (R32). The run stops hard only for safety: the wrong account or region, spend (the run's own |
| 27 | estimate reaching $5; $10 is the approval ceiling), a MicroVM alive outside its step (the orphan |
| 28 | alive past P+15:00 included), or anything not in the ledger. It also stops when a step that later |
| 29 | steps need cannot complete (a resource that cannot be created or deleted). Everything else that |
| 30 | differs from expectation becomes a `FINDING:` line in the journal and the run goes on where it |
| 31 | safely can; the report lists every FINDING. Paul also pre-approves these fallbacks: the operator |
| 32 | role uses the AWS-managed connector policy plus a subnet-scoped delete from the start; 3.7 and 3.8 |
| 33 | step down one base image version once; and 10.2 drops the delete policy's managed-operator condition |
| 34 | once if the connector cannot be deleted. Expected spend is about $0.20, worst case about $5.55, |
| 35 | retained image storage after an early stop about $0.24 to $6.53 a month. Guarded, run-scoped, |
| 36 | read-only calls on this run's own resources are pre-approved even where this plan does not print |
| 37 | them; a failed observation read is a FINDING. Reads needed for identity, ownership, settlement, |
| 38 | deletion or a named later step stay fatal. Any other change to a command, or any other AWS call, |
| 39 | comes back to Paul first. |
| 40 | |
| 41 | ## Changes from revision 5 |
| 42 | |
| 43 | 1. **Scope.** Only revision 5's sections 7 and 8, plus the setup and teardown they need: 0, 1, 2, |
| 44 | 3 (Small only), 4, 5, one contract subtest (6), 7, 8, 10, S, 11 and 12. Section 9 (facts) is |
| 45 | dropped: attempt 4 settled it. The full contract run is dropped; 6.1 re-runs only |
| 46 | `ChangedSpecConflicts`, expected to PASS with the client-token fix (`5f6e3e65`). A failure is a |
| 47 | FINDING, and every VM it made is settled before section 7. |
| 48 | 2. **Code pin.** `PIN_SHA` is `bf29344a` (`bf29344a8b6832dff425aafc1337d4883f6a894f`): the |
| 49 | ErrConflict fix `5f6e3e65` with its two review test rows, on the origin/main merge `2d6d2345`. |
| 50 | 0.1 checks that HEAD contains it, that it contains `a36861a0` (livectl), `bdf85fb7` (livectl |
| 51 | final), `f95575c6` (R32) and `5f6e3e65` (client-token ErrConflict), and that nothing outside |
| 52 | `docs/` changed since it; it runs livectl's offline tests and the awsjob package's offline |
| 53 | tests. The SHA is written once, in 0.1; 0.2 reads it from the file 0.1 leaves, so a re-pin is a |
| 54 | one-line change. |
| 55 | 3. **The 5.6 defect is fixed.** Revision 5 required a `network_audit_passed` audit row, which the |
| 56 | controller writes only when an audit passes again after failing |
| 57 | (`internal/hostedctl/reaper.go:739-747`); a clean first pass writes none, so attempt 4 set |
| 58 | `AUDIT_OK=no` and skipped 7 and 8. 5.6 now requires what a clean start does produce: readiness |
| 59 | (`equipo_hosted_network_audit_passing 1` and `equipo_hosted_reap_last_error 0`, |
| 60 | `internal/hostedctl/metrics.go:118-131`), captured while the controller runs; exactly one |
| 61 | `provider_bound` row naming `aws:640012953448:eu-west-1` (`internal/hostedctl/store.go:366-372`); |
| 62 | the `provider_binding` namespace; no `network_audit_failed` row and no |
| 63 | `hosted controller: network audit failed` log line (`internal/hostedctl/logs.go:35`). A |
| 64 | `network_audit_passed` row is recorded as a fact only. |
| 65 | 4. **MicroVM ID pattern.** Live IDs are `microvm-<uuid>` (44 characters, attempt 4). `harvest` and |
| 66 | 7.3's crash-log grep now use `VMID_RE`, |
| 67 | `microvm-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`, not `mvm-...`. The |
| 68 | adapter's own check (`isolatedjob.Ref.Valid`, `internal/isolatedjob/isolatedjob.go:41-53`, |
| 69 | R36) is letters, digits and `-` up to the maximum length, which is too loose to pick IDs out of |
| 70 | a log, so `harvest` also reports any other `microvm-...` token (other than `microvm-image...`) |
| 71 | as a FINDING; the image-scoped scans stay the inventory. |
| 72 | 5. **Log and metric checks re-read against the code.** Every grep, metric line and audit action |
| 73 | was checked at `bf29344a`: `launches enabled: <bool>` (`cmd/equipo-hosted-controller/main.go:120`), |
| 74 | the crash point's `EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1` and `crash point: the provider launched <vm> |
| 75 | for <attempt>` lines (`crashpoint.go:35,46`), `hosted controller: orphan VM stopped` and |
| 76 | `... left running for a dispatched launch intent` (`logs.go:18,29`), `restart stop requested, |
| 77 | elapsed time unknown` (`logs.go:44`), the job-state and alert metric lines |
| 78 | (`metrics.go:104-153,213-227`), and the audit actions in `launch.go:58-70`, `pause.go:35-49`, |
| 79 | `resume.go:32-39`, `stop.go:44-52` and `reaper.go:48-56`. Controller log checks now read only the |
| 80 | lines written since the latest start (`ctl_log`), so one start's lines never satisfy or fail |
| 81 | another start's check. 7.2 and 7.4 check the named audit actions; each missing one is a FINDING. |
| 82 | 6. **No Large version.** The adapter needs at least one version per image |
| 83 | (`internal/isolatedjob/awsjob/runner.go:141-151`), and every launch in 6, 7 and 8 is Small |
| 84 | (`internal/hostedclient/driver_test.go:45`, the contract's `SizeSmall`, livectl's |
| 85 | `-version $VER_SMALL`). Revision 5's 3.9 is gone; its image read moves into 3.8; both configs |
| 86 | list `small` only. One build and one stored version less. |
| 87 | 7. **SNS topic kept.** `sns_topic_arn` is required (`cmd/equipo-hosted-controller/config.go:122-127`; |
| 88 | the SNS alerter is wired at `main.go:104`), and 8.2 counts the `orphan_stopped` alert as sent |
| 89 | through it. Revision 5 said 5.6 "proves the SNS topic takes startup alerts"; it does not: startup |
| 90 | alerts are queued only after a wall-clock rollback (`internal/hostedctl/store.go:226-235`), so |
| 91 | 8.2's alert is the first publish. |
| 92 | 8. **The sequence attempt ID is set by the plan** (`EQUIPO_HOSTED_LIVE_ATTEMPT`, read by |
| 93 | `TestLiveControllerSequence`), not parsed from the test log. |
| 94 | 9. **Metric reads in 7 and 8 are observations.** A metrics read that fails is a FINDING (`mread`), |
| 95 | not a hard stop; the listener check stays a hard stop. |
| 96 | 10. **Blocks and the controller run as systemd user units (R44), and blocks never overlap.** |
| 97 | Attempt 4 started 7.2, 7.3 and 7.4 back to back. Every long block now runs as the transient |
| 98 | user unit `t17b-<RUN>-<block>.service` and every controller start as |
| 99 | `t17b-<RUN>-ctl-<label>.service` (`systemd-run --user --collect`, `KillMode=control-group`, |
| 100 | `TimeoutStopSec=45`), so systemd tracks each one's processes by its cgroup and reaps them. |
| 101 | Every start, stop and state read goes by unit name; there are no PID files, PID signals or |
| 102 | environment markers. A unit is proved stopped only when it is inactive or failed and gone, or |
| 103 | its cgroup is empty; anything unknown is `unresolved`. The long-block start refuses while a block |
| 104 | unit is running or unresolved, and `env.sh` refuses to load while a block unit other than its own |
| 105 | is. A block past its bound is stopped with `systemctl --user stop`. S.0, a local emergency stop |
| 106 | run before `env.sh`, stops every unit of the run and proves each one done before S.1 to S.3; if |
| 107 | it cannot, that is a hard stop that prints the unit names for Paul. 0.2 proves the mechanism |
| 108 | with a probe unit before any AWS call. Helpers: `unitctl.sh` and `bin/exitpost.sh` (0.2). |
| 109 | 11. **Fresh scratch and names.** Scratch is `$TMPDIR/equipo-t17b` (and `$TMPDIR/equipo-t17b-pre` for |
| 110 | 0.1 and 0.2); revision 5's 0.1a (attempt 1's scratch) is gone. The run ID is |
| 111 | `<mmdd>-b<6 hex>`, so every name is run-unique, with the same collision checks (R39). The base |
| 112 | name keeps livectl's fixed prefix `equipo-hosted-dev-t17-<RUN>`. |
| 113 | 12. **Spend.** Expected about $0.20; worst case about $5.55; self-stop at the run's own estimate of |
| 114 | $5; ceiling $10. 11.2's estimator is updated for this run (one version, two counted pause |
| 115 | cycles, launch snapshot reads per VM). |
| 116 | 13. **Section 12** is re-run: what attempt 4 settled is moved to "settled"; new items are listed. |
| 117 | 14. **Unit environment and ownership (R45, applied after Astra's round 3).** |
| 118 | - Every unit's command is `/usr/bin/env -i <allowlisted NAME=value...> <program> <args>` |
| 119 | (`--expand-environment=no`), so the argument list is the program's whole environment and |
| 120 | nothing from the user manager's environment reaches it. The allowlist keeps PATH, HOME, the |
| 121 | Go settings and the AWS profile and region; `start_ctl` adds explicit controller defaults |
| 122 | (`AWS_PROFILE=kass`, `AWS_REGION` and `AWS_DEFAULT_REGION` `eu-west-1`) and the |
| 123 | `EQUIPO_HOSTED_*` settings it is given. `EQUIPO_HOSTED_CRASH_AFTER_LAUNCH` is set only in 7.3's |
| 124 | unit. 7.4 reads the restarted unit's `ExecStart` and checks its `env -i` argument list has no |
| 125 | crash switch; a failed or unreadable read fails the block (`soft_fail`). 0.2's probe unit |
| 126 | records its environment and must show only allowlisted names. |
| 127 | - 0.2 reserves the run ID atomically (`mkdir "$HOME/.cache/t17b-runs/<RUN>"`, a new ID if it |
| 128 | exists), then requires `systemctl --user list-units --all 't17b-<RUN>-*'` to be empty, before |
| 129 | any unit or AWS call. Every unit name is journalled (`UNIT <name>`) before its `systemd-run`, |
| 130 | and every stop, S.0's included, acts only on journalled names; the glob is a cross-check, and |
| 131 | a matching unit that was not journalled is reported for Paul and never stopped. 10.9 removes |
| 132 | exactly the reservation directory, and its parent only if empty (`rmdir`). |
| 133 | - S.0 stops and proves the block units first, then re-reads the journal and stops and proves |
| 134 | the controller units, then takes a final inventory of the journalled units plus the glob |
| 135 | cross-check before it prints done. |
| 136 | |
| 137 | ## Order of execution |
| 138 | |
| 139 | | Run order | Section | Roughly | |
| 140 | | --- | --- | --- | |
| 141 | | 1 | 0. Guard rails, code pin, collision checks | 10 min | |
| 142 | | 2 | 1. Network | 5 to 10 min | |
| 143 | | 3 | 2. Connector | 10 to 15 min | |
| 144 | | 4 | 3. Image, Small version only | 10 to 30 min | |
| 145 | | 5 | 4. SNS topic | 2 min | |
| 146 | | 6 | 5. Keys, config, builds, and the audit-only controller run | 10 min | |
| 147 | | 7 | 6. Live contract subtest `ChangedSpecConflicts`, every VM settled | 5 to 10 min | |
| 148 | | 8 | 7. Controller sequence, crash and Replay | 30 to 45 min | |
| 149 | | 9 | 8. Orphan | 20 to 25 min | |
| 150 | | 10 | 10. Teardown and verification | 20 to 45 min (up to 130 with 10.2's fallback) | |
| 151 | |
| 152 | About 2 to 3 hours in all. 11.2 (the spend estimate) runs at the end of every section. The SDK-side |
| 153 | network audit (5.6) runs before any VM is launched, so the connector's `VersionArn` and Elastic IP |
| 154 | setting are checked by the controller's own code before the first launch. |
| 155 | |
| 156 | ## Rules for every block |
| 157 | |
| 158 | - **Every block runs with the agent sandbox off.** Attempt 1 showed the sandbox proxy blocks AWS |
| 159 | (its allowlist has no `*.amazonaws.com`, and `allowed_domains` is ignored in this session), and |
| 160 | `$TMPDIR` is a different path inside and outside the sandbox. Running every block the same way |
| 161 | keeps `$TMPDIR/equipo-t17b` one directory and lets AWS calls through. |
| 162 | - **Every block runs as its own script, `bash <file>`.** The agent writes each block's text, |
| 163 | exactly as printed (only the `<T17 printed by 0.2>` path filled in), to `$T17/blocks/<block>.sh` |
| 164 | and runs `bash "$T17/blocks/<block>.sh"` in the foreground, or detached for the long blocks below. |
| 165 | 0.1 and 0.2 run before the scratch exists, so they go to `$TMPDIR/equipo-t17b-pre/` instead |
| 166 | (the executor creates that directory, mode 700, for them), which 10.9 removes. |
| 167 | It never pastes a block into the tool's shell: the plan writer found on 2026-11-28 that a tool's |
| 168 | wrapper can run commands in a context where `set -e` is ignored, which would let a failed command |
| 169 | pass silently. Run as a script, `set -e` is in force, and every hard stop also reaches the parent |
| 170 | through `die`'s FATAL marker. |
| 171 | - **One block, one Bash tool call, run by bash.** Every block begins with |
| 172 | `set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"` and, if it calls AWS, `guard`. The |
| 173 | environment file (0.2) defines every helper the blocks use; nothing is pasted by hand. |
| 174 | - **One block at a time.** A block starts only after the previous one has finished: a foreground |
| 175 | block has returned, and a long block's wait call has printed its exit status. The start call for |
| 176 | a long block refuses while any block unit of the run is running or unresolved, and `env.sh` |
| 177 | refuses to load (exit 1) while a block unit other than the one loading it is, so an overlap stops |
| 178 | at once. Unresolved means its state cannot be established, or its status is `unresolved`; the |
| 179 | proof is described under the long-block mechanism. After an abort, S.0 stops every unit of the |
| 180 | run before anything sources `env.sh` again. (Attempt 4 started 7.2, 7.3 and |
| 181 | 7.4 back to back; with section 7 skipped it did no harm, but it would have with the controller |
| 182 | running.) |
| 183 | - **Two kinds of stop (Paul, 2026-11-28).** `die` is kept for the hard stops: the wrong account or |
| 184 | region (`guard`, livectl's own guard), spend (11.2's $5 rule; $10 is the approval ceiling), a |
| 185 | MicroVM alive outside its step (`settle_all`, `vm_end`, the orphan bound), anything not in the |
| 186 | ledger (collision checks, unknown resources, unresolved creations), and a step later steps need |
| 187 | that cannot complete (a create or delete that fails, the connector's qualified ARN, the image). |
| 188 | Everything else that differs from expectation is a `finding`: a `FINDING` line in the journal, |
| 189 | printed with `FINDING:`, and the block goes on. The report lists every FINDING. |
| 190 | - **The read-only envelope.** Guarded (`guard`, livectl's own guard), run-scoped, read-only calls |
| 191 | on this run's own resources are pre-approved, including ones this plan does not print. A read |
| 192 | that only observes, and errors or answers differently, is a FINDING (`fact_eq`, `fact_json`, |
| 193 | `fact_lv`, `eni_snapshot soft`). A read needed for identity, ownership, settlement, deletion or a |
| 194 | named later step stays fatal: the VM scans and `vm_end`, the collision checks, the connector's |
| 195 | qualified ARN, the base image list, the default-resource lookups, the interface list before the |
| 196 | connector delete, and every deletion check. |
| 197 | - **Failure is loud.** A failed command that is not handled ends the block. Calls that are expected |
| 198 | to fail run under `try` or `lv` and pass only through an explicit branch that names the accepted |
| 199 | error codes. Every poll fails when its bound runs out. |
| 200 | - **livectl (R40).** Every Lambda MicroVMs and Lambda core call goes through `lv`, which runs |
| 201 | `$T17/bin/livectl -run <RUN>` (built in 0.2 from the pinned code). livectl takes only static keys |
| 202 | (R41), and `kass` resolves through a `credential_process`, so each call first runs |
| 203 | `aws configure export-credentials --profile kass --format process` and starts livectl in a |
| 204 | subshell holding only `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and, if one was issued, |
| 205 | `AWS_SESSION_TOKEN`, with `AWS_PROFILE`, `AWS_CONFIG_FILE` and `AWS_SHARED_CREDENTIALS_FILE` unset |
| 206 | (R42). The keys live only in that subshell's environment: never on disk, in the journal, in an |
| 207 | argument list or in output. A failed or incomplete export is a hard stop (as livectl's exit 4). Its replies are the SDK's |
| 208 | output structs with Go field names (`State`, `VersionArn`, `MicrovmId`) and unions under |
| 209 | `.Value`; its errors are one JSON line whose `code` `lv` puts in `ECODE` and whose `aws_message` |
| 210 | it puts in `LV_MSG`. Client tokens start with the run prefix, as livectl requires. Exit codes, as |
| 211 | livectl defines them at `PIN_SHA`: |
| 212 | - **4** (guard: account, region, run prefix, missing `-run`, or credentials that are not static |
| 213 | keys) and **3** (usage) are hard stops, inside `lv` itself. |
| 214 | - **2** (an SDK call failed; livectl makes one attempt per call, so a throttle, a 5xx or no answer |
| 215 | within its 60 s cutoff, `"error":"transport"`, all come back as 2). On a read, `lvr` tries a |
| 216 | transient failure up to 3 times, 5 s apart; what is left is a FINDING, except where a hard stop |
| 217 | depends on the read (the VM scans, `vm_end`, the collision checks, the connector's qualified |
| 218 | ARN, the base image list). On a change it follows the block's own branches; only idempotent |
| 219 | deletes and terminates use `lvr`. |
| 220 | - **5** (a wait's bound passed, including an answer that came after it) and **6** (a failed |
| 221 | state) are handled by each block against its bound. `lv_wait` gives each wait one overall bound |
| 222 | and carries on through a transient exit 2 inside it, as a FINDING. |
| 223 | - **A hard stop means the safe stop (section S, starting with S.0), then ask Paul.** Nothing else |
| 224 | runs after it. |
| 225 | - **Ledger.** Before each create call the block writes an `INTENT` line (kind, run-specific name or |
| 226 | token); after the call it records the confirmed ID with `rec` (checked writes, ARN checks). Every |
| 227 | MicroVM ID that appears anywhere is added to the VM ledger with `vmrec`. A deletion is recorded |
| 228 | with `deleted` only after a direct read shows it gone. Teardown and the safe stop work only from |
| 229 | these records; nothing is ever adopted or deleted because its name looks right. |
| 230 | - **Skip-never-created rule.** Teardown (section 10) and the safe stop act only on resources with |
| 231 | a confirmed creation record, that is, a ledger variable set by `rec` (`VPC`, `CONN_ARN`, |
| 232 | `IMAGE_ARN`, `BUCKET_CREATED` and so on; the names in `run.env` alone do not count). `have` sees |
| 233 | three states. Confirmed: act. Never attempted, or the last attempt followed by a `NOTCREATED` |
| 234 | record (from S.2 or a refused create): journal `SKIP <variable>` and skip. Unresolved (an |
| 235 | `INTENT` with neither): never skipped; the block aborts, so teardown cannot complete, S.3 cannot |
| 236 | report "never created", and 10.9 cannot remove the scratch until S.2 reconciles it. |
| 237 | - **Long blocks, one mechanism.** These blocks can run past the Bash tool's 10-minute limit for one |
| 238 | call: 2.1, 2.3, 3.8, 6.1, 7.2, 7.3, 7.4, 8.2, 10.1 and 10.2 (bounds below). Each is written to a |
| 239 | script file and run as a transient systemd user unit, started from a sandbox-off shell (R44); its |
| 240 | exit status is read from a status file the unit's `ExecStopPost` writes. Every one of them starts |
| 241 | with the sandbox-off header (`T17=` set explicitly). The agent never uses another background |
| 242 | mechanism. |
| 243 | 1. Write the block's text, exactly as printed here with only the `<T17 printed by 0.2>` path filled |
| 244 | in, to `$T17/blocks/<block>.sh` (for example `$T17/blocks/6.1.sh`), as for every block. |
| 245 | 2. Start it (one sandbox-off call). It runs as the transient systemd user unit |
| 246 | `t17b-<RUN>-<block>.service` (R44). A refused start changes nothing and is not an abort: wait |
| 247 | for the unfinished block with its wait call, then start again. (After an abort, the safe stop |
| 248 | begins with S.0, which stops any unit of the run.) |
| 249 | |
| 250 | ```sh |
| 251 | set -euo pipefail; T17='<T17 printed by 0.2>'; B='<block>' |
| 252 | . "$T17/run.env"; . "$T17/unitctl.sh"; d="$T17/blocks" |
| 253 | [ -s "$d/$B.sh" ] || { echo "ABORT: no $d/$B.sh"; exit 1; } |
| 254 | [ ! -e "$d/$B.status" ] && [ ! -e "$d/$B.unit" ] || { echo "ABORT: block $B was already started"; exit 1; } |
| 255 | if busy=$(blocks_busy); then echo "REFUSED: a block is not finished: $busy"; exit 1; fi |
| 256 | bash -n "$d/$B.sh" |
| 257 | u="${UNIT_PREFIX}$B.service"; printf '%s\n' "$u" > "$d/$B.unit"; date +%s > "$d/$B.start" |
| 258 | unit_start "$u" "$d/$B.out" "$d/$B.status" -E "T17_BLOCK=$B" -- bash "$d/$B.sh" || { echo "ABORT: systemd-run could not start $u; run S.0"; exit 1; } |
| 259 | echo "block $B started as unit $u" |
| 260 | ``` |
| 261 | |
| 262 | 3. Wait (repeat this sandbox-off call until it prints an exit status, `ABORT` or `UNRESOLVED`; |
| 263 | `MAXMIN` is the block's bound from the table). Each call has one deadline, 540 s after it |
| 264 | starts, that covers every read and the stop: it waits only while at least 135 s are left, each |
| 265 | wait step (a 5 s sleep and one `systemctl` read bounded at 10 s) takes at most 15 s, and a stop |
| 266 | takes at most 75 s plus 15 s of reads that never pass the deadline. So a call ends within about |
| 267 | 9 minutes, under the tool's 10-minute limit. |
| 268 | |
| 269 | ```sh |
| 270 | set -euo pipefail; T17='<T17 printed by 0.2>'; B='<block>'; MAXMIN='<bound>' |
| 271 | DL=$(( $(date +%s) + 540 )) |
| 272 | . "$T17/run.env"; . "$T17/unitctl.sh"; d="$T17/blocks" |
| 273 | [ -s "$d/$B.unit" ] && [ -s "$d/$B.start" ] || { echo "ABORT: block $B was not started"; exit 1; } |
| 274 | u=$(cat "$d/$B.unit") |
| 275 | over() { [ $(( ($(date +%s) - $(cat "$d/$B.start")) / 60 )) -ge "$MAXMIN" ]; } |
| 276 | while :; do |
| 277 | s=$(unit_state "$u") |
| 278 | [ "$s" = running ] && ! over && [ "$(date +%s)" -le $(( DL - 135 )) ] || break |
| 279 | sleep 5 |
| 280 | done |
| 281 | tail -n 60 "$d/$B.out" 2>/dev/null || true |
| 282 | case "$s" in |
| 283 | done) |
| 284 | st=$(cat "$d/$B.status" 2>/dev/null || echo unknown) |
| 285 | echo "block $B finished: unit $u is inactive or gone with an empty cgroup; exit status $st" |
| 286 | [ "$st" = 0 ] || exit 1; exit 0;; |
| 287 | unresolved) echo "UNRESOLVED: the state of unit $u cannot be established; this is an abort: run S.0"; exit 1;; |
| 288 | esac |
| 289 | if over; then |
| 290 | if unit_stop "$u" "$(( DL - 5 ))"; then |
| 291 | printf 'killed\n' > "$d/$B.status" |
| 292 | echo "ABORT: block $B ran past its $MAXMIN-minute bound; systemd stopped unit $u (TERM, then KILL) and it is inactive or gone with an empty cgroup"; exit 1 |
| 293 | fi |
| 294 | printf 'unresolved\n' > "$d/$B.status" |
| 295 | echo "UNRESOLVED: block $B ran past its $MAXMIN-minute bound and unit $u was not proved stopped within this call; run S.0 in a fresh call"; exit 1 |
| 296 | fi |
| 297 | echo "block $B still running after $(( ($(date +%s) - $(cat "$d/$B.start")) / 60 )) minutes; call again" |
| 298 | ``` |
| 299 | |
| 300 | An exit status other than 0, `killed`, `unresolved` or the bound passing is an abort (safe stop, |
| 301 | from S.0). How "stopped" is proved (R44): systemd keeps a unit's processes, and everything they |
| 302 | start, in the unit's own cgroup, whatever they do to their environment or process group, and it |
| 303 | reaps them. A stop is `systemctl --user stop <unit>`: TERM to every process in the cgroup, KILL |
| 304 | after `TimeoutStopSec=45`. `unit_state` reads `done` only when `ActiveState` is inactive or failed |
| 305 | and the unit is gone (collected, which systemd does only once the cgroup is empty) or its |
| 306 | `cgroup.procs` is absent or empty; anything unknown or unreadable is `unresolved`, which every |
| 307 | guard treats as unfinished until S.0 proves the unit done. Starts, stops and reads go by unit name |
| 308 | only; nothing is signalled by PID. The exit status comes from the unit's `ExecStopPost` |
| 309 | (`bin/exitpost.sh`), which records the main process's status, or `signal:<name>`, however the unit |
| 310 | ends. The unit's command is `/usr/bin/env -i <allowlist> bash <block file>`, so the block sees |
| 311 | only the allowlisted environment (R45). Every unit name is journalled before its `systemd-run`, |
| 312 | and stops act only on journalled names. 0.2 proves the mechanism once with a probe unit before any |
| 313 | AWS call. Bounds in minutes: |
| 314 | 2.1: 10; 2.3: 20; 3.8: 50; 6.1: 40; 7.2: 40; 7.3: 15; 7.4: 25; 8.2: 25; 10.1: 30; 10.2: 130 (its |
| 315 | shared budget is 120). |
| 316 | - **The controller, as a unit (R37, R44).** Every block that starts, checks or stops the |
| 317 | controller runs with the agent's sandbox OFF: 5.6, 6.1, 7.1, 7.2, 7.3, 7.4, 8.1, 8.2, 10.1, 10.9, |
| 318 | S.0, S.1 and S.3, plus the other long blocks (2.1, 2.3, 3.8, 10.2). Those blocks set `T17` |
| 319 | explicitly to the path 0.2 printed; their first line reads |
| 320 | `set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"`, and that path is the only text |
| 321 | the agent fills in. `start_ctl` starts each controller run as its own transient user unit, |
| 322 | `t17b-<RUN>-ctl-<label>.service` (labels `audit-only`, `sequence`, `crash`, `recover`, `orphan`), |
| 323 | never as a child of the block that starts it. The controller is the unit's main process; its |
| 324 | output goes to `controller.log` and its exit status (137 for 7.3's crash point) to |
| 325 | `controller.exit`, written by the unit's `ExecStopPost`. The unit's command is |
| 326 | `/usr/bin/env -i <NAME=value...> <controller> -config ...`, so that argument list is the |
| 327 | controller's whole environment (R45): `unitctl.sh`'s allowlist (PATH, HOME and the rest, so the |
| 328 | kass `credential_process` works), then `AWS_PROFILE=kass`, `AWS_REGION` and `AWS_DEFAULT_REGION` |
| 329 | `eu-west-1`, then the `EQUIPO_HOSTED_*` settings `start_ctl` is given |
| 330 | (`EQUIPO_HOSTED_CRASH_AFTER_LAUNCH` only in 7.3). Nothing from the user manager's environment |
| 331 | reaches it. |
| 332 | `ctl_alive` reads the unit's state; `stop_ctl` stops the unit by name and proves it done. If the |
| 333 | controller is gone when a block expects it, or a port stays open after its unit is done, that is |
| 334 | an abort. |
| 335 | - **docs-t1.** The controller listens on `127.0.0.1:18443` (API) and `127.0.0.1:18444` (metrics) |
| 336 | only, checked after every start. The hook server in the image listens on port 9000 inside the |
| 337 | MicroVM, not on docs-t1. Scratch is `$TMPDIR/equipo-t17b`, removed in 10.9. Go caches stay at |
| 338 | their defaults; every Go command runs with `CGO_ENABLED=0`. No sudo. |
| 339 | - **Records.** After each section, append its results to |
| 340 | `docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md` under a new heading at the end of the file, |
| 341 | `## Task 17b live run (attempt 5)`, and commit that file locally at the end (subject under 80 |
| 342 | characters). Never push. The report lists every `FINDING` line (10.9 prints them all). |
| 343 | - **Spend after every section.** Run 11.2 at the end of every section; its exit status 3 is the |
| 344 | spend hard stop. |
| 345 | |
| 346 | --- |
| 347 | |
| 348 | ## 0. Guard rails |
| 349 | |
| 350 | ### 0.1 Code pin and local tools (no AWS call) |
| 351 | |
| 352 | `PIN_SHA` is `bf29344a` (`bf29344a8b6832dff425aafc1337d4883f6a894f`): the client-token ErrConflict fix |
| 353 | `5f6e3e65` plus the two test rows from its review, on top of the origin/main merge `2d6d2345`. It |
| 354 | contains livectl's first commit `a36861a0`, livectl's final commit `bdf85fb7`, R32 (`f95575c6`) |
| 355 | and the fix `5f6e3e65`. **This block is the only place the SHA is written.** It saves the checked |
| 356 | SHA to `$TMPDIR/equipo-t17b-pre/pin`, and 0.2 reads it from there; a re-pin changes the |
| 357 | `PIN_SHA=` line below and nothing else. The block also runs livectl's offline tests and the |
| 358 | awsjob package's offline tests (the client-token mapping included). |
| 359 | |
| 360 | ```sh |
| 361 | set -euo pipefail |
| 362 | PIN_SHA='bf29344a8b6832dff425aafc1337d4883f6a894f' |
| 363 | : "${TMPDIR:?TMPDIR is unset}" |
| 364 | P="$TMPDIR/equipo-t17b-pre"; [ -d "$P" ] || { echo "ABORT: $P does not exist (it holds this block)"; exit 1; } |
| 365 | [[ "$PIN_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "ABORT: PIN_SHA is not a full commit SHA"; exit 1; } |
| 366 | cd /home/paulca/amadan.net/oficina/equipo-hosted-1a |
| 367 | git rev-parse --verify "$PIN_SHA^{commit}" |
| 368 | for c in a36861a0 bdf85fb7 f95575c6 5f6e3e65; do |
| 369 | git merge-base --is-ancestor "$c" "$PIN_SHA" || { echo "ABORT: $PIN_SHA does not contain $c"; exit 1; } |
| 370 | done |
| 371 | git merge-base --is-ancestor "$PIN_SHA" HEAD || { echo "ABORT: HEAD does not contain $PIN_SHA"; exit 1; } |
| 372 | d=$(git diff "$PIN_SHA" HEAD -- . ':!docs'); [ -z "$d" ] || { echo "ABORT: code differs from $PIN_SHA outside docs/"; exit 1; } |
| 373 | s=$(git status --porcelain --untracked-files=all -- . ':!docs'); [ -z "$s" ] || { echo "ABORT: uncommitted changes outside docs/:"; echo "$s"; exit 1; } |
| 374 | git log --oneline -1 |
| 375 | aws --version |
| 376 | go version |
| 377 | for t in jq openssl sha256sum curl ss python3 systemd-run systemctl timeout; do command -v "$t" >/dev/null || { echo "ABORT: missing $t"; exit 1; }; done |
| 378 | CGO_ENABLED=0 go test -tags hostedlive ./internal/isolatedjob/awsjob/livectl -count=1 |
| 379 | CGO_ENABLED=0 go test ./internal/isolatedjob/awsjob -count=1 |
| 380 | printf '%s\n' "$PIN_SHA" > "$P/pin" |
| 381 | echo "code pin ok: $PIN_SHA" |
| 382 | ``` |
| 383 | |
| 384 | - Expected: both test packages `ok`; `code pin ok`; `aws-cli/2.36.x`; `go1.26.x`. |
| 385 | - Abort if: any check fails. |
| 386 | - A re-pin: if the coordinator relays a new SHA (another review round on the fix), only the |
| 387 | `PIN_SHA=` line above changes, plus the prose in "What Paul approves" and this paragraph's |
| 388 | first line. The new SHA must still contain the four commits checked here. |
| 389 | |
| 390 | ### 0.2 Scratch, the environment file and the run names (no AWS call) |
| 391 | |
| 392 | ```sh |
| 393 | set -euo pipefail |
| 394 | : "${TMPDIR:?TMPDIR is unset}" |
| 395 | PIN_SHA=$(cat "$TMPDIR/equipo-t17b-pre/pin") || { echo "ABORT: 0.1 has not passed (no pin file)"; exit 1; } |
| 396 | [[ "$PIN_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "ABORT: the pin file does not hold a full SHA"; exit 1; } |
| 397 | (cd /home/paulca/amadan.net/oficina/equipo-hosted-1a && git merge-base --is-ancestor "$PIN_SHA" HEAD \ |
| 398 | && [ -z "$(git diff "$PIN_SHA" HEAD -- . ':!docs')" ]) || { echo "ABORT: HEAD moved away from $PIN_SHA since 0.1"; exit 1; } |
| 399 | [ ! -e "$TMPDIR/equipo-t17b" ] || { echo "ABORT: $TMPDIR/equipo-t17b already exists"; exit 1; } |
| 400 | case "$TMPDIR/equipo-t17b" in *[!A-Za-z0-9/._-]*) echo "ABORT: the scratch path has characters a systemd command line could misread"; exit 1;; esac |
| 401 | mkdir -m 700 "$TMPDIR/equipo-t17b" |
| 402 | mkdir -m 700 "$TMPDIR/equipo-t17b"/{out,image,iam,keys,bin,blocks} |
| 403 | cat > "$TMPDIR/equipo-t17b/unitctl.sh" <<'BCEOF' |
| 404 | # unitctl.sh: systemd user units for Task 17b (ruling R44). Functions only; no AWS call. Sourced by |
| 405 | # env.sh, by the long-block start and wait calls, and by S.0, which runs before env.sh. |
| 406 | # Every detached block and every controller start is a transient user service: |
| 407 | # t17b-<RUN>-<block>.service or t17b-<RUN>-ctl-<label>.service. systemd keeps the service's |
| 408 | # processes, and everything they start, in the unit's own cgroup, whatever they do to their |
| 409 | # environment or process group, and reaps them. Every start, stop and state read goes by unit name; |
| 410 | # nothing is ever signalled by PID (R44). |
| 411 | # Ownership (R45): 0.2 reserves the run ID atomically (mkdir $HOME/.cache/t17b-runs/<RUN>) and |
| 412 | # proves no t17b-<RUN>-* unit exists. unit_start journals every unit name (a "UNIT <name>" line) |
| 413 | # before its systemd-run, and unit_stop acts only on names this run journalled. The unit-name glob |
| 414 | # is a cross-check only: a matching unit that was not journalled is never stopped. |
| 415 | # Environment (R45): a unit's command is /usr/bin/env -i <allowlisted NAME=value...> <program>, so |
| 416 | # nothing from the user manager's environment reaches the program; the argv is its whole environment. |
| 417 | : "${T17:?T17 is unset}"; : "${RUN:?RUN is unset}" |
| 418 | UNIT_PREFIX="t17b-$RUN-" |
| 419 | # The allowlist: variables copied into a unit's env -i argv when set in the caller. env.sh unsets |
| 420 | # every AWS key, and no key, token or config-path variable is listed here, so no credential can |
| 421 | # reach a unit. HOME and PATH keep the kass profile's credential_process working. |
| 422 | UNIT_ENV_VARS="PATH HOME USER LOGNAME LANG LANGUAGE LC_ALL TZ TMPDIR XDG_RUNTIME_DIR XDG_CACHE_HOME XDG_CONFIG_HOME |
| 423 | DBUS_SESSION_BUS_ADDRESS GOPATH GOMODCACHE GOCACHE GOCACHEPROG GOFLAGS GOPROXY GOSUMDB GONOSUMDB GOPRIVATE GONOPROXY |
| 424 | GOTOOLCHAIN GOENV SSL_CERT_FILE SSL_CERT_DIR HTTP_PROXY HTTPS_PROXY NO_PROXY http_proxy https_proxy no_proxy |
| 425 | AWS_PROFILE AWS_REGION AWS_DEFAULT_REGION AWS_PAGER AWS_STS_REGIONAL_ENDPOINTS AWS_RETRY_MODE AWS_MAX_ATTEMPTS CGO_ENABLED" |
| 426 | # _sc ARGS...: systemctl --user, bounded at 10 s. |
| 427 | _sc() { timeout 10 systemctl --user "$@"; } |
| 428 | # unit_state UNIT: prints running, done or unresolved. |
| 429 | # running: ActiveState active, activating, deactivating, reloading or refreshing. |
| 430 | # done: ActiveState inactive or failed, and the unit is gone (LoadState not-found: --collect |
| 431 | # removed it, which systemd does only after its cgroup is empty), or it is loaded and |
| 432 | # its cgroup no longer exists or lists no process. |
| 433 | # unresolved: anything else: a systemctl call that fails or times out, any other state, or a |
| 434 | # cgroup that cannot be read or still lists a process. |
| 435 | unit_state() { local o load act cg f procs |
| 436 | o=$(_sc show -p LoadState -p ActiveState -p ControlGroup -- "$1" 2>/dev/null) || { echo unresolved; return 0; } |
| 437 | load=$(sed -n 's/^LoadState=//p' <<<"$o"); act=$(sed -n 's/^ActiveState=//p' <<<"$o"); cg=$(sed -n 's/^ControlGroup=//p' <<<"$o") |
| 438 | case "$act" in |
| 439 | active|activating|deactivating|reloading|refreshing) echo running; return 0;; |
| 440 | inactive|failed) ;; |
| 441 | *) echo unresolved; return 0;; |
| 442 | esac |
| 443 | if [ "$load" = not-found ]; then echo done; return 0; fi |
| 444 | [ "$load" = loaded ] || { echo unresolved; return 0; } |
| 445 | if [ -n "$cg" ]; then |
| 446 | f="/sys/fs/cgroup$cg/cgroup.procs" |
| 447 | if [ -e "$f" ]; then |
| 448 | procs=$(cat "$f" 2>/dev/null) || { echo unresolved; return 0; } |
| 449 | [ -z "$procs" ] || { echo unresolved; return 0; } |
| 450 | fi |
| 451 | fi |
| 452 | echo done; } |
| 453 | # run_units: the names of every unit of this run that systemd has loaded; status 1 if systemctl fails. |
| 454 | run_units() { local o; o=$(_sc list-units --all --plain --no-legend --full -- "${UNIT_PREFIX}*") || return 1 |
| 455 | awk '{for (i = 1; i <= NF; i++) if ($i ~ /\.service$/) {print $i; break}}' <<<"$o"; } |
| 456 | # journal_units: every unit name this run journalled (UNIT lines in journal.tsv, this run's prefix |
| 457 | # only), one per line; status non-zero if the journal cannot be read. |
| 458 | journal_units() { local o |
| 459 | o=$(awk -F'\t' -v p="$UNIT_PREFIX" '$2 ~ /^UNIT / {u = substr($2, 6); if (index(u, p) == 1 && u ~ /\.service$/) print u}' "$T17/journal.tsv") || return 1 |
| 460 | [ -z "$o" ] || sort -u <<<"$o"; } |
| 461 | # unit_recorded UNIT: 0 if this run journalled UNIT. |
| 462 | unit_recorded() { local o; o=$(journal_units) || return 1; grep -qxF -- "$1" <<<"$o"; } |
| 463 | # unit_stop UNIT [DEADLINE]: only for a unit this run journalled (anything else: status 1, nothing |
| 464 | # stopped). systemctl --user stop, bounded at 75 s (systemd sends TERM to every process in the unit's |
| 465 | # cgroup, KILL after TimeoutStopSec=45, and reaps them); then reads unit_state for up to 15 s, never |
| 466 | # past DEADLINE (epoch seconds) when one is given. Status 0 only on done. |
| 467 | unit_stop() { local end |
| 468 | unit_recorded "$1" || { echo "unit_stop: $1 was not journalled by this run; it is not stopped" >&2; return 1; } |
| 469 | timeout 75 systemctl --user stop -- "$1" >/dev/null 2>&1 || true |
| 470 | end=$(( $(date +%s) + 15 )); if [ -n "${2:-}" ] && [ "$2" -lt "$end" ]; then end=$2; fi |
| 471 | while :; do |
| 472 | [ "$(unit_state "$1")" = done ] && return 0 |
| 473 | [ "$(date +%s)" -lt "$end" ] || return 1 |
| 474 | sleep 1 |
| 475 | done; } |
| 476 | # unit_start UNIT OUT STATUS [-E NAME=VALUE]... -- CMD...: journal "UNIT <UNIT>", then run |
| 477 | # /usr/bin/env -i <allowlist> <-E pairs> CMD as a transient user service in its own cgroup, with |
| 478 | # KillMode=control-group and TimeoutStopSec=45; stdout and stderr appended to OUT; working directory |
| 479 | # $T17; and, however it ends, bin/exitpost.sh writes its exit status (or signal:<name>) to STATUS. |
| 480 | # --collect removes the unit once it has ended; --expand-environment=no keeps every argument literal. |
| 481 | # The -E pairs come after the allowlist, so they win. UNIT must carry this run's prefix. |
| 482 | unit_start() { local u=$1 out=$2 st=$3 v; shift 3 |
| 483 | local envv=() |
| 484 | case "$u" in "$UNIT_PREFIX"*.service) ;; *) echo "unit_start: $u is not a unit name of this run" >&2; return 3;; esac |
| 485 | for v in $UNIT_ENV_VARS; do [ -z "${!v+x}" ] || envv+=("$v=${!v}"); done |
| 486 | while [ "$#" -gt 0 ] && [ "$1" != -- ]; do |
| 487 | [ "$1" = -E ] && [ "$#" -ge 2 ] && [[ "$2" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || { echo "unit_start: bad arguments" >&2; return 3; } |
| 488 | envv+=("$2"); shift 2 |
| 489 | done |
| 490 | [ "${1:-}" = -- ] && [ "$#" -ge 2 ] || { echo "unit_start: no command" >&2; return 3; } |
| 491 | shift |
| 492 | printf '%s\tUNIT %s\n' "$(date -u +%FT%T.%3NZ)" "$u" >> "$T17/journal.tsv" || { echo "unit_start: journal write failed" >&2; return 3; } |
| 493 | timeout 30 systemd-run --user --quiet --collect --expand-environment=no "--unit=$u" -p KillMode=control-group \ |
| 494 | -p TimeoutStopSec=45 -p "WorkingDirectory=$T17" -p StandardInput=null -p "StandardOutput=append:$out" \ |
| 495 | -p "StandardError=append:$out" -p "ExecStopPost=$T17/bin/exitpost.sh $st" -- /usr/bin/env -i "${envv[@]}" "$@"; } |
| 496 | # blocks_busy [EXCEPT]: print "<block or unit> <state>" for each detached block of this run, other |
| 497 | # than EXCEPT, that is running or unresolved (status "unresolved" counts), and for each listed block |
| 498 | # unit of this run that is not done; status 0 if there is any, 1 if none. A failed listing counts. |
| 499 | blocks_busy() { local f b s r=1 u units |
| 500 | for f in "$T17"/blocks/*.unit; do |
| 501 | [ -e "$f" ] || continue; b=$(basename "${f%.unit}"); [ "$b" != "${1:-}" ] || continue |
| 502 | s=$(unit_state "$(cat "$f")") |
| 503 | if [ "$s" = done ] && [ "$(cat "$T17/blocks/$b.status" 2>/dev/null || true)" = unresolved ]; then s=unresolved; fi |
| 504 | [ "$s" = done ] || { echo "$b $s"; r=0; } |
| 505 | done |
| 506 | if ! units=$(run_units); then echo "units unresolved: systemctl list-units failed"; return 0; fi |
| 507 | for u in $units; do |
| 508 | case "$u" in "${UNIT_PREFIX}ctl-"*|"${UNIT_PREFIX}probe.service"|"${UNIT_PREFIX}${1:-}.service") continue;; esac |
| 509 | s=$(unit_state "$u"); [ "$s" = done ] || { echo "$u $s"; r=0; } |
| 510 | done |
| 511 | return "$r"; } |
| 512 | # unit_probe: start t17b-<RUN>-probe.service (it records its environment, then runs sleep 60), see it |
| 513 | # running with a process in its cgroup, check that its environment holds only allowlisted names |
| 514 | # (plus PWD, SHLVL and _, which bash sets), stop it, and prove it done with exit status |
| 515 | # signal:TERM. 0.2 aborts unless this passes. |
| 516 | unit_probe() { local u="${UNIT_PREFIX}probe.service" i cg procs n |
| 517 | [ "$(unit_state "$u")" = done ] || return 1 |
| 518 | rm -f "$T17/out/probe.status" "$T17/out/probe.env" |
| 519 | unit_start "$u" "$T17/out/probe.out" "$T17/out/probe.status" -- /bin/bash -c 'env > "$0"; exec sleep 60' "$T17/out/probe.env" || return 1 |
| 520 | for i in $(seq 1 20); do [ "$(unit_state "$u")" = running ] && break; sleep 0.25; done |
| 521 | [ "$(unit_state "$u")" = running ] || { unit_stop "$u"; return 1; } |
| 522 | cg=$(_sc show -p ControlGroup --value -- "$u") || { unit_stop "$u"; return 1; } |
| 523 | procs=$(cat "/sys/fs/cgroup$cg/cgroup.procs" 2>/dev/null) || procs="" |
| 524 | [ -n "$cg" ] && [ -n "$procs" ] || { unit_stop "$u"; return 1; } |
| 525 | for i in $(seq 1 20); do [ -s "$T17/out/probe.env" ] && break; sleep 0.25; done |
| 526 | [ -s "$T17/out/probe.env" ] || { unit_stop "$u"; return 1; } |
| 527 | for n in $(sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' "$T17/out/probe.env"); do |
| 528 | case " $(echo $UNIT_ENV_VARS) PWD SHLVL _ " in *" $n "*) ;; *) echo "unit_probe: $n reached the unit" >&2; unit_stop "$u"; return 1;; esac |
| 529 | done |
| 530 | unit_stop "$u" || return 1 |
| 531 | [ "$(cat "$T17/out/probe.status" 2>/dev/null || true)" = signal:TERM ]; } |
| 532 | BCEOF |
| 533 | cat > "$TMPDIR/equipo-t17b/bin/exitpost.sh" <<'EPEOF' |
| 534 | #!/bin/sh |
| 535 | # ExecStopPost for Task 17b units: record how the unit's main process ended, in the file named by $1. |
| 536 | # systemd sets EXIT_CODE (exited, killed or dumped) and EXIT_STATUS (a number or a signal name). |
| 537 | case "${EXIT_CODE:-}" in |
| 538 | exited) printf '%s\n' "${EXIT_STATUS:-unknown}";; |
| 539 | "") printf 'unknown\n';; |
| 540 | *) printf 'signal:%s\n' "${EXIT_STATUS:-unknown}";; |
| 541 | esac > "$1" |
| 542 | EPEOF |
| 543 | chmod 755 "$TMPDIR/equipo-t17b/bin/exitpost.sh" |
| 544 | cat > "$TMPDIR/equipo-t17b/env.sh" <<'ENVEOF' |
| 545 | # env.sh: sourced by every block, after `set -euo pipefail`. Task 17b only. |
| 546 | : "${TMPDIR:?TMPDIR is unset}" |
| 547 | # T17 may be set by a sandbox-off block (R37); otherwise it is $TMPDIR/equipo-t17b. |
| 548 | unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_SECURITY_TOKEN AWS_DEFAULT_PROFILE \ |
| 549 | AWS_CONFIG_FILE AWS_SHARED_CREDENTIALS_FILE AWS_ROLE_ARN AWS_ROLE_SESSION_NAME AWS_WEB_IDENTITY_TOKEN_FILE \ |
| 550 | AWS_CA_BUNDLE AWS_ENDPOINT_URL AWS_USE_FIPS_ENDPOINT AWS_USE_DUALSTACK_ENDPOINT |
| 551 | for _v in $(env | sed -n 's/^\(AWS_ENDPOINT_URL_[A-Z0-9_]*\)=.*/\1/p'); do unset "$_v"; done |
| 552 | export AWS_PROFILE=kass AWS_REGION=eu-west-1 AWS_DEFAULT_REGION=eu-west-1 AWS_PAGER="" \ |
| 553 | AWS_STS_REGIONAL_ENDPOINTS=regional AWS_RETRY_MODE=standard AWS_MAX_ATTEMPTS=3 |
| 554 | export CGO_ENABLED=0 |
| 555 | if [ -z "${T17:-}" ]; then T17="$TMPDIR/equipo-t17b"; fi |
| 556 | export T17 REPO=/home/paulca/amadan.net/oficina/equipo-hosted-1a |
| 557 | export LIVECTL="$T17/bin/livectl" |
| 558 | export ACCOUNT=640012953448 TAGV=equipo-hosted-dev |
| 559 | export LEDGER="$T17/ledger.env" JOURNAL="$T17/journal.tsv" VMS="$T17/vms.tsv" |
| 560 | export NO_INGRESS=arn:aws:lambda:eu-west-1:aws:network-connector:aws-network-connector:NO_INGRESS |
| 561 | export API=127.0.0.1:18443 METRICS=127.0.0.1:18444 |
| 562 | # A live MicroVM ID: "microvm-" and a lower-case UUID, 44 characters (attempt 4). |
| 563 | export VMID_RE='microvm-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' |
| 564 | [ -d "$T17" ] || { echo "ABORT: $T17 does not exist; was TMPDIR changed?" >&2; exit 1; } |
| 565 | [ -f "$T17/run.env" ] && . "$T17/run.env" |
| 566 | [ -f "$LEDGER" ] && . "$LEDGER" |
| 567 | # One block at a time (R44): refuse to load while a block unit other than this one (T17_BLOCK, set by |
| 568 | # the long-block start call) is running or unresolved. S.0 does not load env.sh. |
| 569 | [ -f "$T17/unitctl.sh" ] || { echo "ABORT: $T17/unitctl.sh is missing" >&2; exit 1; } |
| 570 | . "$T17/unitctl.sh" |
| 571 | if _busy=$(blocks_busy "${T17_BLOCK:-}"); then |
| 572 | echo "ABORT: a block unit is unfinished: $_busy. Wait for it with its wait call; after an abort, run S.0 first." >&2; exit 1 |
| 573 | fi |
| 574 | |
| 575 | # die: a hard stop. It also appends to $T17/FATAL, so a hard stop inside a subshell, a poll or a |
| 576 | # command substitution reaches the parent: finding and fatal_check re-raise it, so it can never |
| 577 | # become a FINDING. Exit status 99. |
| 578 | die() { echo "ABORT: $*" >&2; jw "ABORT $*" 2>/dev/null || true; printf '%s\n' "$*" >> "$T17/FATAL" 2>/dev/null || true; exit 99; } |
| 579 | # soft_fail: an ordinary failure (a poll's bound or an unexpected state) that ends the current |
| 580 | # (sub)shell with status 1 without a hard stop; at a block's top level it still ends the block. |
| 581 | soft_fail() { echo "FAILED: $*" >&2; jw "FAILED $*" 2>/dev/null || true; exit 1; } |
| 582 | _fatal_count() { if [ -f "$T17/FATAL" ]; then wc -l < "$T17/FATAL"; else echo 0; fi; } |
| 583 | _FATAL0=$(_fatal_count) |
| 584 | # fatal_check: re-raise any hard stop that happened in a subshell since this block began. |
| 585 | fatal_check() { [ "$(_fatal_count)" -le "$_FATAL0" ] || die "a hard stop happened inside a subshell: $(tail -n 1 "$T17/FATAL")"; } |
| 586 | # need VAR...: each must be set, non-empty, and not None or null. |
| 587 | need() { local v; for v; do [ -n "${!v:-}" ] && [ "${!v}" != None ] && [ "${!v}" != null ] || die "$v is unset"; done; } |
| 588 | # arn_ok ARN: in this account and eu-west-1 (IAM and S3 ARNs have no region). |
| 589 | arn_ok() { |
| 590 | case "$1" in |
| 591 | *149757027610*) die "ARN $1 names account 149757027610";; |
| 592 | arn:aws:*:eu-west-1:640012953448:*|arn:aws:iam::640012953448:role/*|arn:aws:s3:::*) ;; |
| 593 | *) die "ARN $1 is not in 640012953448 and eu-west-1";; |
| 594 | esac |
| 595 | } |
| 596 | # jw TEXT: one journal line; a failed write is an abort. |
| 597 | jw() { local t="$*"; t=${t//$'\r'/}; t=${t//$'\n'/ | }; t=${t//$'\t'/ } |
| 598 | printf '%s\t%s\n' "$(date -u +%FT%T.%3NZ)" "$t" >> "$JOURNAL" || { echo "ABORT: journal write failed" >&2; exit 1; }; } |
| 599 | # _kind VAR: sets K_I and K_N, the journal patterns for VAR's INTENT and NOTCREATED records ("" when |
| 600 | # VAR has no creation of its own: the VPC defaults exist only with the VPC, and image versions only |
| 601 | # with the image, which livectl deletes whole). |
| 602 | _kind() { case "$1" in |
| 603 | VPC) K_I='^INTENT vpc( |$)'; K_N='^NOTCREATED vpc( |$)';; |
| 604 | SUBNET) K_I='^INTENT subnet( |$)'; K_N='^NOTCREATED subnet( |$)';; |
| 605 | RTB) K_I='^INTENT route-table( |$)'; K_N='^NOTCREATED route-table( |$)';; |
| 606 | RTB_ASSOC) K_I='^INTENT route-table-association( |$)'; K_N='^NOTCREATED route-table-association( |$)';; |
| 607 | SG) K_I='^INTENT security-group( |$)'; K_N='^NOTCREATED security-group( |$)';; |
| 608 | OPERATOR_ROLE_ARN) K_I="^INTENT iam-role $OPERATOR_ROLE( |\$)"; K_N="^NOTCREATED iam-role $OPERATOR_ROLE( |\$)";; |
| 609 | BUILD_ROLE_ARN) K_I="^INTENT iam-role $BUILD_ROLE( |\$)"; K_N="^NOTCREATED iam-role $BUILD_ROLE( |\$)";; |
| 610 | CONN_ARN) K_I='^INTENT connector( |$)'; K_N='^NOTCREATED connector( |$)';; |
| 611 | BUCKET_CREATED) K_I='^INTENT s3-bucket( |$)'; K_N='^NOTCREATED s3-bucket( |$)';; |
| 612 | LOG_GROUP_CREATED) K_I='^INTENT log-group( |$)'; K_N='^NOTCREATED log-group( |$)';; |
| 613 | ARTIFACT) K_I='^INTENT s3-object( |$)'; K_N='^NOTCREATED s3-object( |$)';; |
| 614 | IMAGE_ARN) K_I='^INTENT microvm-image( |$)'; K_N='^NOTCREATED (microvm-image|image attempt)( |$)';; |
| 615 | TOPIC_ARN) K_I='^INTENT sns-topic( |$)'; K_N='^NOTCREATED sns-topic( |$)';; |
| 616 | *) K_I=''; K_N='';; |
| 617 | esac; } |
| 618 | # creation_state VAR: sets CST to confirmed (VAR is set), none (never attempted), absent (the last |
| 619 | # attempt is followed by a NOTCREATED record) or unresolved (attempted, neither confirmed nor shown absent). |
| 620 | creation_state() { |
| 621 | if [ -n "${!1:-}" ]; then CST=confirmed; return 0; fi |
| 622 | _kind "$1"; if [ -z "$K_I" ]; then CST=none; return 0; fi |
| 623 | CST=$(awk -F'\t' -v ri="$K_I" -v rn="$K_N" '$2 ~ ri {li = NR} $2 ~ rn {ln = NR} END {if (!li) print "none"; else if (ln > li) print "absent"; else print "unresolved"}' "$JOURNAL") || die "journal unreadable" |
| 624 | } |
| 625 | # have VAR: 0 to act on a confirmed creation; 1, with a journalled SKIP, for one never attempted or |
| 626 | # shown absent. An unresolved creation is never skipped: it aborts, so teardown cannot complete and |
| 627 | # scratch cannot be removed until S.2 reconciles it (the skip-never-created rule). |
| 628 | have() { |
| 629 | creation_state "$1" |
| 630 | case "$CST" in |
| 631 | confirmed) return 0;; |
| 632 | none|absent) jw "SKIP $1 $CST"; echo "skip: $1 ($CST: never created)"; return 1;; |
| 633 | *) jw "UNRESOLVED-TEARDOWN $1"; die "$1: a creation was attempted but is neither confirmed nor shown absent; reconcile it (S.2) first";; |
| 634 | esac |
| 635 | } |
| 636 | # no_unresolved: abort if any resource is still unresolved. |
| 637 | no_unresolved() { local v; for v in VPC SUBNET RTB RTB_ASSOC SG OPERATOR_ROLE_ARN BUILD_ROLE_ARN CONN_ARN BUCKET_CREATED LOG_GROUP_CREATED ARTIFACT IMAGE_ARN TOPIC_ARN; do |
| 638 | creation_state "$v"; [ "$CST" != unresolved ] || die "$v is unresolved; reconcile it (S.2) before finishing"; done; } |
| 639 | # gone0 WHAT CMD...: a list read that must succeed and count 0 (no error code is guessed). |
| 640 | gone0() { local w=$1; shift; get _g "$@"; [ "$_g" = 0 ] || die "$w is still listed ($_g)"; } |
| 641 | # intent KIND KEY DETAIL...: written BEFORE a create call. |
| 642 | intent() { jw "INTENT $*"; } |
| 643 | # rec VAR VALUE: written AFTER a create call returned the ID; checked; exported. |
| 644 | rec() { |
| 645 | [ $# = 2 ] || die "rec needs a name and a value" |
| 646 | case "$2" in ""|None|null) die "rec $1: empty value";; *149757027610*) die "rec $1=$2 names account 149757027610";; esac |
| 647 | printf 'export %s=%q\n' "$1" "$2" >> "$LEDGER" || die "ledger write failed" |
| 648 | jw "CONFIRMED $1 $2" |
| 649 | export "$1=$2" |
| 650 | } |
| 651 | # deleted KIND ID HOW: written after a deletion is confirmed by a direct read. |
| 652 | deleted() { jw "DELETED $*"; } |
| 653 | # try CMD...: run CMD; never exits; sets OUT, ERR, RC and ECODE (the AWS error code, if any). |
| 654 | try() { |
| 655 | local had=0 e; case $- in *e*) had=1;; esac |
| 656 | e=$(mktemp "$T17/err.XXXXXX") || { echo "ABORT: mktemp" >&2; exit 1; } |
| 657 | set +e; OUT=$("$@" 2>"$e"); RC=$?; [ "$had" = 1 ] && set -e |
| 658 | ERR=$(cat "$e"); rm -f "$e" |
| 659 | ECODE=$(printf '%s' "$ERR" | sed -n 's/.*An error occurred (\([A-Za-z0-9.]*\)).*/\1/p' | head -n 1) |
| 660 | return 0 |
| 661 | } |
| 662 | # must: after try, the call must have succeeded. |
| 663 | must() { [ "$RC" = 0 ] || die "call failed (rc $RC, ${ECODE:-no code}): $ERR"; } |
| 664 | # get VAR CMD...: run a read; abort unless it succeeded; only then store its output in VAR. |
| 665 | get() { local __v=$1; shift; try "$@"; must; printf -v "$__v" '%s' "$OUT"; } |
| 666 | # _creds: export kass's credentials through the CLI's own resolution (its credential_process), |
| 667 | # into shell variables of the calling (sub)shell only (R42). Never written to disk, the journal or |
| 668 | # any argument list, and never printed. AccessKeyId and SecretAccessKey are required; a |
| 669 | # SessionToken, if present, needs an Expiration. Static IAM user keys have neither. |
| 670 | _creds() { |
| 671 | local j rc had=0; case $- in *e*) had=1;; esac |
| 672 | set +e; j=$(timeout 30 aws configure export-credentials --profile kass --format process 2>/dev/null); rc=$?; [ "$had" = 1 ] && set -e |
| 673 | [ "$rc" = 0 ] || return 1 |
| 674 | _AK=$(jq -r '.AccessKeyId // empty' <<<"$j" 2>/dev/null || true) |
| 675 | _SK=$(jq -r '.SecretAccessKey // empty' <<<"$j" 2>/dev/null || true) |
| 676 | _ST=$(jq -r '.SessionToken // empty' <<<"$j" 2>/dev/null || true) |
| 677 | _EXP=$(jq -r '.Expiration // empty' <<<"$j" 2>/dev/null || true) |
| 678 | j="" |
| 679 | [ -n "$_AK" ] && [ -n "$_SK" ] || return 1 |
| 680 | [ -z "$_ST" ] || [ -n "$_EXP" ] || return 1 |
| 681 | } |
| 682 | # _lvx ARGS...: livectl in a subshell whose environment holds exactly the exported static keys: |
| 683 | # AWS_PROFILE, AWS_CONFIG_FILE and AWS_SHARED_CREDENTIALS_FILE are unset for it, so livectl sees only |
| 684 | # static environment keys. A failed export is livectl's guard exit (4): a hard stop in lv. |
| 685 | _lvx() ( |
| 686 | if ! _creds; then echo '{"error":"guard","message":"kass credentials could not be exported as static keys (R42)"}' >&2; exit 4; fi |
| 687 | unset AWS_PROFILE AWS_CONFIG_FILE AWS_SHARED_CREDENTIALS_FILE AWS_SESSION_TOKEN |
| 688 | export AWS_ACCESS_KEY_ID="$_AK" AWS_SECRET_ACCESS_KEY="$_SK" |
| 689 | [ -z "$_ST" ] || export AWS_SESSION_TOKEN="$_ST" |
| 690 | unset _AK _SK _ST |
| 691 | exec "$LIVECTL" -run "$RUN" "$@" |
| 692 | ) |
| 693 | # cred_left: seconds until the exported credentials expire, or "none" for static keys without an |
| 694 | # Expiration. Prints nothing secret. |
| 695 | cred_left() ( _creds || exit 4; unset _AK _SK _ST |
| 696 | if [ -z "$_EXP" ]; then echo none; else echo $(( $(date -d "$_EXP" +%s) - $(date +%s) )); fi ) |
| 697 | # lv ARGS...: one livectl call (every Lambda MicroVMs and Lambda core call, R40). Sets OUT, ERR, RC, |
| 698 | # ECODE (the smithy error code), LV_KIND (api, transport, usage, guard, timeout, failed_state, other) |
| 699 | # and LV_MSG (the service's own text). A guard refusal (4) or usage error (3) is a hard stop. |
| 700 | lv() { |
| 701 | [ -x "$LIVECTL" ] || die "livectl is not built at $LIVECTL" |
| 702 | need RUN |
| 703 | try _lvx "$@" |
| 704 | ECODE=""; LV_KIND=""; LV_MSG=""; LV_HTTP="" |
| 705 | if [ "$RC" != 0 ]; then |
| 706 | local e; e=$(tail -n 1 <<<"$ERR") |
| 707 | ECODE=$(jq -r '.code // empty' <<<"$e" 2>/dev/null || true) |
| 708 | LV_KIND=$(jq -r '.error // empty' <<<"$e" 2>/dev/null || true) |
| 709 | LV_MSG=$(jq -r '.aws_message // empty' <<<"$e" 2>/dev/null || true) |
| 710 | LV_HTTP=$(jq -r '.http_status // empty' <<<"$e" 2>/dev/null || true) |
| 711 | fi |
| 712 | [ "$RC" != 4 ] || die "livectl guard refusal (account, region, run prefix or -run): $ERR" |
| 713 | [ "$RC" != 3 ] || die "livectl usage error (a plan defect): $ERR" |
| 714 | return 0 |
| 715 | } |
| 716 | # _transient: after lv, 0 if the failure is worth trying again: livectl makes one attempt per call, |
| 717 | # so a throttle, a server error or no answer within its 60 s cutoff comes back as exit 2. |
| 718 | _transient() { [ "$RC" = 2 ] || return 1; [ "$LV_KIND" = transport ] && return 0 |
| 719 | case "$ECODE" in ThrottlingException|TooManyRequestsException|InternalServerException|ServiceException|ServiceUnavailableException) return 0;; esac; return 1; } |
| 720 | # lvr ARGS...: lv with up to 3 tries, 5 s apart, on a transient failure. For reads and idempotent |
| 721 | # deletes and terminates only; creates and other changes use lv once. |
| 722 | lvr() { local i; for i in 1 2 3; do lv "$@"; _transient || return 0; [ "$i" = 3 ] || { echo "transient (${ECODE:-$LV_KIND}); trying again"; sleep 5; }; done; return 0; } |
| 723 | # lv_wait SECONDS ARGS...: a livectl wait with one outer deadline, SECONDS from now, covering the |
| 724 | # credential export (bounded at 30 s), livectl's start and account check (its 60 s cutoff) and the |
| 725 | # waiting itself: 90 s of each call is kept for the first two. A chunk is never longer than what is |
| 726 | # left; when the exported credentials expire sooner (less a 120 s margin) the wait is split into |
| 727 | # shorter calls, each with fresh credentials. A transient exit 2 is a FINDING and the wait goes on. |
| 728 | # A success that comes back after the deadline counts as a timeout. Leaves RC 0, 5 (the deadline |
| 729 | # passed), 6 (a failed state) or 2 (any other error). A guard failure stays a hard stop. |
| 730 | lv_wait() { local end=$(( $(date +%s) + $1 )) left cl chunk; shift |
| 731 | while :; do |
| 732 | left=$(( end - $(date +%s) - 90 )); if [ "$left" -le 0 ]; then RC=5; return 0; fi |
| 733 | cl=$(cred_left) || die "kass credentials could not be exported (R42)" |
| 734 | left=$(( end - $(date +%s) - 90 )); if [ "$left" -le 0 ]; then RC=5; return 0; fi |
| 735 | chunk=$left |
| 736 | if [ "$cl" != none ] && [ $(( cl - 120 )) -lt "$chunk" ]; then |
| 737 | chunk=$(( cl - 120 )); if [ "$chunk" -lt 15 ]; then chunk=$(( left < 15 ? left : 15 )); fi |
| 738 | fi |
| 739 | lv "$@" -timeout "${chunk}s" |
| 740 | if [ "$RC" = 0 ] && [ "$(date +%s)" -gt "$end" ]; then finding "a wait answered after its deadline; counted as a timeout"; RC=5; return 0; fi |
| 741 | if _transient; then finding "transient error inside a wait (${ECODE:-$LV_KIND}); waiting on"; sleep 5; continue; fi |
| 742 | if [ "$RC" = 5 ] && [ "$chunk" -lt "$left" ]; then echo "wait split at the credentials' expiry; going on with fresh credentials"; continue; fi |
| 743 | return 0 |
| 744 | done; } |
| 745 | # finding TEXT: a FINDING line in the journal; the run goes on (Paul's rule 1). |
| 746 | finding() { fatal_check; jw "FINDING $*"; echo "FINDING: $*"; } |
| 747 | # fact_eq WHAT WANT CMD...: a read of the run's own resource; a failed read or another value is a FINDING. |
| 748 | fact_eq() { local w=$1 want=$2; shift 2; try "$@" |
| 749 | if [ "$RC" != 0 ]; then finding "$w: read failed (${ECODE:-rc$RC})"; elif [ "$OUT" = "$want" ]; then echo "ok: $w"; else finding "$w: got [$OUT], want [$want]"; fi; } |
| 750 | # fact_json WHAT WANT CMD...: as fact_eq, comparing compacted JSON. |
| 751 | fact_json() { local w=$1 want=$2 got; shift 2; try "$@" |
| 752 | if [ "$RC" != 0 ]; then finding "$w: read failed (${ECODE:-rc$RC})"; return 0; fi |
| 753 | got=$(jq -c . <<<"$OUT" 2>/dev/null) || { finding "$w: reply is not JSON"; return 0; } |
| 754 | if [ "$got" = "$(jq -c . <<<"$want")" ]; then echo "ok: $w"; else finding "$w: got $got, want $want"; fi; } |
| 755 | # fact_lv WHAT WANT JQ ARGS...: a livectl read; jq -r JQ of the reply must equal WANT, else a FINDING. |
| 756 | fact_lv() { local w=$1 want=$2 q=$3 got; shift 3; lvr "$@" |
| 757 | if [ "$RC" != 0 ]; then finding "$w: read failed (${ECODE:-rc$RC})"; return 0; fi |
| 758 | got=$(jq -r "$q" <<<"$OUT" 2>/dev/null) || { finding "$w: reply unreadable"; return 0; } |
| 759 | if [ "$got" = "$want" ]; then echo "ok: $w"; else finding "$w: got [$got], want [$want]"; fi; } |
| 760 | # code_in CODE...: after try, 0 if the call failed with one of CODE. |
| 761 | code_in() { local c; [ "$RC" != 0 ] || return 1; for c; do [ "$ECODE" = "$c" ] && return 0; done; return 1; } |
| 762 | # expect_err CODE...: after try, the call must have failed with one of CODE (an expected-failure branch). |
| 763 | expect_err() { code_in "$@" || die "expected one of [$*], got rc $RC ${ECODE:-no code}: ${ERR:-$OUT}"; } |
| 764 | guard() { |
| 765 | [ "$AWS_PROFILE" = kass ] && [ "$AWS_REGION" = eu-west-1 ] && [ "$AWS_DEFAULT_REGION" = eu-west-1 ] || die "profile or region changed" |
| 766 | [ -z "${AWS_ACCESS_KEY_ID:-}" ] || die "AWS_ACCESS_KEY_ID is set" |
| 767 | try aws sts get-caller-identity --query Account --output text; must |
| 768 | [ "$OUT" = "$ACCOUNT" ] || die "account is $OUT, not $ACCOUNT" |
| 769 | } |
| 770 | # poll SECONDS INTERVAL WHAT FN ARGS...: FN returns 0 done, 1 not yet, anything else an ordinary |
| 771 | # failure (soft_fail). A hard stop inside FN (die) stays a hard stop. |
| 772 | poll() { |
| 773 | local secs=$1 iv=$2 what=$3 rc had=0 end; end=$(( $(date +%s) + secs )); shift 3 |
| 774 | case $- in *e*) had=1;; esac |
| 775 | while :; do |
| 776 | set +e; "$@"; rc=$?; [ "$had" = 1 ] && set -e |
| 777 | [ "$rc" = 0 ] && return 0 |
| 778 | fatal_check |
| 779 | [ "$rc" = 1 ] || soft_fail "$what: unexpected state (rc $rc)" |
| 780 | [ "$(date +%s)" -lt "$end" ] || soft_fail "$what: not done within $secs s" |
| 781 | sleep "$iv" |
| 782 | done |
| 783 | } |
| 784 | |
| 785 | # --- MicroVMs: recorded by ID (they have no tags), found by the image-scoped List --- |
| 786 | # vmrec ID SOURCE START: one VM ledger line per (ID, source, start). START is the provider's |
| 787 | # startedAt, or "phase:<time>" (the start of the phase that found it) when only that is known. |
| 788 | vmrec() { |
| 789 | [ $# = 3 ] && [ -n "$3" ] && [ "$3" != phase: ] || die "vmrec $1: no start time" |
| 790 | [ -f "$VMS" ] || die "no VM ledger" |
| 791 | local key; printf -v key '%s\t%s\t%s\t' "$1" "$2" "$3" |
| 792 | grep -qF "$key" "$VMS" && return 0 |
| 793 | printf '%s%s\n' "$key" "$(date -u +%FT%T.%3NZ)" >> "$VMS" || die "VM ledger write failed" |
| 794 | jw "VM $1 $2 $3" |
| 795 | } |
| 796 | # vm_ids: sets VIDS to every recorded VM ID. |
| 797 | vm_ids() { [ -f "$VMS" ] || die "no VM ledger"; VIDS=$(cut -f1 "$VMS" | sort -u) || die "VM ledger unreadable"; } |
| 798 | # list_items: validate a livectl list reply in OUT: a JSON object with an explicit Items key whose |
| 799 | # value is null or an array. On success ITEMS holds that array, with null read as []. Anything else |
| 800 | # (not JSON, not an object, no Items key, Items of another type) returns 1, and the caller fails per |
| 801 | # its own rules: a hard stop where the result drives a safety decision (collision, settled, deleted, |
| 802 | # reconciliation), a FINDING for an observation. |
| 803 | list_items() { |
| 804 | ITEMS=$(jq -ce 'if type == "object" and has("Items") and (.Items == null or (.Items | type) == "array") then (.Items // []) else error("malformed") end' <<<"$OUT" 2>/dev/null) || { ITEMS=""; return 1; } |
| 805 | } |
| 806 | # scan: one image-scoped List, every page, every state; records every ID; writes last_scan.tsv. |
| 807 | scan() { |
| 808 | need IMAGE_ARN |
| 809 | lvr vm list -image "$IMAGE_ARN"; must |
| 810 | list_items || die "malformed VM list reply: $(head -c 200 <<<"$OUT")" |
| 811 | jq -e --arg a "$IMAGE_ARN" 'all(.[]; .ImageArn == $a)' <<<"$ITEMS" >/dev/null || die "list returned a VM of another image" |
| 812 | jq -r '.[] | [.MicrovmId, .State, .StartedAt] | @tsv' <<<"$ITEMS" > "$T17/last_scan.tsv" || die "VM list items unreadable" |
| 813 | local id st started |
| 814 | while IFS=$'\t' read -r id st started; do [ -n "$id" ] && vmrec "$id" scan "$started"; done < "$T17/last_scan.tsv" |
| 815 | LIVE=$(awk -F'\t' '$2 != "TERMINATED" {print $1}' "$T17/last_scan.tsv") || die "scan output unreadable" |
| 816 | cat "$T17/last_scan.tsv" |
| 817 | } |
| 818 | # After scan, LIVE holds the IDs of this image's VMs that are not TERMINATED. |
| 819 | # vm_get ID: sets VST to the state, NOTFOUND, or ERROR:<code>. |
| 820 | vm_get() { |
| 821 | lvr vm get -id "$1" |
| 822 | if [ "$RC" = 0 ]; then VST=$(jq -r '.State // empty' <<<"$OUT"); [ -n "$VST" ] || VST="ERROR:no-state"; elif [ "$ECODE" = ResourceNotFoundException ]; then VST=NOTFOUND; else VST="ERROR:${ECODE:-${LV_KIND:-rc$RC}}"; fi |
| 823 | } |
| 824 | _vm_check() { vm_get "$1"; echo "$(date -u +%T) $1 $VST"; [ "$VST" = "$2" ] && return 0; case " $3 ThrottlingException transport " in *" ${VST#ERROR:} "*) return 1;; esac; return 2; } |
| 825 | # vm_wait ID TARGET SECONDS ALLOWED...: wait for TARGET; a state outside ALLOWED is fatal. |
| 826 | vm_wait() { local id=$1 t=$2 s=$3; shift 3; poll "$s" 5 "VM $id to $t" _vm_check "$id" "$t" "$*"; } |
| 827 | # vm_end ID: terminate and confirm: TERMINATED, or not found twice at least 60 s apart. |
| 828 | vm_end() { |
| 829 | lvr vm terminate -id "$1" |
| 830 | [ "$RC" = 0 ] || [ "$ECODE" = ResourceNotFoundException ] || die "terminate $1: ${ECODE:-rc$RC} ${LV_MSG:-$ERR}" |
| 831 | local nf=0 end=$(( $(date +%s) + 600 )) |
| 832 | while :; do |
| 833 | vm_get "$1"; echo "$(date -u +%T) $1 $VST" |
| 834 | case "$VST" in |
| 835 | TERMINATED) jw "VMGONE $1 TERMINATED"; return 0;; |
| 836 | NOTFOUND) [ "$nf" = 0 ] && nf=$(date +%s); [ $(( $(date +%s) - nf )) -ge 60 ] && { jw "VMGONE $1 NOTFOUND-TWICE"; return 0; };; |
| 837 | PENDING|RUNNING|SUSPENDING|SUSPENDED|TERMINATING|ERROR:ThrottlingException|ERROR:transport) nf=0;; |
| 838 | *) die "VM $1: $VST";; |
| 839 | esac |
| 840 | [ "$(date +%s)" -lt "$end" ] || die "VM $1 has not ended after 10 min" |
| 841 | sleep 10 |
| 842 | done |
| 843 | } |
| 844 | # settle_all: end every recorded and every listed live VM; done only after three scans 30 s apart show none live. |
| 845 | settle_all() { |
| 846 | need IMAGE_ARN; local round i clean id |
| 847 | for round in 1 2 3; do |
| 848 | scan >/dev/null |
| 849 | for id in $LIVE; do vm_end "$id"; done |
| 850 | vm_ids |
| 851 | for id in $VIDS; do grep -q "VMGONE $id " "$JOURNAL" || vm_end "$id"; done |
| 852 | clean=0 |
| 853 | for i in 1 2 3; do |
| 854 | scan >/dev/null |
| 855 | [ -n "$LIVE" ] && break |
| 856 | clean=$((clean + 1)); [ "$i" -lt 3 ] && sleep 30 |
| 857 | done |
| 858 | vm_ids |
| 859 | [ "$clean" = 3 ] && { jw "SETTLED $(wc -w <<<"$VIDS") recorded"; echo "settled: $(wc -w <<<"$VIDS") VMs recorded, none live in three scans"; return 0; } |
| 860 | done |
| 861 | die "VMs still live after three settle rounds" |
| 862 | } |
| 863 | # launch LABEL TOKEN MAXSECONDS PAYLOADFILE: one livectl vm run (Small, NO_INGRESS, the connector); |
| 864 | # records any VM it returns. TOKEN must start with the run prefix. Sets L_OUTCOME: |
| 865 | # created the reply names a VM (recorded); |
| 866 | # rejected a confirmed refusal: an api error with a 4xx status, so AWS did not run it; |
| 867 | # settled the outcome was uncertain (no answer, a 5xx, an unreadable error): the identical |
| 868 | # request was replayed up to twice under the same client token; if no replay named a |
| 869 | # VM, settle_all ended every live VM of this image (bounded image-scoped scans), which |
| 870 | # proves nothing launched is left. If that cannot be proved, settle_all is a hard stop. |
| 871 | _launch_once() { |
| 872 | lv vm run -image "$IMAGE_ARN" -version "$VER_SMALL" -connector "$CONN_QARN" -max-seconds "$3" \ |
| 873 | -client-token "$2" -payload-file "$4" |
| 874 | printf '%s\n' "$OUT" > "$T17/out/launch-$1.json"; printf '%s\n' "$ERR" > "$T17/out/launch-$1.err" |
| 875 | L_RC=$RC; L_CODE=$ECODE; L_MSG=$LV_MSG; L_ID="" |
| 876 | if [ "$RC" = 0 ]; then |
| 877 | L_ID=$(printf '%s' "$OUT" | jq -r '.MicrovmId // empty') |
| 878 | [ -n "$L_ID" ] || die "launch $1 succeeded with no MicrovmId" |
| 879 | local st; st=$(printf '%s' "$OUT" | jq -r '.StartedAt // empty') |
| 880 | vmrec "$L_ID" "$1" "${st:-phase:$L_T0}"; L_OUTCOME=created |
| 881 | elif [ "$LV_KIND" = api ] && [ -n "$LV_HTTP" ] && [ "$LV_HTTP" -ge 400 ] && [ "$LV_HTTP" -lt 500 ]; then L_OUTCOME=rejected |
| 882 | else L_OUTCOME=uncertain; fi |
| 883 | } |
| 884 | launch() { |
| 885 | need IMAGE_ARN VER_SMALL CONN_QARN; [ -f "$4" ] || die "no payload file $4" |
| 886 | intent vm "$1" "token=$2" "max=$3" |
| 887 | L_T0=$(date -u +%FT%T.%3NZ) |
| 888 | _launch_once "$@" |
| 889 | local k |
| 890 | for k in 1 2; do |
| 891 | [ "$L_OUTCOME" = uncertain ] || break |
| 892 | jw "UNCERTAIN vm $1 token=$2 (${L_CODE:-${LV_KIND:-rc$L_RC}}): replay $k with the same client token"; sleep 5 |
| 893 | _launch_once "$1-replay$k" "$2" "$3" "$4" |
| 894 | done |
| 895 | if [ "$L_OUTCOME" = uncertain ] || { [ "$L_OUTCOME" = rejected ] && grep -q $'\tUNCERTAIN vm '"$1"' ' "$JOURNAL"; }; then |
| 896 | finding "launch $1 has an uncertain outcome (${L_CODE:-${LV_KIND:-rc$L_RC}}); settling every VM of the image" |
| 897 | settle_all; L_OUTCOME=settled; L_ID=""; jw "RESOLVED vm $1 by settlement" |
| 898 | fi |
| 899 | echo "launch $1: $L_OUTCOME rc=$L_RC code=${L_CODE:-none} id=${L_ID:-none}" |
| 900 | } |
| 901 | # eni_snapshot MODE WHEN: list the VPC's interfaces. Any outside this run's subnet is not in the ledger: |
| 902 | # a hard stop, before anything is recorded. Each one inside is recorded once as SERVICE-ENI, so 10.2 |
| 903 | # can prove each ID gone. MODE strict makes a failed list a hard stop (10.2 needs it); soft makes it a |
| 904 | # FINDING (observations during the VM phases). |
| 905 | eni_snapshot() { |
| 906 | need VPC SUBNET |
| 907 | try aws ec2 describe-network-interfaces --filters Name=vpc-id,Values="$VPC" --output json |
| 908 | if [ "$RC" != 0 ]; then |
| 909 | [ "$1" = strict ] && die "interface list failed (${ECODE:-rc$RC}); 10.2 needs it" |
| 910 | finding "interface list failed ($2): ${ECODE:-rc$RC}"; return 0 |
| 911 | fi |
| 912 | printf '%s' "$OUT" | jq -e '.NetworkInterfaces | type == "array"' >/dev/null || die "interface list unreadable ($2)" |
| 913 | printf '%s' "$OUT" | jq -e --arg s "$SUBNET" 'all(.NetworkInterfaces[]; .SubnetId == $s)' >/dev/null \ |
| 914 | || die "an interface outside this run's subnet is in the run's VPC ($2): not in the ledger" |
| 915 | local e n=0 |
| 916 | for e in $(printf '%s' "$OUT" | jq -r '.NetworkInterfaces[].NetworkInterfaceId'); do |
| 917 | n=$((n + 1)); grep -qF "SERVICE-ENI $e" "$JOURNAL" || jw "SERVICE-ENI $e" |
| 918 | done |
| 919 | jw "FACT interfaces in the VPC ($2): $n"; echo "interfaces in the VPC ($2): $n" |
| 920 | } |
| 921 | # harvest LOG SOURCE PHASESTART: record every MicroVM ID (VMID_RE) a log names, with the phase start |
| 922 | # as its conservative start (scans add the provider's startedAt later). Any other "microvm-..." token |
| 923 | # that is not an image name is a FINDING: the ID form may have changed, and the image-scoped scans |
| 924 | # (which record every VM whatever its form) are then the only inventory. |
| 925 | harvest() { |
| 926 | [ -f "$1" ] && [ -n "${3:-}" ] || die "harvest: no log $1 or no phase start" |
| 927 | local ids id odd |
| 928 | ids=$(grep -oE "$VMID_RE" "$1" | sort -u || true) |
| 929 | for id in $ids; do vmrec "$id" "$2" "phase:$3"; done |
| 930 | odd=$(grep -oE 'microvm-[0-9A-Za-z][0-9A-Za-z-]*' "$1" | grep -vxE "$VMID_RE|microvm-image.*" | sort -u | head -n 5 | tr '\n' ' ' || true) |
| 931 | [ -z "$odd" ] || finding "$(basename "$1") names MicroVM-like tokens outside the known ID form: $odd" |
| 932 | } |
| 933 | # ctl_log: the controller log's lines written since the latest start_ctl. |
| 934 | ctl_log() { local n; n=$(cat "$T17/controller.logstart") || die "no controller log start"; tail -n +"$((n + 1))" "$T17/controller.log"; } |
| 935 | # harvest_ctl: save the log lines since the latest start to a slice file (its path in CTL_SLICE), |
| 936 | # then harvest it. |
| 937 | harvest_ctl() { local t; t=$(cat "$T17/controller.start") || die "no controller start time" |
| 938 | CTL_SLICE="$T17/out/controller-$(date -u +%H%M%S).log"; ctl_log > "$CTL_SLICE" || die "controller log unreadable" |
| 939 | harvest "$CTL_SLICE" controller "$t"; } |
| 940 | |
| 941 | # --- the controller: one transient user unit per start, t17b-<RUN>-ctl-<label>.service (R44) --- |
| 942 | # ctl_unit: the unit of the latest start (status 1 if none was started). |
| 943 | ctl_unit() { [ -s "$T17/controller.unit" ] && cat "$T17/controller.unit"; } |
| 944 | # ctl_alive: 0 if the latest controller unit is running; 1 if it is done or none was started; a state |
| 945 | # that cannot be established is a hard stop. A process systemd has not yet reaped still counts as |
| 946 | # running, and once systemd has reaped it the unit is done, so there is no zombie case. |
| 947 | ctl_alive() { local u s; u=$(ctl_unit) || return 1; s=$(unit_state "$u") |
| 948 | case "$s" in running) return 0;; done) return 1;; *) die "controller unit $u: state cannot be established ($s)";; esac; } |
| 949 | # listeners: sets LST to the addresses listening on 18443 or 18444 (empty if none); aborts if ss fails. |
| 950 | listeners() { local o; o=$(ss -ltnH '( sport = :18443 or sport = :18444 )') || die "ss failed"; LST=$(printf '%s\n' "$o" | awk 'NF {print $4}' | sort -u | tr '\n' ' '); } |
| 951 | # start_ctl BINARY LABEL [EQUIPO_HOSTED_X=VALUE...]: start the controller as its own unit (never a |
| 952 | # child of the block that starts it). Its whole environment is the unit's env -i argv: unitctl.sh's |
| 953 | # allowlist, then these explicit defaults (AWS_PROFILE=kass, eu-west-1), then the EQUIPO_HOSTED_ |
| 954 | # settings given (EQUIPO_HOSTED_CRASH_AFTER_LAUNCH only in 7.3), nothing else. Its exit status goes |
| 955 | # to controller.exit (exitpost.sh). |
| 956 | start_ctl() { |
| 957 | local bin=$1 label=$2 u a i ev=(-E AWS_PROFILE=kass -E AWS_REGION=eu-west-1 -E AWS_DEFAULT_REGION=eu-west-1); shift 2 |
| 958 | [ -x "$bin" ] || die "no binary $bin" |
| 959 | ! ctl_alive || die "a controller is already running" |
| 960 | listeners; [ -z "$LST" ] || die "ports 18443 or 18444 are in use: $LST" |
| 961 | u="${UNIT_PREFIX}ctl-$label.service" |
| 962 | [ "$(unit_state "$u")" = done ] || die "unit $u already exists" |
| 963 | for a; do case "$a" in EQUIPO_HOSTED_*=*) ev+=(-E "$a");; *) die "start_ctl: $a is not an EQUIPO_HOSTED_ setting";; esac; done |
| 964 | rm -f "$T17/controller.exit" |
| 965 | [ -f "$T17/controller.log" ] || : > "$T17/controller.log" |
| 966 | wc -l < "$T17/controller.log" > "$T17/controller.logstart" || die "cannot write controller.logstart" |
| 967 | date -u +%FT%T.%3NZ > "$T17/controller.start" || die "cannot write controller.start" |
| 968 | printf '%s\n' "$u" > "$T17/controller.unit" || die "cannot write controller.unit" |
| 969 | jw "CONTROLLER start $label $u $bin $*" |
| 970 | unit_start "$u" "$T17/controller.log" "$T17/controller.exit" "${ev[@]}" -- "$bin" -config "$T17/controller.json" || die "systemd-run could not start $u" |
| 971 | for i in $(seq 1 20); do [ "$(unit_state "$u")" = running ] && break; [ -s "$T17/controller.exit" ] && break; sleep 0.25; done |
| 972 | ctl_alive || die "the controller did not start (see controller.log)" |
| 973 | echo "controller $label started as unit $u" |
| 974 | } |
| 975 | _ctl_ready() { |
| 976 | [ -s "$T17/controller.exit" ] && return 2 |
| 977 | local m; m=$(curl -fsS "http://$METRICS/metrics" 2>/dev/null) || return 1 |
| 978 | printf '%s\n' "$m" | grep -q '^equipo_hosted_network_audit_passing 0$' && return 3 |
| 979 | printf '%s\n' "$m" | grep -q '^equipo_hosted_network_audit_passing 1$' || return 1 |
| 980 | printf '%s\n' "$m" | grep -q '^equipo_hosted_reap_last_age_seconds ' || return 1 |
| 981 | printf '%s\n' "$m" | grep -q '^equipo_hosted_reap_last_error 0$' || return 4 |
| 982 | return 0 |
| 983 | } |
| 984 | # ctl_ready: within 240 s the audit has passed and a reaper pass has finished cleanly (else soft_fail); |
| 985 | # listeners are 127.0.0.1 only (else a hard stop: docs-t1's binding rule). |
| 986 | ctl_ready() { |
| 987 | poll 240 5 "controller ready" _ctl_ready |
| 988 | listeners; [ "$LST" = "127.0.0.1:18443 127.0.0.1:18444 " ] || die "listeners are [$LST], want 127.0.0.1:18443 and :18444 only" |
| 989 | local m; m=$(curl -fsS "http://$METRICS/metrics") || soft_fail "metrics unreadable" |
| 990 | echo "controller ready:"; printf '%s\n' "$m" | grep -E '^equipo_hosted_(network_audit_passing|reap_last_error|reap_last_age_seconds|store_readable) ' || soft_fail "readiness metrics missing" |
| 991 | } |
| 992 | # stop_ctl: stop the latest controller unit (systemd: TERM, KILL after 45 s, reaped) and prove it |
| 993 | # done; its ports must close. |
| 994 | stop_ctl() { |
| 995 | local u s i |
| 996 | if u=$(ctl_unit); then |
| 997 | s=$(unit_state "$u") |
| 998 | if [ "$s" != done ]; then |
| 999 | jw "CONTROLLER stop $u ($s)" |
| 1000 | unit_stop "$u" || die "controller unit $u could not be proved stopped: $(unit_state "$u")" |
| 1001 | fi |
| 1002 | fi |
| 1003 | for i in $(seq 1 10); do [ -s "$T17/controller.exit" ] && break; sleep 1; done |
| 1004 | listeners; [ -z "$LST" ] || die "a listener is still open: $LST" |
| 1005 | jw "CONTROLLER exited $(cat "$T17/controller.exit" 2>/dev/null || echo unknown)" |
| 1006 | echo "controller stopped; exit status $(cat "$T17/controller.exit" 2>/dev/null || echo unknown)" |
| 1007 | } |
| 1008 | metrics() { curl -fsS "http://$METRICS/metrics" | grep -E '^equipo_hosted_' || die "metrics unreadable"; } |
| 1009 | # mread: an observation read of the metrics into MTXT; 1 (and a FINDING) if it fails. |
| 1010 | mread() { MTXT=$(curl -fsS --max-time 10 "http://$METRICS/metrics" 2>/dev/null) && MTXT=$(grep -E '^equipo_hosted_' <<<"$MTXT") && return 0 |
| 1011 | MTXT=""; finding "metrics unreadable"; return 1; } |
| 1012 | # audit_has ATTEMPT ACTION...: with the controller stopped, each ACTION must have an audit row for |
| 1013 | # ATTEMPT; each missing one is a FINDING. The actions are hostedctl's constants. |
| 1014 | audit_has() { local a=$1 x n; shift |
| 1015 | for x; do n=$(dbread "select count(*) from audit where attempt_id='$a' and action='$x'") || { finding "database copy unreadable"; return 0; } |
| 1016 | [ "${n:-0}" -ge 1 ] || finding "no $x audit row for $a"; done; } |
| 1017 | # dbread SQL: read a copy of the stopped controller's database. |
| 1018 | dbread() { |
| 1019 | ! ctl_alive || die "stop the controller before reading its database" |
| 1020 | rm -rf "$T17/dbcopy"; mkdir "$T17/dbcopy"; cp "$T17"/controller.db* "$T17/dbcopy/" |
| 1021 | python3 -I -c 'import sqlite3,sys |
| 1022 | con = sqlite3.connect(sys.argv[1]) |
| 1023 | for r in con.execute(sys.argv[2]): print("\t".join("" if c is None else str(c) for c in r))' "$T17/dbcopy/controller.db" "$1" |
| 1024 | } |
| 1025 | # gotest LOG ARGS...: run go test with output to LOG; record VM IDs it names; return its status. |
| 1026 | gotest() { |
| 1027 | local log=$1 rc had=0 t0; shift; case $- in *e*) had=1;; esac |
| 1028 | t0=$(date -u +%FT%T.%3NZ); jw "PHASE $(basename "$log") start $t0" |
| 1029 | set +e; (cd "$REPO" && CGO_ENABLED=0 go test "$@") > "$log" 2>&1; rc=$?; [ "$had" = 1 ] && set -e |
| 1030 | jw "PHASE $(basename "$log") end rc=$rc" |
| 1031 | harvest "$log" "$(basename "$log")" "$t0" |
| 1032 | grep -E '^(=== RUN|--- (PASS|FAIL|SKIP)|PASS|FAIL|ok|panic)' "$log" | tail -n 40 || true |
| 1033 | return "$rc" |
| 1034 | } |
| 1035 | true |
| 1036 | ENVEOF |
| 1037 | # Reserve the run ID atomically (R45): the leaf mkdir fails if the directory exists, so a run ID |
| 1038 | # another agent of this user holds is never taken; then no unit of it may exist yet. |
| 1039 | mkdir -p "$HOME/.cache/t17b-runs" |
| 1040 | RUN="" |
| 1041 | for _i in 1 2 3 4 5; do |
| 1042 | _r=$(date -u +%m%d)-b$(openssl rand -hex 3) |
| 1043 | if mkdir "$HOME/.cache/t17b-runs/$_r" 2>/dev/null; then RUN=$_r; break; fi |
| 1044 | done |
| 1045 | [ -n "$RUN" ] || { echo "ABORT: could not reserve a run ID under $HOME/.cache/t17b-runs"; exit 1; } |
| 1046 | _u=$(timeout 10 systemctl --user list-units --all --plain --no-legend --full -- "t17b-$RUN-*") || { echo "ABORT: systemctl --user cannot list t17b-$RUN-*"; exit 1; } |
| 1047 | [ -z "$_u" ] || { echo "ABORT: units named t17b-$RUN-* already exist (not this run's; never touched): $_u"; exit 1; } |
| 1048 | NAME=equipo-hosted-dev-t17-$RUN |
| 1049 | cat > "$TMPDIR/equipo-t17b/run.env" <<RUNEOF |
| 1050 | export PIN_SHA='$PIN_SHA' |
| 1051 | export RUN=$RUN NAME=$NAME RUN_RESERVATION=$HOME/.cache/t17b-runs/$RUN |
| 1052 | export OPERATOR_ROLE=$NAME-conn-op BUILD_ROLE=$NAME-build CONN_NAME=$NAME-egress IMAGE_NAME=$NAME |
| 1053 | export BUCKET=$NAME-640012953448 LOG_GROUP=/aws/lambda-microvms/$NAME TOPIC_NAME=$NAME-alerts SG_NAME=$NAME-vm |
| 1054 | export TAGS_EC2="Key=purpose,Value=equipo-hosted-dev Key=run,Value=$RUN" |
| 1055 | RUNEOF |
| 1056 | touch "$TMPDIR/equipo-t17b/ledger.env" "$TMPDIR/equipo-t17b/journal.tsv" "$TMPDIR/equipo-t17b/vms.tsv" |
| 1057 | . "$TMPDIR/equipo-t17b/env.sh" |
| 1058 | unit_probe || die "the systemd user-unit probe (${UNIT_PREFIX}probe.service) failed: detached blocks and the controller could not be tracked (R44); no AWS call has been made" |
| 1059 | [[ "$PIN_SHA" =~ ^[0-9a-f]{40}$ ]] || die "PIN_SHA in run.env is not a full SHA" |
| 1060 | jw "RUN $RUN start pin=$PIN_SHA" |
| 1061 | (cd "$REPO" && CGO_ENABLED=0 go build -tags hostedlive -o "$LIVECTL" ./internal/isolatedjob/awsjob/livectl) |
| 1062 | [ -x "$LIVECTL" ] || die "livectl did not build" |
| 1063 | echo "T17=$T17 RUN=$RUN NAME=$NAME LIVECTL=$LIVECTL" |
| 1064 | ``` |
| 1065 | |
| 1066 | - `PIN_SHA` comes from the file 0.1 wrote after its checks passed; `run.env` carries it for 5.4's |
| 1067 | re-check. livectl is built from the checked-out code, which 0.1 proved is the pinned revision. |
| 1068 | - The run ID is `<mmdd>-b<6 hex>` (the `b` marks Task 17b). Every name below contains it, so every |
| 1069 | name is new to the account; 0.4 still proves each one absent (R39). The base name keeps |
| 1070 | livectl's fixed run prefix `equipo-hosted-dev-t17-<RUN>`. |
| 1071 | - Expected: one line with the scratch path, the run ID and the base name. Record the `T17=` path: |
| 1072 | sandboxed blocks find it through `$TMPDIR`, and the sandbox-off blocks (R37) set it from this line. |
| 1073 | The environment file refuses to load if the directory is not there. |
| 1074 | - Abort if: the scratch directory already exists. |
| 1075 | |
| 1076 | ### 0.3 First AWS call: who am I |
| 1077 | |
| 1078 | ```sh |
| 1079 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1080 | aws sts get-caller-identity --query '[Account,Arn]' --output text |
| 1081 | lvr caller; must |
| 1082 | [ "$(jq -r '"\(.Account) \(.Region)"' <<<"$OUT")" = "640012953448 eu-west-1" ] || die "livectl sees $(jq -c . <<<"$OUT")" |
| 1083 | ``` |
| 1084 | |
| 1085 | - Expected: `640012953448` and an ARN in that account, from the CLI and from livectl. |
| 1086 | - Abort if: anything else. Nothing else runs. |
| 1087 | |
| 1088 | ### 0.4 Observations and collision checks |
| 1089 | |
| 1090 | Every name below contains the random run ID, so a collision is not expected; each check still reads |
| 1091 | the exact name and must get the "does not exist" answer. |
| 1092 | |
| 1093 | ```sh |
| 1094 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1095 | need RUN NAME OPERATOR_ROLE BUILD_ROLE CONN_NAME IMAGE_NAME BUCKET LOG_GROUP TOPIC_NAME |
| 1096 | try aws resourcegroupstaggingapi get-resources --tag-filters Key=purpose,Values=$TAGV --query 'ResourceTagMappingList[].ResourceARN' --output text; must |
| 1097 | echo "observation: resources already tagged purpose=$TAGV (not ours, never touched): [$OUT]" |
| 1098 | try aws ec2 describe-vpcs --filters Name=tag:run,Values=$RUN --query 'Vpcs[].VpcId' --output text; must; [ -z "$OUT" ] || die "a VPC already has run=$RUN" |
| 1099 | for r in "$OPERATOR_ROLE" "$BUILD_ROLE"; do try aws iam get-role --role-name "$r"; expect_err NoSuchEntity; done |
| 1100 | lvr connector get -id "$CONN_NAME"; { [ "$RC" != 0 ] && [ "$ECODE" = ResourceNotFoundException ]; } || die "connector name $CONN_NAME: rc $RC ${ECODE:-} (it exists, or the check could not run)" |
| 1101 | lvr image list -name "$IMAGE_NAME"; must; list_items || die "malformed image list reply (collision check)" |
| 1102 | [ "$(jq --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n)] | length' <<<"$ITEMS")" = 0 ] || die "image name $IMAGE_NAME exists" |
| 1103 | get _v aws s3api list-buckets --prefix "$BUCKET" --query "length(Buckets[?Name=='$BUCKET'])" --output json; [ "$_v" = 0 ] || die "bucket $BUCKET exists in this account" |
| 1104 | try aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text; must; [ -z "$OUT" ] || die "log group exists: $OUT" |
| 1105 | get _v aws sns list-topics --query "length(Topics[?TopicArn=='arn:aws:sns:eu-west-1:$ACCOUNT:$TOPIC_NAME'])" --output json; [ "$_v" = 0 ] || die "topic $TOPIC_NAME exists" |
| 1106 | jw "COLLISION-CHECKS clean"; echo "collision checks clean" |
| 1107 | ``` |
| 1108 | |
| 1109 | - Expected: one observation line; `collision checks clean`. A collision is "anything not in the |
| 1110 | ledger", a hard stop. |
| 1111 | - Abort if: any name exists, or a lookup fails. The image, bucket and topic checks list and match |
| 1112 | the exact name (the CLI reads every page), so they need no error code. A bucket name held by |
| 1113 | another account is not listed here; `create-bucket` in 3.1 then fails before anything is created, |
| 1114 | which is an abort. |
| 1115 | |
| 1116 | --- |
| 1117 | |
| 1118 | ## 1. Network |
| 1119 | |
| 1120 | ### 1.1 VPC, DNS off, and its default resources tagged |
| 1121 | |
| 1122 | ```sh |
| 1123 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1124 | need RUN NAME TAGS_EC2 |
| 1125 | intent vpc "tag:run=$RUN" |
| 1126 | try aws ec2 create-vpc --cidr-block 10.177.0.0/16 \ |
| 1127 | --tag-specifications "ResourceType=vpc,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME}]" --output json; must |
| 1128 | printf '%s\n' "$OUT" > "$T17/out/1.1-vpc.json" |
| 1129 | rec VPC "$(jq -r .Vpc.VpcId "$T17/out/1.1-vpc.json")" |
| 1130 | aws ec2 wait vpc-available --vpc-ids "$VPC" |
| 1131 | aws ec2 modify-vpc-attribute --vpc-id "$VPC" --enable-dns-hostnames '{"Value":false}' |
| 1132 | aws ec2 modify-vpc-attribute --vpc-id "$VPC" --enable-dns-support '{"Value":false}' |
| 1133 | fact_eq "VPC enableDnsSupport" False aws ec2 describe-vpc-attribute --vpc-id "$VPC" --attribute enableDnsSupport --query EnableDnsSupport.Value --output text |
| 1134 | fact_eq "VPC enableDnsHostnames" False aws ec2 describe-vpc-attribute --vpc-id "$VPC" --attribute enableDnsHostnames --query EnableDnsHostnames.Value --output text |
| 1135 | get DEF aws ec2 describe-security-groups --filters Name=vpc-id,Values="$VPC" Name=group-name,Values=default --query 'SecurityGroups[].GroupId' --output text |
| 1136 | [ "$(wc -w <<<"$DEF")" = 1 ] || die "default groups: [$DEF]"; rec DEF_SG "$DEF" |
| 1137 | get DEF aws ec2 describe-route-tables --filters Name=vpc-id,Values="$VPC" Name=association.main,Values=true --query 'RouteTables[].RouteTableId' --output text |
| 1138 | [ "$(wc -w <<<"$DEF")" = 1 ] || die "main route tables: [$DEF]"; rec MAIN_RTB "$DEF" |
| 1139 | get DEF aws ec2 describe-network-acls --filters Name=vpc-id,Values="$VPC" Name=default,Values=true --query 'NetworkAcls[].NetworkAclId' --output text |
| 1140 | [ "$(wc -w <<<"$DEF")" = 1 ] || die "default network ACLs: [$DEF]"; rec DEF_ACL "$DEF" |
| 1141 | get DEF aws ec2 describe-security-group-rules --filters Name=group-id,Values="$DEF_SG" --query 'SecurityGroupRules[].SecurityGroupRuleId' --output text |
| 1142 | [ -n "$DEF" ] || die "the default group has no rules to tag"; rec DEF_SG_RULES "$DEF" |
| 1143 | aws ec2 create-tags --resources "$DEF_SG" "$MAIN_RTB" "$DEF_ACL" $DEF_SG_RULES --tags $TAGS_EC2 |
| 1144 | try aws ec2 describe-tags --filters Name=resource-id,Values="$VPC,$DEF_SG,$MAIN_RTB,$DEF_ACL,$(tr '\t ' ',,' <<<"$DEF_SG_RULES")" Name=key,Values=purpose --query 'length(Tags)' --output json |
| 1145 | if [ "$RC" != 0 ]; then finding "purpose tag read failed: ${ECODE:-rc$RC}" |
| 1146 | elif [ "$OUT" != $(( 4 + $(wc -w <<<"$DEF_SG_RULES") )) ]; then finding "purpose tag read back on $OUT resources"; fi |
| 1147 | echo "VPC $VPC: DNS support and hostnames off; defaults tagged: $DEF_SG $MAIN_RTB $DEF_ACL $DEF_SG_RULES" |
| 1148 | ``` |
| 1149 | |
| 1150 | - Expected: the last line. The defaults go with the VPC in 10.3 and are verified gone in 10.8. |
| 1151 | - Abort if: the create, a default-resource lookup or the tagging fails. A differing or failed |
| 1152 | readback (DNS attributes, tag count) is a FINDING. |
| 1153 | |
| 1154 | ### 1.2 One VM subnet |
| 1155 | |
| 1156 | ```sh |
| 1157 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1158 | need VPC RUN NAME |
| 1159 | intent subnet "tag:run=$RUN" |
| 1160 | try aws ec2 create-subnet --vpc-id "$VPC" --cidr-block 10.177.1.0/24 --availability-zone eu-west-1a \ |
| 1161 | --tag-specifications "ResourceType=subnet,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME-vm}]" --output json; must |
| 1162 | printf '%s\n' "$OUT" > "$T17/out/1.2-subnet.json" |
| 1163 | rec SUBNET "$(jq -r .Subnet.SubnetId "$T17/out/1.2-subnet.json")" |
| 1164 | aws ec2 wait subnet-available --subnet-ids "$SUBNET" |
| 1165 | fact_eq "subnet readback" "$VPC 10.177.1.0/24 eu-west-1a False" aws ec2 describe-subnets --subnet-ids "$SUBNET" --query 'Subnets[0].[VpcId,CidrBlock,AvailabilityZone,MapPublicIpOnLaunch]' --output text |
| 1166 | echo "subnet $SUBNET ok" |
| 1167 | ``` |
| 1168 | |
| 1169 | - Abort if: creation fails (an unsupported zone would be a stop; U10 is settled). A readback that |
| 1170 | differs or fails is a FINDING. |
| 1171 | |
| 1172 | ### 1.3 The subnet's own route table, local route only |
| 1173 | |
| 1174 | ```sh |
| 1175 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1176 | need VPC SUBNET RUN NAME |
| 1177 | intent route-table "tag:run=$RUN" |
| 1178 | try aws ec2 create-route-table --vpc-id "$VPC" \ |
| 1179 | --tag-specifications "ResourceType=route-table,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME-vm}]" --output json; must |
| 1180 | printf '%s\n' "$OUT" > "$T17/out/1.3-rtb.json" |
| 1181 | rec RTB "$(jq -r .RouteTable.RouteTableId "$T17/out/1.3-rtb.json")" |
| 1182 | intent route-table-association "" "$RTB/$SUBNET" |
| 1183 | try aws ec2 associate-route-table --route-table-id "$RTB" --subnet-id "$SUBNET" --query AssociationId --output text; must |
| 1184 | rec RTB_ASSOC "$OUT" |
| 1185 | fact_eq "routes" "10.177.0.0/16 local active" aws ec2 describe-route-tables --route-table-ids "$RTB" --query 'RouteTables[0].Routes[].[DestinationCidrBlock,GatewayId,State]' --output text |
| 1186 | fact_eq "the subnet's route table" "$RTB" aws ec2 describe-route-tables --filters Name=association.subnet-id,Values="$SUBNET" --query 'RouteTables[].RouteTableId' --output text |
| 1187 | echo "route table $RTB: local route only, associated" |
| 1188 | ``` |
| 1189 | |
| 1190 | ### 1.4 Security group with no rules |
| 1191 | |
| 1192 | ```sh |
| 1193 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1194 | need VPC RUN SG_NAME |
| 1195 | intent security-group "$SG_NAME" |
| 1196 | try aws ec2 create-security-group --group-name "$SG_NAME" --description "Task 17 VM group, no rules" --vpc-id "$VPC" \ |
| 1197 | --tag-specifications "ResourceType=security-group,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$SG_NAME}]" --output json; must |
| 1198 | printf '%s\n' "$OUT" > "$T17/out/1.4-sg.json" |
| 1199 | rec SG "$(jq -r .GroupId "$T17/out/1.4-sg.json")" |
| 1200 | aws ec2 describe-security-group-rules --filters Name=group-id,Values="$SG" --output json > "$T17/out/1.4-rules.json" |
| 1201 | jq -e '[.SecurityGroupRules[] | select(.IsEgress)] | length == 1' "$T17/out/1.4-rules.json" >/dev/null || finding "not exactly one default egress rule: $(jq -c . "$T17/out/1.4-rules.json")" |
| 1202 | jq -e '[.SecurityGroupRules[] | select(.IsEgress | not)] | length == 0' "$T17/out/1.4-rules.json" >/dev/null || finding "the new group has inbound rules" |
| 1203 | rules=$(jq -r '.SecurityGroupRules[] | select(.IsEgress) | .SecurityGroupRuleId' "$T17/out/1.4-rules.json") |
| 1204 | [ -z "$rules" ] || [ "$(aws ec2 revoke-security-group-egress --group-id "$SG" --security-group-rule-ids $rules --query Return --output text)" = True ] || die "revoking the default egress rules failed" |
| 1205 | get got aws ec2 describe-security-groups --group-ids "$SG" --query 'SecurityGroups[0].[length(IpPermissions),length(IpPermissionsEgress)]' --output text |
| 1206 | [ "$got" = "0 0" ] || finding "rules left: [$got]" |
| 1207 | fact_eq "VM group rule count" 0 aws ec2 describe-security-group-rules --filters Name=group-id,Values="$SG" --query 'length(SecurityGroupRules)' --output text |
| 1208 | echo "security group $SG: no rules" |
| 1209 | ``` |
| 1210 | |
| 1211 | --- |
| 1212 | |
| 1213 | ## 2. Connector |
| 1214 | |
| 1215 | ### 2.1 The connector's network-interface role |
| 1216 | |
| 1217 | The trust policy is the one AWS documents for the connector operator role (Lambda Web Functions |
| 1218 | networking guide: `lambda.amazonaws.com`, `sts:AssumeRole`), plus `sts:TagSession`, which only lets |
| 1219 | Lambda tag the session it assumes. Attempts 2 and 3 showed a narrow, scoped policy is refused when |
| 1220 | the connector is created, even 3.3 minutes later, while the AWS-managed |
| 1221 | `AWSLambdaNetworkConnectorOperatorPolicy` plus an inline delete was accepted. So, for this |
| 1222 | throwaway dev run (Paul, 2026-11-25 and 2026-11-28), the role gets the managed policy from the |
| 1223 | start, plus an inline `ec2:DeleteNetworkInterface` (the managed policy has none). The delete is |
| 1224 | scoped as narrowly as EC2 allows before the interfaces exist: this account and region, |
| 1225 | network-interface resources only, only interfaces whose `ec2:ManagedResourceOperator` is the |
| 1226 | Lambda connector service, and only interfaces in this run's subnet. The block then waits 120 s |
| 1227 | for IAM propagation, the wait that preceded attempt 3's accepted call. |
| 1228 | |
| 1229 | ```sh |
| 1230 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 1231 | need SUBNET OPERATOR_ROLE RUN |
| 1232 | cat > "$T17/iam/lambda-trust.json" <<'TEOF' |
| 1233 | {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":["sts:AssumeRole","sts:TagSession"]}]} |
| 1234 | TEOF |
| 1235 | A=arn:aws:ec2:eu-west-1:640012953448 |
| 1236 | cat > "$T17/iam/operator-delete.json" <<TEOF |
| 1237 | {"Version":"2012-10-17","Statement":[ |
| 1238 | {"Sid":"DeleteLambdaConnectorEniOnly","Effect":"Allow","Action":"ec2:DeleteNetworkInterface","Resource":"$A:network-interface/*", |
| 1239 | "Condition":{"StringEquals":{"ec2:ManagedResourceOperator":"network-connectors.lambda.amazonaws.com"}, |
| 1240 | "ArnEquals":{"ec2:Subnet":"$A:subnet/$SUBNET"}}}]} |
| 1241 | TEOF |
| 1242 | jq -e . "$T17/iam/operator-delete.json" >/dev/null |
| 1243 | intent iam-role "$OPERATOR_ROLE" |
| 1244 | try aws iam create-role --role-name "$OPERATOR_ROLE" --description "Task 17 connector network interfaces, run $RUN" \ |
| 1245 | --assume-role-policy-document "file://$T17/iam/lambda-trust.json" \ |
| 1246 | --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query Role.Arn --output text; must |
| 1247 | arn_ok "$OUT"; rec OPERATOR_ROLE_ARN "$OUT" |
| 1248 | aws iam attach-role-policy --role-name "$OPERATOR_ROLE" --policy-arn arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy |
| 1249 | rec OPERATOR_MANAGED_POLICY arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy |
| 1250 | aws iam put-role-policy --role-name "$OPERATOR_ROLE" --policy-name t17-connector-eni-delete --policy-document "file://$T17/iam/operator-delete.json" |
| 1251 | rec OPERATOR_INLINE_POLICY t17-connector-eni-delete |
| 1252 | aws iam wait role-exists --role-name "$OPERATOR_ROLE" |
| 1253 | fact_json "operator inline policies" '["t17-connector-eni-delete"]' aws iam list-role-policies --role-name "$OPERATOR_ROLE" --query 'PolicyNames' --output json |
| 1254 | fact_json "operator managed policies" '["AWSLambdaNetworkConnectorOperatorPolicy"]' aws iam list-attached-role-policies --role-name "$OPERATOR_ROLE" --query 'AttachedPolicies[].PolicyName' --output json |
| 1255 | echo "waiting 120 s for IAM propagation before Lambda assumes the operator role"; sleep 120 |
| 1256 | echo "operator role $OPERATOR_ROLE_ARN ready" |
| 1257 | ``` |
| 1258 | |
| 1259 | - Abort if: a create, attach or put call fails (2.2 needs the role). |
| 1260 | - The two readbacks are facts: `fact_json` compares the compacted JSON, and a difference is a |
| 1261 | FINDING. |
| 1262 | |
| 1263 | ### 2.2 Create the VPC_EGRESS connector for MicroVMs (once) |
| 1264 | |
| 1265 | ```sh |
| 1266 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1267 | need SUBNET SG OPERATOR_ROLE_ARN CONN_NAME RUN |
| 1268 | intent connector "$CONN_NAME" "token=$CONN_NAME-1" |
| 1269 | lv connector create -name "$CONN_NAME" -role "$OPERATOR_ROLE_ARN" -subnet "$SUBNET" -sg "$SG" \ |
| 1270 | -client-token "$CONN_NAME-1" -tag purpose=$TAGV -tag run=$RUN |
| 1271 | if [ "$RC" != 0 ]; then |
| 1272 | if [ "$ECODE" = InvalidParameterValueException ] && grep -qF 'invalid ConnectorOperatorRole permissions' <<<"$LV_MSG"; then |
| 1273 | msg=$LV_MSG |
| 1274 | lvr connector get -id "$CONN_NAME" |
| 1275 | if [ "$RC" != 0 ] && [ "$ECODE" = ResourceNotFoundException ]; then jw "NOTCREATED connector attempt 1"; fi |
| 1276 | die "the connector was refused with the managed operator policy ($msg); 2.3 onwards needs it" |
| 1277 | fi |
| 1278 | die "connector create: rc $RC ${ECODE:-} ${LV_MSG:-$ERR} (uncertain: S.2 reconciles it)" |
| 1279 | fi |
| 1280 | printf '%s\n' "$OUT" > "$T17/out/2.2-connector.json" |
| 1281 | arn_ok "$(jq -r .Arn "$T17/out/2.2-connector.json")" |
| 1282 | rec CONN_ARN "$(jq -r .Arn "$T17/out/2.2-connector.json")"; rec CONN_ID "$(jq -r .Id "$T17/out/2.2-connector.json")" |
| 1283 | [ "$CONN_ARN" = "arn:aws:lambda:eu-west-1:$ACCOUNT:network-connector:$CONN_ID" ] || die "connector ARN has an unexpected form: $CONN_ARN" |
| 1284 | rec CONN_OPERATOR_POLICY "managed AWSLambdaNetworkConnectorOperatorPolicy plus inline delete" |
| 1285 | jw "FACT connector create reply: $(jq -c '{State,Version,VersionArn,LatestVersion,LatestVersionArn}' "$T17/out/2.2-connector.json")" |
| 1286 | jq -c '{Arn,Id,State,Version,VersionArn}' "$T17/out/2.2-connector.json" |
| 1287 | ``` |
| 1288 | |
| 1289 | - Expected: state `PENDING`. livectl sends no `ElasticIpConfiguration`, so the connector gets none; |
| 1290 | 2.4 and 5.6 confirm it. |
| 1291 | - Abort if: the create fails. A refusal leaves no connector (attempt 2's evidence); anything else |
| 1292 | is uncertain and S.2 reconciles it by name. |
| 1293 | |
| 1294 | ### 2.3 Wait for ACTIVE (spike, attempts 3 and 4: about 4.3 to 4.5 min; bound 15 min) |
| 1295 | |
| 1296 | ```sh |
| 1297 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 1298 | need CONN_ARN |
| 1299 | lv_wait 900 connector wait-active -id "$CONN_ARN" -interval 15s |
| 1300 | printf '%s\n' "$OUT" > "$T17/out/2.3-active.json" |
| 1301 | jq -c '{State,StateReason,StateReasonCode}' "$T17/out/2.3-active.json" 2>/dev/null || true |
| 1302 | [ "$RC" = 0 ] || die "connector not ACTIVE (rc $RC, ${ECODE:-no code}); 2.4 onwards needs it" |
| 1303 | jw "TIMING connector-active" |
| 1304 | ``` |
| 1305 | |
| 1306 | - Abort if: a failed state (exit 6, the reply shows `StateReason`) or the bound runs out (exit 5). |
| 1307 | |
| 1308 | ### 2.4 The version-1 qualified ARN, facts about versions, and the interfaces |
| 1309 | |
| 1310 | A new connector starts at version 1 (pinned SDK, `CreateNetworkConnector`). Attempt 3's discovery |
| 1311 | read `<arn>:1` and got `Version` 1, ACTIVE; the unqualified read carries only `LatestVersion` and |
| 1312 | `LatestVersionArn`. The launches and the 5.6 audit need the qualified ARN, so that read is a |
| 1313 | requirement; the rest are facts. |
| 1314 | |
| 1315 | ```sh |
| 1316 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1317 | need CONN_ARN CONN_ID SUBNET SG VPC |
| 1318 | lvr connector get -id "$CONN_ARN:1"; must |
| 1319 | printf '%s\n' "$OUT" > "$T17/out/2.4-qualified.json" |
| 1320 | jq -e --arg q "$CONN_ARN:1" --arg s "$SUBNET" --arg g "$SG" '.Version == 1 and .VersionArn == $q and .State == "ACTIVE" |
| 1321 | and .Configuration.Value.SubnetIds == [$s] and .Configuration.Value.SecurityGroupIds == [$g] |
| 1322 | and .Configuration.Value.AssociatedComputeResourceTypes == ["MicroVm"]' "$T17/out/2.4-qualified.json" >/dev/null \ |
| 1323 | || die "the version-1 read does not show this run's ACTIVE connector: $(jq -c '{Version,VersionArn,State,Configuration}' "$T17/out/2.4-qualified.json")" |
| 1324 | rec CONN_VERSION 1; rec CONN_QARN "$CONN_ARN:1" |
| 1325 | fact_lv "connector Elastic IP configuration" "null" '.Configuration.Value.ElasticIpConfiguration' connector get -id "$CONN_QARN" |
| 1326 | lvr connector get -id "$CONN_ARN" |
| 1327 | if [ "$RC" = 0 ]; then |
| 1328 | jw "FACT unqualified read: $(jq -c '{Version,VersionArn,LatestVersion,LatestVersionArn,ServerTime:.ResultMetadata.ServerTime}' <<<"$OUT")" |
| 1329 | [ "$(jq -r .LatestVersionArn <<<"$OUT")" = "$CONN_QARN" ] || finding "unqualified read: LatestVersionArn is $(jq -r .LatestVersionArn <<<"$OUT"), not $CONN_QARN" |
| 1330 | else finding "unqualified connector read failed: ${ECODE:-rc$RC}"; fi |
| 1331 | lvr connector list-versions -id "$CONN_ARN" |
| 1332 | if [ "$RC" = 0 ] && list_items; then jw "FACT connector versions: $(jq -c '[.[] | {Version,VersionArn,State}]' <<<"$ITEMS")" |
| 1333 | elif [ "$RC" = 0 ]; then finding "connector version list reply is malformed" |
| 1334 | else finding "connector version list failed: ${ECODE:-rc$RC}"; fi |
| 1335 | eni_snapshot soft "2.4, connector ACTIVE" |
| 1336 | echo "qualified connector ARN: $CONN_QARN" |
| 1337 | ``` |
| 1338 | |
| 1339 | - Expected: the version-1 read is this run's ACTIVE connector, in this subnet with this group. No |
| 1340 | Elastic IP configuration. Attempt 3 saw no interfaces while ACTIVE, which is recorded as a fact. |
| 1341 | Interfaces Lambda creates later are recorded by ID by `eni_snapshot` in 6.1, 7.2 and 8.1 (while |
| 1342 | VMs run) and in 10.2 just before the connector is deleted; 10.2 then proves each recorded ID gone. |
| 1343 | Attempt 4 saw none in the run's VPC at any snapshot, VMs running included. An interface outside |
| 1344 | this run's subnet is a hard stop. |
| 1345 | - Abort if: the version-1 read fails or shows another connector; everything after needs it. |
| 1346 | |
| 1347 | --- |
| 1348 | |
| 1349 | ## 3. Image |
| 1350 | |
| 1351 | The API builds an image from a zip in S3 holding a `Dockerfile` and its files, on a Lambda-managed |
| 1352 | base image, with a build role that can read the zip and write build logs. Memory, x86_64 and the |
| 1353 | `ALL` capability are set per image version. This run builds only the Small version (2048 MiB): the |
| 1354 | adapter needs at least one version per image, and every VM in sections 6, 7 and 8 is Small. The |
| 1355 | image is a static Go binary that answers 200 on every hook path on port 9000 inside the VM; the run |
| 1356 | hook must answer, because the adapter always sends a run hook payload. Attempt 4 built this exact |
| 1357 | image from base version 4 in about 1.8 minutes. |
| 1358 | |
| 1359 | ### 3.1 S3 bucket |
| 1360 | |
| 1361 | ```sh |
| 1362 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1363 | need BUCKET RUN |
| 1364 | intent s3-bucket "$BUCKET" |
| 1365 | try aws s3api create-bucket --bucket "$BUCKET" --create-bucket-configuration LocationConstraint=eu-west-1 --output json; must |
| 1366 | rec BUCKET_CREATED "$BUCKET" |
| 1367 | aws s3api put-public-access-block --bucket "$BUCKET" --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true |
| 1368 | aws s3api put-bucket-tagging --bucket "$BUCKET" --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]" |
| 1369 | fact_eq "bucket run tag" "$RUN" aws s3api get-bucket-tagging --bucket "$BUCKET" --query "TagSet[?Key=='run'].Value" --output text |
| 1370 | echo "bucket $BUCKET ok" |
| 1371 | ``` |
| 1372 | |
| 1373 | ### 3.2 Log group for the build |
| 1374 | |
| 1375 | ```sh |
| 1376 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1377 | need LOG_GROUP RUN |
| 1378 | intent log-group "$LOG_GROUP" |
| 1379 | try aws logs create-log-group --log-group-name "$LOG_GROUP" --tags purpose=$TAGV,run=$RUN; must |
| 1380 | rec LOG_GROUP_CREATED "$LOG_GROUP" |
| 1381 | aws logs put-retention-policy --log-group-name "$LOG_GROUP" --retention-in-days 1 |
| 1382 | fact_eq "log group and retention" "$LOG_GROUP 1" aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].[logGroupName,retentionInDays]' --output text |
| 1383 | ``` |
| 1384 | |
| 1385 | ### 3.3 Build role (least privilege) |
| 1386 | |
| 1387 | Same trust policy as 2.1. The current getting-started page prints `sts:AssumeRole` only; Astra's |
| 1388 | review cites a version with `sts:TagSession`. Granting both satisfies either. Permissions are the |
| 1389 | guide's, narrowed to the one S3 key and the one log group. It is a build role only: no VM ever gets |
| 1390 | an execution role (spec §3, §15). |
| 1391 | |
| 1392 | ```sh |
| 1393 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1394 | need BUILD_ROLE BUCKET LOG_GROUP RUN |
| 1395 | L="arn:aws:logs:eu-west-1:640012953448:log-group:$LOG_GROUP" |
| 1396 | cat > "$T17/iam/build.json" <<EOF |
| 1397 | {"Version":"2012-10-17","Statement":[ |
| 1398 | {"Sid":"ReadTheCodeArtifact","Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::$BUCKET/t17/app.zip"}, |
| 1399 | {"Sid":"WriteBuildLogsToThisGroup","Effect":"Allow","Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource":["$L","$L:*"]}]} |
| 1400 | EOF |
| 1401 | jq -e . "$T17/iam/build.json" >/dev/null |
| 1402 | intent iam-role "$BUILD_ROLE" |
| 1403 | try aws iam create-role --role-name "$BUILD_ROLE" --description "Task 17 MicroVM image build, run $RUN" \ |
| 1404 | --assume-role-policy-document "file://$T17/iam/lambda-trust.json" \ |
| 1405 | --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query Role.Arn --output text; must |
| 1406 | arn_ok "$OUT"; rec BUILD_ROLE_ARN "$OUT" |
| 1407 | aws iam put-role-policy --role-name "$BUILD_ROLE" --policy-name t17-build --policy-document "file://$T17/iam/build.json" |
| 1408 | aws iam wait role-exists --role-name "$BUILD_ROLE" |
| 1409 | fact_eq "build role inline policy" t17-build aws iam list-role-policies --role-name "$BUILD_ROLE" --query 'PolicyNames' --output text |
| 1410 | echo "waiting 60 s for IAM propagation before Lambda assumes the build role"; sleep 60 |
| 1411 | ``` |
| 1412 | |
| 1413 | ### 3.4 Hook binary, Dockerfile, hooks and zip (no AWS call) |
| 1414 | |
| 1415 | ```sh |
| 1416 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh" |
| 1417 | cd "$T17/image" |
| 1418 | cat > hookd.go <<'EOF' |
| 1419 | // hookd answers every Lambda MicroVM lifecycle hook with 200. Task 17 only. |
| 1420 | package main |
| 1421 | |
| 1422 | import ( |
| 1423 | "io" |
| 1424 | "log" |
| 1425 | "net/http" |
| 1426 | ) |
| 1427 | |
| 1428 | func main() { |
| 1429 | http.HandleFunc("/aws/lambda-microvms/runtime/v1/", func(w http.ResponseWriter, r *http.Request) { |
| 1430 | n, _ := io.Copy(io.Discard, r.Body) |
| 1431 | log.Printf("hook %s %d bytes", r.URL.Path, n) |
| 1432 | w.WriteHeader(http.StatusOK) |
| 1433 | }) |
| 1434 | log.Fatal(http.ListenAndServe(":9000", nil)) |
| 1435 | } |
| 1436 | EOF |
| 1437 | cat > Dockerfile <<'EOF' |
| 1438 | FROM public.ecr.aws/lambda/microvms:al2023-minimal |
| 1439 | COPY hookd /usr/local/bin/hookd |
| 1440 | CMD ["/usr/local/bin/hookd"] |
| 1441 | EOF |
| 1442 | cat > hooks.json <<'EOF' |
| 1443 | {"port":9000, |
| 1444 | "microvmHooks":{"run":"ENABLED","runTimeoutInSeconds":10,"resume":"ENABLED","resumeTimeoutInSeconds":10, |
| 1445 | "suspend":"ENABLED","suspendTimeoutInSeconds":10,"terminate":"ENABLED","terminateTimeoutInSeconds":10}, |
| 1446 | "microvmImageHooks":{"ready":"ENABLED","readyTimeoutInSeconds":120,"validate":"DISABLED"}} |
| 1447 | EOF |
| 1448 | jq -e . hooks.json >/dev/null |
| 1449 | CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags=-s -o hookd hookd.go |
| 1450 | chmod 0755 hookd |
| 1451 | [ "$(head -c 4 hookd | od -An -c | tr -d ' ')" = '177ELF' ] || die "hookd is not an ELF binary" |
| 1452 | python3 -I -m zipfile -c app.zip Dockerfile hookd |
| 1453 | [ "$(python3 -I -c 'import zipfile;print(" ".join(sorted(zipfile.ZipFile("app.zip").namelist())))')" = "Dockerfile hookd" ] || die "zip contents differ" |
| 1454 | sha256sum app.zip |
| 1455 | ``` |
| 1456 | |
| 1457 | ### 3.5 Digest, and the upload that proves it (object tagged) |
| 1458 | |
| 1459 | AWS has no content digest for a MicroVM image, so the controller's allowlist key (`sha256:` and 64 |
| 1460 | lower-case hex digits) is the SHA-256 of the exact zip the image is built from. S3 rejects the |
| 1461 | upload if the bytes do not match the checksum sent; the read-back shows S3 holds that checksum; |
| 1462 | 3.8 shows each version names this object. |
| 1463 | |
| 1464 | ```sh |
| 1465 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1466 | need BUCKET RUN |
| 1467 | cd "$T17/image" |
| 1468 | rec DIGEST "sha256:$(sha256sum app.zip | cut -d' ' -f1)" |
| 1469 | B64=$(openssl dgst -sha256 -binary app.zip | base64) |
| 1470 | rec ARTIFACT_B64 "$B64" |
| 1471 | intent s3-object "s3://$BUCKET/t17/app.zip" |
| 1472 | try aws s3api put-object --bucket "$BUCKET" --key t17/app.zip --body app.zip --checksum-algorithm SHA256 \ |
| 1473 | --checksum-sha256 "$B64" --tagging "purpose=$TAGV&run=$RUN" --query ChecksumSHA256 --output text; must |
| 1474 | [ "$OUT" = "$B64" ] || finding "put-object checksum [$OUT]" |
| 1475 | rec ARTIFACT "s3://$BUCKET/t17/app.zip" |
| 1476 | fact_eq "S3 object checksum" "$B64" aws s3api head-object --bucket "$BUCKET" --key t17/app.zip --checksum-mode ENABLED --query ChecksumSHA256 --output text |
| 1477 | fact_eq "S3 object run tag" "$RUN" aws s3api get-object-tagging --bucket "$BUCKET" --key t17/app.zip --query "TagSet[?Key=='run'].Value" --output text |
| 1478 | echo "artifact $ARTIFACT digest $DIGEST" |
| 1479 | ``` |
| 1480 | |
| 1481 | ### 3.6 Managed base image and version |
| 1482 | |
| 1483 | livectl reads each base version's `Status` and `SupportedCpuConfigurations` (the CLI dropped them). |
| 1484 | The block picks the newest `AVAILABLE` version that supports x86_64, and records the next one down |
| 1485 | for the pre-approved step down in 3.7 and 3.8. |
| 1486 | |
| 1487 | ```sh |
| 1488 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1489 | lvr image base-versions; must |
| 1490 | printf '%s\n' "$OUT" > "$T17/out/3.6-base.json" |
| 1491 | list_items || die "malformed base version list reply; the image needs a base version" |
| 1492 | jq -r '.[] | [.ImageVersion, .Status, ([.SupportedCpuConfigurations[]?.Architecture] | join(","))] | @tsv' <<<"$ITEMS" |
| 1493 | rec BASE_ARN "$(jq -r '.BaseImage' "$T17/out/3.6-base.json")" |
| 1494 | [ "$BASE_ARN" = arn:aws:lambda:eu-west-1:aws:microvm-image:al2023-1 ] || finding "base image ARN is $BASE_ARN" |
| 1495 | vs=$(jq -r '[.[] | select(.Status == "AVAILABLE" and any(.SupportedCpuConfigurations[]?; .Architecture == "X86_64"))] | .[0:2][] | .ImageVersion' <<<"$ITEMS") |
| 1496 | v1=$(sed -n 1p <<<"$vs"); v2=$(sed -n 2p <<<"$vs") |
| 1497 | [ -n "$v1" ] || die "no AVAILABLE base version supports x86_64; the image needs one" |
| 1498 | rec BASE_VER "$v1" |
| 1499 | if [ -n "$v2" ]; then rec BASE_VER_DOWN "$v2"; else finding "only one AVAILABLE x86_64 base version ($v1): no step down available"; fi |
| 1500 | ``` |
| 1501 | |
| 1502 | - Expected: the newest `AVAILABLE` x86_64 version, and one below it. |
| 1503 | - Abort if: the list fails, or no version is both `AVAILABLE` and x86_64. |
| 1504 | |
| 1505 | ### 3.7 Create the image: Small version |
| 1506 | |
| 1507 | Two pre-approved retries, each at most once: |
| 1508 | |
| 1509 | - **A refusal about the build role**, which was created in 3.3, gets the propagation treatment: |
| 1510 | confirm no image exists, wait 120 s, retry with the same base version. It counts only if the |
| 1511 | code is `ValidationException`, `AccessDeniedException` or `InvalidParameterValueException`; the |
| 1512 | service's message names the build role (its name or ARN) or Lambda assuming it ("build role", |
| 1513 | "assume role"); and it is not a denial of the caller ("is not authorized to perform"). |
| 1514 | - **Any other refusal that leaves no image** steps down once to `BASE_VER_DOWN` (Paul, |
| 1515 | 2026-11-28). |
| 1516 | |
| 1517 | Anything else, or a third refusal, is a stop: the image is needed. |
| 1518 | |
| 1519 | ```sh |
| 1520 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1521 | need IMAGE_NAME ARTIFACT BASE_ARN BASE_VER BUILD_ROLE_ARN BUILD_ROLE LOG_GROUP RUN |
| 1522 | # create_image BASEVERSION N: one attempt with client token $IMAGE_NAME-create-N. IMG_RC=0 created; |
| 1523 | # 1 a build-role refusal; 2 another refusal; both with no image left. Anything uncertain aborts. |
| 1524 | create_image() { |
| 1525 | intent microvm-image "$IMAGE_NAME" "token=$IMAGE_NAME-create-$2" "base=$1" |
| 1526 | lv image create -name "$IMAGE_NAME" -description "Task 17 minimal hook image, small, run $RUN" \ |
| 1527 | -artifact "$ARTIFACT" -base "$BASE_ARN" -base-version "$1" -build-role "$BUILD_ROLE_ARN" \ |
| 1528 | -hooks "$T17/image/hooks.json" -log-group "$LOG_GROUP" -memory 2048 \ |
| 1529 | -client-token "$IMAGE_NAME-create-$2" -tag purpose=$TAGV -tag run=$RUN |
| 1530 | if [ "$RC" = 0 ]; then IMG_RC=0; return 0; fi |
| 1531 | [ "$LV_KIND" = api ] || die "image create attempt $2: ${LV_KIND:-rc$RC} (no answer: S.2 reconciles it)" |
| 1532 | IMG_CODE=$ECODE; IMG_MSG=$LV_MSG |
| 1533 | jw "REFUSED image attempt $2 (base $1): ${IMG_CODE} ${IMG_MSG}" |
| 1534 | lvr image list -name "$IMAGE_NAME"; must; list_items || die "malformed image list reply after a refused create" |
| 1535 | [ "$(jq --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n)] | length' <<<"$ITEMS")" = 0 ] || die "a refused create left an image named $IMAGE_NAME" |
| 1536 | jw "NOTCREATED image attempt $2" |
| 1537 | case "$IMG_CODE" in ValidationException|AccessDeniedException|InvalidParameterValueException) role_code=yes;; *) role_code=no;; esac |
| 1538 | if [ "$role_code" = yes ] \ |
| 1539 | && { grep -qF -e "$BUILD_ROLE_ARN" -e "$BUILD_ROLE" <<<"$IMG_MSG" || grep -qiE 'build role|assume (the )?(build )?role' <<<"$IMG_MSG"; } \ |
| 1540 | && ! grep -qi 'is not authorized to perform' <<<"$IMG_MSG"; then IMG_RC=1; else IMG_RC=2; fi |
| 1541 | } |
| 1542 | ver=$BASE_VER; n=1; waited=no; stepped=no |
| 1543 | while :; do |
| 1544 | create_image "$ver" "$n" |
| 1545 | [ "$IMG_RC" = 0 ] && break |
| 1546 | if [ "$IMG_RC" = 1 ] && [ "$waited" = no ]; then waited=yes; echo "build-role refusal: waiting 120 s, then the same version"; sleep 120 |
| 1547 | elif [ "$IMG_RC" = 2 ] && [ "$stepped" = no ] && [ -n "${BASE_VER_DOWN:-}" ]; then |
| 1548 | stepped=yes; finding "image create from base $ver refused (${IMG_CODE}: ${IMG_MSG}); stepping down to $BASE_VER_DOWN"; ver=$BASE_VER_DOWN |
| 1549 | else die "image create refused (attempt $n, ${IMG_CODE}: ${IMG_MSG}); no pre-approved retry is left"; fi |
| 1550 | n=$((n + 1)) |
| 1551 | done |
| 1552 | printf '%s\n' "$OUT" > "$T17/out/3.7-image.json" |
| 1553 | arn_ok "$(jq -r .ImageArn "$T17/out/3.7-image.json")" |
| 1554 | rec IMAGE_ARN "$(jq -r .ImageArn "$T17/out/3.7-image.json")"; rec VER_SMALL "$(jq -r .ImageVersion "$T17/out/3.7-image.json")" |
| 1555 | rec BASE_VER_USED "$ver"; [ "$stepped" = no ] || rec BASE_STEPPED_DOWN yes |
| 1556 | [ "$IMAGE_ARN" = "arn:aws:lambda:eu-west-1:$ACCOUNT:microvm-image:$IMAGE_NAME" ] || die "image ARN [$IMAGE_ARN]" |
| 1557 | ``` |
| 1558 | |
| 1559 | - livectl always sends x86_64 and the `ALL` capability, and no egress connectors, so the build pulls |
| 1560 | its container base image over the default build path; running VMs get only the connector. |
| 1561 | |
| 1562 | ### 3.8 Wait for the Small version and check it (bound 50 min with the step down) |
| 1563 | |
| 1564 | If the Small build fails and 3.7 has not stepped down, the block builds a new Small version from |
| 1565 | `BASE_VER_DOWN` by one update (pre-approved, once), and waits again. |
| 1566 | |
| 1567 | ```sh |
| 1568 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 1569 | need IMAGE_ARN IMAGE_NAME VER_SMALL ARTIFACT BASE_ARN BUILD_ROLE_ARN LOG_GROUP RUN |
| 1570 | lv_wait 1200 image wait-version -id "$IMAGE_ARN" -version "$VER_SMALL" -interval 15s |
| 1571 | if [ "$RC" = 6 ] && [ -z "${BASE_STEPPED_DOWN:-}" ] && [ -n "${BASE_VER_DOWN:-}" ]; then |
| 1572 | finding "Small version $VER_SMALL failed to build from base ${BASE_VER_USED}: $(jq -r '.StateReason // empty' <<<"$OUT"); stepping down to $BASE_VER_DOWN" |
| 1573 | try aws logs filter-log-events --log-group-name "$LOG_GROUP" --limit 50 --query 'events[].message' --output text; [ "$RC" = 0 ] && printf '%s\n' "$OUT" | tail -n 20 |
| 1574 | rec VER_SMALL_FAILED "$VER_SMALL" |
| 1575 | intent microvm-image-version "$IMAGE_NAME" "token=$IMAGE_NAME-update-small-2" "base=$BASE_VER_DOWN" |
| 1576 | lv image update -id "$IMAGE_ARN" -description "Task 17 minimal hook image, small, run $RUN, base $BASE_VER_DOWN" \ |
| 1577 | -artifact "$ARTIFACT" -base "$BASE_ARN" -base-version "$BASE_VER_DOWN" -build-role "$BUILD_ROLE_ARN" \ |
| 1578 | -hooks "$T17/image/hooks.json" -log-group "$LOG_GROUP" -memory 2048 -client-token "$IMAGE_NAME-update-small-2"; must |
| 1579 | rec VER_SMALL "$(jq -r .ImageVersion <<<"$OUT")"; rec BASE_VER_USED "$BASE_VER_DOWN"; rec BASE_STEPPED_DOWN yes |
| 1580 | lv_wait 1200 image wait-version -id "$IMAGE_ARN" -version "$VER_SMALL" -interval 15s |
| 1581 | fi |
| 1582 | if [ "$RC" != 0 ]; then |
| 1583 | try aws logs filter-log-events --log-group-name "$LOG_GROUP" --limit 50 --query 'events[].message' --output text; [ "$RC" = 0 ] && printf '%s\n' "$OUT" | tail -n 20 |
| 1584 | die "the Small version did not build; the image is needed" |
| 1585 | fi |
| 1586 | lvr image get-version -id "$IMAGE_ARN" -version "$VER_SMALL" |
| 1587 | if [ "$RC" = 0 ]; then |
| 1588 | printf '%s\n' "$OUT" > "$T17/out/3.8-small.json" |
| 1589 | jq -e --arg a "$ARTIFACT" '([.CpuConfigurations[].Architecture] == ["X86_64"]) and ([.Resources[].MinimumMemoryInMiB] == [2048]) |
| 1590 | and (.AdditionalOsCapabilities == ["ALL"]) and (.CodeArtifact.Value == $a) and (.Hooks.Port == 9000)' "$T17/out/3.8-small.json" >/dev/null \ |
| 1591 | || finding "the Small version differs from what the adapter checks: $(jq -c '{CpuConfigurations,Resources,AdditionalOsCapabilities,CodeArtifact,Hooks}' "$T17/out/3.8-small.json")" |
| 1592 | jw "FACT Small version: $(jq -c '{ImageVersion,State,Status,Tags}' "$T17/out/3.8-small.json")" |
| 1593 | else finding "Small version read failed: ${ECODE:-rc$RC}"; fi |
| 1594 | lvr image get -id "$IMAGE_ARN" |
| 1595 | if [ "$RC" = 0 ]; then |
| 1596 | case "$(jq -r .State <<<"$OUT")" in CREATED|UPDATED) ;; *) finding "image state $(jq -r .State <<<"$OUT")";; esac |
| 1597 | [ "$(jq -r '.Tags.run // empty' <<<"$OUT")" = "$RUN" ] || finding "image tags: $(jq -c .Tags <<<"$OUT")" |
| 1598 | else finding "image read failed: ${ECODE:-rc$RC}"; fi |
| 1599 | jw "TIMING image-small-built" |
| 1600 | ``` |
| 1601 | |
| 1602 | - Expected: `SUCCESSFUL ACTIVE`; the fields the adapter's image check reads (`checkImageVersion`) |
| 1603 | match, or each difference is a FINDING (the adapter then refuses the version, and the contract |
| 1604 | shows it). |
| 1605 | - Abort if: no Small version builds, after the one step down. |
| 1606 | - There is no Large version in this run (revision 5's 3.9 is gone). |
| 1607 | |
| 1608 | --- |
| 1609 | |
| 1610 | ## 4. SNS topic |
| 1611 | |
| 1612 | The controller refuses a config without `sns_topic_arn` (`cmd/equipo-hosted-controller/config.go:122-127`) |
| 1613 | and wires its alerter to it (`main.go:104`). It stops at a startup alert it cannot deliver |
| 1614 | (`internal/hostedctl/controller.go:105`), but startup alerts are queued only after a wall-clock |
| 1615 | rollback (`store.go:226-235`), so a clean start publishes nothing. The first publish this run |
| 1616 | expects is 8.2's `orphan_stopped` alert, counted by the controller as sent or failed. The topic |
| 1617 | exists from here to 10.7. |
| 1618 | |
| 1619 | ```sh |
| 1620 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 1621 | need TOPIC_NAME RUN |
| 1622 | intent sns-topic "$TOPIC_NAME" |
| 1623 | try aws sns create-topic --name "$TOPIC_NAME" --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query TopicArn --output text; must |
| 1624 | [ "$OUT" = "arn:aws:sns:eu-west-1:$ACCOUNT:$TOPIC_NAME" ] || die "topic ARN [$OUT]" |
| 1625 | rec TOPIC_ARN "$OUT" |
| 1626 | fact_eq "topic run tag" "$RUN" aws sns list-tags-for-resource --resource-arn "$TOPIC_ARN" --query "Tags[?Key=='run'].Value" --output text |
| 1627 | fact_eq "topic subscription count" 0 aws sns list-subscriptions-by-topic --topic-arn "$TOPIC_ARN" --query 'length(Subscriptions)' --output text |
| 1628 | ``` |
| 1629 | |
| 1630 | - 0.4 proved the name did not exist, so `create-topic`'s idempotent return cannot be someone else's |
| 1631 | topic. No subscription is made: alerts are read from the controller's metrics and database. |
| 1632 | |
| 1633 | --- |
| 1634 | |
| 1635 | ## 5. Keys, config, builds, and the audit before any launch |
| 1636 | |
| 1637 | ### 5.1 Keys and the self-signed certificate (pre-flight helper, no AWS call) |
| 1638 | |
| 1639 | ```sh |
| 1640 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh" |
| 1641 | cd "$REPO" && EQUIPO_HOSTED_KEYGEN_DIR="$T17/keys" CGO_ENABLED=0 go test -tags hostedlive ./cmd/equipo-hosted-controller -run 'TestLiveKeygen$' -count=1 -v |
| 1642 | for f in controller.key instance.key operator.key tls.key; do [ "$(stat -c %a "$T17/keys/$f")" = 600 ] || die "$f is not mode 600"; done |
| 1643 | for f in controller.pub verify_keys.json tls.crt; do [ -s "$T17/keys/$f" ] || die "$f missing"; done |
| 1644 | openssl x509 -in "$T17/keys/tls.crt" -noout -ext subjectAltName | grep -q 'IP Address:127.0.0.1' || die "certificate SAN is not 127.0.0.1" |
| 1645 | jq -r '.[] | [.id, .role] | @tsv' "$T17/keys/verify_keys.json" |
| 1646 | ``` |
| 1647 | |
| 1648 | - Expected: `task17-instance instance` and `task17-operator operator`. |
| 1649 | |
| 1650 | ### 5.2 Ports free |
| 1651 | |
| 1652 | ```sh |
| 1653 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh" |
| 1654 | listeners; [ -z "$LST" ] || die "in use: $LST"; echo "ports 18443 and 18444 free" |
| 1655 | ``` |
| 1656 | |
| 1657 | ### 5.3 Controller config and live contract config |
| 1658 | |
| 1659 | ```sh |
| 1660 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh" |
| 1661 | need DIGEST IMAGE_ARN VER_SMALL VPC SUBNET SG CONN_QARN TOPIC_ARN |
| 1662 | jq -n --slurpfile vk "$T17/keys/verify_keys.json" --arg api "$API" --arg met "$METRICS" --arg d "$T17" \ |
| 1663 | --arg digest "$DIGEST" --arg arn "$IMAGE_ARN" --arg small "$VER_SMALL" \ |
| 1664 | --arg vpc "$VPC" --arg subnet "$SUBNET" --arg sg "$SG" --arg conn "$CONN_QARN" --arg topic "$TOPIC_ARN" '{ |
| 1665 | listen: $api, metrics_listen: $met, |
| 1666 | tls_cert_file: ($d + "/keys/tls.crt"), tls_key_file: ($d + "/keys/tls.key"), |
| 1667 | database: ($d + "/controller.db"), signing_key_file: ($d + "/keys/controller.key"), |
| 1668 | verify_keys: $vk[0], |
| 1669 | images: [{digest: $digest, arn: $arn, versions: {small: $small}}], |
| 1670 | region: "eu-west-1", vpc_id: $vpc, vm_subnet_id: $subnet, vm_security_group_id: $sg, |
| 1671 | connector_arn: $conn, egress: [], sns_topic_arn: $topic}' > "$T17/controller.json" |
| 1672 | jq -n --arg digest "$DIGEST" --arg arn "$IMAGE_ARN" --arg small "$VER_SMALL" \ |
| 1673 | --arg vpc "$VPC" --arg subnet "$SUBNET" --arg sg "$SG" --arg conn "$CONN_QARN" '{ |
| 1674 | region: "eu-west-1", connector_id: $conn, vpc_id: $vpc, vm_subnet_id: $subnet, vm_security_group_id: $sg, |
| 1675 | image: $digest, image_arn: $arn, versions: {small: $small}, egress: []}' > "$T17/live.json" |
| 1676 | jq -e '[.. | strings] | all(. != "" and . != "null")' "$T17/controller.json" "$T17/live.json" >/dev/null || die "an empty value in a config" |
| 1677 | jq -e '.egress == []' "$T17/controller.json" "$T17/live.json" >/dev/null || die "egress is not empty (R30)" |
| 1678 | cat "$T17/controller.json" "$T17/live.json" |
| 1679 | ``` |
| 1680 | |
| 1681 | Filled in, `controller.json` reads (angle brackets are ledger values): |
| 1682 | |
| 1683 | ```json |
| 1684 | { |
| 1685 | "listen": "127.0.0.1:18443", |
| 1686 | "metrics_listen": "127.0.0.1:18444", |
| 1687 | "tls_cert_file": "<T17>/keys/tls.crt", |
| 1688 | "tls_key_file": "<T17>/keys/tls.key", |
| 1689 | "database": "<T17>/controller.db", |
| 1690 | "signing_key_file": "<T17>/keys/controller.key", |
| 1691 | "verify_keys": [ |
| 1692 | {"id": "task17-instance", "role": "instance", "public_key": "<base64>"}, |
| 1693 | {"id": "task17-operator", "role": "operator", "public_key": "<base64>"} |
| 1694 | ], |
| 1695 | "images": [{"digest": "<DIGEST>", "arn": "<IMAGE_ARN>", "versions": {"small": "<VER_SMALL>"}}], |
| 1696 | "region": "eu-west-1", |
| 1697 | "vpc_id": "<VPC>", |
| 1698 | "vm_subnet_id": "<SUBNET>", |
| 1699 | "vm_security_group_id": "<SG>", |
| 1700 | "connector_arn": "<CONN_ARN>:<CONN_VERSION>", |
| 1701 | "egress": [], |
| 1702 | "sns_topic_arn": "<TOPIC_ARN>" |
| 1703 | } |
| 1704 | ``` |
| 1705 | |
| 1706 | ### 5.4 Build the two controller binaries (no AWS call) |
| 1707 | |
| 1708 | ```sh |
| 1709 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh" |
| 1710 | cd "$REPO" |
| 1711 | [ -z "$(git diff "$PIN_SHA" HEAD -- . ':!docs')" ] && [ -z "$(git status --porcelain --untracked-files=all -- . ':!docs')" ] || die "code changed since 0.1" |
| 1712 | CGO_ENABLED=0 go build -o "$T17/bin/controller" ./cmd/equipo-hosted-controller |
| 1713 | CGO_ENABLED=0 go build -tags hostedlive -o "$T17/bin/controller-crash" ./cmd/equipo-hosted-controller |
| 1714 | ls -l "$T17/bin" |
| 1715 | ``` |
| 1716 | |
| 1717 | - `controller` is the normal build (no crash point); `controller-crash` is used only in 7.3. |
| 1718 | |
| 1719 | ### 5.5 Driver environment file (no AWS call) |
| 1720 | |
| 1721 | ```sh |
| 1722 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh" |
| 1723 | need DIGEST |
| 1724 | cat > "$T17/driver.env" <<EOF |
| 1725 | export EQUIPO_HOSTED_LIVE_URL=https://$API |
| 1726 | export EQUIPO_HOSTED_LIVE_CA_FILE=$T17/keys/tls.crt |
| 1727 | export EQUIPO_HOSTED_LIVE_KEY_ID=task17-instance |
| 1728 | export EQUIPO_HOSTED_LIVE_KEY_FILE=$T17/keys/instance.key |
| 1729 | export EQUIPO_HOSTED_LIVE_CONTROLLER_KEY_FILE=$T17/keys/controller.pub |
| 1730 | export EQUIPO_HOSTED_LIVE_IMAGE=$DIGEST |
| 1731 | EOF |
| 1732 | cat "$T17/driver.env" |
| 1733 | ``` |
| 1734 | |
| 1735 | ### 5.6 Audit-only controller run: the SDK checks the network before any VM exists |
| 1736 | |
| 1737 | Launches stay off (no `EQUIPO_HOSTED_ENABLED`). The reaper's first passes run the network audit |
| 1738 | through the SDK: VPC DNS both off, the subnet's table local-only, the group with no rules, and the |
| 1739 | connector read by its qualified ARN with `VersionArn` equal to it, `ACTIVE`, `MicroVm` only, this |
| 1740 | subnet and group only, and no service-managed Elastic IPs (`internal/isolatedjob/awsjob/network.go`). |
| 1741 | This also binds the database to `aws:640012953448:eu-west-1` (R28). |
| 1742 | |
| 1743 | What a clean start writes, read from the code at the pin (this is the revision 5 defect: it asked |
| 1744 | for a `network_audit_passed` row, which `reaperAudit` writes only when an audit passes again after |
| 1745 | a failing run, `internal/hostedctl/reaper.go:739-747`): |
| 1746 | |
| 1747 | - **Metrics, while it runs** (`internal/hostedctl/metrics.go:118-131`): |
| 1748 | `equipo_hosted_network_audit_passing 1` (the last audit passed and is fresh enough for |
| 1749 | launches; absent before the first audit), `equipo_hosted_reap_last_error 0` and |
| 1750 | `equipo_hosted_reap_last_age_seconds` (absent before the first pass). `ctl_ready` waits for |
| 1751 | exactly these. |
| 1752 | - **Audit rows:** one `provider_bound` row, reason `database bound to provider namespace |
| 1753 | aws:640012953448:eu-west-1`, written once, on the database's first start |
| 1754 | (`internal/hostedctl/store.go:366-372`); no `network_audit_failed` row (written when a run of |
| 1755 | failed audits begins, `reaper.go:748-754`); normally no `network_audit_passed` row. |
| 1756 | - **The binding:** `provider_binding.namespace` is `aws:640012953448:eu-west-1`. |
| 1757 | - **Log:** `equipo-hosted-controller: API on 127.0.0.1:18443, metrics on 127.0.0.1:18444, launches |
| 1758 | enabled: false` (`cmd/equipo-hosted-controller/main.go:120`), and no |
| 1759 | `hosted controller: network audit failed; launches refused` line (`internal/hostedctl/logs.go:35`). |
| 1760 | |
| 1761 | ```sh |
| 1762 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 1763 | ok=yes |
| 1764 | start_ctl "$T17/bin/controller" audit-only |
| 1765 | if (ctl_ready); then |
| 1766 | if mread; then |
| 1767 | printf '%s\n' "$MTXT" > "$T17/out/5.6-metrics.txt" |
| 1768 | grep -qx 'equipo_hosted_network_audit_passing 1' <<<"$MTXT" || { finding "audit metric is not 1 after ready"; ok=no; } |
| 1769 | grep -qx 'equipo_hosted_reap_last_error 0' <<<"$MTXT" || { finding "the last reaper pass failed after ready"; ok=no; } |
| 1770 | jw "FACT 5.6 metrics: $(grep -E '^equipo_hosted_(network_audit_passing|reap_last_error|reap_last_age_seconds|store_readable) ' <<<"$MTXT" | tr '\n' ' ')" |
| 1771 | else ok=no; fi |
| 1772 | ctl_log | grep -F 'launches enabled: false' || finding "the controller did not report launches off" |
| 1773 | if ctl_log | grep -F 'hosted controller: network audit failed'; then finding "the log shows a failed network audit"; ok=no; fi |
| 1774 | else finding "the audit-only controller did not become ready with the audit passing (see controller.log)"; ok=no; fi |
| 1775 | stop_ctl |
| 1776 | [ "$(cat "$T17/controller.exit" 2>/dev/null || true)" = 0 ] || finding "audit-only controller exit status $(cat "$T17/controller.exit" 2>/dev/null || echo unknown), want 0" |
| 1777 | dbread "select id, action, reason from audit where action in ('provider_bound','network_audit_passed','network_audit_failed') order by id" |
| 1778 | n=$(dbread "select count(*) from audit where action='network_audit_failed'"); [ "$n" = 0 ] || { finding "$n network_audit_failed rows"; ok=no; } |
| 1779 | n=$(dbread "select count(*) from audit where action='provider_bound' and reason='database bound to provider namespace aws:$ACCOUNT:eu-west-1'") |
| 1780 | [ "$n" = 1 ] || { finding "$n provider_bound rows naming aws:$ACCOUNT:eu-west-1, want 1"; ok=no; } |
| 1781 | ns=$(dbread "select namespace from provider_binding") |
| 1782 | [ "$ns" = "aws:$ACCOUNT:eu-west-1" ] || { finding "database bound to [$ns], not aws:$ACCOUNT:eu-west-1"; ok=no; } |
| 1783 | n=$(dbread "select count(*) from audit where action='network_audit_passed'"); jw "FACT network_audit_passed rows after a clean start: $n (0 expected)" |
| 1784 | rec AUDIT_OK "$ok" |
| 1785 | if [ "$ok" = yes ]; then jw "AUDIT passed before any launch"; echo "audit passed: sections 7 and 8 will run" |
| 1786 | else echo "the audit did not pass: sections 7 and 8 will be skipped (each failed check is a FINDING above)"; fi |
| 1787 | ``` |
| 1788 | |
| 1789 | - Expected: ready within 4 minutes; the metrics above (attempt 4 saw them at once); the |
| 1790 | launches-off line and no audit-failed line; one `provider_bound` row naming this account and |
| 1791 | region, no failure rows, the binding as above; exit status 0 after the stop; `audit passed`. |
| 1792 | - If any of those checks fails, each is a FINDING and `AUDIT_OK` is `no`: sections 7 and 8, which |
| 1793 | need a ready controller with a passing audit, are skipped as FINDINGs; 6 does not use the |
| 1794 | controller and still runs. A `network_audit_passed` row is only a fact: it appears only after a |
| 1795 | failed audit, which the failure-row check already reports. |
| 1796 | |
| 1797 | --- |
| 1798 | |
| 1799 | ## 6. Live contract: `ChangedSpecConflicts` only |
| 1800 | |
| 1801 | Attempt 4 ran the whole contract: 8 of 9 subtests passed, and `ChangedSpecConflicts` failed because |
| 1802 | the adapter mapped RunMicrovm's `ValidationException` "The provided clientToken was used with |
| 1803 | different request parameters." to `ErrInvalid`. `5f6e3e65` maps exactly that refusal on `run` to |
| 1804 | `ErrConflict` (`internal/isolatedjob/awsjob/errors.go`), and `bf29344a` adds two test rows. This |
| 1805 | section re-runs only that subtest against AWS. It is expected to PASS. A failure is a FINDING, not |
| 1806 | a stop. The subtest launches one Small VM (15-minute maximum), asks again with the same attempt and |
| 1807 | a new bootstrap, and stops the first VM in its cleanup |
| 1808 | (`internal/isolatedjob/isolatedjobtest/contract.go:172-184`); if AWS ever answered the changed |
| 1809 | request with a second VM, the cleanup would not stop it, so `settle_all` ends every VM of the image |
| 1810 | before section 7, whatever the result. |
| 1811 | |
| 1812 | ### 6.1 Run it, then settle every VM it made (long block, bound 40 min) |
| 1813 | |
| 1814 | ```sh |
| 1815 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 1816 | need IMAGE_ARN |
| 1817 | ! ctl_alive || die "the controller is running" |
| 1818 | scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image before the contract: $LIVE" |
| 1819 | export EQUIPO_HOSTED_LIVE_CONFIG="$T17/live.json" |
| 1820 | J="$T17/out/6-contract.json" |
| 1821 | if gotest "$J" -tags hostedlive ./internal/isolatedjob/awsjob -run '^TestLiveContract$/^ChangedSpecConflicts$' -count=1 -v -json -timeout 20m; then rc=0; else rc=$?; fi |
| 1822 | eni_snapshot soft "6.1, after the contract subtest" |
| 1823 | settle_all |
| 1824 | [ -s "$J" ] || { finding "the contract wrote no test output (rc $rc)"; exit 0; } |
| 1825 | jq -R -r 'fromjson? | select(.Action == "output") | .Output' "$J" > "$T17/out/6-contract.log" |
| 1826 | if grep -E "microvm id is missing or malformed|microvm id is malformed|empty or malformed ref" "$T17/out/6-contract.log"; then finding "the adapter refused a MicroVM ID as malformed (R36)"; fi |
| 1827 | grep -E 'visibility: Get showed new VM ' "$T17/out/6-contract.log" || finding "the contract logged no visibility line" |
| 1828 | T=TestLiveContract/ChangedSpecConflicts |
| 1829 | sub=$(jq -R -r --arg t "$T" 'fromjson? | select(.Test == $t and (.Action == "pass" or .Action == "fail" or .Action == "skip")) | .Action' "$J" | tail -n 1) |
| 1830 | top=$(jq -R -r 'fromjson? | select(.Test == "TestLiveContract" and (.Action == "pass" or .Action == "fail" or .Action == "skip")) | .Action' "$J" | tail -n 1) |
| 1831 | if [ "$rc" = 0 ] && [ "$sub" = pass ] && [ "$top" = pass ]; then rec CONTRACT_CSC pass; jw "CONTRACT ChangedSpecConflicts pass"; echo "ChangedSpecConflicts PASS"; exit 0; fi |
| 1832 | msgs=$(jq -R -r --arg t "$T" 'fromjson? | select(.Test == $t and .Action == "output") | .Output' "$J" | grep -E '^\s+contract\.go:[0-9]+: ' | grep -vE 'contract\.go:[0-9]+: visibility: ' || true) |
| 1833 | label=other |
| 1834 | if grep -qE 'Launch with the same attempt and a new bootstrap = \("", .*ValidationException.*clientToken was used with different request parameters.*\), want ErrConflict$' <<<"$msgs"; then |
| 1835 | label="the old failure: the fix did not take effect" |
| 1836 | elif grep -qE 'Launch with the same attempt and a new bootstrap = \(".+", <nil>\), want ErrConflict$' <<<"$msgs"; then |
| 1837 | label="AWS returned a VM for the changed request" |
| 1838 | elif grep -qE 'Launch with the same attempt and a new bootstrap = ' <<<"$msgs"; then |
| 1839 | label="another refusal, not mapped to ErrConflict" |
| 1840 | fi |
| 1841 | rec CONTRACT_CSC "fail:$label" |
| 1842 | finding "contract $T: rc $rc, subtest [${sub:-did not run}], top [${top:-none}] ($label): $(tr '\n' ' ' <<<"$msgs")" |
| 1843 | echo "ChangedSpecConflicts did not pass; recorded as a FINDING; every VM of the image is settled" |
| 1844 | ``` |
| 1845 | |
| 1846 | - Expected: `ChangedSpecConflicts PASS`, a `visibility: Get showed new VM ...` line, and |
| 1847 | `settled: N VMs recorded, none live in three scans` (N is 1). |
| 1848 | - A failure, a skip, or a subtest that did not run is a FINDING with its messages, labelled from |
| 1849 | the subtest's own output. The run goes on to section 7 either way, because `settle_all` has |
| 1850 | proved no VM of the image is live. |
| 1851 | - Hard stop only if: a VM it made cannot be settled. |
| 1852 | |
| 1853 | --- |
| 1854 | |
| 1855 | ## 7. Controller on docs-t1 |
| 1856 | |
| 1857 | Every block here reads the controller's log only through `ctl_log` (the lines since the latest |
| 1858 | start) or the slice `harvest_ctl` saves (`CTL_SLICE`), so one start's lines never pass or fail |
| 1859 | another start's check. The log lines checked, at the pin: |
| 1860 | |
| 1861 | | Check | Text | Source | |
| 1862 | | --- | --- | --- | |
| 1863 | | launches on | `launches enabled: true` | `cmd/equipo-hosted-controller/main.go:120` | |
| 1864 | | crash switch on | `EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1: the process exits after the next provider launch that returns a VM` | `crashpoint.go:35` | |
| 1865 | | crash point | `crash point: the provider launched <vm> for <attempt>; exiting before the Ref is saved` | `crashpoint.go:46` | |
| 1866 | | no elapsed-unknown stop | `hosted controller: restart stop requested, elapsed time unknown` | `internal/hostedctl/logs.go:44` | |
| 1867 | | malformed ID refused | `microvm id is missing or malformed` | `internal/isolatedjob/awsjob/runner.go:260,328` | |
| 1868 | |
| 1869 | ### 7.1 Start with launches on, check readiness |
| 1870 | |
| 1871 | ```sh |
| 1872 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 1873 | if [ "${AUDIT_OK:-}" != yes ]; then finding "section 7 skipped: the 5.6 audit did not pass"; rec SKIP_7 yes; exit 0; fi |
| 1874 | scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image: $LIVE" |
| 1875 | start_ctl "$T17/bin/controller" sequence EQUIPO_HOSTED_ENABLED=1 |
| 1876 | if ! (ctl_ready); then finding "the controller did not become ready; section 7 skipped"; stop_ctl; rec SKIP_7 yes; exit 0; fi |
| 1877 | ctl_log | grep -F 'launches enabled: true' || finding "the controller did not report launches enabled" |
| 1878 | ``` |
| 1879 | |
| 1880 | - Expected: `controller ready:` with `equipo_hosted_network_audit_passing 1` and |
| 1881 | `equipo_hosted_reap_last_error 0`, then the launches-on line. |
| 1882 | |
| 1883 | ### 7.2 Driver sequence: launch Small, drain, quiescent, suspend, resume, stop with proof (long block, bound 40 min) |
| 1884 | |
| 1885 | The plan names the attempt (`EQUIPO_HOSTED_LIVE_ATTEMPT`, which `TestLiveControllerSequence` uses |
| 1886 | when set, `internal/hostedclient/live_test.go:122-131`). The driver launches one Small VM with a |
| 1887 | 1-hour lifetime (`live_test.go:82`), waits for running, drains, acknowledges quiescence, suspends, |
| 1888 | resumes, and stops until it holds proof, logging each step (`driver_test.go:136-211`). |
| 1889 | |
| 1890 | ```sh |
| 1891 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 1892 | if [ -n "${SKIP_7:-}" ]; then echo "section 7 skipped"; exit 0; fi |
| 1893 | . "$T17/driver.env" |
| 1894 | ctl_alive || die "the controller is not running" |
| 1895 | [ -n "${SEQ_ATTEMPT:-}" ] || rec SEQ_ATTEMPT "task17-seq-$(openssl rand -hex 4)" |
| 1896 | export EQUIPO_HOSTED_LIVE_ATTEMPT="$SEQ_ATTEMPT" |
| 1897 | if gotest "$T17/out/7.2-sequence.log" -tags hostedlive ./internal/hostedclient -run '^TestLiveControllerSequence$' -count=1 -v -timeout 30m; then rc=0; else rc=$?; fi |
| 1898 | grep -E 'attempt |launch:|running:|pause:|suspended:|resume:|stop:|timings:' "$T17/out/7.2-sequence.log" || true |
| 1899 | eni_snapshot soft "7.2, after the sequence" |
| 1900 | stop_ctl |
| 1901 | harvest_ctl |
| 1902 | settle_all |
| 1903 | if grep -hE "microvm id is missing or malformed|microvm id is malformed|empty or malformed ref" "$T17/out/7.2-sequence.log" "$CTL_SLICE"; then finding "a MicroVM ID was refused as malformed (R36)"; fi |
| 1904 | [ "$rc" = 0 ] || finding "TestLiveControllerSequence failed (rc $rc); see 7.2-sequence.log" |
| 1905 | grep -qF "attempt $SEQ_ATTEMPT, image " "$T17/out/7.2-sequence.log" || finding "the sequence log does not name attempt $SEQ_ATTEMPT" |
| 1906 | t=$(grep -oE 'timings: .*' "$T17/out/7.2-sequence.log" | tail -n 1 || true) |
| 1907 | if [ -n "$t" ]; then jw "FACT sequence $t"; else finding "the sequence logged no timings line"; fi |
| 1908 | ep=$(grep -oE 'resume: epoch [0-9]+ \(was [0-9]+\)' "$T17/out/7.2-sequence.log" | tail -n 1 || true) |
| 1909 | if [[ "$ep" =~ ^resume:\ epoch\ ([0-9]+)\ \(was\ ([0-9]+)\)$ ]]; then |
| 1910 | jw "FACT sequence epoch ${BASH_REMATCH[2]} -> ${BASH_REMATCH[1]}" |
| 1911 | [ "${BASH_REMATCH[1]}" = "$(( BASH_REMATCH[2] + 1 ))" ] || finding "resume epoch ${BASH_REMATCH[1]}, want one above ${BASH_REMATCH[2]}" |
| 1912 | else finding "the sequence logged no resume epoch"; fi |
| 1913 | dbread "select attempt_id, state, vm_ref, epoch, pause_generation, stop_proof_json from jobs where attempt_id='$SEQ_ATTEMPT'" |
| 1914 | dbread "select action, reason from audit where attempt_id='$SEQ_ATTEMPT' order by id" |
| 1915 | st=$(dbread "select state from jobs where attempt_id='$SEQ_ATTEMPT'"); [ "$st" = stopped ] || finding "sequence job state [$st], want stopped" |
| 1916 | audit_has "$SEQ_ATTEMPT" launch_intent launch_started drain quiescent suspend_requested resume_prepared resume_committed stop_requested stop_proven |
| 1917 | ``` |
| 1918 | |
| 1919 | - Expected: PASS and the `timings:` line (launch call a few seconds; `to_running` up to about a |
| 1920 | minute, since states are read once per 60 s pass; suspend about 2 s and resume about 4 s, as |
| 1921 | attempt 4 measured directly; `stop_to_proof` about 2 to 3 minutes, R17). The resume epoch is one |
| 1922 | above the launch epoch. The job row is `stopped` with stop proof. Its audit rows include, in |
| 1923 | order, `launch_intent`, `launch_started`, `drain`, `quiescent`, `suspend_requested`, |
| 1924 | `resume_prepared`, `resume_committed`, `stop_requested` and `stop_proven` (the constants in |
| 1925 | `internal/hostedctl/launch.go:58-70`, `pause.go:35-49`, `resume.go:32-39` and `stop.go:44-52`). |
| 1926 | - A FAIL, a missing line or row, or odd evidence is a FINDING; the controller is stopped and every |
| 1927 | VM settled either way. |
| 1928 | |
| 1929 | ### 7.3 Crash between the provider call and transaction 2: the launch step (long block, bound 15 min) |
| 1930 | |
| 1931 | ```sh |
| 1932 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 1933 | if [ -n "${SKIP_7:-}" ]; then echo "section 7 skipped"; exit 0; fi |
| 1934 | . "$T17/driver.env" |
| 1935 | rec CRASH_ATTEMPT "task17-crash-$(openssl rand -hex 4)" |
| 1936 | rec CRASH_START "$(date -u +%FT%T)" |
| 1937 | start_ctl "$T17/bin/controller-crash" crash EQUIPO_HOSTED_ENABLED=1 EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1 |
| 1938 | if ! (ctl_ready); then finding "the crash-build controller did not become ready; 7.3 and 7.4 skipped"; stop_ctl; rec SKIP_74 yes; exit 0; fi |
| 1939 | ctl_log | grep -F 'EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1: the process exits' || finding "the crash switch is not reported on" |
| 1940 | export EQUIPO_HOSTED_LIVE_ATTEMPT="$CRASH_ATTEMPT" EQUIPO_HOSTED_LIVE_CRASH_STEP=launch |
| 1941 | if gotest "$T17/out/7.3-launch.log" -tags hostedlive ./internal/hostedclient -run '^TestLiveCrashRecovery$' -count=1 -v -timeout 10m; then rc=0; else rc=$?; fi |
| 1942 | [ "$rc" = 0 ] || finding "the launch step failed (rc $rc); see 7.3-launch.log" |
| 1943 | _exited() { [ -s "$T17/controller.exit" ] && return 0; return 1; } |
| 1944 | if ! (poll 60 2 "crash-build controller exit" _exited); then finding "the crash-build controller did not exit after the launch"; fi |
| 1945 | stop_ctl |
| 1946 | [ "$(cat "$T17/controller.exit" 2>/dev/null || true)" = 137 ] || finding "crash-build exit status $(cat "$T17/controller.exit" 2>/dev/null || echo unknown), want 137" |
| 1947 | harvest_ctl |
| 1948 | vm=$(grep -oE "provider launched $VMID_RE for $CRASH_ATTEMPT;" "$CTL_SLICE" | tail -n 1 | cut -d' ' -f3 || true) |
| 1949 | if [ -z "$vm" ]; then finding "the crash log names no launched VM; 7.4 skipped"; rec SKIP_74 yes; settle_all; exit 0; fi |
| 1950 | rec CRASH_VM "$vm" |
| 1951 | vm_get "$CRASH_VM"; echo "crash VM $CRASH_VM: $VST" |
| 1952 | case "$VST" in PENDING|RUNNING) ;; *) finding "crash VM state $VST";; esac |
| 1953 | row=$(dbread "select state, ifnull(vm_ref, '-') from jobs where attempt_id='$CRASH_ATTEMPT'") |
| 1954 | [ "$row" = "waiting -" ] || finding "crash job row [$row], want waiting with no VM ref (the Ref must not be saved)" |
| 1955 | audit_has "$CRASH_ATTEMPT" launch_intent |
| 1956 | jw "CRASH controller exited after launching $CRASH_VM" |
| 1957 | ``` |
| 1958 | |
| 1959 | - Expected: the launch fails in transport (the test passes: `launch: the controller went away ...`); |
| 1960 | exit status 137; the log line `crash point: the provider launched <vm> for <attempt>; exiting |
| 1961 | before the Ref is saved`, with `<vm>` matching `VMID_RE`; the VM `PENDING` or `RUNNING`; the job |
| 1962 | row `waiting` with no VM ref, and a `launch_intent` audit row. |
| 1963 | - The controller answering the launch, another exit status, or no launched VM is a FINDING; 7.4 |
| 1964 | is then skipped if there is no VM to recover. Every VM is settled. A launch refused because no |
| 1965 | audit has passed recently is a FINDING, like any other failed launch step. |
| 1966 | |
| 1967 | ### 7.4 Restart without the crash switch; Replay claims the one VM (long block, bound 25 min) |
| 1968 | |
| 1969 | The controller unit's `env -i` argument list is its whole environment (R45), and only 7.3's unit |
| 1970 | gets `EQUIPO_HOSTED_CRASH_AFTER_LAUNCH`. The block reads the restarted unit's `ExecStart` and checks |
| 1971 | that argument list has no crash switch (pre-flight concern 3); a read that fails or cannot be parsed |
| 1972 | fails the block (`soft_fail`), never counts as "absent". The readiness check comes before the recovery driver; Replay runs on the |
| 1973 | second reaper pass, about 60 s after start (pre-flight concern 2). The replay re-sends the stored |
| 1974 | spec with the attempt ID as the client token (`internal/hostedctl/launch.go:233,310`, |
| 1975 | `internal/isolatedjob/awsjob/runner.go:248`), so AWS answers with the crash VM: attempt 4 showed a |
| 1976 | repeated request under a used token returns the same VM, even 7 minutes on and after the VM ended. |
| 1977 | |
| 1978 | ```sh |
| 1979 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 1980 | if [ -n "${SKIP_7:-}" ] || [ -n "${SKIP_74:-}" ]; then echo "7.4 skipped"; settle_all; exit 0; fi |
| 1981 | . "$T17/driver.env" |
| 1982 | need CRASH_ATTEMPT CRASH_VM CRASH_START |
| 1983 | start_ctl "$T17/bin/controller" recover EQUIPO_HOSTED_ENABLED=1 |
| 1984 | if ! (ctl_ready); then finding "the restarted controller did not become ready; 7.4 skipped"; stop_ctl; settle_all; exit 0; fi |
| 1985 | _x=$(_sc show -p ExecStart --value -- "$(ctl_unit)") || soft_fail "cannot read the restarted controller unit's ExecStart" |
| 1986 | _a=$(sed -n 's/.*argv\[\]=\(.*\) ; ignore_errors=.*/\1/p' <<<"$_x") |
| 1987 | [[ "$_a" == "/usr/bin/env -i "* ]] || soft_fail "the restarted controller unit's ExecStart argv is unreadable or not an env -i list: [$_x]" |
| 1988 | if grep -qF 'EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=' <<<"$_a"; then finding "the crash switch is in the restarted controller's env -i argv; 7.4 skipped"; stop_ctl; settle_all; exit 0; fi |
| 1989 | export EQUIPO_HOSTED_LIVE_ATTEMPT="$CRASH_ATTEMPT" EQUIPO_HOSTED_LIVE_CRASH_STEP=recover \ |
| 1990 | EQUIPO_HOSTED_LIVE_OPERATOR_KEY_ID=task17-operator EQUIPO_HOSTED_LIVE_OPERATOR_KEY_FILE="$T17/keys/operator.key" |
| 1991 | if gotest "$T17/out/7.4-recover.log" -tags hostedlive ./internal/hostedclient -run '^TestLiveCrashRecovery$' -count=1 -v -timeout 15m; then rc=0; else rc=$?; fi |
| 1992 | grep -E 'recover:|listed vm|stop:' "$T17/out/7.4-recover.log" || true |
| 1993 | stop_ctl |
| 1994 | harvest_ctl |
| 1995 | settle_all |
| 1996 | [ "$rc" = 0 ] || finding "the recover step failed (rc $rc); see 7.4-recover.log" |
| 1997 | grep -qF "recover: job $CRASH_ATTEMPT holds vm $CRASH_VM " "$T17/out/7.4-recover.log" || finding "the job does not hold $CRASH_VM" |
| 1998 | if grep -F 'restart stop requested, elapsed time unknown' "$CTL_SLICE"; then finding "the restart stopped a job for unknown elapsed time"; fi |
| 1999 | if grep -hE "microvm id is missing or malformed|microvm id is malformed|empty or malformed ref" "$T17/out/7.4-recover.log" "$CTL_SLICE"; then finding "a MicroVM ID was refused as malformed (R36)"; fi |
| 2000 | scan >/dev/null |
| 2001 | n=$(awk -F'\t' -v t="$CRASH_START" '$3 >= t' "$T17/last_scan.tsv" | wc -l) |
| 2002 | awk -F'\t' -v t="$CRASH_START" '$3 >= t' "$T17/last_scan.tsv" |
| 2003 | [ "$n" = 1 ] || finding "$n VMs of this image started since the crash launch, want 1" |
| 2004 | dbread "select attempt_id, state, vm_ref, stop_proof_json from jobs where attempt_id='$CRASH_ATTEMPT'" |
| 2005 | dbread "select action, reason from audit where attempt_id='$CRASH_ATTEMPT' order by id" |
| 2006 | row=$(dbread "select state, vm_ref from jobs where attempt_id='$CRASH_ATTEMPT'") |
| 2007 | [ "$row" = "stopped $CRASH_VM" ] || finding "crash job row [$row], want stopped holding $CRASH_VM" |
| 2008 | audit_has "$CRASH_ATTEMPT" launch_intent replay_started stop_requested stop_proven |
| 2009 | ``` |
| 2010 | |
| 2011 | - Expected: PASS; the job holds `$CRASH_VM`, the same ID the crashed controller launched; the |
| 2012 | operator list shows one VM for the attempt and no unowned live VM; stop with proof; no |
| 2013 | `restart stop requested, elapsed time unknown` line; exactly one VM of this image started since |
| 2014 | 7.3 began; the job row `stopped` holding `$CRASH_VM`; audit rows `launch_intent`, |
| 2015 | `replay_started` (`launch.go:602-604`: a replay that gains a VM writes `replay_started`, not |
| 2016 | `launch_started`), `stop_requested` and `stop_proven`. |
| 2017 | - Each failed check is a FINDING; the controller is stopped and every VM settled. |
| 2018 | |
| 2019 | --- |
| 2020 | |
| 2021 | ## 8. Orphan |
| 2022 | |
| 2023 | ### 8.1 Start the controller (launches off: reaping works regardless) and plant a VM |
| 2024 | |
| 2025 | R22 defers orphans while a dispatched launch intent is still waiting, so the block first reads |
| 2026 | `equipo_hosted_jobs{state="waiting"} 0` (`internal/hostedctl/metrics.go:104-115`). After section 7 |
| 2027 | both jobs are `stopped`. |
| 2028 | |
| 2029 | ```sh |
| 2030 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 2031 | if [ "${AUDIT_OK:-}" != yes ]; then finding "section 8 skipped: the 5.6 audit did not pass"; rec SKIP_8 yes; exit 0; fi |
| 2032 | scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image: $LIVE" |
| 2033 | start_ctl "$T17/bin/controller" orphan |
| 2034 | if ! (ctl_ready); then finding "the controller did not become ready; section 8 skipped"; stop_ctl; rec SKIP_8 yes; exit 0; fi |
| 2035 | if ! mread || ! grep -qx 'equipo_hosted_jobs{state="waiting"} 0' <<<"$MTXT"; then |
| 2036 | finding "no proof that no launch intent is waiting (R22 could defer the orphan); section 8 skipped"; stop_ctl; rec SKIP_8 yes; exit 0 |
| 2037 | fi |
| 2038 | printf 'orphan' > "$T17/out/payload-orphan" |
| 2039 | rec ORPHAN_TOKEN "$NAME-orphan" |
| 2040 | rec ORPHAN_PLANTED "$(date -u +%FT%TZ)" |
| 2041 | launch orphan "$ORPHAN_TOKEN" 1800 "$T17/out/payload-orphan" |
| 2042 | if [ "$L_OUTCOME" != created ]; then finding "the orphan launch was $L_OUTCOME (${L_CODE:-rc$L_RC} ${L_MSG}); section 8 skipped"; stop_ctl; settle_all; rec SKIP_8 yes; exit 0; fi |
| 2043 | rec ORPHAN_VM "$L_ID" |
| 2044 | [[ "$ORPHAN_VM" =~ ^$VMID_RE$ ]] || finding "orphan VM ID [$ORPHAN_VM] is outside the known form" |
| 2045 | eni_snapshot soft "8.1, orphan planted" |
| 2046 | ``` |
| 2047 | |
| 2048 | - Expected: a VM ID of the form `VMID_RE`; no job or intent names its token; its 1800 s maximum |
| 2049 | duration is AWS's backstop. |
| 2050 | |
| 2051 | ### 8.2 Watch the reaper stop it (long block, bound 25 min) |
| 2052 | |
| 2053 | Expected timeline from the plant time P: the reaper lists every 60 s (`ReapInterval`, |
| 2054 | `internal/hostedctl/reaper.go:16`), so it first sees the VM by about P+1:30; it stops an orphan on |
| 2055 | the first pass at least 10 minutes (`OrphanGrace`, `reaper.go:22`) after the first sighting, after |
| 2056 | rechecking ownership; so the stop lands between about P+11:00 and P+12:30, and the VM ends within a |
| 2057 | minute or two after that. The stop raises one `orphan_stopped` alert, published to the run's SNS |
| 2058 | topic: the first SNS publish of the whole task. |
| 2059 | |
| 2060 | ```sh |
| 2061 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 2062 | if [ -n "${SKIP_8:-}" ]; then echo "section 8 skipped"; exit 0; fi |
| 2063 | need ORPHAN_VM ORPHAN_PLANTED |
| 2064 | P=$(date -d "$ORPHAN_PLANTED" +%s) |
| 2065 | while :; do |
| 2066 | now=$(date +%s) |
| 2067 | if [ $(( now - P )) -ge 900 ]; then stop_ctl; vm_end "$ORPHAN_VM"; die "the orphan was not stopped by P+15:00 (last state ${VST:-none}): a VM alive outside its step"; fi |
| 2068 | ctl_alive || { finding "the controller stopped while watching the orphan"; vm_end "$ORPHAN_VM"; settle_all; exit 0; } |
| 2069 | vm_get "$ORPHAN_VM" |
| 2070 | echo "P+$(( (now - P) / 60 )):$(printf %02d $(( (now - P) % 60 ))) $VST" |
| 2071 | case "$VST" in |
| 2072 | TERMINATING|TERMINATED|NOTFOUND) break;; |
| 2073 | PENDING|RUNNING) ;; |
| 2074 | *) finding "orphan read: $VST";; |
| 2075 | esac |
| 2076 | sleep 20 |
| 2077 | done |
| 2078 | [ $(( now - P )) -ge 600 ] || finding "the orphan was stopped before the 10-minute grace (P+$(( now - P ))s)" |
| 2079 | jw "ORPHAN stopped by the reaper at P+$(( now - P ))s" |
| 2080 | for i in 1 2 3 4 5 6; do mread || break; grep -q '^equipo_hosted_alerts_total{kind="orphan_stopped"' <<<"$MTXT" && break; sleep 10; done |
| 2081 | if [ -n "${MTXT:-}" ]; then |
| 2082 | grep -E 'orphan' <<<"$MTXT" || true |
| 2083 | grep -qx 'equipo_hosted_alerts_total{kind="orphan_stopped",result="sent"} 1' <<<"$MTXT" || finding "no orphan_stopped alert counted as sent" |
| 2084 | if grep -q '^equipo_hosted_alerts_total{kind="orphan_stopped",result="failed"}' <<<"$MTXT"; then finding "the orphan_stopped alert failed to publish to SNS"; fi |
| 2085 | fi |
| 2086 | stop_ctl |
| 2087 | harvest_ctl |
| 2088 | grep -F 'hosted controller: orphan VM stopped' "$CTL_SLICE" | grep -F "vm_ref=$ORPHAN_VM" || finding "no orphan-stopped log line for $ORPHAN_VM" |
| 2089 | if grep -F 'hosted controller: orphan VM left running for a dispatched launch intent' "$CTL_SLICE" | grep -qF "vm_ref=$ORPHAN_VM"; then finding "the orphan was deferred (R22)"; fi |
| 2090 | vm_end "$ORPHAN_VM" |
| 2091 | settle_all |
| 2092 | dbread "select action, reason from audit where action like 'orphan%' order by id" |
| 2093 | n=$(dbread "select count(*) from audit where action='orphan_seen' and reason like 'VM $ORPHAN_VM %'"); [ "$n" = 1 ] || finding "$n orphan_seen audit rows for $ORPHAN_VM, want 1" |
| 2094 | n=$(dbread "select count(*) from audit where action='orphan_stopped' and reason like 'VM $ORPHAN_VM %'"); [ "$n" = 1 ] || finding "$n orphan_stopped audit rows for $ORPHAN_VM, want 1" |
| 2095 | ``` |
| 2096 | |
| 2097 | - Expected: `RUNNING` until about P+11:00 to P+12:30; then |
| 2098 | `equipo_hosted_alerts_total{kind="orphan_stopped",result="sent"} 1`; the operator log record |
| 2099 | `msg="hosted controller: orphan VM stopped" vm_ref=<orphan>` (slog text, |
| 2100 | `internal/hostedctl/logs.go:18`) and no deferral record (`logs.go:29`); one `orphan_seen` |
| 2101 | (`reaper.go:559-560`) and one `orphan_stopped` audit row for it, each reason starting |
| 2102 | `VM <orphan> `; the VM ends. |
| 2103 | - Hard stop: no stop seen by P+15:00, whatever the reads returned (the deadline is checked first on |
| 2104 | every iteration); the block stops the controller and ends the VM first. A stop before P+10:00, |
| 2105 | a failed SNS publish and any missing evidence are FINDINGs. |
| 2106 | |
| 2107 | **Task 17b record** (one line each in the progress file, section 11.3 lists them): the |
| 2108 | `ChangedSpecConflicts` result; the sequence's `timings:` line and its epochs; the crash VM, the |
| 2109 | crash exit status and the recover result; the orphan's plant time, its stop time relative to P, |
| 2110 | and the alert result. |
| 2111 | |
| 2112 | --- |
| 2113 | |
| 2114 | ## 10. Teardown and verification |
| 2115 | |
| 2116 | Runs after section 8, or on Paul's word after a safe stop. Dependency order. Each deletion is confirmed by |
| 2117 | a direct read before the next dependency is touched, and recorded with `deleted`. |
| 2118 | |
| 2119 | ### 10.1 No controller, no VM, then the image (all its versions) |
| 2120 | |
| 2121 | ```sh |
| 2122 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 2123 | stop_ctl |
| 2124 | if have IMAGE_ARN; then |
| 2125 | settle_all |
| 2126 | lvr image delete -id "$IMAGE_ARN" |
| 2127 | [ "$RC" = 0 ] || die "image delete: ${ECODE:-rc$RC} ${LV_MSG:-$ERR} (a ConflictException is a stop: U8)" |
| 2128 | _img() { lvr image list -name "$IMAGE_NAME"; [ "$RC" = 0 ] || return 1 |
| 2129 | list_items || die "malformed image list reply while proving the image deleted" |
| 2130 | OUT=$(jq -r --arg a "$IMAGE_ARN" '[.[] | select(.ImageArn == $a) | .State] | join(" ")' <<<"$ITEMS") || die "image list items unreadable" |
| 2131 | echo "$(date -u +%T) listed state: [${OUT}]"; case "$OUT" in ""|DELETED) return 0;; DELETING) return 1;; esac; return 2; } |
| 2132 | poll 900 15 "image deleted" _img |
| 2133 | deleted microvm-image "$IMAGE_ARN" |
| 2134 | for vv in VER_SMALL_FAILED VER_SMALL; do |
| 2135 | [ -n "${!vv:-}" ] || continue; v=${!vv} |
| 2136 | lvr image get-version -id "$IMAGE_ARN" -version "$v" |
| 2137 | if { [ "$RC" = 0 ] && [ "$(jq -r .State <<<"$OUT")" = DELETED ]; } || { [ "$RC" != 0 ] && [ "$ECODE" = ResourceNotFoundException ]; }; then |
| 2138 | deleted microvm-image-version "$IMAGE_ARN:$v" |
| 2139 | else finding "version $v after the image delete: rc $RC ${ECODE:-} $(jq -r '.State // empty' <<<"$OUT" 2>/dev/null || true)"; fi |
| 2140 | done |
| 2141 | fi |
| 2142 | ``` |
| 2143 | |
| 2144 | ### 10.2 Connector, then its network interfaces |
| 2145 | |
| 2146 | ```sh |
| 2147 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 2148 | if have CONN_ARN; then |
| 2149 | need VPC SUBNET OPERATOR_ROLE |
| 2150 | eni_snapshot strict "10.2, before the connector delete" |
| 2151 | B_END=$(( $(date +%s) + 7200 )) |
| 2152 | # budget N: N seconds, or what is left of 10.2's shared 120-minute budget if that is less. |
| 2153 | budget() { local r=$(( B_END - $(date +%s) )); [ "$r" -gt 0 ] || die "10.2's shared 120-minute budget is spent: hard stop"; echo $(( r < $1 ? r : $1 )); } |
| 2154 | conn_delete() { lvr connector delete -id "$CONN_ARN" |
| 2155 | [ "$RC" = 0 ] || [ "$ECODE" = ResourceNotFoundException ] || die "connector delete: ${ECODE:-rc$RC} ${LV_MSG:-$ERR}"; } |
| 2156 | conn_gone() { local b; b=$(budget 2400) || die "10.2's shared budget is spent: hard stop"; lv_wait "$b" connector wait-gone -id "$CONN_ARN" -interval 15s; CG_RC=$RC; CG_CODE=$ECODE |
| 2157 | echo "wait-gone: rc $CG_RC ${CG_CODE:-} $(jq -c '{State,StateReason}' <<<"$OUT" 2>/dev/null || true)"; } |
| 2158 | # enis_gone SECONDS: 0 when no interface is left in the VPC within SECONDS; 1 when some are left at the bound. |
| 2159 | enis_gone() { local end=$(( $(date +%s) + $1 )) |
| 2160 | while :; do |
| 2161 | try aws ec2 describe-network-interfaces --filters Name=vpc-id,Values="$VPC" --query 'length(NetworkInterfaces)' --output json |
| 2162 | [ "$RC" = 0 ] || die "interface count unreadable: ${ECODE:-rc$RC}" |
| 2163 | echo "$(date -u +%T) interfaces in VPC: $OUT"; [ "$OUT" = 0 ] && return 0 |
| 2164 | [ "$(date +%s)" -lt "$end" ] || return 1 |
| 2165 | sleep 30 |
| 2166 | done; } |
| 2167 | conn_delete; conn_gone; ok=no |
| 2168 | if [ "$CG_RC" = 0 ]; then deleted connector "$CONN_ARN"; eb=$(budget 2400) || die "10.2's shared budget is spent: hard stop"; enis_gone "$eb" && ok=yes |
| 2169 | elif [ "$CG_RC" = 6 ] && [ "$CG_CODE" = DELETE_FAILED ]; then : |
| 2170 | else die "connector wait-gone: rc $CG_RC ${CG_CODE:-}"; fi |
| 2171 | if [ "$ok" = no ]; then |
| 2172 | finding "connector teardown needs the pre-approved fallback (wait-gone rc $CG_RC ${CG_CODE:-}, or interfaces left after 40 min)" |
| 2173 | have OPERATOR_ROLE_ARN || die "no operator role to change" |
| 2174 | A=arn:aws:ec2:eu-west-1:640012953448 |
| 2175 | cat > "$T17/iam/operator-delete-subnet.json" <<TEOF |
| 2176 | {"Version":"2012-10-17","Statement":[ |
| 2177 | {"Sid":"DeleteEniInThisSubnet","Effect":"Allow","Action":"ec2:DeleteNetworkInterface","Resource":"$A:network-interface/*", |
| 2178 | "Condition":{"ArnEquals":{"ec2:Subnet":"$A:subnet/$SUBNET"}}}]} |
| 2179 | TEOF |
| 2180 | jq -e . "$T17/iam/operator-delete-subnet.json" >/dev/null |
| 2181 | aws iam put-role-policy --role-name "$OPERATOR_ROLE" --policy-name t17-connector-eni-delete --policy-document "file://$T17/iam/operator-delete-subnet.json" |
| 2182 | rec OPERATOR_DELETE_FALLBACK "subnet condition only (Paul, 2026-11-28)" |
| 2183 | echo "waiting 120 s for IAM propagation, then one more connector delete"; sleep 120 |
| 2184 | conn_delete; conn_gone |
| 2185 | [ "$CG_RC" = 0 ] || die "the connector delete failed again after the fallback (rc $CG_RC ${CG_CODE:-}): hard stop" |
| 2186 | grep -q $'\tDELETED connector '"$CONN_ARN"'$' "$JOURNAL" || deleted connector "$CONN_ARN" |
| 2187 | eb=$(budget 2400) || die "10.2's shared budget is spent: hard stop"; enis_gone "$eb" || die "interfaces are still in the VPC after the fallback: hard stop" |
| 2188 | fi |
| 2189 | for e in $(awk -F'\t' '$2 ~ /^SERVICE-ENI / {split($2, a, " "); print a[2]}' "$JOURNAL"); do |
| 2190 | gone0 "interface $e" aws ec2 describe-network-interfaces --filters Name=network-interface-id,Values="$e" --query 'length(NetworkInterfaces)' --output json |
| 2191 | deleted service-eni "$e" |
| 2192 | done |
| 2193 | fi |
| 2194 | ``` |
| 2195 | |
| 2196 | - Pre-approved fallback (Paul, 2026-11-28): on `DELETE_FAILED`, or interfaces left after 40 |
| 2197 | minutes, the inline delete policy loses its `ec2:ManagedResourceOperator` condition (the subnet |
| 2198 | condition stays), and after 120 s the connector delete is retried once. A second failure, or |
| 2199 | interfaces still left, is a hard stop. Lambda's interfaces are never deleted by hand. |
| 2200 | - One shared budget of 120 minutes covers the attempt and its fallback: each wait takes at most its |
| 2201 | own 40-minute bound and never more than what is left of the 120 minutes; when it is spent, that is |
| 2202 | a hard stop. The detached-block limit for 10.2 alone is 130 minutes, so the wrapper never cuts the |
| 2203 | pre-approved fallback short. |
| 2204 | |
| 2205 | ### 10.3 Network |
| 2206 | |
| 2207 | ```sh |
| 2208 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 2209 | if have SG; then |
| 2210 | get _v aws ec2 delete-security-group --group-id "$SG" --query Return --output text; [ "$_v" = True ] || die "delete group" |
| 2211 | gone0 "group $SG" aws ec2 describe-security-groups --filters Name=group-id,Values="$SG" --query 'length(SecurityGroups)' --output json; deleted security-group "$SG" |
| 2212 | fi |
| 2213 | if have RTB_ASSOC; then aws ec2 disassociate-route-table --association-id "$RTB_ASSOC"; deleted route-table-association "$RTB_ASSOC"; fi |
| 2214 | if have RTB; then |
| 2215 | aws ec2 delete-route-table --route-table-id "$RTB" |
| 2216 | gone0 "route table $RTB" aws ec2 describe-route-tables --filters Name=route-table-id,Values="$RTB" --query 'length(RouteTables)' --output json; deleted route-table "$RTB" |
| 2217 | fi |
| 2218 | if have SUBNET; then |
| 2219 | aws ec2 delete-subnet --subnet-id "$SUBNET" |
| 2220 | gone0 "subnet $SUBNET" aws ec2 describe-subnets --filters Name=subnet-id,Values="$SUBNET" --query 'length(Subnets)' --output json; deleted subnet "$SUBNET" |
| 2221 | fi |
| 2222 | if have VPC; then |
| 2223 | aws ec2 delete-vpc --vpc-id "$VPC" |
| 2224 | gone0 "VPC $VPC" aws ec2 describe-vpcs --filters Name=vpc-id,Values="$VPC" --query 'length(Vpcs)' --output json; deleted vpc "$VPC" |
| 2225 | if have DEF_SG_RULES; then gone0 "default group rules $DEF_SG_RULES" aws ec2 describe-security-group-rules --filters Name=security-group-rule-id,Values="$(tr '\t ' ',,' <<<"$DEF_SG_RULES")" --query 'length(SecurityGroupRules)' --output json; deleted vpc-default-security-group-rules "$DEF_SG_RULES"; fi |
| 2226 | if have DEF_SG; then gone0 "default group $DEF_SG" aws ec2 describe-security-groups --filters Name=group-id,Values="$DEF_SG" --query 'length(SecurityGroups)' --output json; deleted vpc-default-security-group "$DEF_SG"; fi |
| 2227 | if have MAIN_RTB; then gone0 "main route table $MAIN_RTB" aws ec2 describe-route-tables --filters Name=route-table-id,Values="$MAIN_RTB" --query 'length(RouteTables)' --output json; deleted vpc-main-route-table "$MAIN_RTB"; fi |
| 2228 | if have DEF_ACL; then gone0 "default network ACL $DEF_ACL" aws ec2 describe-network-acls --filters Name=network-acl-id,Values="$DEF_ACL" --query 'length(NetworkAcls)' --output json; deleted vpc-default-network-acl "$DEF_ACL"; fi |
| 2229 | fi |
| 2230 | ``` |
| 2231 | |
| 2232 | - Abort if: a `DependencyViolation`, a failed read, or a filtered `describe` that still lists the |
| 2233 | resource. |
| 2234 | |
| 2235 | ### 10.4 IAM roles |
| 2236 | |
| 2237 | The operator role holds the managed attachment and the inline delete policy (2.1; 10.2's fallback |
| 2238 | rewrites the same policy name). The old narrow policy name is still tried, so a role left by an |
| 2239 | earlier revision is cleaned too. Each is removed if present; `NoSuchEntity` means it was never |
| 2240 | added. |
| 2241 | |
| 2242 | ```sh |
| 2243 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 2244 | need OPERATOR_ROLE BUILD_ROLE |
| 2245 | if have OPERATOR_ROLE_ARN; then |
| 2246 | for pn in t17-connector-eni t17-connector-eni-delete; do |
| 2247 | try aws iam delete-role-policy --role-name "$OPERATOR_ROLE" --policy-name "$pn"; [ "$RC" = 0 ] || expect_err NoSuchEntity |
| 2248 | done |
| 2249 | try aws iam detach-role-policy --role-name "$OPERATOR_ROLE" --policy-arn arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy; [ "$RC" = 0 ] || expect_err NoSuchEntity |
| 2250 | aws iam delete-role --role-name "$OPERATOR_ROLE" |
| 2251 | try aws iam get-role --role-name "$OPERATOR_ROLE"; expect_err NoSuchEntity; deleted iam-role "$OPERATOR_ROLE_ARN" |
| 2252 | if [ -n "${OPERATOR_INLINE_POLICY:-}" ]; then deleted iam-inline-policy "$OPERATOR_INLINE_POLICY"; fi |
| 2253 | if [ -n "${OPERATOR_MANAGED_POLICY:-}" ]; then deleted iam-managed-attachment "$OPERATOR_MANAGED_POLICY"; fi |
| 2254 | fi |
| 2255 | if have BUILD_ROLE_ARN; then |
| 2256 | try aws iam delete-role-policy --role-name "$BUILD_ROLE" --policy-name t17-build; [ "$RC" = 0 ] || expect_err NoSuchEntity |
| 2257 | aws iam delete-role --role-name "$BUILD_ROLE" |
| 2258 | try aws iam get-role --role-name "$BUILD_ROLE"; expect_err NoSuchEntity; deleted iam-role "$BUILD_ROLE_ARN" |
| 2259 | fi |
| 2260 | ``` |
| 2261 | |
| 2262 | ### 10.5 S3 |
| 2263 | |
| 2264 | ```sh |
| 2265 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 2266 | need BUCKET |
| 2267 | if have BUCKET_CREATED; then |
| 2268 | if have ARTIFACT; then |
| 2269 | aws s3api delete-object --bucket "$BUCKET" --key t17/app.zip |
| 2270 | gone0 "object t17/app.zip" aws s3api list-objects-v2 --bucket "$BUCKET" --prefix t17/app.zip --query 'length((Contents || `[]`)[?Key==`t17/app.zip`])' --output json; deleted s3-object "s3://$BUCKET/t17/app.zip" |
| 2271 | fi |
| 2272 | get _v aws s3api list-object-versions --bucket "$BUCKET" --output json |
| 2273 | [ "$(jq '((.Versions // []) + (.DeleteMarkers // [])) | length' <<<"$_v")" = 0 ] || die "objects left in the bucket" |
| 2274 | aws s3api delete-bucket --bucket "$BUCKET" |
| 2275 | _bucket() { try aws s3api list-buckets --prefix "$BUCKET" --query "length(Buckets[?Name=='$BUCKET'])" --output json; [ "$RC" = 0 ] || return 3; echo "$(date -u +%T) listed: $OUT"; [ "$OUT" = 0 ] && return 0; return 1; } |
| 2276 | poll 300 10 "bucket gone from the list" _bucket; deleted s3-bucket "$BUCKET" |
| 2277 | fi |
| 2278 | ``` |
| 2279 | |
| 2280 | ### 10.6 Log group |
| 2281 | |
| 2282 | ```sh |
| 2283 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 2284 | need LOG_GROUP |
| 2285 | if have LOG_GROUP_CREATED; then |
| 2286 | get got aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text |
| 2287 | [ "$got" = "$LOG_GROUP" ] || die "log groups under the prefix: [$got]; any group the run did not create goes to Paul" |
| 2288 | aws logs delete-log-group --log-group-name "$LOG_GROUP" |
| 2289 | get got aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text |
| 2290 | [ -z "$got" ] || die "log group still listed: [$got]" |
| 2291 | deleted log-group "$LOG_GROUP" |
| 2292 | fi |
| 2293 | ``` |
| 2294 | |
| 2295 | ### 10.7 SNS topic |
| 2296 | |
| 2297 | ```sh |
| 2298 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 2299 | if have TOPIC_ARN; then |
| 2300 | aws sns delete-topic --topic-arn "$TOPIC_ARN" |
| 2301 | _topic() { try aws sns list-topics --query "length(Topics[?TopicArn=='$TOPIC_ARN'])" --output json; [ "$RC" = 0 ] || return 3; echo "$(date -u +%T) listed: $OUT"; [ "$OUT" = 0 ] && return 0; return 1; } |
| 2302 | poll 300 10 "topic gone from the list" _topic; deleted sns-topic "$TOPIC_ARN" |
| 2303 | fi |
| 2304 | ``` |
| 2305 | |
| 2306 | ### 10.8 Verify: every record classified, then the tag index as a cross-check |
| 2307 | |
| 2308 | ```sh |
| 2309 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 2310 | need RUN |
| 2311 | echo "== confirmed creations without a confirmed deletion:" |
| 2312 | awk -F'\t' ' |
| 2313 | $2 ~ /^DELETED / {split($2, a, " "); d[substr($2, length("DELETED " a[2] " ") + 1)] = 1} |
| 2314 | $2 ~ /^CONFIRMED / {split($2, a, " "); c[substr($2, length("CONFIRMED " a[2] " ") + 1)] = a[2]} |
| 2315 | END {for (k in c) if (!(k in d)) print c[k], k}' "$JOURNAL" | sort |
| 2316 | echo "== VMs: recorded, and how each ended:" |
| 2317 | vm_ids |
| 2318 | for id in $VIDS; do grep -q "VMGONE $id " "$JOURNAL" || die "VM $id has no confirmed end"; done |
| 2319 | echo "$(wc -w <<<"$VIDS") VMs recorded, every one confirmed ended" |
| 2320 | echo "== intents without a confirmation:" |
| 2321 | awk -F'\t' '$2 ~ /^INTENT /' "$JOURNAL" |
| 2322 | echo "== tag index (lags; direct reads above decide):" |
| 2323 | for k in run purpose; do v=$([ "$k" = run ] && echo "$RUN" || echo "$TAGV") |
| 2324 | aws resourcegroupstaggingapi get-resources --tag-filters Key=$k,Values=$v --query 'ResourceTagMappingList[].ResourceARN' --output text | tr '\t' '\n'; done |
| 2325 | ``` |
| 2326 | |
| 2327 | - Expected: the first list holds only values that are not resources (the run's settings: `DIGEST`, |
| 2328 | `VER_*`, `CONN_VERSION`, `CONN_QARN`, `BASE_*`, tokens, times, results); every resource ID has a |
| 2329 | `DELETED` line. Every recorded VM has a confirmed end. Each intent has its confirmation (or, for |
| 2330 | `vm` intents, a VM ID or a recorded refusal). The tag index lists nothing with `run=<RUN>`, or |
| 2331 | only ARNs already confirmed deleted above ("index lag"); with `purpose`, only what 0.4 already |
| 2332 | observed. An ARN that is neither goes to Paul untouched. |
| 2333 | |
| 2334 | ### 10.9 Evidence into the progress file, then remove scratch |
| 2335 | |
| 2336 | ```sh |
| 2337 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh" |
| 2338 | ! ctl_alive || die "the controller is running"; listeners; [ -z "$LST" ] || die "listeners open: $LST" |
| 2339 | _u=$(run_units) || die "systemctl cannot list the run's units" |
| 2340 | for _x in $_u; do [ "$(unit_state "$_x")" = done ] || die "unit $_x is not done; run S.0"; done |
| 2341 | no_unresolved |
| 2342 | cut -f2- "$JOURNAL" | grep -vE '^(INTENT|CONTROLLER) ' > "$T17/journal-for-progress.txt" |
| 2343 | wc -l "$T17/journal-for-progress.txt" "$VMS" |
| 2344 | echo "== every FINDING (the report lists each one):" |
| 2345 | awk -F'\t' '$2 ~ /^FINDING / {print $1, substr($2, 9)}' "$JOURNAL" | tee "$T17/findings.txt" |
| 2346 | ``` |
| 2347 | |
| 2348 | Paste `journal-for-progress.txt`, `vms.tsv`, the Task 17b record lines (section 11.3) and section |
| 2349 | 11.2's estimate into |
| 2350 | `HOSTED-SLICE1-PROGRESS.md` (they hold IDs, times and results only, no keys), then: |
| 2351 | |
| 2352 | ```sh |
| 2353 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; no_unresolved; need RUN RUN_RESERVATION |
| 2354 | [ "$RUN_RESERVATION" = "$HOME/.cache/t17b-runs/$RUN" ] || die "unexpected reservation path [$RUN_RESERVATION]" |
| 2355 | rmdir -- "$RUN_RESERVATION"; rmdir -- "$HOME/.cache/t17b-runs" 2>/dev/null || true |
| 2356 | rm -rf "$TMPDIR/equipo-t17b" "$TMPDIR/equipo-t17b-pre"; [ ! -e "$TMPDIR/equipo-t17b" ] && echo "reservation and scratch removed" |
| 2357 | ``` |
| 2358 | |
| 2359 | --- |
| 2360 | |
| 2361 | ## S. Safe stop |
| 2362 | |
| 2363 | Run in this order after any abort: S.0, S.1, S.2, S.3, S.4. Each part is safe to run whatever |
| 2364 | phase the run reached. |
| 2365 | |
| 2366 | **S.0 Emergency stop of the run's units (local only, no AWS call; always first).** |
| 2367 | `env.sh` refuses to load while a block unit is unfinished, so after an abort the safe stop cannot |
| 2368 | start from it. S.0 runs before `env.sh`, using only `run.env`, `unitctl.sh` and the journal (no AWS |
| 2369 | call). It acts only on unit names this run journalled (`UNIT` lines, written before each |
| 2370 | `systemd-run`; R45), in this order: first the block units (and the probe), stopped and proved done; |
| 2371 | then, from a fresh read of the journal (a block may have started a controller meanwhile), the |
| 2372 | controller units, stopped and proved done; then a final inventory of every journalled unit plus a |
| 2373 | cross-check of `systemctl --user list-units --all 't17b-<RUN>-*'`. A stop is `systemctl --user stop` |
| 2374 | (TERM, then KILL after 45 s, reaped by systemd); done means inactive or gone with an empty cgroup. |
| 2375 | A unit that matches the glob but was not journalled is reported for Paul and never stopped. Each |
| 2376 | outcome is an `EMERGENCY` journal line. S.0 marks a stopped block `emergency-stopped`, so `env.sh` |
| 2377 | loads again, and only then may S.1 to S.3 run. If it cannot read the journal, prove a unit done, list |
| 2378 | the units, or finds an unjournalled match, it prints `HARD STOP` with the unit names: stop there and |
| 2379 | report them to Paul. Nothing is signalled by PID. |
| 2380 | |
| 2381 | ```sh |
| 2382 | set -euo pipefail |
| 2383 | T17='<T17 printed by 0.2>' |
| 2384 | [ -f "$T17/run.env" ] && [ -f "$T17/unitctl.sh" ] && [ -f "$T17/journal.tsv" ] || { echo "HARD STOP: $T17/run.env, unitctl.sh or journal.tsv is missing; nothing was stopped. Tell Paul."; exit 1; } |
| 2385 | . "$T17/run.env"; . "$T17/unitctl.sh" |
| 2386 | ej() { printf '%s\t%s\n' "$(date -u +%FT%T.%3NZ)" "EMERGENCY $*" >> "$T17/journal.tsv" || echo "WARNING: journal write failed"; echo "$*"; } |
| 2387 | bad="" |
| 2388 | # stop_set KIND UNIT...: stop and prove done each journalled unit that is not already done. |
| 2389 | stop_set() { local kind=$1 u s; shift |
| 2390 | for u; do |
| 2391 | s=$(unit_state "$u"); [ "$s" != done ] || continue |
| 2392 | ej "$kind unit $u is $s: stopping it" |
| 2393 | if unit_stop "$u"; then ej "$kind unit $u: inactive or gone, with an empty cgroup" |
| 2394 | else s=$(unit_state "$u"); ej "$kind unit $u could not be proved stopped: $s"; bad="$bad $u($s)"; fi |
| 2395 | done; } |
| 2396 | rec=$(journal_units) || { echo "HARD STOP: the journal's unit records cannot be read; nothing was stopped. Tell Paul."; exit 1; } |
| 2397 | # 1. Block units (and the probe): every journalled unit that is not a controller unit. |
| 2398 | stop_set block $(grep -v -- "^${UNIT_PREFIX}ctl-" <<<"$rec" || true) |
| 2399 | # 2. Controller units, from a fresh read of the journal. |
| 2400 | rec=$(journal_units) || { echo "HARD STOP: the journal's unit records cannot be read after the block stops. Tell Paul."; exit 1; } |
| 2401 | stop_set controller $(grep -- "^${UNIT_PREFIX}ctl-" <<<"$rec" || true) |
| 2402 | for f in "$T17"/blocks/*.unit; do |
| 2403 | [ -e "$f" ] || continue; b=$(basename "${f%.unit}") |
| 2404 | st=$(cat "$T17/blocks/$b.status" 2>/dev/null || true) |
| 2405 | if { [ -z "$st" ] || [ "$st" = unresolved ]; } && [ "$(unit_state "$(cat "$f")")" = done ]; then |
| 2406 | printf 'emergency-stopped\n' > "$T17/blocks/$b.status"; ej "block $b: marked emergency-stopped" |
| 2407 | fi |
| 2408 | done |
| 2409 | # 3. Final inventory: every journalled unit done; the glob is a cross-check only. |
| 2410 | if rec=$(journal_units); then |
| 2411 | for u in $rec; do s=$(unit_state "$u"); [ "$s" = done ] || { ej "inventory: $u is $s"; bad="$bad $u($s)"; }; done |
| 2412 | else ej "inventory: the journal's unit records cannot be read"; bad="$bad journal-unreadable"; rec=""; fi |
| 2413 | if listed=$(run_units); then |
| 2414 | for u in $listed; do |
| 2415 | grep -qxF -- "$u" <<<"$rec" && continue |
| 2416 | ej "inventory: $u matches ${UNIT_PREFIX}* but this run never journalled it: not stopped, for Paul"; bad="$bad $u(not-journalled)" |
| 2417 | done |
| 2418 | else ej "inventory: systemctl cannot list ${UNIT_PREFIX}*"; bad="$bad unit-listing-failed"; fi |
| 2419 | if [ -n "$bad" ]; then echo "HARD STOP:$bad. Report these unit names to Paul; do not run S.1 to S.3."; exit 1; fi |
| 2420 | ej "S.0 done: every journalled unit of this run is inactive or gone with an empty cgroup, and no other unit matches ${UNIT_PREFIX}*" |
| 2421 | echo "S.0 done; run S.1 to S.3" |
| 2422 | ``` |
| 2423 | |
| 2424 | **S.1 Controller.** |
| 2425 | |
| 2426 | ```sh |
| 2427 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh" |
| 2428 | stop_ctl |
| 2429 | ``` |
| 2430 | |
| 2431 | If `stop_ctl` aborts because the controller's unit cannot be proved done, or a port stays open |
| 2432 | after it is, stop here and ask Paul. Nothing is signalled by PID. |
| 2433 | |
| 2434 | **S.2 Reconcile uncertain creations (R39).** For each creation whose `INTENT` has no `CONFIRMED` |
| 2435 | record, one direct, guarded read decides. A resource created with a run-unique name (the run ID, |
| 2436 | proved absent by 0.4) and found by that exact name is ours: it is recorded, tagged if a separate |
| 2437 | tagging call never ran, and torn down. The unnamed EC2 resources carried their tags in the create |
| 2438 | call (`TagSpecifications`) and are found by a direct `describe` filtered on the `run` tag and their |
| 2439 | `Name` tag, never through the tag index. Each read has exactly three outcomes: success (record), |
| 2440 | an empty list or an approved not-found code (`NOTCREATED`), or anything else (`UNRESOLVED`: that resource's |
| 2441 | reconciliation stops and it goes to Paul with its cost in S.4). The MicroVM intents are reconciled |
| 2442 | by S.3. |
| 2443 | |
| 2444 | ```sh |
| 2445 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard |
| 2446 | need RUN NAME SG_NAME OPERATOR_ROLE BUILD_ROLE CONN_NAME IMAGE_NAME BUCKET LOG_GROUP TOPIC_NAME TAGS_EC2 |
| 2447 | UNRES="" |
| 2448 | unresolved() { jw "UNRESOLVED $*"; UNRES="$UNRES|$*"; echo "UNRESOLVED: $*"; } |
| 2449 | absent() { jw "NOTCREATED $*"; echo "not created: $*"; } |
| 2450 | pending() { awk -F'\t' -v k="INTENT $1 $2" 'index($2, k) == 1 {f = 1} END {exit !f}' "$JOURNAL" && [ -z "${!3:-}" ]; } |
| 2451 | # one_ec2 KIND VAR CMD...: a describe that must list 0 or 1 IDs. |
| 2452 | one_ec2() { local kind=$1 var=$2; shift 2; try "$@" |
| 2453 | if [ "$RC" != 0 ]; then unresolved "$kind lookup failed: ${ECODE:-rc$RC}"; return; fi |
| 2454 | case "$(wc -w <<<"$OUT")" in 0) absent "$kind";; 1) rec "$var" "$OUT";; *) unresolved "$kind: several match: $OUT";; esac; } |
| 2455 | # one_def KIND VAR CMD...: a VPC default resource; it exists whenever the VPC does, so only exactly one is an answer. |
| 2456 | one_def() { local kind=$1 var=$2; shift 2; try "$@" |
| 2457 | if [ "$RC" = 0 ] && [ "$(wc -w <<<"$OUT")" = 1 ]; then rec "$var" "$OUT"; else unresolved "$kind: rc $RC ${ECODE:-} [$OUT]"; fi; } |
| 2458 | |
| 2459 | if pending vpc "tag:run=$RUN" VPC; then one_ec2 vpc VPC aws ec2 describe-vpcs --filters Name=tag:run,Values="$RUN" Name=tag:Name,Values="$NAME" --query 'Vpcs[].VpcId' --output text; fi |
| 2460 | if [ -n "${VPC:-}" ] && [ -z "${DEF_SG_RULES:-}" ]; then |
| 2461 | [ -n "${DEF_SG:-}" ] || one_def vpc-default-security-group DEF_SG aws ec2 describe-security-groups --filters Name=vpc-id,Values="$VPC" Name=group-name,Values=default --query 'SecurityGroups[].GroupId' --output text |
| 2462 | [ -n "${MAIN_RTB:-}" ] || one_def vpc-main-route-table MAIN_RTB aws ec2 describe-route-tables --filters Name=vpc-id,Values="$VPC" Name=association.main,Values=true --query 'RouteTables[].RouteTableId' --output text |
| 2463 | [ -n "${DEF_ACL:-}" ] || one_def vpc-default-network-acl DEF_ACL aws ec2 describe-network-acls --filters Name=vpc-id,Values="$VPC" Name=default,Values=true --query 'NetworkAcls[].NetworkAclId' --output text |
| 2464 | if [ -n "${DEF_SG:-}" ] && [ -n "${MAIN_RTB:-}" ] && [ -n "${DEF_ACL:-}" ]; then |
| 2465 | try aws ec2 describe-security-group-rules --filters Name=group-id,Values="$DEF_SG" --query 'SecurityGroupRules[].SecurityGroupRuleId' --output text |
| 2466 | if [ "$RC" = 0 ] && [ -n "$OUT" ]; then rec DEF_SG_RULES "$OUT" |
| 2467 | try aws ec2 create-tags --resources "$DEF_SG" "$MAIN_RTB" "$DEF_ACL" $DEF_SG_RULES --tags $TAGS_EC2 |
| 2468 | [ "$RC" = 0 ] || unresolved "vpc defaults: tagging failed: ${ECODE:-rc$RC}" |
| 2469 | else unresolved "vpc default security group rules: ${ECODE:-rc$RC}"; fi |
| 2470 | fi |
| 2471 | fi |
| 2472 | if pending subnet "tag:run=$RUN" SUBNET; then one_ec2 subnet SUBNET aws ec2 describe-subnets --filters Name=tag:run,Values="$RUN" Name=tag:Name,Values="$NAME-vm" --query 'Subnets[].SubnetId' --output text; fi |
| 2473 | if pending route-table "tag:run=$RUN" RTB; then one_ec2 route-table RTB aws ec2 describe-route-tables --filters Name=tag:run,Values="$RUN" Name=tag:Name,Values="$NAME-vm" --query 'RouteTables[].RouteTableId' --output text; fi |
| 2474 | if pending route-table-association "" RTB_ASSOC && [ -n "${RTB:-}" ] && [ -n "${SUBNET:-}" ]; then |
| 2475 | one_ec2 route-table-association RTB_ASSOC aws ec2 describe-route-tables --route-table-ids "$RTB" --query "RouteTables[0].Associations[?SubnetId=='$SUBNET'].RouteTableAssociationId" --output text; fi |
| 2476 | if pending security-group "$SG_NAME" SG; then one_ec2 security-group SG aws ec2 describe-security-groups --filters Name=tag:run,Values="$RUN" Name=group-name,Values="$SG_NAME" --query 'SecurityGroups[].GroupId' --output text; fi |
| 2477 | for pair in "$OPERATOR_ROLE:OPERATOR_ROLE_ARN" "$BUILD_ROLE:BUILD_ROLE_ARN"; do |
| 2478 | r=${pair%%:*}; v=${pair#*:} |
| 2479 | pending iam-role "$r" "$v" || continue |
| 2480 | try aws iam get-role --role-name "$r" --output json |
| 2481 | if [ "$RC" = 0 ]; then arn=$(jq -r .Role.Arn <<<"$OUT"); arn_ok "$arn"; rec "$v" "$arn" |
| 2482 | if ! jq -e --arg r "$RUN" 'any(.Role.Tags[]?; .Key == "run" and .Value == $r)' <<<"$OUT" >/dev/null; then |
| 2483 | try aws iam tag-role --role-name "$r" --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN; [ "$RC" = 0 ] || unresolved "iam-role $r: tagging failed: ${ECODE:-rc$RC}"; fi |
| 2484 | elif code_in NoSuchEntity; then absent "iam-role $r" |
| 2485 | else unresolved "iam-role $r: ${ECODE:-rc$RC}"; fi |
| 2486 | done |
| 2487 | if pending connector "$CONN_NAME" CONN_ARN; then |
| 2488 | lvr connector get -id "$CONN_NAME" |
| 2489 | if [ "$RC" = 0 ] && [ "$(jq -r .Name <<<"$OUT")" = "$CONN_NAME" ]; then arn=$(jq -r .Arn <<<"$OUT"); arn_ok "$arn"; rec CONN_ARN "$arn"; rec CONN_ID "$(jq -r .Id <<<"$OUT")" |
| 2490 | elif code_in ResourceNotFoundException; then absent "connector $CONN_NAME" |
| 2491 | else unresolved "connector $CONN_NAME: ${ECODE:-rc$RC}"; fi |
| 2492 | fi |
| 2493 | if pending s3-bucket "$BUCKET" BUCKET_CREATED; then |
| 2494 | try aws s3api list-buckets --prefix "$BUCKET" --query "length(Buckets[?Name=='$BUCKET'])" --output json |
| 2495 | if [ "$RC" != 0 ]; then unresolved "s3-bucket $BUCKET: list failed: ${ECODE:-rc$RC}" |
| 2496 | elif [ "$OUT" = 1 ]; then rec BUCKET_CREATED "$BUCKET" |
| 2497 | try aws s3api get-bucket-tagging --bucket "$BUCKET" --query "TagSet[?Key=='run'].Value" --output text |
| 2498 | if [ "$RC" = 0 ] && [ "$OUT" = "$RUN" ]; then : |
| 2499 | elif [ "$RC" = 0 ] || code_in NoSuchTagSet; then |
| 2500 | try aws s3api put-public-access-block --bucket "$BUCKET" --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true |
| 2501 | [ "$RC" = 0 ] || unresolved "s3-bucket $BUCKET: public access block failed: ${ECODE:-rc$RC}" |
| 2502 | try aws s3api put-bucket-tagging --bucket "$BUCKET" --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]" |
| 2503 | [ "$RC" = 0 ] || unresolved "s3-bucket $BUCKET: tagging failed: ${ECODE:-rc$RC}" |
| 2504 | else unresolved "s3-bucket $BUCKET: tags unreadable: ${ECODE:-rc$RC}"; fi |
| 2505 | elif [ "$OUT" = 0 ]; then absent "s3-bucket $BUCKET" |
| 2506 | else unresolved "s3-bucket $BUCKET: listed $OUT times"; fi |
| 2507 | fi |
| 2508 | if pending log-group "$LOG_GROUP" LOG_GROUP_CREATED; then |
| 2509 | try aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text |
| 2510 | if [ "$RC" != 0 ]; then unresolved "log-group: ${ECODE:-rc$RC}" |
| 2511 | elif [ "$OUT" = "$LOG_GROUP" ]; then rec LOG_GROUP_CREATED "$LOG_GROUP" |
| 2512 | elif [ -z "$OUT" ]; then absent "log-group $LOG_GROUP" |
| 2513 | else unresolved "log-group: unexpected groups [$OUT]"; fi |
| 2514 | fi |
| 2515 | if pending s3-object "s3://$BUCKET/t17/app.zip" ARTIFACT; then |
| 2516 | need ARTIFACT_B64 |
| 2517 | if [ -z "${BUCKET_CREATED:-}" ]; then absent "s3-object (no bucket)"; OBJ=absent; RC=0; OUT="" |
| 2518 | else try aws s3api list-objects-v2 --bucket "$BUCKET" --prefix t17/app.zip --query 'length((Contents || `[]`)[?Key==`t17/app.zip`])' --output json |
| 2519 | if [ "$RC" != 0 ]; then unresolved "s3-object: list failed: ${ECODE:-rc$RC}"; OBJ=unknown |
| 2520 | elif [ "$OUT" = 0 ]; then absent "s3-object"; OBJ=absent |
| 2521 | else OBJ=listed; try aws s3api head-object --bucket "$BUCKET" --key t17/app.zip --checksum-mode ENABLED --query ChecksumSHA256 --output text; fi |
| 2522 | fi |
| 2523 | if [ "$OBJ" != listed ]; then : |
| 2524 | elif [ "$RC" = 0 ] && [ "$OUT" = "$ARTIFACT_B64" ]; then rec ARTIFACT "s3://$BUCKET/t17/app.zip" |
| 2525 | try aws s3api get-object-tagging --bucket "$BUCKET" --key t17/app.zip --query "TagSet[?Key=='run'].Value" --output text |
| 2526 | if [ "$RC" = 0 ] && [ "$OUT" != "$RUN" ]; then |
| 2527 | try aws s3api put-object-tagging --bucket "$BUCKET" --key t17/app.zip --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]" |
| 2528 | [ "$RC" = 0 ] || unresolved "s3-object: tagging failed: ${ECODE:-rc$RC}" |
| 2529 | elif [ "$RC" != 0 ]; then unresolved "s3-object: tags unreadable: ${ECODE:-rc$RC}"; fi |
| 2530 | elif [ "$RC" = 0 ]; then unresolved "s3-object: checksum $OUT is not $ARTIFACT_B64" |
| 2531 | else unresolved "s3-object: head failed: ${ECODE:-rc$RC}"; fi |
| 2532 | fi |
| 2533 | if pending microvm-image "$IMAGE_NAME" IMAGE_ARN; then |
| 2534 | lvr image list -name "$IMAGE_NAME" |
| 2535 | if [ "$RC" = 0 ]; then |
| 2536 | list_items || die "malformed image list reply in reconciliation" |
| 2537 | OUT=$(jq -r --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n) | .ImageArn] | join(" ")' <<<"$ITEMS") || die "image list items unreadable" |
| 2538 | fi |
| 2539 | if [ "$RC" != 0 ]; then unresolved "microvm-image $IMAGE_NAME: list failed: ${ECODE:-rc$RC}" |
| 2540 | elif [ -z "$OUT" ]; then absent "microvm-image $IMAGE_NAME" |
| 2541 | elif [ "$(wc -w <<<"$OUT")" != 1 ]; then unresolved "microvm-image $IMAGE_NAME: listed several: $OUT" |
| 2542 | else arn=$OUT |
| 2543 | [ "$arn" = "arn:aws:lambda:eu-west-1:$ACCOUNT:microvm-image:$IMAGE_NAME" ] || die "image ARN [$arn]" |
| 2544 | rec IMAGE_ARN "$arn" |
| 2545 | lvr image get -id "$IMAGE_ARN" |
| 2546 | if [ "$RC" = 0 ] && [ "$(jq -r '.Tags.run // empty' <<<"$OUT")" != "$RUN" ]; then |
| 2547 | finding "microvm-image: tags missing ($(jq -c .Tags <<<"$OUT")); livectl tags only at create" |
| 2548 | elif [ "$RC" != 0 ]; then finding "microvm-image: tags unreadable: ${ECODE:-rc$RC}"; fi |
| 2549 | fi |
| 2550 | fi |
| 2551 | if pending sns-topic "$TOPIC_NAME" TOPIC_ARN; then |
| 2552 | t="arn:aws:sns:eu-west-1:$ACCOUNT:$TOPIC_NAME" |
| 2553 | try aws sns list-topics --query "length(Topics[?TopicArn=='$t'])" --output json |
| 2554 | if [ "$RC" != 0 ]; then unresolved "sns-topic: list failed: ${ECODE:-rc$RC}" |
| 2555 | elif [ "$OUT" = 1 ]; then rec TOPIC_ARN "$t" |
| 2556 | try aws sns list-tags-for-resource --resource-arn "$t" --query "Tags[?Key=='run'].Value" --output text |
| 2557 | if [ "$RC" = 0 ] && [ "$OUT" != "$RUN" ]; then |
| 2558 | try aws sns tag-resource --resource-arn "$t" --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN; [ "$RC" = 0 ] || unresolved "sns-topic: tagging failed: ${ECODE:-rc$RC}" |
| 2559 | elif [ "$RC" != 0 ]; then unresolved "sns-topic: tags unreadable: ${ECODE:-rc$RC}"; fi |
| 2560 | elif [ "$OUT" = 0 ]; then absent "sns-topic $TOPIC_NAME" |
| 2561 | else unresolved "sns-topic: listed $OUT times"; fi |
| 2562 | fi |
| 2563 | [ -z "$UNRES" ] && echo "reconciliation complete: nothing unresolved" || { echo "unresolved, for Paul (S.4):"; tr '|' '\n' <<<"$UNRES"; } |
| 2564 | ``` |
| 2565 | |
| 2566 | The extra IAM call here (`tag-role`, only when a role exists without its tags) is one of the role |
| 2567 | calls R37 covers. Image versions are not reconciled: they go with the image, which livectl deletes |
| 2568 | whole. |
| 2569 | |
| 2570 | **S.3 VMs.** If the image was never created (no `IMAGE_ARN`, even after S.2), no VM can exist; the |
| 2571 | block records the skip and ends (skip-never-created rule). |
| 2572 | |
| 2573 | ```sh |
| 2574 | set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard |
| 2575 | if ! have IMAGE_ARN; then echo "no image was ever created, so no VM can exist"; exit 0; fi |
| 2576 | ! ctl_alive || die "the controller is running" |
| 2577 | settle_all |
| 2578 | sleep 120 |
| 2579 | settle_all |
| 2580 | ``` |
| 2581 | |
| 2582 | `settle_all` ends every recorded VM and every live VM an image-scoped List shows, accepts an end |
| 2583 | only as `TERMINATED` or two not-found reads at least 60 s apart, and finishes only after three |
| 2584 | consecutive scans 30 s apart show nothing live. The second run, at least 2 minutes after the |
| 2585 | controller stopped, covers the residual R21 accepts: a launch request AWS held after the client gave |
| 2586 | up can still create a VM late. A VM that appears even later is visible to any later scan of the |
| 2587 | image while the image exists, and its maximum duration (at most 1 hour for the drivers, 30 minutes |
| 2588 | for the orphan, 15 minutes for the contract) ends it. |
| 2589 | |
| 2590 | **S.4 What is left for Paul.** Everything else in the ledger stays in place, and the agent reports |
| 2591 | the ledger and this exposure: |
| 2592 | |
| 2593 | | Left in place | Cost while it stays | |
| 2594 | | --- | --- | |
| 2595 | | MicroVM image (one version, or two after a step down) | about $0.08 per GB-month (Ireland rate not printed), assumed 3 GB: about $0.24 a month; worst case 68 GB at the rate plus 20 %: about $6.53 a month; one-week minimum already paid | |
| 2596 | | Connector, VPC, subnet, route table, group, defaults | no listed charge (no NAT, gateway or Elastic IP) | |
| 2597 | | IAM roles, log group (1-day retention), SNS topic | none | |
| 2598 | | S3 bucket and one object under 10 MB | under $0.01 a month | |
| 2599 | | Anything S.2 marked `UNRESOLVED` | its row above; an unresolved image is the only one with a cost (storage), an unresolved MicroVM intent is covered by S.3's scans | |
| 2600 | | The run-ID reservation `$HOME/.cache/t17b-runs/<RUN>` (an empty directory on docs-t1) | none; 10.9 removes it | |
| 2601 | |
| 2602 | Teardown (section 10) then runs only on Paul's word, for the recorded resources only. |
| 2603 | |
| 2604 | --- |
| 2605 | |
| 2606 | ## 11. Spend |
| 2607 | |
| 2608 | ### 11.1 Estimate |
| 2609 | |
| 2610 | Rates: Ireland x86_64 compute from spec §10 ($0.155 an hour at 2 GB baseline; above-baseline use up |
| 2611 | to 4x costs extra). The pricing page prints snapshot and storage rates for US East only (write |
| 2612 | $0.0038 per GB, read $0.00155 per GB, storage $0.08 per GB-month, image storage with a one-week |
| 2613 | minimum); the worst case adds 20 % to those for Ireland. As in revision 5, one pause cycle is |
| 2614 | counted at $0.0057 per GB, and one week of image storage at $0.08 x 7/30 = $0.01867 per GB. The |
| 2615 | page lists no charge for image builds or connectors; the worst case still allows for builds billed |
| 2616 | as VM time (20 minutes at 4 GB, twice the 2 GB rate: $0.103 each). |
| 2617 | |
| 2618 | | Item | Expected | Worst case, every approved branch | |
| 2619 | | --- | --- | --- | |
| 2620 | | Contract VMs (6.1) | 1 VM for about 1 min (attempt 4: 13 to 52 s each): $0.01 | 2 VMs (the first, plus one if AWS ever answered the changed request with a new VM) at the contract's 15-min maximum: 0.5 h x $0.155 = $0.08 | |
| 2621 | | Controller VMs (7) | 2 VMs (sequence, crash) for about 5 min each: $0.03 | 2 at the driver's 1-h lifetime, plus one late R21 VM at 1 h: 3 h x $0.155 = $0.47 | |
| 2622 | | Orphan VM (8) | about 12 min: $0.03 | 1800 s: 0.5 h x $0.155 = $0.08 | |
| 2623 | | Above-baseline use | idle hook server, none expected: $0.00 | 4x on all 4.0 VM-hours, so 3 x 4.0 x $0.155 = $1.86 more | |
| 2624 | | Pause and resume | 1 cycle (7.2) at 2 GB: 2 x $0.0057 = $0.01 | 2 cycles (one spare, for a resent suspend) at 40 GB (8 GB memory, 32 GB disk), x1.2: 2 x 40 x $0.0057 x 1.2 = $0.55 | |
| 2625 | | Launch snapshot reads | about 4 starts and 1 resume at 2 GB: 5 x 2 x $0.00155 = $0.02 | 10 starts at 40 GB, x1.2: 10 x 40 x $0.00155 x 1.2 = $0.74 | |
| 2626 | | Image storage | 1 version, assumed 3 GB, one-week minimum: 3 x $0.01867 = $0.06 | 2 versions (Small, and a failed Small after the step down) at 34 GB: 68 x $0.01867 x 1.2 = $1.52 | |
| 2627 | | Image builds | 1 build of about 2 min (attempt 4: 1.8 min): $0.02 | 2 builds (the step down adds one): 2 x $0.103 = $0.21 | |
| 2628 | | S3, CloudWatch Logs, SNS, data transfer | tiny object, under 1 MB of logs, one publish, no route out: $0.02 | $0.05 | |
| 2629 | | **Total** | **about $0.20** ($0.01 + 0.03 + 0.03 + 0.00 + 0.01 + 0.02 + 0.06 + 0.02 + 0.02) | **about $5.55** (unrounded: 0.0775 + 0.465 + 0.0775 + 1.86 + 0.547 + 0.744 + 1.523 + 0.207 + 0.05 = $5.55; the rounded parts add to $5.56) | |
| 2630 | |
| 2631 | Worst-case VM time: 0.5 + 3.0 + 0.5 = 4.0 VM-hours, $0.62 at baseline. The worst case is the sum of |
| 2632 | every bound at once (every VM at its maximum, at 4x, with the largest snapshots and both builds), |
| 2633 | which cannot all happen in one run; it is under the $10 approval ceiling with $4.45 to spare. It is |
| 2634 | above the $5 self-stop only because the self-stop reads the run's own estimate (11.2), which counts |
| 2635 | measured VM time at baseline, not these bounds. Revision 5's worst case was about $9.70; this run |
| 2636 | drops the facts VMs (0.97 h), six of the eight contract VMs, the Large version and build, and two |
| 2637 | of three pause cycles. **Leftovers after an abort** are not in the total: retained image storage |
| 2638 | costs about $0.24 to $6.53 a month until teardown (S.4). |
| 2639 | |
| 2640 | ### 11.2 The run's own estimate (stop rule) |
| 2641 | |
| 2642 | Computed from the VM ledger and the journal at the end of every section, with no billing call. Each |
| 2643 | VM's life starts at the provider's `startedAt` (from the launch reply or any image-scoped scan); |
| 2644 | for a VM known only from a log, at the start of the phase that found it, which is earlier than its |
| 2645 | real start. It ends at the time its end was confirmed (`VMGONE`), which is later than its real end, |
| 2646 | or now if it has not ended. Both ends err on the long side, so the figure is an upper bound on VM |
| 2647 | time at baseline. A VM whose only start is a phase start is counted and listed as such. The fixed |
| 2648 | items are 11.1's expected figures: image storage $0.06 per version built, $0.02 per build, $0.02 |
| 2649 | of small items, two pause cycles at 2 GB ($0.0228), and one launch snapshot read at 2 GB ($0.0031) |
| 2650 | per recorded VM. |
| 2651 | |
| 2652 | ```sh |
| 2653 | set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh" |
| 2654 | python3 -I - "$VMS" "$JOURNAL" <<'EOF' |
| 2655 | import sys, datetime as dt |
| 2656 | def p(x): |
| 2657 | t = dt.datetime.fromisoformat(x.replace("Z", "+00:00")) |
| 2658 | if t.tzinfo is None or t.utcoffset() is None: raise ValueError(f"timestamp {x!r} has no time zone") |
| 2659 | return t |
| 2660 | now = dt.datetime.now(dt.timezone.utc) |
| 2661 | prov, phase, end = {}, {}, {} |
| 2662 | def bad(kind, n, line, why): |
| 2663 | sys.exit(f"ABORT: {kind} line {n} cannot be read ({why}): {line[:160]!r}") |
| 2664 | for n, line in enumerate(open(sys.argv[1]), 1): |
| 2665 | f = line.rstrip("\n").split("\t") |
| 2666 | if len(f) != 4: bad("VM ledger", n, line, f"{len(f)} fields, want 4") |
| 2667 | vid, src, start, _ = f |
| 2668 | if not vid: bad("VM ledger", n, line, "empty VM ID") |
| 2669 | try: |
| 2670 | if start.startswith("phase:"): |
| 2671 | t = p(start[6:]); phase[vid] = min(t, phase.get(vid, t)) |
| 2672 | else: |
| 2673 | t = p(start); prov[vid] = min(t, prov.get(vid, t)) |
| 2674 | except ValueError as e: bad("VM ledger", n, line, e) |
| 2675 | small = failed = False |
| 2676 | for n, line in enumerate(open(sys.argv[2]), 1): |
| 2677 | if "\t" not in line: bad("journal", n, line, "no tab") |
| 2678 | ts, msg = line.rstrip("\n").split("\t", 1) |
| 2679 | w = msg.split(" ") |
| 2680 | if w[0] == "VMGONE": |
| 2681 | if len(w) < 2 or not w[1]: bad("journal", n, line, "VMGONE without an ID") |
| 2682 | try: end[w[1]] = p(ts) |
| 2683 | except ValueError as e: bad("journal", n, line, e) |
| 2684 | if w[0] == "CONFIRMED" and len(w) > 1 and w[1] == "VER_SMALL": small = True |
| 2685 | if w[0] == "CONFIRMED" and len(w) > 1 and w[1] == "VER_SMALL_FAILED": failed = True |
| 2686 | versions = int(small) + int(failed) # each version stored is one build |
| 2687 | ids = set(prov) | set(phase) |
| 2688 | hours, phase_only = 0.0, [] |
| 2689 | for vid in ids: |
| 2690 | start = prov.get(vid) or phase[vid] |
| 2691 | if vid not in prov: phase_only.append(vid) |
| 2692 | hours += max(0.0, (end.get(vid, now) - start).total_seconds()) / 3600 |
| 2693 | live = [v for v in ids if v not in end] |
| 2694 | est = hours * 0.155 + (0.06 + 0.02) * versions + 0.02 + 0.0057 * 2 * 2 + 0.0031 * len(ids) |
| 2695 | print(f"VMs {len(ids)}, not yet ended {len(live)}, started from phase only {len(phase_only)} {phase_only}, " |
| 2696 | f"VM-hours {hours:.2f}, image versions {versions}, estimate ${est:.2f} " |
| 2697 | f"(baseline compute plus image storage, builds, small items, two pause cycles and one launch read per VM; " |
| 2698 | f"retained storage after an abort is separate)") |
| 2699 | sys.exit(3 if est >= 5 else 0) |
| 2700 | EOF |
| 2701 | ``` |
| 2702 | |
| 2703 | - `versions` is 1 once the Small version is recorded, and 2 after a step down (the failed version |
| 2704 | is kept until the image is deleted); each version is one build. |
| 2705 | - Stop rule: exit status 3 (estimate $5 or more), or a VM live outside its step, means the safe |
| 2706 | stop. A journal or VM ledger line that cannot be read ends the block with an `ABORT:` line naming |
| 2707 | it (exit status 1); the estimate is then made by hand from the ledger and reported as such. Paul |
| 2708 | reads the real bill himself (R33). |
| 2709 | |
| 2710 | ### 11.3 What goes into the progress file |
| 2711 | |
| 2712 | One line each: the `ChangedSpecConflicts` result (`CONTRACT_CSC`) with any FINDING text; the |
| 2713 | sequence attempt, its `timings:` line and its epochs; the crash attempt, the crash VM, the crash |
| 2714 | exit status, the recover result and the count of VMs started since the crash launch; the orphan |
| 2715 | VM, its plant time, its stop time relative to P, the alert result and the audit row counts; the |
| 2716 | interface counts at each snapshot; the 11.2 estimate at the end; every FINDING. |
| 2717 | |
| 2718 | **Wall-clock:** about 2 to 3 hours from 0.1 to 10.9. |
| 2719 | |
| 2720 | --- |
| 2721 | |
| 2722 | ## 12. UNCONFIRMED items and placeholders |
| 2723 | |
| 2724 | ### Settled by attempt 4 (no longer open) |
| 2725 | |
| 2726 | - **U4 and U5, base image and container base:** base `al2023-1` versions 4 and 3 were `AVAILABLE` |
| 2727 | with x86_64; `public.ecr.aws/lambda/microvms:al2023-minimal` built in about 1.8 minutes from |
| 2728 | version 4. 3.6 still picks the newest `AVAILABLE` x86_64 version and keeps the one-time step |
| 2729 | down, since AWS can publish a newer base at any time. |
| 2730 | - **U8, image deletion:** `image delete` worked and the image was gone from the list in about |
| 2731 | 1.5 minutes. |
| 2732 | - **U9 and the create half of U2, connector:** the managed operator policy plus the scoped delete |
| 2733 | was accepted on the first `CreateNetworkConnector`; ACTIVE after about 4.3 minutes; deleted in |
| 2734 | about 13 s with no `DELETE_FAILED`. |
| 2735 | - **U11, an unknown VM ref on terminate:** `StopUnknownRef` passed live; not run here. |
| 2736 | - **U12, the Date header:** present on GetMicrovm (`ResultMetadata.ServerTime`). |
| 2737 | - **U14 and U19, image versions:** versions carry the image's tags; the Small version stayed |
| 2738 | `SUCCESSFUL ACTIVE` after an update. This run makes no update unless it steps down. |
| 2739 | - **U17, MicroVM ID format:** `microvm-<uuid>`, 44 characters, inside R36's form. This plan's |
| 2740 | `VMID_RE` is built on it (change 4). |
| 2741 | - **U21, a qualified egress ARN on RunMicrovm:** accepted; the VM echoes `<conn>:1`. |
| 2742 | - **Client tokens:** the same request under a used token returns the same VM (also after the VM |
| 2743 | ended, at least 7 minutes on); a changed request gets `ValidationException` "The provided |
| 2744 | clientToken was used with different request parameters.", now mapped to `ErrConflict`. |
| 2745 | - **Resume on RUNNING, suspend on SUSPENDED:** both accepted as no-ops (not `ConflictException`); |
| 2746 | suspend about 2 s, resume about 4 s. |
| 2747 | - **Payload limit:** 4096 ASCII bytes accepted, 4097 refused. |
| 2748 | - **TERMINATED visibility:** Get and the image-scoped List still showed a terminated VM 6.5 minutes |
| 2749 | later. |
| 2750 | |
| 2751 | ### Still unconfirmed from revision 5, 4 |
| 2752 | |
| 2753 | 1. **U2, delete half.** Lambda's interface cleanup under the `ec2:ManagedResourceOperator` |
| 2754 | condition is still untested: attempt 4's connector never had interfaces in the run's subnet, |
| 2755 | even with VMs running. 10.2's pre-approved fallback drops that condition (keeping the subnet |
| 2756 | condition) and retries once; a second failure is a hard stop. |
| 2757 | 2. **U7, build log group.** Other groups under the prefix are never deleted; 10.6 stops for Paul |
| 2758 | (not in the ledger). |
| 2759 | 3. **U16, Ireland rates** for snapshots, launch reads and image storage: an estimate assumption. |
| 2760 | 4. **U18, the not-found code for a gone VM** (`ResourceNotFoundException`) is documented but was |
| 2761 | never observed: terminated VMs stayed visible as `TERMINATED` for at least 6.5 minutes, which |
| 2762 | `vm_end` accepts. It stays fail-closed only in `vm_end`. |
| 2763 | |
| 2764 | ### New for Task 17b, 9 |
| 2765 | |
| 2766 | 1. **The controller sequence live** (7.2): `to_running` (the reaper reads states once per 60 s |
| 2767 | pass), the drain and quiescent calls, suspend through the controller, the resume epoch (one |
| 2768 | above), and `stop_to_proof` (2 to 3 minutes, R17) are all unmeasured. Each difference is a |
| 2769 | FINDING. |
| 2770 | 2. **The crash point live** (7.3): that `os.Exit(137)` in the hostedlive build leaves the job |
| 2771 | `waiting` with no Ref, and that `start_ctl`'s wrapper records 137. First run. |
| 2772 | 3. **Replay of the crash intent** (7.4): expected to return the crash VM under the same client |
| 2773 | token, from the stored spec (identical maximum duration and payload). If AWS answered with the |
| 2774 | token-reuse `ValidationException` instead, the adapter would now map it to `ErrConflict` and the |
| 2775 | intent would not gain the VM; the VM would then be an orphan, and 7.4 records a FINDING and |
| 2776 | settles it. |
| 2777 | 4. **The orphan timeline** (8.2): first sighting, the 10-minute grace, the ownership recheck and |
| 2778 | the stop, live for the first time. A stop after P+15:00 is a hard stop (a VM alive outside its |
| 2779 | step). |
| 2780 | 5. **The first SNS publish** (8.2): no alert has ever been published live (a clean start sends |
| 2781 | none; see section 4). If `kass` cannot publish to the topic, the alert is counted as failed and |
| 2782 | kept queued, the reaper pass reports an error, and 8.2 records a FINDING; the orphan is still |
| 2783 | stopped, because the stop comes before the alert. |
| 2784 | 6. **`ChangedSpecConflicts` with the fix** (6.1): expected PASS. The mapping matches AWS's message |
| 2785 | text; if AWS changes that text, the subtest fails again as a FINDING. |
| 2786 | 7. **A controller config with one image version** (`small` only): accepted by the config check |
| 2787 | (`runner.go:141-151`) and covered by unit tests, but not yet run live. |
| 2788 | 8. **5.6's readiness gate:** now built from the metrics and rows a clean start writes (attempt 4 |
| 2789 | saw `network_audit_passing 1`, `reap_last_error 0` and no failure rows). The `provider_bound` |
| 2790 | row check is new; a database that was not fresh would fail it, which 0.2's new scratch rules |
| 2791 | out. |
| 2792 | 9. **Blocks and the controller as systemd user units (R44).** The coordinator found |
| 2793 | `systemctl --user` usable on docs-t1 (state `degraded`), with a child under `env -i` kept in the |
| 2794 | unit's cgroup and stopped with it; the plan writer's probes (units `t17b-probe-*`, `sleep` only) |
| 2795 | showed the same, plus KILL after `TimeoutStopSec`, exit status 137 and `signal:<name>` recorded by |
| 2796 | `ExecStopPost`, `--collect` removing ended units, and a unit started from inside a unit living on |
| 2797 | as its own unit. Not yet run with the real blocks, `go test` or the controller. 0.2's probe unit |
| 2798 | must pass before any AWS call; any later unit state that cannot be read is `unresolved`, and S.0 |
| 2799 | stops and proves every unit before cleanup. Since R45 each unit runs under `env -i` with an |
| 2800 | allowlist; the probes showed the program sees only those names. That the kass |
| 2801 | `credential_process`, `go test` and the controller work with that allowlist alone is not yet |
| 2802 | shown live: a missing variable would surface as a failed call (a FINDING or an abort), not a |
| 2803 | safety problem. |
| 2804 | |
| 2805 | ### Placeholders |
| 2806 | |
| 2807 | One per block: `<T17 printed by 0.2>`, the scratch path 0.2 prints, filled in by the executor in |
| 2808 | the sandbox-off blocks. `PIN_SHA` is `bf29344a8b6832dff425aafc1337d4883f6a894f`, written once, in 0.1. |
| 2809 | |
| 2810 | |