carlos / platform Public

Merge branch 'region-ha-p3b-t4' into region-ha-p3b-build

Paul Campbell pushed by claude agent, operated by paul@keymail.dev 1e248348dd987ca4e04f1bb7f574898bb446a2d7 parent 609fde2parent ac2e46e
11 files changed, +1,498 −16
  • internal/host/agent.go +10 −8
  • internal/host/bootstrap.go +27 −3
  • internal/host/group_maintenance.go +347 −0
  • internal/host/group_maintenance_linux.go +49 −0
  • internal/host/group_maintenance_other.go +7 −0
  • internal/host/group_maintenance_protocol_test.go +442 −0
  • internal/host/group_maintenance_test.go +475 −0
  • internal/host/installchannel.go +7 −0
  • internal/host/systemapply.go +93 −5
  • internal/host/systemleg.go +3 −0
  • internal/host/systemunits.go +38 −0
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 1d2a4ed19..04fa1c6d7 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -3480,14 +3480,16 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu
// in a loop of its own because the spread deadline needs a seconds
// cadence to run down on, and this is the loop that already has one.
d.systemLeg = newSystemLeg(store, pub, os.Getenv, dd, optDir)
- d.systemLeg.readers = cachedGroupReaders
- // One observe at arming, on restartSeed's precedent: the leg below only
- // re-observes on a serial move or at its hourly floor, so a box that
- // (re)starts under an already-promoted pointer would otherwise sit on the
- // old build for up to an hour with nobody to bump the serial. observe
- // handles "no pointer" itself, which is every deployment before its first
- // `carlos system update`.
- d.systemLeg.observe(ctx)
+ if d.systemLeg != nil {
+ d.systemLeg.readers = cachedGroupReaders
+ // One observe at arming, on restartSeed's precedent: the leg below only
+ // re-observes on a serial move or at its hourly floor, so a box that
+ // (re)starts under an already-promoted pointer would otherwise sit on the
+ // old build for up to an hour with nobody to bump the serial. observe
+ // handles "no pointer" itself, which is every deployment before its first
+ // `carlos system update`.
+ d.systemLeg.observe(ctx)
+ }
log.Printf("agent: fast converge loop armed (2s + jitter: serial poll + canary/* + unstaged routes + system pointer)")
for {
time.Sleep(fastTickEvery + rand.N(time.Second))
diff --git a/internal/host/bootstrap.go b/internal/host/bootstrap.go
index 5c8b5eaad..5a2d87550 100644
--- a/internal/host/bootstrap.go
+++ b/internal/host/bootstrap.go
@@ -337,7 +337,7 @@ func RunBootstrap(args []string) {
if err := bootstrapWith(*root, consumers, *planJSON); err != nil {
log.Fatalf("bootstrap: %v", err)
}
- if group != nil {
+ if group != nil && !groupInstallationConsumed("/etc") {
if err := initializeGroupLaunch(*group); err != nil {
log.Fatal(err)
}
@@ -394,6 +394,14 @@ func bootstrap(root string, consumers []string) error {
// plan currentBootstrapPlan() prints is alone on stdout.
func bootstrapWith(root string, consumers []string, planJSON bool) error {
live := filepath.Clean(root) == "/"
+ group := live && groupMarkerPresent("/etc")
+ if group {
+ unlock, err := guardGroupBootstrap()
+ if err != nil {
+ return err
+ }
+ defer unlock()
+ }
hostEnv := filepath.Join(root, "etc", "carlos", "host.env")
if live {
hostEnv = claimBootstrapHostEnv
@@ -540,6 +548,9 @@ func bootstrapWith(root string, consumers []string, planJSON bool) error {
return err
}
for _, name := range names {
+ if group && groupAutomaticUnit(name) {
+ continue
+ }
content, err := unitsFS.ReadFile("units/" + name)
if err != nil {
return fmt.Errorf("read embedded unit %s: %v", name, err)
@@ -612,7 +623,16 @@ func bootstrapWith(root string, consumers []string, planJSON bool) error {
fmt.Fprintf(out, " wrote %s\n", journaldPath)
tmpfilesPath := filepath.Join(root, "etc", "tmpfiles.d", "carlos.conf")
- if err := os.WriteFile(tmpfilesPath, []byte(tmpfilesConf), 0o644); err != nil {
+ conf := tmpfilesConf
+ if group {
+ if err := writeFileDurable(filepath.Join(root, "etc/tmpfiles.d/carlos-group-maintenance.conf"), []byte("d /run/carlos-group-maintenance 0700 root root -\n"), 0644); err != nil {
+ return err
+ }
+ if err := preserveGroupUnits("/etc"); err != nil {
+ return err
+ }
+ }
+ if err := os.WriteFile(tmpfilesPath, []byte(conf), 0o644); err != nil {
return fmt.Errorf("write %s: %v", tmpfilesPath, err)
}
fmt.Fprintf(out, " wrote %s\n", tmpfilesPath)
@@ -645,7 +665,11 @@ func bootstrapWith(root string, consumers []string, planJSON bool) error {
if out, err := exec.Command(tmpfilesApply[0], tmpfilesApply[1:]...).CombinedOutput(); err != nil {
return fmt.Errorf("%s: %v: %s", strings.Join(tmpfilesApply, " "), err, strings.TrimSpace(string(out)))
}
- for _, args := range systemctlPlan(enabledUnits) {
+ toEnable := enabledUnits
+ if group {
+ toEnable = groupManualUnits(toEnable)
+ }
+ for _, args := range systemctlPlan(toEnable) {
if err := systemctl(args...); err != nil {
return err
}
diff --git a/internal/host/group_maintenance.go b/internal/host/group_maintenance.go
new file mode 100644
index 000000000..21079bfbb
--- /dev/null
+++ b/internal/host/group_maintenance.go
@@ -0,0 +1,347 @@
+package host
+
+import (
+ "bytes"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "regexp"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hostenv"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const groupMaintenanceDir = "/run/carlos-group-maintenance"
+const groupInstallUsed = "group-install-used"
+
+var errGroupMaintenance = errors.New("group_maintenance_required")
+var groupTransactionID = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,80}$`)
+
+// Only the deployment operator writes permits, over Session Manager after
+// exact Standby and both target-group deregistration readbacks. Root cannot
+// establish those cloud facts locally. The receipt is never an authority input.
+type groupMaintenancePermit struct {
+ V int `json:"v"`
+ Account string `json:"account"`
+ Region string `json:"region"`
+ Group string `json:"group"`
+ Instance string `json:"iid"`
+ BootID string `json:"boot_id"`
+ ConfigDigest string `json:"config_digest"`
+ Transaction string `json:"transaction"`
+ Phase string `json:"phase"`
+ Action string `json:"action"`
+ OldSHA256 string `json:"old_sha256"`
+ NewSHA256 string `json:"new_sha256"`
+ Expires int64 `json:"expires"`
+ AllowRollback bool `json:"allow_rollback"`
+}
+
+type groupMaintenance struct {
+ dir string
+ owner int
+ bootID func() string
+ read func(string, int, os.FileMode) ([]byte, error)
+ permit *groupMaintenancePermit
+ used map[string]bool
+ initial bool
+}
+
+func (a *systemApplier) maintenance() *groupMaintenance {
+ if a.groupMaintenance == nil {
+ a.groupMaintenance = &groupMaintenance{dir: groupMaintenanceDir, read: hostenv.ReadGroupFile, bootID: func() string { return readBootID(bootIDPath) }}
+ }
+ return a.groupMaintenance
+}
+
+// Lstat first preserves fixed-box behavior in staging trees. Any present or
+// unreadable marker requires the strict reader; a flag cannot turn it off.
+func groupMarkerPresent(etc string) bool {
+ _, err := os.Lstat(filepath.Join(etc, "carlos", "group.json"))
+ return !errors.Is(err, os.ErrNotExist)
+}
+func (a *systemApplier) maintenanceConfig() (*hostenv.GroupConfig, error) {
+ if !groupMarkerPresent(a.etcDir) {
+ return nil, nil
+ }
+ g := a.maintenance()
+ b, err := g.read(filepath.Join(a.etcDir, "carlos", "group.json"), g.owner, 0644)
+ if err != nil {
+ return nil, errors.Join(errGroupMaintenance, err)
+ }
+ c, err := hostenv.ParseGroupConfig(b)
+ if err != nil || c.BootID != g.bootID() {
+ return nil, errGroupMaintenance
+ }
+ return &c, nil
+}
+func groupDigest(s string) bool {
+ b, err := hex.DecodeString(s)
+ return err == nil && len(b) == 32 && hex.EncodeToString(b) == s
+}
+
+// Called under the apply lock before mutation. Each process consumes an action
+// once, durably, before its first side effect. A crash requires a new operator
+// decision; changing phases or replaying the same permit cannot replay it.
+func (a *systemApplier) requireGroupMaintenance(action string) error {
+ c, err := a.maintenanceConfig()
+ if err != nil || c == nil {
+ return err
+ }
+ g := a.maintenance()
+ if err := checkGroupMaintenanceDirectory(g.dir, g.owner); err != nil {
+ return err
+ }
+ b, err := g.read(filepath.Join(g.dir, "permit.json"), g.owner, 0600)
+ if err != nil {
+ return errors.Join(errGroupMaintenance, err)
+ }
+ var p groupMaintenancePermit
+ if decodeMaintenancePermit(b, &p) != nil || p.V != 1 || p.Account != c.Account || p.Region != c.AWSRegion || p.Group != c.Group || p.Instance != c.InstanceID || p.BootID != c.BootID || p.ConfigDigest != c.ConfigDigest || !groupTransactionID.MatchString(p.Transaction) || p.Phase != "mutation" || !a.ops.now().Before(time.Unix(p.Expires, 0)) || !groupDigest(p.OldSHA256) || !groupDigest(p.NewSHA256) {
+ return errGroupMaintenance
+ }
+ switch p.Action {
+ case "apply", "rollback", "repair", "install":
+ default:
+ return errGroupMaintenance
+ }
+ if action == "mutation" {
+ action = p.Action
+ }
+ if action != "check" && action != p.Action && !(action == "rollback" && p.AllowRollback && p.Action == "apply") {
+ return errGroupMaintenance
+ }
+ if g.permit != nil && *g.permit != p {
+ return errGroupMaintenance
+ }
+ // The installed binary must still be one of the exact operator-authorized
+ // artifacts. The normal release verifier independently verifies new code.
+ if !groupArtifactHolds(systemBinaryPath(a.optDir), p.OldSHA256) && !groupArtifactHolds(systemBinaryPath(a.optDir), p.NewSHA256) {
+ return errGroupMaintenance
+ }
+ if action == "check" {
+ if !g.used[p.Action] {
+ if _, err := os.Lstat(filepath.Join(g.dir, "used-"+p.Transaction+"-"+p.Action)); !errors.Is(err, os.ErrNotExist) {
+ return errGroupMaintenance
+ }
+ }
+ return nil
+ }
+ if g.used[action] {
+ return nil
+ }
+ if err := consumeGroupAction(g.dir, "used-"+p.Transaction+"-"+action, g.owner); err != nil {
+ return errors.Join(errGroupMaintenance, err)
+ }
+ if g.used == nil {
+ g.used = map[string]bool{}
+ }
+ g.used[action] = true
+ g.permit = &p
+ return nil
+}
+func (a *systemApplier) groupTarget(path string, rollback bool) error {
+ if !groupMarkerPresent(a.etcDir) {
+ return nil
+ }
+ action := "apply"
+ if rollback {
+ action = "rollback"
+ }
+ if err := a.requireGroupMaintenance(action); err != nil {
+ return err
+ }
+ p := a.maintenance().permit
+ want := p.NewSHA256
+ if rollback {
+ want = p.OldSHA256
+ }
+ if !groupArtifactHolds(path, want) {
+ return errGroupMaintenance
+ }
+ return nil
+}
+
+// Initial installation is a separate, one-use root permission. Its marker is
+// persistent across reboot and consumed before any installation or edge start.
+func (a *systemApplier) requireGroupInstall() error {
+ c, err := a.maintenanceConfig()
+ if err != nil || c == nil {
+ return err
+ }
+ g := a.maintenance()
+ if _, err := os.Lstat(filepath.Join(a.etcDir, "carlos", groupInstallUsed)); !errors.Is(err, os.ErrNotExist) {
+ return a.requireGroupMaintenance("install")
+ }
+ if !a.ops.now().Before(time.Unix(c.Deadline, 0)) || a.ops.edgeStartedThisBoot() {
+ return errGroupMaintenance
+ }
+ if err := consumeGroupAction(filepath.Join(a.etcDir, "carlos"), groupInstallUsed, g.owner); err != nil {
+ return err
+ }
+ g.initial = true
+ return nil
+}
+func (a *systemApplier) groupInstallTarget(digest string) error {
+ if !groupMarkerPresent(a.etcDir) || a.maintenance().initial {
+ return nil
+ }
+ if err := a.requireGroupMaintenance("install"); err != nil {
+ return err
+ }
+ if a.maintenance().permit.NewSHA256 != digest {
+ return errGroupMaintenance
+ }
+ return nil
+}
+
+func groupAutomaticUnit(u string) bool {
+ return u == systemUpdatePathUnit || u == "carlos-system-update.service" || u == systemRecoverUnit
+}
+func groupManualUnits(units []string) []string {
+ out := make([]string, 0, len(units))
+ for _, u := range units {
+ if !groupAutomaticUnit(u) {
+ out = append(out, u)
+ }
+ }
+ return out
+}
+func preserveGroupUnits(etc string) error {
+ unitDir := filepath.Join(etc, "systemd", "system")
+ drop := filepath.Join(unitDir, "carlos-edge.service.d")
+ if err := os.MkdirAll(drop, 0755); err != nil {
+ return err
+ }
+ if err := writeFileDurable(filepath.Join(drop, "50-group.conf"), []byte(groupUnitProtection), 0644); err != nil {
+ return err
+ }
+ for _, u := range []string{systemUpdatePathUnit, "carlos-system-update.service", systemRecoverUnit} {
+ path := filepath.Join(unitDir, u)
+ if to, err := os.Readlink(path); err == nil && to == "/dev/null" {
+ continue
+ }
+ if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ if err := os.Symlink("/dev/null", path); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func groupInstallationConsumed(etc string) bool {
+ _, err := os.Lstat(filepath.Join(etc, "carlos", groupInstallUsed))
+ return !errors.Is(err, os.ErrNotExist)
+}
+func guardGroupBootstrap() (func(), error) {
+ a := &systemApplier{etcDir: "/etc", optDir: release.OptDir(), ops: productionSysOps()}
+ return a.guardGroupBootstrap()
+}
+func (a *systemApplier) guardGroupBootstrap() (func(), error) {
+ if err := os.MkdirAll(a.rootDir(), 0755); err != nil {
+ return nil, err
+ }
+ lock, err := os.OpenFile(a.lockPath(), os.O_CREATE|os.O_RDWR, 0600)
+ if err != nil {
+ return nil, err
+ }
+ fail := func(err error) (func(), error) { lock.Close(); return nil, err }
+ if err := flockExclusiveNonblock(lock); err != nil {
+ return fail(err)
+ }
+ a.resetGroupMaintenance()
+ c, err := a.maintenanceConfig()
+ if err != nil || c == nil {
+ return fail(errGroupMaintenance)
+ }
+ if groupInstallationConsumed(a.etcDir) {
+ if err := a.requireGroupMaintenance("repair"); err != nil {
+ return fail(err)
+ }
+ } else if c.BootID != a.maintenance().bootID() || !a.ops.now().Before(time.Unix(c.Deadline, 0)) || a.ops.edgeStartedThisBoot() {
+ return fail(errGroupMaintenance)
+ }
+ // Created by root, outside the recursive service-user ownership plan.
+ if err := os.Mkdir(a.maintenance().dir, 0700); err != nil && !errors.Is(err, os.ErrExist) {
+ return fail(err)
+ }
+ if err := checkGroupMaintenanceDirectory(a.maintenance().dir, a.maintenance().owner); err != nil {
+ return fail(err)
+ }
+ return func() { lock.Close() }, nil
+}
+
+// Permit keys are exact and unique; encoding/json alone accepts duplicate and
+// case-insensitive keys, which are ambiguous in an authorization document.
+func decodeMaintenancePermit(b []byte, p *groupMaintenancePermit) error {
+ if len(b) > 4096 {
+ return errGroupMaintenance
+ }
+ d := json.NewDecoder(bytes.NewReader(b))
+ tok, err := d.Token()
+ if err != nil || tok != json.Delim('{') {
+ return errGroupMaintenance
+ }
+ allowed := map[string]bool{"v": true, "account": true, "region": true, "group": true, "iid": true, "boot_id": true, "config_digest": true, "transaction": true, "phase": true, "action": true, "old_sha256": true, "new_sha256": true, "expires": true, "allow_rollback": true}
+ seen := map[string]bool{}
+ for d.More() {
+ tok, err := d.Token()
+ key, ok := tok.(string)
+ if err != nil || !ok || !allowed[key] || seen[key] {
+ return errGroupMaintenance
+ }
+ seen[key] = true
+ var value json.RawMessage
+ if d.Decode(&value) != nil || string(value) == "null" {
+ return errGroupMaintenance
+ }
+ }
+ if len(seen) != len(allowed) {
+ return errGroupMaintenance
+ }
+ return strictGroupJSON(b, p)
+}
+func (a *systemApplier) groupStageDigest(digest string) error {
+ if !groupMarkerPresent(a.etcDir) || a.maintenance().initial {
+ return nil
+ }
+ if err := a.requireGroupMaintenance("mutation"); err != nil {
+ return err
+ }
+ p := a.maintenance().permit
+ if (p.Action != "apply" && p.Action != "install") || p.NewSHA256 != digest {
+ return errGroupMaintenance
+ }
+ return nil
+}
+func (a *systemApplier) groupExecutable(path string) error {
+ if !groupMarkerPresent(a.etcDir) {
+ return nil
+ }
+ if err := a.requireGroupMaintenance("mutation"); err != nil {
+ return err
+ }
+ p := a.maintenance().permit
+ if !groupArtifactHolds(path, p.OldSHA256) && !groupArtifactHolds(path, p.NewSHA256) {
+ return errGroupMaintenance
+ }
+ return nil
+}
+
+func (a *systemApplier) resetGroupMaintenance() {
+ if g := a.groupMaintenance; g != nil {
+ g.permit = nil
+ g.used = nil
+ g.initial = false
+ }
+}
+
+func groupArtifactHolds(path, digest string) bool {
+ state, err := slotState(path, digest)
+ return err == nil && state == slotHolds
+}
diff --git a/internal/host/group_maintenance_linux.go b/internal/host/group_maintenance_linux.go
new file mode 100644
index 000000000..857e30614
--- /dev/null
+++ b/internal/host/group_maintenance_linux.go
@@ -0,0 +1,49 @@
+//go:build linux
+
+package host
+
+import (
+ "golang.org/x/sys/unix"
+ "os"
+ "path/filepath"
+)
+
+// The caller has proved the protected ancestors with ReadGroupFile. A root
+// sibling of /run/carlos is essential: that agent-owned directory is excluded.
+func consumeGroupAction(path, name string, owner int) error {
+ fd, err := unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS})
+ if err != nil {
+ return err
+ }
+ defer unix.Close(fd)
+ var st unix.Stat_t
+ if unix.Fstat(fd, &st) != nil || int(st.Uid) != owner || st.Mode&0022 != 0 || (filepath.Base(path) == "carlos-group-maintenance" && (st.Gid != 0 || st.Mode&0777 != 0700)) {
+ return errGroupMaintenance
+ }
+ leaf, err := unix.Openat(fd, name, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600)
+ if err != nil {
+ return err
+ }
+ f := os.NewFile(uintptr(leaf), name)
+ defer f.Close()
+ if _, err = f.Write([]byte("consumed\n")); err != nil {
+ return err
+ }
+ if err = f.Sync(); err != nil {
+ return err
+ }
+ return unix.Fsync(fd)
+}
+
+func checkGroupMaintenanceDirectory(path string, owner int) error {
+ fd, err := unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS})
+ if err != nil {
+ return err
+ }
+ defer unix.Close(fd)
+ var st unix.Stat_t
+ if unix.Fstat(fd, &st) != nil || int(st.Uid) != owner || (owner == 0 && st.Gid != 0) || st.Mode&0777 != 0700 {
+ return errGroupMaintenance
+ }
+ return nil
+}
diff --git a/internal/host/group_maintenance_other.go b/internal/host/group_maintenance_other.go
new file mode 100644
index 000000000..e48d6d0dd
--- /dev/null
+++ b/internal/host/group_maintenance_other.go
@@ -0,0 +1,7 @@
+//go:build !linux
+
+package host
+
+func consumeGroupAction(string, string, int) error { return errGroupMaintenance }
+
+func checkGroupMaintenanceDirectory(string, int) error { return errGroupMaintenance }
diff --git a/internal/host/group_maintenance_protocol_test.go b/internal/host/group_maintenance_protocol_test.go
new file mode 100644
index 000000000..df4ece1ea
--- /dev/null
+++ b/internal/host/group_maintenance_protocol_test.go
@@ -0,0 +1,442 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxroles"
+ "github.com/carlosframework/platform/internal/groupadmission"
+)
+
+// Executable Task 7 contract, not an operator implementation. The provider and
+// durable journal outlive the simulated operator process. No AWS client exists.
+type maintenanceCloud struct {
+ phase string
+ iid, boot, process, transaction string
+ n, min, desired, max int
+ peer, healthy, admitted, published bool
+ targets [2]string
+ now, deadline time.Time
+ hook, loseEnter, loseExit, loseComplete, dropAfterExit, apiDown bool
+ rejected int
+ replacements, boxCompletions, operatorCompletions, reads int
+ writes []string
+}
+type maintenanceJournal struct {
+ transaction, iid, boot, process, exitActivity string
+ phase string
+ observed time.Time
+ attempts int
+ unknown, failed, alert, permit bool
+}
+type fakeMaintenanceOperator struct {
+ c *maintenanceCloud
+ j *maintenanceJournal
+}
+
+func newMaintenanceTransaction() *fakeMaintenanceOperator {
+ now := time.Unix(1000, 0)
+ return &fakeMaintenanceOperator{c: &maintenanceCloud{phase: "InService", iid: "i-member", boot: "boot", process: "pid-1/start-1", n: 2, min: 2, desired: 2, max: 2, peer: true, healthy: true, admitted: true, published: true, targets: [2]string{"healthy", "healthy"}, now: now}, j: &maintenanceJournal{transaction: "tx-1"}}
+}
+func (o *fakeMaintenanceOperator) describe() error {
+ o.c.reads += 4
+ if o.c.apiDown {
+ return errors.New("provider unavailable")
+ }
+ if o.c.iid != o.j.iid || o.c.n != o.c.max {
+ return errors.New("membership changed")
+ }
+ return nil
+}
+func (o *fakeMaintenanceOperator) begin() error {
+ c, j := o.c, o.j
+ if c.n < 2 || !c.peer || !c.admitted || !c.healthy || (c.transaction != "" && c.transaction != j.transaction) {
+ return errors.New("maintenance refused")
+ }
+ c.transaction = j.transaction
+ if j.iid == "" {
+ j.iid = c.iid
+ j.boot = c.boot
+ j.process = c.process
+ j.phase = "lower-intent"
+ }
+ if err := o.describe(); err != nil {
+ return err
+ }
+ if c.phase == "InService" {
+ if c.desired != c.n || (c.min != c.n && c.min != c.n-1) {
+ return errors.New("wrong topology")
+ }
+ if c.min == c.n {
+ c.writes = append(c.writes, "lower-min")
+ c.min = c.n - 1
+ }
+ if c.min != c.n-1 || c.desired != c.n || c.max != c.n {
+ return errors.New("wrong topology")
+ }
+ j.phase = "enter-intent"
+ c.writes = append(c.writes, "enter-decrement")
+ c.phase = "Standby"
+ c.desired--
+ c.targets = [2]string{"unused", "unused"}
+ if c.loseEnter {
+ c.loseEnter = false
+ return errors.New("lost enter response")
+ }
+ }
+ if err := o.describe(); err != nil {
+ return err
+ }
+ if c.phase != "Standby" || c.desired != c.n-1 || c.min != c.n-1 || c.max != c.n || c.targets != [2]string{"unused", "unused"} {
+ return errors.New("standby not established")
+ }
+ j.phase = "mutation"
+ j.permit = true
+ return nil
+}
+func (o *fakeMaintenanceOperator) restart() error {
+ if o.c.phase != "Standby" || !o.j.permit || o.j.phase != "mutation" {
+ return errors.New("restart refused")
+ }
+ o.c.admitted = false
+ o.c.published = false
+ o.c.healthy = false
+ o.c.process = "pid-2/start-2"
+ o.j.process = o.c.process
+ o.j.phase = "verify"
+ return nil
+}
+func (o *fakeMaintenanceOperator) ready() bool {
+ c, j := o.c, o.j
+ return c.iid == j.iid && c.boot == j.boot && c.transaction == j.transaction && c.process == j.process && c.admitted && c.healthy && c.published
+}
+func (o *fakeMaintenanceOperator) observeReady() error {
+ if !o.ready() {
+ return errors.New("fresh process unready")
+ }
+ o.j.observed = o.c.now
+ return nil
+}
+func (o *fakeMaintenanceOperator) returnMember() error {
+ c, j := o.c, o.j
+ if err := o.describe(); err != nil {
+ if c.phase == "Pending:Wait" {
+ j.failed = true
+ j.alert = true
+ }
+ return err
+ }
+ if c.phase == "Standby" {
+ if !o.ready() || c.now.Sub(j.observed) > 5*time.Second {
+ return errors.New("fresh process unready")
+ }
+ j.phase = "return-intent"
+ c.writes = append(c.writes, "exit")
+ c.desired++
+ c.phase = "InService"
+ c.targets = [2]string{"healthy", "healthy"}
+ j.exitActivity = "activity-1"
+ if c.hook {
+ c.phase = "Pending:Wait"
+ c.deadline = c.now.Add(900 * time.Second)
+ c.targets = [2]string{"initial", "initial"}
+ }
+ if c.dropAfterExit {
+ c.admitted = false
+ }
+ if c.loseExit {
+ c.loseExit = false
+ return errors.New("lost exit response")
+ }
+ }
+ if c.phase == "Pending:Wait" {
+ if !o.ready() {
+ j.failed = true
+ j.alert = true
+ return errors.New("failed return probe")
+ }
+ if j.exitActivity == "" {
+ return errors.New("unknown exit activity")
+ }
+ // This journal is separate from the original launch receipt and survives
+ // operator restart. Ambiguous outcomes require describe before retry.
+ if j.unknown {
+ return errors.New("return completion unknown")
+ }
+ for j.attempts < 4 {
+ if !o.ready() {
+ j.failed = true
+ j.alert = true
+ return errors.New("failed return probe")
+ }
+ j.attempts++
+ j.unknown = true
+ c.operatorCompletions++
+ c.now = c.now.Add(2 * time.Second)
+ c.writes = append(c.writes, "continue")
+ if c.rejected > 0 {
+ c.rejected--
+ j.unknown = false
+ if j.attempts < 4 {
+ c.now = c.now.Add(time.Duration(1<<uint(j.attempts-1)) * time.Second)
+ }
+ continue
+ }
+ c.phase = "InService"
+ c.targets = [2]string{"healthy", "healthy"}
+ if c.loseComplete {
+ c.loseComplete = false
+ return errors.New("lost completion response")
+ }
+ j.unknown = false
+ break
+ }
+ if c.phase != "InService" {
+ j.failed = true
+ j.alert = true
+ return errors.New("return attempts exhausted")
+ }
+ }
+ if c.phase != "InService" || !o.ready() || c.desired != c.n || c.targets != [2]string{"healthy", "healthy"} {
+ return errors.New("return not healthy")
+ }
+ if c.min != c.n {
+ c.writes = append(c.writes, "restore-min")
+ c.min = c.n
+ }
+ j.unknown = false
+ j.permit = false
+ j.phase = "revoked"
+ c.transaction = ""
+ return nil
+}
+func (o *fakeMaintenanceOperator) advance(d time.Duration) {
+ c, j := o.c, o.j
+ c.now = c.now.Add(d)
+ if c.phase == "Standby" && d >= 15*time.Minute {
+ j.alert = true
+ }
+ if c.phase == "Pending:Wait" && !c.now.Before(c.deadline) {
+ c.phase = "Terminated"
+ c.replacements++
+ j.failed = true
+ }
+}
+func finishLocal(o *fakeMaintenanceOperator) {
+ o.c.admitted = true
+ o.c.published = true
+ o.c.healthy = true
+}
+func heldTransaction(t *testing.T) *fakeMaintenanceOperator {
+ t.Helper()
+ o := newMaintenanceTransaction()
+ if err := o.begin(); err != nil {
+ t.Fatal(err)
+ }
+ if err := o.restart(); err != nil {
+ t.Fatal(err)
+ }
+ return o
+}
+func TestGroupSharedDependencyHealth(t *testing.T) {
+ a := readyGroupAdmission(t)
+ a.observe(groupadmission.Facts{TerminationStarted: true})
+ a.tick(t.Context())
+ if !a.state.Admitted() {
+ t.Fatal("initial admission")
+ }
+ _ = a.applyRole(boxroles.Serve, false)
+ a.observe(groupadmission.Facts{})
+ a.tick(t.Context())
+ if !a.state.Admitted() || len(a.health.Failing(time.Now())) != 0 {
+ t.Fatal("shared S3/SSM error changed live health")
+ }
+ o := heldTransaction(t)
+ o.c.apiDown = true
+ o.advance(16 * time.Minute)
+ if o.c.phase != "Standby" || o.c.replacements != 0 || !o.j.alert {
+ t.Fatal("shared outage released maintenance", o.c.phase)
+ }
+ if err := o.returnMember(); err == nil {
+ t.Fatal("operator ignored provider outage")
+ }
+}
+func TestGroupMaintenanceCrashResume(t *testing.T) {
+ for _, crash := range []string{"enter", "restart", "exit", "completion", "no-hook", "rejected"} {
+ t.Run(crash, func(t *testing.T) {
+ o := newMaintenanceTransaction()
+ o.c.hook = crash != "no-hook"
+ o.c.loseEnter = crash == "enter"
+ err := o.begin()
+ if err != nil && crash != "enter" {
+ t.Fatal(err)
+ }
+ o = &fakeMaintenanceOperator{c: o.c, j: o.j}
+ if err := o.begin(); err != nil {
+ t.Fatal(err)
+ }
+ if err := o.restart(); err != nil {
+ t.Fatal(err)
+ }
+ o.advance(16 * time.Minute)
+ if o.c.phase != "Standby" || o.c.replacements != 0 || !o.j.permit {
+ t.Fatal("crash lost hold", o.c.phase)
+ }
+ if o.c.admitted {
+ t.Fatal("restarted process opened early")
+ }
+ o = &fakeMaintenanceOperator{c: o.c, j: o.j}
+ finishLocal(o)
+ if err := o.observeReady(); err != nil {
+ t.Fatal(err)
+ }
+ o.c.loseExit = crash == "exit"
+ o.c.loseComplete = crash == "completion"
+ if crash == "rejected" {
+ o.c.rejected = 3
+ }
+ _ = o.returnMember()
+ o = &fakeMaintenanceOperator{c: o.c, j: o.j}
+ _ = o.returnMember()
+ if o.c.phase != "InService" || o.j.permit || o.c.min != 2 || o.c.desired != 2 || o.c.max != 2 || o.j.attempts > 4 {
+ t.Fatalf("resume: %+v %+v", o.c, o.j)
+ }
+ exits := 0
+ for _, w := range o.c.writes {
+ if w == "exit" {
+ exits++
+ }
+ }
+ if exits != 1 {
+ t.Fatal("ambiguous exit replayed", o.c.writes)
+ }
+ })
+ }
+}
+func TestGroupStandbyExitPendingWait(t *testing.T) {
+ // Real Task 3 receipt suppresses only the initial launch. Fresh admission is
+ // still required after restarting, and no box completes the synthetic return.
+ boxCalls := 0
+ receipt := groupLaunchFixture(t, func(context.Context, groupadmission.Launch) error { boxCalls++; return nil })
+ if err := receipt.Complete(t.Context(), receipt.binding.launch()); err != nil {
+ t.Fatal(err)
+ }
+ a := readyGroupAdmission(t)
+ a.launch = ptrLaunch(receipt.binding.launch())
+ a.completer = receipt
+ a.observe(groupadmission.Facts{TerminationStarted: true})
+ a.tick(t.Context())
+ if !a.state.Admitted() || boxCalls != 1 {
+ t.Fatal("fresh admission/receipt")
+ }
+ o := heldTransaction(t)
+ o.c.hook = true
+ finishLocal(o)
+ if err := o.observeReady(); err != nil {
+ t.Fatal(err)
+ }
+ if err := o.returnMember(); err != nil {
+ t.Fatal(err)
+ }
+ o.advance(901 * time.Second)
+ if o.c.phase != "InService" || o.c.operatorCompletions != 1 || boxCalls != 1 || o.c.replacements != 0 {
+ t.Fatalf("operator=%d box=%d phase=%s replacement=%d", o.c.operatorCompletions, boxCalls, o.c.phase, o.c.replacements)
+ }
+ t.Run("pre-exit-refusals", func(t *testing.T) {
+ for _, fault := range []string{"admission", "publication", "process", "transaction", "boot", "iid", "stale"} {
+ o := heldTransaction(t)
+ finishLocal(o)
+ _ = o.observeReady()
+ switch fault {
+ case "admission":
+ o.c.admitted = false
+ case "publication":
+ o.c.published = false
+ case "process":
+ o.c.process = "other"
+ case "transaction":
+ o.c.transaction = "other"
+ case "boot":
+ o.c.boot = "other"
+ case "iid":
+ o.c.iid = "other"
+ case "stale":
+ o.c.now = o.c.now.Add(6 * time.Second)
+ }
+ if o.returnMember() == nil || o.c.phase != "Standby" || o.c.operatorCompletions != 0 {
+ t.Fatal(fault)
+ }
+ }
+ })
+ t.Run("post-exit-admission-loss", func(t *testing.T) {
+ o := heldTransaction(t)
+ o.c.hook = true
+ o.c.dropAfterExit = true
+ finishLocal(o)
+ _ = o.observeReady()
+ if o.returnMember() == nil || !o.j.failed || !o.j.alert || o.c.operatorCompletions != 0 {
+ t.Fatal("did not fail before deadline")
+ }
+ o.advance(901 * time.Second)
+ if !o.j.failed || o.c.replacements != 1 || o.c.phase != "Terminated" {
+ t.Fatal("default abandon reported as retention")
+ }
+ })
+}
+func ptrLaunch(l groupadmission.Launch) *groupadmission.Launch { return &l }
+func TestGroupMaintenanceTransactionPreconditions(t *testing.T) {
+ for _, fault := range []string{"single", "peer", "concurrent", "wrong-desired", "one-target"} {
+ o := newMaintenanceTransaction()
+ switch fault {
+ case "single":
+ o.c.n = 1
+ case "peer":
+ o.c.peer = false
+ case "concurrent":
+ o.c.transaction = "other"
+ case "wrong-desired":
+ o.c.desired = 3
+ case "one-target":
+ o.c.phase = "Standby"
+ o.c.min = 1
+ o.c.desired = 1
+ o.c.targets = [2]string{"unused", "draining"}
+ }
+ if o.begin() == nil || o.j.permit {
+ t.Fatal(fault)
+ }
+ }
+ o := heldTransaction(t)
+ finishLocal(o)
+ _ = o.observeReady()
+ if err := o.returnMember(); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(o.c.writes, []string{"lower-min", "enter-decrement", "exit", "restore-min"}) {
+ t.Fatal(o.c.writes)
+ }
+ if o.j.phase != "revoked" {
+ t.Fatal(fmt.Sprint(o.j))
+ }
+}
+
+func TestGroupStandbyReturnAttemptBudget(t *testing.T) {
+ o := heldTransaction(t)
+ o.c.hook = true
+ o.c.rejected = 4
+ finishLocal(o)
+ _ = o.observeReady()
+ start := o.c.now
+ if o.returnMember() == nil || o.j.attempts != 4 || o.c.now.Sub(start) != 15*time.Second || !o.j.failed {
+ t.Fatal("return retry budget", o.j, o.c.now.Sub(start))
+ }
+ o = &fakeMaintenanceOperator{c: o.c, j: o.j}
+ _ = o.returnMember()
+ if o.j.attempts != 4 || o.c.operatorCompletions != 4 {
+ t.Fatal("resume reset completion attempts")
+ }
+}
diff --git a/internal/host/group_maintenance_test.go b/internal/host/group_maintenance_test.go
new file mode 100644
index 000000000..47cf7e4fb
--- /dev/null
+++ b/internal/host/group_maintenance_test.go
@@ -0,0 +1,475 @@
+package host
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "github.com/carlosframework/platform/internal/hostenv"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestGroupMaintenanceRestartGuard(t *testing.T) {
+ for _, entry := range []string{"apply", "recover", "restart", "quiesce", "repoint", "units", "rollback", "restore", "recovery", "install-channel"} {
+ t.Run(entry, func(t *testing.T) {
+ f := newApplyFixture(t, "stable", "v1.0.0")
+ os.MkdirAll(filepath.Join(f.a.etcDir, "carlos"), 0700)
+ os.WriteFile(filepath.Join(f.a.etcDir, "carlos", "group.json"), []byte(`{}`), 0644)
+ var err error
+ switch entry {
+ case "apply":
+ err = f.a.Run(t.Context(), false)
+ case "recover":
+ err = f.a.Run(t.Context(), true)
+ case "restart":
+ err = f.a.restartEdge()
+ case "quiesce":
+ f.a.quiesce()
+ case "repoint":
+ err = f.a.activationGuard(t.Context(), "v1.1.0", "v1.0.0", func(context.Context) error { f.calls = append(f.calls, "REPOINT"); return nil })
+ case "units":
+ err = f.a.installUnits(t.Context(), t.TempDir(), nil)
+ case "rollback":
+ err = f.a.rollback(t.Context(), systemRequest{}, "test", &systemJournal{})
+ case "restore":
+ _, err = f.a.restoreFiles(t.Context(), &systemJournal{})
+ case "recovery":
+ _, err = f.a.recoverIfNeeded(t.Context())
+ case "install-channel":
+ in := channelInstall{a: f.a}
+ _, err = in.run(t.Context())
+ }
+ if entry != "quiesce" && !errors.Is(err, errGroupMaintenance) {
+ t.Error("entry accepted group without permit")
+ }
+ for _, call := range f.calls {
+ if strings.Contains(call, "stop") || strings.Contains(call, "restart") || strings.Contains(call, "REPOINT") || strings.HasPrefix(call, "run ") {
+ t.Errorf("side effect before guard: %s", call)
+ }
+ }
+ })
+ }
+}
+
+func TestGroupUnitsCannotRearmUpdate(t *testing.T) {
+ etc := t.TempDir()
+ os.MkdirAll(filepath.Join(etc, "carlos"), 0700)
+ os.WriteFile(filepath.Join(etc, "carlos", "group.json"), []byte(`{}`), 0644)
+ var calls []string
+ ctl := func(args ...string) (string, error) { calls = append(calls, strings.Join(args, " ")); return "", nil }
+ probe := func(args ...string) (string, error) { return "inactive", nil }
+ ensureSystemUnits(etc, filepath.Join(t.TempDir(), "lock"), ctl, probe, func(string, ...any) {})
+ if len(calls) > 0 {
+ t.Fatalf("group repair mutated without permit: %v", calls)
+ }
+}
+
+func maintenanceFixture(t *testing.T) (*applyFixture, groupMaintenancePermit) {
+ t.Helper()
+ f := newApplyFixture(t, "stable", "v1.0.0")
+ home, err := os.UserHomeDir()
+ if err != nil {
+ t.Fatal(err)
+ }
+ root, err := os.MkdirTemp(home, ".group-maintenance-test-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(root) })
+ f.a.etcDir = filepath.Join(root, "etc")
+ dir := filepath.Join(root, "maintenance")
+ for _, p := range []string{filepath.Join(f.a.etcDir, "carlos"), dir} {
+ if err := os.MkdirAll(p, 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ c, _ := groupConfigFixture()
+ c.Deadline = f.now.Add(time.Minute).Unix()
+ c.ConfigDigest = c.Digest()
+ b, _ := json.Marshal(c)
+ if err := os.WriteFile(filepath.Join(f.a.etcDir, "carlos", "group.json"), b, 0644); err != nil {
+ t.Fatal(err)
+ }
+ f.a.groupMaintenance = &groupMaintenance{dir: dir, owner: os.Geteuid(), read: hostenv.ReadGroupFile, bootID: func() string { return c.BootID }}
+ old, _ := os.ReadFile(systemBinaryPath(f.a.optDir))
+ sum := sha256.Sum256(old)
+ p := groupMaintenancePermit{V: 1, Account: c.Account, Region: c.AWSRegion, Group: c.Group, Instance: c.InstanceID, BootID: c.BootID, ConfigDigest: c.ConfigDigest, Transaction: "tx-1", Phase: "mutation", Action: "apply", OldSHA256: hex.EncodeToString(sum[:]), NewSHA256: strings.Repeat("a", 64), Expires: f.now.Add(time.Hour).Unix()}
+ writeMaintenancePermit(t, f, p)
+ return f, p
+}
+func writeMaintenancePermit(t *testing.T, f *applyFixture, p groupMaintenancePermit) {
+ t.Helper()
+ b, _ := json.Marshal(p)
+ if err := os.WriteFile(filepath.Join(f.a.maintenance().dir, "permit.json"), b, 0600); err != nil {
+ t.Fatal(err)
+ }
+}
+func TestGroupMaintenancePermit(t *testing.T) {
+ for _, bad := range []string{"valid", "missing", "account", "region", "group", "iid", "boot", "transaction", "old", "new", "digest", "expiry", "verify", "return", "revoked", "mode", "symlink", "hardlink", "directory", "oversize", "unknown", "trailing", "parent-mode", "marker-mode", "marker-corrupt", "agent-receipt"} {
+ t.Run(bad, func(t *testing.T) {
+ f, p := maintenanceFixture(t)
+ path := filepath.Join(f.a.maintenance().dir, "permit.json")
+ switch bad {
+ case "account":
+ p.Account = "other"
+ case "region":
+ p.Region = "other"
+ case "group":
+ p.Group = "other"
+ case "iid":
+ p.Instance = "other"
+ case "boot":
+ p.BootID = "other"
+ case "transaction":
+ p.Transaction = "../escape"
+ case "old":
+ p.OldSHA256 = strings.Repeat("b", 64)
+ case "new":
+ p.NewSHA256 = "unsigned"
+ case "digest":
+ p.ConfigDigest = "other"
+ case "expiry":
+ p.Expires = f.now.Unix()
+ case "verify", "return", "revoked":
+ p.Phase = bad
+ }
+ writeMaintenancePermit(t, f, p)
+ switch bad {
+ case "missing":
+ os.Remove(path)
+ case "mode":
+ os.Chmod(path, 0644)
+ case "symlink":
+ os.Rename(path, path+".real")
+ os.Symlink(path+".real", path)
+ case "hardlink":
+ os.Link(path, path+".link")
+ case "directory":
+ os.Remove(path)
+ os.Mkdir(path, 0600)
+ case "oversize":
+ os.WriteFile(path, []byte(strings.Repeat(" ", 65537)), 0600)
+ case "unknown":
+ b, _ := os.ReadFile(path)
+ os.WriteFile(path, append(b[:len(b)-1], []byte(`,"extra":1}`)...), 0600)
+ case "trailing":
+ b, _ := os.ReadFile(path)
+ os.WriteFile(path, append(b, []byte(` {}`)...), 0600)
+ case "parent-mode":
+ os.Chmod(f.a.maintenance().dir, 0770)
+ case "marker-mode":
+ os.Chmod(filepath.Join(f.a.etcDir, "carlos", "group.json"), 0664)
+ case "marker-corrupt":
+ os.WriteFile(filepath.Join(f.a.etcDir, "carlos", "group.json"), []byte(`{}`), 0644)
+ case "agent-receipt":
+ os.Remove(path)
+ os.MkdirAll(filepath.Join(f.a.dataDir, "carlos", "group-admission"), 0700)
+ b, _ := json.Marshal(p)
+ os.WriteFile(filepath.Join(f.a.dataDir, "carlos", "group-admission", "receipt.json"), b, 0600)
+ }
+ err := f.a.restartEdge()
+ if (err == nil) != (bad == "valid") {
+ t.Fatalf("%s: %v", bad, err)
+ }
+ if bad != "valid" && len(f.calls) != 0 {
+ t.Fatalf("side effects: %v", f.calls)
+ }
+ })
+ }
+ t.Run("production-owner", func(t *testing.T) {
+ f, _ := maintenanceFixture(t)
+ f.a.maintenance().owner = 0
+ if f.a.restartEdge() == nil {
+ t.Fatal("nonroot config trusted")
+ }
+ })
+ t.Run("replay-and-expiry", func(t *testing.T) {
+ f, _ := maintenanceFixture(t)
+ if err := f.a.restartEdge(); err != nil {
+ t.Fatal(err)
+ }
+ g := f.a.maintenance()
+ g.permit = nil
+ g.used = nil
+ if f.a.restartEdge() == nil {
+ t.Fatal("stale permit replayed")
+ }
+ f.now = f.now.Add(2 * time.Hour)
+ if f.a.restartEdge() == nil {
+ t.Fatal("expired permit mutated")
+ }
+ })
+ t.Run("rollback", func(t *testing.T) {
+ f, p := maintenanceFixture(t)
+ old, _ := os.ReadFile(systemBinaryPath(f.a.optDir))
+ os.WriteFile(systemPrevPath(f.a.optDir), old, 0755)
+ if f.a.groupTarget(systemPrevPath(f.a.optDir), true) == nil {
+ t.Fatal("implicit rollback")
+ }
+ p.AllowRollback = true
+ writeMaintenancePermit(t, f, p)
+ if err := f.a.groupTarget(systemPrevPath(f.a.optDir), true); err != nil {
+ t.Fatal(err)
+ }
+ os.WriteFile(systemPrevPath(f.a.optDir), []byte("wrong"), 0755)
+ if f.a.groupTarget(systemPrevPath(f.a.optDir), true) == nil {
+ t.Fatal("wrong rollback artifact")
+ }
+ })
+ t.Run("target", func(t *testing.T) {
+ f, _ := maintenanceFixture(t)
+ if f.a.groupTarget(systemBinaryPath(f.a.optDir), false) == nil {
+ t.Fatal("wrong new artifact")
+ }
+ })
+ t.Run("expired-before-repoint", func(t *testing.T) {
+ f, _ := maintenanceFixture(t)
+ f.a.beforeSwap = func() { f.now = f.now.Add(2 * time.Hour) }
+ called := false
+ err := f.a.activationGuard(t.Context(), "v1.0.0", "v1.0.0", func(context.Context) error { called = true; return nil })
+ if err == nil || called {
+ t.Fatal("repoint after expiry")
+ }
+ })
+}
+func TestGroupMaintenanceInitialInstall(t *testing.T) {
+ f, _ := maintenanceFixture(t)
+ f.edgeStartedThisBoot = false
+ if err := f.a.requireGroupInstall(); err != nil {
+ t.Fatal(err)
+ }
+ if !groupInstallationConsumed(f.a.etcDir) {
+ t.Fatal("permission not consumed")
+ }
+ f.a.maintenance().initial = false
+ if f.a.requireGroupInstall() == nil {
+ t.Fatal("initial installation replayed")
+ }
+ f2, _ := maintenanceFixture(t)
+ if f2.a.requireGroupInstall() == nil {
+ t.Fatal("booted member reused installation")
+ }
+}
+func TestGroupMaintenanceUnitPreservation(t *testing.T) {
+ f, _ := maintenanceFixture(t)
+ if err := preserveGroupUnits(f.a.etcDir); err != nil {
+ t.Fatal(err)
+ }
+ if err := preserveGroupUnits(f.a.etcDir); err != nil {
+ t.Fatal(err)
+ }
+ b, err := os.ReadFile(filepath.Join(f.a.etcDir, "systemd/system/carlos-edge.service.d/50-group.conf"))
+ if err != nil || string(b) != groupUnitProtection || !strings.Contains(string(b), "Restart=no") {
+ t.Fatalf("drop-in: %s %v", b, err)
+ }
+ for _, u := range []string{systemUpdatePathUnit, "carlos-system-update.service", systemRecoverUnit} {
+ to, err := os.Readlink(filepath.Join(f.a.etcDir, "systemd/system", u))
+ if err != nil || to != "/dev/null" {
+ t.Fatal(u, to, err)
+ }
+ }
+ if err := f.a.arm(bootstrapPlan{Enabled: append([]string{systemEdgeUnit}, ensureSystemArmed...)}); err != nil {
+ t.Fatal(err)
+ }
+ for _, call := range f.calls {
+ if strings.Contains(call, "system-update") || strings.Contains(call, "system-recover") {
+ t.Fatal("automatic update armed", call)
+ }
+ }
+}
+
+func TestGroupMaintenanceSystemLegDisabled(t *testing.T) {
+ get := func(k string) string {
+ if k == "CARLOS_BOX_REFERENCE" {
+ return "group"
+ }
+ return ""
+ }
+ if l := newSystemLeg(nil, nil, get, t.TempDir(), t.TempDir()); l != nil {
+ t.Fatal("group self-update leg armed")
+ }
+ if l := newSystemLeg(nil, nil, func(string) string { return "" }, t.TempDir(), t.TempDir()); l == nil {
+ t.Fatal("fixed self-update changed")
+ }
+}
+func TestGroupMaintenanceRepair(t *testing.T) {
+ f, p := maintenanceFixture(t)
+ p.Action = "repair"
+ writeMaintenancePermit(t, f, p)
+ probe := func(args ...string) (string, error) {
+ if args[0] == "is-enabled" {
+ return "disabled", nil
+ }
+ return "inactive", nil
+ }
+ ensureSystemUnitsWithGuard(f.a.etcDir, f.a.lockPath(), f.a.ops.systemctl, probe, t.Logf, f.a)
+ for _, call := range f.calls {
+ if strings.Contains(call, "system-update") || strings.Contains(call, "system-recover") {
+ t.Fatal("repair rearmed update", call)
+ }
+ }
+ if _, err := os.Stat(filepath.Join(f.a.etcDir, "systemd/system", instanceControlSocket)); err != nil {
+ t.Fatal("repair did not install control socket", err)
+ }
+ b, err := os.ReadFile(filepath.Join(f.a.etcDir, "systemd/system/carlos-edge.service.d/50-group.conf"))
+ if err != nil || string(b) != groupUnitProtection {
+ t.Fatal("repair lost group drop-in", err)
+ }
+ for _, u := range []string{systemUpdatePathUnit, "carlos-system-update.service", systemRecoverUnit} {
+ to, err := os.Readlink(filepath.Join(f.a.etcDir, "systemd/system", u))
+ if err != nil || to != "/dev/null" {
+ t.Fatal("repair lost mask", u)
+ }
+ }
+}
+
+func TestGroupMaintenanceBootstrap(t *testing.T) {
+ f, _ := maintenanceFixture(t)
+ if unlock, err := f.a.guardGroupBootstrap(); err == nil {
+ unlock()
+ t.Fatal("booted bootstrap accepted")
+ }
+ f.edgeStartedThisBoot = false
+ unlock, err := f.a.guardGroupBootstrap()
+ if err != nil {
+ t.Fatal(err)
+ }
+ unlock()
+ if err := f.a.requireGroupInstall(); err != nil {
+ t.Fatal(err)
+ }
+ if unlock, err := f.a.guardGroupBootstrap(); err == nil {
+ unlock()
+ t.Fatal("bootstrap reused consumed initial permission")
+ }
+}
+func TestGroupMaintenanceStrictPermit(t *testing.T) {
+ _, p := maintenanceFixture(t)
+ raw, _ := json.Marshal(p)
+ for _, b := range [][]byte{append([]byte(`{"v":1,`), raw[1:]...), bytes.Replace(raw, []byte(`"v"`), []byte(`"V"`), 1), bytes.Replace(raw, []byte(`"allow_rollback":false`), []byte(`"allow_rollback":null`), 1), bytes.Replace(raw, []byte(`,"allow_rollback":false`), nil, 1)} {
+ var out groupMaintenancePermit
+ if decodeMaintenancePermit(b, &out) == nil {
+ t.Fatalf("ambiguous permit accepted: %s", b)
+ }
+ }
+}
+
+func TestGroupMaintenanceApplyAndRecovery(t *testing.T) {
+ for _, mode := range []string{"apply", "rollback", "recovery", "wrong-signed-target"} {
+ t.Run(mode, func(t *testing.T) {
+ m, p := maintenanceFixture(t)
+ f, _ := applyHappy(t)
+ f.a.etcDir = m.a.etcDir
+ f.a.groupMaintenance = m.a.groupMaintenance
+ old, _ := os.ReadFile(systemBinaryPath(f.a.optDir))
+ sum := sha256.Sum256(old)
+ p.OldSHA256 = hex.EncodeToString(sum[:])
+ body, _ := os.ReadFile(systemCachePath(f.a.dataDir, "v2"))
+ sum = sha256.Sum256(body)
+ p.NewSHA256 = hex.EncodeToString(sum[:])
+ p.AllowRollback = true
+ if mode == "wrong-signed-target" {
+ p.NewSHA256 = strings.Repeat("d", 64)
+ }
+ writeMaintenancePermit(t, f, p)
+ envPath := filepath.Join(f.a.etcDir, "carlos/host.env")
+ os.WriteFile(envPath, []byte("EXISTING=value\n"), 0600)
+ certPath := filepath.Join(f.a.dataDir, "cert.pem")
+ os.WriteFile(certPath, []byte("preserved cert"), 0600)
+ if mode == "rollback" {
+ f.edgeUp = false
+ orig := f.a.ops.systemctl
+ f.a.ops.systemctl = func(args ...string) (string, error) {
+ if args[0] == "restart" && systemCacheHolds(systemBinaryPath(f.a.optDir), p.OldSHA256) {
+ f.edgeUp = true
+ }
+ return orig(args...)
+ }
+ }
+ err := f.a.Run(t.Context(), false)
+ if mode == "wrong-signed-target" {
+ if err == nil || len(f.calls) != 0 {
+ t.Fatal("executed unpermitted signed artifact", err, f.calls)
+ }
+ return
+ }
+ if mode == "rollback" {
+ if err == nil || f.result() == nil || f.result().Outcome != systemOutcomeRolledBack {
+ t.Fatal("rollback", err, f.result())
+ }
+ } else if err != nil || f.result() == nil || f.result().Outcome != systemOutcomeApplied {
+ t.Fatal("apply", err, f.result())
+ }
+ if mode == "recovery" {
+ // Reconstruct a pre-gate crash journal and explicitly authorize rollback.
+ req, _ := f.a.readRequest()
+ f.a.journal(systemJournal{Phase: systemPhaseInstalled, Target: "v2", PrevBuild: "v1", PromotedAt: req.PromotedAt})
+ f.a.maintenance().used = nil
+ f.a.maintenance().permit = nil
+ p.Action = "rollback"
+ writeMaintenancePermit(t, f, p)
+ if err := f.a.Run(t.Context(), true); err != nil {
+ t.Fatal("authorized recovery", err)
+ }
+ if !systemCacheHolds(systemBinaryPath(f.a.optDir), p.OldSHA256) {
+ t.Fatal("recovery did not restore recorded artifact")
+ }
+ }
+ for _, call := range f.calls {
+ if (strings.HasPrefix(call, "systemctl enable") || strings.HasPrefix(call, "systemctl start")) && (strings.Contains(call, "system-update") || strings.Contains(call, "system-recover")) {
+ t.Fatal("rearmed automatic update", call)
+ }
+ }
+ for path, want := range map[string]string{envPath: "EXISTING=value\n", certPath: "preserved cert"} {
+ got, err := os.ReadFile(path)
+ if err != nil || string(got) != want {
+ t.Fatal("restart-time configuration changed", path, err)
+ }
+ }
+ for _, u := range []string{systemUpdatePathUnit, "carlos-system-update.service", systemRecoverUnit} {
+ to, err := os.Readlink(filepath.Join(f.a.etcDir, "systemd/system", u))
+ if err != nil || to != "/dev/null" {
+ t.Fatal("apply/recovery mask lost", u)
+ }
+ }
+ })
+ }
+}
+
+func TestGroupMaintenanceInitialChannelInstall(t *testing.T) {
+ m, _ := maintenanceFixture(t)
+ f := newChannelFixture(t, "")
+ f.a.etcDir = m.a.etcDir
+ f.a.groupMaintenance = m.a.groupMaintenance
+ f.edgeStartedThisBoot = false
+ f.in.group = true
+ if _, err := f.in.run(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ if !groupInstallationConsumed(f.a.etcDir) {
+ t.Fatal("edge could start without consumed initial permission")
+ }
+ if _, err := f.in.run(t.Context()); err == nil {
+ t.Fatal("direct reentry reused first boot")
+ }
+}
+
+func TestGroupMaintenanceArtifactLink(t *testing.T) {
+ f, _ := maintenanceFixture(t)
+ path := systemBinaryPath(f.a.optDir)
+ if err := os.Rename(path, path+".real"); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(path+".real", path); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.a.restartEdge(); err == nil || len(f.calls) != 0 {
+ t.Fatal("followed artifact link", err, f.calls)
+ }
+}
diff --git a/internal/host/installchannel.go b/internal/host/installchannel.go
index 721cc1fad..3ec91595b 100644
--- a/internal/host/installchannel.go
+++ b/internal/host/installchannel.go
@@ -280,11 +280,15 @@ func (in channelInstall) run(ctx context.Context) (channelInstalled, error) {
if err := flockExclusiveNonblock(lock); err != nil {
return channelInstalled{}, fmt.Errorf("an update is running on this box, so nothing was installed: %w", err)
}
+ a.resetGroupMaintenance()
return in.install(ctx)
}
func (in channelInstall) install(ctx context.Context) (channelInstalled, error) {
a := in.a
+ if err := a.requireGroupInstall(); err != nil {
+ return channelInstalled{}, err
+ }
var pub ed25519.PublicKey
open := a.openStore
a.openStore = func(ctx context.Context) (release.Store, ed25519.PublicKey, error) {
@@ -313,6 +317,9 @@ func (in channelInstall) install(ctx context.Context) (channelInstalled, error)
if !ok {
return got, fmt.Errorf("the %s channel names %s with no artifact for %s, so nothing was installed", a.channel, p.Current.Version, a.platform)
}
+ if err := a.groupInstallTarget(art.SHA256); err != nil {
+ return got, err
+ }
if in.group && in.expectedRelease != "" && in.expectedRelease != p.Current.ReleaseTag && in.expectedRelease != art.SHA256 {
return got, errGroupLaunch
}
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go
index 1be22c4a4..5df5d2909 100644
--- a/internal/host/systemapply.go
+++ b/internal/host/systemapply.go
@@ -234,10 +234,11 @@ func productionSysOps() sysOps {
}
type systemApplier struct {
- floorAlerted bool
- rootMoves rootFloorIdentitySource
- participation *rootparticipation.Ledger
- floor *hostfloor.Disk
+ groupMaintenance *groupMaintenance
+ floorAlerted bool
+ rootMoves rootFloorIdentitySource
+ participation *rootparticipation.Ledger
+ floor *hostfloor.Disk
// floorHook, when set, decides legacy or floor-guarded state once Run
// holds the apply lock, so a concurrent run's marker write is never read.
floorHook func(*systemApplier) error
@@ -301,7 +302,9 @@ func (a *systemApplier) Run(ctx context.Context, recover bool) (retErr error) {
}
}
}()
- reapStagingWrites(a.optDir, a.dataDir, a.etcDir, a.ops.logf)
+ if !groupMarkerPresent(a.etcDir) {
+ reapStagingWrites(a.optDir, a.dataDir, a.etcDir, a.ops.logf)
+ }
if err := os.MkdirAll(a.rootDir(), 0o755); err != nil {
return err
}
@@ -327,6 +330,13 @@ 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
}
+ a.resetGroupMaintenance()
+ if err := a.requireGroupMaintenance("check"); err != nil {
+ return err
+ }
+ if groupMarkerPresent(a.etcDir) {
+ reapStagingWrites(a.optDir, a.dataDir, a.etcDir, a.ops.logf)
+ }
if a.floorHook != nil {
if err := a.floorHook(a); err != nil {
return err
@@ -414,6 +424,9 @@ func (a *systemApplier) Run(ctx context.Context, recover bool) (retErr error) {
if err != nil {
return a.record(req, err)
}
+ if err := a.groupStageDigest(p.Current.Artifacts[a.platform].SHA256); err != nil {
+ return err
+ }
// The moves protocol floor (moves spec §11), written to disk from the
// store before anything is staged, so every check below and every later
// recovery enforces what is published.
@@ -550,6 +563,9 @@ func (a *systemApplier) waitForLock(lock *os.File) (bool, error) {
// box-changing dance — each step journaled before it happens, and any
// failure from the quiesce on going to the rollback of step 13.
func (a *systemApplier) install(ctx context.Context, req systemRequest, p *release.SystemPointer, staged string) error {
+ if err := a.groupTarget(staged, false); err != nil {
+ return err
+ }
target := p.Current.Version
if err := a.guardImage(staged); err != nil {
return err
@@ -769,6 +785,9 @@ func (a *systemApplier) rearmPending() {
// if the step they were paused for is refused. When their state cannot be
// read, all of them are returned: active is what an armed box has.
func (a *systemApplier) quiesce() []string {
+ if err := a.requireGroupMaintenance("mutation"); err != nil {
+ return nil
+ }
var triggers []string
for _, u := range systemQuiesceUnits {
if strings.HasSuffix(u, ".timer") || strings.HasSuffix(u, ".path") {
@@ -795,6 +814,12 @@ func (a *systemApplier) quiesce() []string {
// rearm starts units again (nothing to do for none).
func (a *systemApplier) rearm(units []string) error {
+ if err := a.requireGroupMaintenance("mutation"); err != nil {
+ return err
+ }
+ if groupMarkerPresent(a.etcDir) {
+ units = groupManualUnits(units)
+ }
if len(units) == 0 {
return nil
}
@@ -1080,6 +1105,9 @@ func (e activationDeferred) Unwrap() error { return e.error }
// since reading it runs a binary. A refusal or deferral comes back typed;
// fn's own error comes back as it is.
func (a *systemApplier) activationGuard(ctx context.Context, target, running string, fn func(context.Context) error) error {
+ if err := a.requireGroupMaintenance("mutation"); err != nil {
+ return err
+ }
guard := func(ctx context.Context) error {
if _, required, err := a.rootMoves.read(); err != nil {
return err
@@ -1098,6 +1126,9 @@ func (a *systemApplier) activationGuard(ctx context.Context, target, running str
if a.beforeSwap != nil {
a.beforeSwap()
}
+ if err := a.requireGroupMaintenance("mutation"); err != nil {
+ return err
+ }
return fn(ctx)
}
locked := false
@@ -1258,6 +1289,9 @@ func (a *systemApplier) prevBuild(ctx context.Context) string {
// in <dir>/plan.json next to them, so a later step can pick up the whole
// staging (stagedPlan) without exec'ing the binary a second time.
func (a *systemApplier) stagePlan(ctx context.Context, binary, dir string) (bootstrapPlan, []string, error) {
+ if err := a.groupExecutable(binary); err != nil {
+ return bootstrapPlan{}, nil, err
+ }
os.RemoveAll(dir)
if err := os.MkdirAll(dir, 0o700); err != nil {
return bootstrapPlan{}, nil, err
@@ -1378,6 +1412,15 @@ func (a *systemApplier) journal(j systemJournal) error {
// next boot — then daemon-reload. Never the staging root's data/: it holds
// a 0-byte registry.db.
func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, remove []string) error {
+ if err := a.requireGroupMaintenance("mutation"); err != nil {
+ return err
+ }
+ if groupMarkerPresent(a.etcDir) {
+ remove = groupManualUnits(remove)
+ if err := preserveGroupUnits(a.etcDir); err != nil {
+ return err
+ }
+ }
claimSettings, settingsErr := readClaimUnitSettings(filepath.Join(a.etcDir, "carlos", "host.env"))
if settingsErr != nil {
a.ops.logf("system apply: instance-control unit settings: %v", settingsErr)
@@ -1409,6 +1452,9 @@ func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, rem
return err
}
for _, e := range entries {
+ if groupMarkerPresent(a.etcDir) && groupAutomaticUnit(e.Name()) {
+ continue
+ }
if e.IsDir() {
continue
}
@@ -1500,6 +1546,9 @@ func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, rem
// restartEdge resets the failure counter FIRST — a unit that hit its start
// limit refuses restart, and so would the rollback — then restarts.
func (a *systemApplier) restartEdge() error {
+ if err := a.requireGroupMaintenance("mutation"); err != nil {
+ return err
+ }
a.ops.systemctl("reset-failed", systemEdgeUnit)
_, err := a.ops.systemctl("restart", systemEdgeUnit)
return err
@@ -1536,6 +1585,9 @@ func (a *systemApplier) restartEdge() error {
// systemctl. reset-failed first, as restartEdge does, so a unit that hit
// its start limit can be restarted at all.
func (a *systemApplier) restartInstanceControl() error {
+ if err := a.requireGroupMaintenance("mutation"); err != nil {
+ return err
+ }
if _, err := os.Stat(filepath.Join(a.etcDir, "systemd", "system", systemControlUnit)); err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
@@ -1566,6 +1618,9 @@ func (a *systemApplier) restartInstanceControl() error {
// a failure of the update — the edge, the binary and the gate are all fine —
// and `carlos relay status` is where a dead region is meant to be read.
func (a *systemApplier) restartRelay() {
+ if err := a.requireGroupMaintenance("mutation"); err != nil {
+ return
+ }
a.ops.systemctl("reset-failed", systemRelayUnit)
if _, err := a.ops.systemctl("restart", systemRelayUnit); err != nil {
a.ops.logf("system apply: relay restart: %v", err)
@@ -1738,6 +1793,15 @@ func (a *systemApplier) gateCheck(ctx context.Context, target string) (string, e
// than the relay. Now the list comes from the target build, so the guarantee
// is enforced here instead, explicitly.
func (a *systemApplier) arm(plan bootstrapPlan) error {
+ if err := a.requireGroupMaintenance("mutation"); err != nil {
+ return err
+ }
+ if groupMarkerPresent(a.etcDir) {
+ plan.Enabled = groupManualUnits(plan.Enabled)
+ if plan.Armed != nil {
+ plan.Armed = groupManualUnits(plan.Armed)
+ }
+ }
// plan.Armed is the TARGET build's answer to "and which of these get a
// start" (discussion #118). Preferring it is what lets a build introduce
// a unit that must be started at apply time rather than at the next
@@ -1786,6 +1850,9 @@ func (a *systemApplier) arm(plan bootstrapPlan) error {
// build's, restoring them again would change nothing, and the box needs a
// human rather than a loop.
func (a *systemApplier) rollback(ctx context.Context, req systemRequest, reason string, j *systemJournal) error {
+ if err := a.groupTarget(systemPrevPath(a.optDir), true); err != nil {
+ return err
+ }
a.ops.logf("system apply: %s %s: rolling back: %s", a.channel, j.Target, reason)
failed := func(what string, err error) error {
_ = a.writeResult(req, systemOutcomeRollbackFailed, reason+"; "+what+": "+err.Error())
@@ -1859,6 +1926,9 @@ func (a *systemApplier) rollback(ctx context.Context, req systemRequest, reason
// it comes up at the next boot. No restart, no start: what to do about the
// running edge is the caller's, and at boot the answer is nothing.
func (a *systemApplier) restoreFiles(ctx context.Context, j *systemJournal) (bootstrapPlan, error) {
+ if err := a.groupTarget(systemPrevPath(a.optDir), true); err != nil {
+ return bootstrapPlan{}, err
+ }
prev := systemPrevPath(a.optDir)
if err := a.guardImage(prev); err != nil {
return bootstrapPlan{}, err
@@ -1939,6 +2009,9 @@ func (a *systemApplier) restoreFiles(ctx context.Context, j *systemJournal) (boo
if err := a.installUnits(ctx, prevDir, j.UnitsAdded); err != nil {
return bootstrapPlan{}, err
}
+ if groupMarkerPresent(a.etcDir) {
+ plan.Enabled = groupManualUnits(plan.Enabled)
+ }
if len(plan.Enabled) > 0 {
if _, err := a.ops.systemctl(append([]string{"enable"}, plan.Enabled...)...); err != nil {
return bootstrapPlan{}, err
@@ -2006,10 +2079,19 @@ func copyFileDurable(src, dst string, mode os.FileMode) error {
// It reports whether it moved the box: a run that recovered has written the
// result it answers with, and does not then go on to apply a request.
func (a *systemApplier) recoverIfNeeded(ctx context.Context) (bool, error) {
+ if err := a.requireGroupMaintenance("check"); err != nil {
+ return false, err
+ }
j, err := readSystemJournal(a.optDir)
if err != nil || j == nil {
return false, err
}
+ if groupMarkerPresent(a.etcDir) {
+ if err := a.groupTarget(systemPrevPath(a.optDir), true); err != nil {
+ return false, err
+ }
+ j.Phase = systemPhaseInstalled
+ }
// The result belongs to the promote being recovered, which the journal
// names in full. The request is used only when it is that same promote,
// version and promoted_at both: a re-promote of the same version is a
@@ -2091,6 +2173,9 @@ func (a *systemApplier) recoverIfNeeded(ctx context.Context) (bool, error) {
// --no-block: this can be running as the edge's own OnFailure=
// handler, and a blocking restart of the unit that triggered it
// would wait on the job that is waiting on this one.
+ if err := a.requireGroupMaintenance("rollback"); err != nil {
+ return false, err
+ }
if _, err := a.ops.systemctl("restart", "--no-block", systemEdgeUnit); err != nil {
return false, fmt.Errorf("system apply: recovery: restart: %w", err)
}
@@ -2227,6 +2312,9 @@ func carlosVersionOf(out string) string {
// verifies the copy's sha against the pointer, makes it executable, and
// runs its `version`. Nothing under /data is read after the copy.
func (a *systemApplier) stageCandidate(ctx context.Context, p *release.SystemPointer, req systemRequest) (string, error) {
+ if err := a.groupStageDigest(p.Current.Artifacts[a.platform].SHA256); err != nil {
+ return "", err
+ }
art, ok := p.Current.Artifacts[a.platform]
if !ok {
return "", fmt.Errorf("pointer names no artifact for %s", a.platform)
diff --git a/internal/host/systemleg.go b/internal/host/systemleg.go
index 6abbc9c94..dca443289 100644
--- a/internal/host/systemleg.go
+++ b/internal/host/systemleg.go
@@ -76,6 +76,9 @@ type systemPending struct {
const systemObserveEvery = time.Hour
func newSystemLeg(store release.Store, pub ed25519.PublicKey, getenv func(string) string, dataDir, optDir string) *systemLeg {
+ if groupReferenced(getenv) || groupMarkerPresent("/etc") {
+ return nil
+ }
channel, invalid := systemChannel(getenv)
l := &systemLeg{
store: store, pub: pub, channel: channel,
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go
index 20ab61df9..edae092d9 100644
--- a/internal/host/systemunits.go
+++ b/internal/host/systemunits.go
@@ -54,6 +54,11 @@ var systemUnitFiles = []string{"carlos-system-update.path", "carlos-system-updat
// failure to report, and probe asks the two QUESTIONS, where non-zero is
// half the answer (see the block below).
func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...string) (string, error), logf func(string, ...any)) {
+ a := &systemApplier{etcDir: etcDir, optDir: filepath.Dir(filepath.Dir(filepath.Dir(lockPath))), ops: productionSysOps()}
+ ensureSystemUnitsWithGuard(etcDir, lockPath, systemctl, probe, logf, a)
+}
+func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(args ...string) (string, error), logf func(string, ...any), a *systemApplier) {
+
if err := os.MkdirAll(filepath.Dir(lockPath), 0o755); err != nil {
logf("adopt: system units: %v", err)
return
@@ -74,6 +79,26 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
return
}
+ a.resetGroupMaintenance()
+ group := groupMarkerPresent(etcDir)
+ if group {
+ call := systemctl
+ systemctl = func(args ...string) (string, error) {
+ if err := a.requireGroupMaintenance("repair"); err != nil {
+ return "", err
+ }
+ return call(args...)
+ }
+ if err := a.requireGroupMaintenance("repair"); err != nil {
+ logf("%v", err)
+ return
+ }
+ if err := preserveGroupUnits(etcDir); err != nil {
+ logf("%v", err)
+ return
+ }
+ }
+
claimSettings, settingsErr := readClaimUnitSettings(filepath.Join(etcDir, "carlos", "host.env"))
if settingsErr != nil {
logf("adopt: instance-control unit settings: %v", settingsErr)
@@ -108,6 +133,10 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
// unit: it prints a state word even for a unit systemd has never heard
// of, so no word at all means the question could not be asked — no
// binary, or an exec that failed outright.
+ if group {
+ active = "active"
+ enabled = "enabled"
+ }
isActive := parseIsActive(active)
ctlActive := parseIsActive(ctlActiveOut)
dbrActive := parseIsActive(dbrActiveOut)
@@ -132,6 +161,9 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
isEnabled := parseIsEnabled(enabled)
missing := false
for _, u := range systemUnitFiles {
+ if group && groupAutomaticUnit(u) {
+ continue
+ }
if _, err := os.Stat(filepath.Join(unitDir, u)); err != nil {
missing = true
}
@@ -167,6 +199,9 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
return
}
for _, u := range systemUnitFiles {
+ if group && groupAutomaticUnit(u) {
+ continue
+ }
// A host.env this pass cannot parse says nothing about the claim
// (6b-N2): a control unit rendered for an enabled box stays as it is.
if u == claimControlUnit && settingsErr != nil && bytes.Contains(installed, []byte(claimControlEnvironment)) {
@@ -183,6 +218,9 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
}
}
arm := ensureSystemArmed
+ if group {
+ arm = groupManualUnits(arm)
+ }
if !dbrWant {
arm = slices.DeleteFunc(slices.Clone(arm), func(u string) bool { return u == dbReadSocketUnit })
if !dbrDark {