host, activator, instancectl: bound every systemctl and journalctl call
A stalled systemd (PID 1 waiting on a child that never execs, a D-Bus that never answers) made a host loop hang forever while holding reconcileMu or configSyncMu: 45 systemctl and journalctl calls in the root binary's graph ran with no deadline or only the caller's. internal/systemd.Command now runs them all, under the caller's context and a bound per verb: QueryTimeout (30 s, above sd-bus's own 25 s method call timeout) for show, is-active, list-units, cat and journalctl; ControlTimeout (5 min, above the longest unit stop of 170 s plus the longest waited-on start of 120 s) for every verb that waits on a job. The system apply and recovery, which restart carlos-edge through the drain and, under the guard, the recovery unit, use 18 min (below the update unit's 20 min). At the bound the process is killed and the error is a *TimeoutError naming the verb and units; it reads as a temporary deadline, so adopt does not poison a version over a slow restart. A caller's own earlier deadline keeps os/exec's error, as before. The constructor is named Command so the root-read census still counts each caller's site; every unit keeps its disposition. TestSystemctlCallsAreBounded fails on any root-graph file that names systemctl or journalctl as a program outside internal/systemd. The gVisor probe's journal tail moves from Server.Run to a Server.Journal seam so the program name lives in the helper.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
35 files changed,
+791
−84
internal/activator/backend_unit.go+2 −2internal/activator/control.go+5 −4internal/caps/converge.go+6 −2internal/demobuild/unit.go+4 −6internal/hairpin/native_linux.go+2 −1internal/host/adopt_advice.go+2 −1internal/host/agent.go+6 −6internal/host/bootstrap.go+2 −1internal/host/claimfilesseed_delegation_linux.go+2 −2internal/host/claimjournal_migration_linux.go+2 −2internal/host/claimlaunch_production.go+2 −2internal/host/claimstop_production.go+2 −2internal/host/claimstop_writers_linux.go+3 −3internal/host/claimunit_socket_migration_linux.go+2 −2internal/host/dbreads_linux.go+3 −2internal/host/egress_source.go+2 −2internal/host/group_maintenance_verbs_linux.go+5 −6internal/host/probes.go+5 −5internal/host/restartwatch.go+3 −3internal/host/rootgeneration_services_linux.go+2 −2internal/host/runscensure.go+2 −2internal/host/systemapply.go+16 −2internal/host/systemunits.go+2 −2internal/host/unitops.go+4 −4internal/host/unitsettle.go+5 −5internal/instancectl/gvisor_claim_rootrunner_linux_test.go+4 −0internal/instancectl/gvisorprobe.go+2 −2internal/instancectl/gvisorprobe_flow_linux_test.go+4 −4internal/instancectl/hairpin.go+2 −2internal/instancectl/peer_linux.go+3 −2internal/instancectl/server.go+10 −1internal/ops/ops.go+2 −2internal/systemd/command.go+273 −0internal/systemd/command_test.go+216 −0internal/systemd/guard_test.go+184 −0
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go| index 63edbb2a6..c901a2e5b 100644 |
| --- a/internal/activator/backend_unit.go |
| +++ b/internal/activator/backend_unit.go |
| @@ -53,7 +53,6 @@ import ( |
| "io" |
| "net" |
| "net/http" |
| - "os/exec" |
| "strings" |
| "sync" |
| "time" |
| @@ -65,6 +64,7 @@ import ( |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/upstreamguard" |
| ) |
| @@ -110,7 +110,7 @@ func (b *UnitBackend) systemctl(ctx context.Context, verb, unit string) error { |
| if b.Systemctl != nil { |
| return b.Systemctl(ctx, verb, unit) |
| } |
| - out, err := exec.CommandContext(ctx, "systemctl", verb, unit).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, verb, unit).CombinedOutput(ctx) |
| if err != nil { |
| return fmt.Errorf("systemctl %s %s: %v: %s", verb, unit, err, strings.TrimSpace(string(out))) |
| } |
diff --git a/internal/activator/control.go b/internal/activator/control.go| index a4dc01826..c65391361 100644 |
| --- a/internal/activator/control.go |
| +++ b/internal/activator/control.go |
| @@ -10,6 +10,7 @@ import ( |
| "strings" |
| "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // Control is what the exec backend needs from the root instance-control |
| @@ -118,7 +119,7 @@ var _ StagedExeControl = (*instancectl.Client)(nil) |
| type UnitState func(ctx context.Context, unit string) (active, invocation string, err error) |
| func systemctlUnitState(ctx context.Context, unit string) (string, string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "ActiveState,InvocationID", unit).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "ActiveState,InvocationID", unit).Output(ctx) |
| if err != nil { |
| return "", "", unitStateError(err) |
| } |
| @@ -141,7 +142,7 @@ func systemctlUnitState(ctx context.Context, unit string) (string, string, error |
| type UnitsListed func(ctx context.Context, glob string) (string, error) |
| func systemctlUnitsListed(ctx context.Context, glob string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", "list-units", "--all", "--plain", "--no-legend", "--no-pager", glob).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "list-units", "--all", "--plain", "--no-legend", "--no-pager", glob).Output(ctx) |
| if err != nil { |
| return "", unitStateError(err) |
| } |
| @@ -164,7 +165,7 @@ type MainExit struct { |
| } |
| func systemctlUnitMainExit(ctx context.Context, unit string) (MainExit, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "InvocationID,ExecMainCode,ExecMainStatus,SuccessExitStatus", unit).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "InvocationID,ExecMainCode,ExecMainStatus,SuccessExitStatus", unit).Output(ctx) |
| if err != nil { |
| return MainExit{}, unitStateError(err) |
| } |
| @@ -197,7 +198,7 @@ type CgroupEvents func(slice, unit string) (exists, populated bool, err error) |
| type ControlGroupOf func(ctx context.Context, unit string) (string, error) |
| func systemctlControlGroup(ctx context.Context, unit string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "ControlGroup", "--value", unit).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "ControlGroup", "--value", unit).Output(ctx) |
| if err != nil { |
| return "", unitStateError(err) |
| } |
diff --git a/internal/caps/converge.go b/internal/caps/converge.go| index 177d95bcd..68ec9e7e5 100644 |
| --- a/internal/caps/converge.go |
| +++ b/internal/caps/converge.go |
| @@ -19,6 +19,8 @@ import ( |
| "sort" |
| "strconv" |
| "strings" |
| + |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| const ( |
| @@ -1035,7 +1037,8 @@ func (o Ops) systemctl(args ...string) error { |
| if o.Systemctl != nil { |
| return o.Systemctl(args...) |
| } |
| - out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + // Detached: Ops carries no context; the verb's bound is the deadline. |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(systemd.Detached()) |
| if err != nil { |
| return fmt.Errorf("systemctl %s: %v: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) |
| } |
| @@ -1058,7 +1061,8 @@ func (o Ops) query(args ...string) bool { |
| if o.Query != nil { |
| return o.Query(args...) |
| } |
| - return exec.Command("systemctl", args...).Run() == nil |
| + // Detached: Ops carries no context; the verb's bound is the deadline. |
| + return systemd.Command(systemd.Systemctl, args...).Run(systemd.Detached(), nil, nil) == nil |
| } |
| // ensureUser creates the locked, home-less, nologin system user a host_role |
diff --git a/internal/demobuild/unit.go b/internal/demobuild/unit.go| index ebecd28d9..8dbc86ea0 100644 |
| --- a/internal/demobuild/unit.go |
| +++ b/internal/demobuild/unit.go |
| @@ -9,7 +9,6 @@ import ( |
| "io/fs" |
| "log" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -18,6 +17,7 @@ import ( |
| "github.com/carlosframework/platform/internal/execsandbox" |
| "github.com/carlosframework/platform/internal/instancefs" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| var unitRoot = "/run/systemd/system" |
| @@ -76,12 +76,10 @@ func mountName(p string) string { |
| } |
| var systemctl = func(ctx context.Context, args ...string) (string, error) { |
| - c := exec.CommandContext(ctx, "/usr/bin/systemctl", args...) |
| - c.Env = []string{"PATH=/usr/bin:/bin", "LANG=C", "SYSTEMD_COLORS=0", "SYSTEMD_PAGER="} |
| var b limitedLog |
| - c.Stdout = &b |
| - c.Stderr = &b |
| - err := c.Run() |
| + c := systemd.Command(systemd.SystemctlAbsolute, args...) |
| + c.Env = []string{"PATH=/usr/bin:/bin", "LANG=C", "SYSTEMD_COLORS=0", "SYSTEMD_PAGER="} |
| + err := c.Run(ctx, &b, &b) |
| if err != nil { |
| err = fmt.Errorf("systemctl %v: %w: %s", args, err, strings.TrimSpace(string(b.b))) |
| } |
diff --git a/internal/hairpin/native_linux.go b/internal/hairpin/native_linux.go| index 2fb9c409e..4537b119b 100644 |
| --- a/internal/hairpin/native_linux.go |
| +++ b/internal/hairpin/native_linux.go |
| @@ -18,6 +18,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "golang.org/x/sys/unix" |
| ) |
| @@ -75,7 +76,7 @@ func Authenticate(ctx context.Context, conn net.Conn, p Process) error { |
| return Current(ctx, p) |
| } |
| func MainProcess(ctx context.Context) (Process, error) { |
| - raw, err := exec.CommandContext(ctx, "systemctl", "show", "carlos-edge.service", "--property=MainPID", "--property=LoadState").CombinedOutput() |
| + raw, err := systemd.Command(systemd.Systemctl, "show", "carlos-edge.service", "--property=MainPID", "--property=LoadState").CombinedOutput(ctx) |
| fields := map[string]string{} |
| for _, line := range strings.Split(string(raw), "\n") { |
| if k, v, ok := strings.Cut(line, "="); ok { |
diff --git a/internal/host/adopt_advice.go b/internal/host/adopt_advice.go| index dea7fa9df..59ef23c43 100644 |
| --- a/internal/host/adopt_advice.go |
| +++ b/internal/host/adopt_advice.go |
| @@ -14,6 +14,7 @@ import ( |
| "github.com/carlosframework/platform/internal/caps" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // warnBackingMismatch reports hosts whose route claims exec backing |
| @@ -52,7 +53,7 @@ func unitsAreActive(hosts []string) map[string]bool { |
| for _, h := range hosts { |
| args = append(args, "carlos-app@"+h+".service") |
| } |
| - out, _ := exec.Command("systemctl", args...).Output() |
| + out, _ := systemd.Command(systemd.Systemctl, args...).Output(systemd.Detached()) |
| return parseIsActiveBatch(out, hosts) |
| } |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 3283fd277..f850f78e6 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -165,7 +165,6 @@ import ( |
| "net" |
| "net/http" |
| "os" |
| - "os/exec" |
| "os/signal" |
| "path" |
| "path/filepath" |
| @@ -217,6 +216,7 @@ import ( |
| "github.com/carlosframework/platform/internal/rootstate" |
| "github.com/carlosframework/platform/internal/schedule" |
| "github.com/carlosframework/platform/internal/status" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| @@ -5546,7 +5546,7 @@ func makeStartRoute(reg *registry.Registry, startUnit func(unit string) error) f |
| // line; they simply have nothing here to restart, and pick the new version |
| // up on their next wake. |
| func systemctlTryRestart(host string) { |
| - out, err := exec.Command("systemctl", "try-restart", activator.UnitName(host)).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, "try-restart", activator.UnitName(host)).CombinedOutput(systemd.Detached()) |
| if err != nil { |
| log.Printf("adopt: try-restart carlos-app@%s: %v: %s (continuing)", host, err, strings.TrimSpace(string(out))) |
| } |
| @@ -5566,12 +5566,12 @@ func systemctlTryRestart(host string) { |
| // summary line per host; the exit status and systemctl's own words belong in |
| // the journal where an operator greps for the unit name. |
| // |
| -// The unit reaches exec.Command as ONE argv element, so there is no shell for |
| +// The unit reaches systemctl as ONE argv element, so there is no shell for |
| // a name to escape into; the shape rail lives at the write (registry's |
| // ValidUnitName), where a typo can still be reported to the person who typed |
| // it. |
| func systemctlTryRestartUnit(unit string) error { |
| - out, err := exec.Command("systemctl", "try-restart", unit).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, "try-restart", unit).CombinedOutput(systemd.Detached()) |
| if err != nil { |
| log.Printf("adopt: try-restart %s: %v: %s", unit, err, strings.TrimSpace(string(out))) |
| return fmt.Errorf("try-restart %s: %w: %s", unit, err, strings.TrimSpace(string(out))) |
| @@ -5691,9 +5691,9 @@ func agentRollbackUnitRestart(reg *registry.Registry, sys unitSystem, optDir str |
| // nothing, and the caller's one summary line per host must say so while the |
| // exit status and systemd's own words stay in the journal under the unit |
| // name an operator would grep for. Same no-shell shape too: the unit reaches |
| -// exec.Command as ONE argv element. |
| +// systemctl as ONE argv element. |
| func systemctlStartUnit(unit string) error { |
| - out, err := exec.Command("systemctl", "start", unit).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, "start", unit).CombinedOutput(systemd.Detached()) |
| if err != nil { |
| log.Printf("adopt: start %s: %v: %s", unit, err, strings.TrimSpace(string(out))) |
| return fmt.Errorf("start %s: %w: %s", unit, err, strings.TrimSpace(string(out))) |
diff --git a/internal/host/bootstrap.go b/internal/host/bootstrap.go| index e5228f4ce..e00a4d16a 100644 |
| --- a/internal/host/bootstrap.go |
| +++ b/internal/host/bootstrap.go |
| @@ -13,6 +13,7 @@ import ( |
| "github.com/carlosframework/platform/internal/cliflag" |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "embed" |
| "encoding/json" |
| @@ -848,7 +849,7 @@ func bootstrapOwner(owner, group string) (int, int, error) { |
| } |
| func systemctl(args ...string) error { |
| - out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(systemd.Detached()) |
| if err != nil { |
| return fmt.Errorf("systemctl %s: %v: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) |
| } |
diff --git a/internal/host/claimfilesseed_delegation_linux.go b/internal/host/claimfilesseed_delegation_linux.go| index c9d540795..773064cea 100644 |
| --- a/internal/host/claimfilesseed_delegation_linux.go |
| +++ b/internal/host/claimfilesseed_delegation_linux.go |
| @@ -6,10 +6,10 @@ import ( |
| "context" |
| "fmt" |
| "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "golang.org/x/sys/unix" |
| "net" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -19,7 +19,7 @@ import ( |
| func filesSeedEdgePID(ctx context.Context) (int, error) { |
| ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| defer cancel() |
| - b, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", "carlos-edge.service").Output() |
| + b, err := systemd.Command(systemd.Systemctl, "show", "-p", "MainPID", "--value", "carlos-edge.service").Output(ctx) |
| if err != nil { |
| return 0, err |
| } |
diff --git a/internal/host/claimjournal_migration_linux.go b/internal/host/claimjournal_migration_linux.go| index a62b5edb6..9064d0a62 100644 |
| --- a/internal/host/claimjournal_migration_linux.go |
| +++ b/internal/host/claimjournal_migration_linux.go |
| @@ -11,7 +11,6 @@ import ( |
| "fmt" |
| "log" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -19,6 +18,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hostbox" |
| "github.com/carlosframework/platform/internal/safefile" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "golang.org/x/sys/unix" |
| ) |
| @@ -40,7 +40,7 @@ type claimEdgeMaskRecord struct { |
| } |
| var claimSystemctl = func(ctx context.Context, args ...string) ([]byte, error) { |
| - return exec.CommandContext(ctx, "systemctl", args...).Output() |
| + return systemd.Command(systemd.Systemctl, args...).Output(ctx) |
| } |
| func claimEdgeMaskAnchor(token string) string { |
diff --git a/internal/host/claimlaunch_production.go b/internal/host/claimlaunch_production.go| index b4beebc41..3649a4f13 100644 |
| --- a/internal/host/claimlaunch_production.go |
| +++ b/internal/host/claimlaunch_production.go |
| @@ -4,7 +4,6 @@ import ( |
| "context" |
| "net/http" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strings" |
| @@ -13,6 +12,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hostclaim" |
| execlease "github.com/carlosframework/platform/internal/hostexec" |
| "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // ClaimRootWithLaunch is the claim-mode root handler with the isolated |
| @@ -92,7 +92,7 @@ func claimLaunchFor(root ClaimRootHTTP, actor func(context.Context) (hostbox.Act |
| } |
| units := instancectl.ClaimUnits{ |
| Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(ctx) |
| return string(out), err |
| }, |
| CgroupRoot: "/sys/fs/cgroup", |
diff --git a/internal/host/claimstop_production.go b/internal/host/claimstop_production.go| index 883ce1896..176af8633 100644 |
| --- a/internal/host/claimstop_production.go |
| +++ b/internal/host/claimstop_production.go |
| @@ -7,7 +7,6 @@ import ( |
| "encoding/hex" |
| "net" |
| "net/http" |
| - "os/exec" |
| "os/user" |
| "strconv" |
| "strings" |
| @@ -15,6 +14,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hostbox" |
| "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| type StopControllerReader interface { |
| @@ -49,7 +49,7 @@ func NewProductionClaimStopHandler(c ClaimStopCoordinator, j hostbox.StopKernelJ |
| authenticate := func(ctx context.Context, conn net.Conn) (StopPeer, error) { |
| ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| defer cancel() |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", "carlos-edge.service").Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "MainPID", "--value", "carlos-edge.service").Output(ctx) |
| if err != nil { |
| return StopPeer{}, err |
| } |
diff --git a/internal/host/claimstop_writers_linux.go b/internal/host/claimstop_writers_linux.go| index a9334e2b5..9c1a1b424 100644 |
| --- a/internal/host/claimstop_writers_linux.go |
| +++ b/internal/host/claimstop_writers_linux.go |
| @@ -8,7 +8,6 @@ import ( |
| "fmt" |
| "io/fs" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "reflect" |
| "sort" |
| @@ -22,6 +21,7 @@ import ( |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/stopevidence" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // stopKernelRoots are the trees root observes. Production uses the real |
| @@ -388,7 +388,7 @@ func emptyContainmentAt(ctx context.Context, dir, name string) (string, error) { |
| func agentUnitCgroup(ctx context.Context) (string, error) { |
| ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| defer cancel() |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "ControlGroup", "--value", "carlos-edge.service").Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "ControlGroup", "--value", "carlos-edge.service").Output(ctx) |
| if err != nil { |
| return "", err |
| } |
| @@ -433,7 +433,7 @@ func noProcessGroups(ctx context.Context, roots stopKernelRoots, host string, re |
| func rootStopAgentCgroup(ctx context.Context) (string, error) { |
| ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| defer cancel() |
| - raw, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "ControlGroup,Id,Slice,ActiveState", "carlos-edge.service").Output() |
| + raw, err := systemd.Command(systemd.Systemctl, "show", "-p", "ControlGroup,Id,Slice,ActiveState", "carlos-edge.service").Output(ctx) |
| if err != nil { |
| return "", err |
| } |
diff --git a/internal/host/claimunit_socket_migration_linux.go b/internal/host/claimunit_socket_migration_linux.go| index a1fe099bb..85a5ff31d 100644 |
| --- a/internal/host/claimunit_socket_migration_linux.go |
| +++ b/internal/host/claimunit_socket_migration_linux.go |
| @@ -6,7 +6,6 @@ import ( |
| "errors" |
| "net" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -14,6 +13,7 @@ import ( |
| "github.com/carlosframework/platform/internal/rootstate" |
| "github.com/carlosframework/platform/internal/safefile" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "golang.org/x/sys/unix" |
| ) |
| @@ -95,7 +95,7 @@ func captureProductionClaimUnitSocket(ctx context.Context, s claimUnitShape, p c |
| if err != nil { |
| return before, err |
| } |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", p.Unit).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "MainPID", "--value", p.Unit).Output(ctx) |
| if err != nil { |
| return before, err |
| } |
diff --git a/internal/host/dbreads_linux.go b/internal/host/dbreads_linux.go| index e58f7c232..ecf2e4b9b 100644 |
| --- a/internal/host/dbreads_linux.go |
| +++ b/internal/host/dbreads_linux.go |
| @@ -5,9 +5,10 @@ package host |
| import ( |
| "context" |
| "net" |
| - "os/exec" |
| "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| func dialDBReadWorker(ctx context.Context) (net.Conn, error) { |
| @@ -17,7 +18,7 @@ func dialDBReadWorker(ctx context.Context) (net.Conn, error) { |
| // dbReadUnits lists carlos-dbread@ units, readable without privilege. |
| func dbReadUnits(ctx context.Context) (int, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", "list-units", "--all", "--plain", "--no-legend", "--no-pager", "carlos-dbread@*.service").Output() |
| + out, err := systemd.Command(systemd.Systemctl, "list-units", "--all", "--plain", "--no-legend", "--no-pager", "carlos-dbread@*.service").Output(ctx) |
| if err != nil { |
| return 0, err |
| } |
diff --git a/internal/host/egress_source.go b/internal/host/egress_source.go| index 2f66d2993..d08b3b160 100644 |
| --- a/internal/host/egress_source.go |
| +++ b/internal/host/egress_source.go |
| @@ -18,7 +18,6 @@ import ( |
| "errors" |
| "fmt" |
| "log" |
| - "os/exec" |
| "os/user" |
| "path/filepath" |
| "strconv" |
| @@ -32,6 +31,7 @@ import ( |
| "github.com/carlosframework/platform/internal/layout" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // boxWhollyNested: no row is a sidecar member (IsSidecar, Kind "sidecar": |
| @@ -384,7 +384,7 @@ func userUID(name string) (string, bool, error) { |
| // systemctlOutput runs systemctl and returns its combined output. |
| func systemctlOutput(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(ctx) |
| return string(out), err |
| } |
diff --git a/internal/host/group_maintenance_verbs_linux.go b/internal/host/group_maintenance_verbs_linux.go| index d2a2c928b..935c79ae9 100644 |
| --- a/internal/host/group_maintenance_verbs_linux.go |
| +++ b/internal/host/group_maintenance_verbs_linux.go |
| @@ -10,13 +10,14 @@ import ( |
| "errors" |
| "io" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| "time" |
| "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // Open every ancestor by descriptor. Production starts at /; the test anchor |
| @@ -165,13 +166,11 @@ func (b *maintenanceBoundedOutput) Write(p []byte) (int, error) { |
| func maintenanceEdgeProcess(ctx context.Context) (int, string, error) { |
| ctx, cancel := context.WithTimeout(ctx, time.Second) |
| defer cancel() |
| - cmd := exec.CommandContext(ctx, "/usr/bin/systemctl", "show", "--property=MainPID", "--value", "carlos-edge.service") |
| + var out maintenanceBoundedOutput |
| + cmd := systemd.Command(systemd.SystemctlAbsolute, "show", "--property=MainPID", "--value", "carlos-edge.service") |
| cmd.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"} |
| cmd.Dir = "/" |
| - cmd.WaitDelay = time.Second |
| - var out maintenanceBoundedOutput |
| - cmd.Stdout = &out |
| - if err := cmd.Run(); err != nil { |
| + if err := cmd.Run(ctx, &out, nil); err != nil { |
| return 0, "", err |
| } |
| pid, err := maintenanceMainPID(out.body) |
diff --git a/internal/host/probes.go b/internal/host/probes.go| index 9140019bb..0de5f1e70 100644 |
| --- a/internal/host/probes.go |
| +++ b/internal/host/probes.go |
| @@ -14,12 +14,12 @@ import ( |
| "bufio" |
| "io" |
| "os" |
| - "os/exec" |
| "strconv" |
| "strings" |
| "sync" |
| "github.com/carlosframework/platform/internal/status" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| @@ -42,7 +42,7 @@ const adoptTimerUnit = "carlos-adopt.timer" |
| // does. A systemctl that couldn't run at all prints nothing, and nothing maps |
| // to nil. |
| func adoptTimerActive() *bool { |
| - out, _ := exec.Command("systemctl", "is-active", adoptTimerUnit).Output() |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", adoptTimerUnit).Output(systemd.Detached()) |
| return parseIsActive(string(out)) |
| } |
| @@ -60,7 +60,7 @@ const configPathUnit = "carlos-adopt.path" |
| // happily, and nothing ever reads it — so this probe is the only thing that |
| // can tell an operator the box quietly fell back to the hourly config floor. |
| func configPathActive() *bool { |
| - out, _ := exec.Command("systemctl", "is-active", configPathUnit).Output() |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", configPathUnit).Output(systemd.Detached()) |
| return parseIsActive(string(out)) |
| } |
| @@ -79,7 +79,7 @@ const restartPathUnit = "carlos-restart.path" |
| // pass comes round. Nothing inside the agent can see the difference: it writes |
| // its marker either way. |
| func restartPathActive() *bool { |
| - out, _ := exec.Command("systemctl", "is-active", restartPathUnit).Output() |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", restartPathUnit).Output(systemd.Detached()) |
| return parseIsActive(string(out)) |
| } |
| @@ -93,7 +93,7 @@ const systemUpdatePathUnit = "carlos-system-update.path" |
| // the self-update relay: an unarmed path here means an agent that fetched and |
| // verified a new build touches its marker and nothing ever picks it up. |
| func systemUpdatePathActive() *bool { |
| - out, _ := exec.Command("systemctl", "is-active", systemUpdatePathUnit).Output() |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", systemUpdatePathUnit).Output(systemd.Detached()) |
| return parseIsActive(string(out)) |
| } |
diff --git a/internal/host/restartwatch.go b/internal/host/restartwatch.go| index 66e6be32b..74e710358 100644 |
| --- a/internal/host/restartwatch.go |
| +++ b/internal/host/restartwatch.go |
| @@ -14,13 +14,13 @@ import ( |
| "context" |
| "encoding/json" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // restartWindow is how far back a unit's restarts are counted. A unit's |
| @@ -258,8 +258,8 @@ func saveRestartWatch(path string, w restartWatch) error { |
| func platformUnitRestarts() map[string]unitRestartState { |
| ctx, cancel := context.WithTimeout(context.Background(), restartProbeTimeout) |
| defer cancel() |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", |
| - "--property=Id", "--property=NRestarts", "--property=ActiveState", "carlos-*.service").Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", |
| + "--property=Id", "--property=NRestarts", "--property=ActiveState", "carlos-*.service").Output(ctx) |
| if err != nil { |
| return nil |
| } |
diff --git a/internal/host/rootgeneration_services_linux.go b/internal/host/rootgeneration_services_linux.go| index 9075333ef..baf22bf12 100644 |
| --- a/internal/host/rootgeneration_services_linux.go |
| +++ b/internal/host/rootgeneration_services_linux.go |
| @@ -10,13 +10,13 @@ import ( |
| "fmt" |
| "io" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "slices" |
| "strconv" |
| "strings" |
| "github.com/carlosframework/platform/internal/rootstate" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "golang.org/x/sys/unix" |
| ) |
| @@ -106,7 +106,7 @@ type generationExeBinding struct { |
| } |
| func generationServiceShow(ctx context.Context, unit string) (map[string]string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", unit, "-p", "ControlGroup", "-p", "MainPID", "-p", "ExecStart", "-p", "FragmentPath", "-p", "DropInPaths").Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", unit, "-p", "ControlGroup", "-p", "MainPID", "-p", "ExecStart", "-p", "FragmentPath", "-p", "DropInPaths").Output(ctx) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/host/runscensure.go b/internal/host/runscensure.go| index 52a43bf6b..2dcc7cb29 100644 |
| --- a/internal/host/runscensure.go |
| +++ b/internal/host/runscensure.go |
| @@ -7,7 +7,6 @@ import ( |
| "io/fs" |
| "log" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "runtime" |
| "strings" |
| @@ -17,6 +16,7 @@ import ( |
| "github.com/carlosframework/platform/internal/execsandbox" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| func RunSystemRunscEnsure(args []string) { |
| @@ -34,7 +34,7 @@ func RunSystemRunscEnsure(args []string) { |
| } |
| } |
| func runscSystemctl(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(ctx) |
| return string(out), err |
| } |
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go| index e8678e08b..381352f62 100644 |
| --- a/internal/host/systemapply.go |
| +++ b/internal/host/systemapply.go |
| @@ -30,6 +30,7 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/rootparticipation" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| @@ -200,11 +201,24 @@ func openSystemRegistry(dataDir string) (*registry.Registry, error) { |
| return reg, nil |
| } |
| +// systemApplyControlTimeout bounds each state-changing systemctl call of a |
| +// system apply or recovery (productionSysOps), in place of the default |
| +// systemd.ControlTimeout, because these restart carlos-edge: the restart |
| +// stops carlos-edge-drain.service first (TimeoutStopSec=170) and then the |
| +// edge (120 s), and under the guard the edge Requires |
| +// carlos-system-recover.service (TimeoutStartSec=13min). That is 17 min 50 s |
| +// at worst; 18 min is above it and below carlos-system-update.service's |
| +// TimeoutStartSec=20min, so a call that hangs fails the apply, which rolls |
| +// back, before systemd kills it. |
| +const systemApplyControlTimeout = 18 * time.Minute |
| + |
| // productionSysOps is the real box behind the seam. |
| func productionSysOps() sysOps { |
| return sysOps{ |
| systemctl: func(args ...string) (string, error) { |
| - out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + c := systemd.Command(systemd.Systemctl, args...) |
| + c.ControlTimeout = systemApplyControlTimeout |
| + out, err := c.CombinedOutput(systemd.Detached()) |
| if err != nil { |
| return string(out), fmt.Errorf("systemctl %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) |
| } |
| @@ -242,7 +256,7 @@ func productionSysOps() sysOps { |
| return nil |
| }, |
| edgeStartedThisBoot: func() bool { |
| - out, err := exec.Command("systemctl", "show", "-p", "ActiveEnterTimestampMonotonic", "--value", systemEdgeUnit).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "ActiveEnterTimestampMonotonic", "--value", systemEdgeUnit).Output(systemd.Detached()) |
| return err == nil && strings.TrimSpace(string(out)) != "" && strings.TrimSpace(string(out)) != "0" |
| }, |
| logf: log.Printf, |
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go| index 79e480172..53d004061 100644 |
| --- a/internal/host/systemunits.go |
| +++ b/internal/host/systemunits.go |
| @@ -4,8 +4,8 @@ import ( |
| "bytes" |
| "errors" |
| "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "slices" |
| "strings" |
| @@ -324,7 +324,7 @@ func parseIsEnabled(out string) *bool { |
| // rather than productionSysOps().systemctl's fail-on-non-zero. The error |
| // comes back only so a caller left with no word to read can say why. |
| func systemctlProbe(args ...string) (string, error) { |
| - out, err := exec.Command("systemctl", args...).Output() |
| + out, err := systemd.Command(systemd.Systemctl, args...).Output(systemd.Detached()) |
| return string(out), err |
| } |
diff --git a/internal/host/unitops.go b/internal/host/unitops.go| index 1e8cf7200..c5399e59e 100644 |
| --- a/internal/host/unitops.go |
| +++ b/internal/host/unitops.go |
| @@ -9,11 +9,11 @@ import ( |
| "fmt" |
| "log" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strings" |
| "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // dropInRoot is where systemd looks for a unit's drop-ins whichever tree |
| @@ -138,7 +138,7 @@ func lockConfigSync(path string) (unlock func(), err error) { |
| // post-reload verification compare against. |
| func probeUnits(units []string) (map[string]appconfig.UnitState, error) { |
| args := append([]string{"show", "-p", "Id,LoadState,EnvironmentFiles"}, units...) |
| - out, err := exec.Command("systemctl", args...).Output() |
| + out, err := systemd.Command(systemd.Systemctl, args...).Output(systemd.Detached()) |
| if err != nil && len(out) == 0 { |
| return nil, fmt.Errorf("systemctl show: %w", err) |
| } |
| @@ -188,7 +188,7 @@ func parseSystemctlShow(out []byte, units []string) (map[string]appconfig.UnitSt |
| } |
| func daemonReload() error { |
| - out, err := exec.Command("systemctl", "daemon-reload").CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, "daemon-reload").CombinedOutput(systemd.Detached()) |
| if err != nil { |
| return fmt.Errorf("daemon-reload: %w: %s", err, strings.TrimSpace(string(out))) |
| } |
| @@ -199,7 +199,7 @@ func daemonReload() error { |
| // unit owes a restart even when a previous one left it inactive (spec |
| // §3.2 step 4). Logs and returns like systemctlTryRestartUnit. |
| func systemctlRestartUnit(unit string) error { |
| - out, err := exec.Command("systemctl", "restart", unit).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, "restart", unit).CombinedOutput(systemd.Detached()) |
| if err != nil { |
| log.Printf("adopt: restart %s: %v: %s", unit, err, strings.TrimSpace(string(out))) |
| return fmt.Errorf("restart %s: %w: %s", unit, err, strings.TrimSpace(string(out))) |
diff --git a/internal/host/unitsettle.go b/internal/host/unitsettle.go| index 6dfe95d79..91c1bbb86 100644 |
| --- a/internal/host/unitsettle.go |
| +++ b/internal/host/unitsettle.go |
| @@ -20,7 +20,6 @@ import ( |
| "net" |
| "net/http" |
| "os" |
| - "os/exec" |
| "regexp" |
| "strconv" |
| "strings" |
| @@ -29,6 +28,7 @@ import ( |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/upstreamguard" |
| ) |
| @@ -59,8 +59,8 @@ type unitSystem interface { |
| type systemdUnits struct{} |
| func (systemdUnits) Show(unit string) (unitProps, error) { |
| - out, err := exec.Command("systemctl", "show", unit, |
| - "-p", "Id", "-p", "FragmentPath", "-p", "DropInPaths", "-p", "ActiveState", "-p", "SubState", "-p", "InvocationID", "-p", "MainPID", "-p", "NRestarts", "-p", "ExecStart", "-p", "ActiveEnterTimestamp").Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", unit, |
| + "-p", "Id", "-p", "FragmentPath", "-p", "DropInPaths", "-p", "ActiveState", "-p", "SubState", "-p", "InvocationID", "-p", "MainPID", "-p", "NRestarts", "-p", "ExecStart", "-p", "ActiveEnterTimestamp").Output(systemd.Detached()) |
| if err != nil { |
| return unitProps{}, fmt.Errorf("systemctl show %s: %w", unit, err) |
| } |
| @@ -72,7 +72,7 @@ func (systemdUnits) Restart(unit string) error { return systemctlVerb("resta |
| func (systemdUnits) ResetFailed(unit string) error { return systemctlVerb("reset-failed", unit) } |
| func (systemdUnits) JournalTail(unit string, n int) string { |
| - out, _ := exec.Command("journalctl", "-u", unit, "-o", "cat", "-n", strconv.Itoa(n), "--no-pager").Output() |
| + out, _ := systemd.Command(systemd.Journalctl, "-u", unit, "-o", "cat", "-n", strconv.Itoa(n), "--no-pager").Output(systemd.Detached()) |
| return strings.TrimSpace(string(out)) |
| } |
| @@ -103,7 +103,7 @@ func (systemdUnits) StartTime(pid int) (string, error) { |
| } |
| func systemctlVerb(verb, unit string) error { |
| - out, err := exec.Command("systemctl", verb, unit).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, verb, unit).CombinedOutput(systemd.Detached()) |
| if err != nil { |
| return fmt.Errorf("systemctl %s %s: %w: %s", verb, unit, err, strings.TrimSpace(string(out))) |
| } |
diff --git a/internal/instancectl/gvisor_claim_rootrunner_linux_test.go b/internal/instancectl/gvisor_claim_rootrunner_linux_test.go| index 29ba8df55..ff39dd188 100644 |
| --- a/internal/instancectl/gvisor_claim_rootrunner_linux_test.go |
| +++ b/internal/instancectl/gvisor_claim_rootrunner_linux_test.go |
| @@ -55,6 +55,10 @@ func rootrunnerClaimControl() error { |
| Run: func(ctx context.Context, args ...string) (string, error) { |
| b, e := exec.CommandContext(ctx, args[0], args[1:]...).CombinedOutput() |
| return string(b), e |
| + }, |
| + Journal: func(ctx context.Context, args ...string) (string, error) { |
| + b, e := exec.CommandContext(ctx, "journalctl", args...).CombinedOutput() |
| + return string(b), e |
| }} |
| s.snapshots = newDemoSnapshotSupervisor(s) |
| prepare := s.snapshots.prepare |
diff --git a/internal/instancectl/gvisorprobe.go b/internal/instancectl/gvisorprobe.go| index e82f328f4..897536b5d 100644 |
| --- a/internal/instancectl/gvisorprobe.go |
| +++ b/internal/instancectl/gvisorprobe.go |
| @@ -178,10 +178,10 @@ func (s *Server) runGVisorProbe(ctx context.Context) (report ProbeReport) { |
| } |
| s.report, s.probed = report, true |
| s.mu.Unlock() |
| - if !report.Ready && s.Run != nil && attempted { |
| + if !report.Ready && s.Journal != nil && attempted { |
| diag, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) |
| defer cancel() |
| - out, err := s.Run(diag, "journalctl", "--no-pager", "--output=cat", "--lines=20", "--since=@"+strconv.FormatInt(started.Unix(), 10), "--unit="+gvisorProbeUnit) |
| + out, err := s.Journal(diag, "--no-pager", "--output=cat", "--lines=20", "--since=@"+strconv.FormatInt(started.Unix(), 10), "--unit="+gvisorProbeUnit) |
| if len(out) > 4096 { |
| out = out[len(out)-4096:] |
| } |
diff --git a/internal/instancectl/gvisorprobe_flow_linux_test.go b/internal/instancectl/gvisorprobe_flow_linux_test.go| index 45a4bb811..586de8ddc 100644 |
| --- a/internal/instancectl/gvisorprobe_flow_linux_test.go |
| +++ b/internal/instancectl/gvisorprobe_flow_linux_test.go |
| @@ -170,14 +170,14 @@ func newProbeFlow(t *testing.T) *probeFlow { |
| } |
| return nil |
| } |
| - s.Run = func(ctx context.Context, args ...string) (string, error) { |
| + s.Journal = func(ctx context.Context, args ...string) (string, error) { |
| // Only this attempt's lines: a --since bound no earlier than the |
| // probe's start, so a failure never replays older probes' journal. |
| - if len(args) != 6 || strings.Join(args[:4], " ") != "journalctl --no-pager --output=cat --lines=20" || args[5] != "--unit="+gvisorProbeUnit || !strings.HasPrefix(args[4], "--since=@") { |
| + if len(args) != 5 || strings.Join(args[:3], " ") != "--no-pager --output=cat --lines=20" || args[4] != "--unit="+gvisorProbeUnit || !strings.HasPrefix(args[3], "--since=@") { |
| t.Error(args) |
| - } else if since, err := strconv.ParseInt(strings.TrimPrefix(args[4], "--since=@"), 10, 64); err != nil || since > time.Now().Unix() || (!f.callStart.IsZero() && since < f.callStart.Unix()) { |
| + } else if since, err := strconv.ParseInt(strings.TrimPrefix(args[3], "--since=@"), 10, 64); err != nil || since > time.Now().Unix() || (!f.callStart.IsZero() && since < f.callStart.Unix()) { |
| // Within this probe call, allowing whole-second truncation. |
| - t.Error("journal window not bounded to this attempt", args[4], f.callStart) |
| + t.Error("journal window not bounded to this attempt", args[3], f.callStart) |
| } |
| deadline, ok := ctx.Deadline() |
| if !ok || time.Until(deadline) > 5*time.Second { |
diff --git a/internal/instancectl/hairpin.go b/internal/instancectl/hairpin.go| index fe37e1737..67b18ae70 100644 |
| --- a/internal/instancectl/hairpin.go |
| +++ b/internal/instancectl/hairpin.go |
| @@ -10,12 +10,12 @@ import ( |
| "net/http" |
| "net/netip" |
| "os" |
| - "os/exec" |
| "slices" |
| "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/hairpin" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| var ( |
| @@ -323,7 +323,7 @@ func ClearGroupHairpin(ctx context.Context) error { |
| } |
| func newHairpinResetServer() *Server { |
| return &Server{LocalAddrs: LocalAddresses, Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(ctx) |
| return string(out), err |
| }} |
| } |
diff --git a/internal/instancectl/peer_linux.go b/internal/instancectl/peer_linux.go| index 50475715a..dc58cbef4 100644 |
| --- a/internal/instancectl/peer_linux.go |
| +++ b/internal/instancectl/peer_linux.go |
| @@ -9,7 +9,6 @@ import ( |
| "log" |
| "net" |
| "os" |
| - "os/exec" |
| "os/user" |
| "strconv" |
| "strings" |
| @@ -17,6 +16,8 @@ import ( |
| "time" |
| "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // peerCred reads SO_PEERCRED from a connected unix socket. |
| @@ -98,7 +99,7 @@ func EdgePeerRuleFor(carlosUID int, mainPID func() (int, error)) func(net.Conn) |
| func systemdEdgeMainPID() (int, error) { |
| ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| defer cancel() |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", edgeUnit).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "MainPID", "--value", edgeUnit).Output(ctx) |
| if err != nil { |
| return 0, err |
| } |
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go| index a0e487a55..5b44d06b5 100644 |
| --- a/internal/instancectl/server.go |
| +++ b/internal/instancectl/server.go |
| @@ -32,6 +32,7 @@ import ( |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| @@ -179,6 +180,10 @@ type Server struct { |
| // inspectMountpoints uses it, and every argument it passes is a |
| // constant: nothing from a request reaches it. |
| Run func(ctx context.Context, args ...string) (string, error) |
| + // Journal runs journalctl with args and returns its combined output; |
| + // production is internal/systemd's bounded journalctl Command, tests |
| + // record. nil skips the journal tail a failed gVisor probe logs. |
| + Journal func(ctx context.Context, args ...string) (string, error) |
| // Build is the build this process runs (version.Build), answered on |
| // every /ready as the BuildHeader so the agent can see it talks to |
| @@ -330,7 +335,11 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV |
| ClaimStop: claim, |
| ClaimHeldRelease: heldRelease, |
| Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(ctx) |
| + return string(out), err |
| + }, |
| + Journal: func(ctx context.Context, args ...string) (string, error) { |
| + out, err := systemd.Command(systemd.Journalctl, args...).CombinedOutput(ctx) |
| return string(out), err |
| }, |
| Run: func(ctx context.Context, args ...string) (string, error) { |
diff --git a/internal/ops/ops.go b/internal/ops/ops.go| index 15bd44131..408010035 100644 |
| --- a/internal/ops/ops.go |
| +++ b/internal/ops/ops.go |
| @@ -7,6 +7,7 @@ package ops |
| import ( |
| "github.com/carlosframework/platform/internal/cliflag" |
| "github.com/carlosframework/platform/internal/clireg" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "context" |
| "encoding/json" |
| @@ -17,7 +18,6 @@ import ( |
| "io/fs" |
| "log" |
| "os" |
| - "os/exec" |
| "os/signal" |
| "path/filepath" |
| "strings" |
| @@ -232,7 +232,7 @@ const daemonReloadTimeout = time.Minute |
| func systemdDaemonReload() error { |
| ctx, cancel := context.WithTimeout(context.Background(), daemonReloadTimeout) |
| defer cancel() |
| - out, err := exec.CommandContext(ctx, "systemctl", "daemon-reload").CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, "daemon-reload").CombinedOutput(ctx) |
| if err != nil { |
| return fmt.Errorf("systemctl daemon-reload: %v: %s", err, strings.TrimSpace(string(out))) |
| } |
diff --git a/internal/systemd/command.go b/internal/systemd/command.go| new file mode 100644 |
| index 000000000..5a2b64a9a |
| --- /dev/null |
| +++ b/internal/systemd/command.go |
| @@ -0,0 +1,273 @@ |
| +// Package systemd runs systemctl and journalctl with a deadline. Every |
| +// call in the root binary goes through Command (TestSystemctlCallsAreBounded): |
| +// a systemd that stalls (a PID 1 waiting on a child that never execs, a |
| +// D-Bus that never answers) must fail a pass, not hold it, and the host |
| +// agent's loops make these calls while holding reconcileMu or |
| +// configSyncMu. |
| +// |
| +// Each call runs under the caller's context and a default bound for its |
| +// verb, whichever ends first: QueryTimeout for a verb that only reads, |
| +// ControlTimeout for one that waits on a job. When the bound ends the call, |
| +// the process is killed and the error is a *TimeoutError naming the verb |
| +// and the units. When the caller's own context ends it, the error is what |
| +// os/exec returns, as before this package existed. Every other result |
| +// (output, exit status, *exec.ExitError with its Stderr) is exactly what |
| +// exec.Cmd gives. |
| +// |
| +// The constructor is called Command on purpose: the root-read census |
| +// (internal/provision) counts a call by that name as running a command, |
| +// so each caller keeps its own site there, as it had with exec.Command. |
| +package systemd |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "io" |
| + "os/exec" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// QueryTimeout bounds a verb that only reads (show, is-active, list-units, |
| +// cat, ...) and every journalctl call. systemctl's own D-Bus method calls |
| +// give up after 25 s (sd-bus's default), so a systemd that answers late |
| +// still gets systemctl's own error first; this bound is for a systemctl |
| +// that hangs past that. It also matches the settle check's default window |
| +// (CARLOS_UNIT_SETTLE, 30 s), so one stuck query costs a settle no more |
| +// than its whole window. |
| +const QueryTimeout = 30 * time.Second |
| + |
| +// ControlTimeout bounds every other verb: start, stop, restart, |
| +// try-restart, reset-failed, daemon-reload, enable, set-property, kill. |
| +// Without --no-block these wait for systemd's job, so the bound is above |
| +// the longest job a caller waits on with the default: a restart is a stop |
| +// and then a start; the longest stop of one unit is |
| +// carlos-edge-drain.service's TimeoutStopSec=170, the longest start waited |
| +// on is a 120 s oneshot (carlos-instance-seed@, carlos-runsc: |
| +// TimeoutStartSec=120), and an app or instance unit's restart is at most |
| +// systemd's default 90 s stop and 90 s start. All are under five minutes. |
| +// The one longer job, carlos-edge's restart (the drain's stop, then the |
| +// edge's 120 s, then under the guard the recovery it Requires), only the |
| +// system apply and recovery make, with their own Cmd.ControlTimeout. |
| +const ControlTimeout = 5 * time.Minute |
| + |
| +// killWait is exec.Cmd.WaitDelay: how long after the kill the call waits |
| +// for the process's output pipes to close (a child that inherited them) |
| +// before closing them itself. A second, as the group maintenance verbs' |
| +// own MainPID read used before this package. |
| +const killWait = time.Second |
| + |
| +// Program is the program a Command runs. |
| +type Program int |
| + |
| +const ( |
| + // Systemctl is systemctl, looked up on PATH as exec.Command does. |
| + Systemctl Program = iota |
| + // SystemctlAbsolute is /usr/bin/systemctl, for a caller that runs with |
| + // a fixed environment and no PATH lookup. |
| + SystemctlAbsolute |
| + // Journalctl is journalctl, looked up on PATH. Every verb of it is a |
| + // query. |
| + Journalctl |
| +) |
| + |
| +// programPaths names each Program. Only this package names them (the |
| +// guard test); a test may point one at a fake. |
| +var programPaths = map[Program]string{ |
| + Systemctl: "systemctl", |
| + SystemctlAbsolute: "/usr/bin/systemctl", |
| + Journalctl: "journalctl", |
| +} |
| + |
| +// Detached is the context for a call whose caller has none to pass on: a |
| +// method of an interface that takes no context (internal/host's |
| +// unitSystem), a status probe, a one-shot command. The verb's bound is |
| +// then the call's only deadline, which is the point of this package. A |
| +// caller that has a context passes that instead. |
| +func Detached() context.Context { |
| + // Detached on purpose, as the doc comment says: the bound is the |
| + // deadline. |
| + return context.Background() |
| +} |
| + |
| +// Cmd is one bounded systemctl or journalctl run. Its exported fields may |
| +// be set before it runs; it runs once. |
| +type Cmd struct { |
| + // ControlTimeout replaces the package's ControlTimeout for a control |
| + // verb; 0 keeps it. Queries keep QueryTimeout. |
| + ControlTimeout time.Duration |
| + // Env and Dir are exec.Cmd's: nil and "" inherit the caller's. |
| + Env []string |
| + Dir string |
| + |
| + program Program |
| + args []string |
| +} |
| + |
| +// Command returns the Cmd running program with args. |
| +func Command(program Program, args ...string) *Cmd { |
| + return &Cmd{program: program, args: args} |
| +} |
| + |
| +// Output runs the command and returns its stdout, as exec.Cmd.Output: an |
| +// *exec.ExitError carries stderr. |
| +func (c *Cmd) Output(ctx context.Context) ([]byte, error) { |
| + return c.run(ctx, func(cmd *exec.Cmd) ([]byte, error) { return cmd.Output() }) |
| +} |
| + |
| +// CombinedOutput runs the command and returns stdout and stderr together, |
| +// as exec.Cmd.CombinedOutput. |
| +func (c *Cmd) CombinedOutput(ctx context.Context) ([]byte, error) { |
| + return c.run(ctx, func(cmd *exec.Cmd) ([]byte, error) { return cmd.CombinedOutput() }) |
| +} |
| + |
| +// Run runs the command with stdout and stderr going to the given writers |
| +// (nil discards, as exec.Cmd does). |
| +func (c *Cmd) Run(ctx context.Context, stdout, stderr io.Writer) error { |
| + _, err := c.run(ctx, func(cmd *exec.Cmd) ([]byte, error) { |
| + cmd.Stdout, cmd.Stderr = stdout, stderr |
| + return nil, cmd.Run() |
| + }) |
| + return err |
| +} |
| + |
| +func (c *Cmd) run(ctx context.Context, do func(*exec.Cmd) ([]byte, error)) ([]byte, error) { |
| + path, ok := programPaths[c.program] |
| + if !ok { |
| + return nil, fmt.Errorf("systemd: unknown program %d", c.program) |
| + } |
| + return bounded(ctx, path, c.args, c.bound(), func(cmd *exec.Cmd) ([]byte, error) { |
| + cmd.Env, cmd.Dir = c.Env, c.Dir |
| + return do(cmd) |
| + }, c.describe) |
| +} |
| + |
| +// bound is the deadline this command's verb gets. |
| +func (c *Cmd) bound() time.Duration { |
| + if verb, _ := describe(c.args); c.program == Journalctl || queryVerbs[verb] { |
| + return QueryTimeout |
| + } |
| + if c.ControlTimeout > 0 { |
| + return c.ControlTimeout |
| + } |
| + return ControlTimeout |
| +} |
| + |
| +// describe names the command for a TimeoutError. |
| +func (c *Cmd) describe() (program, verb string, units []string) { |
| + if c.program == Journalctl { |
| + return "journalctl", "", journalUnits(c.args) |
| + } |
| + verb, units = describe(c.args) |
| + return "systemctl", verb, units |
| +} |
| + |
| +// bounded runs path under parent and the bound, killing it when either |
| +// ends, and turns a kill at the bound into a *TimeoutError. When parent |
| +// ended first (the caller's own deadline or cancel), the error is os/exec's, |
| +// unchanged: a caller deadline earlier than the bound ends parent before |
| +// the context derived from it, so parent's state tells the two apart. |
| +func bounded(parent context.Context, path string, args []string, bound time.Duration, do func(*exec.Cmd) ([]byte, error), name func() (string, string, []string)) ([]byte, error) { |
| + ctx, cancel := context.WithTimeout(parent, bound) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, path, args...) |
| + cmd.WaitDelay = killWait |
| + out, err := do(cmd) |
| + if err == nil || ctx.Err() == nil || parent.Err() != nil { |
| + return out, err |
| + } |
| + program, verb, units := name() |
| + return out, &TimeoutError{Program: program, Verb: verb, Units: units, After: bound, Err: err} |
| +} |
| + |
| +// TimeoutError is a systemctl or journalctl that did not finish within its |
| +// bound and was killed. It is temporary: the next pass asks again, and a |
| +// restart that was only slow is not a verdict on the build it started |
| +// (release's adopt reads Temporary before it poisons a version). |
| +type TimeoutError struct { |
| + Program string // "systemctl" or "journalctl" |
| + Verb string // systemctl's verb; "" for journalctl |
| + Units []string // the units, patterns or assignments the call named |
| + After time.Duration |
| + Err error // os/exec's error after the kill |
| +} |
| + |
| +func (e *TimeoutError) Error() string { |
| + name := e.Program |
| + if e.Verb != "" { |
| + name += " " + e.Verb |
| + } |
| + if len(e.Units) > 0 { |
| + if e.Program == "journalctl" { |
| + name += " -u" |
| + } |
| + name += " " + strings.Join(e.Units, " ") |
| + } |
| + return fmt.Sprintf("%s: no answer within %s; killed", name, e.After) |
| +} |
| + |
| +// Unwrap is context.DeadlineExceeded, so errors.Is sees a timeout. The |
| +// killed process's *exec.ExitError is not exposed: its exit status is the |
| +// kill's, not an answer a caller should read. |
| +func (e *TimeoutError) Unwrap() error { return context.DeadlineExceeded } |
| +func (e *TimeoutError) Timeout() bool { return true } |
| +func (e *TimeoutError) Temporary() bool { return true } |
| + |
| +// queryVerbs only read systemd's state; every other verb is a control verb. |
| +var queryVerbs = map[string]bool{ |
| + "show": true, "status": true, "cat": true, "help": true, |
| + "is-active": true, "is-enabled": true, "is-failed": true, "is-system-running": true, |
| + "list-units": true, "list-unit-files": true, "list-jobs": true, "list-timers": true, |
| + "list-sockets": true, "list-dependencies": true, "list-automounts": true, "list-paths": true, |
| + "get-default": true, "show-environment": true, |
| +} |
| + |
| +// valueFlags are systemctl's options that take their value as the next |
| +// argument; the value is neither the verb nor a unit. |
| +var valueFlags = map[string]bool{ |
| + "-p": true, "--property": true, "-t": true, "--type": true, "--state": true, |
| + "-s": true, "--signal": true, "--kill-whom": true, "--kill-value": true, |
| + "-H": true, "--host": true, "-M": true, "--machine": true, |
| + "-n": true, "--lines": true, "-o": true, "--output": true, |
| + "--job-mode": true, "--root": true, "--image": true, "--what": true, |
| + "--timestamp": true, "--message": true, "--preset-mode": true, "--drop-in": true, "--when": true, |
| +} |
| + |
| +// describe splits systemctl's arguments into its verb (the first that is |
| +// not an option) and the rest that are not options: the units, patterns or |
| +// assignments the verb acts on. |
| +func describe(args []string) (verb string, units []string) { |
| + for i := 0; i < len(args); i++ { |
| + a := args[i] |
| + if strings.HasPrefix(a, "-") { |
| + if valueFlags[a] { |
| + i++ |
| + } |
| + continue |
| + } |
| + if verb == "" { |
| + verb = a |
| + continue |
| + } |
| + units = append(units, a) |
| + } |
| + return verb, units |
| +} |
| + |
| +// journalUnits is the units a journalctl call reads (-u X, -uX, --unit X, |
| +// --unit=X). |
| +func journalUnits(args []string) []string { |
| + var units []string |
| + for i := 0; i < len(args); i++ { |
| + switch a := args[i]; { |
| + case (a == "-u" || a == "--unit") && i+1 < len(args): |
| + units = append(units, args[i+1]) |
| + i++ |
| + case strings.HasPrefix(a, "--unit="): |
| + units = append(units, strings.TrimPrefix(a, "--unit=")) |
| + case strings.HasPrefix(a, "-u") && len(a) > 2: |
| + units = append(units, a[2:]) |
| + } |
| + } |
| + return units |
| +} |
diff --git a/internal/systemd/command_test.go b/internal/systemd/command_test.go| new file mode 100644 |
| index 000000000..eb2ef3ad0 |
| --- /dev/null |
| +++ b/internal/systemd/command_test.go |
| @@ -0,0 +1,216 @@ |
| +package systemd |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "reflect" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// fakeSystemctl puts scripts named systemctl and journalctl first on PATH |
| +// and points SystemctlAbsolute at the systemctl one. Each records its pid |
| +// in dir/pid and then runs body. Nothing here runs the real programs. |
| +func fakeSystemctl(t *testing.T, body string) (dir string) { |
| + t.Helper() |
| + dir = t.TempDir() |
| + script := "#!/bin/sh\necho $$ > " + filepath.Join(dir, "pid") + "\n" + body + "\n" |
| + for _, name := range []string{"systemctl", "journalctl"} { |
| + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) |
| + old := programPaths[SystemctlAbsolute] |
| + programPaths[SystemctlAbsolute] = filepath.Join(dir, "systemctl") |
| + t.Cleanup(func() { programPaths[SystemctlAbsolute] = old }) |
| + return dir |
| +} |
| + |
| +// hang is a fake that never answers: exec replaces the shell, so the kill |
| +// reaches the process holding the pipes. |
| +const hang = "exec sleep 600" |
| + |
| +// gone reports whether the fake's recorded process no longer exists: the |
| +// kill reached it (and Wait reaped it). |
| +func gone(t *testing.T, dir string) bool { |
| + t.Helper() |
| + b, err := os.ReadFile(filepath.Join(dir, "pid")) |
| + if err != nil { |
| + t.Fatalf("the fake never ran: %v", err) |
| + } |
| + pid, err := strconv.Atoi(strings.TrimSpace(string(b))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return errors.Is(syscall.Kill(pid, 0), syscall.ESRCH) |
| +} |
| + |
| +// A systemctl that hangs is killed at the bound, and the error says which |
| +// verb and unit, is a timeout, and is temporary. |
| +func TestHungSystemctlIsKilledAtTheBound(t *testing.T) { |
| + dir := fakeSystemctl(t, hang) |
| + const bound = 300 * time.Millisecond |
| + c := Command(Systemctl, "restart", "carlos-app@shop.example.com.service") |
| + c.ControlTimeout = bound |
| + start := time.Now() |
| + _, err := c.CombinedOutput(context.Background()) |
| + took := time.Since(start) |
| + var te *TimeoutError |
| + if !errors.As(err, &te) { |
| + t.Fatalf("err = %v (%T), want a *TimeoutError", err, err) |
| + } |
| + if took < bound || took > bound+killWait+time.Second { |
| + t.Fatalf("returned after %s, want at the %s bound", took, bound) |
| + } |
| + want := "systemctl restart carlos-app@shop.example.com.service: no answer within 300ms; killed" |
| + if err.Error() != want { |
| + t.Fatalf("err = %q, want %q", err, want) |
| + } |
| + if !errors.Is(err, context.DeadlineExceeded) || !te.Timeout() || !te.Temporary() { |
| + t.Fatal("a TimeoutError must read as a temporary deadline") |
| + } |
| + var ee *exec.ExitError |
| + if errors.As(err, &ee) { |
| + t.Fatal("a TimeoutError must not expose the kill's exit status as an answer") |
| + } |
| + if !gone(t, dir) { |
| + t.Fatal("the hung systemctl is still running") |
| + } |
| +} |
| + |
| +// journalctl is bounded the same way, and its error names the unit it read. |
| +func TestHungJournalctlIsKilledAtTheBound(t *testing.T) { |
| + dir := fakeSystemctl(t, hang) |
| + c := Command(Journalctl, "-u", "carlos-edge.service", "-o", "cat", "-n", "20", "--no-pager") |
| + if c.bound() != QueryTimeout { |
| + t.Fatalf("journalctl bound %s, want QueryTimeout", c.bound()) |
| + } |
| + _, err := bounded(context.Background(), programPaths[Journalctl], c.args, 200*time.Millisecond, func(cmd *exec.Cmd) ([]byte, error) { return cmd.Output() }, c.describe) |
| + want := "journalctl -u carlos-edge.service: no answer within 200ms; killed" |
| + if err == nil || err.Error() != want { |
| + t.Fatalf("err = %v, want %q", err, want) |
| + } |
| + if !gone(t, dir) { |
| + t.Fatal("the hung journalctl is still running") |
| + } |
| +} |
| + |
| +// SystemctlAbsolute runs the absolute path with no PATH lookup, under the |
| +// same bound. |
| +func TestAbsoluteSystemctlIsBounded(t *testing.T) { |
| + fakeSystemctl(t, hang) |
| + t.Setenv("PATH", "/nonexistent") |
| + c := Command(SystemctlAbsolute, "stop", "carlos-edge.service") |
| + c.ControlTimeout = 200 * time.Millisecond |
| + c.Env = []string{"PATH=/usr/bin:/bin"} |
| + err := c.Run(context.Background(), nil, nil) |
| + var te *TimeoutError |
| + if !errors.As(err, &te) || te.Verb != "stop" || !reflect.DeepEqual(te.Units, []string{"carlos-edge.service"}) { |
| + t.Fatalf("err = %v, want a TimeoutError for stop carlos-edge.service", err) |
| + } |
| +} |
| + |
| +// A caller whose own deadline ends the call first gets os/exec's error, as |
| +// before the helper: the bound did not end it. |
| +func TestCallerDeadlineKeepsExecError(t *testing.T) { |
| + fakeSystemctl(t, hang) |
| + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) |
| + defer cancel() |
| + _, err := Command(Systemctl, "show", "-p", "MainPID", "--value", "carlos-edge.service").Output(ctx) |
| + var te *TimeoutError |
| + if err == nil || errors.As(err, &te) { |
| + t.Fatalf("err = %v, want os/exec's error, not a TimeoutError", err) |
| + } |
| + var ee *exec.ExitError |
| + if !errors.As(err, &ee) { |
| + t.Fatalf("err = %v (%T), want the killed process's *exec.ExitError", err, err) |
| + } |
| +} |
| + |
| +// Everything that is not a timeout is exec.Cmd's: output, exit status and |
| +// stderr on the ExitError. |
| +func TestAnswersPassThrough(t *testing.T) { |
| + fakeSystemctl(t, `echo "args: $*"; echo complaint >&2; exit 3`) |
| + out, err := Command(Systemctl, "is-active", "carlos-adopt.timer").Output(context.Background()) |
| + if string(out) != "args: is-active carlos-adopt.timer\n" { |
| + t.Fatalf("stdout = %q", out) |
| + } |
| + var ee *exec.ExitError |
| + if !errors.As(err, &ee) || ee.ExitCode() != 3 || strings.TrimSpace(string(ee.Stderr)) != "complaint" { |
| + t.Fatalf("err = %v, want exit 3 with stderr", err) |
| + } |
| + out, err = Command(Systemctl, "try-restart", "x.service").CombinedOutput(context.Background()) |
| + if !strings.Contains(string(out), "complaint") || err == nil { |
| + t.Fatalf("combined = %q, %v", out, err) |
| + } |
| + out, err = Command(Journalctl, "-u", "x.service").Output(context.Background()) |
| + if string(out) != "args: -u x.service\n" || err == nil { |
| + t.Fatalf("journal = %q, %v", out, err) |
| + } |
| + if _, err := Command(Program(99), "show").Output(context.Background()); err == nil { |
| + t.Fatal("an unknown program ran") |
| + } |
| +} |
| + |
| +func TestBoundPerVerb(t *testing.T) { |
| + cases := []struct { |
| + program Program |
| + control time.Duration |
| + args []string |
| + want time.Duration |
| + }{ |
| + {Systemctl, 0, []string{"show", "-p", "MainPID", "--value", "u"}, QueryTimeout}, |
| + {Systemctl, 0, []string{"--no-pager", "list-units", "--all", "carlos-*"}, QueryTimeout}, |
| + {Systemctl, 0, []string{"is-active", "a", "b"}, QueryTimeout}, |
| + {Systemctl, 0, []string{"cat", "--no-pager", "u"}, QueryTimeout}, |
| + {SystemctlAbsolute, 0, []string{"list-jobs", "--plain"}, QueryTimeout}, |
| + {Systemctl, 0, []string{"restart", "u"}, ControlTimeout}, |
| + {Systemctl, 0, []string{"start", "--no-block", "u"}, ControlTimeout}, |
| + {Systemctl, 0, []string{"daemon-reload"}, ControlTimeout}, |
| + {Systemctl, 0, []string{"set-property", "--runtime", "u", "IPAddressAllow="}, ControlTimeout}, |
| + {Systemctl, 0, nil, ControlTimeout}, |
| + {Systemctl, time.Hour, []string{"restart", "u"}, time.Hour}, |
| + {Systemctl, time.Hour, []string{"show", "u"}, QueryTimeout}, |
| + {Journalctl, time.Hour, []string{"-u", "u"}, QueryTimeout}, |
| + } |
| + for _, c := range cases { |
| + cmd := Command(c.program, c.args...) |
| + cmd.ControlTimeout = c.control |
| + if got := cmd.bound(); got != c.want { |
| + t.Errorf("%v: bound %s, want %s", c.args, got, c.want) |
| + } |
| + } |
| + if QueryTimeout >= ControlTimeout { |
| + t.Fatal("a query must be bounded tighter than a job") |
| + } |
| +} |
| + |
| +func TestDescribe(t *testing.T) { |
| + cases := []struct { |
| + args []string |
| + verb string |
| + units []string |
| + }{ |
| + {[]string{"show", "-p", "Id,LoadState", "a.service", "b.service"}, "show", []string{"a.service", "b.service"}}, |
| + {[]string{"show", "--property=MainPID", "--value", "carlos-edge.service"}, "show", []string{"carlos-edge.service"}}, |
| + {[]string{"-p", "X", "show", "u"}, "show", []string{"u"}}, |
| + {[]string{"kill", "--kill-whom=all", "--signal=SIGKILL", "u"}, "kill", []string{"u"}}, |
| + {[]string{"daemon-reload"}, "daemon-reload", nil}, |
| + } |
| + for _, c := range cases { |
| + verb, units := describe(c.args) |
| + if verb != c.verb || !reflect.DeepEqual(units, c.units) { |
| + t.Errorf("%v: %q %q, want %q %q", c.args, verb, units, c.verb, c.units) |
| + } |
| + } |
| + if got := journalUnits([]string{"--no-pager", "--unit=a", "-u", "b", "-uc"}); !reflect.DeepEqual(got, []string{"a", "b", "c"}) { |
| + t.Errorf("journalUnits = %q", got) |
| + } |
| +} |
diff --git a/internal/systemd/guard_test.go b/internal/systemd/guard_test.go| new file mode 100644 |
| index 000000000..f18a62b5e |
| --- /dev/null |
| +++ b/internal/systemd/guard_test.go |
| @@ -0,0 +1,184 @@ |
| +package systemd |
| + |
| +import ( |
| + "bytes" |
| + "fmt" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// unboundedSystemctlAllowlist names root-graph files that may still name |
| +// systemctl or journalctl as a program, and why. Empty: every call goes |
| +// through this package. A file added here must say what bounds its call. |
| +var unboundedSystemctlAllowlist = map[string]string{} |
| + |
| +// TestSystemctlCallsAreBounded: no non-test Go file of a module package the |
| +// root binary links (linux, amd64 and arm64), outside this package, names |
| +// systemctl or journalctl as a program: no string literal that is exactly |
| +// "systemctl" or "journalctl", or a path ending in /systemctl or |
| +// /journalctl. That is how every call so far has named it (exec.Command's |
| +// name, a seam's first argument, a constant), so a new call that does not |
| +// come through this package fails here. A literal that only mentions the |
| +// program in a sentence ("systemctl restart carlos-edge" in a message, a |
| +// shell script sent to another box) is not a program name and passes. |
| +func TestSystemctlCallsAreBounded(t *testing.T) { |
| + if testing.Short() { |
| + t.Skip("lists the root binary's packages with go list") |
| + } |
| + root := moduleRoot(t) |
| + files := rootBinaryFiles(t, root) |
| + if len(files) < 100 { |
| + t.Fatalf("listed only %d root-binary files; the scan would prove nothing", len(files)) |
| + } |
| + var bad []string |
| + seen := map[string]bool{} |
| + for _, rel := range files { |
| + if strings.HasPrefix(rel, "internal/systemd/") { |
| + continue |
| + } |
| + hits := programNames(t, filepath.Join(root, rel)) |
| + if _, ok := unboundedSystemctlAllowlist[rel]; ok { |
| + seen[rel] = len(hits) > 0 |
| + continue |
| + } |
| + for _, h := range hits { |
| + bad = append(bad, rel+":"+h) |
| + } |
| + } |
| + sort.Strings(bad) |
| + for _, b := range bad { |
| + t.Errorf("%s: run it through internal/systemd.Command, which bounds it", b) |
| + } |
| + for rel := range unboundedSystemctlAllowlist { |
| + if !seen[rel] { |
| + t.Errorf("%s is allowlisted but names neither program (or left the root binary): drop it from the allowlist", rel) |
| + } |
| + } |
| +} |
| + |
| +// The scan catches each shape a call has taken, and lets a sentence through. |
| +func TestProgramNamesScan(t *testing.T) { |
| + src := `package x |
| +import ( |
| + "context" |
| + "os/exec" |
| +) |
| +const bin = "/usr/bin/systemctl" |
| +var run func(context.Context, ...string) (string, error) |
| +func f(ctx context.Context) { |
| + exec.Command("systemctl", "show") |
| + exec.CommandContext(ctx, "journalctl", "-u", "x") |
| + exec.Command(bin) |
| + run(ctx, "journalctl", "--no-pager") |
| + exec.Command("/bin/journalctl") |
| + _ = "run systemctl restart carlos-edge" |
| + _ = "systemctl show" |
| + _ = "systemd-journald" |
| +} |
| +` |
| + path := filepath.Join(t.TempDir(), "x.go") |
| + if err := os.WriteFile(path, []byte(src), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + got := programNames(t, path) |
| + if len(got) != 5 { |
| + t.Fatalf("caught %d, want 5: %v", len(got), got) |
| + } |
| +} |
| + |
| +// programNames reports, as line:literal, each string literal in the file |
| +// that names systemctl or journalctl as a program. Import paths are not |
| +// string literals the scan reads. |
| +func programNames(t *testing.T, path string) []string { |
| + t.Helper() |
| + fset := token.NewFileSet() |
| + f, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution) |
| + if err != nil { |
| + t.Fatalf("parse %s: %v", path, err) |
| + } |
| + imports := map[*ast.BasicLit]bool{} |
| + for _, imp := range f.Imports { |
| + imports[imp.Path] = true |
| + } |
| + var hits []string |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + lit, ok := n.(*ast.BasicLit) |
| + if !ok || lit.Kind != token.STRING || imports[lit] { |
| + return true |
| + } |
| + v, err := strconv.Unquote(lit.Value) |
| + if err != nil { |
| + return true |
| + } |
| + for _, p := range []string{"systemctl", "journalctl"} { |
| + if v == p || strings.HasSuffix(v, "/"+p) { |
| + hits = append(hits, fmt.Sprintf("%d: %q", fset.Position(lit.Pos()).Line, v)) |
| + } |
| + } |
| + return true |
| + }) |
| + return hits |
| +} |
| + |
| +func moduleRoot(t *testing.T) string { |
| + t.Helper() |
| + dir, err := os.Getwd() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for { |
| + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { |
| + return dir |
| + } |
| + parent := filepath.Dir(dir) |
| + if parent == dir { |
| + t.Fatal("no go.mod above the test") |
| + } |
| + dir = parent |
| + } |
| +} |
| + |
| +// rootBinaryFiles is every non-test Go file, relative to root, of every |
| +// module package the root binary links on linux/amd64 or linux/arm64 (as |
| +// internal/rootaws's guard lists them). |
| +func rootBinaryFiles(t *testing.T, root string) []string { |
| + t.Helper() |
| + set := map[string]bool{} |
| + for _, arch := range []string{"amd64", "arm64"} { |
| + cmd := exec.Command("go", "list", "-deps", "-f", `{{if not .Standard}}{{.Dir}}|{{join .GoFiles ","}}{{end}}`, ".") |
| + cmd.Dir = root |
| + cmd.Env = append(os.Environ(), "GOOS=linux", "GOARCH="+arch, "CGO_ENABLED=0") |
| + var stderr bytes.Buffer |
| + cmd.Stderr = &stderr |
| + out, err := cmd.Output() |
| + if err != nil { |
| + t.Fatalf("go list (linux/%s): %v: %s", arch, err, stderr.String()) |
| + } |
| + for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { |
| + dir, names, _ := strings.Cut(line, "|") |
| + rel, err := filepath.Rel(root, dir) |
| + if dir == "" || err != nil || strings.HasPrefix(rel, "..") { |
| + continue // the standard library and other modules |
| + } |
| + for _, n := range strings.Split(names, ",") { |
| + if n != "" { |
| + set[filepath.ToSlash(filepath.Join(rel, n))] = true |
| + } |
| + } |
| + } |
| + } |
| + files := make([]string, 0, len(set)) |
| + for f := range set { |
| + files = append(files, f) |
| + } |
| + sort.Strings(files) |
| + return files |
| +} |