carlos / platform Public

Add attended group preparation and local rollback

Prepare the signed system artifact without restarting the member. Reuse the
apply lock and guard for explicit same-transaction rollback permits.

Report edge start timestamps from kernel boot time and AT_CLKTCK. Cover
preparation, apply, rollback refusals, replay and cache tampering with fakes.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev d48d82d1b004cbd80182fda793288ea3d35f2404 parent 8b29402
6 files changed, +938 −19
  • internal/host/group_maintenance_clock.go +95 −0
  • internal/host/group_maintenance_prepare.go +280 −0
  • internal/host/group_maintenance_prepare_test.go +467 −0
  • internal/host/group_maintenance_verbs.go +63 −11
  • internal/host/systemapply.go +27 −8
  • internal/host/systemleg.go +6 −0

Intent

Human

<task-notification> <task-id>a1a337dfbefa6d1b9</task-id> <tool-use-id>toolu_01GfrvLcMbvfVJwRNq3hKhH8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/a1a337dfbefa6d1b9.output</output-file> <status>completed</status> <summary>Agent "Re-review B2 follow-up" 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>Change 1 (lock scope, no create): ADDRESSED. - `group_maintenance_verbs.go` ~86-110: status skips `MkdirAll`. `openMaintenanceLock(path, create=false)` for status, and ENOENT leaves `lock` nil, so no lock is taken. - Marker re-read, directory open and `permitStatus` all run under the lock (~108-145). The lock is closed (~146-152) before `cmd.status` makes the `cmd.edge` and health probes. - `_linux.go` drops `O_CREAT` and `Mode` when `create` is false. - The comment about group boxes always having a lock is present. - `TestGroupMaintenanceVerbsStatusLockScope` asserts the lock is held on the permit read and on the second marker read, and free during all 3 probes. - `StatusNoCreate` covers a missing root dir and a missing lock file, and checks nothing is created. Change 2 (`accepted`): ADDRESSED, with one caveat below. - `permitStatus` (~226-233) calls `validateMaintenancePermit`, then `validateMaintenanceArtifact`. That is the guard's order, minus the action-match check in between, which has no meaning without a requested action. - A missing permit.json or an absent dir leaves `Accepted` nil. An unreadable file returns early with nil, which is correct. - Malformed JSON gives `accepted: false` with state `unknown`. This is consistent with the brief. - The help text has the two new lines. - Per-mode tests: valid, expired, wrong iid/phase/binary, new-binary, unreadable, malformed, absent dir, revoked. Change 3 (`rollback_consumed`): ADDRESSED. - `permitStatus` ~243-250: `consumed` is read for the permit's own action. `RollbackConsumed` is set only when `p.AllowRollback`, otherwise nil. Tests cover rollback-unused, rollback-used, both-used and rollback-action. Change 4 (permit dir without permit.json): ADDRESSED. - The `revoked` subtest in `StatusPermit` runs revoke, checks the dir still exists, then expects `state: absent` with `accepted`, `consumed` and `rollback_consumed` null. Schema is still `v: 1` with additive keys. Status still makes one local GET and no cloud calls. In the run I did, `go test -run GroupMaintenance` passed, gofmt was clean and vet was silent. I did not run cross builds. New breakage: - Important, to your "never true when the guard would refuse" criterion: `accepted` ignores consumption. A permit with `consumed: true`, or `rollback_consumed: true`, still reports `accepted: true`. The guard's `check` path (`maintenanceUnconsumed`) and `consumeGroupAction` (which, going by its call in `requireGroupMaintenance`, fails if the record exists) would refuse it. This matches the brief's literal definition and the verb exposes `consumed` separately. But `accepted: true` can then sit beside a permit the guard refuses. Either document in the help text that `accepted` means validators only, or fold the consumed state into it. Related minor point: `accepted` is also action-agnostic, so an `install` permit reads accepted for an apply the guard would refuse. - Nothing else new in this diff. Verdict: open: `accepted` versus a consumed permit (document it or fold it in). The four requested changes are otherwise addressed.</result> <usage><subagent_tokens>54564</subagent_tokens><tool_uses>5</tool_uses><duration_ms>48965</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>b56z5h9dg</task-id> <tool-use-id>toolu_01TS2emKLcg1axs1nGos5ZLU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/b56z5h9dg.output</output-file> <status>completed</status> <summary>Background command ".superpowers/sdd/2026-11-04-region-ha-p3b-group/run-astra.sh b1g" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a9e2253db86963c22</task-id> <tool-use-id>toolu_01D2KihMR6QSyd6WVKoUVFHm</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/a9e2253db86963c22.output</output-file> <status>completed</status> <summary>Agent "Re-review B1 fix round 1" 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>(1) ADDRESSED. `group_operator.tf:97` sets the resource to `${local.group_operator_ssm_arn}${data.aws_caller_identity.current.account_id}:session/*`. The ssm ARN local at line 15 is `arn:&lt;partition&gt;:ssm:&lt;region&gt;:`, so this is `arn:&lt;partition&gt;:ssm:&lt;region&gt;:&lt;account&gt;:session/*`. The explanatory comment is at lines 88-93. It covers the group-tag and approved-document gate on StartSession, the starter-only session token, why the `aws:userid` prefix never matches roles or SSO users, and the witness runbook confirmation. (2) ADDRESSED. The precondition at `group_operator.tf:102-106` now has `!endswith(local.group_operator_document, ":document/SSM-SessionManagerRunShell") &amp;&amp; (...)`. The existing AWS-StartNonInteractiveCommand and account-owned-document checks are kept inside the parentheses. The comment at lines 64-65 is updated. The test is `run "invalid_default_shell_document"` at `tests/group_operator.tftest.hcl:227-231`. It uses an account-owned ARN, so it exercises the new guard and not the existing AWS-owned rejection. It uses `expect_failures = [output.group_operator_policy_json]`, the same as the neighbouring document tests. The report says this test failed before the fix and the suite passed after it. I did not run tofu myself. (3) ADDRESSED. In `tests/group_operator.tftest.hcl`, the edges GetObject resource is the literal `arn:aws:s3:::carlos-dev-platform/control/edges/*` at line 168. The OpenDataChannel resource is the literal `arn:aws:ssm:eu-west-1:123456789012:session/*` at line 174. New breakage: none. The diff touches only that one statement, the precondition, a comment and the tests. - **Fixed mode:** the output is still `""`, and the precondition still returns true when `!group_enabled`. - **Other statements:** none changed. The OwnSessions Terminate/Resume statement keeps its `aws:userid` session-id tag condition, so ResumeSession and TerminateSession stay caller-scoped. - **Precondition message:** `error_message` does not mention the shell-document rejection. That is cosmetic only. - **Accepted trade-off:** OpenDataChannel is now account-wide `session/*` by design, per R9. Its safety rests on the session-token argument in the comment, and live IAM and Session Manager behaviour is not tested. The report says the witness runbook must confirm it from the real operator identity. Verdict: all addressed</result> <usage><subagent_tokens>44484</subagent_tokens><tool_uses>2</tool_uses><duration_ms>16245</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>b30z22pol</task-id> <tool-use-id>toolu_01HdXubdGPxohHC6cGBBhvhi</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/b30z22pol.output</output-file> <status>completed</status> <summary>Background command ".superpowers/sdd/2026-11-04-region-ha-p3b-group/run-astra.sh b3" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bac8q96hm</task-id> <tool-use-id>toolu_015KgwTe1kr2yy357tdPw1vJ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/e47280e8-3e59-4dc1-95d2-11de7237d34c/tasks/bac8q96hm.output</output-file> <status>completed</status> <summary>Background command ".superpowers/sdd/2026-11-04-region-ha-p3b-group/run-astra.sh b2b" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/host/group_maintenance_clock.go b/internal/host/group_maintenance_clock.go
new file mode 100644
index 000000000..6f863cf24
--- /dev/null
+++ b/internal/host/group_maintenance_clock.go
@@ -0,0 +1,95 @@
+package host
+
+import (
+ "encoding/binary"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// The edges object's generation is written by this box's own agent using the
+// same clock. The operator compares publication and process start on one clock.
+func maintenanceProcessStartedAt(procRoot, start string) (string, error) {
+ ticks, err := strconv.ParseUint(start, 10, 64)
+ if err != nil || ticks == 0 {
+ return "", errors.New("process start ticks unavailable")
+ }
+ stat, err := maintenanceReadProc(filepath.Join(procRoot, "stat"), 1<<20)
+ if err != nil {
+ return "", err
+ }
+ boot := uint64(0)
+ for _, line := range strings.Split(string(stat), "\n") {
+ fields := strings.Fields(line)
+ if len(fields) > 0 && fields[0] == "btime" {
+ if len(fields) != 2 || boot != 0 {
+ return "", errors.New("boot time invalid")
+ }
+ boot, err = strconv.ParseUint(fields[1], 10, 64)
+ if err != nil || boot == 0 {
+ return "", errors.New("boot time invalid")
+ }
+ }
+ }
+ if boot == 0 {
+ return "", errors.New("boot time unavailable")
+ }
+ aux, err := maintenanceReadProc(filepath.Join(procRoot, "self", "auxv"), 65536)
+ if err != nil {
+ return "", err
+ }
+ word := strconv.IntSize / 8
+ if len(aux)%(2*word) != 0 {
+ return "", errors.New("auxv invalid")
+ }
+ read := func(b []byte) uint64 {
+ if word == 4 {
+ return uint64(binary.NativeEndian.Uint32(b))
+ }
+ return binary.NativeEndian.Uint64(b)
+ }
+ hz := uint64(0)
+ ended := false
+ for i := 0; i < len(aux); i += 2 * word {
+ key, value := read(aux[i:]), read(aux[i+word:])
+ if key == 0 {
+ ended = true
+ break
+ }
+ if key == 17 { // AT_CLKTCK, supplied by the kernel for this process.
+ if hz != 0 || value == 0 || value > 1e9 {
+ return "", errors.New("clock ticks invalid")
+ }
+ hz = value
+ }
+ }
+ if !ended || hz == 0 {
+ return "", errors.New("AT_CLKTCK unavailable")
+ }
+ const maxRFC3339Second = 253402300799
+ seconds := ticks / hz
+ if boot > maxRFC3339Second || seconds > maxRFC3339Second-boot {
+ return "", errors.New("process start time out of range")
+ }
+ return time.Unix(int64(boot+seconds), int64((ticks%hz)*1e9/hz)).UTC().Format(time.RFC3339Nano), nil
+}
+
+func maintenanceReadProc(path string, limit int64) ([]byte, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ b, err := io.ReadAll(io.LimitReader(f, limit+1))
+ if err != nil {
+ return nil, err
+ }
+ if int64(len(b)) > limit {
+ return nil, errors.New("process clock input too large")
+ }
+ return b, nil
+}
diff --git a/internal/host/group_maintenance_prepare.go b/internal/host/group_maintenance_prepare.go
new file mode 100644
index 000000000..a8c8c05ca
--- /dev/null
+++ b/internal/host/group_maintenance_prepare.go
@@ -0,0 +1,280 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/hostenv"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/safefile"
+)
+
+// Session Manager shells need not have sourced host.env. Use only the checked
+// root file for store/channel selection and restart settings, never shell input.
+func configureMaintenanceApplier(a *systemApplier, env map[string]string) error {
+ os.Clearenv()
+ for k, v := range env {
+ if err := os.Setenv(k, v); err != nil {
+ return err
+ }
+ }
+ for k, v := range map[string]string{"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "HOME": "/root", "AWS_MAX_ATTEMPTS": "1", "AWS_RETRY_MODE": "standard"} {
+ if err := os.Setenv(k, v); err != nil {
+ return err
+ }
+ }
+ if err := registerProductionLaunchVerifier(); err != nil {
+ return err
+ }
+ channel, _ := systemChannel(os.Getenv)
+ configured := productionSystemApplier(channel)
+ configured.groupMaintenance = a.groupMaintenance
+ configured.optDir, configured.dataDir, configured.etcDir = a.optDir, a.dataDir, a.etcDir
+ *a = *configured
+ return nil
+}
+
+func (cmd *groupMaintenanceCommand) localConfiguration(c *hostenv.GroupConfig) (map[string]string, error) {
+ a := cmd.a
+ b, err := a.maintenance().read(filepath.Join(a.etcDir, "carlos", "host.env"), a.maintenance().owner, 0600)
+ if err != nil {
+ return nil, fmt.Errorf("host.env: %w", err)
+ }
+ env, err := hostenv.Parse(b)
+ if err != nil {
+ return nil, errors.New("host.env does not parse")
+ }
+ if env[hostenv.BoxReference] != hostenv.GroupReference {
+ return nil, hostenv.ErrGroupConfig
+ }
+ // Reuse boot's required settings and marker bindings without fetching SSM.
+ checked, err := hostenv.AssembleGroup(env, nil, *c, c.QueueURL)
+ if err != nil {
+ return nil, err
+ }
+ if env["CARLOS_TERMINATION_QUEUE_URL"] != checked["CARLOS_TERMINATION_QUEUE_URL"] {
+ return nil, hostenv.ErrGroupConfig
+ }
+ for k := range env {
+ if strings.HasPrefix(k, "CARLOS_HOST_CLAIM") {
+ return nil, hostenv.ErrGroupConfig
+ }
+ }
+ if _, err := release.ParsePublicKey(env["CARLOS_RELEASE_PUBKEY"], "CARLOS_RELEASE_PUBKEY"); err != nil {
+ return nil, err
+ }
+ if _, err := appconfig.ParsePrivateKey(env["CARLOS_SECRETS_KEY"], "CARLOS_SECRETS_KEY"); err != nil {
+ return nil, err
+ }
+ if _, invalid := systemChannel(func(k string) string { return env[k] }); invalid != "" {
+ return nil, errors.New("invalid system channel")
+ }
+ return env, nil
+}
+
+type maintenancePrepared struct {
+ V int `json:"v"`
+ Version string `json:"version"`
+ ReleaseTag string `json:"release_tag"`
+ ArtifactSHA256 string `json:"artifact_sha256"`
+ CachePath string `json:"cache_path"`
+ CacheState string `json:"cache_state"`
+ RequestWritten bool `json:"request_written"`
+ OldBinarySHA256 string `json:"old_binary_sha256"`
+ ConfigCheck string `json:"config_check"`
+}
+
+func (cmd *groupMaintenanceCommand) prepare(ctx context.Context, c *hostenv.GroupConfig, out io.Writer) error {
+ if !groupDigest(cmd.sha256) {
+ return errors.New("invalid artifact digest")
+ }
+ env, err := cmd.localConfiguration(c)
+ if err != nil {
+ return err
+ }
+ if cmd.configure != nil {
+ if err := cmd.configure(cmd.a, env); err != nil {
+ return err
+ }
+ }
+ a := cmd.a
+ old, err := maintenanceBinaryDigest(systemBinaryPath(a.optDir))
+ if err != nil {
+ return err
+ }
+ store, pub, err := a.openStore(ctx)
+ if err != nil {
+ return err
+ }
+ l := systemLegForPreparation(store, pub, func(k string) string { return env[k] }, a.dataDir, a.optDir)
+ l.platform = a.platform
+ p, _, err := release.GetSystemPointer(ctx, l.store, l.pub, release.SystemComponentRouter, l.channel)
+ if err != nil {
+ return err
+ }
+ art, ok := p.Current.Artifacts[l.platform]
+ if !ok || art.SHA256 != cmd.sha256 {
+ return errors.New("pointer artifact does not match requested digest")
+ }
+ if !validSystemVersion(p.Current.Version) {
+ return errors.New("invalid pointer version")
+ }
+ // groupReaderTargetAllowed is the fixed-reader automatic-update gate. This
+ // group-only entry is the serialized operator's path; it has no cached fold
+ // and cannot manufacture the operator's deployment-wide retirement evidence.
+ pending := &systemPending{version: p.Current.Version, promotedAt: p.PromotedAt, artifact: art}
+ // Root never feeds an agent path to fetch/writeRequest's ordinary mkdirs.
+ // Work in root's private scratch, then publish with safefile's descriptor
+ // traversal and private temporary files. Apply re-verifies the published copy.
+ scratch, err := os.MkdirTemp(a.rootDir(), ".prepare-")
+ if err != nil {
+ return err
+ }
+ defer os.RemoveAll(scratch)
+ l.dataDir = scratch
+ cache := systemCachePath(scratch, pending.version)
+ if err := os.MkdirAll(filepath.Dir(cache), 0700); err != nil {
+ return err
+ }
+ src, err := openBeneath(a.dataDir, systemCacheParts(pending.version)...)
+ if err == nil {
+ defer src.Close()
+ if err := writeDurable(cache, 0600, func(w io.Writer) error { _, err := io.Copy(w, io.LimitReader(src, systemArtifactLimit+1)); return err }); err != nil {
+ return err
+ }
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ if err := l.fetch(ctx, pending); err != nil {
+ return err
+ }
+ if !systemCacheHolds(cache, art.SHA256) {
+ return errors.New("cached artifact digest mismatch")
+ }
+ if err := l.writeRequest(pending, a.ops.now()); err != nil {
+ return err
+ }
+ dst := systemCachePath(a.dataDir, pending.version)
+ if err := safefile.MkdirAll(filepath.Dir(dst), 0755); err != nil {
+ return err
+ }
+ if err := copyFileDurable(cache, dst, 0644); err != nil {
+ return err
+ }
+ if err := copyFileDurable(systemRequestPath(scratch), systemRequestPath(a.dataDir), 0644); err != nil {
+ return err
+ }
+ result := maintenancePrepared{V: 1, Version: p.Current.Version, ReleaseTag: p.Current.ReleaseTag, ArtifactSHA256: art.SHA256, CachePath: dst, CacheState: "verified", RequestWritten: true, OldBinarySHA256: old, ConfigCheck: "valid"}
+ b, err := json.Marshal(result)
+ if err != nil {
+ return err
+ }
+ if len(b)+1 > 8192 {
+ return errors.New("prepare result exceeds 8192 bytes")
+ }
+ _, err = out.Write(append(b, '\n'))
+ return err
+}
+
+// Apply reports a completed failure rollback as an error. The attended
+// rollback command alone translates that specific completion into success.
+type systemRollbackCompleted struct{ target, reason string }
+
+func (e *systemRollbackCompleted) Error() string {
+ return fmt.Sprintf("system apply: %s rolled back: %s", e.target, e.reason)
+}
+
+func (cmd *groupMaintenanceCommand) rollback(ctx context.Context, c *hostenv.GroupConfig) error {
+ a := cmd.a
+ if err := a.requireGroupMaintenance("check"); err != nil {
+ return err
+ }
+ g := a.maintenance()
+ raw, err := g.read(filepath.Join(g.dir, "permit.json"), g.owner, 0600)
+ if err != nil {
+ return err
+ }
+ p, err := a.validateMaintenancePermit(raw, c)
+ if err != nil {
+ return err
+ }
+ // R12 binds the return to the apply transaction, even across CLI processes.
+ appliedAction, err := g.read(filepath.Join(g.dir, "used-"+p.Transaction+"-apply"), g.owner, 0600)
+ if err != nil || string(appliedAction) != "consumed\n" {
+ return errGroupMaintenance
+ }
+ // Check both slots before consuming, clearing admission, staging or executing.
+ if p.Action != "rollback" || !groupArtifactHolds(systemPrevPath(a.optDir), p.OldSHA256) || !groupArtifactHolds(systemBinaryPath(a.optDir), p.NewSHA256) {
+ return errGroupMaintenance
+ }
+ if j, err := readSystemJournal(a.optDir); err != nil {
+ return err
+ } else if j != nil {
+ return errors.New("unfinished apply requires recovery")
+ }
+ env, err := cmd.localConfiguration(c)
+ if err != nil {
+ return err
+ }
+ if cmd.configure != nil {
+ if err := cmd.configure(a, env); err != nil {
+ return err
+ }
+ }
+ return a.withSystemRelease(ctx, func(ctx context.Context) error { return a.runLocked(ctx, false, a.rollbackCompletedApply) })
+}
+
+func (a *systemApplier) rollbackCompletedApply(ctx context.Context) error {
+ if err := a.groupTarget(systemPrevPath(a.optDir), true); err != nil {
+ return err
+ }
+ previous, err := a.restoreVersion()
+ if err != nil {
+ return err
+ }
+ if !validSystemVersion(previous) {
+ return errors.New("previous artifact version unavailable")
+ }
+ current := a.onDiskBuild(ctx)
+ applied, err := readSystemApplied(a.optDir)
+ if err != nil {
+ return err
+ }
+ result, err := readSystemResult(a.optDir)
+ if err != nil {
+ return err
+ }
+ if applied == nil || applied.Version != current || result == nil || result.Outcome != systemOutcomeApplied || result.Version != current || result.Channel != a.channel {
+ return errors.New("completed apply record required")
+ }
+ newDir, prevDir := filepath.Join(a.stagingDir(), "new"), filepath.Join(a.stagingDir(), "prev")
+ _, newUnits, err := a.stagePlan(ctx, systemBinaryPath(a.optDir), newDir)
+ if err != nil {
+ return err
+ }
+ _, prevUnits, err := a.stagePlan(ctx, systemPrevPath(a.optDir), prevDir)
+ if err != nil {
+ return err
+ }
+ if err := a.beginExecutableChange(ctx, previous, result.PromotedAt); err != nil {
+ return err
+ }
+ j := systemJournal{Phase: systemPhaseInstalled, Target: current, PromotedAt: result.PromotedAt, PrevBuild: previous, UnitsAdded: unitsMinus(newUnits, prevUnits), UnitsRemoved: unitsMinus(prevUnits, newUnits), StartedAt: a.ops.now().UTC()}
+ if err := a.journal(j); err != nil {
+ return err
+ }
+ req := systemRequest{Version: current, PromotedAt: result.PromotedAt}
+ err = a.rollback(ctx, req, "operator rollback", &j)
+ var completed *systemRollbackCompleted
+ if !errors.As(err, &completed) {
+ return err
+ }
+ return writeJSONDurable(a.file("applied.json"), systemApplied{Version: previous, Channel: a.channel, At: a.ops.now().UTC()}, 0644)
+}
diff --git a/internal/host/group_maintenance_prepare_test.go b/internal/host/group_maintenance_prepare_test.go
new file mode 100644
index 000000000..f4dd08a2f
--- /dev/null
+++ b/internal/host/group_maintenance_prepare_test.go
@@ -0,0 +1,467 @@
+//go:build linux
+
+package host
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "encoding/base64"
+ "encoding/binary"
+ "encoding/json"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/hostenv"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func maintenancePrepareFixture(t *testing.T) (*applyFixture, groupMaintenancePermit, *groupMaintenanceCommand) {
+ t.Helper()
+ f, p, cmd := maintenanceVerbFixture(t)
+ body := []byte("#!/bin/sh\necho carlos v2.0.0\n")
+ f.promote("v2.0.0", body, false)
+ p.NewSHA256, _ = maintenanceBinaryDigest(systemCachePath(f.a.dataDir, "v2.0.0"))
+ cmd.sha256 = p.NewSHA256
+ if err := os.RemoveAll(systemDataDir(f.a.dataDir)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := runMaintenanceVerb(cmd, "revoke", nil); err != nil {
+ t.Fatal(err)
+ }
+ c, err := f.a.maintenanceConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ env := map[string]string{}
+ for _, k := range hostenv.Required {
+ if !strings.HasPrefix(k, "CARLOS_HOST_CLAIM") {
+ env[k] = "1"
+ }
+ }
+ env["CARLOS_RELEASE_PUBKEY"] = base64.StdEncoding.EncodeToString(f.pub)
+ env["CARLOS_SECRETS_KEY"] = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32))
+ env["CARLOS_DEPLOYMENT_BUCKET"] = c.Bucket
+ env["CARLOS_REGION"] = *c.Placement
+ env["AWS_REGION"] = c.DeploymentAWSRegion
+ env["CARLOS_HIBERNATE_REGION"] = c.AWSRegion
+ env["CARLOS_POOLS"] = strings.Join(c.Pools, ",")
+ env["CARLOS_REGION_HA"] = "true"
+ env["CARLOS_GROUP_ADMISSION"] = "1"
+ env["CARLOS_CHANGE_INDEX"] = "read"
+ env["CARLOS_TERMINATION_QUEUE_URL"] = c.QueueURL
+ env["CARLOS_HIBERNATE_BUCKET"] = c.DataBucket
+ env["CARLOS_SYSTEM_CHANNEL"] = f.a.channel
+ env[hostenv.BoxReference] = hostenv.GroupReference
+ b, err := hostenv.Render(env)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(f.a.etcDir, "carlos", "host.env"), b, 0600); err != nil {
+ t.Fatal(err)
+ }
+ current := systemBinaryPath(f.a.optDir)
+ delete(f.answer, "version:"+current)
+ for _, binary := range []string{filepath.Join(f.a.stagingDir(), "carlos"), systemPrevPath(f.a.optDir)} {
+ f.answer["plan:"+binary] = f.answer["plan:"+current]
+ f.answer["units:"+binary] = f.answer["units:"+current]
+ }
+ return f, p, cmd
+}
+
+func TestGroupMaintenancePrepareApply(t *testing.T) {
+ for _, permit := range []bool{false, true} {
+ t.Run(map[bool]string{false: "no-permit", true: "permit"}[permit], func(t *testing.T) {
+ f, p, cmd := maintenancePrepareFixture(t)
+ for i := 0; i < 2; i++ {
+ raw, err := runMaintenanceVerb(cmd, "prepare", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got struct {
+ V int `json:"v"`
+ Artifact string `json:"artifact_sha256"`
+ Old string `json:"old_binary_sha256"`
+ Written bool `json:"request_written"`
+ Config string `json:"config_check"`
+ Cache string `json:"cache_state"`
+ }
+ if err := json.Unmarshal(raw, &got); err != nil {
+ t.Fatal(err)
+ }
+ if got.V != 1 || got.Artifact != p.NewSHA256 || got.Old != p.OldSHA256 || !got.Written || got.Config != "valid" || got.Cache != "verified" || len(raw) > 8192 {
+ t.Fatalf("result: %s", raw)
+ }
+ if !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.OldSHA256) || len(f.calls) != 0 {
+ t.Fatalf("prepare changed running system: %v", f.calls)
+ }
+ if _, err := os.Stat(f.a.stagingDir()); !os.IsNotExist(err) {
+ t.Fatalf("prepare staged: %v", err)
+ }
+ if _, err := os.Stat(systemPrevPath(f.a.optDir)); !os.IsNotExist(err) {
+ t.Fatalf("prepare made backup: %v", err)
+ }
+ req, err := f.a.readRequest()
+ if err != nil || req.Version != "v2.0.0" || req.NoOp {
+ t.Fatalf("request %+v: %v", req, err)
+ }
+ }
+ if permit {
+ b, _ := json.Marshal(p)
+ if _, err := runMaintenanceVerb(cmd, "permit", b); err != nil {
+ t.Fatal(err)
+ }
+ }
+ err := f.a.Run(t.Context(), false)
+ if !permit {
+ if err == nil || len(f.calls) != 0 || !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.OldSHA256) {
+ t.Fatalf("unguarded apply: %v %v", err, f.calls)
+ }
+ if _, err := os.Stat(f.a.stagingDir()); !os.IsNotExist(err) {
+ t.Fatal("unguarded stage")
+ }
+ } else if err != nil || !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.NewSHA256) || f.result().Outcome != systemOutcomeApplied {
+ t.Fatalf("apply: %v %+v", err, f.result())
+ }
+ })
+ }
+}
+
+func TestGroupMaintenancePrepareRefuses(t *testing.T) {
+ for _, bad := range []string{"digest", "signature", "config-missing", "config-parse", "config-mode", "fixed", "marker", "symlink-cache", "symlink-request"} {
+ t.Run(bad, func(t *testing.T) {
+ f, p, cmd := maintenancePrepareFixture(t)
+ switch bad {
+ case "digest":
+ cmd.sha256 = strings.Repeat("b", 64)
+ case "signature":
+ _, priv, _ := ed25519.GenerateKey(nil)
+ f.pub = priv.Public().(ed25519.PublicKey)
+ case "config-missing":
+ os.Remove(filepath.Join(f.a.etcDir, "carlos", "host.env"))
+ case "config-parse":
+ os.WriteFile(filepath.Join(f.a.etcDir, "carlos", "host.env"), []byte("not an assignment"), 0600)
+ case "config-mode":
+ os.Chmod(filepath.Join(f.a.etcDir, "carlos", "host.env"), 0644)
+ case "fixed":
+ os.Remove(filepath.Join(f.a.etcDir, "carlos", "group.json"))
+ case "marker":
+ os.WriteFile(filepath.Join(f.a.etcDir, "carlos", "group.json"), []byte("{}"), 0644)
+ case "symlink-cache":
+ if err := os.RemoveAll(filepath.Join(f.a.dataDir, "system")); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(t.TempDir(), filepath.Join(f.a.dataDir, "system")); err != nil {
+ t.Fatal(err)
+ }
+ case "symlink-request":
+ os.MkdirAll(systemDataDir(f.a.dataDir), 0755)
+ os.Symlink(t.TempDir(), filepath.Dir(systemCachePath(f.a.dataDir, "v2.0.0")))
+ }
+ if _, err := runMaintenanceVerb(cmd, "prepare", nil); err == nil {
+ t.Fatal("accepted " + bad)
+ }
+ if len(f.calls) != 0 || !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.OldSHA256) {
+ t.Fatalf("side effects: %v", f.calls)
+ }
+ })
+ }
+}
+
+func TestGroupMaintenanceCompletedRollback(t *testing.T) {
+ for _, mode := range []string{"success", "no-permit", "wrong-old", "apply-consumed", "consumed", "wrong-transaction"} {
+ t.Run(mode, func(t *testing.T) {
+ f, p, cmd := maintenancePrepareFixture(t)
+ if _, err := runMaintenanceVerb(cmd, "prepare", nil); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := json.Marshal(p)
+ if _, err := runMaintenanceVerb(cmd, "permit", b); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.a.Run(t.Context(), false); err != nil {
+ t.Fatal(err)
+ }
+ if !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.NewSHA256) {
+ t.Fatal("apply did not install")
+ }
+ if mode != "apply-consumed" {
+ if _, err := runMaintenanceVerb(cmd, "revoke", nil); err != nil {
+ t.Fatal(err)
+ }
+ p.Action = "rollback"
+ if mode == "wrong-transaction" {
+ p.Transaction = "other-transaction"
+ }
+ if mode == "wrong-old" {
+ p.OldSHA256 = strings.Repeat("c", 64)
+ }
+ if mode != "no-permit" {
+ b, _ = json.Marshal(p)
+ if _, err := runMaintenanceVerb(cmd, "permit", b); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ if mode == "consumed" {
+ if err := consumeGroupAction(f.a.maintenance().dir, "used-"+p.Transaction+"-rollback", f.a.maintenance().owner); err != nil {
+ t.Fatal(err)
+ }
+ }
+ f.calls = nil
+ f.a.openStore = func(context.Context) (release.Store, ed25519.PublicKey, error) {
+ t.Fatal("rollback opened cloud store")
+ return nil, nil, nil
+ }
+ _, err := runMaintenanceVerb(cmd, "rollback", nil)
+ if mode != "success" {
+ if mode == "wrong-old" {
+ if _, e := os.Lstat(filepath.Join(f.a.maintenance().dir, "used-"+p.Transaction+"-rollback")); !os.IsNotExist(e) {
+ t.Fatalf("wrong old digest consumed action: %v", e)
+ }
+ }
+ if err == nil || len(f.calls) != 0 || !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.NewSHA256) {
+ t.Fatalf("bad rollback: %v %v", err, f.calls)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.OldSHA256) || !f.called("systemctl restart carlos-edge") {
+ t.Fatalf("rollback not complete: %v", f.calls)
+ }
+ f.calls = nil
+ if _, err := runMaintenanceVerb(cmd, "rollback", nil); err == nil || len(f.calls) != 0 {
+ t.Fatalf("replayed rollback: %v %v", err, f.calls)
+ }
+ })
+ }
+}
+
+func TestGroupMaintenanceStartedAt(t *testing.T) {
+ for _, bad := range []string{"valid", "stat-missing", "auxv-missing", "ticks-missing", "ticks-zero", "stat-invalid", "overflow"} {
+ t.Run(bad, func(t *testing.T) {
+ root := t.TempDir()
+ os.Mkdir(filepath.Join(root, "self"), 0700)
+ stat := []byte("cpu 1 2 3\nbtime 1700000000\n")
+ aux := make([]byte, 32)
+ binary.NativeEndian.PutUint64(aux, 17)
+ binary.NativeEndian.PutUint64(aux[8:], 250)
+ start := "625"
+ switch bad {
+ case "ticks-missing":
+ binary.NativeEndian.PutUint64(aux, 16)
+ case "ticks-zero":
+ binary.NativeEndian.PutUint64(aux[8:], 0)
+ case "stat-invalid":
+ stat = []byte("btime no\n")
+ case "overflow":
+ start = "18446744073709551615"
+ }
+ if bad != "stat-missing" {
+ os.WriteFile(filepath.Join(root, "stat"), stat, 0600)
+ }
+ if bad != "auxv-missing" {
+ os.WriteFile(filepath.Join(root, "self", "auxv"), aux, 0600)
+ }
+ got, err := maintenanceProcessStartedAt(root, start)
+ if bad == "valid" {
+ if err != nil || got != "2023-11-14T22:13:22.5Z" {
+ t.Fatalf("%q %v", got, err)
+ }
+ } else if err == nil {
+ t.Fatalf("accepted %s: %s", bad, got)
+ }
+ f, _, cmd := maintenanceVerbFixture(t)
+ _ = f
+ cmd.startedAt = func(string) (string, error) { return got, err }
+ raw, e := runMaintenanceVerb(cmd, "status", nil)
+ if e != nil {
+ t.Fatal(e)
+ }
+ var s struct {
+ Edge struct {
+ Started *string `json:"started_at"`
+ Error *string `json:"error"`
+ } `json:"edge"`
+ }
+ if json.Unmarshal(raw, &s) != nil {
+ t.Fatal(string(raw))
+ }
+ if bad == "valid" {
+ if s.Edge.Started == nil || *s.Edge.Started != got {
+ t.Fatal(string(raw))
+ }
+ } else if s.Edge.Started != nil || s.Edge.Error == nil {
+ t.Fatal(string(raw))
+ }
+ })
+ }
+}
+
+func TestGroupMaintenancePrepareArguments(t *testing.T) {
+ for _, args := range [][]string{{"prepare"}, {"prepare", "--sha256", "bad"}, {"rollback", "extra"}} {
+ var out bytes.Buffer
+ if code := RunGroupMaintenance(args, strings.NewReader(""), io.Discard, &out); code != 2 {
+ t.Fatalf("%v: %d", args, code)
+ }
+ }
+ if !strings.Contains(groupMaintenanceHelp, "attended") || !strings.Contains(groupMaintenanceHelp, "prepare") || !strings.Contains(groupMaintenanceHelp, "accepted means") {
+ t.Fatal("missing help")
+ }
+}
+
+// Count store reads without giving the wrapper a streaming fast path.
+type maintenanceCountingStore struct {
+ release.Store
+ gets map[string]int
+}
+
+func (s maintenanceCountingStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.gets[key]++
+ return s.Store.Get(ctx, key)
+}
+
+func TestGroupMaintenancePrepareCache(t *testing.T) {
+ f, p, cmd := maintenancePrepareFixture(t)
+ gets := map[string]int{}
+ f.a.openStore = func(context.Context) (release.Store, ed25519.PublicKey, error) {
+ return maintenanceCountingStore{f.store, gets}, f.pub, nil
+ }
+ artifactKey := release.SystemArtifactKey("v2.0.0", f.a.platform)
+ for i := 0; i < 2; i++ {
+ if _, err := runMaintenanceVerb(cmd, "prepare", nil); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if gets[artifactKey] != 1 || gets[release.SystemPointerKey("router", f.a.channel)] != 2 {
+ t.Fatalf("GETs: %v", gets)
+ }
+ // A later agent cache substitution is only input. Apply checks the signed
+ // digest again before it executes anything from the cache.
+ cache := systemCachePath(f.a.dataDir, "v2.0.0")
+ if err := os.WriteFile(cache, []byte("changed cache"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := json.Marshal(p)
+ if _, err := runMaintenanceVerb(cmd, "permit", b); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.a.Run(t.Context(), false); err != nil {
+ t.Fatal(err)
+ }
+ if f.result() == nil || f.result().Outcome != systemOutcomeRefused || !groupArtifactHolds(systemBinaryPath(f.a.optDir), p.OldSHA256) || f.called("systemctl stop") || f.called("run carlos bootstrap") {
+ t.Fatalf("cache trusted: %+v %v", f.result(), f.calls)
+ }
+}
+
+func TestGroupMaintenancePrepareLocalChecksBeforeStore(t *testing.T) {
+ for _, which := range []string{"missing-config", "wrong-bucket", "missing-secret", "invalid-secret", "wrong-queue", "claim-mode", "busy", "not-root"} {
+ t.Run(which, func(t *testing.T) {
+ f, _, cmd := maintenancePrepareFixture(t)
+ path := filepath.Join(f.a.etcDir, "carlos", "host.env")
+ b, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ env, err := hostenv.Parse(b)
+ if err != nil {
+ t.Fatal(err)
+ }
+ switch which {
+ case "missing-config":
+ os.Remove(path)
+ case "wrong-bucket":
+ env["CARLOS_DEPLOYMENT_BUCKET"] = "other"
+ case "invalid-secret":
+ env["CARLOS_SECRETS_KEY"] = "invalid"
+ case "missing-secret":
+ delete(env, "CARLOS_SECRETS_KEY")
+ case "wrong-queue":
+ env["CARLOS_TERMINATION_QUEUE_URL"] = "other"
+ case "claim-mode":
+ env["CARLOS_HOST_CLAIM"] = "1"
+ case "not-root":
+ cmd.euid = func() int { return 123 }
+ case "busy":
+ held, e := openMaintenanceLock(f.a.lockPath(), true)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer held.Close()
+ if e := flockExclusiveNonblock(held); e != nil {
+ t.Fatal(e)
+ }
+ }
+ if which != "missing-config" {
+ b, err = hostenv.Render(env)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(path, b, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ f.a.openStore = func(context.Context) (release.Store, ed25519.PublicKey, error) {
+ t.Fatal("store opened before local refusal")
+ return nil, nil, nil
+ }
+ if _, err := runMaintenanceVerb(cmd, "prepare", nil); err == nil {
+ t.Fatal("accepted " + which)
+ }
+ })
+ }
+}
+
+func TestGroupMaintenancePreparePreservesLocalFiles(t *testing.T) {
+ f, p, cmd := maintenancePrepareFixture(t)
+ hostEnv := filepath.Join(f.a.etcDir, "carlos", "host.env")
+ before, err := os.ReadFile(hostEnv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cert := filepath.Join(f.a.dataDir, "cert.pem")
+ if err := os.WriteFile(cert, []byte("existing certificate"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := runMaintenanceVerb(cmd, "prepare", nil); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := json.Marshal(p)
+ if _, err := runMaintenanceVerb(cmd, "permit", b); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.a.Run(t.Context(), false); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := runMaintenanceVerb(cmd, "revoke", nil); err != nil {
+ t.Fatal(err)
+ }
+ p.Action = "rollback"
+ b, _ = json.Marshal(p)
+ if _, err := runMaintenanceVerb(cmd, "permit", b); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := runMaintenanceVerb(cmd, "rollback", nil); err != nil {
+ t.Fatal(err)
+ }
+ for path, want := range map[string][]byte{hostEnv: before, cert: []byte("existing certificate")} {
+ got, err := os.ReadFile(path)
+ if err != nil || !bytes.Equal(got, want) {
+ t.Fatalf("local file changed: %s %v", path, err)
+ }
+ }
+ entries, err := os.ReadDir(f.a.rootDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, entry := range entries {
+ if strings.HasPrefix(entry.Name(), ".prepare-") {
+ t.Fatalf("scratch left: %s", entry.Name())
+ }
+ }
+}
diff --git a/internal/host/group_maintenance_verbs.go b/internal/host/group_maintenance_verbs.go
index 1a42baf8d..bfc737946 100644
--- a/internal/host/group_maintenance_verbs.go
+++ b/internal/host/group_maintenance_verbs.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "flag"
"fmt"
"io"
"net"
@@ -17,11 +18,20 @@ import (
"github.com/carlosframework/platform/internal/release"
)
-const groupMaintenanceHelp = `Usage: carlos system group-maintenance {status|permit|revoke}
+const groupMaintenanceHelp = `Usage: carlos system group-maintenance {status|permit|revoke|prepare|rollback}
Root only, on a group member. Use through the attended Session Manager operator.
+ prepare --sha256 <digest>
+ Verify the configured signed pointer, cache its artifact and write a request.
+ Check local restart configuration. No staging, repoint or restart.
+ Makes cloud GETs only when attended and operator-invoked, never on a timer.
+ rollback Restore this member's previous artifact using an explicit rollback permit.
+ Use the same transaction and old/new digests after revoking the apply permit.
+ Local only. A consumed rollback permit cannot be replayed.
permit Read at most 4096 bytes of permit JSON from stdin and install it.
revoke Remove the permit. Keep all consumed-action records.
status Print one v1 JSON object, at most 8192 bytes. Make one local health GET.
+Status includes edge.started_at in UTC, derived from kernel boot time and clock ticks.
+accepted means the guard's validators accept this permit now; it is not readiness: check the action and its consumed flag too.
Status is local evidence, not proof of fresh admission or role publication.
Present and accepted is still not authorization for the operator.
The cloud facts are the operator's.
@@ -32,7 +42,7 @@ refuses the command. Unknown status fields are null or state "unknown".
`
// RunGroupMaintenance returns an exit code so command errors never log.Fatal
-// inside tests. No store, credentials provider or host.env is opened here.
+// inside tests. Only prepare opens a store; status remains local.
func RunGroupMaintenance(args []string, in io.Reader, out, stderr io.Writer) int {
if len(args) == 1 && (args[0] == "help" || args[0] == "-h" || args[0] == "--help") {
if _, err := io.WriteString(out, groupMaintenanceHelp); err != nil {
@@ -40,16 +50,19 @@ func RunGroupMaintenance(args []string, in io.Reader, out, stderr io.Writer) int
}
return 0
}
- if len(args) != 1 || (args[0] != "permit" && args[0] != "revoke" && args[0] != "status") {
+ verb, digest, err := maintenanceArguments(args)
+ if err != nil {
fmt.Fprint(stderr, groupMaintenanceHelp)
return 2
}
cmd := groupMaintenanceCommand{
- a: &systemApplier{etcDir: "/etc", optDir: release.OptDir(), ops: productionSysOps()},
+ a: &systemApplier{etcDir: "/etc", optDir: release.OptDir(), dataDir: dataDir(), ops: productionSysOps()},
euid: os.Geteuid, root: "/", edge: maintenanceEdgeProcess,
- client: maintenanceHealthClient(nil),
+ client: maintenanceHealthClient(nil), sha256: digest,
+ startedAt: func(start string) (string, error) { return maintenanceProcessStartedAt("/proc", start) },
+ configure: configureMaintenanceApplier,
}
- if err := cmd.run(context.Background(), args[0], in, out); err != nil {
+ if err := cmd.run(context.Background(), verb, in, out); err != nil {
fmt.Fprintf(stderr, "group-maintenance: %v\n", err)
return 1
}
@@ -60,10 +73,13 @@ type groupMaintenanceCommand struct {
a *systemApplier
euid func() int
// root anchors protected directory traversal. Production always uses /.
- root string
- edge func(context.Context) (int, string, error)
- client *http.Client
- rename func(int, string, int, string) error
+ root string
+ edge func(context.Context) (int, string, error)
+ client *http.Client
+ rename func(int, string, int, string) error
+ sha256 string
+ startedAt func(string) (string, error)
+ configure func(*systemApplier, map[string]string) error
}
func (cmd *groupMaintenanceCommand) run(ctx context.Context, verb string, in io.Reader, out io.Writer) error {
@@ -77,7 +93,7 @@ func (cmd *groupMaintenanceCommand) run(ctx context.Context, verb string, in io.
if c == nil {
return errors.New("group marker required")
}
- if verb != "permit" && verb != "revoke" && verb != "status" {
+ if verb != "permit" && verb != "revoke" && verb != "status" && verb != "prepare" && verb != "rollback" {
return errors.New("unknown operation")
}
// Use the same lock and refusal behavior as system apply. Refuse before
@@ -112,6 +128,12 @@ func (cmd *groupMaintenanceCommand) run(ctx context.Context, verb string, in io.
if c == nil {
return errors.New("group marker required")
}
+ if verb == "prepare" {
+ return cmd.prepare(ctx, c, out)
+ }
+ if verb == "rollback" {
+ return cmd.rollback(ctx, c)
+ }
var body []byte
var permit groupMaintenancePermit
if verb == "permit" {
@@ -177,6 +199,7 @@ type maintenanceProcessStatus struct {
State string `json:"state"`
PID *int `json:"pid"`
StartTime *string `json:"start_time"`
+ StartedAt *string `json:"started_at"`
Identity *string `json:"identity"`
Error *string `json:"error"`
}
@@ -290,6 +313,16 @@ func (cmd *groupMaintenanceCommand) status(ctx context.Context, c *hostenv.Group
if processErr == nil && afterErr == nil && pid > 0 && start != "" && pid == afterPID && start == afterStart {
identity := fmt.Sprintf("%s:%d:%s", c.BootID, pid, start)
s.Edge = maintenanceProcessStatus{State: "known", PID: &pid, StartTime: &start, Identity: &identity}
+ if cmd.startedAt != nil {
+ at, err := cmd.startedAt(start)
+ if err != nil {
+ s.Edge.Error = maintenanceError(err)
+ } else {
+ s.Edge.StartedAt = &at
+ }
+ } else {
+ s.Edge.Error = maintenanceError(errors.New("process clock unavailable"))
+ }
} else {
if processErr == nil {
processErr = afterErr
@@ -311,3 +344,22 @@ func (cmd *groupMaintenanceCommand) status(ctx context.Context, c *hostenv.Group
_, err = out.Write(append(b, '\n'))
return err
}
+
+func maintenanceArguments(args []string) (string, string, error) {
+ if len(args) == 0 {
+ return "", "", errGroupMaintenance
+ }
+ if args[0] == "prepare" {
+ fs := flag.NewFlagSet("prepare", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ digest := fs.String("sha256", "", "artifact digest")
+ if err := fs.Parse(args[1:]); err != nil || fs.NArg() != 0 || !groupDigest(*digest) {
+ return "", "", errGroupMaintenance
+ }
+ return "prepare", *digest, nil
+ }
+ if len(args) == 1 && (args[0] == "permit" || args[0] == "revoke" || args[0] == "status" || args[0] == "rollback") {
+ return args[0], "", nil
+ }
+ return "", "", errGroupMaintenance
+}
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go
index 85cae12dc..1bd5ad522 100644
--- a/internal/host/systemapply.go
+++ b/internal/host/systemapply.go
@@ -128,27 +128,37 @@ func RunSystemApply(args []string) {
if invalidChannel != "" {
log.Printf("system apply: %s=%q is not a channel; this box follows %s", systemChannelEnv, invalidChannel, channel)
}
+ a := productionSystemApplier(channel)
+ a.allowBelowRootfsFloor = *allowBelowRootfsFloor
+ runErr := a.runWithRelease(ctx, *recover)
+ if runErr != nil {
+ log.Fatalf("%v", runErr)
+ }
+}
+
+func productionSystemApplier(channel string) *systemApplier {
a := &systemApplier{
rootMoves: rootMovesFloorIdentity, ops: productionSysOps(), openStore: openSystemStore, channel: channel,
optDir: release.OptDir(), dataDir: dataDir(), etcDir: "/etc", build: version.Build,
platform: runtime.GOOS + "-" + runtime.GOARCH, soak: systemGateSoak,
- handRun: systemApplyHandRun(os.Getenv), allowBelowRootfsFloor: *allowBelowRootfsFloor,
+ handRun: systemApplyHandRun(os.Getenv),
}
a.readEnvironment(os.Getenv)
a.floorHook = installFloorHook // decided under the apply lock, in Run
- runErr := a.runWithRelease(ctx, *recover)
- if runErr != nil {
- log.Fatalf("%v", runErr)
- }
+ return a
}
func (a *systemApplier) runWithRelease(ctx context.Context, recover bool) error {
+ return a.withSystemRelease(ctx, func(ctx context.Context) error { return a.Run(ctx, recover) })
+}
+
+func (a *systemApplier) withSystemRelease(ctx context.Context, run func(context.Context) error) error {
if _, _, err := a.rootMoves.read(); err != nil {
return err
}
return a.participationDisk().WithParticipation(ctx, func(ctx context.Context, _ rootparticipation.Ledger) error {
- return a.Run(ctx, recover)
- }, func() error { return a.Run(ctx, recover) })
+ return run(ctx)
+ }, func() error { return run(ctx) })
}
// openSystemStore is the production openStore: the deploy store and the
@@ -330,6 +340,12 @@ func (a *systemApplier) Run(ctx context.Context, recover bool) (retErr error) {
a.ops.logf("system apply: another apply is running; leaving it to finish")
return nil
}
+ return a.runLocked(ctx, recover, nil)
+}
+
+// The attended rollback already holds the same lock through its command entry.
+// Keep recovery, participation settlement and staging cleanup shared with apply.
+func (a *systemApplier) runLocked(ctx context.Context, recover bool, operation func(context.Context) error) (retErr error) {
a.resetGroupMaintenance()
if err := a.requireGroupMaintenance("check"); err != nil {
return err
@@ -403,6 +419,9 @@ func (a *systemApplier) Run(ctx context.Context, recover bool) (retErr error) {
// if it still wants the update, and by then it can read the result.
return nil
}
+ if operation != nil {
+ return operation(ctx)
+ }
req, err := a.readRequest()
if errors.Is(err, os.ErrNotExist) {
return nil
@@ -1919,7 +1938,7 @@ func (a *systemApplier) rollback(ctx context.Context, req systemRequest, reason
if closeErr != nil {
return closeErr
}
- return fmt.Errorf("system apply: %s rolled back: %s", j.Target, reason)
+ return &systemRollbackCompleted{target: j.Target, reason: reason}
}
// restoreFiles is the files-only half shared by rollback and recovery:
diff --git a/internal/host/systemleg.go b/internal/host/systemleg.go
index 909be5681..98253b4b0 100644
--- a/internal/host/systemleg.go
+++ b/internal/host/systemleg.go
@@ -79,6 +79,12 @@ func newSystemLeg(store release.Store, pub ed25519.PublicKey, getenv func(string
if groupReferenced(getenv) || groupMarkerPresent("/etc") {
return nil
}
+ return systemLegForPreparation(store, pub, getenv, dataDir, optDir)
+}
+
+// Construction is shared with the attended group command. Only newSystemLeg
+// arms automatic observation; group preparation never calls observe or tick.
+func systemLegForPreparation(store release.Store, pub ed25519.PublicKey, getenv func(string) string, dataDir, optDir string) *systemLeg {
channel, invalid := systemChannel(getenv)
l := &systemLeg{
store: store, pub: pub, channel: channel,