carlos / platform Public

scripts: hosts-used-scan-aws.sh, the hostname history's AWS adapter

Nearest-region never-reuse plan Task 11 (offline activation, spec §3b).
Scans every target on a `console hosts-used roster` file, read-only, and
writes one TargetListing JSON line per target for `console hosts-used
activate -listings`.

Summary

- bucket targets: s3api list-objects-v2 under the replica prefix, moves/
  and seeds/ (the whole bucket when the prefix is ""), every page, keys
  kept as JSON so no key is split.
- box targets: find <data dir> -maxdepth 3 through ssm send-command. SSM
  keeps 24,000 characters of output, so the listing comes back sorted,
  gzipped and base64'd in pages, each carrying the whole listing's sha256,
  length and line count; reassembly must match all three, a page shorter
  than expected fails, and a listing that changed between pages is taken
  again (three tries). A path with a newline in its name fails the box.
- The roster is provider-neutral, so AWS coordinates come from an
  operator-written --targets file (instance, region, data_dir per box;
  prefix, region per bucket). prefix is required: a wrong default would
  miss replicas silently.
- Any failure gives the target ok:false with the error; exit 1 if any.
- Test (cmd/console): a fake aws (the test binary re-run as aws) pages S3
  two keys at a time and runs SSM scripts with sh; the real console
  roster, the scan and the real activate run end to end, and activate
  refuses an ok:false listing. Failure cases: S3 denied, S3 failing on
  page 2, send-command refused, command failed, output cut short,
  listing changing every page, a bad instance id, missing coordinates.
- README: the script lives here, not "(in infra)".
Agent notes
- Dev dry run (read-only, profile kass): 5 of 6 targets ok; the r10w
  fleet's bucket does not exist (NoSuchBucket). The box listings carry
  instances/_probe and .instances/_probe on every box, which the Task 6
  mapper reports unmapped, so activate on dev would refuse today. That is
  the mapper's to fix, not the scan's.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev e45b71d7a45150dc2813a85c1ca984a607d6e0da parent 0a32ce3
4 files changed, +786 −2
  • README.md +1 −2
  • cmd/console/hostsused_scan_test.go +548 −0
  • cmd/console/main_test.go +5 −0
  • scripts/hosts-used-scan-aws.sh +232 −0

CI cancelled — superseded by a newer push — run details

