carlos system group: plan and status
The engine's read paths (call, box, snapshot, identity, readiness, preflight) and the plan and status verbs, ported from the script, with the Go fake of Group and Box. The leaves refuse Windows, root and a carlos box, take flags only and never open a console session. The AWS adapter gains a read-only object store for the edges files. Parity rows, cli.md section, golden skips and the census proposal are included.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/parity.md+1 −0docs/site/cli.md+25 −0docs/superpowers/notes/census-proposal-group-roll-verb.md+34 −0internal/grouproll/box.go+9 −6internal/grouproll/engine.go+843 −0internal/grouproll/engine_test.go+511 −0internal/grouproll/fake_test.go+794 −0internal/grouproll/plan.go+145 −0internal/grouproll/plan_test.go+353 −0internal/grouproll/status.go+83 −0internal/grouproll/status_test.go+166 −0internal/grouproll/testdata/live/edges-g-00000000000000000000.json+1 −0internal/grouproll/testdata/live/edges-g-11111111111111111111.json+1 −0internal/grouproll/testdata/live/status-framed-raw.txt+3 −0internal/grouprollaws/group.go+3 −0internal/grouprollaws/group_test.go+2 −1internal/grouprollaws/objects.go+61 −0internal/grouprollaws/objects_test.go+83 −0internal/provision/group_roll_verb_census_test.go+11 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-group-roll-verb.tsv+46 −0parity/cli.tsv+2 −0parity/parity.tsv+1 −0region_ha_boundary_test.go+4 −0system_group.go+223 −0system_group_other.go+8 −0system_group_test.go+284 −0system_group_unix.go+10 −0system_roles.go+12 −2testdata/clireg-golden.jsonl+2 −0
CI failed — run details
Intent
<task-notification> <task-id>a896eadf34d50bd7e</task-id> <tool-use-id>toolu_012ArtYvQPgfNt4SSnaiXebW</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/a896eadf34d50bd7e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 4: SSM transport" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE. Both Important items and the first P3 are fixed. Commit: `ae37103c grouprollaws: reap plugins only after the group kill; bound --version`, on top of `182fe4aa`. Not pushed. Fixes: 1. **Kill before reap:** the plugin's exit is now watched without reaping it, and it is reaped only after the kill decision is made. Every cut-off path kills the group first and then reaps. A normal exit is reaped with no kill, as in the script. 2. **`--version` bounded:** the version check runs in its own process group and reads its output against a deadline, with Ctrl-C handled. Every path kills the group and then reaps, so a leftover child holding the output can't stall the check. 3. **Commit pinned:** the floor comment cites aws-cli `37b21e674b4e262f2789d58b82ac72dfc63e6bdd` and the file path. I read the file at that commit, and it confirms the strict check (the `inclusive=True` there is only the outdated-plugin warning). It also showed the CLI strips all whitespace and allows at most four parts. I matched both, so `1.2.497.0.1` is now refused. Tests: new regressions where the plugin exits while its child keeps the terminal open (timeout and output-cap cases), a normal exit that sends no kill, and a bounded `--version` with a forked child and with a hang. Putting the old early reap back fails all three regression cases. Removing the deadline makes the version test hang. The grouproll and grouprollaws suites, the stable rerun (`-count=3`), the boundary test, vet on all three platforms, both cross-builds and gofmt all pass. Concerns: - My mutation runs had left two orphaned fake-plugin children. I killed both by exact PID and removed the leftover temp dir; none remain. - The second P3, recording the StartSession `Uncertain(api)` ruling in the parity exceptions, is a coordinator doc change and is not done. - The Mac exit watcher builds and passes vet but has not run on a Mac. Report (fix section appended): `.superpowers/sdd/2026-11-09-group-roll-verb/task-4-report.md`</result> <usage><subagent_tokens>201609</subagent_tokens><tool_uses>15</tool_uses><duration_ms>363561</duration_ms></usage> </task-notification>
<task-notification> <task-id>b0l3094fv</task-id> <tool-use-id>toolu_01MergWwZq5hdWsuHyHu4PCQ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/b0l3094fv.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 4 re-review" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 20.9 g CO₂e (2,575,665 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on group-roll-verb, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/parity.md b/docs/parity.md| index 2bf12513b..f935f325c 100644 |
| --- a/docs/parity.md |
| +++ b/docs/parity.md |
| @@ -409,6 +409,7 @@ Discussion #742. |
| | op-system-geoip | operator | `system geoip publish`<br>`system geoip status`<br>`system geoip off` | | The platform GeoIP database. | |
| | op-system-cutovers | operator | `system seeds-floor publish`<br>`system legacy-routes assign`<br>`system lifetimes cutover`<br>`system hosts-used status` | | One-off cutovers and floors. | |
| | op-system-roles | operator | `system box role`<br>`system group role` | | Box and group roles. | |
| +| op-system-group-roll | operator | `system group plan`<br>`system group status` | | Group maintenance from an operator machine. | |
| | op-system-demos | operator | `system demos status`<br>`system demos serving`<br>`system demos takedown`<br>`system demos takedown-status`<br>`system demos reports`<br>`system demos reports resolve` | | Demo serving, takedowns and reports. | |
| | op-system-managed-fleets | operator | `system managed-fleets show`<br>`system managed-fleets set` | | The managed-fleet catalog. | |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 635420d45..71dac10eb 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -3175,6 +3175,31 @@ carlos system host-env seed --deployment prod --region ie --kms-key alias/carlos |
| Seeding needs ssm:GetParametersByPath and ssm:PutParameter on the deployment's two parameter paths, and kms:Encrypt and kms:Decrypt on its configuration key. |
| +#### carlos system group: maintain one group member |
| + |
| +Attended maintenance of one member of a region's Auto Scaling group. It replaces |
| +`scripts/region-group-roll.py`. Run it from the deployment's operator account on |
| +the operator machine named in the card. Never run it as root or on a box. It |
| +needs the AWS profile named in the group config and the Session Manager plugin |
| +on PATH. Every command takes flags only. `--config` names the group config file. |
| + |
| +```sh |
| +carlos system group plan --config ie.json --member i-0abc --to-sha256 <sha> |
| +carlos system group roll --config ie.json --member i-0abc --to-sha256 <sha> |
| +carlos system group replace --config ie.json --member i-0abc |
| +carlos system group remove --config ie.json --member i-0abc |
| +carlos system group resume --config ie.json --transaction <id> |
| +carlos system group status --config ie.json --transaction <id> |
| +carlos system group cancel-drain --config ie.json --member i-0abc --transaction <id> |
| +carlos system group probe start --config ie.json --member i-0abc |
| +``` |
| + |
| +One transaction runs per group at a time. A replace or remove drains the member |
| +first, so its hosts move to other members before the member stops. If a step |
| +cannot be proved, the command stops and keeps the transaction for `resume`. It |
| +never guesses. `plan` changes nothing. `status` reads the saved transaction |
| +without contacting AWS. |
| + |
| ### carlos move |
| Moves into or out of an active high availability region are refused before staging, stopping or other move state is written. Imports into an active high availability region are refused before import data is written. An immutable high availability record remains refused even after the region setting is turned off. Static records are exempt only from this new regional refusal. Existing seed, runtime, shape and immutable-record refusals still apply. Operations that already started can finish or be cleaned up. |
diff --git a/docs/superpowers/notes/census-proposal-group-roll-verb.md b/docs/superpowers/notes/census-proposal-group-roll-verb.md| new file mode 100644 |
| index 000000000..d8db8201e |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-group-roll-verb.md |
| @@ -0,0 +1,34 @@ |
| +# Census approval: group-roll-verb |
| + |
| +Ruling `census-ruling-group-roll-verb`. The independent reviewer approves or rejects every change below, 20 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `.`, `internal/grouproll`, `internal/grouprollaws`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/grouproll/config.go:LoadConfig`: reads +file:ReadFile; written legacy, accepted-legacy, frozen |
| +- new `internal/grouproll/engine.go:Engine.blocked`: reads +file:Stat; written legacy, accepted-legacy, frozen |
| +- new `internal/grouproll/engine.go:Engine.preflight`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/grouproll/journal.go:Journal.read`: reads +file:ReadAll; written legacy, accepted-legacy, frozen |
| +- new `internal/grouproll/plan.go:Engine.Plan`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/grouproll/state.go:State.ActiveID`: reads +file:Lstat ×2, +file:Read, +file:ReadDir; written legacy, accepted-legacy, frozen |
| +- new `internal/grouproll/state.go:State.Create`: reads +file:Create; written legacy, accepted-legacy, frozen |
| +- new `internal/grouproll/state.go:State.Read`: reads +file:Read, +file:ReadAll; written legacy, accepted-legacy, frozen |
| +- new `internal/grouproll/state.go:randomHex`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/grouproll/state_unix.go:lstatOwner`: reads +file:Lstat; written legacy, accepted-legacy, frozen |
| +- new `internal/grouproll/state_unix.go:privateFile`: reads +file:Fstat, +file:Open; written legacy, accepted-legacy, frozen |
| +- new `internal/grouproll/state_unix.go:syncDirectory`: reads +file:Open; written legacy, accepted-legacy, frozen |
| +- new `internal/grouprollaws/group.go:Adapter.TemplateRelease`: reads +file:ReadAll; written legacy, accepted-legacy, frozen |
| +- new `internal/grouprollaws/pty_linux.go:openPTY`: reads +file:Open ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/grouprollaws/pty_unix.go:pty.run`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/grouprollaws/pty_unix.go:runVersion`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/grouprollaws/session.go:newNonce`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/grouprollaws/transport.go:boundBody.HandleDeserialize`: reads +file:ReadAll; written legacy, accepted-legacy, frozen |
| +- new `internal/grouprollaws/transport.go:boundedBody.Read`: reads +file:Read ×2; written legacy, accepted-legacy, frozen |
| +- new `system_group.go:runSystemGroup`: reads +file:Lstat; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `8924fafc5b6083858a72f45c764081abe3bcad6a6de71901470586c076c64bb6` → `69a7af2adbf2566a2b321f66c67dd64802995f4c66f99291a2781deb2f8adfb1`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-group-roll-verb.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/grouproll/box.go b/internal/grouproll/box.go| index 79ad3b408..8524dad8c 100644 |
| --- a/internal/grouproll/box.go |
| +++ b/internal/grouproll/box.go |
| @@ -178,7 +178,10 @@ func pythonEncoded(v any) ([]byte, error) { |
| return []byte(b.String()), nil |
| } |
| -func writePython(b *strings.Builder, v any) error { |
| +func writePython(b *strings.Builder, v any) error { return writePythonSep(b, v, ",", ":") } |
| + |
| +// writePythonSep is json.dumps with the given item and key separators. |
| +func writePythonSep(b *strings.Builder, v any, item, key string) error { |
| switch x := v.(type) { |
| case nil: |
| b.WriteString("null") |
| @@ -192,9 +195,9 @@ func writePython(b *strings.Builder, v any) error { |
| b.WriteByte('[') |
| for i, e := range x { |
| if i > 0 { |
| - b.WriteByte(',') |
| + b.WriteString(item) |
| } |
| - if err := writePython(b, e); err != nil { |
| + if err := writePythonSep(b, e, item, key); err != nil { |
| return err |
| } |
| } |
| @@ -209,13 +212,13 @@ func writePython(b *strings.Builder, v any) error { |
| b.WriteByte('{') |
| for i, k := range keys { |
| if i > 0 { |
| - b.WriteByte(',') |
| + b.WriteString(item) |
| } |
| if err := writePythonString(b, k); err != nil { |
| return err |
| } |
| - b.WriteByte(':') |
| - if err := writePython(b, x[k]); err != nil { |
| + b.WriteString(key) |
| + if err := writePythonSep(b, x[k], item, key); err != nil { |
| return err |
| } |
| } |
diff --git a/internal/grouproll/engine.go b/internal/grouproll/engine.go| new file mode 100644 |
| index 000000000..d174ed014 |
| --- /dev/null |
| +++ b/internal/grouproll/engine.go |
| @@ -0,0 +1,843 @@ |
| +package grouproll |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "os" |
| + "regexp" |
| + "sort" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Engine is the script's Operator (region-group-roll.py :1147): it runs |
| +// one verb against one group, journaling every provider and box call. |
| +// Task 5 ports call, box, snapshot, identity, readiness, preflight and |
| +// plan; the writing verbs build on these. |
| +type Engine struct { |
| + c Config |
| + g Group |
| + b Box |
| + s *State |
| + j *Journal |
| + clock func() time.Time |
| + sleep func(time.Duration) |
| + out io.Writer |
| + attended string |
| + |
| + // Caller answers who the provider calls run as; the engine journals |
| + // its user id in every begin row. NewEngine takes it from the Group |
| + // when the Group is one (the AWS adapter is). |
| + Caller Caller |
| + // Objects opens the object store holding a bucket (edges files, |
| + // locks, release pointers). NewEngine takes it from the Group when the |
| + // Group is one (the AWS adapter is). |
| + Objects Objects |
| + |
| + header Row |
| + lastResponseAt time.Time |
| + memberEdges map[string]map[string]any |
| + |
| + // afterEvent, when set, runs after every journaled row (tests). |
| + afterEvent func(kind string, row Row) |
| +} |
| + |
| +// Caller is the provider's "who am I": the user id the provider's own |
| +// access policy names (sts:GetCallerIdentity on AWS). |
| +type Caller interface { |
| + CallerIdentity(ctx context.Context) (userID, arn string, err error) |
| +} |
| + |
| +// Objects opens the read side of an object store bucket. |
| +type Objects interface { |
| + Bucket(name string) release.Store |
| +} |
| + |
| +// NewEngine is the script's Operator(config, adapter, state, ...). out |
| +// receives the phase lines; attendedBy is the person attending, already |
| +// resolved by the caller (the script's --attended-by, SUDO_USER or login |
| +// name). |
| +func NewEngine(c Config, g Group, b Box, s *State, clock func() time.Time, sleep func(time.Duration), out io.Writer, attendedBy string) *Engine { |
| + e := &Engine{c: c, g: g, b: b, s: s, clock: clock, sleep: sleep, out: out, attended: attendedBy} |
| + if caller, ok := g.(Caller); ok { |
| + e.Caller = caller |
| + } |
| + if objects, ok := g.(Objects); ok { |
| + e.Objects = objects |
| + } |
| + return e |
| +} |
| + |
| +// Bounds the engine applies (plan Global Constraints). |
| +const ( |
| + readinessAge = 60 * time.Second // 0 <= now - first response <= 60 s |
| + publicationMargin = 2 * time.Second // generation >= edge start + 2 s |
| + exitFreshness = 5 * time.Second // 0 <= age <= 5 s at ExitStandby |
| + objectCallBound = 15 * time.Second // the script's invoke(timeout=15) |
| + objectBodyCap = 4 << 20 // the script's 4 MiB output cap |
| + launchHookTimeout = 900 |
| + launchHookDefault = "ABANDON" |
| + launchHookLaunches = "autoscaling:EC2_INSTANCE_LAUNCHING" |
| +) |
| + |
| +var ( |
| + templateVersion = regexp.MustCompile(`^[1-9][0-9]*$`) |
| + boxRefPattern = regexp.MustCompile(`^g-[a-z0-9-]+$`) |
| +) |
| + |
| +// ms is a format 2 journal time: integer milliseconds since the epoch. |
| +func ms(t time.Time) int64 { return t.UnixMilli() } |
| + |
| +// say prints one phase line; a closed output is ignored, as the script |
| +// ignores BrokenPipeError. |
| +func (e *Engine) say(phase, detail string) { |
| + io.WriteString(e.out, Text("line", "phase", phase, "detail", detail)+"\n") |
| +} |
| + |
| +// event journals one row stamped at_ms (the script's at), when a journal |
| +// is open. |
| +func (e *Engine) event(kind string, data map[string]any) (Row, error) { |
| + if e.j == nil { |
| + return nil, nil |
| + } |
| + if kind == "phase" { |
| + iid, _ := e.header["iid"].(string) |
| + phase, _ := data["phase"].(string) |
| + e.say(phase, iid) |
| + } |
| + fields := make(map[string]any, len(data)+1) |
| + for k, v := range data { |
| + fields[k] = v |
| + } |
| + fields["at_ms"] = ms(e.clock()) |
| + row, err := e.j.Add(kind, fields) |
| + if err == nil && e.afterEvent != nil { |
| + e.afterEvent(kind, row) |
| + } |
| + return row, err |
| +} |
| + |
| +// errorName is the script's type(exc).__name__ for the error row. |
| +func errorName(err error) string { |
| + var r Refusal |
| + var u Uncertain |
| + switch { |
| + case errors.As(err, &r): |
| + return "Refusal" |
| + case errors.As(err, &u): |
| + return "Uncertain" |
| + case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): |
| + return "Canceled" |
| + } |
| + return "Error" |
| +} |
| + |
| +// call is the script's Operator.call: an intent row before the request |
| +// and a response or error row after it, with the dispatch evidence. args |
| +// are journaled as given. fresh, when not zero, is the observation the |
| +// request acts on: it must be 0-5 s old when the request is sent, counting |
| +// the intent's fsync. For a box call, onSession journals each session id. |
| +func (e *Engine) call(ctx context.Context, op string, args map[string]any, fresh time.Time, |
| + request func(ctx context.Context, onSession func(string)) (any, error)) (any, error) { |
| + // H4: only this transaction's member may enter Standby, with decrement. |
| + if op == "enter" { |
| + iid, _ := e.header["iid"].(string) |
| + if e.header == nil || args["iid"] != iid || args["decrement"] != true { |
| + return nil, refuse("h4") |
| + } |
| + } |
| + var session any |
| + if op == "session" { |
| + n := 1 |
| + if e.j != nil { |
| + for _, r := range e.j.Rows() { |
| + if r["op"] == "session" && r["kind"] == "intent" { |
| + n++ |
| + } |
| + } |
| + } |
| + session = n |
| + } |
| + intent, err := e.event("intent", map[string]any{"op": op, "args": args, "session": session}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var intentSeq any |
| + if intent != nil { |
| + intentSeq = intent["seq"] |
| + } |
| + lastSession := "" |
| + onSession := func(id string) { |
| + lastSession = id |
| + // The script's observer journals the id as the session opens; a |
| + // journal failure here surfaces at the response or error row. |
| + e.event("session-opened", map[string]any{"session_id": id, "intent": intentSeq}) |
| + } |
| + sessionID := func() any { |
| + if op != "session" || lastSession == "" { |
| + return nil |
| + } |
| + return lastSession |
| + } |
| + evidence := map[string]any{} |
| + dispatched, expired := false, false |
| + result, err := func() (any, error) { |
| + if !fresh.IsZero() { |
| + age := e.clock().Sub(fresh) |
| + evidence["exit_observation_age"] = age.Milliseconds() |
| + if age < 0 || age > exitFreshness { |
| + expired = true |
| + return nil, refuse("admission") |
| + } |
| + } |
| + dispatched = true |
| + return request(ctx, onSession) |
| + }() |
| + if err != nil { |
| + details := map[string]any{} |
| + var u Uncertain |
| + if errors.As(err, &u) { |
| + details = u.Details() |
| + } |
| + name := errorName(err) |
| + if expired { |
| + name = "ObservationExpired" |
| + } |
| + row := map[string]any{"intent": intentSeq, "op": op, "error": name, "reason": reasonOf(err), |
| + "details": details, "dispatched": dispatched, "session_id": sessionID()} |
| + for k, v := range evidence { |
| + row[k] = v |
| + } |
| + if _, jerr := e.event("error", row); jerr != nil { |
| + return nil, jerr |
| + } |
| + if op == "session" && errors.As(err, &u) && u.Timeout && lastSession != "" { |
| + id := lastSession |
| + if _, cerr := e.call(ctx, "terminate_session", map[string]any{"session_id": id}, time.Time{}, |
| + func(ctx context.Context, _ func(string)) (any, error) { |
| + return map[string]any{}, e.b.CancelSession(ctx, id) |
| + }); cerr != nil { |
| + e.say("ALERT", Text("session_cleanup")) |
| + } |
| + } |
| + return nil, err |
| + } |
| + received := e.clock() |
| + row := map[string]any{"intent": intentSeq, "op": op, "result": result, "received_at": ms(received), |
| + "session_id": sessionID()} |
| + for k, v := range evidence { |
| + row[k] = v |
| + } |
| + if _, err := e.event("response", row); err != nil { |
| + return nil, err |
| + } |
| + e.lastResponseAt = received |
| + return result, nil |
| +} |
| + |
| +// reasonOf is the script's str(exc) for the error row. |
| +func reasonOf(err error) string { |
| + var r Refusal |
| + var u Uncertain |
| + switch { |
| + case errors.As(err, &r): |
| + return r.Error() |
| + case errors.As(err, &u): |
| + return u.Error() |
| + } |
| + return err.Error() |
| +} |
| + |
| +// box is the script's Operator.box: one framed verb on one member. The |
| +// response row holds the verb's value, as the script journals it. |
| +func (e *Engine) box(ctx context.Context, iid, verb string, a BoxArgs) (BoxResult, error) { |
| + args := map[string]any{"iid": iid, "verb": verb} |
| + if a.SHA256 != "" { |
| + args["sha256"] = a.SHA256 |
| + } |
| + if a.Transaction != "" { |
| + args["transaction"] = a.Transaction |
| + } |
| + if a.Permit != nil { |
| + args["permit"] = a.Permit |
| + } |
| + var res BoxResult |
| + _, err := e.call(ctx, "session", args, time.Time{}, func(ctx context.Context, onSession func(string)) (any, error) { |
| + r, err := e.b.Run(ctx, iid, verb, a, onSession) |
| + res = r |
| + return r.Value, err |
| + }) |
| + return res, err |
| +} |
| + |
| +// status is box(iid) with the script's status dict: a status body that |
| +// is not an object is a damaged answer (the script's .get raised). |
| +func (e *Engine) status(ctx context.Context, iid string) (map[string]any, error) { |
| + r, err := e.box(ctx, iid, "status", BoxArgs{}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + s, ok := r.Value.(map[string]any) |
| + if !ok { |
| + return nil, refuse("record") |
| + } |
| + return s, nil |
| +} |
| + |
| +// snapshotView is the script's snapshot dict: the group, plus each target |
| +// group's health in config order. |
| +type snapshotView struct { |
| + View GroupView |
| + Targets []map[string]string |
| +} |
| + |
| +// groupMap is the script's "group" dict as journaled: the raw provider |
| +// states beside their phases. |
| +func groupMap(g GroupView) map[string]any { |
| + members, phases, healthy := map[string]any{}, map[string]any{}, map[string]any{} |
| + for iid, m := range g.Members { |
| + members[iid], phases[iid], healthy[iid] = m.Raw, string(m.Phase), m.Healthy |
| + } |
| + tgs := make([]any, len(g.TargetGroups)) |
| + for i, a := range g.TargetGroups { |
| + tgs[i] = a |
| + } |
| + var template any |
| + if g.Template != nil { |
| + template = g.Template |
| + } |
| + return map[string]any{"name": g.Name, "arn": g.ARN, "deployment": g.Deployment, "region": g.Region, |
| + "minimum": g.Minimum, "desired": g.Desired, "maximum": g.Maximum, |
| + "members": members, "phases": phases, "healthy": healthy, "target_groups": tgs, "template": template} |
| +} |
| + |
| +func targetsMap(t map[string]string) map[string]any { |
| + out := make(map[string]any, len(t)) |
| + for k, v := range t { |
| + out[k] = v |
| + } |
| + return out |
| +} |
| + |
| +// describe is the script's call("group"). |
| +func (e *Engine) describe(ctx context.Context) (GroupView, error) { |
| + var g GroupView |
| + _, err := e.call(ctx, "group", map[string]any{}, time.Time{}, func(ctx context.Context, _ func(string)) (any, error) { |
| + var err error |
| + g, err = e.g.Describe(ctx) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return groupMap(g), nil |
| + }) |
| + return g, err |
| +} |
| + |
| +// snapshot is the script's Operator.snapshot: the described group must be |
| +// the configured one, with a numbered launch template version. |
| +func (e *Engine) snapshot(ctx context.Context) (snapshotView, error) { |
| + g, err := e.describe(ctx) |
| + if err != nil { |
| + return snapshotView{}, err |
| + } |
| + if g.Name != e.c.Group || g.ARN != e.c.GroupARN || g.Deployment != e.c.Deployment || |
| + g.Region != e.c.Region || !sameSet(g.TargetGroups, e.c.TargetGroups) { |
| + return snapshotView{}, refuse("scope") |
| + } |
| + if v, ok := g.Template["Version"].(string); g.Template == nil || !ok || !templateVersion.MatchString(v) { |
| + return snapshotView{}, refuse("scope") |
| + } |
| + snap := snapshotView{View: g} |
| + targets := make([]any, 0, len(e.c.TargetGroups)) |
| + for _, arn := range e.c.TargetGroups { |
| + var t map[string]string |
| + _, err := e.call(ctx, "targets", map[string]any{"arn": arn}, time.Time{}, func(ctx context.Context, _ func(string)) (any, error) { |
| + var err error |
| + t, err = e.g.Targets(ctx, arn) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return targetsMap(t), nil |
| + }) |
| + if err != nil { |
| + return snapshotView{}, err |
| + } |
| + snap.Targets = append(snap.Targets, t) |
| + targets = append(targets, targetsMap(t)) |
| + } |
| + row := groupMap(g) |
| + row["targets"] = targets |
| + if _, err := e.event("snapshot", map[string]any{"group": row}); err != nil { |
| + return snapshotView{}, err |
| + } |
| + return snap, nil |
| +} |
| + |
| +func sameSet(a, b []string) bool { |
| + set := func(xs []string) map[string]bool { |
| + m := map[string]bool{} |
| + for _, x := range xs { |
| + m[x] = true |
| + } |
| + return m |
| + } |
| + sa, sb := set(a), set(b) |
| + if len(sa) != len(sb) { |
| + return false |
| + } |
| + for x := range sa { |
| + if !sb[x] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// hook is the script's call("hooks"). |
| +func (e *Engine) hook(ctx context.Context) (Hook, error) { |
| + var h Hook |
| + _, err := e.call(ctx, "hooks", map[string]any{}, time.Time{}, func(ctx context.Context, _ func(string)) (any, error) { |
| + var err error |
| + h, err = e.g.Hook(ctx) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return map[string]any{"name": h.Name, "timeout": h.Timeout, "default": h.Default, "transition": h.Transition}, nil |
| + }) |
| + return h, err |
| +} |
| + |
| +// hookOK is the immutable launch hook the script requires. |
| +func (e *Engine) hookOK(h Hook) bool { |
| + return h == Hook{Name: e.c.Hook, Timeout: launchHookTimeout, Default: launchHookDefault, Transition: launchHookLaunches} |
| +} |
| + |
| +// online is the script's call("online", iid=...). |
| +func (e *Engine) online(ctx context.Context, iid string) (bool, error) { |
| + var on bool |
| + _, err := e.call(ctx, "online", map[string]any{"iid": iid}, time.Time{}, func(ctx context.Context, _ func(string)) (any, error) { |
| + var err error |
| + on, err = e.g.Online(ctx, iid) |
| + return on, err |
| + }) |
| + return on, err |
| +} |
| + |
| +// park is the script's call("enter", iid=..., decrement=True), guarded |
| +// by H4 in call. |
| +func (e *Engine) park(ctx context.Context, iid string) (WriteResult, error) { |
| + var w WriteResult |
| + _, err := e.call(ctx, "enter", map[string]any{"iid": iid, "decrement": true}, time.Time{}, func(ctx context.Context, _ func(string)) (any, error) { |
| + var err error |
| + w, err = e.g.Park(ctx, iid) |
| + return writeMap(w), err |
| + }) |
| + return w, err |
| +} |
| + |
| +// writeMap is a provider write's answer as the script journals it. |
| +func writeMap(w WriteResult) map[string]any { |
| + if w.Activity != "" { |
| + return map[string]any{"activity": w.Activity} |
| + } |
| + if w.Uncertain { |
| + return map[string]any{"outcome": "uncertain-success", "response": w.Response} |
| + } |
| + return map[string]any{} |
| +} |
| + |
| +// edges is the script's call("edges", box_ref=...): the member's edges |
| +// file in the config bucket, read through the object store. |
| +func (e *Engine) edges(ctx context.Context, boxRef string) (map[string]any, error) { |
| + if !boxRefPattern.MatchString(boxRef) { |
| + // The script refused inside the request, after the intent row; the |
| + // key is never built from a reference it cannot take. |
| + return nil, refuse("identity") |
| + } |
| + var out map[string]any |
| + _, err := e.call(ctx, "edges", map[string]any{"box_ref": boxRef}, time.Time{}, func(ctx context.Context, _ func(string)) (any, error) { |
| + if e.Objects == nil { |
| + return nil, refuse("unsupported") |
| + } |
| + body, err := readObject(ctx, e.Objects.Bucket(e.c.Bucket), "control/edges/"+boxRef+".json") |
| + if err != nil { |
| + return nil, err |
| + } |
| + v, err := decodeObject(body) |
| + if err != nil { |
| + return nil, err |
| + } |
| + m, ok := v.(map[string]any) |
| + if !ok { |
| + // readiness's e.get() raised on a non-object: record. |
| + return nil, refuse("record") |
| + } |
| + out = m |
| + return m, nil |
| + }) |
| + return out, err |
| +} |
| + |
| +// readObject is the script's get-object through invoke: a 15-second bound, |
| +// every failure Uncertain(api) (a missing object too: the script never |
| +// read a failed GET as absence), and a body over 4 MiB refused. |
| +func readObject(parent context.Context, store release.Store, key string) ([]byte, error) { |
| + ctx, cancel := context.WithTimeout(parent, objectCallBound) |
| + defer cancel() |
| + body, _, err := store.Get(ctx, key) |
| + if err != nil { |
| + if parent.Err() != nil { |
| + return nil, parent.Err() |
| + } |
| + var u Uncertain |
| + if errors.As(err, &u) { |
| + return nil, u |
| + } |
| + if errors.Is(err, context.DeadlineExceeded) { |
| + return nil, Uncertain{Key: "api", Timeout: true} |
| + } |
| + return nil, Uncertain{Key: "api"} |
| + } |
| + if len(body) > objectBodyCap { |
| + return nil, refuse("api") |
| + } |
| + return body, nil |
| +} |
| + |
| +// decodeObject is the script's `decode(body) if body.strip() else {}`. |
| +func decodeObject(body []byte) (any, error) { |
| + if len(bytes.TrimLeft(body, " \t\n\r\v\f")) == 0 { |
| + return map[string]any{}, nil |
| + } |
| + v, err := decodeStrict(body) |
| + if err != nil { |
| + return nil, refuse("record") |
| + } |
| + return v, nil |
| +} |
| + |
| +// identity is the script's Operator.identity: the status must name this |
| +// member and the configured account, region and group, a boot, and |
| +// well-formed digests; within a transaction, the member's recorded |
| +// identity too. |
| +func (e *Engine) identity(s map[string]any, iid string) error { |
| + st, _ := DecodeBoxStatus(s) |
| + ok := st.V != nil && *st.V == 1 && strEq(st.IID, iid) && strEq(st.Account, e.c.Account) && |
| + strEq(st.Region, e.c.Region) && strEq(st.Group, e.c.Group) && |
| + st.BootID != nil && *st.BootID != "" && |
| + st.ConfigDigest != nil && SHA.MatchString(*st.ConfigDigest) && |
| + st.BinarySHA256 != nil && SHA.MatchString(*st.BinarySHA256) |
| + if !ok { |
| + return refuse("identity") |
| + } |
| + if want, has := e.header["identity"].(map[string]any); has && len(want) > 0 && iid == e.header["iid"] { |
| + for k, v := range want { |
| + if !pyEqual(s[k], v) { |
| + return refuse("identity") |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +func strEq(p *string, want string) bool { return p != nil && *p == want } |
| + |
| +// pyEqual is Python's == over decoded JSON values: True == 1 and 1.0 == 1. |
| +func pyEqual(a, b any) bool { |
| + if ia, ib := pyNumber(a), pyNumber(b); ia != nil || ib != nil { |
| + return ia != nil && ib != nil && *ia == *ib |
| + } |
| + switch x := a.(type) { |
| + case map[string]any: |
| + y, ok := b.(map[string]any) |
| + if !ok || len(x) != len(y) { |
| + return false |
| + } |
| + for k, v := range x { |
| + w, ok := y[k] |
| + if !ok || !pyEqual(v, w) { |
| + return false |
| + } |
| + } |
| + return true |
| + case []any: |
| + y, ok := b.([]any) |
| + if !ok || len(x) != len(y) { |
| + return false |
| + } |
| + for i := range x { |
| + if !pyEqual(x[i], y[i]) { |
| + return false |
| + } |
| + } |
| + return true |
| + } |
| + return sameValue(a, b) |
| +} |
| + |
| +// pyNumber is an integer, bool or integral number as Python compares |
| +// it, nil for anything else. |
| +func pyNumber(v any) *int64 { |
| + switch x := v.(type) { |
| + case int: |
| + n := int64(x) |
| + return &n |
| + case bool, int64, json.Number: |
| + return pyInt(v) |
| + } |
| + return nil |
| +} |
| + |
| +// pyTruthy is Python truthiness of a decoded JSON value. |
| +func pyTruthy(v any) bool { |
| + switch x := v.(type) { |
| + case nil: |
| + return false |
| + case bool: |
| + return x |
| + case string: |
| + return x != "" |
| + case map[string]any: |
| + return len(x) > 0 |
| + case []any: |
| + return len(x) > 0 |
| + } |
| + if n := pyNumber(v); n != nil { |
| + return *n != 0 |
| + } |
| + return true |
| +} |
| + |
| +// instant is the script's instant(): an ISO 8601 time ending in Z, else |
| +// the admission refusal. |
| +func instant(v any) (time.Time, error) { |
| + s, ok := v.(string) |
| + if !ok || len(s) == 0 || s[len(s)-1] != 'Z' { |
| + return time.Time{}, refuse("admission") |
| + } |
| + t, err := time.Parse(time.RFC3339Nano, s) |
| + if err != nil { |
| + return time.Time{}, refuse("admission") |
| + } |
| + return t, nil |
| +} |
| + |
| +// readiness is one member's admission proof (the script's |
| +// Operator.readiness without the maintenance checks, which the return |
| +// adds): two status reads around its edges file, the same edge process |
| +// and artifact in both, healthy and known, the edges file admitting it as |
| +// a serving box at least two seconds after the edge started, and the |
| +// first status answer at most 60 s old. |
| +type readiness struct { |
| + Observed time.Time |
| + Status map[string]any |
| + Generation any |
| + Edges map[string]any |
| +} |
| + |
| +func (e *Engine) readiness(ctx context.Context, iid string) (readiness, error) { |
| + s, err := e.status(ctx, iid) |
| + if err != nil { |
| + return readiness{}, err |
| + } |
| + // Session startup before the first response is not observation age. |
| + observed := e.lastResponseAt |
| + if err := e.identity(s, iid); err != nil { |
| + return readiness{}, err |
| + } |
| + ref, ok := s["box_ref"] |
| + if !ok { |
| + return readiness{}, refuse("record") |
| + } |
| + refStr, ok := ref.(string) |
| + if !ok { |
| + return readiness{}, refuse("record") |
| + } |
| + edges, err := e.edges(ctx, refStr) |
| + if err != nil { |
| + return readiness{}, err |
| + } |
| + after, err := e.status(ctx, iid) |
| + if err != nil { |
| + return readiness{}, err |
| + } |
| + if err := e.identity(after, iid); err != nil { |
| + return readiness{}, err |
| + } |
| + if ok, err := e.admitted(s, after, edges, observed); err != nil { |
| + return readiness{}, err |
| + } else if !ok { |
| + return readiness{}, refuse("admission") |
| + } |
| + if _, err := e.event("readiness", map[string]any{"iid": iid, "observed": ms(observed), "status": s, |
| + "generation": edges["generation"]}); err != nil { |
| + return readiness{}, err |
| + } |
| + return readiness{Observed: observed, Status: s, Generation: edges["generation"], Edges: edges}, nil |
| +} |
| + |
| +// admitted is readiness's admission condition, evaluated in the script's |
| +// order (a malformed time is the admission refusal, as instant() raises). |
| +func (e *Engine) admitted(s, after, edges map[string]any, observed time.Time) (bool, error) { |
| + se, _ := s["edge"].(map[string]any) |
| + if !pyTruthy(se["identity"]) || !pyEqual(s["edge"], after["edge"]) || |
| + !pyEqual(s["binary_sha256"], after["binary_sha256"]) { |
| + return false, nil |
| + } |
| + for _, x := range []map[string]any{s, after} { |
| + h, _ := x["health"].(map[string]any) |
| + edge, _ := x["edge"].(map[string]any) |
| + code := pyNumber(h["code"]) |
| + if h["state"] != "healthy" || code == nil || *code != 200 || edge["state"] != "known" { |
| + return false, nil |
| + } |
| + } |
| + v := pyNumber(edges["v"]) |
| + if v == nil || *v != 1 || !pyEqual(edges["box"], s["box_ref"]) || edges["admitted"] != true || |
| + edges["box_role"] != "serve" { |
| + return false, nil |
| + } |
| + generation, err := instant(edges["generation"]) |
| + if err != nil { |
| + return false, err |
| + } |
| + started, err := instant(se["started_at"]) |
| + if err != nil { |
| + return false, err |
| + } |
| + if generation.Before(started.Add(publicationMargin)) { |
| + return false, nil |
| + } |
| + age := e.clock().Sub(observed) |
| + return age >= 0 && age <= readinessAge, nil |
| +} |
| + |
| +// blocked is the script's state.blocked.exists(). |
| +func (e *Engine) blocked() bool { |
| + _, err := os.Stat(e.s.DivergencePath()) |
| + return err == nil |
| +} |
| + |
| +// observationOK is the approved no-hook observation for this group and |
| +// template. |
| +func (e *Engine) observationOK(obs any, template map[string]any) bool { |
| + return pyEqual(obs, map[string]any{"v": 1, "group_arn": e.c.GroupARN, "hook": e.c.Hook, |
| + "template": normalTemplate(template), "documented_no_hook": true}) |
| +} |
| + |
| +func normalTemplate(t map[string]any) any { |
| + if t == nil { |
| + return nil |
| + } |
| + n, err := normalize(t) |
| + if err != nil { |
| + return nil |
| + } |
| + return n |
| +} |
| + |
| +// shapeOK is the script's shape rule: min = desired = max = N >= 2, N |
| +// members, and the member among them. |
| +func shapeOK(g GroupView, iid string) bool { |
| + n := g.Desired |
| + _, member := g.Members[iid] |
| + return n >= 2 && g.Minimum == n && g.Maximum == n && len(g.Members) == n && member |
| +} |
| + |
| +// peerOK is the script's peer rule: in service, healthy in the group and |
| +// healthy in every target group. |
| +func peerOK(snap snapshotView, iid string) bool { |
| + m, ok := snap.View.Members[iid] |
| + if !ok || m.Raw != "InService" || !m.Healthy { |
| + return false |
| + } |
| + for _, t := range snap.Targets { |
| + if t[iid] != "healthy" { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func sortedMembers(g GroupView) []string { |
| + out := make([]string, 0, len(g.Members)) |
| + for iid := range g.Members { |
| + out = append(out, iid) |
| + } |
| + sort.Strings(out) |
| + return out |
| +} |
| + |
| +// preflight is the script's Operator.preflight: everything a writing verb |
| +// needs before its first write. digest "" is the script's None. |
| +func (e *Engine) preflight(ctx context.Context, iid, digest string) (snapshotView, map[string]any, error) { |
| + if !IID.MatchString(iid) || (digest != "" && !SHA.MatchString(digest)) { |
| + return snapshotView{}, nil, refuse("config_invalid") |
| + } |
| + if e.blocked() { |
| + return snapshotView{}, nil, refuse("blocked") |
| + } |
| + snap, err := e.snapshot(ctx) |
| + if err != nil { |
| + return snapshotView{}, nil, err |
| + } |
| + if !shapeOK(snap.View, iid) { |
| + return snapshotView{}, nil, refuse("shape") |
| + } |
| + h, err := e.hook(ctx) |
| + if err != nil { |
| + return snapshotView{}, nil, err |
| + } |
| + if !e.hookOK(h) { |
| + return snapshotView{}, nil, refuse("hook") |
| + } |
| + obs, err := e.s.Read(e.s.ObservationPath()) |
| + if err != nil { |
| + return snapshotView{}, nil, refuse("observation") |
| + } |
| + if !e.observationOK(obs, snap.View.Template) { |
| + return snapshotView{}, nil, refuse("observation") |
| + } |
| + e.memberEdges = map[string]map[string]any{} |
| + for _, m := range sortedMembers(snap.View) { |
| + on, err := e.online(ctx, m) |
| + if err != nil { |
| + return snapshotView{}, nil, err |
| + } |
| + if !on { |
| + return snapshotView{}, nil, refuse("offline") |
| + } |
| + if !peerOK(snap, m) { |
| + return snapshotView{}, nil, refuse("peer") |
| + } |
| + ready, err := e.readiness(ctx, m) |
| + if err != nil { |
| + return snapshotView{}, nil, err |
| + } |
| + e.memberEdges[m] = ready.Edges |
| + } |
| + s, err := e.status(ctx, iid) |
| + if err != nil { |
| + return snapshotView{}, nil, err |
| + } |
| + if err := e.identity(s, iid); err != nil { |
| + return snapshotView{}, nil, err |
| + } |
| + if permitState(s) != "absent" { |
| + return snapshotView{}, nil, refuse("permit") |
| + } |
| + if digest != "" && s["binary_sha256"] == digest { |
| + return snapshotView{}, nil, refuse("process") |
| + } |
| + return snap, s, nil |
| +} |
| + |
| +// permitState is s["permit"].get("state"); "" when absent. |
| +func permitState(s map[string]any) any { |
| + p, _ := s["permit"].(map[string]any) |
| + return p["state"] |
| +} |
diff --git a/internal/grouproll/engine_test.go b/internal/grouproll/engine_test.go| new file mode 100644 |
| index 000000000..fcb776cc8 |
| --- /dev/null |
| +++ b/internal/grouproll/engine_test.go |
| @@ -0,0 +1,511 @@ |
| +//go:build linux || darwin |
| + |
| +package grouproll |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// journaled is an engine holding the lock with an open log, as preflight |
| +// and readiness run inside a verb's journal. |
| +func (h *harness) journaled() *Engine { |
| + h.t.Helper() |
| + unlock, err := h.state.Lock() |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + j, err := h.state.CreatePlanLog() |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + if _, err := j.Add("begin", map[string]any{"config": h.c.Map()}); err != nil { |
| + h.t.Fatal(err) |
| + } |
| + h.t.Cleanup(func() { j.Close(); unlock() }) |
| + e := h.engine() |
| + e.j = j |
| + return e |
| +} |
| + |
| +// edgesRace rewrites the edges answer for the member, or acts at it, as |
| +// test_stale_and_racing_readiness's racing request does. |
| +func edgesRace(h *harness, race string) { |
| + h.f.wrap = func(op string, args map[string]any, r any, err error) (any, error) { |
| + if op != "edges" || err != nil || args["box_ref"] != h.f.boxes[fakeIID]["box_ref"] { |
| + return r, err |
| + } |
| + e := r.(map[string]any) |
| + switch race { |
| + case "generation": |
| + e["generation"] = h.f.edge(fakeIID)["started_at"] |
| + case "slow": |
| + h.f.sleep(61 * time.Second) |
| + case "restart": |
| + h.f.edge(fakeIID)["identity"] = h.f.edge(fakeIID)["identity"].(string) + "-restarted" |
| + } |
| + return e, nil |
| + } |
| +} |
| + |
| +// test_stale_and_racing_readiness: a generation not after the start, a |
| +// read older than 60 s, or an edge restart between the two status reads |
| +// is not admission, and nothing is written. |
| +func TestReadinessStaleAndRacing(t *testing.T) { |
| + for _, race := range []string{"generation", "slow", "restart"} { |
| + t.Run(race, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + edgesRace(h, race) |
| + _, _, err := h.journaled().preflight(context.Background(), fakeIID, newSHA) |
| + if refusalKey(err) != "admission" || len(h.f.writes) != 0 { |
| + t.Fatalf("preflight = %v, writes %v", err, h.f.writes) |
| + } |
| + |
| + h = newHarness(t, 2) |
| + edgesRace(h, race) |
| + if ok, err := h.plan(fakeIID, newSHA); ok || err != nil || |
| + !hasRefusal(refusalsOf(t, h.planLog()), "admission") || len(h.f.writes) != 0 { |
| + t.Fatalf("plan = %v, %v: %v", ok, err, refusalsOf(t, h.planLog())) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_publication_lag_and_two_second_margin, the readiness half: the |
| +// generation must be at least two seconds after the edge started. (The |
| +// roll's wait for a late publication is Task 7's.) |
| +func TestReadinessPublicationMargin(t *testing.T) { |
| + for _, tc := range []struct { |
| + lag time.Duration |
| + ok bool |
| + }{{0, false}, {time.Second, false}, {1999 * time.Millisecond, false}, {2 * time.Second, true}, {20 * time.Second, true}} { |
| + t.Run(tc.lag.String(), func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.publicationLag = tc.lag |
| + _, err := h.journaled().readiness(context.Background(), fakeIID) |
| + if tc.ok != (err == nil) || (err != nil && refusalKey(err) != "admission") { |
| + t.Fatalf("readiness = %v", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// test_readiness_clock_starts_at_first_response_and_peers_get_sixty: |
| +// session startup before the first response is not observation age. |
| +func TestReadinessClockStartsAtFirstResponse(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.before = func(op string, args map[string]any) error { |
| + if op == "session" && args["verb"] == "status" { |
| + if args["iid"] == fakePeer { |
| + h.f.sleep(20 * time.Second) |
| + } else { |
| + h.f.sleep(3 * time.Second) |
| + } |
| + } |
| + return nil |
| + } |
| + if ok, err := h.plan(fakeIID, newSHA); !ok || err != nil { |
| + t.Fatalf("plan = %v, %v: %v", ok, err, refusalsOf(t, h.planLog())) |
| + } |
| + // 59 s between the first answer and the check passes; 61 s does not. |
| + for _, tc := range []struct { |
| + wait time.Duration |
| + ok bool |
| + }{{59 * time.Second, true}, {61 * time.Second, false}} { |
| + h := newHarness(t, 2) |
| + h.f.before = func(op string, args map[string]any) error { |
| + if op == "edges" { |
| + h.f.sleep(tc.wait) |
| + } |
| + return nil |
| + } |
| + _, err := h.journaled().readiness(context.Background(), fakePeer) |
| + if tc.ok != (err == nil) { |
| + t.Fatalf("wait %v: readiness = %v", tc.wait, err) |
| + } |
| + } |
| +} |
| + |
| +// test_observation_age_includes_first_response_journal_flush: observed is |
| +// when the first answer arrived, before its response row was written. |
| +func TestReadinessObservedBeforeJournalFlush(t *testing.T) { |
| + h := newHarness(t, 2) |
| + e := h.journaled() |
| + responses := 0 |
| + e.afterEvent = func(kind string, row Row) { |
| + if kind == "response" && row["op"] == "session" { |
| + responses++ |
| + if responses == 1 { |
| + h.f.sleep(10 * time.Second) |
| + } |
| + } |
| + } |
| + start := h.f.now |
| + ready, err := e.readiness(context.Background(), fakeIID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !ready.Observed.Equal(start) { |
| + t.Fatalf("observed = %v, want %v", ready.Observed, start) |
| + } |
| + row, _ := e.j.Last("readiness", nil) |
| + if row["observed"] != start.UnixMilli() || row["iid"] != fakeIID || row["generation"] != ready.Generation { |
| + t.Fatalf("readiness row = %v", row) |
| + } |
| +} |
| + |
| +// test_live_edges_and_root_frame, the readiness half: the captured status |
| +// and edges file are a ready member. |
| +func TestReadinessLiveFrame(t *testing.T) { |
| + status := liveStatus(t) |
| + edges := liveEdges(t, fakeBox) |
| + h := newHarness(t, 2) |
| + h.f.c.Account = "123456789012" |
| + h.c.Account = "123456789012" |
| + h.f.boxes[fakeIID] = status |
| + h.f.wrap = func(op string, _ map[string]any, r any, err error) (any, error) { |
| + if op == "edges" { |
| + return copyArgs(edges), nil |
| + } |
| + return r, err |
| + } |
| + e := h.journaled() |
| + e.c.Account = "123456789012" |
| + ready, err := e.readiness(context.Background(), fakeIID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !sameValue(ready.Status, status) || !sameValue(ready.Edges, edges) { |
| + t.Fatalf("readiness = %v", ready) |
| + } |
| +} |
| + |
| +// Review Focus 1: the local clock is three minutes behind the box. The |
| +// edge's start is in this machine's future, so the published generation |
| +// cannot be two seconds after it, and readiness refuses rather than passes. |
| +func TestSkewedClockRefuses(t *testing.T) { |
| + skew := func(h *harness) { |
| + h.f.edge(fakeIID)["started_at"] = stamp(h.f.now.Add(3 * time.Minute)) |
| + } |
| + h := newHarness(t, 2) |
| + skew(h) |
| + if _, _, err := h.journaled().preflight(context.Background(), fakeIID, newSHA); refusalKey(err) != "admission" { |
| + t.Fatalf("preflight = %v", err) |
| + } |
| + h = newHarness(t, 2) |
| + skew(h) |
| + if ok, err := h.plan(fakeIID, newSHA); ok || err != nil || !hasRefusal(refusalsOf(t, h.planLog()), "admission") { |
| + t.Fatalf("plan = %v, %v", ok, err) |
| + } |
| + // The other way round, a box three minutes behind publishes a |
| + // generation the local clock reads as three minutes old: the read |
| + // itself is fresh, so readiness is the box's to prove, and it does. |
| + h = newHarness(t, 2) |
| + h.f.edge(fakeIID)["started_at"] = stamp(h.f.now.Add(-3 * time.Minute)) |
| + if _, err := h.journaled().readiness(context.Background(), fakeIID); err != nil { |
| + t.Fatalf("readiness behind = %v", err) |
| + } |
| +} |
| + |
| +// Review Focus 3: another account's transaction has parked a member of a |
| +// three-member group (minimum = desired = N-1). Preflight refuses on shape |
| +// before any write. (Tasks 7 and 10 run the same group through roll, |
| +// replace and remove and check the journal closes preflight-refused.) |
| +func TestPreflightRefusesForeignTransactionShape(t *testing.T) { |
| + foreign := func(h *harness) { |
| + h.f.minimum, h.f.desired = 2, 2 |
| + h.f.states[fakePeer] = "Standby" |
| + h.f.tg[fakePeer] = "unused" |
| + } |
| + h := newHarness(t, 3) |
| + foreign(h) |
| + _, _, err := h.journaled().preflight(context.Background(), fakeIID, newSHA) |
| + if refusalKey(err) != "shape" || len(h.f.writes) != 0 { |
| + t.Fatalf("preflight = %v, writes %v", err, h.f.writes) |
| + } |
| + for _, op := range h.f.ops() { |
| + if isWrite(op, map[string]any{"verb": "status"}) { |
| + t.Fatalf("preflight wrote: %v", h.f.ops()) |
| + } |
| + } |
| + h = newHarness(t, 3) |
| + foreign(h) |
| + if ok, err := h.plan(fakeIID, newSHA); ok || err != nil || !hasRefusal(refusalsOf(t, h.planLog()), "shape") { |
| + t.Fatalf("plan = %v, %v", ok, err) |
| + } |
| +} |
| + |
| +func TestPreflight(t *testing.T) { |
| + h := newHarness(t, 3) |
| + e := h.journaled() |
| + snap, s, err := e.preflight(context.Background(), fakeIID, newSHA) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if snap.View.Desired != 3 || len(snap.Targets) != 2 || s["binary_sha256"] != oldSHA { |
| + t.Fatalf("preflight = %+v %v", snap, s) |
| + } |
| + if len(e.memberEdges) != 3 { |
| + t.Fatalf("member edges = %v", e.memberEdges) |
| + } |
| + if len(h.f.writes) != 0 { |
| + t.Fatalf("writes = %v", h.f.writes) |
| + } |
| + |
| + for _, tc := range []struct { |
| + name string |
| + iid string |
| + sha string |
| + setup func(h *harness) |
| + want string |
| + }{ |
| + {"bad iid", "i-1", newSHA, nil, "config_invalid"}, |
| + {"bad sha", fakeIID, "B", nil, "config_invalid"}, |
| + {"no digest", fakeIID, "", nil, ""}, |
| + {"blocked", fakeIID, newSHA, func(h *harness) { |
| + h.withLock(func() { must(t, h.state.Write(h.state.DivergencePath(), map[string]any{})) }) |
| + }, "blocked"}, |
| + {"two members is the floor", fakeIID, newSHA, func(h *harness) { |
| + h.f.minimum, h.f.desired, h.f.maximum = 1, 1, 1 |
| + delete(h.f.states, fakePeer) |
| + }, "shape"}, |
| + {"max above", fakeIID, newSHA, func(h *harness) { h.f.maximum = 4 }, "shape"}, |
| + {"min below", fakeIID, newSHA, func(h *harness) { h.f.minimum = 1 }, "shape"}, |
| + {"desired below", fakeIID, newSHA, func(h *harness) { h.f.desired = 1 }, "shape"}, |
| + {"hook", fakeIID, newSHA, func(h *harness) { h.f.hookTimeout = 60 }, "hook"}, |
| + {"no observation", fakeIID, newSHA, func(h *harness) { must(t, os.Remove(h.state.ObservationPath())) }, "observation"}, |
| + {"offline", fakeIID, newSHA, func(h *harness) { h.f.online = false }, "offline"}, |
| + {"peer draining", fakeIID, newSHA, func(h *harness) { h.f.tg[fakePeer] = "draining" }, "peer"}, |
| + {"peer unhealthy", fakeIID, newSHA, func(h *harness) { |
| + h.f.wrap = func(op string, _ map[string]any, r any, err error) (any, error) { |
| + if op == "group" { |
| + g := r.(GroupView) |
| + m := g.Members[fakePeer] |
| + m.Healthy = false |
| + g.Members[fakePeer] = m |
| + return g, err |
| + } |
| + return r, err |
| + } |
| + }, "peer"}, |
| + {"permit", fakeIID, newSHA, func(h *harness) { h.f.presentPermit(fakeIID, "other", "apply") }, "permit"}, |
| + {"process", fakeIID, oldSHA, nil, "process"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + if tc.setup != nil { |
| + tc.setup(h) |
| + } |
| + _, _, err := h.journaled().preflight(context.Background(), tc.iid, tc.sha) |
| + if got := refusalKey(err); got != tc.want { |
| + t.Fatalf("preflight = %v (%s), want %q", err, got, tc.want) |
| + } |
| + if len(h.f.writes) != 0 { |
| + t.Fatalf("writes = %v", h.f.writes) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// identity(): the box must name this member, account, region and group, a |
| +// boot, and well-formed digests; within a transaction, its recorded |
| +// identity. |
| +func TestIdentity(t *testing.T) { |
| + h := newHarness(t, 2) |
| + e := h.journaled() |
| + good := func() map[string]any { return copyArgs(h.f.box(fakeIID)) } |
| + if err := e.identity(good(), fakeIID); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, tc := range []struct { |
| + key string |
| + v any |
| + }{ |
| + {"v", int64(2)}, {"v", "1"}, {"iid", fakePeer}, {"account", "111111111111"}, {"region", "us-east-1"}, |
| + {"group", "other"}, {"boot_id", ""}, {"boot_id", int64(1)}, {"config_digest", "C"}, |
| + {"binary_sha256", strings.Repeat("A", 64)}, {"binary_sha256", nil}, |
| + } { |
| + s := good() |
| + s[tc.key] = tc.v |
| + if err := e.identity(s, fakeIID); refusalKey(err) != "identity" { |
| + t.Errorf("%s = %v: identity = %v", tc.key, tc.v, err) |
| + } |
| + } |
| + // Python ==: True == 1. |
| + s := good() |
| + s["v"] = true |
| + if err := e.identity(s, fakeIID); err != nil { |
| + t.Errorf("v = true: %v", err) |
| + } |
| + // A transaction's recorded identity binds the member, not its peers. |
| + e.header = Row{"iid": fakeIID, "identity": map[string]any{"boot_id": "boot-" + fakeIID}} |
| + s = good() |
| + s["boot_id"] = "rebooted" |
| + if err := e.identity(s, fakeIID); refusalKey(err) != "identity" { |
| + t.Errorf("rebooted member: %v", err) |
| + } |
| + p := copyArgs(h.f.box(fakePeer)) |
| + if err := e.identity(p, fakePeer); err != nil { |
| + t.Errorf("peer: %v", err) |
| + } |
| +} |
| + |
| +// snapshot(): the described group must be the configured one, with a |
| +// numbered template version. |
| +func TestSnapshotScope(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + edit func(g *GroupView) |
| + }{ |
| + {"name", func(g *GroupView) { g.Name = "x" }}, |
| + {"arn", func(g *GroupView) { g.ARN = "x" }}, |
| + {"deployment", func(g *GroupView) { g.Deployment = "x" }}, |
| + {"region", func(g *GroupView) { g.Region = "x" }}, |
| + {"target groups", func(g *GroupView) { g.TargetGroups = g.TargetGroups[:1] }}, |
| + {"no template", func(g *GroupView) { g.Template = nil }}, |
| + {"latest", func(g *GroupView) { g.Template["Version"] = "$Latest" }}, |
| + {"zero", func(g *GroupView) { g.Template["Version"] = "0" }}, |
| + {"version not a string", func(g *GroupView) { g.Template["Version"] = int64(1) }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.wrap = func(op string, _ map[string]any, r any, err error) (any, error) { |
| + if op == "group" { |
| + g := r.(GroupView) |
| + tc.edit(&g) |
| + return g, err |
| + } |
| + return r, err |
| + } |
| + if _, err := h.journaled().snapshot(context.Background()); refusalKey(err) != "scope" { |
| + t.Fatalf("snapshot = %v", err) |
| + } |
| + }) |
| + } |
| + // Target groups compare as sets, as the script compares them. |
| + h := newHarness(t, 2) |
| + h.f.wrap = func(op string, _ map[string]any, r any, err error) (any, error) { |
| + if op == "group" { |
| + g := r.(GroupView) |
| + g.TargetGroups = []string{g.TargetGroups[1], g.TargetGroups[0], g.TargetGroups[1]} |
| + return g, err |
| + } |
| + return r, err |
| + } |
| + if _, err := h.journaled().snapshot(context.Background()); err != nil { |
| + t.Fatalf("reordered target groups: %v", err) |
| + } |
| +} |
| + |
| +// A failed call journals an error row with the script's evidence. |
| +func TestCallJournalsErrors(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.outage = true |
| + e := h.journaled() |
| + if _, err := e.edges(context.Background(), "g-0123456789abcdef0"); !errors.As(err, new(Uncertain)) { |
| + t.Fatalf("edges = %v", err) |
| + } |
| + row, ok := e.j.Last("error", nil) |
| + if !ok { |
| + t.Fatal("no error row") |
| + } |
| + intent, _ := e.j.Last("intent", nil) |
| + want := map[string]any{"op": "edges", "error": "Uncertain", "reason": Text("api"), "dispatched": true, |
| + "intent": intent["seq"], "details": map[string]any{}, "session_id": nil} |
| + for k, v := range want { |
| + if !sameValue(row[k], v) { |
| + t.Errorf("error %s = %v, want %v", k, row[k], v) |
| + } |
| + } |
| + if !sameValue(intent["args"], map[string]any{"box_ref": "g-0123456789abcdef0"}) { |
| + t.Errorf("intent args = %v", intent["args"]) |
| + } |
| + // A box_ref the edges key cannot take is refused before any read. |
| + before := len(h.f.calls) |
| + if _, err := e.edges(context.Background(), "../x"); refusalKey(err) != "identity" || len(h.f.calls) != before { |
| + t.Fatalf("bad box_ref = %v", err) |
| + } |
| + // An unreadable, empty, non-object or oversized edges body. |
| + for _, tc := range []struct { |
| + body []byte |
| + want string |
| + }{{[]byte("{"), "record"}, {[]byte("[1]"), "record"}, {[]byte(" \n"), ""}, {make([]byte, 4<<20+1), "api"}} { |
| + h := newHarness(t, 2) |
| + h.f.wrap = func(op string, _ map[string]any, r any, err error) (any, error) { |
| + if op == "edges" { |
| + return tc.body, nil |
| + } |
| + return r, err |
| + } |
| + got, err := h.journaled().edges(context.Background(), "g-0123456789abcdef0") |
| + if refusalKey(err) != tc.want { |
| + t.Errorf("body %.10q: %v", tc.body, err) |
| + } |
| + if tc.want == "" && len(got) != 0 { |
| + t.Errorf("empty body = %v, want {}", got) |
| + } |
| + } |
| +} |
| + |
| +// A timed-out session is terminated by id, journaled as its own call; a |
| +// failed cleanup is an ALERT and the original error stands. |
| +func TestCallTerminatesTimedOutSession(t *testing.T) { |
| + for _, cleanup := range []error{nil, Uncertain{Key: "api"}} { |
| + h := newHarness(t, 2) |
| + h.f.sessions = func(iid, verb string) []string { return []string{"s-1"} } |
| + h.f.wrap = func(op string, _ map[string]any, r any, err error) (any, error) { |
| + if op == "session" { |
| + return nil, Uncertain{Key: "remote", Timeout: true} |
| + } |
| + return r, err |
| + } |
| + h.f.cancelSession = func(string) error { return cleanup } |
| + e := h.journaled() |
| + _, err := e.box(context.Background(), fakeIID, "status", BoxArgs{}) |
| + var u Uncertain |
| + if !errors.As(err, &u) || !u.Timeout { |
| + t.Fatalf("box = %v", err) |
| + } |
| + if got := h.f.ops(); !reflect.DeepEqual(got, []string{"session", "terminate_session"}) { |
| + t.Fatalf("ops = %v", got) |
| + } |
| + opened, _ := e.j.Last("session-opened", nil) |
| + intent, _ := e.j.Last("intent", map[string]any{"op": "session"}) |
| + if opened["session_id"] != "s-1" || opened["intent"] != intent["seq"] { |
| + t.Fatalf("session-opened = %v", opened) |
| + } |
| + er, _ := e.j.Last("error", map[string]any{"op": "session"}) |
| + if er["session_id"] != "s-1" || !sameValue(er["details"], map[string]any{"timeout": true}) { |
| + t.Fatalf("error row = %v", er) |
| + } |
| + if _, ok := e.j.Last("intent", map[string]any{"op": "terminate_session", |
| + "args": map[string]any{"session_id": "s-1"}}); !ok { |
| + t.Fatal("no terminate_session intent") |
| + } |
| + alert := Text("line", "phase", "ALERT", "detail", Text("session_cleanup")) |
| + if (cleanup != nil) != strings.Contains(h.out.String(), alert) { |
| + t.Fatalf("cleanup %v, output:\n%s", cleanup, h.out.String()) |
| + } |
| + } |
| +} |
| + |
| +// H4 in call: only this transaction's member may park, with decrement. |
| +func TestCallH4(t *testing.T) { |
| + h := newHarness(t, 2) |
| + e := h.journaled() |
| + if _, err := e.park(context.Background(), fakeIID); refusalKey(err) != "h4" { |
| + t.Fatalf("park without a header = %v", err) |
| + } |
| + e.header = Row{"iid": fakeIID} |
| + if _, err := e.park(context.Background(), fakePeer); refusalKey(err) != "h4" { |
| + t.Fatalf("park of a peer = %v", err) |
| + } |
| + if len(h.f.calls) != 0 { |
| + t.Fatalf("calls = %v", h.f.ops()) |
| + } |
| +} |
diff --git a/internal/grouproll/fake_test.go b/internal/grouproll/fake_test.go| new file mode 100644 |
| index 000000000..ee3b4c02c |
| --- /dev/null |
| +++ b/internal/grouproll/fake_test.go |
| @@ -0,0 +1,794 @@ |
| +//go:build linux || darwin |
| + |
| +package grouproll |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "sort" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The Go port of the script test's Fake (scripts/region_group_roll_test.py, |
| +// class Fake): one provider group and its members' boxes, in memory, with |
| +// the script's fixtures (testdata/live, copied from |
| +// scripts/testdata/region_group_live). It implements Group, Box, Caller and |
| +// Objects, records every operation by the script's op names, and moves time |
| +// only through sleep. |
| +// |
| +// Extension points for later tasks (the script's tests wrap request and |
| +// perform; these are the same seams): |
| +// - before runs before every operation, after the call is recorded: make |
| +// time pass, mutate state, or return an error to fail the operation. |
| +// - wrap sees every operation's result and error and may replace them |
| +// (racing readiness, malformed answers). |
| +// - after runs after every write, named as the script's writes list names |
| +// it (minimum, desired, enter, exit, terminate, or the box verb). |
| +// - fault/faultAt (with failBefore) inject a death or an Uncertain at the |
| +// Nth write, exactly as the script's fault and fault_at do. A death is a |
| +// panic(fakeDeath{...}); tests recover it with expectDeath. |
| +// - every field below is plain state a test may set before a run. |
| + |
| +const ( |
| + fakeIID = "i-0123456789abcdef0" |
| + fakePeer = "i-0fedcba9876543210" |
| + fakeBox = "g-00000000000000000000" |
| + fakePBox = "g-11111111111111111111" |
| +) |
| + |
| +var ( |
| + oldSHA = strings.Repeat("a", 64) |
| + newSHA = strings.Repeat("b", 64) |
| + // fakeStart is the script Fake's now (1800000000.0). |
| + fakeStart = time.Unix(1800000000, 0).UTC() |
| + // fakeTemplate is the captured group's launch template. |
| + fakeTemplate = map[string]any{"LaunchTemplateId": "lt-0123456789abcdef0", |
| + "LaunchTemplateName": "example-group", "Version": "1"} |
| +) |
| + |
| +// fakeCall is one recorded operation: the script's op and its arguments. |
| +type fakeCall struct { |
| + Op string |
| + Args map[string]any |
| +} |
| + |
| +// fakeDeath is the script's Death: the process dies at that point. |
| +type fakeDeath struct{ At string } |
| + |
| +type fake struct { |
| + t *testing.T |
| + c Config |
| + |
| + now time.Time |
| + minimum, desired, maximum int |
| + order []string // members in the order the group lists them |
| + states map[string]string // raw provider lifecycle state ("Terminated" = gone) |
| + ec2State string // "" = not found |
| + tg map[string]string |
| + boxes map[string]map[string]any |
| + online bool |
| + admitted bool |
| + outage bool |
| + hook bool |
| + hookTimeout int |
| + lossAfterExit bool |
| + prepareBad bool |
| + deadline time.Time |
| + launches, exits, abandons int |
| + activity []Activity |
| + used map[[2]string]bool |
| + permitBodies map[string]map[string]any |
| + publicationLag time.Duration |
| + published map[string]time.Time |
| + version string |
| + previousResult any |
| + targetWarmup time.Duration |
| + targetReadyAt *time.Time |
| + templateRelease string |
| + userID string |
| + |
| + writes []string |
| + calls []fakeCall |
| + |
| + fault string // "death" or "uncertain" |
| + faultAt int |
| + failBefore bool |
| + before func(op string, args map[string]any) error |
| + wrap func(op string, args map[string]any, result any, err error) (any, error) |
| + after func(name string) |
| + // cancelSession answers CancelSession; nil succeeds. |
| + cancelSession func(id string) error |
| + // sessions, when set, names the session each box call reports. |
| + sessions func(iid, verb string) []string |
| +} |
| + |
| +// newFake is a group of n members (the script's Fake has two): the |
| +// member fakeIID, the peer fakePeer, then generated peers. |
| +func newFake(t *testing.T, n int) *fake { |
| + t.Helper() |
| + if n < 2 { |
| + t.Fatalf("newFake: n = %d, want at least two members", n) |
| + } |
| + f := &fake{ |
| + t: t, c: testConfig(t), now: fakeStart, |
| + minimum: n, desired: n, maximum: n, |
| + states: map[string]string{}, ec2State: "running", tg: map[string]string{}, |
| + boxes: map[string]map[string]any{}, online: true, admitted: true, hookTimeout: 900, |
| + used: map[[2]string]bool{}, permitBodies: map[string]map[string]any{}, |
| + publicationLag: 2 * time.Second, published: map[string]time.Time{}, |
| + version: "v0.34.0", targetWarmup: 30 * time.Second, templateRelease: "v0.34.0", |
| + userID: "AIDAEXAMPLEOPERATOR", |
| + } |
| + f.order = []string{fakeIID, fakePeer} |
| + for i := 2; i < n; i++ { |
| + f.order = append(f.order, fmt.Sprintf("i-%017x", i)) |
| + } |
| + for _, iid := range f.order { |
| + f.states[iid] = "InService" |
| + f.tg[iid] = "healthy" |
| + f.boxes[iid] = f.box(iid) |
| + f.published[iid] = f.now.Add(-5 * time.Second) |
| + } |
| + return f |
| +} |
| + |
| +// liveFixture reads a copied live fixture. |
| +func liveFixture(t *testing.T, name string) []byte { |
| + t.Helper() |
| + b, err := os.ReadFile(filepath.Join("testdata", "live", name)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +// liveStatus is the captured root status (live.status()). |
| +func liveStatus(t *testing.T) map[string]any { |
| + t.Helper() |
| + lines := strings.Split(string(liveFixture(t, "status-framed-raw.txt")), "\n") |
| + v, err := decodeStrict([]byte(lines[1])) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return v.(map[string]any) |
| +} |
| + |
| +// liveEdges is a captured edges file. |
| +func liveEdges(t *testing.T, box string) map[string]any { |
| + t.Helper() |
| + v, err := decodeStrict(liveFixture(t, "edges-"+box+".json")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return v.(map[string]any) |
| +} |
| + |
| +// stamp is the script's stamp: an RFC 3339 UTC time with a Z. |
| +func stamp(t time.Time) string { |
| + return t.UTC().Format("2006-01-02T15:04:05.999999") + "Z" |
| +} |
| + |
| +// box is the script Fake's box(iid): the live status for this member. |
| +func (f *fake) box(iid string) map[string]any { |
| + boot := "boot-" + iid |
| + s := liveStatus(f.t) |
| + s["iid"], s["boot_id"], s["account"] = iid, boot, f.c.Account |
| + s["region"], s["group"] = f.c.Region, f.c.Group |
| + s["config_digest"], s["box_ref"], s["binary_sha256"] = strings.Repeat("c", 64), "g-"+iid[2:], oldSHA |
| + e := s["edge"].(map[string]any) |
| + e["pid"], e["start_time"], e["identity"] = int64(100), "100", boot+":100:100" |
| + e["started_at"] = stamp(f.now.Add(-60 * time.Second)) |
| + return s |
| +} |
| + |
| +func (f *fake) edge(iid string) map[string]any { return f.boxes[iid]["edge"].(map[string]any) } |
| + |
| +func (f *fake) permit(iid string) map[string]any { return f.boxes[iid]["permit"].(map[string]any) } |
| + |
| +// presentPermit leaves a present permit for action on the member's box, |
| +// as another transaction's permit would be. |
| +func (f *fake) presentPermit(iid, tx, action string) { |
| + p := f.permit(iid) |
| + p["state"], p["transaction"], p["action"] = "present", tx, action |
| + p["expires"], p["accepted"], p["consumed"], p["rollback_consumed"] = f.now.Unix()+3600, true, false, false |
| +} |
| + |
| +func (f *fake) clock() time.Time { return f.now } |
| + |
| +// sleep is the script Fake's sleep: time passes, and a held return hook's |
| +// deadline abandons the member and launches a replacement. |
| +func (f *fake) sleep(d time.Duration) { |
| + f.now = f.now.Add(d) |
| + if !f.deadline.IsZero() && !f.now.Before(f.deadline) && f.states[fakeIID] == "Pending:Wait" { |
| + f.states[fakeIID] = "Terminated" |
| + f.abandons++ |
| + f.launches++ |
| + replacement := "i-" + strings.Repeat("3", 17) |
| + f.states[replacement] = "Pending:Wait" |
| + f.order = append(f.order, replacement) |
| + delete(f.tg, fakeIID) |
| + f.tg[replacement] = "initial" |
| + f.deadline = time.Time{} |
| + } |
| +} |
| + |
| +func copyArgs(args map[string]any) map[string]any { |
| + if args == nil { |
| + return map[string]any{} |
| + } |
| + n, err := normalize(args) |
| + if err != nil { |
| + panic(err) |
| + } |
| + return n.(map[string]any) |
| +} |
| + |
| +// isWrite is the script Fake's write test. |
| +func isWrite(op string, args map[string]any) bool { |
| + switch op { |
| + case "minimum", "enter", "exit", "complete", "desired", "terminate": |
| + return true |
| + case "session": |
| + return args["verb"] != "status" |
| + } |
| + return false |
| +} |
| + |
| +// request is the script Fake's request: record, inject, perform. |
| +func (f *fake) request(op string, args map[string]any, perform func() (any, error)) (any, error) { |
| + f.calls = append(f.calls, fakeCall{op, copyArgs(args)}) |
| + write := isWrite(op, args) |
| + if write && f.failBefore && f.faultAt == len(f.writes)+1 { |
| + f.faultAt = 0 |
| + panic(fakeDeath{op}) |
| + } |
| + var result any |
| + var err error |
| + if f.before != nil { |
| + err = f.before(op, args) |
| + } |
| + if err == nil { |
| + result, err = perform() |
| + } |
| + if f.wrap != nil { |
| + result, err = f.wrap(op, args, result, err) |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + if write { |
| + name := op |
| + if op == "session" { |
| + name = args["verb"].(string) |
| + } |
| + f.writes = append(f.writes, name) |
| + if f.after != nil { |
| + f.after(name) |
| + } |
| + if f.faultAt != 0 && f.faultAt == len(f.writes) { |
| + fault := f.fault |
| + f.faultAt = 0 |
| + if fault == "death" { |
| + panic(fakeDeath{name}) |
| + } |
| + return nil, Uncertain{Key: "api"} |
| + } |
| + } |
| + return result, nil |
| +} |
| + |
| +// expectDeath runs fn and reports whether it died at a fault. |
| +func expectDeath(t *testing.T, fn func()) (died bool) { |
| + t.Helper() |
| + defer func() { |
| + if r := recover(); r != nil { |
| + if _, ok := r.(fakeDeath); !ok { |
| + panic(r) |
| + } |
| + died = true |
| + } |
| + }() |
| + fn() |
| + return false |
| +} |
| + |
| +func fakePhase(raw string) Phase { |
| + switch { |
| + case raw == "InService": |
| + return Serving |
| + case raw == "EnteringStandby": |
| + return Parking |
| + case raw == "Standby": |
| + return Parked |
| + case raw == "Pending", raw == "PreInService", raw == "Pending:Proceed": |
| + return Returning |
| + case raw == "Pending:Wait": |
| + return ReturnHeld |
| + case strings.HasPrefix(raw, "Terminat"): |
| + return Leaving |
| + } |
| + return Unknown |
| +} |
| + |
| +func (f *fake) view() GroupView { |
| + g := GroupView{ |
| + Name: f.c.Group, ARN: f.c.GroupARN, Deployment: f.c.Deployment, Region: f.c.Region, |
| + Minimum: f.minimum, Desired: f.desired, Maximum: f.maximum, |
| + Members: map[string]Member{}, |
| + Template: copyArgs(fakeTemplate), |
| + TargetGroups: append([]string(nil), f.c.TargetGroups...), |
| + } |
| + for _, iid := range f.order { |
| + if raw, ok := f.states[iid]; ok && raw != "Terminated" { |
| + g.Members[iid] = Member{Phase: fakePhase(raw), Raw: raw, Healthy: true} |
| + } |
| + } |
| + return g |
| +} |
| + |
| +// Group. |
| + |
| +func (f *fake) Describe(ctx context.Context) (GroupView, error) { |
| + r, err := f.request("group", nil, func() (any, error) { return f.view(), nil }) |
| + if err != nil { |
| + return GroupView{}, err |
| + } |
| + return r.(GroupView), nil |
| +} |
| + |
| +func (f *fake) Targets(ctx context.Context, arn string) (map[string]string, error) { |
| + r, err := f.request("targets", map[string]any{"arn": arn}, func() (any, error) { |
| + if f.targetReadyAt != nil && !f.now.Before(*f.targetReadyAt) { |
| + switch f.states[fakeIID] { |
| + case "InService", "PreInService", "Pending:Proceed": |
| + f.tg[fakeIID] = "healthy" |
| + } |
| + } |
| + out := map[string]string{} |
| + for iid, s := range f.tg { |
| + out[iid] = s |
| + } |
| + return out, nil |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return r.(map[string]string), nil |
| +} |
| + |
| +func (f *fake) Hook(ctx context.Context) (Hook, error) { |
| + r, err := f.request("hooks", nil, func() (any, error) { |
| + return Hook{Name: f.c.Hook, Timeout: f.hookTimeout, Default: "ABANDON", |
| + Transition: "autoscaling:EC2_INSTANCE_LAUNCHING"}, nil |
| + }) |
| + if err != nil { |
| + return Hook{}, err |
| + } |
| + return r.(Hook), nil |
| +} |
| + |
| +func (f *fake) Online(ctx context.Context, iid string) (bool, error) { |
| + r, err := f.request("online", map[string]any{"iid": iid}, func() (any, error) { |
| + // The captured instance list names the boxes the fake runs. |
| + _, known := f.boxes[iid] |
| + return known && f.online, nil |
| + }) |
| + if err != nil { |
| + return false, err |
| + } |
| + return r.(bool), nil |
| +} |
| + |
| +func (f *fake) Activities(ctx context.Context, iid string) ([]Activity, error) { |
| + r, err := f.request("activities", map[string]any{"iid": iid}, func() (any, error) { |
| + // The script Fake's activities all name the member. |
| + if iid != fakeIID { |
| + return []Activity{}, nil |
| + } |
| + return append([]Activity{}, f.activity...), nil |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return r.([]Activity), nil |
| +} |
| + |
| +func (f *fake) Membership(ctx context.Context, iid string) (MemberRow, bool, error) { |
| + var found bool |
| + r, err := f.request("instance", map[string]any{"iid": iid}, func() (any, error) { |
| + raw, ok := f.states[iid] |
| + if !ok || raw == "Terminated" { |
| + return MemberRow{}, nil |
| + } |
| + found = true |
| + return MemberRow{IID: iid, Group: f.c.Group, Template: copyArgs(fakeTemplate), Raw: raw, |
| + Phase: fakePhase(raw), Healthy: true}, nil |
| + }) |
| + if err != nil { |
| + return MemberRow{}, false, err |
| + } |
| + return r.(MemberRow), found, nil |
| +} |
| + |
| +func (f *fake) Instance(ctx context.Context, iid string) (InstanceState, error) { |
| + r, err := f.request("ec2_instance", map[string]any{"iid": iid}, func() (any, error) { |
| + state := f.ec2State |
| + if state == "" { |
| + state = "not-found" |
| + } |
| + return InstanceState{IID: iid, State: state, Describe: map[string]any{}}, nil |
| + }) |
| + if err != nil { |
| + return InstanceState{}, err |
| + } |
| + return r.(InstanceState), nil |
| +} |
| + |
| +func (f *fake) TemplateRelease(ctx context.Context, tpl map[string]any) (string, error) { |
| + r, err := f.request("template_release", map[string]any{"template": tpl}, func() (any, error) { |
| + return f.templateRelease, nil |
| + }) |
| + if err != nil { |
| + return "", err |
| + } |
| + return r.(string), nil |
| +} |
| + |
| +func (f *fake) SetMinimum(ctx context.Context, n int) (WriteResult, error) { |
| + r, err := f.request("minimum", map[string]any{"value": n}, func() (any, error) { |
| + f.minimum = n |
| + if f.desired < f.minimum { |
| + f.desired = f.minimum |
| + } |
| + return WriteResult{Response: map[string]any{}}, nil |
| + }) |
| + if err != nil { |
| + return WriteResult{}, err |
| + } |
| + return r.(WriteResult), nil |
| +} |
| + |
| +func (f *fake) RaiseDesired(ctx context.Context, n int) (WriteResult, error) { |
| + r, err := f.request("desired", map[string]any{"value": n}, func() (any, error) { |
| + f.desired = n |
| + return WriteResult{Response: map[string]any{}}, nil |
| + }) |
| + if err != nil { |
| + return WriteResult{}, err |
| + } |
| + return r.(WriteResult), nil |
| +} |
| + |
| +func (f *fake) Park(ctx context.Context, iid string) (WriteResult, error) { |
| + r, err := f.request("enter", map[string]any{"iid": iid, "decrement": true}, func() (any, error) { |
| + if f.desired-1 < f.minimum { |
| + return nil, Uncertain{Key: "api"} // ValidationError: desired below minimum |
| + } |
| + id := fmt.Sprintf("enter-%d", len(f.activity)) |
| + f.activity = append(f.activity, Activity{ID: id, Kind: "enter", Time: f.now.UnixMilli()}) |
| + f.states[iid] = "Standby" |
| + f.tg[iid] = "unused" |
| + f.targetReadyAt = nil |
| + f.desired-- |
| + return WriteResult{Activity: id}, nil |
| + }) |
| + if err != nil { |
| + return WriteResult{}, err |
| + } |
| + return r.(WriteResult), nil |
| +} |
| + |
| +func (f *fake) Unpark(ctx context.Context, iid string) (WriteResult, error) { |
| + r, err := f.request("exit", map[string]any{"iid": iid}, func() (any, error) { |
| + f.exits++ |
| + f.desired++ |
| + f.tg[iid] = "initial" |
| + if f.hook { |
| + f.states[iid] = "Pending:Wait" |
| + f.targetReadyAt = nil |
| + f.deadline = f.now.Add(900 * time.Second) |
| + } else { |
| + f.states[iid] = "InService" |
| + ready := f.now.Add(f.targetWarmup) |
| + f.targetReadyAt = &ready |
| + } |
| + f.activity = append(f.activity, Activity{ID: "exit-1", Kind: "exit", Time: f.now.UnixMilli()}) |
| + if f.lossAfterExit { |
| + f.admitted = false |
| + } |
| + return WriteResult{Activity: "exit-1"}, nil |
| + }) |
| + if err != nil { |
| + return WriteResult{}, err |
| + } |
| + return r.(WriteResult), nil |
| +} |
| + |
| +// Terminate removes a parked member without decrement. Task 10's depart |
| +// tests extend it (activities, settle and replacement launches). |
| +func (f *fake) Terminate(ctx context.Context, iid string) (WriteResult, error) { |
| + r, err := f.request("terminate", map[string]any{"iid": iid, "decrement": false}, func() (any, error) { |
| + if f.states[iid] != "Standby" || f.desired != f.minimum { |
| + return nil, Refusal{Key: "h4"} |
| + } |
| + id := fmt.Sprintf("terminate-%d", len(f.activity)) |
| + f.activity = append(f.activity, Activity{ID: id, Kind: "terminate", Status: "Successful", Time: f.now.UnixMilli()}) |
| + f.states[iid] = "Terminated" |
| + delete(f.tg, iid) |
| + return WriteResult{Activity: id}, nil |
| + }) |
| + if err != nil { |
| + return WriteResult{}, err |
| + } |
| + return r.(WriteResult), nil |
| +} |
| + |
| +// Caller. |
| + |
| +func (f *fake) CallerIdentity(ctx context.Context) (string, string, error) { |
| + r, err := f.request("caller", nil, func() (any, error) { return f.userID, nil }) |
| + if err != nil { |
| + return "", "", err |
| + } |
| + return r.(string), "arn:aws:iam::" + f.c.Account + ":user/operator", nil |
| +} |
| + |
| +// Box. |
| + |
| +func (f *fake) Run(ctx context.Context, iid, verb string, a BoxArgs, onSession func(string)) (BoxResult, error) { |
| + args := map[string]any{"iid": iid, "verb": verb} |
| + if a.SHA256 != "" { |
| + args["sha256"] = a.SHA256 |
| + } |
| + if a.Transaction != "" { |
| + args["transaction"] = a.Transaction |
| + } |
| + if a.Permit != nil { |
| + args["permit"] = a.Permit |
| + } |
| + r, err := f.request("session", args, func() (any, error) { |
| + if f.sessions != nil { |
| + for _, id := range f.sessions(iid, verb) { |
| + onSession(id) |
| + } |
| + } |
| + return f.session(iid, verb, a) |
| + }) |
| + if err != nil { |
| + return BoxResult{}, err |
| + } |
| + n, err := normalize(r) |
| + if err != nil { |
| + return BoxResult{}, err |
| + } |
| + return BoxResult{Verb: verb, Value: n}, nil |
| +} |
| + |
| +func (f *fake) CancelSession(ctx context.Context, id string) error { |
| + _, err := f.request("terminate_session", map[string]any{"session_id": id}, func() (any, error) { |
| + if f.cancelSession != nil { |
| + return nil, f.cancelSession(id) |
| + } |
| + return map[string]any{}, nil |
| + }) |
| + return err |
| +} |
| + |
| +// session is the script Fake's perform for op "session". |
| +func (f *fake) session(iid, verb string, a BoxArgs) (any, error) { |
| + s, ok := f.boxes[iid] |
| + if !ok { |
| + return nil, Refusal{Key: "remote"} |
| + } |
| + switch verb { |
| + case "status": |
| + p := s["permit"].(map[string]any) |
| + if p["state"] == "present" { |
| + p["accepted"] = p["expires"].(int64) > f.now.Unix() |
| + p["consumed"] = f.used[[2]string{p["transaction"].(string), p["action"].(string)}] |
| + } |
| + return s, nil |
| + case "prepare": |
| + if f.prepareBad { |
| + return nil, Refusal{Key: "prepare"} |
| + } |
| + return map[string]any{"v": 1, "version": f.version, "previous_result": f.previousResult, |
| + "artifact_sha256": a.SHA256, "old_binary_sha256": oldSHA, "cache_state": "verified", |
| + "request_written": true, "config_check": "valid"}, nil |
| + case "permit": |
| + p := copyArgs(a.Permit) |
| + if f.states[fakeIID] != "Standby" || f.tg[fakeIID] != "unused" { |
| + f.t.Errorf("permit outside Standby: %v %v", f.states[fakeIID], f.tg[fakeIID]) |
| + } |
| + if f.used[[2]string{fmt.Sprint(p["transaction"]), fmt.Sprint(p["action"])}] { |
| + f.t.Errorf("permit replays a consumed action: %v", p) |
| + } |
| + f.permitBodies[iid] = p |
| + permit := liveStatus(f.t)["permit"].(map[string]any) |
| + for _, k := range []string{"transaction", "action", "expires"} { |
| + permit[k] = p[k] |
| + } |
| + permit["state"], permit["accepted"], permit["consumed"], permit["rollback_consumed"] = "present", true, false, false |
| + s["permit"] = permit |
| + return s, nil |
| + case "revoke": |
| + s["permit"] = liveStatus(f.t)["permit"] |
| + delete(f.permitBodies, iid) |
| + return map[string]any{}, nil |
| + case "apply", "rollback": |
| + p := s["permit"].(map[string]any) |
| + if p["action"] != verb || p["accepted"] != true || p["consumed"] != false || f.states[fakeIID] != "Standby" { |
| + f.t.Errorf("%s without an accepted, unconsumed permit in Standby: %v", verb, p) |
| + } |
| + f.used[[2]string{p["transaction"].(string), verb}] = true |
| + body := f.permitBodies[iid] |
| + e := s["edge"].(map[string]any) |
| + if verb == "apply" { |
| + s["binary_sha256"] = body["new_sha256"] |
| + e["pid"] = int64(101) |
| + } else { |
| + s["binary_sha256"] = body["old_sha256"] |
| + e["pid"] = int64(102) |
| + } |
| + e["identity"], e["started_at"] = verb+"-process", stamp(f.now) |
| + f.now = f.now.Add(time.Second) |
| + if f.outage { |
| + f.admitted = false |
| + h := s["health"].(map[string]any) |
| + h["state"], h["code"] = "unhealthy", int64(503) |
| + } |
| + return map[string]any{}, nil |
| + } |
| + f.t.Fatalf("fake: unsupported box verb %q", verb) |
| + return nil, nil |
| +} |
| + |
| +// Objects: the config bucket's edges files, published as the script |
| +// Fake's get-object publishes them. |
| + |
| +func (f *fake) Bucket(name string) release.Store { return fakeStore{f: f, bucket: name} } |
| + |
| +type fakeStore struct { |
| + release.Store // nil: only Get is modelled |
| + f *fake |
| + bucket string |
| +} |
| + |
| +func (s fakeStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + f := s.f |
| + ref := strings.TrimSuffix(strings.TrimPrefix(key, "control/edges/"), ".json") |
| + r, err := f.request("edges", map[string]any{"box_ref": ref}, func() (any, error) { |
| + if s.bucket != f.c.Bucket || !strings.HasPrefix(key, "control/edges/") { |
| + return nil, os.ErrNotExist |
| + } |
| + if f.outage { |
| + return nil, Uncertain{Key: "api"} |
| + } |
| + var iid string |
| + for _, m := range sortedKeys(f.boxes) { |
| + if f.boxes[m]["box_ref"] == ref { |
| + iid = m |
| + } |
| + } |
| + if iid == "" { |
| + return nil, os.ErrNotExist |
| + } |
| + started, err := time.Parse(time.RFC3339Nano, f.edge(iid)["started_at"].(string)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + lag := 2 * time.Second |
| + if iid == fakeIID { |
| + lag = f.publicationLag |
| + } |
| + if !f.now.Before(started.Add(lag)) { |
| + f.published[iid] = started.Add(lag) |
| + } |
| + fixture := fakePBox |
| + if iid == fakeIID { |
| + fixture = fakeBox |
| + } |
| + e := liveEdges(f.t, fixture) |
| + e["box"], e["box_id"], e["generation"], e["admitted"] = ref, ref, stamp(f.published[iid]), f.admitted |
| + return e, nil |
| + }) |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + if b, ok := r.([]byte); ok { |
| + return b, "etag", nil |
| + } |
| + b, err := json.Marshal(r) |
| + return b, "etag", err |
| +} |
| + |
| +func sortedKeys[V any](m map[string]V) []string { |
| + out := make([]string, 0, len(m)) |
| + for k := range m { |
| + out = append(out, k) |
| + } |
| + sort.Strings(out) |
| + return out |
| +} |
| + |
| +// ops lists the recorded operations' names. |
| +func (f *fake) ops() []string { |
| + out := make([]string, len(f.calls)) |
| + for i, c := range f.calls { |
| + out[i] = c.Op |
| + } |
| + return out |
| +} |
| + |
| +// harness is the script tests' StandbyTests.setUp: a private state |
| +// directory with the approved observation, a fake group of n members and |
| +// an engine over both. |
| +type harness struct { |
| + t *testing.T |
| + f *fake |
| + c Config |
| + root string |
| + state *State |
| + out strings.Builder |
| +} |
| + |
| +func newHarness(t *testing.T, n int) *harness { |
| + t.Helper() |
| + f := newFake(t, n) |
| + h := &harness{t: t, f: f, c: f.c, root: stateRoot(t)} |
| + s, err := OpenState(h.root, h.c, false) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.state = s |
| + h.withLock(func() { |
| + if err := s.Write(s.ObservationPath(), map[string]any{"v": 1, "group_arn": h.c.GroupARN, |
| + "hook": h.c.Hook, "template": copyArgs(fakeTemplate), "documented_no_hook": true}); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + return h |
| +} |
| + |
| +// engine is StandbyTests.engine: the fake's clock and sleep. |
| +func (h *harness) engine() *Engine { |
| + return NewEngine(h.c, h.f, h.f, h.state, h.f.clock, h.f.sleep, &h.out, "test operator") |
| +} |
| + |
| +func (h *harness) withLock(fn func()) { |
| + h.t.Helper() |
| + unlock, err := h.state.Lock() |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + defer unlock() |
| + fn() |
| +} |
| + |
| +// plan runs Plan under the lock. |
| +func (h *harness) plan(iid, sha string) (ok bool, err error) { |
| + h.withLock(func() { ok, err = h.engine().Plan(context.Background(), iid, sha) }) |
| + return ok, err |
| +} |
| + |
| +// planLog opens the one plan log read-only. |
| +func (h *harness) planLog() *Journal { |
| + h.t.Helper() |
| + paths, err := filepath.Glob(filepath.Join(h.state.Directory(), "plan-*.log")) |
| + if err != nil || len(paths) != 1 { |
| + h.t.Fatalf("plan logs = %v (%v), want one", paths, err) |
| + } |
| + j, err := openJournal(paths[0], os.Geteuid(), false, true) |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + h.t.Cleanup(func() { j.Close() }) |
| + return j |
| +} |
diff --git a/internal/grouproll/plan.go b/internal/grouproll/plan.go| new file mode 100644 |
| index 000000000..694989984 |
| --- /dev/null |
| +++ b/internal/grouproll/plan.go |
| @@ -0,0 +1,145 @@ |
| +package grouproll |
| + |
| +import ( |
| + "context" |
| + "errors" |
| +) |
| + |
| +// errAbort carries a Ctrl-C out of plan's checks: the script's check() |
| +// caught only Refusal, Uncertain and the damaged-record errors, so a |
| +// KeyboardInterrupt ended the plan. |
| +type errAbort struct{ err error } |
| + |
| +func (e errAbort) Error() string { return e.err.Error() } |
| +func (e errAbort) Unwrap() error { return e.err } |
| + |
| +// Plan is the script's Operator.plan: read the group and every member's |
| +// readiness, collect every refusal instead of stopping at the first, and |
| +// change nothing. It journals into a new plan-<hex>.log, prints the |
| +// state directory, each distinct refusal, the maintenance sequence and the |
| +// log's path, and reports whether the group is ready. |
| +// |
| +// The caller holds the group lock. Before the log is created the engine |
| +// asks the provider who it runs as, and the begin row records that user |
| +// id; a failure there (an expired SSO token) is returned with no log |
| +// written and no group read. |
| +func (e *Engine) Plan(ctx context.Context, iid, sha string) (ok bool, err error) { |
| + if !e.s.Held() { |
| + return false, refuse("busy") |
| + } |
| + if e.Caller == nil { |
| + return false, refuse("unsupported") |
| + } |
| + user, _, err := e.Caller.CallerIdentity(ctx) |
| + if err != nil { |
| + return false, err |
| + } |
| + j, err := e.s.CreatePlanLog() |
| + if err != nil { |
| + return false, err |
| + } |
| + e.j = j |
| + defer func() { |
| + j.Close() |
| + e.j = nil |
| + }() |
| + if _, err := e.event("begin", map[string]any{"config": e.c.Map(), "attended_by": e.attended, |
| + "command": "plan", "caller_user_id": user}); err != nil { |
| + return false, err |
| + } |
| + var refusals []any |
| + check := func(fn func() error) bool { |
| + err := fn() |
| + if err == nil { |
| + return true |
| + } |
| + if ctx.Err() != nil && (errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)) { |
| + panic(errAbort{err}) |
| + } |
| + var r Refusal |
| + var u Uncertain |
| + switch { |
| + case errors.As(err, &r): |
| + refusals = append(refusals, r.Error()) |
| + case errors.As(err, &u): |
| + refusals = append(refusals, u.Error()) |
| + default: |
| + refusals = append(refusals, Text("record")) |
| + } |
| + return false |
| + } |
| + require := func(cond bool, key string) func() error { |
| + return func() error { |
| + if !cond { |
| + return refuse(key) |
| + } |
| + return nil |
| + } |
| + } |
| + defer func() { |
| + if r := recover(); r != nil { |
| + a, isAbort := r.(errAbort) |
| + if !isAbort { |
| + panic(r) |
| + } |
| + ok, err = false, a.err |
| + } |
| + }() |
| + |
| + e.say("state", e.s.Directory()) |
| + check(require(IID.MatchString(iid) && SHA.MatchString(sha), "config_invalid")) |
| + check(func() error { |
| + active, err := e.s.ActiveID() |
| + if err != nil { |
| + return err |
| + } |
| + return require(active == "", "active")() |
| + }) |
| + check(require(!e.blocked(), "blocked")) |
| + var snap snapshotView |
| + snapped := check(func() (err error) { snap, err = e.snapshot(ctx); return err }) |
| + var h Hook |
| + hooked := check(func() (err error) { h, err = e.hook(ctx); return err }) |
| + // The script compares the failed read's None with the hook too. |
| + check(require(hooked && e.hookOK(h), "hook")) |
| + if snapped { |
| + check(require(shapeOK(snap.View, iid), "shape")) |
| + check(func() error { |
| + obs, err := e.s.Read(e.s.ObservationPath()) |
| + if err != nil { |
| + return err |
| + } |
| + return require(e.observationOK(obs, snap.View.Template), "observation")() |
| + }) |
| + for _, m := range sortedMembers(snap.View) { |
| + var on bool |
| + read := check(func() (err error) { on, err = e.online(ctx, m); return err }) |
| + check(require(read && on, "offline")) |
| + check(require(peerOK(snap, m), "peer")) |
| + if read && on { |
| + var ready readiness |
| + if check(func() (err error) { ready, err = e.readiness(ctx, m); return err }) && m == iid { |
| + check(require(permitState(ready.Status) == "absent", "permit")) |
| + check(require(ready.Status["binary_sha256"] != sha, "process")) |
| + } |
| + } |
| + } |
| + } |
| + if refusals == nil { |
| + refusals = []any{} |
| + } |
| + if _, err := e.event("done", map[string]any{"outcome": "plan", "refusals": refusals}); err != nil { |
| + return false, err |
| + } |
| + seen := map[string]bool{} |
| + for _, r := range refusals { |
| + reason := r.(string) |
| + if !seen[reason] { |
| + seen[reason] = true |
| + e.say("refused", reason) |
| + } |
| + } |
| + e.say("plan", Text("sequence")) |
| + e.say("journal", j.Path()) |
| + return len(refusals) == 0, nil |
| +} |
diff --git a/internal/grouproll/plan_test.go b/internal/grouproll/plan_test.go| new file mode 100644 |
| index 000000000..6c9051e46 |
| --- /dev/null |
| +++ b/internal/grouproll/plan_test.go |
| @@ -0,0 +1,353 @@ |
| +//go:build linux || darwin |
| + |
| +package grouproll |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// refusalsOf is the plan log's done.refusals. |
| +func refusalsOf(t *testing.T, j *Journal) []string { |
| + t.Helper() |
| + done, ok := j.Last("done", nil) |
| + if !ok { |
| + t.Fatal("plan log has no done row") |
| + } |
| + var out []string |
| + for _, r := range done["refusals"].([]any) { |
| + out = append(out, r.(string)) |
| + } |
| + return out |
| +} |
| + |
| +func hasRefusal(rs []string, key string) bool { |
| + for _, r := range rs { |
| + if r == Text(key) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// test_plan (RollArgvTests): a ready group plans clean, journals into one |
| +// plan log and changes nothing. |
| +func TestPlanReady(t *testing.T) { |
| + h := newHarness(t, 2) |
| + ok, err := h.plan(fakeIID, newSHA) |
| + if err != nil || !ok { |
| + t.Fatalf("plan = %v, %v\n%s", ok, err, h.out.String()) |
| + } |
| + if got := h.f.ops()[:2]; !reflect.DeepEqual(got, []string{"caller", "group"}) { |
| + t.Fatalf("first calls = %v, want the caller identity, then the group", got) |
| + } |
| + if len(h.f.writes) != 0 { |
| + t.Fatalf("writes = %v", h.f.writes) |
| + } |
| + j := h.planLog() |
| + if rs := refusalsOf(t, j); len(rs) != 0 { |
| + t.Fatalf("refusals = %v", rs) |
| + } |
| + begin := j.Rows()[0] |
| + for k, want := range map[string]any{"attended_by": "test operator", "command": "plan", |
| + "caller_user_id": h.f.userID, "format": int64(2)} { |
| + if begin[k] != want { |
| + t.Errorf("begin %s = %v, want %v", k, begin[k], want) |
| + } |
| + } |
| + if !sameValue(begin["config"], h.c.Map()) { |
| + t.Errorf("begin config = %v", begin["config"]) |
| + } |
| + if _, ok := begin["at_ms"].(int64); !ok { |
| + t.Errorf("begin at_ms = %#v, want integer milliseconds", begin["at_ms"]) |
| + } |
| + out := h.out.String() |
| + for _, line := range []string{ |
| + Text("line", "phase", "state", "detail", h.state.Directory()), |
| + Text("line", "phase", "plan", "detail", Text("sequence")), |
| + Text("line", "phase", "journal", "detail", j.Path()), |
| + } { |
| + if !strings.Contains(out, line+"\n") { |
| + t.Errorf("output lacks %q:\n%s", line, out) |
| + } |
| + } |
| + if strings.Contains(out, "refused") { |
| + t.Errorf("output names a refusal:\n%s", out) |
| + } |
| + if id, err := h.state.ActiveID(); err != nil || id != "" { |
| + t.Fatalf("plan opened a transaction: %q %v", id, err) |
| + } |
| + // Every member's readiness was read and journaled. |
| + for _, m := range []string{fakeIID, fakePeer} { |
| + if _, ok := j.Last("readiness", map[string]any{"iid": m}); !ok { |
| + t.Errorf("no readiness row for %s", m) |
| + } |
| + } |
| +} |
| + |
| +// test_plan_collects_refusals_without_mutation. |
| +func TestPlanCollectsRefusalsWithoutMutation(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.minimum = 1 |
| + h.f.online = false |
| + h.f.tg[fakePeer] = "unhealthy" |
| + ok, err := h.plan(fakeIID, newSHA) |
| + if err != nil || ok { |
| + t.Fatalf("plan = %v, %v", ok, err) |
| + } |
| + if len(h.f.writes) != 0 { |
| + t.Fatalf("writes = %v", h.f.writes) |
| + } |
| + out := h.out.String() |
| + for _, key := range []string{"offline", "shape", "peer"} { |
| + line := Text("line", "phase", "refused", "detail", Text(key)) |
| + if strings.Count(out, line+"\n") != 1 { |
| + t.Errorf("output names %q %d times, want once:\n%s", key, strings.Count(out, line), out) |
| + } |
| + } |
| + rs := refusalsOf(t, h.planLog()) |
| + // Two members offline: the log keeps every refusal, the output each once. |
| + n := 0 |
| + for _, r := range rs { |
| + if r == Text("offline") { |
| + n++ |
| + } |
| + } |
| + if n != 2 { |
| + t.Errorf("log has %d offline refusals, want 2: %v", n, rs) |
| + } |
| +} |
| + |
| +func TestPlanRefusals(t *testing.T) { |
| + cases := []struct { |
| + name string |
| + iid string |
| + sha string |
| + setup func(h *harness) |
| + want []string |
| + }{ |
| + {"bad member", "i-xyz", newSHA, nil, []string{"config_invalid", "shape"}}, |
| + {"bad sha", fakeIID, "abc", nil, []string{"config_invalid"}}, |
| + {"active", fakeIID, newSHA, func(h *harness) { |
| + h.withLock(func() { |
| + j, err := h.state.Create(Header{Transaction: "t1", IID: fakeIID, New: newSHA, AttendedBy: "x"}) |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + j.Close() |
| + }) |
| + }, []string{"active"}}, |
| + {"blocked", fakeIID, newSHA, func(h *harness) { |
| + h.withLock(func() { |
| + if err := h.state.Write(h.state.DivergencePath(), map[string]any{"v": 1}); err != nil { |
| + h.t.Fatal(err) |
| + } |
| + }) |
| + }, []string{"blocked"}}, |
| + // The script's plan reads the observation without catching a |
| + // missing file: FileNotFoundError reaches check() as record. |
| + {"no observation", fakeIID, newSHA, func(h *harness) { |
| + if err := os.Remove(h.state.ObservationPath()); err != nil { |
| + h.t.Fatal(err) |
| + } |
| + }, []string{"record"}}, |
| + {"other observation", fakeIID, newSHA, func(h *harness) { |
| + h.withLock(func() { |
| + if err := h.state.Write(h.state.ObservationPath(), map[string]any{"v": 1, "group_arn": h.c.GroupARN, |
| + "hook": h.c.Hook, "template": map[string]any{"Version": "2"}, "documented_no_hook": true}); err != nil { |
| + h.t.Fatal(err) |
| + } |
| + }) |
| + }, []string{"observation"}}, |
| + {"hook", fakeIID, newSHA, func(h *harness) { h.f.hookTimeout = 300 }, []string{"hook"}}, |
| + // A failed hook read is the api refusal, and the comparison with |
| + // nothing is the hook refusal too, as the script's plan reports. |
| + {"hook read", fakeIID, newSHA, func(h *harness) { |
| + h.f.before = func(op string, _ map[string]any) error { |
| + if op == "hooks" { |
| + return Uncertain{Key: "api"} |
| + } |
| + return nil |
| + } |
| + }, []string{"api", "hook"}}, |
| + {"permit present", fakeIID, newSHA, func(h *harness) { |
| + h.f.presentPermit(fakeIID, "other", "apply") |
| + }, []string{"permit"}}, |
| + {"already on the artifact", fakeIID, oldSHA, nil, []string{"process"}}, |
| + {"member not in group", "i-0aaaaaaaaaaaaaaa0", newSHA, nil, []string{"shape"}}, |
| + {"group read", fakeIID, newSHA, func(h *harness) { |
| + h.f.before = func(op string, _ map[string]any) error { |
| + if op == "group" { |
| + return Uncertain{Key: "api"} |
| + } |
| + return nil |
| + } |
| + }, []string{"api"}}, |
| + {"scope", fakeIID, newSHA, func(h *harness) { |
| + h.f.wrap = func(op string, _ map[string]any, r any, err error) (any, error) { |
| + if op == "group" { |
| + g := r.(GroupView) |
| + g.Deployment = "other" |
| + return g, err |
| + } |
| + return r, err |
| + } |
| + }, []string{"scope"}}, |
| + {"edges outage", fakeIID, newSHA, func(h *harness) { h.f.outage = true }, []string{"api"}}, |
| + {"plugin missing", fakeIID, newSHA, func(h *harness) { |
| + h.f.before = func(op string, _ map[string]any) error { |
| + if op == "session" { |
| + return Refusal{Key: "plugin_missing"} |
| + } |
| + return nil |
| + } |
| + }, []string{"plugin_missing"}}, |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + h := newHarness(t, 2) |
| + if tc.setup != nil { |
| + tc.setup(h) |
| + } |
| + ok, err := h.plan(tc.iid, tc.sha) |
| + if err != nil || ok { |
| + t.Fatalf("plan = %v, %v\n%s", ok, err, h.out.String()) |
| + } |
| + rs := refusalsOf(t, h.planLog()) |
| + seen := map[string]bool{} |
| + for _, r := range rs { |
| + seen[r] = true |
| + } |
| + want := map[string]bool{} |
| + for _, k := range tc.want { |
| + want[Text(k)] = true |
| + } |
| + if !reflect.DeepEqual(seen, want) { |
| + t.Fatalf("refusals = %v, want %v", rs, tc.want) |
| + } |
| + if len(h.f.writes) != 0 { |
| + t.Fatalf("writes = %v", h.f.writes) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPlanNeedsTheLock(t *testing.T) { |
| + h := newHarness(t, 2) |
| + ok, err := h.engine().Plan(context.Background(), fakeIID, newSHA) |
| + if ok || refusalKey(err) != "busy" || len(h.f.calls) != 0 { |
| + t.Fatalf("plan without the lock = %v, %v, calls %v", ok, err, h.f.calls) |
| + } |
| +} |
| + |
| +// An expired SSO token fails the first call (Review Focus 4): the plan |
| +// refuses with the api text, writes no plan log and reads no group. |
| +func TestPlanCallerIdentityFails(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.before = func(op string, _ map[string]any) error { |
| + if op == "caller" { |
| + return Uncertain{Key: "api"} |
| + } |
| + return nil |
| + } |
| + ok, err := h.plan(fakeIID, newSHA) |
| + var u Uncertain |
| + if ok || !errors.As(err, &u) || u.Key != "api" { |
| + t.Fatalf("plan = %v, %v", ok, err) |
| + } |
| + if got := h.f.ops(); !reflect.DeepEqual(got, []string{"caller"}) { |
| + t.Fatalf("calls = %v", got) |
| + } |
| + logs, _ := filepath.Glob(filepath.Join(h.state.Directory(), "plan-*.log")) |
| + if len(logs) != 0 { |
| + t.Fatalf("plan logs = %v", logs) |
| + } |
| +} |
| + |
| +func TestPlanCancelled(t *testing.T) { |
| + h := newHarness(t, 2) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + h.f.before = func(op string, _ map[string]any) error { |
| + if op == "hooks" { |
| + cancel() |
| + return context.Canceled |
| + } |
| + return nil |
| + } |
| + var ok bool |
| + var err error |
| + h.withLock(func() { ok, err = h.engine().Plan(ctx, fakeIID, newSHA) }) |
| + if ok || !errors.Is(err, context.Canceled) { |
| + t.Fatalf("plan = %v, %v", ok, err) |
| + } |
| + if n := len(h.f.calls); h.f.calls[n-1].Op != "hooks" { |
| + t.Fatalf("plan went on after Ctrl-C: %v", h.f.ops()) |
| + } |
| +} |
| + |
| +// Every provider and box call is an intent before and a response after, |
| +// with integer millisecond times, as Operator.call journals them. |
| +func TestPlanJournalsEveryCall(t *testing.T) { |
| + h := newHarness(t, 2) |
| + h.f.before = func(op string, _ map[string]any) error { |
| + h.f.sleep(1500 * time.Millisecond) |
| + return nil |
| + } |
| + if ok, err := h.plan(fakeIID, newSHA); err != nil || !ok { |
| + t.Fatalf("plan = %v, %v\n%s", ok, err, h.out.String()) |
| + } |
| + j := h.planLog() |
| + rows := j.Rows() |
| + intents, sessions := 0, int64(0) |
| + for i, r := range rows { |
| + for k, v := range r { |
| + if k == "at_ms" || k == "received_at" || k == "observed" { |
| + if _, ok := v.(int64); !ok { |
| + t.Fatalf("row %d %s = %#v, want integer milliseconds", i, k, v) |
| + } |
| + } |
| + } |
| + if r["kind"] != "intent" { |
| + continue |
| + } |
| + intents++ |
| + next := rows[i+1] |
| + if next["kind"] != "response" || next["intent"] != r["seq"] || next["op"] != r["op"] { |
| + t.Fatalf("intent %v is followed by %v", r, next) |
| + } |
| + if r["op"] == "session" { |
| + sessions++ |
| + if r["session"] != sessions { |
| + t.Fatalf("session intent %v numbered %v, want %d", r["seq"], r["session"], sessions) |
| + } |
| + if _, ok := next["session_id"]; !ok { |
| + t.Fatalf("session response lacks session_id: %v", next) |
| + } |
| + } else if v, ok := r["session"]; !ok || v != nil { |
| + t.Fatalf("non-session intent has session %v", r) |
| + } |
| + if next["received_at"].(int64) < r["at_ms"].(int64) { |
| + t.Fatalf("response before its intent: %v %v", r, next) |
| + } |
| + } |
| + // group, hooks, then per member online, status, edges, status, and |
| + // the targets per target group. |
| + if intents != 2+2*4+2 { |
| + t.Fatalf("intents = %d, ops %v", intents, h.f.ops()) |
| + } |
| + snap, ok := j.Last("snapshot", nil) |
| + if !ok { |
| + t.Fatal("no snapshot row") |
| + } |
| + g := snap["group"].(map[string]any) |
| + if g["members"].(map[string]any)[fakeIID] != "InService" || g["phases"].(map[string]any)[fakeIID] != "Serving" || |
| + g["healthy"].(map[string]any)[fakeIID] != true || len(g["targets"].([]any)) != 2 { |
| + t.Fatalf("snapshot group = %v", g) |
| + } |
| +} |
diff --git a/internal/grouproll/status.go b/internal/grouproll/status.go| new file mode 100644 |
| index 000000000..2f98b102e |
| --- /dev/null |
| +++ b/internal/grouproll/status.go |
| @@ -0,0 +1,83 @@ |
| +package grouproll |
| + |
| +import ( |
| + "io" |
| + "strings" |
| +) |
| + |
| +// SavedStatus is the script's Operator.saved_status: the saved |
| +// transaction as one object, read from its journal alone. Times are the |
| +// format 2 journal's integer milliseconds (last_observed_at is the last |
| +// snapshot's at_ms). |
| +func SavedStatus(j *Journal) map[string]any { |
| + rows := j.Rows() |
| + header := rows[0] |
| + last := func(kind string) Row { |
| + r, _ := j.Last(kind, nil) |
| + return r |
| + } |
| + valid, phase, observed := last("validated"), last("phase"), last("snapshot") |
| + newSHA, ok := valid["new"] |
| + if !ok { |
| + newSHA = header["new"] |
| + } |
| + phaseName, ok := phase["phase"] |
| + if !ok { |
| + phaseName = "preflight" |
| + } |
| + var done any |
| + if r := last("done"); r != nil { |
| + done = r |
| + } |
| + sessions := 0 |
| + for _, r := range rows { |
| + if r["kind"] == "intent" && r["op"] == "session" { |
| + sessions++ |
| + } |
| + } |
| + return map[string]any{ |
| + "transaction": header["transaction"], "iid": header["iid"], |
| + "old_sha256": valid["old"], "new_sha256": newSHA, |
| + "phase": phaseName, "done": done, |
| + "last_observed_at": observed["at_ms"], "last_observed_group": observed["group"], |
| + "sessions": sessions, "last_event": rows[len(rows)-1], "journal": j.Path(), |
| + } |
| +} |
| + |
| +// Status is the status verb (script main's status branch): open the |
| +// group's state read-only, load transaction tx read-only, and print its |
| +// SavedStatus as one line of json.dumps(sort_keys=True). It takes no lock |
| +// and contacts no provider. |
| +func Status(stateDir string, c Config, tx string, w io.Writer) error { |
| + s, err := OpenState(stateDir, c, true) |
| + if err != nil { |
| + return err |
| + } |
| + j, err := s.Load(tx, true) |
| + if err != nil { |
| + return err |
| + } |
| + defer j.Close() |
| + line, err := pythonDumps(SavedStatus(j)) |
| + if err != nil { |
| + return refuse("record") |
| + } |
| + if _, err := io.WriteString(w, line+"\n"); err != nil { |
| + return refuse("record") |
| + } |
| + return nil |
| +} |
| + |
| +// pythonDumps is json.dumps(v, sort_keys=True): Python's default ", " and |
| +// ": " separators and ensure_ascii. |
| +func pythonDumps(v any) (string, error) { |
| + n, err := normalize(v) |
| + if err != nil { |
| + return "", err |
| + } |
| + var b strings.Builder |
| + if err := writePythonSep(&b, n, ", ", ": "); err != nil { |
| + return "", err |
| + } |
| + return b.String(), nil |
| +} |
diff --git a/internal/grouproll/status_test.go b/internal/grouproll/status_test.go| new file mode 100644 |
| index 000000000..eab6c0120 |
| --- /dev/null |
| +++ b/internal/grouproll/status_test.go |
| @@ -0,0 +1,166 @@ |
| +//go:build linux || darwin |
| + |
| +package grouproll |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// seed is CLIHarness.seed: a roll transaction with its validated row. |
| +func (h *harness) seed(validated bool) string { |
| + h.t.Helper() |
| + tx := "argv-test" |
| + h.withLock(func() { |
| + j, err := h.state.Create(Header{Transaction: tx, IID: fakeIID, New: newSHA, AttendedBy: "argv operator"}) |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + defer j.Close() |
| + if validated { |
| + s := h.f.boxes[fakeIID] |
| + identity := map[string]any{} |
| + for _, k := range []string{"iid", "boot_id", "account", "region", "group", "config_digest", "box_ref"} { |
| + identity[k] = s[k] |
| + } |
| + if _, err := j.Add("validated", map[string]any{"old": oldSHA, "new": newSHA, "n": 2, |
| + "members": []any{fakeIID, fakePeer}, "template": copyArgs(fakeTemplate), |
| + "original_process": h.f.edge(fakeIID)["identity"], "identity": identity}); err != nil { |
| + h.t.Fatal(err) |
| + } |
| + } |
| + }) |
| + return tx |
| +} |
| + |
| +func snapshotFiles(t *testing.T, dir string) map[string]string { |
| + t.Helper() |
| + out := map[string]string{} |
| + entries, err := os.ReadDir(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, e := range entries { |
| + b, err := os.ReadFile(filepath.Join(dir, e.Name())) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out[e.Name()] = string(b) |
| + } |
| + return out |
| +} |
| + |
| +// test_status and test_status_is_lock_free_and_read_only: status reads |
| +// the saved transaction while another operator holds the lock, prints one |
| +// JSON object and changes no file. |
| +func TestStatusLockFreeAndReadOnly(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seed(true) |
| + before := snapshotFiles(t, h.state.Directory()) |
| + var out bytes.Buffer |
| + h.withLock(func() { |
| + if err := Status(h.root, h.c, tx, &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + if len(h.f.calls) != 0 { |
| + t.Fatalf("calls = %v", h.f.ops()) |
| + } |
| + if after := snapshotFiles(t, h.state.Directory()); !reflect.DeepEqual(before, after) { |
| + t.Fatal("status changed the state directory") |
| + } |
| + line := out.String() |
| + if strings.Count(line, "\n") != 1 || !strings.HasSuffix(line, "\n") { |
| + t.Fatalf("status printed %q, want one line", line) |
| + } |
| + var got map[string]any |
| + if err := json.Unmarshal([]byte(line), &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got["transaction"] != tx || got["iid"] != fakeIID || got["new_sha256"] != newSHA || got["old_sha256"] != oldSHA { |
| + t.Fatalf("status = %v", got) |
| + } |
| + // json.dumps(sort_keys=True): ", " and ": " separators, ASCII only. |
| + if !strings.HasPrefix(line, `{"done": null, "iid": "`+fakeIID+`", "journal": "`) { |
| + t.Fatalf("status is not Python's json.dumps layout: %s", line) |
| + } |
| +} |
| + |
| +func TestSavedStatus(t *testing.T) { |
| + h := newHarness(t, 2) |
| + tx := h.seed(false) |
| + j, err := h.state.Load(tx, true) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer j.Close() |
| + got := SavedStatus(j) |
| + want := map[string]any{ |
| + "transaction": tx, "iid": fakeIID, "old_sha256": nil, "new_sha256": newSHA, "phase": "preflight", |
| + "done": nil, "last_observed_at": nil, "last_observed_group": nil, "sessions": 0, |
| + "last_event": j.Rows()[0], "journal": j.Path(), |
| + } |
| + if !sameValue(got, want) { |
| + t.Fatalf("status = %v\nwant %v", got, want) |
| + } |
| + |
| + // A transaction with phases, a snapshot and sessions. |
| + h.withLock(func() { |
| + w, err := h.state.Load(tx, false) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer w.Close() |
| + for _, r := range []struct { |
| + kind string |
| + f map[string]any |
| + }{ |
| + {"validated", map[string]any{"old": oldSHA, "new": newSHA}}, |
| + {"snapshot", map[string]any{"at_ms": int64(1800000000000), "group": map[string]any{"name": "g"}}}, |
| + {"intent", map[string]any{"op": "session", "session": 1}}, |
| + {"intent", map[string]any{"op": "group", "session": nil}}, |
| + {"intent", map[string]any{"op": "session", "session": 2}}, |
| + {"phase", map[string]any{"phase": "standby"}}, |
| + {"done", map[string]any{"outcome": "returned"}}, |
| + } { |
| + if _, err := w.Add(r.kind, r.f); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + }) |
| + j2, err := h.state.Load(tx, true) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer j2.Close() |
| + got = SavedStatus(j2) |
| + rows := j2.Rows() |
| + for k, v := range map[string]any{"old_sha256": oldSHA, "phase": "standby", "sessions": 2, |
| + "last_observed_at": int64(1800000000000), "last_observed_group": map[string]any{"name": "g"}, |
| + "done": rows[len(rows)-1], "last_event": rows[len(rows)-1]} { |
| + if !sameValue(got[k], v) { |
| + t.Errorf("%s = %v, want %v", k, got[k], v) |
| + } |
| + } |
| +} |
| + |
| +func TestStatusRefusals(t *testing.T) { |
| + h := newHarness(t, 2) |
| + if err := Status(h.root, h.c, "absent", new(bytes.Buffer)); refusalKey(err) != "record" { |
| + t.Fatalf("absent = %v", err) |
| + } |
| + if err := Status(h.root, h.c, "-bad id", new(bytes.Buffer)); refusalKey(err) != "record" { |
| + t.Fatalf("bad id = %v", err) |
| + } |
| + tx := h.seed(true) |
| + other := h.c |
| + other.Bucket = "other-bucket" |
| + if err := Status(h.root, other, tx, new(bytes.Buffer)); refusalKey(err) == "" { |
| + t.Fatalf("other config = %v", err) |
| + } |
| +} |
diff --git a/internal/grouproll/testdata/live/edges-g-00000000000000000000.json b/internal/grouproll/testdata/live/edges-g-00000000000000000000.json| new file mode 100644 |
| index 000000000..4ce5edbe5 |
| --- /dev/null |
| +++ b/internal/grouproll/testdata/live/edges-g-00000000000000000000.json |
| @@ -0,0 +1 @@ |
| +{"box_role":"serve","admitted":true,"drained":false,"v":1,"box":"g-00000000000000000000","eip":"198.51.100.10","region":"eu-west-1","private_ip":"192.0.2.10","private_cidr":"192.0.2.0/24","data_bucket":"example-bucket","data_bucket_region":"eu-west-1","hibernation_configured":true,"serves_shared_pool":false,"accepts_inbound":true,"named_pools":["example-app"],"served_pools":["example-app"],"burst_notices":true,"secrets_key_fp":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","box_id":"g-00000000000000000000","capabilities":["lifetimes-1","region-ha-1","names-2","offline-move-1","offline-stage-1"],"headroom":{"mem_free_mib":695,"disk_free_mib":17707,"awake":0,"mem_total_mib":927,"disk_total_mib":19925},"moves_protocol":1,"seeds_protocol":1,"addrs":["203.0.113.10","203.0.113.11","192.0.2.10","2001:db8::3","2001:db8::4"],"box_mem_total_mib":927,"generation":"2026-11-05T15:47:45Z","hosts":{"example.com":{"role":"home","platform":true,"account":"example-account","app":"example-app"}}} |
| \ No newline at end of file |
diff --git a/internal/grouproll/testdata/live/edges-g-11111111111111111111.json b/internal/grouproll/testdata/live/edges-g-11111111111111111111.json| new file mode 100644 |
| index 000000000..297e4b4df |
| --- /dev/null |
| +++ b/internal/grouproll/testdata/live/edges-g-11111111111111111111.json |
| @@ -0,0 +1 @@ |
| +{"box_role":"serve","admitted":true,"drained":false,"v":1,"box":"g-11111111111111111111","eip":"198.51.100.11","region":"eu-west-1","private_ip":"192.0.2.11","private_cidr":"192.0.2.0/24","data_bucket":"example-bucket","data_bucket_region":"eu-west-1","hibernation_configured":true,"serves_shared_pool":false,"accepts_inbound":true,"named_pools":["example-app"],"served_pools":["example-app"],"burst_notices":true,"secrets_key_fp":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","box_id":"g-11111111111111111111","capabilities":["lifetimes-1","region-ha-1","names-2","offline-move-1","offline-stage-1"],"headroom":{"mem_free_mib":664,"disk_free_mib":17707,"awake":0,"mem_total_mib":927,"disk_total_mib":19925,"apps":{"example-account/example-app":1}},"moves_protocol":1,"seeds_protocol":1,"addrs":["203.0.113.10","203.0.113.11","192.0.2.11","2001:db8::1","2001:db8::2"],"box_mem_total_mib":927,"generation":"2026-11-05T15:47:44Z","hosts":{"example.com":{"role":"home","platform":true,"account":"example-account","app":"example-app"}}} |
| \ No newline at end of file |
diff --git a/internal/grouproll/testdata/live/status-framed-raw.txt b/internal/grouproll/testdata/live/status-framed-raw.txt| new file mode 100644 |
| index 000000000..9d7e35f2f |
| --- /dev/null |
| +++ b/internal/grouproll/testdata/live/status-framed-raw.txt |
| @@ -0,0 +1,3 @@ |
| +00000000000000000000000000000000:BEGIN |
| +{"v":1,"iid":"i-0123456789abcdef0","boot_id":"01234567-89ab-cdef-0123-456789abcdef","account":"123456789012","region":"eu-west-1","group":"example-group","config_digest":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc","box_ref":"g-00000000000000000000","edge":{"state":"known","pid":1910,"start_time":"4468","started_at":"2026-11-05T15:19:10Z","started_at_error":null,"identity":"01234567-89ab-cdef-0123-456789abcdef:1910:4468","error":null},"binary_sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","binary_error":null,"permit":{"state":"absent","transaction":null,"action":null,"expires":null,"consumed":null,"accepted":null,"rollback_consumed":null,"error":null},"health":{"state":"healthy","code":200,"error":null}} |
| +00000000000000000000000000000000:END:0 |
diff --git a/internal/grouprollaws/group.go b/internal/grouprollaws/group.go| index 272bdd975..97c91a621 100644 |
| --- a/internal/grouprollaws/group.go |
| +++ b/internal/grouprollaws/group.go |
| @@ -21,6 +21,7 @@ import ( |
| "github.com/aws/aws-sdk-go-v2/service/ec2" |
| ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" |
| elbv2 "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| "github.com/aws/aws-sdk-go-v2/service/ssm" |
| ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types" |
| "github.com/aws/aws-sdk-go-v2/service/sts" |
| @@ -40,6 +41,7 @@ type Adapter struct { |
| ec2 *ec2.Client |
| ssm *ssm.Client |
| sts *sts.Client |
| + s3 *s3.Client // objects.go: edges files, locks, release pointers |
| plugin pluginCheck // session.go: the plugin's path and version, once |
| } |
| @@ -59,6 +61,7 @@ func newAdapter(cfg aws.Config, c grouproll.Config) *Adapter { |
| ec2: ec2.NewFromConfig(cfg, func(o *ec2.Options) { o.BaseEndpoint = nil }), |
| ssm: ssm.NewFromConfig(cfg, func(o *ssm.Options) { o.BaseEndpoint = nil }), |
| sts: sts.NewFromConfig(cfg, func(o *sts.Options) { o.BaseEndpoint = nil }), |
| + s3: newS3(cfg), |
| } |
| } |
diff --git a/internal/grouprollaws/group_test.go b/internal/grouprollaws/group_test.go| index 6fba4faf3..3b871d33f 100644 |
| --- a/internal/grouprollaws/group_test.go |
| +++ b/internal/grouprollaws/group_test.go |
| @@ -516,7 +516,8 @@ func TestWriteShapes(t *testing.T) { |
| sort.Strings(names) |
| // Run, CancelSession and CheckPlugin (session.go) are the Session |
| // Manager transport: none touches the group's capacity. |
| - want := []string{"Activities", "CallerIdentity", "CancelSession", "CheckPlugin", "Describe", "Hook", |
| + // Bucket (objects.go) is a read-only object store. |
| + want := []string{"Activities", "Bucket", "CallerIdentity", "CancelSession", "CheckPlugin", "Describe", "Hook", |
| "Instance", "Membership", "Online", "Park", "RaiseDesired", "Run", "SetMinimum", "Targets", |
| "TemplateRelease", "Terminate", "Unpark"} |
| if !reflect.DeepEqual(names, want) { |
diff --git a/internal/grouprollaws/objects.go b/internal/grouprollaws/objects.go| new file mode 100644 |
| index 000000000..5927954c4 |
| --- /dev/null |
| +++ b/internal/grouprollaws/objects.go |
| @@ -0,0 +1,61 @@ |
| +package grouprollaws |
| + |
| +import ( |
| + "context" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +var _ grouproll.Objects = (*Adapter)(nil) |
| + |
| +// newS3 is the adapter's S3 client: the configured region's endpoint, |
| +// never a configured one (spec §4), checksums only where required, as |
| +// release.S3Store sets them. |
| +func newS3(cfg aws.Config) *s3.Client { |
| + return s3.NewFromConfig(cfg, func(o *s3.Options) { |
| + o.BaseEndpoint = nil |
| + o.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired |
| + o.ResponseChecksumValidation = aws.ResponseChecksumValidationWhenRequired |
| + }) |
| +} |
| + |
| +// Bucket is the read side of bucket (edges files, locks, release |
| +// pointers), the script's s3api get-object and list-objects-v2: each read |
| +// is bounded as every provider call is, every failure (a missing object |
| +// too) is Uncertain(api), and the store has no write path. |
| +func (a *Adapter) Bucket(name string) release.Store { |
| + return readStore{s: &release.S3Store{Client: a.s3, Bucket: name}} |
| +} |
| + |
| +type readStore struct{ s *release.S3Store } |
| + |
| +type object struct { |
| + body []byte |
| + etag string |
| +} |
| + |
| +func (r readStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + out, err := call(ctx, func(ctx context.Context) (object, error) { |
| + b, etag, err := r.s.Get(ctx, key) |
| + return object{b, etag}, err |
| + }) |
| + return out.body, out.etag, err |
| +} |
| + |
| +func (r readStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + return call(ctx, func(ctx context.Context) ([]string, error) { return r.s.List(ctx, prefix) }) |
| +} |
| + |
| +func (r readStore) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + return call(ctx, func(ctx context.Context) ([]string, error) { return r.s.ListDirs(ctx, prefix) }) |
| +} |
| + |
| +func (readStore) Put(context.Context, string, []byte, string) (string, error) { |
| + return "", grouproll.Refusal{Key: "unsupported"} |
| +} |
| + |
| +func (readStore) Delete(context.Context, string) error { return grouproll.Refusal{Key: "unsupported"} } |
diff --git a/internal/grouprollaws/objects_test.go b/internal/grouprollaws/objects_test.go| new file mode 100644 |
| index 000000000..ab6dcaee5 |
| --- /dev/null |
| +++ b/internal/grouprollaws/objects_test.go |
| @@ -0,0 +1,83 @@ |
| +package grouprollaws |
| + |
| +import ( |
| + "bytes" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| +) |
| + |
| +// s3Recorder answers S3 REST requests: GETs of objects, nothing else. |
| +type s3Recorder struct { |
| + mu sync.Mutex |
| + reqs []*http.Request |
| + status int |
| + body string |
| +} |
| + |
| +func (r *s3Recorder) Do(req *http.Request) (*http.Response, error) { |
| + r.mu.Lock() |
| + r.reqs = append(r.reqs, req) |
| + r.mu.Unlock() |
| + status, body := r.status, r.body |
| + if status != 200 && body == "" { |
| + body = `<Error><Code>NoSuchKey</Code><Message>x</Message></Error>` |
| + if status != 404 { |
| + body = `<Error><Code>InternalError</Code><Message>x</Message></Error>` |
| + } |
| + } |
| + return &http.Response{StatusCode: status, Status: http.StatusText(status), |
| + Header: http.Header{"Content-Type": []string{"application/xml"}, "Etag": []string{`"e"`}}, |
| + Body: io.NopCloser(bytes.NewReader([]byte(body))), |
| + Request: req}, nil |
| +} |
| + |
| +// The edges files are read through the adapter's object store: the |
| +// configured region's S3 endpoint whatever the environment names, every |
| +// failure (a missing object too) an api Uncertain, and no write path. |
| +func TestBucketReadsOnly(t *testing.T) { |
| + t.Setenv("CARLOS_S3_ENDPOINT", "http://127.0.0.1:9") |
| + t.Setenv("AWS_ENDPOINT_URL", "http://127.0.0.1:9") |
| + t.Setenv("AWS_ENDPOINT_URL_S3", "http://127.0.0.1:9") |
| + rec := &s3Recorder{status: 200, body: `{"v":1}`} |
| + store := testAdapterWith(t, rec).Bucket("carlos-dev-store") |
| + body, _, err := store.Get(ctx, "control/edges/g-0123.json") |
| + if err != nil || string(body) != `{"v":1}` { |
| + t.Fatalf("Get = %q, %v", body, err) |
| + } |
| + if len(rec.reqs) != 1 { |
| + t.Fatalf("requests = %d", len(rec.reqs)) |
| + } |
| + q := rec.reqs[0] |
| + if q.Method != http.MethodGet || !strings.HasPrefix(q.URL.Host, "carlos-dev-store.s3.eu-west-1.amazonaws.com") || |
| + q.URL.Path != "/control/edges/g-0123.json" { |
| + t.Fatalf("request = %s %s%s", q.Method, q.URL.Host, q.URL.Path) |
| + } |
| + for _, status := range []int{404, 500, 403} { |
| + _, _, err := testAdapterWith(t, &s3Recorder{status: status}).Bucket("b").Get(ctx, "k") |
| + if u := uncertainKey(t, err); u.Key != "api" { |
| + t.Fatalf("status %d: %v", status, err) |
| + } |
| + } |
| + // Over 4 MiB is the script's output cap. |
| + big := &s3Recorder{status: 200, body: strings.Repeat("x", outputCap+1)} |
| + if _, _, err := testAdapterWith(t, big).Bucket("b").Get(ctx, "k"); !uncertainKey(t, err).OutputTooLarge { |
| + t.Fatalf("over the cap: %v", err) |
| + } |
| + rec = &s3Recorder{status: 200} |
| + store = testAdapterWith(t, rec).Bucket("b") |
| + if _, err := store.Put(ctx, "k", []byte("x"), ""); refusalKey(t, err) != "unsupported" { |
| + t.Fatalf("Put = %v", err) |
| + } |
| + if err := store.Delete(ctx, "k"); refusalKey(t, err) != "unsupported" { |
| + t.Fatalf("Delete = %v", err) |
| + } |
| + if len(rec.reqs) != 0 { |
| + t.Fatalf("a write was sent: %d requests", len(rec.reqs)) |
| + } |
| + var _ grouproll.Objects = testAdapterWith(t, rec) |
| +} |
diff --git a/internal/provision/group_roll_verb_census_test.go b/internal/provision/group_roll_verb_census_test.go| new file mode 100644 |
| index 000000000..ab7117e7f |
| --- /dev/null |
| +++ b/internal/provision/group_roll_verb_census_test.go |
| @@ -0,0 +1,11 @@ |
| +package provision |
| + |
| +// groupRollVerbWriteCensusInventory is the group roll verb's review of the |
| +// record-write census: the AWS adapter's object store for carlos system |
| +// group (internal/grouprollaws/objects.go) is read-only. Its Put defines |
| +// the release.Store method only to refuse it, sends nothing and writes no |
| +// record. |
| +func groupRollVerbWriteCensusInventory() []censusEntry { |
| + return append(append([]censusEntry(nil), billingDashboard1WriteCensusInventory()...), |
| + censusEntry{"internal/grouprollaws/objects.go", "readStore.Put", "nonrecord", "def:Put", "eca4ac5bfc69da9215d6274d226b615fa0757ce051783db6694e6b1c0f4be47b"}) |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index c939a79db..9965b5636 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := billingDashboard1WriteCensusInventory() |
| + inventory := groupRollVerbWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 329163528..c581d9e62 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -146,3 +146,4 @@ plan14-root-reads-security-review-mitigations.tsv a6f3f9eec4aac5ea88f20d0e52eaa0 |
| plan14-root-reads-cli-registry-words.tsv 8924fafc5b6083858a72f45c764081abe3bcad6a6de71901470586c076c64bb6 |
| plan14-root-reads-billing-dashboard-1.tsv 8924fafc5b6083858a72f45c764081abe3bcad6a6de71901470586c076c64bb6 |
| plan14-root-reads-billing-dash-3-cost.tsv 8924fafc5b6083858a72f45c764081abe3bcad6a6de71901470586c076c64bb6 |
| +plan14-root-reads-group-roll-verb.tsv 69a7af2adbf2566a2b321f66c67dd64802995f4c66f99291a2781deb2f8adfb1 |
diff --git a/internal/provision/testdata/plan14-root-reads-group-roll-verb.tsv b/internal/provision/testdata/plan14-root-reads-group-roll-verb.tsv| new file mode 100644 |
| index 000000000..cb365404a |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-group-roll-verb.tsv |
| @@ -0,0 +1,46 @@ |
| +# Census overlay group-roll-verb, written by census-propose (#369). census-ruling-group-roll-verb, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-group-roll-verb.md. |
| +# 0 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 20 new dispositions: 0 reads re-frozen at their disposition with the claim, 20 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 5301fc4779fe18ebdb3ab3f939536655fff2f0f69b77cb4da8232f2d0bf57e60 internal/grouproll/config.go LoadConfig legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads the operator's group config file named by --config (operator CLI only; refuses root) file:ReadFile@60 104fe171b8ce675aec5b764f43b1151bc9e9fba27d47c11b51b0bc7ea4065661 |
| +@legacy 98a907bed6b04f1ae2fd12df2a2ffca97fd6cd27e8bd3613156ce1caf2ca69e5 internal/grouproll/engine.go Engine.blocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: stats provider-divergence.json in the operator's own 0700 state directory file:Stat@45 5a1271bdebf2ddfe30d53ffa5bb74d5418e7163f860333a4e28e0f8a93be281d |
| +@legacy f054d418b4bc79970f300d5d84cb8aba6f19a17115d57633a99b2b1cba62df5b internal/grouproll/engine.go Engine.preflight legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads provider-observation.json from the operator's own 0700 state directory file:Read@630 7fc8c49acade80e8c7e3b3a1c72d46343c0e9f66c03a48ee684c49f5b20a0ece |
| +@legacy 1a7211d1fd02a49878e27ee824566d33b0c34bc6b4aa89e9d9158224f447a041 internal/grouproll/journal.go Journal.read legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads a format 2 journal from the operator's own 0700 state directory, capped at 64 MiB file:ReadAll@57 70ca67ebedcdf02e651ae0b6e016f578bb415438466bb78e247e649bde17c94b |
| +@legacy 7bc64898fa2bcff55a3152e358c0ae25cb087e82709b23cdae687c4f4b82ee91 internal/grouproll/plan.go Engine.Plan legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads provider-observation.json from the operator's own 0700 state directory file:Read@2082 4d5228ed17c41e0ccda1517f5715a16e1c52cf6c24873bfd3ebbb20dbeb11903 |
| +@legacy 0d8c73d4843fceb26628539fd6a99d63633b0299b25da660b92a7c4ef986142a internal/grouproll/state.go State.ActiveID legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: lists and reads active-v2.json and journals in the operator's own state directory file:Lstat@1138,file:Lstat@74,file:Read@125,file:ReadDir@434 9d44b2accce767cd6b36f813e2b429f36b0a54201603bb9c23d62ae557af1784 |
| +@legacy 13880520ddcf8c9e525f37c334169bf13b214aa2edba733dee404620cf57f7ef internal/grouproll/state.go State.Create legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: creates a journal in the operator's own state directory (O_NOFOLLOW, 0600) file:Create@16 b9aea0e0651c69cba91721bfd788318c274685a684c65da69d51d8953775cf14 |
| +@legacy fdffaf14ef0de828e31a2b336d25378097c0de862bcdfba155fec9b231f0d276 internal/grouproll/state.go State.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads a small state file (65,536-byte cap) from the operator's own state directory file:Read@16,file:ReadAll@168 591dafeefdcdb3bf61135d1245169a1c5be53464809c623baf956775fec37516 |
| +@legacy 625b07f777959fa0bb7ddc978335061be47a0854d9ef6067820dca0595af45a7 internal/grouproll/state.go randomHex legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads crypto/rand for plan log and transaction names file:Read@56 354b626f961cb7bf467fda630527c1ffc8d16f927b6d14eace7054630ac61ae3 |
| +@legacy 796d6894510486cf11a362d939709d456884c668c0023107b94703929bd1e803 internal/grouproll/state_unix.go lstatOwner legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: lstats the state directory and its ancestors to refuse symlinks and unsafe owners file:Lstat@83 98b0d85298b28884cc5a24ae07edec72762db01a5dd0e70dc9a6cf4b45a3589b |
| +@legacy cb6b283cbaab2453d18a92e6ea619e490da6c7e251e7d5548e032ff0888319be internal/grouproll/state_unix.go privateFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: opens a state file O_NOFOLLOW and checks it is a private regular file owned by the caller file:Fstat@318,file:Open@84 2b689035c80437e3f3a8c99ef9e1e1970ee7d8087bcdca0bb276eab3b3d6ebef |
| +@legacy 7c427a62f1a4a5411fad89025592b3b9c6888acaf22ec377aeebe6d6e0ccd392 internal/grouproll/state_unix.go syncDirectory legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: opens the state directory to fsync it file:Open@52 5e53836f352bbeb3bc0518407e4db67d407331bcea784191693e94339a6c1520 |
| +@legacy 0137f4465f132b206858e823cf74da3748be0887eebde8400dd1678c99bba80d internal/grouprollaws/group.go Adapter.TemplateRelease legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads the launch template's user data from the EC2 answer (in memory, 4 MiB cap) file:ReadAll@1474 1fca0c893f4983a2a5e4d109e9c79eeaccb560255e9e0126a1db80103c36ff96 |
| +@legacy 0039188458a3b700ccf22d9e3c5f703950de7ec49466e0ad87769602bb9b86c3 internal/grouprollaws/pty_linux.go openPTY legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: opens /dev/ptmx and the pts slave for the Session Manager plugin file:Open@421,file:Open@47 12f5a07caf7bb27f2cc8b0b2ac5da4074c1c073fa6f73da9816b5473115fd988 |
| +@legacy 9d0e8abe70411923bc3af2d9f20bdae1c722764633e1a20f1024398c256526e0 internal/grouprollaws/pty_unix.go pty.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads the plugin's pty output, capped at 4 MiB file:Read@996 2d6798bc9760f315d67cd93a75d3b746fbe538881f0d50d3acd2070f3e91379f |
| +@legacy c53f0f8796ede4f379e30e9b9c6e3835bebcca55d182b4558f59fa41089e15e6 internal/grouprollaws/pty_unix.go runVersion legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads session-manager-plugin --version output, capped at 4 KiB file:Read@789 996b5cb79b292f5de0fcb42c5987eaf739ec27869e1744380e0d6f65deb639fd |
| +@legacy fcf9bf3f19da2f83fb1514585abd83c6bddeef983c47957a8c84c4689797fbca internal/grouprollaws/session.go newNonce legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads crypto/rand for the frame nonce file:Read@49 7bba200ea8c254001d09c73841b2b454d95ea5015fb75840187c4612f28edb6e |
| +@legacy fc7f077ae17a4c567792904f6a9f0bd229423365a9884a7035fc0273ed4607ae internal/grouprollaws/transport.go boundBody.HandleDeserialize legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads an AWS API answer body under the 4 MiB cap file:ReadAll@436 020d98263efa2c56f212b20f4d3e3d9497ebc1a86d737c0ffc481cb1c48d38e8 |
| +@legacy 5f2211a1c118d3be97d2abdfd57e5fe5a42a2d65d364a2d1d01b8cc31ad359f6 internal/grouprollaws/transport.go boundedBody.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads an AWS API answer body under the 4 MiB cap and the read timeout file:Read@22,file:Read@448 7ff90cef635efcf75d046d9113cb6a0dcddd8dfb3570c73984bc5565b637e872 |
| +@legacy e76de0f49c6b8cbd42aa4d1eab1dc48477d629258b58e477a6948649fc59aab4 system_group.go runSystemGroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: lstats /etc/carlos/host.env to refuse running on a carlos box (euid 0 is refused first) file:Lstat@245 08579781ed6b6c32c375fc18155a6dd5e7e5035e3eb011beb51d6c87d24f178c |
| +internal/grouproll/config.go LoadConfig legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads the operator's group config file named by --config (operator CLI only; refuses root) file:ReadFile@60 104fe171b8ce675aec5b764f43b1151bc9e9fba27d47c11b51b0bc7ea4065661 |
| +internal/grouproll/engine.go Engine.blocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: stats provider-divergence.json in the operator's own 0700 state directory file:Stat@45 5a1271bdebf2ddfe30d53ffa5bb74d5418e7163f860333a4e28e0f8a93be281d |
| +internal/grouproll/engine.go Engine.preflight legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads provider-observation.json from the operator's own 0700 state directory file:Read@630 7fc8c49acade80e8c7e3b3a1c72d46343c0e9f66c03a48ee684c49f5b20a0ece |
| +internal/grouproll/journal.go Journal.read legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads a format 2 journal from the operator's own 0700 state directory, capped at 64 MiB file:ReadAll@57 70ca67ebedcdf02e651ae0b6e016f578bb415438466bb78e247e649bde17c94b |
| +internal/grouproll/plan.go Engine.Plan legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads provider-observation.json from the operator's own 0700 state directory file:Read@2082 4d5228ed17c41e0ccda1517f5715a16e1c52cf6c24873bfd3ebbb20dbeb11903 |
| +internal/grouproll/state.go State.ActiveID legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: lists and reads active-v2.json and journals in the operator's own state directory file:Lstat@1138,file:Lstat@74,file:Read@125,file:ReadDir@434 9d44b2accce767cd6b36f813e2b429f36b0a54201603bb9c23d62ae557af1784 |
| +internal/grouproll/state.go State.Create legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: creates a journal in the operator's own state directory (O_NOFOLLOW, 0600) file:Create@16 b9aea0e0651c69cba91721bfd788318c274685a684c65da69d51d8953775cf14 |
| +internal/grouproll/state.go State.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads a small state file (65,536-byte cap) from the operator's own state directory file:Read@16,file:ReadAll@168 591dafeefdcdb3bf61135d1245169a1c5be53464809c623baf956775fec37516 |
| +internal/grouproll/state.go randomHex legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads crypto/rand for plan log and transaction names file:Read@56 354b626f961cb7bf467fda630527c1ffc8d16f927b6d14eace7054630ac61ae3 |
| +internal/grouproll/state_unix.go lstatOwner legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: lstats the state directory and its ancestors to refuse symlinks and unsafe owners file:Lstat@83 98b0d85298b28884cc5a24ae07edec72762db01a5dd0e70dc9a6cf4b45a3589b |
| +internal/grouproll/state_unix.go privateFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: opens a state file O_NOFOLLOW and checks it is a private regular file owned by the caller file:Fstat@318,file:Open@84 2b689035c80437e3f3a8c99ef9e1e1970ee7d8087bcdca0bb276eab3b3d6ebef |
| +internal/grouproll/state_unix.go syncDirectory legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: opens the state directory to fsync it file:Open@52 5e53836f352bbeb3bc0518407e4db67d407331bcea784191693e94339a6c1520 |
| +internal/grouprollaws/group.go Adapter.TemplateRelease legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads the launch template's user data from the EC2 answer (in memory, 4 MiB cap) file:ReadAll@1474 1fca0c893f4983a2a5e4d109e9c79eeaccb560255e9e0126a1db80103c36ff96 |
| +internal/grouprollaws/pty_linux.go openPTY legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: opens /dev/ptmx and the pts slave for the Session Manager plugin file:Open@421,file:Open@47 12f5a07caf7bb27f2cc8b0b2ac5da4074c1c073fa6f73da9816b5473115fd988 |
| +internal/grouprollaws/pty_unix.go pty.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads the plugin's pty output, capped at 4 MiB file:Read@996 2d6798bc9760f315d67cd93a75d3b746fbe538881f0d50d3acd2070f3e91379f |
| +internal/grouprollaws/pty_unix.go runVersion legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads session-manager-plugin --version output, capped at 4 KiB file:Read@789 996b5cb79b292f5de0fcb42c5987eaf739ec27869e1744380e0d6f65deb639fd |
| +internal/grouprollaws/session.go newNonce legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads crypto/rand for the frame nonce file:Read@49 7bba200ea8c254001d09c73841b2b454d95ea5015fb75840187c4612f28edb6e |
| +internal/grouprollaws/transport.go boundBody.HandleDeserialize legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads an AWS API answer body under the 4 MiB cap file:ReadAll@436 020d98263efa2c56f212b20f4d3e3d9497ebc1a86d737c0ffc481cb1c48d38e8 |
| +internal/grouprollaws/transport.go boundedBody.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: reads an AWS API answer body under the 4 MiB cap and the read timeout file:Read@22,file:Read@448 7ff90cef635efcf75d046d9113cb6a0dcddd8dfb3570c73984bc5565b637e872 |
| +system_group.go runSystemGroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-group-roll-verb;basis=new: lstats /etc/carlos/host.env to refuse running on a carlos box (euid 0 is refused first) file:Lstat@245 08579781ed6b6c32c375fc18155a6dd5e7e5035e3eb011beb51d6c87d24f178c |
| +@coverage . e4510f22fe12a9dd4aad38272b0aeeea526302bd53dfba6e8490174b7f05f006 |
| +@coverage internal/grouproll 0c7b9674daf52548372c45066936519869c10c11dc121c4ffbf059c92dfe9170 |
| +@coverage internal/grouprollaws 42606b41b520f77c7c0d5b971e57be7766cafbe8cc67214e38468a0b97e47184 |
diff --git a/parity/cli.tsv b/parity/cli.tsv| index aabbc202a..69d7236b8 100644 |
| --- a/parity/cli.tsv |
| +++ b/parity/cli.tsv |
| @@ -249,7 +249,9 @@ system floor-allows-prev box-local - - - - - |
| system geoip off operator - - - - - |
| system geoip publish operator - - - - - |
| system geoip status operator - - - - - |
| +system group plan operator - - - - - |
| system group role operator - - - - - |
| +system group status operator - - - - - |
| system group-maintenance box-local - - - - - |
| system guard-arm box-local - - - - - |
| system guard-exec box-local - - - - - |
diff --git a/parity/parity.tsv b/parity/parity.tsv| index 5354217d6..819b8695d 100644 |
| --- a/parity/parity.tsv |
| +++ b/parity/parity.tsv |
| @@ -210,6 +210,7 @@ op-system-layout operator operator system layout status ; system layout migrate |
| op-system-geoip operator operator system geoip publish ; system geoip status ; system geoip off The platform GeoIP database. |
| op-system-cutovers operator operator system seeds-floor publish ; system legacy-routes assign ; system lifetimes cutover ; system hosts-used status One-off cutovers and floors. |
| op-system-roles operator operator system box role ; system group role Box and group roles. |
| +op-system-group-roll operator operator system group plan ; system group status Group maintenance from an operator machine. |
| op-system-demos operator operator system demos status ; system demos serving ; system demos takedown ; system demos takedown-status ; system demos reports ; system demos reports resolve Demo serving, takedowns and reports. |
| op-system-managed-fleets operator operator system managed-fleets show ; system managed-fleets set The managed-fleet catalog. |
diff --git a/region_ha_boundary_test.go b/region_ha_boundary_test.go| index 2eadff9a2..fd0a62d5c 100644 |
| --- a/region_ha_boundary_test.go |
| +++ b/region_ha_boundary_test.go |
| @@ -49,6 +49,9 @@ var regionHACoreFiles = []string{ |
| "internal/grouproll/text.go", |
| "internal/grouproll/box.go", |
| "internal/grouproll/provider.go", |
| + "internal/grouproll/engine.go", |
| + "internal/grouproll/plan.go", |
| + "internal/grouproll/status.go", |
| } |
| // regionHAAdapterFiles are spec 2's AWS adapters. Each is named for AWS so |
| @@ -66,6 +69,7 @@ var regionHAAdapterFiles = []string{ |
| "internal/grouprollaws/pty_linux.go", |
| "internal/grouprollaws/pty_darwin.go", |
| "internal/grouprollaws/pty_other.go", |
| + "internal/grouprollaws/objects.go", |
| } |
| // regionHAPackages are the packages spec 2 touches. Every S3 client built |
diff --git a/system_group.go b/system_group.go| new file mode 100644 |
| index 000000000..802e71fd4 |
| --- /dev/null |
| +++ b/system_group.go |
| @@ -0,0 +1,223 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "os" |
| + "os/signal" |
| + "os/user" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| + "github.com/carlosframework/platform/internal/grouprollaws" |
| +) |
| + |
| +// carlos system group plan|status (group roll verb spec §3-§4): the |
| +// script scripts/region-group-roll.py's main, ported. It runs on an |
| +// operator machine as the deployment's operator account, takes flags only, |
| +// and works from the group config file alone: it never opens a console |
| +// session, reads the CLI's saved login or falls back to a default |
| +// deployment. |
| + |
| +// groupProvider is what a writing or reading verb drives: the group's |
| +// provider calls and its members' boxes. The AWS adapter is both. |
| +type groupProvider interface { |
| + grouproll.Group |
| + grouproll.Box |
| +} |
| + |
| +// groupEnvironment is everything runSystemGroup touches outside itself, |
| +// so tests can replace it. |
| +type groupEnvironment struct { |
| + stdout, stderr io.Writer |
| + geteuid func() int |
| + hostEnv string // a carlos box's /etc/carlos/host.env |
| + username func() string |
| + terminal func() bool // stdin is a terminal |
| + getenv func(string) string |
| + sharedFiles func() grouprollaws.SharedFiles |
| + isolate func(profile string) error |
| + provider func(ctx context.Context, c grouproll.Config, files grouprollaws.SharedFiles) (groupProvider, error) |
| +} |
| + |
| +var groupEnv = groupEnvironment{ |
| + stdout: os.Stdout, stderr: os.Stderr, |
| + geteuid: os.Geteuid, hostEnv: "/etc/carlos/host.env", |
| + username: processUser, terminal: groupStdinIsTerminal, getenv: os.Getenv, |
| + sharedFiles: grouprollaws.ResolveSharedFiles, |
| + isolate: grouprollaws.IsolateEnvironment, |
| + provider: func(ctx context.Context, c grouproll.Config, files grouprollaws.SharedFiles) (groupProvider, error) { |
| + return grouprollaws.New(ctx, c, grouprollaws.WithSharedFiles(files)) |
| + }, |
| +} |
| + |
| +// processUser is the effective user's login name, "" when unknown. |
| +func processUser() string { |
| + u, err := user.LookupId(strconv.Itoa(os.Geteuid())) |
| + if err != nil { |
| + return "" |
| + } |
| + return u.Username |
| +} |
| + |
| +// runSystemGroupPlan and runSystemGroupStatus are the registry's leaves. |
| +func runSystemGroupPlan(args []string) { os.Exit(runSystemGroup("plan", args)) } |
| +func runSystemGroupStatus(args []string) { os.Exit(runSystemGroup("status", args)) } |
| + |
| +// groupFlags are one verb's flags, as the script's argparse declares them. |
| +type groupFlags struct { |
| + config, attendedBy, member, sha, transaction string |
| +} |
| + |
| +// groupRefused prints the script main's refusal line and returns its exit |
| +// status. |
| +func groupRefused(err error) int { |
| + reason := grouproll.Text("record") |
| + var r grouproll.Refusal |
| + var u grouproll.Uncertain |
| + switch { |
| + case errors.As(err, &r): |
| + reason = r.Error() |
| + case errors.As(err, &u): |
| + reason = u.Error() |
| + } |
| + fmt.Fprint(groupEnv.stderr, grouproll.Text("refused", "reason", reason)+"\n") |
| + return 1 |
| +} |
| + |
| +// groupExitCode is the status for a verb's error: Ctrl-C ends it as the |
| +// shell's interrupt does, with no text; anything else is a refusal. |
| +func groupExitCode(err error) int { |
| + if errors.Is(err, context.Canceled) { |
| + return 130 |
| + } |
| + return 1 |
| +} |
| + |
| +// parseGroupFlags reads verb's flags. ok is false when the verb has |
| +// already ended with status rc (help, a flag error or a refusal). |
| +func parseGroupFlags(verb string, args []string) (f groupFlags, rc int, ok bool) { |
| + fs := flag.NewFlagSet("carlos system group "+verb, flag.ContinueOnError) |
| + var out bytes.Buffer |
| + fs.SetOutput(&out) |
| + fs.Usage = func() { |
| + fmt.Fprintln(&out, grouproll.Text(verb)) |
| + fs.PrintDefaults() |
| + } |
| + fs.StringVar(&f.config, "config", "", grouproll.Text("config")) |
| + fs.StringVar(&f.attendedBy, "attended-by", "", grouproll.Text("attended")) |
| + switch verb { |
| + case "plan": |
| + fs.StringVar(&f.member, "member", "", grouproll.Text("member")) |
| + fs.StringVar(&f.sha, "to-sha256", "", grouproll.Text("sha")) |
| + case "status": |
| + fs.StringVar(&f.transaction, "transaction", "", grouproll.Text("transaction")) |
| + } |
| + if err := fs.Parse(args); err != nil { |
| + if errors.Is(err, flag.ErrHelp) { |
| + groupEnv.stdout.Write(out.Bytes()) |
| + return f, 0, false |
| + } |
| + groupEnv.stderr.Write(out.Bytes()) |
| + return f, 2, false |
| + } |
| + if fs.NArg() > 0 { |
| + return f, groupRefused(grouproll.Refusal{Key: "usage_positional", Args: map[string]string{"arg": fs.Arg(0)}}), false |
| + } |
| + if f.config == "" { |
| + return f, groupRefused(grouproll.Refusal{Key: "config_required"}), false |
| + } |
| + return f, 0, true |
| +} |
| + |
| +// attendedBy is the script's attended_by or SUDO_USER or getpass.getuser(). |
| +func attendedBy(flagValue string) string { |
| + if flagValue != "" { |
| + return flagValue |
| + } |
| + for _, k := range []string{"SUDO_USER", "LOGNAME", "USER", "LNAME", "USERNAME"} { |
| + if v := groupEnv.getenv(k); v != "" { |
| + return v |
| + } |
| + } |
| + return groupEnv.username() |
| +} |
| + |
| +// runSystemGroup runs one carlos system group verb and returns its exit |
| +// status. The order of work is fixed: refuse Windows, root and a carlos |
| +// box; read the flags; resolve the state directory and the shared AWS |
| +// files from the environment; load the config; isolate the environment |
| +// for its profile (before any goroutine starts); then the verb. |
| +func runSystemGroup(verb string, args []string) int { |
| + if !groupSupported { |
| + return groupRefused(grouproll.Refusal{Key: "windows"}) |
| + } |
| + if groupEnv.geteuid() == 0 { |
| + return groupRefused(grouproll.Refusal{Key: "root_refused"}) |
| + } |
| + if _, err := os.Lstat(groupEnv.hostEnv); err == nil || groupEnv.username() == "carlos" { |
| + return groupRefused(grouproll.Refusal{Key: "on_box"}) |
| + } |
| + f, rc, ok := parseGroupFlags(verb, args) |
| + if !ok { |
| + return rc |
| + } |
| + if !groupEnv.terminal() && strings.TrimSpace(f.attendedBy) == "" { |
| + return groupRefused(grouproll.Refusal{Key: "attended_required"}) |
| + } |
| + attended := attendedBy(f.attendedBy) |
| + dir, err := grouproll.ResolveStateDir(groupEnv.getenv) |
| + if err != nil { |
| + return groupRefused(err) |
| + } |
| + files := groupEnv.sharedFiles() |
| + c, err := grouproll.LoadConfig(f.config) |
| + if err != nil { |
| + return groupRefused(err) |
| + } |
| + if err := groupEnv.isolate(c.Profile); err != nil { |
| + return groupRefused(err) |
| + } |
| + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| + defer stop() |
| + |
| + if verb == "status" { |
| + if err := grouproll.Status(dir, c, f.transaction, groupEnv.stdout); err != nil { |
| + return groupRefused(err) |
| + } |
| + return 0 |
| + } |
| + |
| + state, err := grouproll.OpenState(dir, c, false) |
| + if err != nil { |
| + return groupRefused(err) |
| + } |
| + unlock, err := state.Lock() |
| + if err != nil { |
| + return groupRefused(err) |
| + } |
| + defer unlock() |
| + p, err := groupEnv.provider(ctx, c, files) |
| + if err != nil { |
| + return groupRefused(err) |
| + } |
| + e := grouproll.NewEngine(c, p, p, state, time.Now, time.Sleep, groupEnv.stdout, attended) |
| + ok, err = e.Plan(ctx, f.member, f.sha) |
| + if err != nil { |
| + if groupExitCode(err) == 130 { |
| + return 130 |
| + } |
| + return groupRefused(err) |
| + } |
| + if !ok { |
| + return 1 |
| + } |
| + return 0 |
| +} |
diff --git a/system_group_other.go b/system_group_other.go| new file mode 100644 |
| index 000000000..a9f0bedb1 |
| --- /dev/null |
| +++ b/system_group_other.go |
| @@ -0,0 +1,8 @@ |
| +//go:build !(linux || darwin) |
| + |
| +package main |
| + |
| +// groupSupported: carlos system group refuses every verb here (spec §4). |
| +const groupSupported = false |
| + |
| +func groupStdinIsTerminal() bool { return false } |
diff --git a/system_group_test.go b/system_group_test.go| new file mode 100644 |
| index 000000000..546e278bf |
| --- /dev/null |
| +++ b/system_group_test.go |
| @@ -0,0 +1,284 @@ |
| +//go:build linux || darwin |
| + |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| + "github.com/carlosframework/platform/internal/grouprollaws" |
| +) |
| + |
| +// groupHarness replaces every outside effect of runSystemGroup: identity, |
| +// the box marker, the terminal, isolation and the provider constructor, |
| +// and records the order the steps ran in. |
| +type groupHarness struct { |
| + t *testing.T |
| + stdout, stderr bytes.Buffer |
| + steps []string |
| + config string |
| +} |
| + |
| +func newGroupHarness(t *testing.T) *groupHarness { |
| + h := &groupHarness{t: t} |
| + dir := t.TempDir() |
| + h.config = filepath.Join(dir, "group.json") |
| + cfg := `{"deployment":"example","account":"000000000000","region":"eu-west-1","group":"example-group",` + |
| + `"hook":"example-launch","group_arn":"arn:aws:autoscaling:eu-west-1:000000000000:autoScalingGroup:example:autoScalingGroupName/example-group",` + |
| + `"target_groups":["arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-8/8888888888888888",` + |
| + `"arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-4/4444444444444444"],` + |
| + `"bucket":"example-deployment","document":"AWS-StartNonInteractiveCommand","state_dir":"/state",` + |
| + `"profile":"example","min_release":"v0.34.0"}` |
| + if err := os.WriteFile(h.config, []byte(cfg), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + old := groupEnv |
| + t.Cleanup(func() { groupEnv = old }) |
| + groupEnv = groupEnvironment{ |
| + stdout: &h.stdout, stderr: &h.stderr, |
| + geteuid: func() int { return 1000 }, |
| + hostEnv: filepath.Join(dir, "absent-host.env"), |
| + username: func() string { return "operator" }, |
| + terminal: func() bool { return false }, |
| + getenv: func(k string) string { |
| + if k == "HOME" { |
| + return filepath.Join(dir, "home") |
| + } |
| + return "" |
| + }, |
| + sharedFiles: func() grouprollaws.SharedFiles { |
| + h.steps = append(h.steps, "shared-files") |
| + return grouprollaws.SharedFiles{Config: []string{"/c"}, Credentials: []string{"/k"}} |
| + }, |
| + isolate: func(profile string) error { |
| + h.steps = append(h.steps, "isolate "+profile) |
| + return nil |
| + }, |
| + provider: func(ctx context.Context, c grouproll.Config, f grouprollaws.SharedFiles) (groupProvider, error) { |
| + h.steps = append(h.steps, "provider") |
| + return nil, grouproll.Refusal{Key: "api"} |
| + }, |
| + } |
| + return h |
| +} |
| + |
| +func (h *groupHarness) run(verb string, args ...string) int { |
| + return runSystemGroup(verb, args) |
| +} |
| + |
| +func (h *groupHarness) refused(key string, args ...string) string { |
| + return grouproll.Text("refused", "reason", grouproll.Text(key, args...)) + "\n" |
| +} |
| + |
| +// TestCLIRefusesRootBoxWindows: root, a carlos box, positional arguments |
| +// and a missing --config are refused before anything else runs, each |
| +// with its text on stderr and exit 1. |
| +func TestCLIRefusesRootBoxWindows(t *testing.T) { |
| + plan := []string{"--config", "", "--member", "i-0123456789abcdef0", "--to-sha256", strings.Repeat("b", 64)} |
| + t.Run("root", func(t *testing.T) { |
| + h := newGroupHarness(t) |
| + groupEnv.geteuid = func() int { return 0 } |
| + if rc := h.run("plan"); rc != 1 || h.stderr.String() != h.refused("root_refused") || len(h.steps) != 0 { |
| + t.Fatalf("rc %d stderr %q steps %v", rc, h.stderr.String(), h.steps) |
| + } |
| + }) |
| + t.Run("host.env", func(t *testing.T) { |
| + h := newGroupHarness(t) |
| + if err := os.WriteFile(groupEnv.hostEnv, nil, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rc := h.run("status", "--config", h.config, "--transaction", "t"); rc != 1 || |
| + h.stderr.String() != h.refused("on_box") || len(h.steps) != 0 { |
| + t.Fatalf("rc %d stderr %q steps %v", rc, h.stderr.String(), h.steps) |
| + } |
| + }) |
| + t.Run("carlos user", func(t *testing.T) { |
| + h := newGroupHarness(t) |
| + groupEnv.username = func() string { return "carlos" } |
| + if rc := h.run("plan"); rc != 1 || h.stderr.String() != h.refused("on_box") { |
| + t.Fatalf("rc %d stderr %q", rc, h.stderr.String()) |
| + } |
| + }) |
| + t.Run("positional", func(t *testing.T) { |
| + h := newGroupHarness(t) |
| + if rc := h.run("plan", "--config", h.config, "i-0123456789abcdef0"); rc != 1 || |
| + h.stderr.String() != h.refused("usage_positional", "arg", "i-0123456789abcdef0") || len(h.steps) != 0 { |
| + t.Fatalf("rc %d stderr %q", rc, h.stderr.String()) |
| + } |
| + }) |
| + t.Run("no config", func(t *testing.T) { |
| + h := newGroupHarness(t) |
| + if rc := h.run("plan", plan[2:]...); rc != 1 || h.stderr.String() != h.refused("config_required") || len(h.steps) != 0 { |
| + t.Fatalf("rc %d stderr %q", rc, h.stderr.String()) |
| + } |
| + }) |
| + t.Run("attended", func(t *testing.T) { |
| + h := newGroupHarness(t) |
| + args := append([]string{}, plan...) |
| + args[1] = h.config |
| + if rc := h.run("plan", args...); rc != 1 || h.stderr.String() != h.refused("attended_required") || len(h.steps) != 0 { |
| + t.Fatalf("rc %d stderr %q", rc, h.stderr.String()) |
| + } |
| + h = newGroupHarness(t) |
| + if rc := h.run("plan", append(args, "--attended-by", " ")...); rc != 1 || h.stderr.String() != h.refused("attended_required") { |
| + t.Fatalf("blank: rc %d stderr %q", rc, h.stderr.String()) |
| + } |
| + }) |
| + t.Run("unknown flag", func(t *testing.T) { |
| + h := newGroupHarness(t) |
| + if rc := h.run("plan", "--zz"); rc != 2 || h.stdout.Len() != 0 || len(h.steps) != 0 { |
| + t.Fatalf("rc %d stderr %q", rc, h.stderr.String()) |
| + } |
| + }) |
| + t.Run("help", func(t *testing.T) { |
| + h := newGroupHarness(t) |
| + if rc := h.run("plan", "-h"); rc != 0 || !strings.HasPrefix(h.stdout.String(), grouproll.Text("plan")+"\n") || |
| + !strings.Contains(h.stdout.String(), grouproll.Text("sha")) || len(h.steps) != 0 { |
| + t.Fatalf("rc %d stdout %q", rc, h.stdout.String()) |
| + } |
| + }) |
| +} |
| + |
| +// The order of work: refusals, flags, the state directory and shared |
| +// files, isolation with the config's profile, then the provider. The |
| +// provider's refusal reaches stderr as the script's main printed it. |
| +func TestCLIPlanOrder(t *testing.T) { |
| + h := newGroupHarness(t) |
| + state := filepath.Join(groupEnv.getenv("HOME"), ".local", "state", "carlos", "group") |
| + if err := os.MkdirAll(state, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + rc := h.run("plan", "--config", h.config, "--attended-by", "op", "--member", "i-0123456789abcdef0", |
| + "--to-sha256", strings.Repeat("b", 64)) |
| + // The state directory's ancestors on a test machine may be group |
| + // writable; either refusal comes after the shared files and isolation. |
| + want := []string{"shared-files", "isolate example"} |
| + if rc != 1 || len(h.steps) < 2 || !reflect.DeepEqual(h.steps[:2], want) { |
| + t.Fatalf("rc %d steps %v stderr %q", rc, h.steps, h.stderr.String()) |
| + } |
| + if len(h.steps) == 3 && h.steps[2] == "provider" { |
| + if h.stderr.String() != h.refused("api") { |
| + t.Fatalf("stderr %q", h.stderr.String()) |
| + } |
| + } else if !strings.HasPrefix(h.stderr.String(), grouproll.Text("refused", "reason", "")) { |
| + t.Fatalf("stderr %q", h.stderr.String()) |
| + } |
| + // A config that does not validate is refused before isolation. |
| + h = newGroupHarness(t) |
| + if err := os.WriteFile(h.config, []byte(`{}`), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rc := h.run("status", "--config", h.config, "--attended-by", "op", "--transaction", "t"); rc != 1 || |
| + h.stderr.String() != h.refused("config_invalid") || !reflect.DeepEqual(h.steps, []string{"shared-files"}) { |
| + t.Fatalf("rc %d stderr %q steps %v", rc, h.stderr.String(), h.steps) |
| + } |
| +} |
| + |
| +// Status never builds a provider and never isolates into one: it reads |
| +// the journal alone. |
| +func TestCLIStatusBuildsNoProvider(t *testing.T) { |
| + h := newGroupHarness(t) |
| + rc := h.run("status", "--config", h.config, "--attended-by", "op", "--transaction", "absent") |
| + if rc != 1 || !strings.HasPrefix(h.stderr.String(), grouproll.Text("refused", "reason", "")) { |
| + t.Fatalf("rc %d stderr %q", rc, h.stderr.String()) |
| + } |
| + for _, s := range h.steps { |
| + if s == "provider" { |
| + t.Fatalf("status built a provider: %v", h.steps) |
| + } |
| + } |
| +} |
| + |
| +// No console session is ever opened: nothing reachable from |
| +// runSystemGroup in package main reaches the console session or client |
| +// constructors, and the engine packages import no console code. |
| +func TestCLIGroupNeverOpensAConsole(t *testing.T) { |
| + fset := token.NewFileSet() |
| + files, err := filepath.Glob("*.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + funcs := map[string][]*ast.FuncDecl{} |
| + for _, name := range files { |
| + if strings.HasSuffix(name, "_test.go") { |
| + continue |
| + } |
| + f, err := parser.ParseFile(fset, name, nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, d := range f.Decls { |
| + if fd, ok := d.(*ast.FuncDecl); ok { |
| + funcs[fd.Name.Name] = append(funcs[fd.Name.Name], fd) |
| + } |
| + } |
| + } |
| + forbidden := map[string]bool{"resolveMode": true, "newConsoleClient": true, |
| + "requireDeployAPISession": true, "requireAPISession": true} |
| + for name := range forbidden { |
| + if len(funcs[name]) == 0 { |
| + t.Fatalf("%s is gone: update this test's list of console constructors", name) |
| + } |
| + } |
| + seen := map[string]bool{} |
| + var path []string |
| + var walk func(name string) |
| + walk = func(name string) { |
| + if seen[name] { |
| + return |
| + } |
| + seen[name] = true |
| + if forbidden[name] { |
| + t.Fatalf("runSystemGroup reaches %s: %s", name, strings.Join(append(path, name), " -> ")) |
| + } |
| + path = append(path, name) |
| + for _, fd := range funcs[name] { |
| + ast.Inspect(fd, func(n ast.Node) bool { |
| + if id, ok := n.(*ast.Ident); ok && len(funcs[id.Name]) > 0 { |
| + walk(id.Name) |
| + } |
| + return true |
| + }) |
| + } |
| + path = path[:len(path)-1] |
| + } |
| + walk("runSystemGroup") |
| + if !seen["runSystemGroup"] || len(funcs["runSystemGroup"]) == 0 { |
| + t.Fatal("runSystemGroup not found") |
| + } |
| + // The engine and adapter packages import nothing that opens a console. |
| + for _, dir := range []string{"internal/grouproll", "internal/grouprollaws"} { |
| + names, _ := filepath.Glob(filepath.Join(dir, "*.go")) |
| + for _, name := range names { |
| + if strings.HasSuffix(name, "_test.go") { |
| + continue |
| + } |
| + f, err := parser.ParseFile(fset, name, nil, parser.ImportsOnly) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, imp := range f.Imports { |
| + if p := strings.Trim(imp.Path.Value, `"`); strings.Contains(p, "/internal/console") || |
| + strings.Contains(p, "/internal/cliauth") { |
| + t.Errorf("%s imports %s", name, p) |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +// Ctrl-C ends the verb with the shell's interrupt status and no text. |
| +func TestCLIGroupInterrupted(t *testing.T) { |
| + if groupExitCode(context.Canceled) != 130 || groupExitCode(grouproll.Refusal{Key: "api"}) != 1 { |
| + t.Fatal("exit codes") |
| + } |
| +} |
diff --git a/system_group_unix.go b/system_group_unix.go| new file mode 100644 |
| index 000000000..89b872e60 |
| --- /dev/null |
| +++ b/system_group_unix.go |
| @@ -0,0 +1,10 @@ |
| +//go:build linux || darwin |
| + |
| +package main |
| + |
| +// groupSupported: the session transport needs a pseudo-terminal (spec |
| +// §4, §5.3), which these systems have. |
| +const groupSupported = true |
| + |
| +// groupStdinIsTerminal is the script's sys.stdin.isatty(). |
| +func groupStdinIsTerminal() bool { return isTTY(0) } |
diff --git a/system_roles.go b/system_roles.go| index c79ae9ae3..95b91ebe4 100644 |
| --- a/system_roles.go |
| +++ b/system_roles.go |
| @@ -119,12 +119,22 @@ func systemBoxCommand() *clireg.Node { |
| } |
| } |
| -// systemGroupCommand is `carlos system group role`. |
| +// groupVerbGolden is why the golden corpus skips the group roll verbs: |
| +// they refuse root and carlos boxes before they read their arguments. |
| +const groupVerbGolden = "refuses root and carlos boxes before it reads its arguments, -h included" |
| + |
| +// systemGroupCommand is `carlos system group role`, and the group roll |
| +// verbs (system_group.go), which run on an operator machine from the |
| +// group config alone and never through a console. |
| func systemGroupCommand() *clireg.Node { |
| return &clireg.Node{ |
| Name: "group", |
| Audience: clireg.Operator, |
| - Children: []*clireg.Node{raw("role", clireg.Operator, runSystemGroupRole)}, |
| + Children: []*clireg.Node{ |
| + raw("role", clireg.Operator, runSystemGroupRole), |
| + noHint(skipGolden(raw("plan", clireg.Operator, runSystemGroupPlan), groupVerbGolden)), |
| + noHint(skipGolden(raw("status", clireg.Operator, runSystemGroupStatus), groupVerbGolden)), |
| + }, |
| Fallback: systemRolesFallback, |
| } |
| } |
diff --git a/testdata/clireg-golden.jsonl b/testdata/clireg-golden.jsonl| index 52e9597a0..4bd622966 100644 |
| --- a/testdata/clireg-golden.jsonl |
| +++ b/testdata/clireg-golden.jsonl |
| @@ -803,9 +803,11 @@ |
| {"case":"system geoip | extra","argv":["system","geoip"],"exit":2,"stdout":"","stderr":"system geoip: no verb given\n\nusage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |
| {"case":"system geoip | help","argv":["system","geoip","help"],"exit":2,"stdout":"","stderr":"system geoip: unknown verb \"help\"\n\nusage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |
| {"case":"system geoip | zz-unknown","argv":["system","geoip","zz-unknown"],"exit":2,"stdout":"","stderr":"system geoip: unknown verb \"zz-unknown\"\n\nusage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |
| +{"case":"system group plan | skipped","skipped":"refuses root and carlos boxes before it reads its arguments, -h included"} |
| {"case":"system group role x y --zz z | extra","argv":["system","group","role","x","y","--zz","z"],"exit":2,"stdout":"","stderr":"usage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |
| {"case":"system group role | --zz-unknown-flag","argv":["system","group","role","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"usage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |
| {"case":"system group role | -h","argv":["system","group","role","-h"],"exit":2,"stdout":"","stderr":"usage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |
| +{"case":"system group status | skipped","skipped":"refuses root and carlos boxes before it reads its arguments, -h included"} |
| {"case":"system group | --help","argv":["system","group","--help"],"exit":2,"stdout":"","stderr":"usage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |
| {"case":"system group | --zz-unknown-flag","argv":["system","group","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"usage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |
| {"case":"system group | -h","argv":["system","group","-h"],"exit":2,"stdout":"","stderr":"usage: carlos system <verb> [flags]\n carlos system router <verb> [flags]\n carlos system demos <status|serving on|serving off|takedown|takedown-status>\n carlos system managed-fleets <show|set --file f.json>\n carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]\n carlos system pdf status\n carlos system geoip <publish|status|off> [flags]\n carlos system seeds-floor publish --min-release <release>\n carlos system legacy-routes assign --name <name> --to <account>/<app>\n carlos system lifetimes cutover [--no-wait]\n carlos system hosts-used status\n carlos system named-units install <file>\n carlos system box role <box> <default|legacy|platform>\n carlos system box publish-record\n carlos system group role <region> <default|legacy>\n carlos system host-env <write|seed> --deployment <name> --region <code> [flags]\n\nThe platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n update promote a platform release to a channel; every box on it rolls itself\n status every box: platform, channel, running build, channel target, last apply outcome\n rollback point a channel back at the release before this one\n cancel-activation\n release a channel's activation reservation that was never\n published, so promote and rollback work again\n apply (root oneshot behind carlos-system-update.service; not for operators)\n layout migrate|revert|status: move every instance into its own directory\n and namespace, or back; see carlos system layout help\n seeds-floor publish --min-release <release>\n the first release whose boxes can place a seed, such as v0.27.0\n legacy-routes assign --name <name> --to <account>/<app>\n say which account and app the routes an operator filed by hand belong to\n lifetimes cutover [--no-wait]\n switch a console without host claims onto instance lifetimes,\n once, after the old console has stopped. Waits until they are on\n hosts-used status\n the hostname history: its mode, how many hostnames it has\n recorded, its closed fleets and its floor\n box role <box> <default|legacy|platform>\n whether new instances may be placed on a box. A legacy or\n platform box keeps the instances it has and takes no new ones\n group role <region> <default|legacy>\n the same for every box a region's group has enrolled, and for\n every box it enrolls later\n box publish-record\n run on a box as the agent user, with systemd-run -p User=carlos:\n publish its AWS-signed identity record to the deployment\n bucket, once. It never replaces or deletes a record\n\nA box a region's group launches (region HA):\n\n host-env write build host.env from the deployment's parameters (root)\n host-env seed copy a box's host.env into the deployment's parameters\n install-channel install the release this box's channel names (root)\n\nDeployment-wide settings (CARLOS_STORE_OPERATORS):\n\n pdf status\n\n antivirus status is object scanning wired, switched on, and answering?\n Reports wiring and policy separately, because they fail\n separately.\n antivirus enable turn object scanning on for this deployment. Refused if\n no engine is wired: a record claiming enabled with\n nothing behind it would report health where no scan can\n run.\n antivirus disable turn it off. Takes effect on the next tick — no restart,\n which is the point of the switch living in a record\n rather than in the unit file.\n antivirus rotate-webhook-key\n deliver the current master-derived callback secret to\n every scanning-enabled app, one bounded batch at a\n time. Skips apps already on that key, restarts the\n rest, and is safe to run again.\n\nPlatform GeoIP (ops account owners and CARLOS_SYSTEM_OPERATORS):\n\n geoip publish <file.mmdb> publish a MaxMind-format database (DB-IP Lite or\n GeoLite2) to every edge. -force skips the shrink check\n geoip status the published database, and whether every box\n strips forged headers and has it\n geoip off stop: edges drop the database and send no geo headers\n\nEnabling antivirus scans nothing by itself: a member still requests scanning\nfor their app, and an operator still grants it per store.\n\nThe platform is not an app: the console is updated with carlos deploy --app console.\n"} |