carlos / platform Public

fix: managed startup decision, owed control restart

Task 3 fix round 2 (Astra R2 P2s; review stopped at R2).
- A rewritten control drop-in records an owed instance-control restart
  in root's /run before the rewrite; ensureSystemUnits pays it only
  after a successful reload and clears it only when try-restart
  succeeds, so a failed reload or restart is retried next pass.
- RunAgent makes one managed/BYO decision before any fatal group
  preflight: a managed box with any group configuration (marker present
  or invalid, CARLOS_BOX_REFERENCE=group, CARLOS_GROUP_ADMISSION=1)
  takes the refused path and never waits for a group reference; BYO
  keeps the group validation and its fatal exits exactly.
- Named-unit recovery is witnessed through passOption inside
  release.Pass: no work while joining, repair after admission.
- The group name-class census re-pins Reconcile and ReconcileSidecars
  (joining early return, no name class changed).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5e519120340b0039ecf2995380d5f95d5edff674 parent ad28b50
8 files changed, +380 −51
  • internal/host/agent.go +34 −15
  • internal/host/group_names_test.go +9 −6
  • internal/host/managedjoin.go +0 −11
  • internal/host/managedjoin_fix1_test.go +128 −13
  • internal/host/managedstartup.go +79 −0
  • internal/host/managedunits.go +58 −2
  • internal/host/managedunits_fix1_test.go +63 −0
  • internal/host/systemunits.go +9 −4
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 55223aa30..e953b6dbe 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -195,6 +195,7 @@ import (
"github.com/carlosframework/platform/internal/hadeparture"
"github.com/carlosframework/platform/internal/hafresh"
"github.com/carlosframework/platform/internal/hairpin"
+ "github.com/carlosframework/platform/internal/hostenv"
"github.com/carlosframework/platform/internal/hostwrite"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/instancefs"
@@ -234,14 +235,20 @@ func dataDir() string {
// account or region IMDS did not answer within 2 seconds is asked for
// again every minute.
func RunAgent(args []string) {
- groupBoot, err := loadGroupConfiguration(os.Getenv)
+ // Managed fleets 2b-2: the one managed/BYO decision, before any fatal
+ // group preflight (decideAgentStartup). BYO: the group validation and
+ // its fatal exits exactly as before.
+ startup, err := decideAgentStartup("/", hostenv.GroupConfigPath, os.Getenv, instancectl.NewClient(controlsock.Path), log.Printf)
if err != nil {
log.Fatal(err)
}
+ armedAgentStartup.Store(&startup)
+ groupBoot := startup.groupBoot
+ entryEnv := os.Getenv
+ if startup.join != nil {
+ entryEnv = managedEntryEnv(os.Getenv)
+ }
if groupBoot != nil {
- if _, _, _, err = groupBootEvidence(*groupBoot); err != nil {
- log.Fatal(err)
- }
groupRef.Lock()
groupRef.ref = groupReferenceOf(groupBoot.Account, groupBoot.InstanceID)
groupRef.Unlock()
@@ -255,7 +262,7 @@ func RunAgent(args []string) {
}
return self
}
- agentEntry(os.Getenv, resolveGroupBoxReference, groupReferenceBackoff, log.Printf, identity, func() {
+ agentEntry(entryEnv, resolveGroupBoxReference, groupReferenceBackoff, log.Printf, identity, func() {
startHASelfRetry(context.Background(), self, os.Getenv, haIMDSClient, time.Minute, lease.SetSelf)
runAgent(args, productionClaimFactory)
})
@@ -264,17 +271,29 @@ func RunAgent(args []string) {
func runAgent(args []string, buildClaims ClaimFactory) {
agentCtx, cancelAgent := context.WithCancel(context.Background())
defer cancelAgent()
- groupBoot, err := loadGroupConfiguration(os.Getenv)
- if err != nil {
- log.Fatal(err)
+ // Managed fleets 2b-2: RunAgent's managed/BYO decision, made before any
+ // fatal group preflight and before any admission is armed. A managed box
+ // takes tenant admission from root alone (managedJoin), never reads
+ // group configuration and never builds fixed group admission; an
+ // identity that fails its checks or any group configuration is a refused
+ // join (every admission predicate closed, the agent and edge running).
+ // BYO: the group configuration is read and validated exactly as on main.
+ startup := armedAgentStartup.Load()
+ if startup == nil {
+ s, err := decideAgentStartup("/", hostenv.GroupConfigPath, os.Getenv, instancectl.NewClient(controlsock.Path), log.Printf)
+ if err != nil {
+ log.Fatal(err)
+ }
+ startup = &s
+ }
+ join := startup.join
+ var groupBoot *hostenv.GroupConfig
+ var err error
+ if join == nil {
+ if groupBoot, err = loadGroupConfiguration(os.Getenv); err != nil {
+ log.Fatal(err)
+ }
}
- // Managed fleets 2b-2, decided before any admission is armed: a managed
- // box takes tenant admission from root alone (managedJoin) and never
- // builds fixed group admission. An identity that fails its checks, or
- // group admission configured on a managed box, is a refused join: every
- // admission predicate closed, the agent and edge still running. nil on a
- // BYO box, where everything below is as on main.
- join := armManagedJoin("/", instancectl.NewClient(controlsock.Path), os.Getenv, groupBoot != nil, log.Printf)
var admission *fixedAdmission
if join == nil {
admission = newFixedAdmission(os.Getenv, lbhealth.Default)
diff --git a/internal/host/group_names_test.go b/internal/host/group_names_test.go
index d6fefe7a8..9d1ccacb1 100644
--- a/internal/host/group_names_test.go
+++ b/internal/host/group_names_test.go
@@ -424,11 +424,14 @@ var groupNameProducerInventory = map[string]string{
// Demo protections wrap existing proxies and retain refusal-only names.
// They do not derive or publish a new group-name class. The site demo API
// proxy is built over an existing exact console row and publishes no name.
- "../edge/edge.go:*Edge.Reload": "9df3a40130a4c26edc728e67e4cec2788ea8be1fe28eb495013bfeba1154f3e0",
- "../edge/platformalias.go:PlatformAliasFold": "a18e4963cf88320ef3fb94b666b02838dc12cc3e9b2df3f2cbe2576ca682735f",
- "../edge/regional.go:*Edge.foldRegional": "2c52d0d9147ab4b426649a78573a8550e0ba1073e2f5e5ef10e894f2570e9a8d",
- "../provision/forward.go:forwardRowFor": "e7294d6a3c96e51646257200f5cedb26aaf491afea23be3d943b3e3f742c4db4",
- "../provision/reconcile.go:Reconcile": "b2bc85f6ea8218fe4114a2847c7f4b828daa28181562f104bd5023179c03b9d0",
+ "../edge/edge.go:*Edge.Reload": "9df3a40130a4c26edc728e67e4cec2788ea8be1fe28eb495013bfeba1154f3e0",
+ "../edge/platformalias.go:PlatformAliasFold": "a18e4963cf88320ef3fb94b666b02838dc12cc3e9b2df3f2cbe2576ca682735f",
+ "../edge/regional.go:*Edge.foldRegional": "2c52d0d9147ab4b426649a78573a8550e0ba1073e2f5e5ef10e894f2570e9a8d",
+ "../provision/forward.go:forwardRowFor": "e7294d6a3c96e51646257200f5cedb26aaf491afea23be3d943b3e3f742c4db4",
+ // Managed fleets 2b-2 Task 3: Reconcile and ReconcileSidecars return
+ // before any list, mint or removal while ReconcileConfig.Joining is true;
+ // no name class is added or changed (a joining box produces none).
+ "../provision/reconcile.go:Reconcile": "8e5c07b77c83cbea869a773d6cf1557fcd7314f66d54ff68e84e8c5df1d0237d",
"../provision/reconcile.go:RouteFor": "304e92d9123c1cc7d756319756c4311ee235266cd6b2290f058c91e45fbe0cc1",
"../provision/reconcile.go:mintHeld": "9fe4ad876c727af36cc06bd0105baf344748c61e6f21ced48e5288a323851344",
"../provision/seedreconcile.go:purgeAbortedFromLocal": "889e93e6fbd74adf614ba184bcd2f554196eccc4506829c65326a3502e98d89a",
@@ -436,7 +439,7 @@ var groupNameProducerInventory = map[string]string{
// B6 retains the synthetic sidecar name and Kind. HA affects lifetime and
// nested DB paths only; TestSidecarNeverAdvertisedOrDialled exercises the
// real stamped record/reconcile/publication path as well as the legacy row.
- "../provision/sidecar_reconcile.go:ReconcileSidecars": "d656cff0e545d332ddb8282e464896f949f05cadaa29533c1ae58e556c998f21",
+ "../provision/sidecar_reconcile.go:ReconcileSidecars": "b01db9dbfa566953f93e29247e648e850d63c357b04be5f584ba31911d8c6fb1",
"../provision/sidecar_reconcile.go:sidecarRouteFor": "c8cc26bdb7a0aff550219b1c095fd0289392620465b659cd29e5ef4e7895028a",
"claimretire_transport.go:ClaimRootHTTP.retire": "a60c74d0e0461e0a432f9a338aa25799cc0cd9d163c7b6eb803cfb33d55d7c2a",
"claimunit_binding.go:claimUnitShape.route": "f38fd6e10aba680354ee908c255fd34e731fe2d1a22fffd41ac449e8b763dd2c",
diff --git a/internal/host/managedjoin.go b/internal/host/managedjoin.go
index c6633177b..9270041aa 100644
--- a/internal/host/managedjoin.go
+++ b/internal/host/managedjoin.go
@@ -122,17 +122,6 @@ func newManagedJoinAt(root string, door managedAdmissionDoor, logf func(string,
return j
}
-// armManagedJoin is runAgent's decision, before any admission is armed: a
-// managed box gets a join and never fixed group admission; group
-// admission or group configuration on a managed box refuses the join.
-func armManagedJoin(root string, door managedAdmissionDoor, getenv func(string) string, groupConfigured bool, logf func(string, ...any)) *managedJoin {
- j := newManagedJoinAt(root, door, logf)
- if j != nil && (getenv("CARLOS_GROUP_ADMISSION") == "1" || groupConfigured) {
- j.refuse(errManagedGroupAdmission.Error())
- }
- return j
-}
-
func (j *managedJoin) refuse(why string) {
j.refused, j.refusedWhy = true, why
j.logf("agent: ERROR managed box admission refused: %s. tenant work stays closed; status, probes and updates keep running", why)
diff --git a/internal/host/managedjoin_fix1_test.go b/internal/host/managedjoin_fix1_test.go
index db8396765..8bcfa6ba7 100644
--- a/internal/host/managedjoin_fix1_test.go
+++ b/internal/host/managedjoin_fix1_test.go
@@ -7,6 +7,7 @@ import (
"errors"
"net/http"
"net/http/httptest"
+ "os"
"path/filepath"
"strings"
"testing"
@@ -17,6 +18,7 @@ import (
"github.com/carlosframework/platform/internal/managedboot"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
)
// TestManagedJoinRootFirst (Astra R1 P1-1): a ready.json GET happens only
@@ -134,29 +136,50 @@ func TestManagedJoinRefused(t *testing.T) {
t.Fatal("a refused join ran the admit callback")
}
}
- for name, env := range map[string]string{"group admission": "1"} {
+ env := func(kv ...string) func(string) string {
+ return func(k string) string {
+ for i := 0; i+1 < len(kv); i += 2 {
+ if kv[i] == k {
+ return kv[i+1]
+ }
+ }
+ return ""
+ }
+ }
+ absent := func(t *testing.T) string { return filepath.Join(t.TempDir(), "group.json") }
+ invalid := func(t *testing.T) string {
+ p := filepath.Join(t.TempDir(), "group.json")
+ writeFileT(t, p, "{not a group marker")
+ return p
+ }
+ // Through the production entry decision (decideAgentStartup), never an
+ // error and never a group read on a managed box.
+ cases := map[string]struct {
+ getenv func(string) string
+ marker func(t *testing.T) string
+ }{
+ "group admission": {env("CARLOS_GROUP_ADMISSION", "1"), absent},
+ "group reference with missing marker": {env("CARLOS_BOX_REFERENCE", "group"), absent},
+ "invalid marker": {env(), invalid},
+ "group reference with invalid marker": {env("CARLOS_BOX_REFERENCE", "group", "CARLOS_GROUP_ADMISSION", "1"), invalid},
+ }
+ for name, tc := range cases {
t.Run(name+" over an admitted root", func(t *testing.T) {
f := newJoinFixture(t)
f.publish(t, f.m.Wire(t))
if err := f.m.Commit(f.m.Wire(t)); err != nil {
t.Fatal(err)
}
- j := armManagedJoin(f.m.Root, f.door, func(k string) string {
- if k == "CARLOS_GROUP_ADMISSION" {
- return env
- }
- return ""
- }, false, f.logf)
- check(t, j, f)
+ st, err := decideAgentStartup(f.m.Root, tc.marker(t), tc.getenv, f.door, f.logf)
+ if err != nil || st.groupBoot != nil {
+ t.Fatalf("managed box: startup error %v group %v (the agent would exit)", err, st.groupBoot)
+ }
+ check(t, st.join, f)
if !strings.Contains(f.logs.String(), "admission refused") {
t.Fatalf("refusal not logged: %s", f.logs)
}
})
}
- t.Run("group configuration", func(t *testing.T) {
- f := newJoinFixture(t)
- check(t, armManagedJoin(f.m.Root, f.door, func(string) string { return "" }, true, f.logf), f)
- })
t.Run("identity with an error", func(t *testing.T) {
root := t.TempDir()
prev := managedIdentityAt
@@ -165,10 +188,70 @@ func TestManagedJoinRefused(t *testing.T) {
}
defer func() { managedIdentityAt = prev }()
// A nil door: a refused join never asks root.
- check(t, armManagedJoin(root, nil, func(string) string { return "" }, false, t.Logf), nil)
+ st, err := decideAgentStartup(root, invalid(t), env("CARLOS_BOX_REFERENCE", "group"), nil, t.Logf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ check(t, st.join, nil)
+ })
+ t.Run("managed without group configuration is not refused", func(t *testing.T) {
+ f := newJoinFixture(t)
+ st, err := decideAgentStartup(f.m.Root, absent(t), env(), f.door, f.logf)
+ if err != nil || st.join == nil || st.join.refused || st.groupBoot != nil {
+ t.Fatalf("%+v %v", st, err)
+ }
+ })
+ t.Run("the managed entry never waits for a group reference", func(t *testing.T) {
+ if managedEntryEnv(env("CARLOS_BOX_REFERENCE", "group"))("CARLOS_BOX_REFERENCE") != "" || groupReferenced(managedEntryEnv(env("CARLOS_BOX_REFERENCE", "group"))) {
+ t.Fatal("the managed entry still sees the group reference")
+ }
})
}
+// TestAgentStartupBYOUnchanged (Astra R2 P2-2 guard): a BYO box's startup
+// decision is the existing group preflight exactly: the same errors (which
+// RunAgent treats as fatal) and the same configuration, and no join.
+func TestAgentStartupBYOUnchanged(t *testing.T) {
+ root := t.TempDir() // no identity: BYO
+ env := func(kv ...string) func(string) string {
+ return func(k string) string {
+ for i := 0; i+1 < len(kv); i += 2 {
+ if kv[i] == k {
+ return kv[i+1]
+ }
+ }
+ return ""
+ }
+ }
+ missing := filepath.Join(t.TempDir(), "group.json")
+ bad := filepath.Join(t.TempDir(), "group.json")
+ writeFileT(t, bad, "{not a group marker")
+ for name, tc := range map[string]struct {
+ getenv func(string) string
+ marker string
+ }{
+ "group reference, missing marker": {env("CARLOS_BOX_REFERENCE", "group"), missing},
+ "invalid marker": {env(), bad},
+ "group admission without HA": {env("CARLOS_BOX_REFERENCE", "group", "CARLOS_GROUP_ADMISSION", "1"), missing},
+ "no group configuration": {env(), missing},
+ } {
+ t.Run(name, func(t *testing.T) {
+ door := &fakeRootDoor{}
+ st, err := decideAgentStartup(root, tc.marker, tc.getenv, door, t.Logf)
+ g, want := loadGroupConfigurationAt(tc.getenv, tc.marker)
+ if st.join != nil || door.asks.Load() != 0 {
+ t.Fatal("a BYO box got a managed join")
+ }
+ if (err == nil) != (want == nil) || (err != nil && err.Error() != want.Error()) {
+ t.Fatalf("BYO preflight changed: got %v, main's %v", err, want)
+ }
+ if err == nil && (st.groupBoot == nil) != (g == nil) {
+ t.Fatalf("BYO group configuration changed: %v vs %v", st.groupBoot, g)
+ }
+ })
+ }
+}
+
// TestManagedJoinWhenAdmittedOnce (Astra R1 P3-1): the boot-pass callback
// runs exactly once, whether admission lands before or after it is
// registered, or races the registration.
@@ -282,3 +365,35 @@ func TestManagedNamedRecoveryGate(t *testing.T) {
t.Fatal("root doubt did not refuse")
}
}
+
+// TestManagedNamedRecoveryPassOption (Astra R2 P2-3): the root pass's
+// named-unit recovery, driven through passOption inside release.Pass, does
+// no recovery work while the managed box is joining and repairs the unit
+// once root has admitted it.
+func TestManagedNamedRecoveryPassOption(t *testing.T) {
+ e, u, c, source, pub := signedRecoveryFixture(t)
+ rt, err := e.root.reg.Get(observedHost)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.history = func() (*release.RootHistoryPass, error) { return nil, os.ErrPermission }
+ f := newJoinFixture(t)
+ n := namedUnitRecovery{source: source, pub: pub, readLive: os.Readlink, gate: managedRootGateWith(f.m.Admission)}
+ pass := func() error {
+ return release.Pass(t.Context(), e.root.reg, e.store, pub, u.opt, nil,
+ release.WithRootHistory(nil), n.passOption(e.root.reg, c, func(string) string { return "5s" }))
+ }
+ _ = pass()
+ if len(u.effects) != 0 {
+ t.Fatalf("joining box: named-unit recovery ran: %v", u.effects)
+ }
+ if live, err := release.LiveVersion(u.opt, rt.Host); err != nil || live != "v1" {
+ t.Fatalf("joining box: live link moved to %s (%v)", live, err)
+ }
+ if err := f.m.Commit(f.m.Wire(t)); err != nil {
+ t.Fatal(err)
+ }
+ if err := pass(); err != nil || len(u.effects) != 1 || u.exe != release.VersionPath(u.opt, rt.Account, "v2", rt.App) {
+ t.Fatalf("admitted box: recovery did not repair the unit: effects=%v exe=%s err=%v", u.effects, u.exe, err)
+ }
+}
diff --git a/internal/host/managedstartup.go b/internal/host/managedstartup.go
new file mode 100644
index 000000000..176f482c3
--- /dev/null
+++ b/internal/host/managedstartup.go
@@ -0,0 +1,79 @@
+package host
+
+import (
+ "errors"
+ "io/fs"
+ "os"
+ "strings"
+ "sync/atomic"
+
+ "github.com/carlosframework/platform/internal/hostenv"
+)
+
+// agentStartup is RunAgent's one managed/BYO decision (Astra R2 P2-2),
+// made at the entry before any fatal group preflight. A managed box has a
+// join and never reads group configuration: any group configuration on it
+// (a marker present or uninspectable, CARLOS_BOX_REFERENCE=group,
+// CARLOS_GROUP_ADMISSION=1) is the refused path, so the edge, status and
+// probes stay up with every admission predicate closed. A BYO box keeps
+// the existing group validation and its fatal behaviour exactly.
+type agentStartup struct {
+ join *managedJoin // nil: BYO
+ groupBoot *hostenv.GroupConfig // BYO only
+}
+
+// armedAgentStartup carries RunAgent's decision into runAgent.
+var armedAgentStartup atomic.Pointer[agentStartup]
+
+// decideAgentStartup is that decision for the box at root, with the group
+// marker at marker. An error is BYO group preflight's, which the caller
+// treats as fatal exactly as before; a managed box never returns one.
+func decideAgentStartup(root, marker string, getenv func(string) string, door managedAdmissionDoor, logf func(string, ...any)) (agentStartup, error) {
+ if j := newManagedJoinAt(root, door, logf); j != nil {
+ if why := managedGroupConfiguration(getenv, marker); why != "" {
+ j.refuse(why)
+ }
+ return agentStartup{join: j}, nil
+ }
+ g, err := loadGroupConfigurationAt(getenv, marker)
+ if err != nil {
+ return agentStartup{}, err
+ }
+ if g != nil {
+ if _, _, _, err = groupBootEvidence(*g); err != nil {
+ return agentStartup{}, err
+ }
+ }
+ return agentStartup{groupBoot: g}, nil
+}
+
+// managedGroupConfiguration names the group configuration a managed box
+// carries, or "" for none. Nothing is parsed: on a managed box any of it
+// is refused, never validated.
+func managedGroupConfiguration(getenv func(string) string, marker string) string {
+ var found []string
+ if _, err := os.Lstat(marker); !errors.Is(err, fs.ErrNotExist) {
+ found = append(found, "a group marker at "+marker)
+ }
+ if groupReferenced(getenv) {
+ found = append(found, hostenv.BoxReference+"="+hostenv.GroupReference)
+ }
+ if getenv("CARLOS_GROUP_ADMISSION") == "1" {
+ found = append(found, "CARLOS_GROUP_ADMISSION=1")
+ }
+ if len(found) == 0 {
+ return ""
+ }
+ return "this managed box carries group configuration (" + strings.Join(found, ", ") + "), which managed boxes do not support. remove it from host.env and /etc/carlos"
+}
+
+// managedEntryEnv hides the group box reference from the agent entry on a
+// managed box, which never waits for a group reference to resolve.
+func managedEntryEnv(getenv func(string) string) func(string) string {
+ return func(k string) string {
+ if k == hostenv.BoxReference {
+ return ""
+ }
+ return getenv(k)
+ }
+}
diff --git a/internal/host/managedunits.go b/internal/host/managedunits.go
index e28cf6386..3bc2832a8 100644
--- a/internal/host/managedunits.go
+++ b/internal/host/managedunits.go
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io/fs"
+ "os"
"path/filepath"
"github.com/carlosframework/platform/internal/appconfig"
@@ -34,6 +35,15 @@ const (
// managedRootOf is the filesystem root an etc directory belongs to.
func managedRootOf(etcDir string) string { return filepath.Dir(filepath.Clean(etcDir)) }
+// managedEtcRoot reports whether etcDir is a valid managed box's /etc.
+func managedEtcRoot(etcDir string) (bool, error) {
+ if filepath.Base(filepath.Clean(etcDir)) != "etc" {
+ return false, nil
+ }
+ _, managed, err := managedIdentityAt(managedRootOf(etcDir))
+ return managed && err == nil, err
+}
+
// managedGateEtc is managedGateUnits for a publisher that writes under
// etcDir: the drop-ins land in <root>/etc/systemd/system, so an etcDir that
// is not <root>/etc on a managed box is refused rather than gated elsewhere.
@@ -64,7 +74,7 @@ func managedGateUnits(root string, units, extraNamed []string, reload func() err
if err != nil {
return false, fmt.Errorf("managed box identity is unreadable, so no unit is published: %w", err)
}
- _, control, err = managedGateUnitsKnown(root, managedUnitUID, units, extraNamed, reload)
+ _, control, err = managedGateUnitsOwing(root, managedUnitUID, units, extraNamed, reload, true)
return control, err
}
@@ -73,6 +83,21 @@ func managedGateUnits(root string, units, extraNamed []string, reload func() err
// changed says any drop-in was written; control that the control
// service's was. reload, when not nil, always runs last.
func managedGateUnitsKnown(root string, uid int, units, extraNamed []string, reload func() error) (changed, control bool, err error) {
+ return managedGateUnitsOwing(root, uid, units, extraNamed, reload, false)
+}
+
+// managedControlRestartOwed records, in root's /run, that the running
+// instance-control process predates a rewritten control drop-in and owes a
+// restart (Astra R2 P2-1). Written before the drop-in is rewritten and
+// removed only after a try-restart succeeds after a successful reload, so a
+// failed reload or restart cannot lose it; a reboot starts the service
+// fresh with the drop-in, which is why /run is the right place.
+const managedControlRestartOwed = "/run/carlos-managed-control-restart"
+
+// managedGateUnitsOwing is the gate; owe records an owed control restart
+// before the control drop-in is rewritten (every publisher but managed
+// boot, which runs before the control service can be up).
+func managedGateUnitsOwing(root string, uid int, units, extraNamed []string, reload func() error, owe bool) (changed, control bool, err error) {
named, err := managedDeclaredUnits(root, uid)
if err != nil {
return false, false, err
@@ -88,6 +113,11 @@ func managedGateUnitsKnown(root string, uid int, units, extraNamed []string, rel
}
changed = changed || c
}
+ if owe && !managedDropInExact(root, uid, managedboot.ControlUnit, managedboot.ControlDropInName, managedboot.ControlDropIn) {
+ if err = mbWriteRootFile(root, managedControlRestartOwed, []byte("owed\n"), 0o600, uid, -1); err != nil {
+ return changed, false, fmt.Errorf("managed admission drop-ins: record the owed control restart: %w", err)
+ }
+ }
if control, err = managedEnsureDropIn(root, uid, managedboot.ControlUnit, managedboot.ControlDropInName, managedboot.ControlDropIn); err != nil {
return changed, false, err
}
@@ -126,7 +156,7 @@ func managedEnsureDropIn(root string, uid int, unit, name, body string) (bool, e
return false, fmt.Errorf("managed admission drop-in %s: %w", unit, err)
}
path := filepath.Join(dir, name)
- if got, err := mbReadRootFile(root, path, uid, 4096, managedDropInMode); err == nil && bytes.Equal(got, []byte(body)) {
+ if managedDropInExact(root, uid, unit, name, body) {
return false, nil
}
if err := mbWriteRootFile(root, path, []byte(body), managedDropInMode, uid, -1); err != nil {
@@ -150,3 +180,29 @@ func managedNamedUnitDropIns(raw []byte, reload func() error) error {
_, err = managedGateUnits(namedUnitRoot, own, units, reload)
return err
}
+
+// managedDropInExact reports whether <unit>.d/<name> is already the exact,
+// trusted (root-owned chain, single link, 0644) file.
+func managedDropInExact(root string, uid int, unit, name, body string) bool {
+ got, err := mbReadRootFile(root, filepath.Join(mbUnitDir, unit+".d", name), uid, 4096, managedDropInMode)
+ return err == nil && bytes.Equal(got, []byte(body))
+}
+
+// managedSettleControlRestart pays an owed control restart: only after the
+// gate's reload succeeded, try-restart the control service and clear the
+// record once that succeeds. A failure keeps the record for the next pass.
+func managedSettleControlRestart(root string, uid int, tryRestart func() error) error {
+ if _, err := mbReadRootFile(root, managedControlRestartOwed, uid, 64, 0o600); err != nil {
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil
+ }
+ return fmt.Errorf("owed control restart record: %w", err)
+ }
+ if err := tryRestart(); err != nil {
+ return fmt.Errorf("try-restart %s (still owed): %w", managedboot.ControlUnit, err)
+ }
+ if err := os.Remove(filepath.Join(root, managedControlRestartOwed)); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return err
+ }
+ return nil
+}
diff --git a/internal/host/managedunits_fix1_test.go b/internal/host/managedunits_fix1_test.go
index ea1852a3b..96f95a00a 100644
--- a/internal/host/managedunits_fix1_test.go
+++ b/internal/host/managedunits_fix1_test.go
@@ -22,6 +22,7 @@ func managedApplyFixture(t *testing.T, staged ...string) (*applyFixture, string,
root := t.TempDir()
f.a.etcDir = filepath.Join(root, "etc")
writeFileT(t, filepath.Join(f.a.etcDir, "systemd/system/.keep"), "")
+ writeFileT(t, filepath.Join(root, "run/.keep"), "")
stubManagedIdentity(t, root)
stage := t.TempDir()
writeFileT(t, filepath.Join(stage, "etc/tmpfiles.d/carlos.conf"), "d /run/carlos\n")
@@ -315,3 +316,65 @@ func TestManagedDeclaredScope(t *testing.T) {
}
}
}
+
+// TestManagedControlRestartOwed (Astra R2 P2-1): a rewritten control
+// drop-in owes the running control service a restart until a try-restart
+// succeeds after a successful reload; a failed reload or a failed restart
+// keeps it owed for the next pass.
+func TestManagedControlRestartOwed(t *testing.T) {
+ probe := func(...string) (string, error) { return "active", nil }
+ run := func(t *testing.T, etc string, failReload, failRestart bool) []string {
+ t.Helper()
+ var calls []string
+ ensureSystemUnits(etc, filepath.Join(t.TempDir(), "lock"), func(args ...string) (string, error) {
+ calls = append(calls, strings.Join(args, " "))
+ switch {
+ case args[0] == "daemon-reload" && failReload:
+ return "", errors.New("daemon-reload failed")
+ case args[0] == "try-restart" && failRestart:
+ return "", errors.New("try-restart failed")
+ }
+ return "", nil
+ }, probe, t.Logf)
+ return calls
+ }
+ restarted := func(calls []string) bool {
+ return slices.Contains(calls, "try-restart "+managedboot.ControlUnit)
+ }
+ for name, first := range map[string][2]bool{"failed reload": {true, false}, "failed restart": {false, true}} {
+ t.Run(name+" then success", func(t *testing.T) {
+ tree, etc := managedTree(t)
+ owed := filepath.Join(tree.root, managedControlRestartOwed)
+ _ = os.Remove(filepath.Join(etc, "systemd/system", managedboot.ControlUnit+".d", managedboot.ControlDropInName))
+ calls := run(t, etc, first[0], first[1])
+ if first[0] && restarted(calls) {
+ t.Fatal("restarted the control service after a failed reload")
+ }
+ if _, err := os.Stat(owed); err != nil {
+ t.Fatalf("the owed restart was not kept after a %s: %v", name, err)
+ }
+ calls = run(t, etc, false, false)
+ if !restarted(calls) {
+ t.Fatalf("the owed control restart was lost: %v", calls)
+ }
+ if _, err := os.Stat(owed); err == nil {
+ t.Fatal("the owed restart was not cleared after it succeeded")
+ }
+ if calls = run(t, etc, false, false); restarted(calls) {
+ t.Fatalf("a settled control service was restarted again: %v", calls)
+ }
+ })
+ }
+ t.Run("owed before the drop-in is rewritten", func(t *testing.T) {
+ tree, etc := managedTree(t)
+ _ = os.Remove(filepath.Join(etc, "systemd/system", managedboot.ControlUnit+".d", managedboot.ControlDropInName))
+ own, _ := unitNames()
+ // The gate fails after recording: the reload never runs.
+ if _, err := managedGateUnits(tree.root, own, nil, func() error { return errors.New("reload failed") }); err == nil {
+ t.Fatal("no error")
+ }
+ if _, err := os.Stat(filepath.Join(tree.root, managedControlRestartOwed)); err != nil {
+ t.Fatal("the control drop-in was rewritten without recording the owed restart")
+ }
+ })
+}
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go
index 48484bc4c..add6d42b0 100644
--- a/internal/host/systemunits.go
+++ b/internal/host/systemunits.go
@@ -110,15 +110,20 @@ func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(a
if own, err := unitNames(); err != nil {
logf("adopt: system units: %v", err)
return
- } else if control, err := managedGateEtc(etcDir, own, func() error {
+ } else if _, err := managedGateEtc(etcDir, own, func() error {
_, err := systemctl("daemon-reload")
return err
}); err != nil {
logf("adopt: managed admission drop-ins: %v; no unit published this pass", err)
return
- } else if control {
- if _, err := systemctl("try-restart", managedboot.ControlUnit); err != nil {
- logf("adopt: managed admission drop-ins: try-restart %s: %v", managedboot.ControlUnit, err)
+ } else if managed, _ := managedEtcRoot(etcDir); managed {
+ // After a successful reload: pay a control restart a rewritten
+ // control drop-in owes, this pass or an earlier one that failed.
+ if err := managedSettleControlRestart(managedRootOf(etcDir), managedUnitUID, func() error {
+ _, err := systemctl("try-restart", managedboot.ControlUnit)
+ return err
+ }); err != nil {
+ logf("adopt: managed admission drop-ins: %v", err)
}
}