carlos / platform Public

activator: an exit record with no code reads systemd's ExecMainCode/ExecMainStatus

On systemd 257 with PrivatePIDs (r10r, Task 11 end-to-end, #366) a
SIGKILLed unit's main process is killed before systemd records its exit,
so ExecStopPost runs with no EXIT_CODE/EXIT_STATUS and SERVICE_RESULT
"success". systemctl show still holds ExecMainCode=1 ExecMainStatus=137.

observe now fills a record whose code is empty from a new UnitMainExit
seam (systemctl show -p InvocationID,ExecMainCode,ExecMainStatus, beside
UnitState and ControlGroupOf), only for the handle's own invocation:
1 exited/status, 2 killed and 3 dumped with the signal named as
workerSignals names it, and a "success" result over anything but exit 0
becomes systemd's word for it (exit-code, signal, core-dump).

Both readers of the record had the gap: a worker's observer logged "ended
with no exit status to tell", and a web generation (run, gen, sidecar
alike) told the member "instance exited (exit 0)" at info. The release
cmd unit did not: its status is root's systemctl show of ExecMainCode and
ExecMainStatus (instancectl cmdStatusOf), never the record.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 60edee133af50e090ca628e7b0675c9a1fcb338f parent a66482c
4 files changed, +222 −1
  • internal/activator/backend_exec.go +4 −0
  • internal/activator/control.go +29 −0
  • internal/activator/rootfsworkers_backend_test.go +122 −1
  • internal/activator/unitproc.go +67 −0
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 3c75bd141..3bde4f030 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -192,6 +192,10 @@ type ExecBackend struct {
// UnitState answers `systemctl show` for the observer (design §6.5).
// Nil: systemctlUnitState, the real systemctl binary.
UnitState UnitState
+ // UnitMainExit answers how systemd recorded a unit's main process's
+ // end, for an exit record that carries no code (unitMainExitOf). Nil:
+ // systemctlUnitMainExit, the real systemctl binary.
+ UnitMainExit UnitMainExit
// CgroupEvents reads a unit's cgroup.events for the observer and for a
// seed's cgroup-empty wait. Nil: cgroupEventsUnder("/sys/fs/cgroup"),
// or CgroupRoot when set.
diff --git a/internal/activator/control.go b/internal/activator/control.go
index 9c6fadcb6..92cafa34c 100644
--- a/internal/activator/control.go
+++ b/internal/activator/control.go
@@ -116,6 +116,35 @@ func systemctlUnitState(ctx context.Context, unit string) (string, string, error
return active, inv, nil
}
+// UnitMainExit answers `systemctl show -p
+// InvocationID,ExecMainCode,ExecMainStatus <unit>`, which needs no
+// privilege: how systemd recorded the end of the unit's main process, and
+// the invocation it belongs to. The code is a number (0 none recorded, 1
+// exited, 2 killed, 3 dumped), the status the exit code or the signal's
+// number.
+type UnitMainExit func(ctx context.Context, unit string) (invocation, code, status string, err error)
+
+func systemctlUnitMainExit(ctx context.Context, unit string) (string, string, string, error) {
+ out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "InvocationID,ExecMainCode,ExecMainStatus", unit).Output()
+ if err != nil {
+ return "", "", "", err
+ }
+ var inv, code, status string
+ for _, line := range strings.Split(string(out), "\n") {
+ if k, v, ok := strings.Cut(line, "="); ok {
+ switch k {
+ case "InvocationID":
+ inv = strings.TrimSpace(v)
+ case "ExecMainCode":
+ code = strings.TrimSpace(v)
+ case "ExecMainStatus":
+ status = strings.TrimSpace(v)
+ }
+ }
+ }
+ return inv, code, status, nil
+}
+
// CgroupEvents reads the unit's cgroup.events under the host slice. cgroup
// v2 files are world-readable, so the agent reads them as carlos, as the
// sampler does. An absent directory is the unit's cgroup already removed.
diff --git a/internal/activator/rootfsworkers_backend_test.go b/internal/activator/rootfsworkers_backend_test.go
index daf7be644..4cf10f7d9 100644
--- a/internal/activator/rootfsworkers_backend_test.go
+++ b/internal/activator/rootfsworkers_backend_test.go
@@ -33,6 +33,9 @@ type workerUnits struct {
m map[string]workerUnitState
read []string // every unit whose cgroup was read
stopEmpties bool
+ // main is a unit's ExecMainCode and ExecMainStatus, with the
+ // invocation they belong to (setMain); a unit not set has none.
+ main map[string][3]string
}
type workerUnitState struct {
@@ -60,6 +63,29 @@ func (u *workerUnits) state(_ context.Context, unit string) (string, string, err
return s.active, s.inv, nil
}
+// setMain sets what systemd holds of unit's main process: the invocation,
+// ExecMainCode and ExecMainStatus.
+func (u *workerUnits) setMain(unit, inv, code, status string) {
+ u.mu.Lock()
+ if u.main == nil {
+ u.main = map[string][3]string{}
+ }
+ u.main[unit] = [3]string{inv, code, status}
+ u.mu.Unlock()
+}
+
+// mainExit is the fake UnitMainExit: an unset unit answers as systemd
+// does for one that never ran, code and status 0.
+func (u *workerUnits) mainExit(_ context.Context, unit string) (string, string, string, error) {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ m, ok := u.main[unit]
+ if !ok {
+ return "", "0", "0", nil
+ }
+ return m[0], m[1], m[2], nil
+}
+
func (u *workerUnits) events(_ string, unit string) (bool, bool, error) {
u.mu.Lock()
defer u.mu.Unlock()
@@ -96,7 +122,7 @@ func newWorkerBackend(t *testing.T) (*ExecBackend, *fakeControl, registry.Route,
b, ctl := newRootfsBackend(t)
b.GenContainment = true
units := newWorkerUnits()
- b.UnitState, b.CgroupEvents = units.state, units.events
+ b.UnitState, b.CgroupEvents, b.UnitMainExit = units.state, units.events, units.mainExit
ctl.stopHook = units.stopped
return b, ctl, rootfsRoute(b), units
}
@@ -586,6 +612,101 @@ func TestRootfsWorkerExitIsSilentToMembers(t *testing.T) {
})
}
+// Task 11 end-to-end (#366): on systemd 257 with PrivatePIDs a SIGKILLed
+// unit's ExecStopPost gets no EXIT_CODE or EXIT_STATUS, so its record says
+// "success" with no code, while systemd still holds the main process's
+// end (ExecMainCode=1, ExecMainStatus=137). An empty code is read from
+// systemd, for the same invocation only, for a worker and for web alike.
+func TestAnExitRecordWithNoCodeReadsSystemd(t *testing.T) {
+ t.Parallel()
+ noCode := instancectl.ExitRecord{Invocation: "inv1", Result: "success"}
+ worker := func(t *testing.T, mainInv, code, status string) (instancectl.ExitRecord, bool) {
+ t.Helper()
+ b, ctl, rt, units := newWorkerBackend(t)
+ sink := &rootfsSink{}
+ b.Logs = sink
+ web, g := startWorkerWeb(t, b, ctl, rt, units, "")
+ unit := instancectl.WorkerUnitName(rt.Host, "jobs")
+ units.set(unit, "active", "inv1", true)
+ wp, err := b.LaunchRootfsWorker(context.Background(), rt, "jobs", g, web)
+ if err != nil {
+ t.Fatal(err)
+ }
+ up := wp.(*unitProc)
+ raw, err := json.Marshal(noCode)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(up.runDir, instancectl.WorkerExitRecordName("jobs", "inv1")), raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ units.setMain(unit, mainInv, code, status)
+ units.set(unit, "inactive", "inv1", false)
+ waitFor(t, "the worker to exit", wp.Exited)
+ if msgs := sink.msgs(); len(msgs) != 0 {
+ t.Errorf("a worker's exit told the member %q", msgs)
+ }
+ return up.WorkerExit()
+ }
+ for _, tc := range []struct {
+ name, code, status string
+ want instancectl.ExitRecord
+ status137 bool
+ }{
+ {"killed under PrivatePIDs: exited 137", "1", "137", instancectl.ExitRecord{Invocation: "inv1", Result: "exit-code", Code: "exited", Status: "137"}, true},
+ {"killed by KILL", "2", "9", instancectl.ExitRecord{Invocation: "inv1", Result: "signal", Code: "killed", Status: "KILL"}, true},
+ {"dumped by SEGV", "3", "11", instancectl.ExitRecord{Invocation: "inv1", Result: "core-dump", Code: "dumped", Status: "SEGV"}, false},
+ {"a clean exit stays a success", "1", "0", instancectl.ExitRecord{Invocation: "inv1", Result: "success", Code: "exited", Status: "0"}, false},
+ {"no exit recorded", "0", "0", noCode, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ got, ok := worker(t, "inv1", tc.code, tc.status)
+ if !ok || got != tc.want {
+ t.Fatalf("WorkerExit = %+v, %v; want %+v", got, ok, tc.want)
+ }
+ p := &fakeWorkerProc{}
+ p.exit(got.Code, got.Status)
+ if n, ok := workerExitStatus(p); tc.status137 && (!ok || n != 137) {
+ t.Errorf("workerExitStatus = %d, %v; want 137", n, ok)
+ }
+ })
+ }
+ t.Run("another invocation's end is not ours", func(t *testing.T) {
+ t.Parallel()
+ got, ok := worker(t, "inv2", "1", "137")
+ if !ok || got != noCode {
+ t.Fatalf("WorkerExit = %+v, %v; want the record as written", got, ok)
+ }
+ })
+ t.Run("web", func(t *testing.T) {
+ t.Parallel()
+ b, ctl, rt, units := newWorkerBackend(t)
+ sink := &rootfsSink{}
+ b.Logs = sink
+ web, _ := startWorkerWeb(t, b, ctl, rt, units, "")
+ raw, err := json.Marshal(noCode)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(web.runDir, instancectl.GenExitRecordName(7, "inv1")), raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ unit := instancectl.RootfsGenUnitName(rt.Host, 7)
+ units.setMain(unit, "inv1", "1", "137")
+ units.set(unit, "inactive", "inv1", false)
+ waitFor(t, "web to exit", web.Exited)
+ if msgs := sink.msgs(); !slices.Equal(msgs, []string{"instance exited: exit 137 (exit-code)"}) {
+ t.Errorf("web's exit told the member %q, want exit 137", msgs)
+ }
+ sink.mu.Lock()
+ defer sink.mu.Unlock()
+ if len(sink.events) == 1 && sink.events[0].level != "warn" {
+ t.Errorf("web's exit 137 at %q, want warn", sink.events[0].level)
+ }
+ })
+}
+
func TestRootfsWorkerRefusalsStartNothing(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
diff --git a/internal/activator/unitproc.go b/internal/activator/unitproc.go
index a368938d7..cf4bc2f97 100644
--- a/internal/activator/unitproc.go
+++ b/internal/activator/unitproc.go
@@ -8,6 +8,7 @@ import (
"log"
"os"
"path/filepath"
+ "strconv"
"sync/atomic"
"time"
@@ -467,6 +468,9 @@ func (b *ExecBackend) observe(p *unitProc) {
if !exists || !populated {
if terminal {
rec, ok := p.readRecord()
+ if ok && rec.Code == "" {
+ rec = b.unitMainExitOf(p, rec)
+ }
if p.worker != "" {
// A worker's end is the supervisor's to tell (W1b):
// the record is kept for it, never worded here.
@@ -501,6 +505,69 @@ func (b *ExecBackend) observe(p *unitProc) {
}
}
+// unitMainExitOf fills rec, an exit record with no code, from how systemd
+// recorded the end of p's main process, when that is p's own invocation.
+// On systemd 257 with PrivatePIDs a SIGKILLed unit's main process is killed
+// before systemd records its exit, so ExecStopPost runs with no EXIT_CODE
+// or EXIT_STATUS and SERVICE_RESULT "success" (Task 11, #366), while
+// ExecMainCode and ExecMainStatus still hold it. A read that fails, names
+// another invocation or recorded no exit leaves rec as it is.
+func (b *ExecBackend) unitMainExitOf(p *unitProc, rec instancectl.ExitRecord) instancectl.ExitRecord {
+ read := b.UnitMainExit
+ if read == nil {
+ read = systemctlUnitMainExit
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ inv, code, status, err := read(ctx, p.unit)
+ if err != nil {
+ log.Printf("activator: %s: main exit of %s: %v", p.rt.Host, p.unit, err)
+ return rec
+ }
+ if inv == "" || inv != p.invocation {
+ return rec
+ }
+ return withMainExit(rec, code, status)
+}
+
+// withMainExit is rec with systemd's ExecMainCode and ExecMainStatus as its
+// code and status, the words systemd gives ExecStopPost: 1 (CLD_EXITED) is
+// exited with the exit code; 2 (CLD_KILLED) and 3 (CLD_DUMPED) are killed
+// and dumped with the signal's name where workerSignals knows it, its
+// number otherwise. A result of "success" (or none) over anything but exit
+// 0 becomes systemd's own word for it. Any other code recorded no exit,
+// and rec is returned as it is.
+func withMainExit(rec instancectl.ExitRecord, code, status string) instancectl.ExitRecord {
+ n, err := strconv.Atoi(status)
+ if err != nil || n < 0 {
+ return rec
+ }
+ var result string
+ switch code {
+ case "1", "exited":
+ rec.Code, rec.Status, result = "exited", status, "exit-code"
+ if n == 0 {
+ result = "success"
+ }
+ case "2", "3", "killed", "dumped":
+ rec.Code, rec.Status, result = "killed", status, "signal"
+ if code == "3" || code == "dumped" {
+ rec.Code, result = "dumped", "core-dump"
+ }
+ for name, num := range workerSignals {
+ if num == n {
+ rec.Status = name
+ }
+ }
+ default:
+ return rec
+ }
+ if rec.Result == "" || rec.Result == "success" {
+ rec.Result = result
+ }
+ return rec
+}
+
// exitLine words the event line from the advisory record observe already
// read once and passes to both exitLine and exitLevel, so the two can
// never disagree from reading the file twice with something changing in