carlos / platform Public

hosts-used-scan-snapshot (#444): the hostname history scan lists each box with one find into a mktemp scratch file in /run (with -ignore_readdir_race) and pages that snapshot over SSM, keeping the sha256, length and line-count check over it, so a busy box whose SQLite -wal/-shm files come and go between commands can be scanned. The scratch file is removed by exact path after paging, on failure too; a failed snapshot command removes its own, and a detached timer removes the exact path after HOSTS_SCAN_EXPIRE (900 s) if its name never reached the scan. Tests: TestHostsUsedScanAWSPagesOneSnapshot (failed first with the old 'changed while it was paged'), TestHostsUsedScanAWSExpiresALostSnapshot. Astra round 1 READY AFTER FIXES, the one P2 fixed.

Squashed from hosts-used-scan-snapshot into main.
claude agent, operated by paul@keymail.dev 57aec0adf93b088b4ab41ea2e322f768e1b69484 parent 7de0f08
4 files changed, +329 −41
  • cmd/console/hostsused_scan_test.go +122 −10
  • docs/superpowers/reviews/CODEX-FINDINGS-hosts-used-scan-snapshot.md +15 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-hosts-used-scan-snapshot.md +77 −0
  • scripts/hosts-used-scan-aws.sh +115 −31

CI passed — run details

diff --git a/cmd/console/hostsused_scan_test.go b/cmd/console/hostsused_scan_test.go
index d2b596162..16089b5ef 100644
--- a/cmd/console/hostsused_scan_test.go
+++ b/cmd/console/hostsused_scan_test.go
@@ -21,6 +21,7 @@ import (
"strconv"
"strings"
"testing"
+ "time"
boxlayout "github.com/carlosframework/platform/internal/layout"
"github.com/carlosframework/platform/internal/provision"
@@ -51,6 +52,9 @@ type fakeInstance struct {
// Break replaces one tool the box's script runs with one that fails
// after writing part of its output.
Break string `json:"break"`
+ // Lose runs this instance's nth command but loses its result, which
+ // reads as TimedOut with no output.
+ Lose int `json:"lose"`
}
// fakeAWS is the fake aws CLI. It logs every call's arguments, one JSON
@@ -161,7 +165,8 @@ func fakeSendCommand(dir string, cfg fakeAWSConfig, opts map[string]string) int
return 99
}
n := fakeCounter(dir, "commands")
- if mine := fakeCounter(dir, "commands-"+opts["--instance-ids"]); inst.GrowDir != "" && (inst.GrowAt == 0 || mine == inst.GrowAt) {
+ mine := fakeCounter(dir, "commands-"+opts["--instance-ids"])
+ if inst.GrowDir != "" && (inst.GrowAt == 0 || mine == inst.GrowAt) {
os.WriteFile(filepath.Join(inst.GrowDir, fmt.Sprintf("grow-%d.example.com.db", n)), nil, 0o600)
}
var stdout, stderr strings.Builder
@@ -182,6 +187,9 @@ func fakeSendCommand(dir string, cfg fakeAWSConfig, opts map[string]string) int
}
}
out := stdout.String()
+ if inst.Lose == mine {
+ code, status, out = 1, "TimedOut", ""
+ }
limit := 24000
if inst.Truncate > 0 {
limit = inst.Truncate
@@ -228,6 +236,7 @@ func fakeCounter(dir, name string) int {
type scanWorld struct {
t *testing.T
dir, fake string
+ run string // the boxes' scratch directory, standing in for /run
env []string
coordsPath string
cfg fakeAWSConfig
@@ -246,11 +255,11 @@ func newScanWorld(t *testing.T) *scanWorld {
t.Fatal(err)
}
dir := t.TempDir()
- w := &scanWorld{t: t, dir: dir, fake: filepath.Join(dir, "fake"),
+ w := &scanWorld{t: t, dir: dir, fake: filepath.Join(dir, "fake"), run: filepath.Join(dir, "run"),
cfg: fakeAWSConfig{Buckets: map[string]fakeBucket{}, Instances: map[string]fakeInstance{}},
coordinates: map[string]map[string]string{}}
bin := filepath.Join(dir, "bin")
- for _, d := range []string{bin, w.fake} {
+ for _, d := range []string{bin, w.fake, w.run} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
@@ -260,7 +269,7 @@ func newScanWorld(t *testing.T) *scanWorld {
}
w.coordsPath = filepath.Join(dir, "coords.json")
w.env = []string{"PATH=" + bin + string(os.PathListSeparator) + os.Getenv("PATH"), "FAKE_AWS_DIR=" + w.fake,
- "HOSTS_SCAN_POLL=0", "HOSTS_SCAN_WAIT=30", "TMPDIR=" + dir}
+ "HOSTS_SCAN_POLL=0", "HOSTS_SCAN_WAIT=30", "HOSTS_SCAN_RUNDIR=" + w.run, "HOSTS_SCAN_EXPIRE=60", "TMPDIR=" + dir}
return w
}
@@ -354,6 +363,20 @@ func (w *scanWorld) calls() [][]string {
return out
}
+// leftovers is every scratch listing still on the boxes' scratch directory.
+func (w *scanWorld) leftovers() []string {
+ w.t.Helper()
+ ents, err := os.ReadDir(w.run)
+ if err != nil {
+ w.t.Fatal(err)
+ }
+ var out []string
+ for _, e := range ents {
+ out = append(out, e.Name())
+ }
+ return out
+}
+
func writeJSON(t *testing.T, path string, v any) {
t.Helper()
b, err := json.Marshal(v)
@@ -508,8 +531,9 @@ func TestHostsUsedScanAWSActivates(t *testing.T) {
// TestHostsUsedScanAWSFailsATargetClosed: each failure gives its target one
// ok:false line with the reason and no entries, the other targets are still
-// scanned, and the scan exits 1. A listing that changed between pages is
-// scanned again, up to three times.
+// scanned, and the scan exits 1. A box that changes between SSM commands is
+// still listed in full, from the one snapshot its first command took
+// (#444). No snapshot is left on any box, whatever failed.
func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
w := newScanWorld(t)
w.bucket("bucket:ok", "instances", "instances/a.example.com/x", "moves/b.example.com/y", "seeds/c.example.com/z")
@@ -537,7 +561,7 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
w.cfg.Buckets["malformed-"+m] = fakeBucket{Malformed: m}
malformed = append(malformed, "bucket:malformed-"+m)
}
- for i, tool := range []string{"gzip", "sha256sum", "wc"} {
+ for i, tool := range []string{"gzip", "sha256sum", "wc", "find"} {
inst := fmt.Sprintf("i-0b%d", i)
w.box("box:broken-"+tool, inst, "shop.example.com.db")
w.cfg.Instances[inst] = fakeInstance{Break: tool}
@@ -545,7 +569,7 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
roster := map[string]any{"targets": []string{"bucket:ok", "bucket:denied", "bucket:page2", "bucket:noprefix", "bucket:nocoords",
"box:okbox", "box:unsent", "box:nodir", "box:cut", "box:grows", "box:grows-once", "box:badinst", "box:nocoords", "pool:p1",
- "box:broken-gzip", "box:broken-sha256sum", "box:broken-wc"}}
+ "box:broken-gzip", "box:broken-sha256sum", "box:broken-wc", "box:broken-find"}}
roster["targets"] = append(roster["targets"].([]string), malformed...)
rosterPath := filepath.Join(w.dir, "roster.json")
writeJSON(t, rosterPath, roster)
@@ -554,7 +578,7 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
t.Fatalf("scan exit %d, want 1\n%s", code, stderr)
}
ls := byTarget(got)
- if want := 17 + len(malformedPages); len(got) != want || len(ls) != want {
+ if want := 18 + len(malformedPages); len(got) != want || len(ls) != want {
t.Fatalf("want one line for each of %d targets, got %d: %+v", want, len(got), got)
}
expect := func(target, want string) {
@@ -573,6 +597,7 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
"bucket:ok": "",
"box:okbox": "",
"box:grows-once": "",
+ "box:grows": "",
"bucket:denied": "AccessDenied",
"bucket:page2": "AccessDenied",
"bucket:noprefix": "no prefix for bucket:noprefix",
@@ -580,13 +605,13 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
"box:unsent": "InvalidInstanceId",
"box:nodir": "Failed (exit 3)",
"box:cut": "cut short",
- "box:grows": "changed while it was paged",
"box:badinst": "is not an instance id",
"box:nocoords": "no instance for box:nocoords",
"pool:p1": "does not know this kind of target",
"box:broken-gzip": "does not decode",
"box:broken-sha256sum": "Failed (exit 6)",
"box:broken-wc": "Failed (exit 6)",
+ "box:broken-find": "Failed (exit 4)",
} {
expect(target, want)
}
@@ -598,6 +623,93 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) {
t.Errorf("a bad instance id reached aws: %q", c)
}
}
+ if left := w.leftovers(); len(left) != 0 {
+ t.Errorf("scratch listings left on the boxes: %q", left)
+ }
+}
+
+// TestHostsUsedScanAWSPagesOneSnapshot (#444): on a busy box, files come
+// and go between SSM commands (SQLite -wal and -shm files on annie-welding),
+// so a listing re-taken for every page never matched itself across about
+// 23 pages and the box could not be scanned. Now the box runs find once
+// into a scratch file, and every page is cut from that file: the listing
+// is ok, and it is the directory as that one find saw it. The scratch file
+// is removed afterwards, also when a page fails.
+func TestHostsUsedScanAWSPagesOneSnapshot(t *testing.T) {
+ w := newScanWorld(t)
+ var paths []string
+ for i := range 40 {
+ paths = append(paths, fmt.Sprintf("app-%02d.example.com.db", i))
+ }
+ d := w.box("box:busy", "i-0c1", paths...)
+ w.cfg.Instances["i-0c1"] = fakeInstance{GrowDir: d} // a new file before every command
+ w.box("box:cut", "i-0c2", paths...)
+ w.cfg.Instances["i-0c2"] = fakeInstance{Truncate: 110}
+ rosterPath := filepath.Join(w.dir, "roster.json")
+ writeJSON(t, rosterPath, map[string]any{"targets": []string{"box:busy", "box:cut"}})
+ got, stderr, code := w.scan(rosterPath, "HOSTS_SCAN_PAGE=64")
+ if code != 1 {
+ t.Fatalf("scan exit %d, want 1 for box:cut alone\n%s", code, stderr)
+ }
+ ls := byTarget(got)
+ busy := ls["box:busy"]
+ if !busy.OK || busy.Error != "" {
+ t.Fatalf("box:busy: %+v\n%s", busy, stderr)
+ }
+ for _, p := range paths {
+ if !slices.Contains(busy.Entries, p) {
+ t.Errorf("box:busy is missing %q", p)
+ }
+ }
+ grown := 0
+ for _, e := range busy.Entries {
+ if strings.HasPrefix(e, "grow-") {
+ grown++
+ }
+ }
+ sends := 0
+ for _, c := range w.calls() {
+ if slices.Contains(c, "send-command") && slices.Contains(c, "i-0c1") {
+ sends++
+ }
+ }
+ // The first command's file is in the snapshot; the ones made before
+ // every later page are not.
+ if grown != 1 || sends < 4 {
+ t.Errorf("box:busy has %d grown files over %d commands, want exactly the 1 its snapshot saw over several pages", grown, sends)
+ }
+ if cut := ls["box:cut"]; cut.OK || !strings.Contains(cut.Error, "cut short") {
+ t.Errorf("box:cut: %+v, want ok:false, cut short", cut)
+ }
+ if left := w.leftovers(); len(left) != 0 {
+ t.Errorf("scratch listings left on the boxes: %q", left)
+ }
+}
+
+// TestHostsUsedScanAWSExpiresALostSnapshot (#444, Astra round 1 P2): when
+// the first command's result is lost, the scan never learns the scratch
+// file's name and cannot remove it, so the box removes that exact path
+// itself once HOSTS_SCAN_EXPIRE runs out. The target fails.
+func TestHostsUsedScanAWSExpiresALostSnapshot(t *testing.T) {
+ w := newScanWorld(t)
+ w.box("box:lost", "i-0d1", "shop.example.com.db")
+ w.cfg.Instances["i-0d1"] = fakeInstance{Lose: 1}
+ rosterPath := filepath.Join(w.dir, "roster.json")
+ writeJSON(t, rosterPath, map[string]any{"targets": []string{"box:lost"}})
+ got, stderr, code := w.scan(rosterPath, "HOSTS_SCAN_EXPIRE=5")
+ if l := byTarget(got)["box:lost"]; code != 1 || l.OK || !strings.Contains(l.Error, "TimedOut") {
+ t.Fatalf("box:lost: exit %d, %+v\n%s", code, l, stderr)
+ }
+ if left := w.leftovers(); len(left) != 1 {
+ t.Fatalf("want the lost snapshot still on the box before it expires, got %q", left)
+ }
+ deadline := time.Now().Add(30 * time.Second)
+ for len(w.leftovers()) != 0 && time.Now().Before(deadline) {
+ time.Sleep(200 * time.Millisecond)
+ }
+ if left := w.leftovers(); len(left) != 0 {
+ t.Errorf("the lost snapshot did not expire: %q", left)
+ }
}
// TestHostsUsedScanAWSPrefixInPlainFormOnly (Paul's cut on discussion 438):
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-hosts-used-scan-snapshot.md b/docs/superpowers/reviews/CODEX-FINDINGS-hosts-used-scan-snapshot.md
new file mode 100644
index 000000000..e6cbcf9ce
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-hosts-used-scan-snapshot.md
@@ -0,0 +1,15 @@
+No P1 findings.
+
+- **P2 — Brief §3, cleanup: a completed snapshot can lose its cleanup owner.** The remote command disables its removal trap before returning the first page ([scripts/hosts-used-scan-aws.sh:225](scripts/hosts-used-scan-aws.sh#L225)). The caller records `pending` only after receiving and validating the filename ([line 314](scripts/hosts-used-scan-aws.sh#L314)); an initial SSM failure returns before that ([line 304](scripts/hosts-used-scan-aws.sh#L304)).
+
+ **Failure scenario:** the snapshot completes, but polling fails, times out, or the operator interrupts before its header is processed. Neither side removes the file. A truncated or invalid first header also loses the filename. These paths leave roughly 500 KB of root-only tmpfs data per attempt; they do not compromise listing integrity, but repeated attempts accumulate files. Explicit cleanup failures also leave files, although those produce a warning.
+
+ **Fix:** give each snapshot bounded remote expiry that removes only its exact path independently of successful response delivery, while retaining immediate cleanup. Add coverage for lost initial responses and interruption before filename registration.
+
+ **Fault family:** every remote scratch file retains a cleanup owner throughout creation, transfer and termination.
+
+The remaining scoped checks look sound: pages retain header, length, checksum and line-count validation; the filename and scratch-directory constraints prevent shell injection; both `find` calls place `-ignore_readdir_race` correctly and check failure status. The new growing-directory test distinguishes snapshot paging from the old implementation, and the previous failure expectations remain except for the deliberately removed changing-directory refusal.
+
+The prescribed test command could not start: Go’s work-directory creation was denied by the read-only sandbox. Runtime verification, including the reported old-script failure, therefore remains unconfirmed. No files were changed.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-hosts-used-scan-snapshot.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-hosts-used-scan-snapshot.md
new file mode 100644
index 000000000..87945d710
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-hosts-used-scan-snapshot.md
@@ -0,0 +1,77 @@
+# Review brief: branch hosts-used-scan-snapshot (#444), round 1 of 3
+
+Repo carlos/platform, branch `hosts-used-scan-snapshot`, commit cab9c9cf (the fix), plus this brief's own commit.
+Under review: the diff `5f4df955..HEAD`, which touches only `scripts/hosts-used-scan-aws.sh` and
+`cmd/console/hostsused_scan_test.go`. Scope is narrow: this change only. Do not review the rest of the
+script or the activation code except where this change interacts with it.
+Authorities (all on main): spec `docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md`
+§3b, plan `docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md` Task 11, README "Completing the
+history". Do not review against unmerged branches; if this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the diff, then the code it touches, and check every claim in the
+comments, the commit message and this brief against that code.
+
+## The problem (#444)
+
+The script lists each box's data directory (`find . -maxdepth 3`) over SSM, which returns at most
+24,000 characters, so a big listing comes back in pages. Before this change, every page re-ran `find` and
+the pages were accepted only if every page's header (sha256, length, line count) matched. On flagship's
+busiest box (12,124 paths, about 23 pages) SQLite `-wal`/`-shm` files appear and vanish every few seconds,
+so the listing never matched itself and the box could not be scanned. Activation refuses an unscanned
+target, so flagship could not complete its hostname history.
+
+## Fixed: do not re-argue
+
+Paul's go (2026-10-27, via the coordinator): each box runs `find` once into a scratch file in /run or
+/dev/shm with a mktemp name, removed by exact path when done, including on failure; pages are cut from
+that file with the sha256, length and line-count check kept, now over the file; GNU find's
+`-ignore_readdir_race` so a file vanishing mid-walk doesn't fail the listing, any other find error still
+ok:false. The scan writing one scratch file per box is accepted.
+
+## What to check
+
+1. Correctness of a snapshot listing: the reassembled listing must be exactly what the one `find` saw;
+ the integrity check (sha256, base64 length, line count) must still catch a short, cut or corrupted
+ page or a replaced scratch file. Could any page come from a different snapshot or file?
+2. Command injection: the scratch file's name comes back from the box and is written into later SSM
+ commands; HOSTS_SCAN_RUNDIR is written into every box command. Are both constrained enough?
+3. Cleanup: is the scratch file removed by exact path in every path you can find (success, a page that
+ fails, a header mismatch and its retry, a snapshot command that fails, an interrupted run)? Name any
+ path that leaks one, and whether it matters (tmpfs, root-only, about 500 KB).
+4. `-ignore_readdir_race`: does any find error other than a vanished entry still fail the box with
+ ok:false? Is the flag placed where GNU find honours it for both finds?
+5. The tests: does TestHostsUsedScanAWSPagesOneSnapshot fail on the old script and prove a single
+ snapshot is paged? Do the changed expectations in TestHostsUsedScanAWSFailsATargetClosed still pin
+ every failure they pinned before (except the deliberately removed "changed while it was paged")?
+
+Run only `go test ./cmd/console -run TestHostsUsedScanAWS` if you run anything (needs GOFLAGS=-buildvcs=false
+in this worktree).
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/scripts/hosts-used-scan-aws.sh b/scripts/hosts-used-scan-aws.sh
index 602a08f19..937c75308 100755
--- a/scripts/hosts-used-scan-aws.sh
+++ b/scripts/hosts-used-scan-aws.sh
@@ -11,7 +11,7 @@
# moves/ and seeds/ (s3api list-objects-v2, every page).
# box:<name> every path under the box's data directory to depth 3
# (find, run through `aws ssm send-command`), relative to
-# that directory.
+# that directory, as one find saw it.
#
# The roster is provider-neutral and names targets only, so their AWS
# coordinates come from the operator's coords file, keyed by roster target:
@@ -31,19 +31,32 @@
# optional for a bucket.
#
# Any failure for a target (no coordinates, an AWS error, a command that
-# failed or timed out, a listing that changed while it was paged) gives that
-# target ok:false and the error, which activate refuses. SSM returns at most
-# 24,000 characters of output, so a box's listing comes back in find's own
-# order, gzipped and base64-encoded, in pages of HOSTS_SCAN_PAGE characters; every page
-# carries the whole listing's sha256, length and line count, and the
+# failed or timed out, a find that failed) gives that target ok:false and
+# the error, which activate refuses. SSM returns at most 24,000 characters
+# of output, so a box's listing comes back in pages of HOSTS_SCAN_PAGE
+# characters. A busy box's files come and go between commands (SQLite -wal
+# and -shm files), so the box runs find ONCE (#444), with
+# -ignore_readdir_race so a file that vanishes mid-walk is not an error,
+# and keeps the result, gzipped and base64-encoded, in a scratch file made
+# by mktemp in /run (root-only, tmpfs). Every page is cut from that file
+# and carries the snapshot's sha256, length and line count, and the
# reassembled listing must match all three. Nothing is truncated silently.
+# The scratch file is removed by its exact name once the box is paged,
+# whether paging worked or not; a box whose snapshot command fails removes
+# its own. Each snapshot also starts a detached timer that removes that
+# same path after HOSTS_SCAN_EXPIRE seconds (900), so a file whose name
+# never reached the scan (a lost or cut first response, an interrupted
+# run) does not outlive it for long. A box paged slower than that fails
+# cleanly: its next page finds the file gone.
#
-# Read-only: the only AWS calls are s3api list-objects-v2, ssm send-command
-# (running find, which writes nothing on the box) and ssm
-# get-command-invocation. Exit 0 when every target is ok, 1 when any is
-# not (the output file is still written), 2 on bad arguments, a prefix not
-# in plain form, or an output file that could not be written.
-# HOSTS_SCAN_POLL, HOSTS_SCAN_WAIT and HOSTS_SCAN_PAGE exist for tests.
+# Read-only for platform data: the only AWS calls are s3api
+# list-objects-v2, ssm send-command (running find, cut and rm of the
+# scan's own scratch file) and ssm get-command-invocation. Exit 0 when
+# every target is ok, 1 when any is not (the output file is still
+# written), 2 on bad arguments, a prefix not in plain form, or an output
+# file that could not be written. HOSTS_SCAN_POLL, HOSTS_SCAN_WAIT,
+# HOSTS_SCAN_PAGE, HOSTS_SCAN_RUNDIR (the boxes' scratch directory, /run)
+# and HOSTS_SCAN_EXPIRE exist for tests.
set -uo pipefail
export LC_ALL=C
usage() { echo "usage: hosts-used-scan-aws.sh --profile <aws-profile> --targets <coords.json> <roster.json> <scan.jsonl>" >&2; exit 2; }
@@ -66,6 +79,11 @@ case "$page" in ''|*[!0-9]*) echo "HOSTS_SCAN_PAGE must be a number" >&2; exit 2
# SSM keeps the first 24,000 characters of output; a page and its header
# line must fit.
[ "$page" -ge 1 ] && [ "$page" -le 23000 ] || { echo "HOSTS_SCAN_PAGE must be 1 to 23000" >&2; exit 2; }
+rundir="${HOSTS_SCAN_RUNDIR:-/run}"
+# It is written into the box's commands, so only a plain absolute path.
+[[ "$rundir" =~ ^/[A-Za-z0-9._/-]*$ ]] || { echo "HOSTS_SCAN_RUNDIR must be a plain absolute path" >&2; exit 2; }
+expire="${HOSTS_SCAN_EXPIRE:-900}"
+[[ "$expire" =~ ^[1-9][0-9]{0,5}$ ]] || { echo "HOSTS_SCAN_EXPIRE must be a number of seconds" >&2; exit 2; }
command -v jq >/dev/null || { echo "hosts-used-scan: jq is required" >&2; exit 2; }
command -v aws >/dev/null || { echo "hosts-used-scan: the aws CLI is required" >&2; exit 2; }
targets="$(jq -r 'if (.targets|type) == "array" and all(.targets[]; type == "string") then .targets[] else error("no targets array") end' "$roster")" || {
@@ -96,7 +114,11 @@ fi
export AWS_PAGER=""
work="$(mktemp -d "${TMPDIR:-/tmp}/hosts-used-scan.XXXXXX")" || exit 2
part="$(mktemp "$out.XXXXXX")" || { rm -rf "$work"; exit 2; }
-trap 'rm -rf "$work"; rm -f "$part"' EXIT
+# A box snapshot not yet removed ("<region> <instance> <path>"): removed on
+# the way out too, so an interrupted run leaves nothing on a box.
+pending=""
+trap 'drop_pending; rm -rf "$work"; rm -f "$part"' EXIT
+trap 'exit 130' INT TERM
awsp() { aws --profile "$profile" "$@" </dev/null; }
sha256() { if command -v sha256sum >/dev/null; then sha256sum; else shasum -a 256; fi | cut -d' ' -f1; }
@@ -174,33 +196,80 @@ scan_bucket() { # <roster target> <bucket>
echo "ok bucket:$b: $(jq '.entries|length' <<<"$line") keys" >&2
}
-# remote_script <data dir> <first char> <last char>: the command the box
-# runs. POSIX sh, as AWS-RunShellScript runs it. Read-only: find and
-# encoders over pipes, nothing written (no sort, which can spill to disk;
-# find's order is stable while the directory is unchanged, and a change
-# shows as a different sum). The sum and count are taken from find's own
-# checked output, so a failed or partial encoder can only make the
-# reassembled listing disagree with them, which fails the box.
-remote_script() {
+# The box's commands, POSIX sh, as AWS-RunShellScript runs them (as root).
+#
+# snapshot_script <data dir>: run find once and keep the listing in a
+# scratch file made by mktemp in $rundir, then print its first page. The
+# file's first line is the header, "hosts-used-scan v2 <sha256> <length>
+# <lines> <name>", where sha256 and the line count are of find's own
+# checked output, length is that of the gzipped, base64-encoded listing on
+# the second line, and name is the random part of the file's name. A
+# failed or partial encoder can only make the reassembled listing disagree
+# with them, which fails the box. Until the file is complete, an exit
+# removes it. -ignore_readdir_race: a file that vanishes while find walks
+# (a SQLite -wal or -shm file closing) is not an error; any other find
+# error is.
+snapshot_script() {
cat <<EOF
export LC_ALL=C
+umask 077
cd '$1' || { echo "cannot enter $1" >&2; exit 3; }
+snap=\$(mktemp '$rundir/hosts-used-scan.XXXXXXXXXX') || { echo "cannot make a scratch file in $rundir" >&2; exit 7; }
+trap 'rm -f "\$snap"' EXIT
+# The bounded expiry: this exact path, whatever happens to this command's
+# response. Detached and silent, so the command still returns at once.
+if command -v setsid >/dev/null 2>&1; then
+ setsid sh -c 'sleep $expire; rm -f -- "\$1"' sh "\$snap" </dev/null >/dev/null 2>&1 &
+else
+ sh -c 'sleep $expire; rm -f -- "\$1"' sh "\$snap" </dev/null >/dev/null 2>&1 &
+fi
nl='
'
-bad=\$(find . -maxdepth 3 -name "*\${nl}*" -print) || { echo "find failed under $1" >&2; exit 4; }
+bad=\$(find . -maxdepth 3 -ignore_readdir_race -name "*\${nl}*" -print) || { echo "find failed under $1" >&2; exit 4; }
[ -z "\$bad" ] || { echo "a path under $1 has a newline in its name" >&2; exit 5; }
-list=\$(find . -maxdepth 3 -print) || { echo "find failed under $1" >&2; exit 4; }
+list=\$(find . -maxdepth 3 -ignore_readdir_race -print) || { echo "find failed under $1" >&2; exit 4; }
sum=\$(printf '%s\n' "\$list" | sha256sum | cut -d' ' -f1)
n=\$(printf '%s\n' "\$list" | wc -l | tr -d ' ')
blob=\$(printf '%s\n' "\$list" | gzip -n -c | base64 | tr -d '\n')
case "\$sum" in *[!0-9a-f]*|'') sum=bad ;; esac
case "\$n" in *[!0-9]*|'') n=bad ;; esac
[ "\${#sum}" -eq 64 ] && [ "\$n" != bad ] && [ -n "\$blob" ] || { echo "could not encode the listing of $1" >&2; exit 6; }
-printf 'hosts-used-scan v1 %s %s %s\n' "\$sum" "\${#blob}" "\$n"
-printf '%s' "\$blob" | cut -c $2-$3
+printf 'hosts-used-scan v2 %s %s %s %s\n%s\n' "\$sum" "\${#blob}" "\$n" "\${snap##*.}" "\$blob" >"\$snap" || { echo "could not write the scratch file in $rundir" >&2; exit 7; }
+trap - EXIT
+head -n 1 "\$snap"
+sed -n '2p' "\$snap" | cut -c 1-$2
+EOF
+}
+
+# page_script <name> <first char> <last char>: one page of a snapshot.
+page_script() {
+ cat <<EOF
+export LC_ALL=C
+snap='$rundir/hosts-used-scan.$1'
+[ -f "\$snap" ] && [ ! -L "\$snap" ] || { echo "the scratch listing \$snap is gone" >&2; exit 8; }
+head -n 1 "\$snap"
+sed -n '2p' "\$snap" | cut -c $2-$3
EOF
}
+# drop_snapshot <region> <instance> <name>: remove the box's scratch file by
+# its exact name, and say so when that fails; the listing itself stands.
+drop_snapshot() {
+ local f="$rundir/hosts-used-scan.$3"
+ if ssm_run "$1" "$2" "rm -f -- '$f' && [ ! -e '$f' ]"; then
+ pending=""
+ else
+ echo "WARN box $2: could not remove the scratch listing $f ($err). remove it by hand" >&2
+ pending=""
+ fi
+}
+drop_pending() {
+ [ -n "$pending" ] || return 0
+ local r i n err=""
+ read -r r i n <<<"$pending"
+ drop_snapshot "$r" "$i" "$n"
+}
+
# ssm_run <region> <instance> <script>: run it and leave its stdout in
# $work/stdout; on failure set $err and return 1.
ssm_run() {
@@ -230,22 +299,37 @@ ssm_run() {
done
}
-# box_listing <region> <instance> <data dir>: one consistent listing,
-# reassembled from pages, in $work/listing; on failure set $err and return
-# 1 (2 when the listing changed between pages, which is worth a retry).
+# box_listing <region> <instance> <data dir>: one snapshot, reassembled
+# from pages, in $work/listing; on failure set $err and return 1 (2 when
+# the snapshot's header changed between pages, which is worth a retry with
+# a new snapshot). The box's scratch file is removed either way.
box_listing() {
+ local r="$1" i="$2" d="$3" name="" rc
+ box_pages "$r" "$i" "$d"; rc=$?
+ [ -z "$name" ] || { local keep="$err"; drop_snapshot "$r" "$i" "$name"; err="$keep"; }
+ return "$rc"
+}
+box_pages() {
local r="$1" i="$2" d="$3" first=1 header="" total=1 got want h
: >"$work/blob"
while [ "$first" -le "$total" ]; do
- ssm_run "$r" "$i" "$(remote_script "$d" "$first" $((first + page - 1)))" || return 1
+ if [ -z "$header" ]; then
+ ssm_run "$r" "$i" "$(snapshot_script "$d" "$page")" || return 1
+ else
+ ssm_run "$r" "$i" "$(page_script "$name" "$first" $((first + page - 1)))" || return 1
+ fi
h="$(head -n1 "$work/stdout")"
- case "$h" in "hosts-used-scan v1 "*) ;; *) err="$i: no listing header in the command's output"; return 1 ;; esac
+ case "$h" in "hosts-used-scan v2 "*) ;; *) err="$i: no listing header in the command's output"; return 1 ;; esac
if [ -z "$header" ]; then
+ # The name goes into the next commands, so only mktemp's own shape.
+ name="$(cut -d' ' -f6 <<<"$h")"
+ [[ "$name" =~ ^[A-Za-z0-9]{10}$ ]] || { name=""; err="$i: a bad listing header: $h"; return 1; }
+ pending="$r $i $name"
header="$h"
total="$(cut -d' ' -f4 <<<"$h")"
case "$total" in ''|*[!0-9]*) err="$i: a bad listing header: $h"; return 1 ;; esac
elif [ "$h" != "$header" ]; then
- err="$i: the listing under $d changed while it was paged"; return 2
+ err="$i: the scratch listing under $rundir changed while it was paged"; return 2
fi
got="$(sed -n '2p' "$work/stdout" | tr -d '\r\n')"
want=$((total - first + 1)); [ "$want" -gt "$page" ] && want="$page"