diff --git a/README.md b/README.md
index 2e2128fc4..05ef8c748 100644
--- a/README.md
+++ b/README.md
@@ -363,8 +363,7 @@ while it is stopped.
1. Stop the console.
2. Run `console hosts-used roster -o roster.json`. It lists every box and
bucket the regions and fleets use.
-3. Scan every target on the roster with `scripts/hosts-used-scan-aws.sh`
- (in infra).
+3. Scan every target on the roster with `scripts/hosts-used-scan-aws.sh`.
4. Run `console hosts-used activate -roster roster.json -listings
scan.jsonl`. A fleet that cannot be scanned can be closed instead, with
`-close-fleet <fleet>`. A closed fleet takes no new instances. Regions
diff --git a/cmd/console/hostsused_scan_test.go b/cmd/console/hostsused_scan_test.go
new file mode 100644
index 000000000..b6d0688c1
--- /dev/null
+++ b/cmd/console/hostsused_scan_test.go
@@ -0,0 +1,548 @@
+package main_test
+
+// scripts/hosts-used-scan-aws.sh, the hostname history's AWS adapter
+// (nearest-region never-reuse plan Task 11), run against a fake `aws`: this
+// test binary, re-executed under the name aws (TestMain). The fake pages S3
+// listings two keys at a time and runs an SSM command's script with sh
+// against a local directory, keeping at most SSM's 24,000 characters of its
+// output. The happy path goes through the real verbs: `console hosts-used
+// roster`, the scan, then `console hosts-used activate`.
+
+import (
+ "bufio"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+
+ boxlayout "github.com/carlosframework/platform/internal/layout"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+const scanScript = "../../scripts/hosts-used-scan-aws.sh"
+
+// fakeAWSConfig is the fake's world, in config.json under FAKE_AWS_DIR.
+type fakeAWSConfig struct {
+ Buckets map[string]fakeBucket `json:"buckets"`
+ Instances map[string]fakeInstance `json:"instances"`
+}
+
+type fakeBucket struct {
+ Keys []string `json:"keys"`
+ Fail string `json:"fail"` // every call fails with this
+ FailPage int `json:"fail_page"` // the call for this page (1-based) fails
+}
+
+type fakeInstance struct {
+ SendFail string `json:"send_fail"` // send-command fails with this
+ Truncate int `json:"truncate"` // keep only this many characters of output
+ GrowDir string `json:"grow_dir"` // send-commands add a file here: every one...
+ GrowAt int `json:"grow_at"` // ...or only this instance's nth
+}
+
+// fakeAWS is the fake aws CLI. It logs every call's arguments, one JSON
+// array per line, to calls.jsonl, and refuses any operation the scan has no
+// business making.
+func fakeAWS(args []string) int {
+ dir := os.Getenv("FAKE_AWS_DIR")
+ if f, err := os.OpenFile(filepath.Join(dir, "calls.jsonl"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600); err == nil {
+ b, _ := json.Marshal(args)
+ f.Write(append(b, '\n'))
+ f.Close()
+ }
+ var cfg fakeAWSConfig
+ if b, err := os.ReadFile(filepath.Join(dir, "config.json")); err != nil || json.Unmarshal(b, &cfg) != nil {
+ fmt.Fprintln(os.Stderr, "fake aws: no config")
+ return 99
+ }
+ opts, words := map[string]string{}, []string{}
+ for i := 0; i < len(args); i++ {
+ switch {
+ case args[i] == "--no-paginate":
+ case strings.HasPrefix(args[i], "--") && i+1 < len(args):
+ opts[args[i]] = args[i+1]
+ i++
+ default:
+ words = append(words, args[i])
+ }
+ }
+ op := strings.Join(words, " ")
+ switch op {
+ case "s3api list-objects-v2":
+ return fakeListObjects(cfg, opts)
+ case "ssm send-command":
+ return fakeSendCommand(dir, cfg, opts)
+ case "ssm get-command-invocation":
+ return fakeGetInvocation(dir, opts)
+ }
+ fmt.Fprintf(os.Stderr, "fake aws: unexpected call %q\n", op)
+ return 99
+}
+
+func fakeListObjects(cfg fakeAWSConfig, opts map[string]string) int {
+ b, ok := cfg.Buckets[opts["--bucket"]]
+ if !ok {
+ fmt.Fprintln(os.Stderr, "An error occurred (NoSuchBucket) when calling the ListObjectsV2 operation: The specified bucket does not exist")
+ return 254
+ }
+ start := 0
+ if tok := opts["--continuation-token"]; tok != "" {
+ start, _ = strconv.Atoi(strings.TrimPrefix(tok, "tok-"))
+ }
+ if b.Fail != "" || (b.FailPage > 0 && start/2+1 == b.FailPage) {
+ fmt.Fprintf(os.Stderr, "An error occurred (AccessDenied) when calling the ListObjectsV2 operation: %s\n", b.Fail)
+ return 254
+ }
+ var keys []string
+ for _, k := range b.Keys {
+ if strings.HasPrefix(k, opts["--prefix"]) {
+ keys = append(keys, k)
+ }
+ }
+ sort.Strings(keys)
+ end := min(start+2, len(keys))
+ resp := map[string]any{"IsTruncated": end < len(keys), "KeyCount": end - start}
+ if end > start {
+ var contents []map[string]string
+ for _, k := range keys[start:end] {
+ contents = append(contents, map[string]string{"Key": k})
+ }
+ resp["Contents"] = contents
+ }
+ if end < len(keys) {
+ resp["NextContinuationToken"] = "tok-" + strconv.Itoa(end)
+ }
+ json.NewEncoder(os.Stdout).Encode(resp)
+ return 0
+}
+
+func fakeSendCommand(dir string, cfg fakeAWSConfig, opts map[string]string) int {
+ inst, ok := cfg.Instances[opts["--instance-ids"]]
+ if !ok || inst.SendFail != "" {
+ fmt.Fprintf(os.Stderr, "An error occurred (InvalidInstanceId) when calling the SendCommand operation: %s\n", inst.SendFail)
+ return 254
+ }
+ var params struct {
+ Commands []string `json:"commands"`
+ }
+ if err := json.Unmarshal([]byte(opts["--parameters"]), &params); err != nil || len(params.Commands) != 1 {
+ fmt.Fprintln(os.Stderr, "fake aws: bad --parameters")
+ return 99
+ }
+ n := fakeCounter(dir, "commands")
+ if mine := fakeCounter(dir, "commands-"+opts["--instance-ids"]); 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
+ cmd := exec.Command("sh", "-c", params.Commands[0])
+ cmd.Stdout, cmd.Stderr = &stdout, &stderr
+ code, status := 0, "Success"
+ if err := cmd.Run(); err != nil {
+ code, status = 1, "Failed"
+ var ee *exec.ExitError
+ if errors.As(err, &ee) {
+ code = ee.ExitCode()
+ }
+ }
+ out := stdout.String()
+ limit := 24000
+ if inst.Truncate > 0 {
+ limit = inst.Truncate
+ }
+ if len(out) > limit {
+ out = out[:limit]
+ }
+ id := fmt.Sprintf("cmd-%d", n)
+ b, _ := json.Marshal(map[string]any{"Status": status, "ResponseCode": code, "StandardOutputContent": out, "StandardErrorContent": stderr.String()})
+ os.WriteFile(filepath.Join(dir, id+".json"), b, 0o600)
+ fmt.Println(id)
+ return 0
+}
+
+// fakeGetInvocation answers InvocationDoesNotExist on its first call for a
+// command, as SSM does straight after send-command, then the result.
+func fakeGetInvocation(dir string, opts map[string]string) int {
+ id := opts["--command-id"]
+ seen := filepath.Join(dir, id+".seen")
+ if _, err := os.Stat(seen); err != nil {
+ os.WriteFile(seen, nil, 0o600)
+ fmt.Fprintln(os.Stderr, "An error occurred (InvocationDoesNotExist) when calling the GetCommandInvocation operation: ")
+ return 254
+ }
+ b, err := os.ReadFile(filepath.Join(dir, id+".json"))
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "An error occurred (InvalidCommandId) when calling the GetCommandInvocation operation: ")
+ return 254
+ }
+ os.Stdout.Write(b)
+ return 0
+}
+
+func fakeCounter(dir, name string) int {
+ p := filepath.Join(dir, name)
+ b, _ := os.ReadFile(p)
+ n, _ := strconv.Atoi(strings.TrimSpace(string(b)))
+ n++
+ os.WriteFile(p, []byte(strconv.Itoa(n)), 0o600)
+ return n
+}
+
+// scanWorld is one test's fake AWS, its PATH and its scratch.
+type scanWorld struct {
+ t *testing.T
+ dir, fake string
+ env []string
+ coordsPath string
+ cfg fakeAWSConfig
+ coordinates map[string]map[string]string
+}
+
+func newScanWorld(t *testing.T) *scanWorld {
+ t.Helper()
+ for _, tool := range []string{"jq", "sh", "find", "gzip", "base64", "sha256sum"} {
+ if _, err := exec.LookPath(tool); err != nil {
+ t.Skipf("%s not installed", tool)
+ }
+ }
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ w := &scanWorld{t: t, dir: dir, fake: filepath.Join(dir, "fake"),
+ 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} {
+ if err := os.MkdirAll(d, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.Symlink(exe, filepath.Join(bin, "aws")); err != nil {
+ t.Fatal(err)
+ }
+ 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}
+ return w
+}
+
+// box makes a data directory holding paths (a trailing "/" is a directory)
+// behind instance inst, with the box's coordinates.
+func (w *scanWorld) box(target, inst string, paths ...string) string {
+ w.t.Helper()
+ d := filepath.Join(w.dir, "data-"+inst)
+ if err := os.MkdirAll(d, 0o755); err != nil {
+ w.t.Fatal(err)
+ }
+ for _, p := range paths {
+ full := filepath.Join(d, p)
+ if strings.HasSuffix(p, "/") {
+ os.MkdirAll(full, 0o755)
+ continue
+ }
+ os.MkdirAll(filepath.Dir(full), 0o755)
+ if err := os.WriteFile(full, []byte("x"), 0o600); err != nil {
+ w.t.Fatal(err)
+ }
+ }
+ w.cfg.Instances[inst] = fakeInstance{}
+ w.coordinates[target] = map[string]string{"instance": inst, "region": "eu-west-1", "data_dir": d}
+ return d
+}
+
+func (w *scanWorld) bucket(target, prefix string, keys ...string) {
+ name := strings.TrimPrefix(target, "bucket:")
+ w.cfg.Buckets[name] = fakeBucket{Keys: keys}
+ w.coordinates[target] = map[string]string{"prefix": prefix, "region": "eu-west-1"}
+}
+
+// scan writes the fake's config and the coords, runs the script and
+// returns its output lines, its stderr and its exit code.
+func (w *scanWorld) scan(rosterPath string, extraEnv ...string) ([]provision.TargetListing, string, int) {
+ w.t.Helper()
+ writeJSON(w.t, filepath.Join(w.fake, "config.json"), w.cfg)
+ writeJSON(w.t, w.coordsPath, w.coordinates)
+ out := filepath.Join(w.dir, "scan.jsonl")
+ os.Remove(out)
+ cmd := exec.Command(scanScript, "--profile", "scan-test", "--targets", w.coordsPath, rosterPath, out)
+ cmd.Env = append(append(os.Environ(), w.env...), extraEnv...)
+ var stderr strings.Builder
+ cmd.Stderr = &stderr
+ err := cmd.Run()
+ code := 0
+ var ee *exec.ExitError
+ if errors.As(err, &ee) {
+ code = ee.ExitCode()
+ } else if err != nil {
+ w.t.Fatalf("run the scan: %v", err)
+ }
+ f, err := os.Open(out)
+ if err != nil {
+ w.t.Fatalf("no scan output (exit %d): %v\n%s", code, err, stderr.String())
+ }
+ defer f.Close()
+ // Every line is one JSON object, as activate's reader (readListings)
+ // decodes them: strictly, with no unknown fields.
+ var got []provision.TargetListing
+ sc := bufio.NewScanner(f)
+ sc.Buffer(nil, 1<<24)
+ for sc.Scan() {
+ dec := json.NewDecoder(strings.NewReader(sc.Text()))
+ dec.DisallowUnknownFields()
+ var l provision.TargetListing
+ if err := dec.Decode(&l); err != nil {
+ w.t.Fatalf("line %q: %v", sc.Text(), err)
+ }
+ got = append(got, l)
+ }
+ return got, stderr.String(), code
+}
+
+// calls is every aws invocation the fake saw.
+func (w *scanWorld) calls() [][]string {
+ w.t.Helper()
+ b, _ := os.ReadFile(filepath.Join(w.fake, "calls.jsonl"))
+ var out [][]string
+ for _, line := range strings.Split(strings.TrimSpace(string(b)), "\n") {
+ if line == "" {
+ continue
+ }
+ var args []string
+ if err := json.Unmarshal([]byte(line), &args); err != nil {
+ w.t.Fatal(err)
+ }
+ out = append(out, args)
+ }
+ return out
+}
+
+func writeJSON(t *testing.T, path string, v any) {
+ t.Helper()
+ b, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, b, 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func byTarget(ls []provision.TargetListing) map[string]provision.TargetListing {
+ out := map[string]provision.TargetListing{}
+ for _, l := range ls {
+ out[l.Kind+":"+l.Target] = l
+ }
+ return out
+}
+
+// TestHostsUsedScanAWSActivates: a roster taken by the real console, scanned
+// through paged S3 listings and paged SSM output, is accepted by the real
+// activate, which marks every hostname the listings name. Every aws call
+// names the profile, and is a listing, a send-command or a read of its
+// result. Before that, a scan with a failed target is refused by activate.
+func TestHostsUsedScanAWSActivates(t *testing.T) {
+ bin := buildConsole(t)
+ w := newScanWorld(t)
+ deploy := filepath.Join(w.dir, "deploy")
+ for box, edges := range map[string]string{
+ "b1": `{"v":1,"box":"b1","eip":"192.0.2.1","region":"eu-west-1","placement":"","data_bucket":"data-ie","hosts":{}}`,
+ "b2": `{"v":1,"box":"b2","eip":"192.0.2.2","region":"eu-west-2","placement":"uk","data_bucket":"data-uk","hosts":{}}`,
+ } {
+ p := filepath.Join(deploy, "control", "edges", box+".json")
+ os.MkdirAll(filepath.Dir(p), 0o755)
+ if err := os.WriteFile(p, []byte(edges), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ os.MkdirAll(filepath.Join(w.dir, "console"), 0o755)
+ run := runner(t, bin, "CARLOS_DEPLOYMENT_DIR="+deploy, "CONSOLE_DB="+filepath.Join(w.dir, "console", "console.db"),
+ "CARLOS_REGISTRY="+filepath.Join(w.dir, "registry.db"))
+ rosterPath := filepath.Join(w.dir, "roster.json")
+ if out, err := run("hosts-used", "roster", "-o", rosterPath); err != nil {
+ t.Fatalf("roster: %v\n%s", err, out)
+ }
+
+ // Seven keys under the three roots, two keys a page: several pages per
+ // prefix. other/ is outside them and never listed.
+ ieKeys := []string{
+ "instances/shop.example.com/db/000001", "instances/shop.example.com/generation", "instances/blog.example.org/db/1",
+ "moves/moved.example.net/stage", "moves/@lanes/lane-1", "moves/@offline/off.example.com/x",
+ "seeds/seed.example.com/snap",
+ }
+ w.bucket("bucket:data-ie", "instances", append(slices.Clone(ieKeys), "other/not-a-root")...)
+ // An empty prefix: replicas at the top level, the whole bucket listed.
+ ukKeys := []string{"uk.example.com/db/1", "moves/uk-moved.example.com/x", "seeds/uk-seed.example.com/y"}
+ w.bucket("bucket:data-uk", "", ukKeys...)
+ var filler []string
+ for i := range 40 {
+ filler = append(filler, fmt.Sprintf("static/asset-%02d.css", i))
+ }
+ w.box("box:b1", "i-0b1", append([]string{
+ "shop.example.com.db", "shop.example.com.db-wal", "registry.db",
+ "instances/blog.example.org/app.db", ".offline-moves/moved.example.net/x", "deep/a/b/c/too-deep.example.com.db",
+ }, filler...)...)
+ w.box("box:b2", "i-0b2", "uk.example.com.db")
+
+ // A failed target: the scan says so, and activate refuses the listing.
+ w.cfg.Buckets["data-ie"] = fakeBucket{Keys: w.cfg.Buckets["data-ie"].Keys, Fail: "Access Denied"}
+ if _, stderr, code := w.scan(rosterPath); code != 1 || !strings.Contains(stderr, "FAIL bucket:data-ie") {
+ t.Fatalf("scan with a denied bucket: exit %d\n%s", code, stderr)
+ }
+ listings := filepath.Join(w.dir, "scan.jsonl")
+ if out, err := run("hosts-used", "activate", "-roster", rosterPath, "-listings", listings); err == nil ||
+ !strings.Contains(out, "The listing of bucket:data-ie failed.") {
+ t.Fatalf("activate took a failed listing: %v\n%s", err, out)
+ }
+ w.cfg.Buckets["data-ie"] = fakeBucket{Keys: w.cfg.Buckets["data-ie"].Keys}
+ os.Remove(filepath.Join(w.fake, "calls.jsonl"))
+
+ // 64 characters a page: the box listings take several SSM pages.
+ got, stderr, code := w.scan(rosterPath, "HOSTS_SCAN_PAGE=64")
+ if code != 0 {
+ t.Fatalf("scan exit %d\n%s", code, stderr)
+ }
+ ls := byTarget(got)
+ if len(got) != 4 || len(ls) != 4 {
+ t.Fatalf("want one line for each of 4 targets, got %+v", got)
+ }
+ for k, l := range ls {
+ if !l.OK || l.Error != "" {
+ t.Fatalf("%s: %+v", k, l)
+ }
+ }
+ sort.Strings(ieKeys)
+ if ie := ls["bucket:data-ie"]; !slices.Equal(ie.Entries, ieKeys) || ie.Prefix != "instances" {
+ t.Errorf("data-ie = %q prefix %q, want %q", ie.Entries, ie.Prefix, ieKeys)
+ }
+ sort.Strings(ukKeys)
+ if uk := ls["bucket:data-uk"]; !slices.Equal(uk.Entries, ukKeys) || uk.Prefix != "" {
+ t.Errorf("data-uk = %q prefix %q, want %q", uk.Entries, uk.Prefix, ukKeys)
+ }
+ b1 := ls["box:b1"].Entries
+ for _, want := range []string{"shop.example.com.db", "instances", "instances/blog.example.org", "instances/blog.example.org/app.db",
+ ".offline-moves/moved.example.net/x", "deep/a/b", "static/asset-39.css"} {
+ if !slices.Contains(b1, want) {
+ t.Errorf("box b1 is missing %q: %q", want, b1)
+ }
+ }
+ for _, e := range b1 {
+ if strings.HasPrefix(e, "/") || strings.HasPrefix(e, "./") || e == "." || strings.Count(e, "/") > 2 {
+ t.Errorf("box b1 entry %q is not relative to depth 3", e)
+ }
+ }
+ hosts, unmapped := boxlayout.HostsFromBoxListing(b1)
+ if len(unmapped) != 0 || !slices.Contains(hosts, "shop.example.com") || !slices.Contains(hosts, "blog.example.org") {
+ t.Errorf("box b1 maps to %q, unmapped %q", hosts, unmapped)
+ }
+
+ // Pagination happened on both sides.
+ lists, sends := 0, 0
+ for _, c := range w.calls() {
+ if len(c) < 2 || c[0] != "--profile" || c[1] != "scan-test" {
+ t.Errorf("a call without the profile first: %q", c)
+ }
+ switch op := strings.Join(c[2:min(4, len(c))], " "); op {
+ case "s3api list-objects-v2":
+ lists++
+ case "ssm send-command":
+ sends++
+ case "ssm get-command-invocation":
+ default:
+ t.Errorf("an unexpected aws call: %q", c)
+ }
+ }
+ if lists < 7 || sends < 4 {
+ t.Errorf("%d listings and %d commands: the scan did not page", lists, sends)
+ }
+
+ // The real activate accepts the scan and marks what it names.
+ out, err := run("hosts-used", "activate", "-roster", rosterPath, "-listings", listings)
+ if err != nil || !strings.Contains(out, "the hostname history is complete") {
+ t.Fatalf("activate: %v\n%s", err, out)
+ }
+ for _, h := range []string{"shop.example.com", "blog.example.org", "moved.example.net", "off.example.com", "seed.example.com",
+ "uk.example.com", "uk-moved.example.com", "uk-seed.example.com"} {
+ if _, err := os.Stat(filepath.Join(deploy, "control", "hosts-used", h+".json")); err != nil {
+ t.Errorf("%s is not marked: %v", h, err)
+ }
+ }
+}
+
+// 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.
+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")
+ w.bucket("bucket:denied", "instances", "instances/a.example.com/x")
+ w.cfg.Buckets["denied"] = fakeBucket{Fail: "Access Denied"}
+ w.bucket("bucket:page2", "instances", "instances/a.example.com/1", "instances/a.example.com/2", "instances/a.example.com/3")
+ w.cfg.Buckets["page2"] = fakeBucket{Keys: w.cfg.Buckets["page2"].Keys, FailPage: 2}
+ w.cfg.Buckets["noprefix"] = fakeBucket{}
+ w.coordinates["bucket:noprefix"] = map[string]string{"region": "eu-west-1"}
+ w.box("box:okbox", "i-0a0", "shop.example.com.db")
+ w.box("box:unsent", "i-0a1", "shop.example.com.db")
+ w.cfg.Instances["i-0a1"] = fakeInstance{SendFail: "Instances not in a valid state for account"}
+ w.box("box:nodir", "i-0a2")
+ w.coordinates["box:nodir"]["data_dir"] = filepath.Join(w.dir, "no-such-dir")
+ w.box("box:cut", "i-0a3", "shop.example.com.db")
+ w.cfg.Instances["i-0a3"] = fakeInstance{Truncate: 110}
+ d := w.box("box:grows", "i-0a4", "shop.example.com.db")
+ w.cfg.Instances["i-0a4"] = fakeInstance{GrowDir: d}
+ d = w.box("box:grows-once", "i-0a5", "shop.example.com.db")
+ w.cfg.Instances["i-0a5"] = fakeInstance{GrowDir: d, GrowAt: 2}
+ w.coordinates["box:badinst"] = map[string]string{"instance": "i-0a6; rm -rf /", "region": "eu-west-1"}
+
+ 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"}}
+ rosterPath := filepath.Join(w.dir, "roster.json")
+ writeJSON(t, rosterPath, roster)
+ got, stderr, code := w.scan(rosterPath, "HOSTS_SCAN_PAGE=40")
+ if code != 1 {
+ t.Fatalf("scan exit %d, want 1\n%s", code, stderr)
+ }
+ ls := byTarget(got)
+ if len(got) != 14 || len(ls) != 14 {
+ t.Fatalf("want one line for each of 14 targets, got %d: %+v", len(got), got)
+ }
+ for target, want := range map[string]string{
+ "bucket:ok": "",
+ "box:okbox": "",
+ "box:grows-once": "",
+ "bucket:denied": "AccessDenied",
+ "bucket:page2": "AccessDenied",
+ "bucket:noprefix": "no prefix for bucket:noprefix",
+ "bucket:nocoords": "no prefix for bucket:nocoords",
+ "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",
+ } {
+ l, ok := ls[target]
+ switch {
+ case !ok:
+ t.Errorf("%s: no line", target)
+ case want == "" && (!l.OK || l.Error != "" || len(l.Entries) == 0):
+ t.Errorf("%s: want ok with entries, got %+v", target, l)
+ case want != "" && (l.OK || !strings.Contains(l.Error, want) || len(l.Entries) != 0):
+ t.Errorf("%s: want ok:false with %q and no entries, got %+v", target, want, l)
+ }
+ }
+ for _, c := range w.calls() {
+ if slices.Contains(c, "i-0a6; rm -rf /") {
+ t.Errorf("a bad instance id reached aws: %q", c)
+ }
+ }
+}
diff --git a/cmd/console/main_test.go b/cmd/console/main_test.go
index 0c889abc5..2e93612e3 100644
--- a/cmd/console/main_test.go
+++ b/cmd/console/main_test.go
@@ -64,6 +64,11 @@ func runner(t *testing.T, bin string, env ...string) func(args ...string) (strin
}
func TestMain(m *testing.M) {
+ // The fake aws CLI for the hosts-used scan script (hostsused_scan_test.go):
+ // this binary, run under the name aws.
+ if filepath.Base(os.Args[0]) == "aws" {
+ os.Exit(fakeAWS(os.Args[1:]))
+ }
// The GeoIP verifier verb: openGeoIP re-runs its own binary to verify
// the override in a child process, and under `go test` that binary is
// this one.
diff --git a/scripts/hosts-used-scan-aws.sh b/scripts/hosts-used-scan-aws.sh
new file mode 100755
index 000000000..092b6435c
--- /dev/null
+++ b/scripts/hosts-used-scan-aws.sh
@@ -0,0 +1,232 @@
+#!/usr/bin/env bash
+# scripts/hosts-used-scan-aws.sh --profile <aws-profile> --targets <coords.json> <roster.json> <scan.jsonl>
+#
+# The hostname history's AWS adapter (nearest-region never-reuse plan Task
+# 11, spec §3b): scans every target on a `console hosts-used roster` file,
+# read-only, and writes one TargetListing JSON line per target
+# (internal/provision/hostsused_map.go) for `console hosts-used activate
+# -roster <roster.json> -listings <scan.jsonl>`.
+#
+# bucket:<name> every current object key under the replica prefix,
+# 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.
+#
+# The roster is provider-neutral and names targets only, so their AWS
+# coordinates come from the operator's coords file, keyed by roster target:
+#
+# {"box:<name>": {"instance": "i-...", "region": "eu-west-1", "data_dir": "/data"},
+# "bucket:<name>": {"prefix": "instances", "region": "eu-west-1"}}
+#
+# data_dir defaults to /data. prefix is required: it is the boxes'
+# CARLOS_HIBERNATE_PREFIX ("" puts replicas at the bucket's top level, and
+# then the whole bucket is listed). A wrong prefix misses that bucket's
+# replicas, so it is never defaulted. region is 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 sorted, 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
+# reassembled listing must match all three. Nothing is truncated silently.
+#
+# 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.
+# HOSTS_SCAN_POLL, HOSTS_SCAN_WAIT and HOSTS_SCAN_PAGE exist for tests.
+set -uo pipefail
+usage() { echo "usage: hosts-used-scan-aws.sh --profile <aws-profile> --targets <coords.json> <roster.json> <scan.jsonl>" >&2; exit 2; }
+profile="" coords=""
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --profile) [ $# -ge 2 ] || usage; profile="$2"; shift 2 ;;
+ --targets) [ $# -ge 2 ] || usage; coords="$2"; shift 2 ;;
+ --) shift; break ;;
+ -*) usage ;;
+ *) break ;;
+ esac
+done
+[ $# -eq 2 ] && [ -n "$profile" ] && [ -n "$coords" ] || usage
+roster="$1" out="$2"
+poll="${HOSTS_SCAN_POLL:-2}"
+wait_s="${HOSTS_SCAN_WAIT:-300}"
+page="${HOSTS_SCAN_PAGE:-20000}"
+case "$page" in ''|*[!0-9]*) echo "HOSTS_SCAN_PAGE must be a number" >&2; exit 2 ;; esac
+# 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; }
+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")" || {
+ echo "hosts-used-scan: $roster is not a roster: it needs a targets array of strings" >&2; exit 2; }
+jq -e 'type == "object"' "$coords" >/dev/null 2>&1 || { echo "hosts-used-scan: $coords is not a JSON object" >&2; exit 2; }
+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
+
+awsp() { aws --profile "$profile" "$@" </dev/null; }
+sha256() { if command -v sha256sum >/dev/null; then sha256sum; else shasum -a 256; fi | cut -d' ' -f1; }
+# oneline: an AWS error's text, on one line, short enough for a report.
+oneline() { tr '\n' ' ' | sed 's/ */ /g; s/^ //; s/ $//' | cut -c1-400; }
+
+fail=0
+emit_fail() { # <target name> <kind> <error>
+ jq -nc --arg t "$1" --arg k "$2" --arg e "$3" '{target:$t,kind:$k,ok:false,error:$e,entries:[]}' >>"$part"
+ echo "FAIL $2:$1: $3" >&2
+ fail=1
+}
+coord() { # <roster target> <field>: the field, or exit 1 when absent
+ jq -er --arg t "$1" --arg f "$2" '.[$t] | if type == "object" and has($f) and (.[$f]|type) == "string" then .[$f] else error("missing") end' "$coords" 2>/dev/null
+}
+
+# list_prefix <bucket> <region> <prefix>: append every page's keys, one JSON
+# array per line, to $work/keys; on failure set $err and return 1.
+list_prefix() {
+ local b="$1" r="$2" p="$3" token="" resp trunc n=0
+ while :; do
+ set -- s3api list-objects-v2 --bucket "$b" --prefix "$p" --max-keys 1000 --no-paginate --output json
+ [ -n "$r" ] && set -- "$@" --region "$r"
+ [ -n "$token" ] && set -- "$@" --continuation-token "$token"
+ resp="$(awsp "$@" 2>"$work/err")" || { err="list s3://$b/$p: $(oneline <"$work/err")"; return 1; }
+ n=$((n + 1))
+ jq -ce '[(.Contents // [])[] | .Key | strings]' <<<"$resp" >>"$work/keys" 2>/dev/null || {
+ err="list s3://$b/$p: page $n is not a listing"; return 1; }
+ trunc="$(jq -r '.IsTruncated // false' <<<"$resp")"
+ [ "$trunc" = true ] || return 0
+ token="$(jq -r '.NextContinuationToken // empty' <<<"$resp")"
+ [ -n "$token" ] || { err="list s3://$b/$p: page $n is truncated with no continuation token"; return 1; }
+ done
+}
+
+scan_bucket() { # <roster target> <bucket>
+ local t="$1" b="$2" prefix region p
+ prefix="$(coord "$t" prefix)" || { emit_fail "$b" bucket "no prefix for $t in $coords"; return; }
+ region="$(coord "$t" region)" || region=""
+ prefix="${prefix#/}"; prefix="${prefix%/}"
+ : >"$work/keys"
+ err=""
+ if [ -z "$prefix" ]; then
+ list_prefix "$b" "$region" "" || { emit_fail "$b" bucket "$err"; return; }
+ else
+ for p in "$prefix/" moves/ seeds/; do
+ list_prefix "$b" "$region" "$p" || { emit_fail "$b" bucket "$err"; return; }
+ done
+ fi
+ jq -cs --arg t "$b" --arg p "$prefix" '{target:$t,kind:"bucket",prefix:$p,ok:true,entries:(add // [] | unique)}' "$work/keys" >"$work/line" || {
+ emit_fail "$b" bucket "could not assemble the listing"; return; }
+ cat "$work/line" >>"$part"
+ echo "ok bucket:$b: $(jq '.entries|length' "$work/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, sort and
+# encoders over pipes, nothing written.
+remote_script() {
+ cat <<EOF
+export LC_ALL=C
+cd '$1' || { echo "cannot enter $1" >&2; exit 3; }
+nl='
+'
+bad=\$(find . -maxdepth 3 -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=\$(printf '%s\n' "\$list" | sort)
+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')
+printf 'hosts-used-scan v1 %s %s %s\n' "\$sum" "\${#blob}" "\$n"
+printf '%s' "\$blob" | cut -c $2-$3
+EOF
+}
+
+# ssm_run <region> <instance> <script>: run it and leave its stdout in
+# $work/stdout; on failure set $err and return 1.
+ssm_run() {
+ local r="$1" i="$2" id deadline resp status
+ id="$(awsp ssm send-command --region "$r" --instance-ids "$i" --document-name AWS-RunShellScript \
+ --comment "hosts-used scan: read-only find" --timeout-seconds 60 \
+ --parameters "$(jq -nc --arg c "$3" '{commands:[$c],executionTimeout:["120"]}')" \
+ --query Command.CommandId --output text 2>"$work/err")" || { err="ssm send-command to $i: $(oneline <"$work/err")"; return 1; }
+ [ -n "$id" ] && [ "$id" != None ] || { err="ssm send-command to $i returned no command id"; return 1; }
+ deadline=$((SECONDS + wait_s))
+ while :; do
+ sleep "$poll"
+ if resp="$(awsp ssm get-command-invocation --region "$r" --command-id "$id" --instance-id "$i" --output json 2>"$work/err")"; then
+ status="$(jq -r '.Status // empty' <<<"$resp")"
+ case "$status" in
+ Success)
+ jq -r '.StandardOutputContent // empty' <<<"$resp" >"$work/stdout"; return 0 ;;
+ Pending|InProgress|Delayed|"") ;;
+ *)
+ err="command $id on $i: $status (exit $(jq -r '.ResponseCode // "?"' <<<"$resp")): $(jq -r '.StandardErrorContent // empty' <<<"$resp" | oneline)"
+ return 1 ;;
+ esac
+ elif ! grep -q InvocationDoesNotExist "$work/err"; then
+ err="ssm get-command-invocation $id on $i: $(oneline <"$work/err")"; return 1
+ fi
+ [ "$SECONDS" -lt "$deadline" ] || { err="command $id on $i: no result after ${wait_s}s"; return 1; }
+ 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() {
+ 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
+ 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
+ if [ -z "$header" ]; then
+ 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
+ fi
+ got="$(sed -n '2p' "$work/stdout" | tr -d '\r\n')"
+ want=$((total - first + 1)); [ "$want" -gt "$page" ] && want="$page"
+ [ "${#got}" -eq "$want" ] || { err="$i: page at $first has ${#got} characters, want $want: the output was cut short"; return 1; }
+ printf '%s' "$got" >>"$work/blob"
+ first=$((first + page))
+ done
+ base64 -d <"$work/blob" 2>/dev/null | gunzip -c >"$work/listing" 2>/dev/null || { err="$i: the listing does not decode"; return 1; }
+ [ "$(sha256 <"$work/listing")" = "$(cut -d' ' -f3 <<<"$header")" ] || { err="$i: the listing's checksum does not match"; return 1; }
+ [ "$(wc -l <"$work/listing" | tr -d ' ')" = "$(cut -d' ' -f5 <<<"$header")" ] || { err="$i: the listing's line count does not match"; return 1; }
+}
+
+scan_box() { # <roster target> <box>
+ local t="$1" x="$2" inst region dir try rc
+ inst="$(coord "$t" instance)" || { emit_fail "$x" box "no instance for $t in $coords"; return; }
+ region="$(coord "$t" region)" || { emit_fail "$x" box "no region for $t in $coords"; return; }
+ dir="$(coord "$t" data_dir)" || dir=/data
+ [[ "$inst" =~ ^m?i-[0-9a-f]+$ ]] || { emit_fail "$x" box "instance $inst is not an instance id"; return; }
+ [[ "$region" =~ ^[a-z0-9-]+$ ]] || { emit_fail "$x" box "region $region is not a region"; return; }
+ [[ "$dir" =~ ^/[A-Za-z0-9._/-]*$ ]] || { emit_fail "$x" box "data_dir $dir is not a plain absolute path"; return; }
+ err=""
+ for try in 1 2 3; do
+ box_listing "$region" "$inst" "$dir"; rc=$?
+ [ "$rc" -eq 2 ] || break
+ done
+ [ "$rc" -eq 0 ] || { emit_fail "$x" box "$err"; return; }
+ jq -Rnc --arg t "$x" '{target:$t,kind:"box",ok:true,entries:[inputs | select(. != ".") | sub("^\\./"; "")]}' <"$work/listing" >"$work/line" || {
+ emit_fail "$x" box "could not assemble the listing"; return; }
+ cat "$work/line" >>"$part"
+ echo "ok box:$x: $(jq '.entries|length' "$work/line") paths" >&2
+}
+
+while IFS= read -r t; do
+ [ -n "$t" ] || continue
+ case "$t" in
+ bucket:*) scan_bucket "$t" "${t#bucket:}" ;;
+ box:*) scan_box "$t" "${t#box:}" ;;
+ *) emit_fail "${t#*:}" "${t%%:*}" "the scan does not know this kind of target" ;;
+ esac
+done <<<"$targets"
+mv "$part" "$out" || exit 2
+exit "$fail"