host: root installs named-units from the box's parameter
runAdoptUnderRootRelease runs a named-units step after the -restart-only return and before the release key parse: read the box's SSM parameter (IMDS identity), gate it with validateForInstall and the console guard rule, and under the config-sync flock install it unless the bytes are equal or a recorded rollback may still compare the file's identity (declarationBindingInUse). The outcome is written to /var/lib/carlos-named-units/status.json; status gains the record types.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+933
−0
internal/host/agent.go+12 −0internal/host/namedunitsfetch.go+324 −0internal/host/namedunitsfetch_test.go+525 −0internal/host/rootrollback.go+43 −0internal/status/snapshot.go+29 −0
Intent
Attributed to this commit: 6.72 g CO₂e (759,234 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on named-units-param-114, 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/internal/host/agent.go b/internal/host/agent.go| index a9cd9b53b..e92c1903c 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -6155,6 +6155,18 @@ func runAdoptUnderRootRelease(args []string, buildClaims ClaimFactory, ensureUni |
| })) |
| return nil |
| } |
| + // The named-units step (#114 follow-up): install this box's declaration |
| + // parameter as the file SyncUnits and the release path read, under the |
| + // config-sync flock, on full and config-only passes alike. Here, outside |
| + // the CARLOS_SECRETS_KEY branch below, because the release path reads |
| + // the same file on a box without the key; and its record is written |
| + // before the release key parse, which can end the pass, so an install |
| + // is never left unreported. Never fatal. |
| + namedUnits := adoptNamedUnitsStep(ctx) |
| + log.Print(namedUnitsLogLine(namedUnits)) |
| + if err := writeNamedUnitsStatus(namedUnits); err != nil { |
| + log.Printf("adopt: named-units status: %v", err) |
| + } |
| // Parsed here, before config sync, exactly as the full pass always has |
| // (a box with an unusable release key must die before it converges |
| // anything), but SKIPPED entirely for -config-only: that mode never |
diff --git a/internal/host/namedunitsfetch.go b/internal/host/namedunitsfetch.go| new file mode 100644 |
| index 000000000..560968363 |
| --- /dev/null |
| +++ b/internal/host/namedunitsfetch.go |
| @@ -0,0 +1,324 @@ |
| +// Root's named-units step (spec 2026-11-19-named-units-from-parameters, |
| +// "What root does each pass"): read this box's declaration parameter, |
| +// gate it the way both readers of the file would, and install it under |
| +// the config-sync flock, unless the release path may still compare the |
| +// current file's identity. The step never touches the file when the |
| +// parameter is absent, a read fails, the value is refused or the bytes are |
| +// equal. Its outcome is a status record the agent reports; nothing reads |
| +// the record as authority. |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "slices" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/namedunits" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rootstate" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// namedUnitsStatusDir is the public root store the step's record lands in |
| +// (status.json), the /var/lib/carlos-swap-status convention: root-owned, |
| +// world-readable, replaced atomically. |
| +const namedUnitsStatusDir = "/var/lib/carlos-named-units" |
| + |
| +// namedUnitsReadTimeout bounds opening the parameter store and the one |
| +// GetParameter, so an unreachable SSM costs a pass at most this. |
| +const namedUnitsReadTimeout = 10 * time.Second |
| + |
| +// The step's outcomes, as the record and the journal spell them. |
| +const ( |
| + namedUnitsInstalled = "installed" |
| + namedUnitsUnchanged = "unchanged" |
| + namedUnitsNotFound = "not-found" |
| + namedUnitsUnreadable = "unreadable" |
| + namedUnitsInvalid = "invalid" |
| + namedUnitsHeld = "held" |
| + namedUnitsSkipped = "skipped" |
| + // namedUnitsFailed: the config-sync lock could not be taken, or the |
| + // value passed every gate and the hold and the write itself failed (a |
| + // full disk, say). Not in the spec's list, which has no word for it. |
| + namedUnitsFailed = "failed" |
| +) |
| + |
| +// namedUnitsFetch is the step with every effect injected; production |
| +// wiring is productionNamedUnitsFetch. |
| +type namedUnitsFetch struct { |
| + skip func() string // non-empty: skip, with this reason, before any network call |
| + identity func(ctx context.Context) (iid, region string, err error) |
| + open func(ctx context.Context, region string) (hostenv.NamedUnitsStore, error) |
| + lock func() (func(), error) |
| + dst string |
| + // openDst opens dst for reading: rootstate.OpenTrustedFile in |
| + // production, the reader the release path uses for the same file. |
| + openDst func(path string) (*os.File, error) |
| + // inUse is declarationBindingInUse, bound to the box's stores. |
| + inUse func(host string) (bool, error) |
| + // guardHost is consoleGuardHost(release.OptDir()); an error refuses |
| + // the value (invalid). |
| + guardHost func() (host string, ok bool, err error) |
| + now func() time.Time |
| +} |
| + |
| +// run is one pass of the step. It never writes the status record; its |
| +// caller does, so a later stage can add the pass's delivery outcomes. |
| +func (f namedUnitsFetch) run(ctx context.Context) status.NamedUnitsStatus { |
| + st := status.NamedUnitsStatus{At: f.now().UTC()} |
| + if reason := f.skip(); reason != "" { |
| + return f.settle(st, namedUnitsSkipped, reason) |
| + } |
| + iid, region, err := f.identity(ctx) |
| + if err == nil && (iid == "" || region == "") { |
| + err = errors.New("the identity document has no instance ID or region") |
| + } |
| + if err != nil { |
| + return f.settle(st, namedUnitsSkipped, fmt.Sprintf("no EC2 identity: %v", err)) |
| + } |
| + st.InstanceID, st.Region = iid, region |
| + param, err := hostenv.NamedUnitsParameter(iid) |
| + if err != nil { |
| + return f.settle(st, namedUnitsSkipped, err.Error()) |
| + } |
| + st.Parameter = param |
| + |
| + raw, version, err := f.read(ctx, region, iid) |
| + if errors.Is(err, hostenv.ErrNoParameter) { |
| + return f.settle(st, namedUnitsNotFound, "") |
| + } |
| + if err != nil { |
| + return f.settle(st, namedUnitsUnreadable, err.Error()) |
| + } |
| + st.Version = version |
| + if err := validateForInstall(raw); err != nil { |
| + return f.settle(st, namedUnitsInvalid, err.Error()) |
| + } |
| + entries, err := namedunits.Decode(raw) |
| + if err != nil { |
| + return f.settle(st, namedUnitsInvalid, err.Error()) |
| + } |
| + |
| + unlock, err := f.lock() |
| + if err != nil { |
| + return f.settle(st, namedUnitsFailed, fmt.Sprintf("config-sync lock: %v", err)) |
| + } |
| + defer unlock() |
| + return f.installLocked(st, raw, entries) |
| +} |
| + |
| +// read opens the store and gets the parameter within namedUnitsReadTimeout. |
| +func (f namedUnitsFetch) read(ctx context.Context, region, iid string) ([]byte, int64, error) { |
| + ctx, cancel := context.WithTimeout(ctx, namedUnitsReadTimeout) |
| + defer cancel() |
| + store, err := f.open(ctx, region) |
| + if err != nil { |
| + return nil, 0, err |
| + } |
| + return store.Get(ctx, iid) |
| +} |
| + |
| +// installLocked is the half of the step that runs under the config-sync |
| +// flock: the box's guard rule (its read under the same lock as the write), |
| +// the current file, the hold, and the write. |
| +func (f namedUnitsFetch) installLocked(st status.NamedUnitsStatus, raw []byte, entries []namedunits.Entry) status.NamedUnitsStatus { |
| + guarded, armed, err := f.guardHost() |
| + if err != nil { |
| + return f.settle(st, namedUnitsInvalid, fmt.Sprintf("console guard marker: %v", err)) |
| + } |
| + if err := checkGuardRule(entries, guarded, armed); err != nil { |
| + return f.settle(st, namedUnitsInvalid, err.Error()) |
| + } |
| + // A current file root can't read safely is held, not replaced: root |
| + // can't tell which hosts' bindings it is part of. |
| + current, exists, err := f.readDst() |
| + if err != nil { |
| + st.Outcome, st.Reason = namedUnitsHeld, fmt.Sprintf("cannot read the installed file %s: %v", f.dst, err) |
| + return st |
| + } |
| + if exists && bytes.Equal(current, raw) { |
| + st.Outcome, st.Digest = namedUnitsUnchanged, namedUnitsDigest(current) |
| + return st |
| + } |
| + // The hosts whose binding the file's identity may be part of: every |
| + // host the current file names, and the guarded console host even when |
| + // no file names it, since the release path synthesises its entry and |
| + // binds the file's identity all the same (proofnamed.go). A current |
| + // file the release path can't decode binds nothing. |
| + var affected []string |
| + if exists { |
| + if prior, err := namedunits.Decode(current); err == nil { |
| + affected = namedunits.Hosts(prior) |
| + } |
| + } |
| + if armed && !slices.Contains(affected, guarded) { |
| + affected = append(affected, guarded) |
| + } |
| + for _, host := range affected { |
| + inUse, err := f.inUse(host) |
| + if err != nil { |
| + st.Outcome, st.Reason = namedUnitsHeld, fmt.Sprintf("cannot tell whether a recorded rollback of %s needs the current declarations: %v", host, err) |
| + } else if inUse { |
| + st.Outcome, st.Reason = namedUnitsHeld, fmt.Sprintf("a recorded rollback of %s needs the current declarations", host) |
| + } else { |
| + continue |
| + } |
| + if exists { |
| + st.Digest = namedUnitsDigest(current) |
| + } |
| + return st |
| + } |
| + if err := installNamedUnitsLocked(f.dst, raw); err != nil { |
| + return f.settle(st, namedUnitsFailed, err.Error()) |
| + } |
| + st.Outcome, st.Digest = namedUnitsInstalled, namedUnitsDigest(raw) |
| + return st |
| +} |
| + |
| +// settle sets the outcome and the digest of the file as it stands, read |
| +// best-effort: the record only reports. |
| +func (f namedUnitsFetch) settle(st status.NamedUnitsStatus, outcome, reason string) status.NamedUnitsStatus { |
| + st.Outcome, st.Reason = outcome, reason |
| + if raw, exists, err := f.readDst(); err == nil && exists { |
| + st.Digest = namedUnitsDigest(raw) |
| + } |
| + return st |
| +} |
| + |
| +// readDst is the current file through openDst, capped as the release path |
| +// caps it. Absent is (nil, false, nil). |
| +func (f namedUnitsFetch) readDst() ([]byte, bool, error) { |
| + file, err := f.openDst(f.dst) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil, false, nil |
| + } |
| + if err != nil { |
| + return nil, false, err |
| + } |
| + defer file.Close() |
| + raw, err := io.ReadAll(io.LimitReader(file, rootstate.MaxRecord+1)) |
| + if err != nil { |
| + return nil, false, err |
| + } |
| + if len(raw) > rootstate.MaxRecord { |
| + return nil, false, os.ErrPermission |
| + } |
| + return raw, true, nil |
| +} |
| + |
| +func namedUnitsDigest(raw []byte) string { |
| + sum := sha256.Sum256(raw) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +// productionNamedUnitsFetch is the step as root runs it. |
| +func productionNamedUnitsFetch() namedUnitsFetch { |
| + return namedUnitsFetch{ |
| + skip: func() string { return namedUnitsSkipReason("/etc", os.Getenv) }, |
| + identity: func(context.Context) (string, string, error) { |
| + iid, _, region, err := readIdentity(haIMDSClient, imdsBase) |
| + return iid, region, err |
| + }, |
| + open: hostenv.OpenNamedUnitsStore, |
| + lock: func() (func(), error) { return lockConfigSync(appconfig.DefaultEnvDir + "/.sync") }, |
| + dst: appconfig.DefaultNamedUnitsPath, |
| + openDst: rootstate.OpenTrustedFile, |
| + inUse: func(host string) (bool, error) { |
| + return productionDeclarationBindingInUse(host, time.Now()) |
| + }, |
| + guardHost: func() (string, bool, error) { return consoleGuardHost(release.OptDir()) }, |
| + now: time.Now, |
| + } |
| +} |
| + |
| +// namedUnitsSkipReason: boxes that can't take a per-box declaration skip |
| +// the step without a network call, rather than fail every pass with |
| +// AccessDenied. A group-launched box has /etc/carlos/group.json; a managed |
| +// fleet box has CARLOS_FLEET set (resolved or not: a misconfigured fleet |
| +// box is still not a fixed box). |
| +func namedUnitsSkipReason(etc string, getenv func(string) string) string { |
| + if groupMarkerPresent(etc) { |
| + return "a group-launched box takes no per-box declaration" |
| + } |
| + if _, err := resolveFleetIdentity(getenv); !errors.Is(err, errNotFleetBox) { |
| + return "a managed-fleet box takes no per-box declaration" |
| + } |
| + return "" |
| +} |
| + |
| +// productionDeclarationBindingInUse opens the restart journal and the root |
| +// history read-only, as their owners lay them out (rootRestartState; |
| +// release.RootHistoryDir, as openRootHistory opens it but without |
| +// creating it). A store that doesn't exist holds nothing. |
| +func productionDeclarationBindingInUse(host string, now time.Time) (bool, error) { |
| + attempts, err := rootstate.Open(rootRestartState, false, false) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + defer attempts.Close() |
| + var history *release.RootHistory |
| + s, err := rootstate.Open(release.RootHistoryDir, false, false) |
| + switch { |
| + case err == nil: |
| + defer s.Close() |
| + history = &release.RootHistory{Store: s} |
| + case !errors.Is(err, os.ErrNotExist): |
| + return false, err |
| + } |
| + return declarationBindingInUse(attempts, history, host, now) |
| +} |
| + |
| +// adoptNamedUnitsStep is the step runAdoptUnderRootRelease runs; a |
| +// variable so a test can drive the real pass with the step injected. |
| +var adoptNamedUnitsStep = func(ctx context.Context) status.NamedUnitsStatus { |
| + return productionNamedUnitsFetch().run(ctx) |
| +} |
| + |
| +// writeNamedUnitsStatus replaces status.json in namedUnitsStatusDir. |
| +func writeNamedUnitsStatus(st status.NamedUnitsStatus) error { |
| + raw, err := json.Marshal(st) |
| + if err != nil { |
| + return err |
| + } |
| + s, err := rootstate.Open(namedUnitsStatusDir, true, true) |
| + if err != nil { |
| + return err |
| + } |
| + defer s.Close() |
| + return s.Write("status.json", raw) |
| +} |
| + |
| +// namedUnitsLogLine is the step's one journal line per pass. |
| +func namedUnitsLogLine(st status.NamedUnitsStatus) string { |
| + switch st.Outcome { |
| + case namedUnitsUnreadable: |
| + if st.Parameter != "" { |
| + return fmt.Sprintf("named-units: parameter %s unreadable: %s; the installed declarations stand", st.Parameter, st.Reason) |
| + } |
| + return fmt.Sprintf("named-units: unreadable: %s; the installed declarations stand", st.Reason) |
| + case namedUnitsInstalled: |
| + return fmt.Sprintf("named-units: installed %s version %d from %s (sha256 %s)", appconfig.DefaultNamedUnitsPath, st.Version, st.Parameter, st.Digest) |
| + case namedUnitsNotFound: |
| + return fmt.Sprintf("named-units: no parameter %s; the installed declarations stand", st.Parameter) |
| + case namedUnitsUnchanged: |
| + return fmt.Sprintf("named-units: %s version %d unchanged", st.Parameter, st.Version) |
| + default: |
| + if st.Parameter != "" { |
| + return fmt.Sprintf("named-units: %s version %d %s: %s", st.Parameter, st.Version, st.Outcome, st.Reason) |
| + } |
| + return fmt.Sprintf("named-units: %s: %s", st.Outcome, st.Reason) |
| + } |
| +} |
diff --git a/internal/host/namedunitsfetch_test.go b/internal/host/namedunitsfetch_test.go| new file mode 100644 |
| index 000000000..4cf2219b2 |
| --- /dev/null |
| +++ b/internal/host/namedunitsfetch_test.go |
| @@ -0,0 +1,525 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "maps" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +const ( |
| + fetchIID = "i-0123456789abcdef0" |
| + fetchRegion = "eu-west-1" |
| + shopAEntry = `{"host":"a.example.com","app":"shop","unit":"shop.service","addr":"127.0.0.1:1","health":{"path":"/"}}` |
| + shopBEntry = `{"host":"b.example.com","app":"shop","unit":"shop-b.service","addr":"127.0.0.1:2","health":{"path":"/"}}` |
| + consoleC = `{"host":"c.example.com","app":"console","unit":"console.service","addr":"127.0.0.1:8090","health":{"path":"/healthz"}}` |
| +) |
| + |
| +func declFile(entries ...string) []byte { |
| + return []byte(`{"schema":1,"units":[` + strings.Join(entries, ",") + `]}`) |
| +} |
| + |
| +type fakeNamedUnitsStore struct { |
| + raw []byte |
| + version int64 |
| + err error |
| + gets int |
| +} |
| + |
| +func (s *fakeNamedUnitsStore) Get(_ context.Context, iid string) ([]byte, int64, error) { |
| + s.gets++ |
| + if iid != fetchIID { |
| + return nil, 0, errors.New("wrong instance id") |
| + } |
| + return s.raw, s.version, s.err |
| +} |
| + |
| +func (s *fakeNamedUnitsStore) Put(context.Context, string, []byte) (int64, error) { |
| + return 0, errors.New("root never puts") |
| +} |
| + |
| +// fetchFixture fakes every field of namedUnitsFetch except the lock, which |
| +// is the real config-sync flock in a temp directory. |
| +type fetchFixture struct { |
| + dir, dst string |
| + store *fakeNamedUnitsStore |
| + skipReason string |
| + inUse map[string]bool |
| + inUseErr error |
| + asked []string |
| + guard string |
| + guardErr error |
| + identityCalls int |
| + openCalls int |
| +} |
| + |
| +func newFetchFixture(t *testing.T) *fetchFixture { |
| + t.Helper() |
| + dir := t.TempDir() |
| + return &fetchFixture{dir: dir, dst: filepath.Join(dir, "named-units.json"), store: &fakeNamedUnitsStore{version: 4}, inUse: map[string]bool{}} |
| +} |
| + |
| +var fetchClock = time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC) |
| + |
| +func (x *fetchFixture) fetch() namedUnitsFetch { |
| + return namedUnitsFetch{ |
| + skip: func() string { return x.skipReason }, |
| + identity: func(context.Context) (string, string, error) { |
| + x.identityCalls++ |
| + return fetchIID, fetchRegion, nil |
| + }, |
| + open: func(_ context.Context, region string) (hostenv.NamedUnitsStore, error) { |
| + x.openCalls++ |
| + if region != fetchRegion { |
| + return nil, errors.New("wrong region") |
| + } |
| + return x.store, nil |
| + }, |
| + lock: func() (func(), error) { return lockConfigSync(x.dir + "/.sync") }, |
| + dst: x.dst, |
| + openDst: os.Open, |
| + inUse: func(host string) (bool, error) { |
| + x.asked = append(x.asked, host) |
| + return x.inUse[host], x.inUseErr |
| + }, |
| + guardHost: func() (string, bool, error) { return x.guard, x.guard != "", x.guardErr }, |
| + now: func() time.Time { return fetchClock }, |
| + } |
| +} |
| + |
| +func (x *fetchFixture) install(t *testing.T, raw []byte) os.FileInfo { |
| + t.Helper() |
| + if err := os.WriteFile(x.dst, raw, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + fi, err := os.Stat(x.dst) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return fi |
| +} |
| + |
| +// unchanged: the file holds raw on the same inode it had before. |
| +func (x *fetchFixture) unchanged(t *testing.T, before os.FileInfo, raw []byte) { |
| + t.Helper() |
| + got, err := os.ReadFile(x.dst) |
| + if err != nil || string(got) != string(raw) { |
| + t.Fatalf("file = %q, %v; want %q", got, err, raw) |
| + } |
| + after, err := os.Stat(x.dst) |
| + if err != nil || !os.SameFile(before, after) { |
| + t.Fatalf("the file was replaced (%v)", err) |
| + } |
| +} |
| + |
| +func digestOf(raw []byte) string { |
| + sum := sha256.Sum256(raw) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +func wantOutcome(t *testing.T, st status.NamedUnitsStatus, outcome string) { |
| + t.Helper() |
| + if st.Outcome != outcome { |
| + t.Fatalf("outcome = %q (%s), want %q", st.Outcome, st.Reason, outcome) |
| + } |
| + if !st.At.Equal(fetchClock) { |
| + t.Fatalf("At = %v, want %v", st.At, fetchClock) |
| + } |
| +} |
| + |
| +func TestNamedUnitsFetchNotFoundKeepsFile(t *testing.T) { |
| + x := newFetchFixture(t) |
| + current := declFile(shopAEntry) |
| + before := x.install(t, current) |
| + x.store.err = hostenv.ErrNoParameter |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "not-found") |
| + x.unchanged(t, before, current) |
| + if st.Parameter != hostenv.NamedUnitsPrefix+fetchIID || st.InstanceID != fetchIID || st.Region != fetchRegion { |
| + t.Fatalf("identity not recorded: %+v", st) |
| + } |
| + if st.Digest != digestOf(current) { |
| + t.Fatalf("Digest = %q, want the installed file's", st.Digest) |
| + } |
| +} |
| + |
| +func TestNamedUnitsFetchReadErrorKeepsFileAndContinues(t *testing.T) { |
| + x := newFetchFixture(t) |
| + current := declFile(shopAEntry) |
| + before := x.install(t, current) |
| + x.store.err = context.DeadlineExceeded |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "unreadable") |
| + x.unchanged(t, before, current) |
| + if !strings.Contains(st.Reason, context.DeadlineExceeded.Error()) { |
| + t.Fatalf("reason %q does not carry the error", st.Reason) |
| + } |
| +} |
| + |
| +func TestNamedUnitsFetchInvalidKeepsFile(t *testing.T) { |
| + x := newFetchFixture(t) |
| + current := declFile(shopAEntry) |
| + before := x.install(t, current) |
| + x.store.raw = declFile(`{"host":"b.example.com","app":"shop","unit":"shop-b.service","health":{"path":"/"}}`) |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "invalid") |
| + x.unchanged(t, before, current) |
| + if !strings.Contains(st.Reason, "b.example.com") { |
| + t.Fatalf("reason %q does not name the host", st.Reason) |
| + } |
| + if st.Version != 4 { |
| + t.Fatalf("Version = %d, want the version read", st.Version) |
| + } |
| +} |
| + |
| +func TestNamedUnitsFetchEqualBytesNoRewrite(t *testing.T) { |
| + x := newFetchFixture(t) |
| + current := declFile(shopAEntry) |
| + before := x.install(t, current) |
| + x.store.raw = append([]byte(nil), current...) |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "unchanged") |
| + x.unchanged(t, before, current) |
| + if st.Digest != digestOf(current) { |
| + t.Fatalf("Digest = %q", st.Digest) |
| + } |
| +} |
| + |
| +func TestNamedUnitsFetchInstallsNewValue(t *testing.T) { |
| + x := newFetchFixture(t) |
| + x.install(t, declFile(shopAEntry)) |
| + value := declFile(shopAEntry, shopBEntry) |
| + x.store.raw = value |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "installed") |
| + got, err := os.ReadFile(x.dst) |
| + if err != nil || string(got) != string(value) { |
| + t.Fatalf("file = %q, %v", got, err) |
| + } |
| + if fi, _ := os.Stat(x.dst); fi.Mode().Perm() != 0o644 { |
| + t.Fatalf("mode = %o, want 0644", fi.Mode().Perm()) |
| + } |
| + if st.Version != 4 || st.Digest != digestOf(value) { |
| + t.Fatalf("Version %d Digest %q", st.Version, st.Digest) |
| + } |
| +} |
| + |
| +func TestNamedUnitsFetchInstallsClearingValue(t *testing.T) { |
| + x := newFetchFixture(t) |
| + x.install(t, declFile(shopAEntry)) |
| + value := []byte(`{"schema":1,"units":[]}`) |
| + x.store.raw = value |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "installed") |
| + if got, _ := os.ReadFile(x.dst); string(got) != string(value) { |
| + t.Fatalf("file = %q", got) |
| + } |
| +} |
| + |
| +func TestNamedUnitsFetchHeldWhileBindingInUse(t *testing.T) { |
| + x := newFetchFixture(t) |
| + current := declFile(shopAEntry) |
| + before := x.install(t, current) |
| + value := declFile(shopBEntry) |
| + x.store.raw = value |
| + x.inUse["a.example.com"] = true |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "held") |
| + x.unchanged(t, before, current) |
| + if !strings.Contains(st.Reason, "a.example.com") { |
| + t.Fatalf("reason %q does not name the host", st.Reason) |
| + } |
| + if st.Digest != digestOf(current) { |
| + t.Fatalf("Digest = %q, want the file as it stands", st.Digest) |
| + } |
| + |
| + t.Run("an error reading the attempt holds too", func(t *testing.T) { |
| + x.inUse["a.example.com"] = false |
| + x.inUseErr = os.ErrPermission |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "held") |
| + x.unchanged(t, before, current) |
| + x.inUseErr = nil |
| + }) |
| + |
| + x.inUse["a.example.com"] = false |
| + st = x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "installed") |
| + if got, _ := os.ReadFile(x.dst); string(got) != string(value) { |
| + t.Fatalf("file = %q", got) |
| + } |
| +} |
| + |
| +func TestNamedUnitsFetchHoldsForGuardedConsoleHost(t *testing.T) { |
| + x := newFetchFixture(t) |
| + x.guard = "c.example.com" |
| + x.inUse["c.example.com"] = true |
| + x.store.raw = declFile(shopBEntry) |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "held") |
| + if !strings.Contains(st.Reason, "c.example.com") { |
| + t.Fatalf("reason %q does not name the guarded host", st.Reason) |
| + } |
| + if _, err := os.Stat(x.dst); !os.IsNotExist(err) { |
| + t.Fatalf("the file was written while held: %v", err) |
| + } |
| + if st.Digest != "" { |
| + t.Fatalf("Digest = %q for an absent file", st.Digest) |
| + } |
| +} |
| + |
| +func TestNamedUnitsFetchSkipsGroupAndFleetWithoutNetwork(t *testing.T) { |
| + x := newFetchFixture(t) |
| + current := declFile(shopAEntry) |
| + before := x.install(t, current) |
| + x.skipReason = "group-launched box" |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "skipped") |
| + if st.Reason != "group-launched box" { |
| + t.Fatalf("reason = %q", st.Reason) |
| + } |
| + if x.identityCalls != 0 || x.openCalls != 0 || x.store.gets != 0 { |
| + t.Fatalf("a skipped box reached the network: identity %d open %d get %d", x.identityCalls, x.openCalls, x.store.gets) |
| + } |
| + x.unchanged(t, before, current) |
| + |
| + t.Run("no identity", func(t *testing.T) { |
| + x.skipReason = "" |
| + f := x.fetch() |
| + f.identity = func(context.Context) (string, string, error) { return "", "", errors.New("IMDS token: no route") } |
| + st := f.run(context.Background()) |
| + wantOutcome(t, st, "skipped") |
| + if x.openCalls != 0 { |
| + t.Fatal("a box with no identity opened the store") |
| + } |
| + }) |
| +} |
| + |
| +func TestNamedUnitsFetchGuardHostMustBeConsole(t *testing.T) { |
| + x := newFetchFixture(t) |
| + current := declFile(shopBEntry) |
| + before := x.install(t, current) |
| + x.guard = "a.example.com" |
| + x.store.raw = declFile(shopAEntry, shopBEntry) |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "invalid") |
| + x.unchanged(t, before, current) |
| + if !strings.Contains(st.Reason, "a.example.com") { |
| + t.Fatalf("reason %q does not name the host", st.Reason) |
| + } |
| + |
| + t.Run("an unreadable marker refuses", func(t *testing.T) { |
| + x.guard = "" |
| + x.guardErr = os.ErrPermission |
| + x.store.raw = declFile(shopBEntry, `{"host":"d.example.com","app":"shop","unit":"shop-d.service","addr":"127.0.0.1:4","health":{"path":"/"}}`) |
| + st := x.fetch().run(context.Background()) |
| + wantOutcome(t, st, "invalid") |
| + x.unchanged(t, before, current) |
| + }) |
| +} |
| + |
| +func TestNamedUnitsFetchWaitsForConfigSyncLock(t *testing.T) { |
| + x := newFetchFixture(t) |
| + value := declFile(shopAEntry) |
| + x.store.raw = value |
| + unlock, err := lockConfigSync(x.dir + "/.sync") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + done := make(chan status.NamedUnitsStatus, 1) |
| + go func() { done <- x.fetch().run(context.Background()) }() |
| + select { |
| + case st := <-done: |
| + t.Fatalf("the step finished while the pass held the lock: %+v", st) |
| + case <-time.After(300 * time.Millisecond): |
| + } |
| + if _, err := os.Stat(x.dst); err == nil { |
| + t.Fatal("the file appeared while the lock was held") |
| + } |
| + unlock() |
| + select { |
| + case st := <-done: |
| + wantOutcome(t, st, "installed") |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the step did not proceed once the lock was released") |
| + } |
| + if got, _ := os.ReadFile(x.dst); string(got) != string(value) { |
| + t.Fatalf("file = %q", got) |
| + } |
| +} |
| + |
| +// TestDeclarationBindingInUse follows what the recovery code would still do |
| +// with an attempt (recoverRootRestarts -> resumeHistoryRestart -> |
| +// settleHistory): only that work compares the declaration file's identity. |
| +func TestDeclarationBindingInUse(t *testing.T) { |
| + const host = "a.example.com" |
| + rt := registry.Route{Host: host, Account: "acme", App: "shop"} |
| + binding := release.HistoryBinding{Host: host, Account: "acme", App: "shop"} |
| + now := time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC) |
| + hist := release.HistoryAttempt{ID: "attempt-1", Version: "v2", Source: "src", Started: now.Add(-time.Hour)} |
| + attempt := func(mut func(*rollbackAttempt)) rollbackAttempt { |
| + a := rollbackAttempt{ID: strings.Repeat("ab", 16), Host: host, Created: now.Add(-2 * time.Minute), Deadline: now.Add(time.Minute), Target: "t"} |
| + mut(&a) |
| + return a |
| + } |
| + type tc struct { |
| + name string |
| + journal *rollbackAttempt |
| + pending bool // the history still holds hist as its pending attempt |
| + noHist bool // no history store on the box |
| + settle bool // hist was begun and then completed |
| + want bool |
| + } |
| + withHistory := func(a *rollbackAttempt) { h := hist; a.History, a.HistoryBinding = &h, binding } |
| + past := func(a *rollbackAttempt) { a.Deadline = now.Add(-time.Minute - rollbackMargin - time.Second) } |
| + cases := []tc{ |
| + {name: "no attempt", want: false}, |
| + {name: "open within the deadline", journal: p(attempt(func(*rollbackAttempt) {})), want: true}, |
| + {name: "open at deadline plus margin", journal: p(attempt(func(a *rollbackAttempt) { a.Deadline = now.Add(-rollbackMargin) })), want: true}, |
| + {name: "past the deadline, no history", journal: p(attempt(past)), want: false}, |
| + {name: "settled, no history", journal: p(attempt(func(a *rollbackAttempt) { a.Settled = true })), want: false}, |
| + {name: "settled and verified, history pending", journal: p(attempt(func(a *rollbackAttempt) { past(a); a.Settled, a.Verified = true, true; withHistory(a) })), pending: true, want: true}, |
| + {name: "settled by the deadline, history pending", journal: p(attempt(func(a *rollbackAttempt) { past(a); a.Settled = true; withHistory(a) })), pending: true, want: true}, |
| + {name: "unsettled past the deadline, history pending", journal: p(attempt(func(a *rollbackAttempt) { past(a); withHistory(a) })), pending: true, want: true}, |
| + {name: "settled, history completed", journal: p(attempt(func(a *rollbackAttempt) { past(a); a.Settled, a.Verified = true, true; withHistory(a) })), settle: true, want: false}, |
| + {name: "settled, history pending another attempt", journal: p(attempt(func(a *rollbackAttempt) { |
| + past(a) |
| + a.Settled, a.Verified = true, true |
| + withHistory(a) |
| + a.History.ID = "attempt-0" |
| + })), pending: true, want: false}, |
| + // resumeHistoryRestart returns at once for a settled, failed or |
| + // recovering attempt that was never verified: no binding work. |
| + {name: "settled recovering unverified, history pending", journal: p(attempt(func(a *rollbackAttempt) { past(a); a.Settled, a.Recovering = true, true; withHistory(a) })), pending: true, want: false}, |
| + {name: "settled failed unverified, history pending", journal: p(attempt(func(a *rollbackAttempt) { past(a); a.Settled, a.Failed = true, true; withHistory(a) })), pending: true, want: false}, |
| + // settleHistory never consults Pending for an independent attempt. |
| + {name: "settled independent", journal: p(attempt(func(a *rollbackAttempt) { |
| + past(a) |
| + a.Settled, a.Verified, a.Independent = true, true, true |
| + withHistory(a) |
| + })), pending: true, want: false}, |
| + {name: "history store absent", journal: p(attempt(func(a *rollbackAttempt) { past(a); a.Settled, a.Verified = true, true; withHistory(a) })), noHist: true, want: false}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + attempts := &rollbackMemory{files: map[string][]byte{}} |
| + if c.journal != nil { |
| + if err := writeRollbackState(attempts, rollbackJournalKey(host), *c.journal); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var history *release.RootHistory |
| + if !c.noHist { |
| + history = seedHostRootHistory(t, rt) |
| + if c.pending || c.settle { |
| + if err := history.Begin(binding, hist); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if c.settle { |
| + if err := history.Settle(binding, hist.ID, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + beforeAttempts := maps.Clone(attempts.files) |
| + var beforeHistory map[string][]byte |
| + if history != nil { |
| + beforeHistory = maps.Clone(history.Store.(*rollbackMemory).files) |
| + } |
| + got, err := declarationBindingInUse(attempts, history, host, now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got != c.want { |
| + t.Fatalf("in use = %v, want %v", got, c.want) |
| + } |
| + if !reflect.DeepEqual(beforeAttempts, attempts.files) { |
| + t.Fatal("the attempt store changed") |
| + } |
| + if history != nil && !reflect.DeepEqual(beforeHistory, history.Store.(*rollbackMemory).files) { |
| + t.Fatal("the history store changed") |
| + } |
| + }) |
| + } |
| + t.Run("an unreadable journal is an error", func(t *testing.T) { |
| + attempts := &rollbackMemory{files: map[string][]byte{rollbackJournalKey(host): []byte("{")}} |
| + if _, err := declarationBindingInUse(attempts, nil, host, now); err == nil { |
| + t.Fatal("a corrupt journal read as not in use") |
| + } |
| + }) |
| +} |
| + |
| +func p(a rollbackAttempt) *rollbackAttempt { return &a } |
| + |
| +// TestAdoptRunsNamedUnitsStepBeforeConfigSync reads source for the same |
| +// reason TestRunAdoptOpensTheRegistryThroughTheHelper does: the order is |
| +// the invariant. The step runs on full and config-only passes (after the |
| +// -restart-only return), its record is written before the release key |
| +// parse can kill the pass, and it sits outside the CARLOS_SECRETS_KEY |
| +// branch, so a box without the key still installs. |
| +func TestAdoptRunsNamedUnitsStepBeforeConfigSync(t *testing.T) { |
| + raw, err := os.ReadFile("agent.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + src := string(raw) |
| + start := strings.Index(src, "\nfunc runAdoptUnderRootRelease(") |
| + if start < 0 { |
| + t.Fatal("runAdoptUnderRootRelease is no longer in agent.go, move this test with it") |
| + } |
| + body := src[start+1:] |
| + if end := strings.Index(body, "\n}\n"); end >= 0 { |
| + body = body[:end] |
| + } |
| + at := func(s string) int { |
| + t.Helper() |
| + i := strings.Index(body, s) |
| + if i < 0 { |
| + t.Fatalf("runAdoptUnderRootRelease no longer contains %q", s) |
| + } |
| + return i |
| + } |
| + restart := at("if *restartOnly {") |
| + restartEnd := restart + strings.Index(body[restart:], "\n\t}\n") |
| + step := at("adoptNamedUnitsStep(") |
| + write := at("writeNamedUnitsStatus(") |
| + pub := at("release.ParsePublicKey(") |
| + secrets := at(`os.Getenv("CARLOS_SECRETS_KEY")`) |
| + sync := at("appconfig.SyncUnits(") |
| + if n := strings.Count(body, "adoptNamedUnitsStep("); n != 1 { |
| + t.Fatalf("adoptNamedUnitsStep( appears %d times, want once", n) |
| + } |
| + if !(restartEnd < step && step < write && write < pub && pub < secrets && secrets < sync) { |
| + t.Fatalf("order: restart-only end %d, step %d, write %d, ParsePublicKey %d, secrets %d, SyncUnits %d", restartEnd, step, write, pub, secrets, sync) |
| + } |
| +} |
| + |
| +func TestProductionNamedUnitsFetchIsWired(t *testing.T) { |
| + f := productionNamedUnitsFetch() |
| + v := reflect.ValueOf(f) |
| + for i := 0; i < v.NumField(); i++ { |
| + if fv := v.Field(i); fv.Kind() == reflect.Func && fv.IsNil() { |
| + t.Errorf("productionNamedUnitsFetch leaves %s nil", v.Type().Field(i).Name) |
| + } |
| + } |
| + if f.dst != appconfig.DefaultNamedUnitsPath { |
| + t.Fatalf("dst = %q, want %q", f.dst, appconfig.DefaultNamedUnitsPath) |
| + } |
| + if adoptNamedUnitsStep == nil { |
| + t.Fatal("adoptNamedUnitsStep is nil") |
| + } |
| +} |
diff --git a/internal/host/rootrollback.go b/internal/host/rootrollback.go| index 2833c81e0..1aab3ac18 100644 |
| --- a/internal/host/rootrollback.go |
| +++ b/internal/host/rootrollback.go |
| @@ -73,6 +73,49 @@ func readRollbackAttempt(s rootstate.Store, host string) (rollbackAttempt, error |
| return a, nil |
| } |
| +// declarationBindingInUse: the release path may still compare the |
| +// declaration file's identity for host, so root must not replace the file |
| +// yet (Astra plan R1 #1). True when host's attempt journal exists and |
| +// either |
| +// |
| +// - it is unsettled and now is not after Deadline+rollbackMargin (the |
| +// window captureRollback and loadRollback honour), or |
| +// - it carries a history attempt that recoverRootRestarts would still |
| +// settle through settleHistory, which binds the host again: the history |
| +// still holds exactly *a.History as pending (the Pending comparison |
| +// settleHistory makes), the attempt is not independent (settleHistory |
| +// never consults Pending for those), and it is not a failed or |
| +// recovering attempt that was never verified (resumeHistoryRestart |
| +// returns at once for those). Settled or not: an unsettled one past |
| +// its deadline is settled by loadRollback and then reaches the same |
| +// settleHistory. |
| +// |
| +// history may be nil (no history store on the box: nothing pending). No |
| +// side effects beyond Pending's own recommit of the record's exact bytes. |
| +func declarationBindingInUse(s rootstate.Store, history *release.RootHistory, host string, now time.Time) (bool, error) { |
| + a, err := readRollbackAttempt(s, host) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + if !a.Settled && !now.After(a.Deadline.Add(rollbackMargin)) { |
| + return true, nil |
| + } |
| + if a.History == nil || a.Independent || ((a.Failed || a.Recovering) && !a.Verified) || history == nil { |
| + return false, nil |
| + } |
| + pending, err := history.Pending(a.HistoryBinding) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + return pending != nil && *pending == *a.History, nil |
| +} |
| + |
| func settleRollbackAttempt(s rootstate.Store, a rollbackAttempt) error { |
| if !a.Settled { |
| a.Settled = true |
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go| index e28a8f9cc..0b04b3e8a 100644 |
| --- a/internal/status/snapshot.go |
| +++ b/internal/status/snapshot.go |
| @@ -398,6 +398,35 @@ type ConfigRefusal struct { |
| Count int `json:"count"` |
| } |
| +// NamedUnitsStatus is root's record of its last named-units step: which |
| +// parameter it read, at what version, what it did with the value |
| +// (Outcome: installed, unchanged, not-found, unreadable, invalid, held, |
| +// skipped or failed) and why, the sha256 of the declaration file as it |
| +// stood afterwards, and each declared unit's delivery state from the last |
| +// config pass. It only reports; nothing reads it as authority. |
| +// |
| +// PRIVATE, like everything under Box.Metrics: it names hosts and units. |
| +type NamedUnitsStatus struct { |
| + Parameter string `json:"parameter,omitempty"` |
| + InstanceID string `json:"instance_id,omitempty"` |
| + Region string `json:"region,omitempty"` |
| + Version int64 `json:"version,omitempty"` |
| + Outcome string `json:"outcome"` |
| + Reason string `json:"reason,omitempty"` |
| + Digest string `json:"digest,omitempty"` // sha256 hex of the installed file |
| + At time.Time `json:"at"` |
| + Units []NamedUnitDelivery `json:"units,omitempty"` |
| +} |
| + |
| +// NamedUnitDelivery is one declared unit's config delivery on the last |
| +// pass: State "delivered", or "refused" with the rail's Reason. |
| +type NamedUnitDelivery struct { |
| + Host string `json:"host"` |
| + Unit string `json:"unit"` |
| + State string `json:"state"` // "delivered" | "refused" |
| + Reason string `json:"reason,omitempty"` |
| +} |
| + |
| // ReleaseRefusal is a build this box rolled back because its unit did not |
| // come up (D1, release.Refusal). PRIVATE like the rest of Box.Metrics: Host |
| // is a real route name. |