systemd: bound queries only; settle's unknown observation is no verdict
Astra round 1 on bounded-systemctl (P1, P2-2 to P2-5), with the scope cut the coordinator set. Only queries are bounded now: show, is-active, list-units, cat and the other read-only verbs, and every journalctl call, at 30 s. Mutating verbs (start, stop, restart, try-restart, reload, daemon-reload and the rest, the system apply and recovery included) run under the caller's context alone, as before: killing systemctl does not cancel its job, so a timed-out restart is an unknown outcome no caller reconciles yet. The 5 min and 18 min classes are gone; the package comment says why and names the follow-up. settleUnit no longer turns a deadline it reached while show kept failing into a UnitNotUpError. It returns errUnitUnobserved, temporary, so adoption neither poisons the version nor runs the not-up recovery; the root path settles that attempt instead of recording it failed. A unit seen failed, on the wrong executable or not ready keeps its verdict. caps' Ops.systemctl wraps with %w. Detached() is gone: callers with no context to pass use an explicit context.Background() with a one-line reason, counted by the host-context ratchet (17 sites raised, named). The guard folds constants and finds local shells: "system"+"ctl", a const or variable command line, fmt.Sprintf and sh/bash/dash -c argv. grouproll's remote edge-stop script is a named exception.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
18 files changed,
+769
−198
.amadan/code-health.tsv+17 −0internal/caps/converge.go+6 −5internal/caps/systemctl_error_test.go+30 −0internal/host/adopt_advice.go+3 −1internal/host/agent.go+6 −3internal/host/bootstrap.go+3 −1internal/host/probes.go+9 −4internal/host/rootrestart.go+7 −0internal/host/settle_unobserved_adopt_test.go+118 −0internal/host/settle_unobserved_root_test.go+81 −0internal/host/systemapply.go+6 −15internal/host/systemunits.go+3 −1internal/host/unitops.go+7 −3internal/host/unitsettle.go+33 −6internal/host/unitsettle_test.go+32 −5internal/systemd/command.go+61 −63internal/systemd/command_test.go+52 −37internal/systemd/guard_test.go+295 −54
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index 16ef2deaa..390bde2dc 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -2119,6 +2119,7 @@ host-context internal/host RunSystemJournalMigrate context.Background 1 |
| host-context internal/host RunSystemProxyAllowsPrev context.Background 1 |
| host-context internal/host RunSystemRunscEnsure context.Background 1 |
| host-context internal/host adoptLoop context.Background 1 |
| +host-context internal/host adoptTimerActive context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host agentEntry context.Background 2 |
| host-context internal/host armDBReads context.Background 1 |
| host-context internal/host armHAPlacement context.Background 1 |
| @@ -2130,9 +2131,11 @@ host-context internal/host boxRecordLoop context.Background 1 |
| host-context internal/host checkedUnitRestart context.Background 4 |
| host-context internal/host closeReplicaCoordinator context.Background 1 |
| host-context internal/host configGenLoop context.Background 1 |
| +host-context internal/host configPathActive context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host configSyncLoop context.Background 1 |
| host-context internal/host configureGroupHairpinClient context.Background 2 |
| host-context internal/host createClaimEdgeMask context.Background 1 |
| +host-context internal/host daemonReload context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host domainsLoop context.Background 2 |
| host-context internal/host edgeFenceStatusReport context.Background 1 |
| host-context internal/host edgesFileLoop context.Background 2 |
| @@ -2163,7 +2166,9 @@ host-context internal/host package-level context.Background 1 |
| host-context internal/host parkRecoveryJournal context.Background 1 |
| host-context internal/host parkRevertJournal context.Background 1 |
| host-context internal/host platformUnitRestarts context.Background 1 |
| +host-context internal/host probeUnits context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host productionRootRestartChecks context.Background 1 |
| +host-context internal/host productionSysOps context.Background 2 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host proofObserver.observe context.Background 2 |
| host-context internal/host proofRoot.stillLive context.Background 1 |
| host-context internal/host publishResidentFleetBindings context.Background 1 |
| @@ -2177,6 +2182,7 @@ host-context internal/host releaseHousekeeperLease context.Background 1 |
| host-context internal/host releaseOwnLease context.Background 1 |
| host-context internal/host resolveHost context.Background 1 |
| host-context internal/host restartBoundUnit context.Background 4 |
| +host-context internal/host restartPathActive context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host retentionLoop context.Background 1 |
| host-context internal/host rollbackUnitRestart context.Background 5 |
| host-context internal/host rootInstallationHostApp context.Background 3 |
| @@ -2198,7 +2204,18 @@ host-context internal/host startHousekeeper context.Background 1 |
| host-context internal/host statusLoop context.Background 1 |
| host-context internal/host steeringLoop context.Background 1 |
| host-context internal/host sweepStagedVersions context.Background 1 |
| +host-context internal/host systemUpdatePathActive context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctl context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlProbe context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlRestartUnit context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlStartUnit context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlTryRestart context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlTryRestartUnit context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlVerb context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemdUnits.JournalTail context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemdUnits.Show context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host tunnelLoop context.Background 1 |
| +host-context internal/host unitsAreActive context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host usageLoop context.Background 1 |
| host-context internal/host validateServingParkRecord context.Background 2 |
| host-context internal/host wireRawSecretPages context.Background 1 |
diff --git a/internal/caps/converge.go b/internal/caps/converge.go| index 68ec9e7e5..d8305eb72 100644 |
| --- a/internal/caps/converge.go |
| +++ b/internal/caps/converge.go |
| @@ -10,6 +10,7 @@ package caps |
| import ( |
| "bytes" |
| + "context" |
| "errors" |
| "fmt" |
| "os" |
| @@ -1037,10 +1038,10 @@ func (o Ops) systemctl(args ...string) error { |
| if o.Systemctl != nil { |
| return o.Systemctl(args...) |
| } |
| - // Detached: Ops carries no context; the verb's bound is the deadline. |
| - out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(systemd.Detached()) |
| + // Background: Ops.systemctl takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(context.Background()) |
| if err != nil { |
| - return fmt.Errorf("systemctl %s: %v: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) |
| + return fmt.Errorf("systemctl %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) |
| } |
| return nil |
| } |
| @@ -1061,8 +1062,8 @@ func (o Ops) query(args ...string) bool { |
| if o.Query != nil { |
| return o.Query(args...) |
| } |
| - // Detached: Ops carries no context; the verb's bound is the deadline. |
| - return systemd.Command(systemd.Systemctl, args...).Run(systemd.Detached(), nil, nil) == nil |
| + // Background: Ops.query takes no context; QueryTimeout is this query's deadline. |
| + return systemd.Command(systemd.Systemctl, args...).Run(context.Background(), nil, nil) == nil |
| } |
| // ensureUser creates the locked, home-less, nologin system user a host_role |
diff --git a/internal/caps/systemctl_error_test.go b/internal/caps/systemctl_error_test.go| new file mode 100644 |
| index 000000000..f9e408eba |
| --- /dev/null |
| +++ b/internal/caps/systemctl_error_test.go |
| @@ -0,0 +1,30 @@ |
| +package caps |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// Ops.systemctl wraps systemctl's error with %w, so a caller can still read |
| +// it: the exit status here, and a TimeoutError's Temporary() through |
| +// caps.Restart into adoption, which decides on it whether to poison a |
| +// version. A fake systemctl on PATH answers; the real one never runs. |
| +func TestOpsSystemctlKeepsTheErrorReadable(t *testing.T) { |
| + bin := t.TempDir() |
| + if err := os.WriteFile(filepath.Join(bin, "systemctl"), []byte("#!/bin/sh\necho \"Unit $2 not found.\"\nexit 5\n"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) |
| + err := Ops{}.systemctl("restart", "carlos-app@shop.example.com.service") |
| + var ee *exec.ExitError |
| + if !errors.As(err, &ee) || ee.ExitCode() != 5 { |
| + t.Fatalf("err = %v, want systemctl's *exec.ExitError (exit 5) wrapped", err) |
| + } |
| + if !strings.Contains(err.Error(), "systemctl restart carlos-app@shop.example.com.service") || !strings.Contains(err.Error(), "not found") { |
| + t.Fatalf("err = %q, want the command and systemctl's words", err) |
| + } |
| +} |
diff --git a/internal/host/adopt_advice.go b/internal/host/adopt_advice.go| index 59ef23c43..9cdf30faf 100644 |
| --- a/internal/host/adopt_advice.go |
| +++ b/internal/host/adopt_advice.go |
| @@ -5,6 +5,7 @@ |
| package host |
| import ( |
| + "context" |
| "log" |
| "os/exec" |
| "os/user" |
| @@ -53,7 +54,8 @@ func unitsAreActive(hosts []string) map[string]bool { |
| for _, h := range hosts { |
| args = append(args, "carlos-app@"+h+".service") |
| } |
| - out, _ := systemd.Command(systemd.Systemctl, args...).Output(systemd.Detached()) |
| + // Background: unitsAreActive takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Systemctl, args...).Output(context.Background()) |
| return parseIsActiveBatch(out, hosts) |
| } |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index f850f78e6..a9cd9b53b 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -5546,7 +5546,8 @@ 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 := systemd.Command(systemd.Systemctl, "try-restart", activator.UnitName(host)).CombinedOutput(systemd.Detached()) |
| + // Background: systemctlTryRestart takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, "try-restart", activator.UnitName(host)).CombinedOutput(context.Background()) |
| if err != nil { |
| log.Printf("adopt: try-restart carlos-app@%s: %v: %s (continuing)", host, err, strings.TrimSpace(string(out))) |
| } |
| @@ -5571,7 +5572,8 @@ func systemctlTryRestart(host string) { |
| // ValidUnitName), where a typo can still be reported to the person who typed |
| // it. |
| func systemctlTryRestartUnit(unit string) error { |
| - out, err := systemd.Command(systemd.Systemctl, "try-restart", unit).CombinedOutput(systemd.Detached()) |
| + // Background: systemctlTryRestartUnit takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, "try-restart", unit).CombinedOutput(context.Background()) |
| 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))) |
| @@ -5693,7 +5695,8 @@ func agentRollbackUnitRestart(reg *registry.Registry, sys unitSystem, optDir str |
| // name an operator would grep for. Same no-shell shape too: the unit reaches |
| // systemctl as ONE argv element. |
| func systemctlStartUnit(unit string) error { |
| - out, err := systemd.Command(systemd.Systemctl, "start", unit).CombinedOutput(systemd.Detached()) |
| + // Background: systemctlStartUnit takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, "start", unit).CombinedOutput(context.Background()) |
| 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 e00a4d16a..1020bc6ca 100644 |
| --- a/internal/host/bootstrap.go |
| +++ b/internal/host/bootstrap.go |
| @@ -10,6 +10,7 @@ |
| package host |
| import ( |
| + "context" |
| "github.com/carlosframework/platform/internal/cliflag" |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/hostenv" |
| @@ -849,7 +850,8 @@ func bootstrapOwner(owner, group string) (int, int, error) { |
| } |
| func systemctl(args ...string) error { |
| - out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(systemd.Detached()) |
| + // Background: systemctl takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(context.Background()) |
| if err != nil { |
| return fmt.Errorf("systemctl %s: %v: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) |
| } |
diff --git a/internal/host/probes.go b/internal/host/probes.go| index 0de5f1e70..3931760db 100644 |
| --- a/internal/host/probes.go |
| +++ b/internal/host/probes.go |
| @@ -12,6 +12,7 @@ package host |
| import ( |
| "bufio" |
| + "context" |
| "io" |
| "os" |
| "strconv" |
| @@ -42,7 +43,8 @@ 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, _ := systemd.Command(systemd.Systemctl, "is-active", adoptTimerUnit).Output(systemd.Detached()) |
| + // Background: adoptTimerActive takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", adoptTimerUnit).Output(context.Background()) |
| return parseIsActive(string(out)) |
| } |
| @@ -60,7 +62,8 @@ 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, _ := systemd.Command(systemd.Systemctl, "is-active", configPathUnit).Output(systemd.Detached()) |
| + // Background: configPathActive takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", configPathUnit).Output(context.Background()) |
| return parseIsActive(string(out)) |
| } |
| @@ -79,7 +82,8 @@ 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, _ := systemd.Command(systemd.Systemctl, "is-active", restartPathUnit).Output(systemd.Detached()) |
| + // Background: restartPathActive takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", restartPathUnit).Output(context.Background()) |
| return parseIsActive(string(out)) |
| } |
| @@ -93,7 +97,8 @@ 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, _ := systemd.Command(systemd.Systemctl, "is-active", systemUpdatePathUnit).Output(systemd.Detached()) |
| + // Background: systemUpdatePathActive takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", systemUpdatePathUnit).Output(context.Background()) |
| return parseIsActive(string(out)) |
| } |
diff --git a/internal/host/rootrestart.go b/internal/host/rootrestart.go| index b48302a30..2429d33c0 100644 |
| --- a/internal/host/rootrestart.go |
| +++ b/internal/host/rootrestart.go |
| @@ -272,6 +272,13 @@ func checkedUnitRestart(sys unitSystem, optDir string, getenv func(string) strin |
| if errors.Is(err, errRestartBinding) && !restartEffectFailed(err) { |
| return errors.Join(err, settleRollbackAttempt(s, attempt)) |
| } |
| + if errors.Is(err, errUnitUnobserved) && !restartEffectFailed(err) { |
| + // Settle could not ask systemd about the unit: an unknown |
| + // observation, not a failed build. Settled like a stop, never |
| + // recorded failed or turned into a UnitNotUpError, so adoption |
| + // neither poisons the version nor runs the not-up recovery. |
| + return errors.Join(err, settleRollbackAttempt(s, attempt)) |
| + } |
| attempt.Failed = true |
| var notUp *release.UnitNotUpError |
| if !errors.As(err, ¬Up) { |
diff --git a/internal/host/settle_unobserved_adopt_test.go b/internal/host/settle_unobserved_adopt_test.go| new file mode 100644 |
| index 000000000..5c859428c |
| --- /dev/null |
| +++ b/internal/host/settle_unobserved_adopt_test.go |
| @@ -0,0 +1,118 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "errors" |
| + "runtime" |
| + "slices" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// settleOutcomeThroughAdoption runs one adoption pass of v2 over two |
| +// named-unit routes of one app that both run v1. The first restart the pass |
| +// asks for returns first (an error settleUnit produced); every later one |
| +// succeeds. It reports which hosts were restarted, which got the not-up |
| +// recovery (WithRollbackRestart), which got the plain start, and the |
| +// version each live link names after the pass. |
| +func settleOutcomeThroughAdoption(t *testing.T, first error) (restarted, recovered, started []string, live map[string]string) { |
| + t.Helper() |
| + ctx := context.Background() |
| + optDir := t.TempDir() |
| + s := release.NewDirStore(t.TempDir()) |
| + plat := runtime.GOOS + "-" + runtime.GOARCH |
| + pub, priv, err := ed25519.GenerateKey(nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + reg := restartTestRegistry(t) |
| + hosts := []string{"a.console.test", "b.console.test"} |
| + for i, h := range hosts { |
| + // Different upstreams: two processes, so a not-up group rollback |
| + // does not take the other route with it. |
| + if err := reg.Upsert(registry.Route{Host: h, Kind: "instance", App: "console", Channel: "canary/console", |
| + Addr: []string{"127.0.0.1:8091", "127.0.0.1:8092"}[i], Status: "ready", Unit: "console-" + string(rune('a'+i)) + ".service"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, v := range []string{"v1", "v2"} { |
| + m := release.Manifest{App: "console", Version: v, Kind: "binary", Artifacts: map[string]release.Artifact{plat: {}}} |
| + if err := release.Ship(ctx, s, "bab", m, map[string][]byte{plat: []byte("build " + v)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := release.StageArtifact(optDir, "bab", "v1", "console", []byte("build v1")); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, h := range hosts { |
| + if err := release.PointLive(optDir, h, "bab", "v1", "console"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := release.Promote(ctx, s, priv, "bab", "console", "canary/console", "v2"); err != nil { |
| + t.Fatal(err) |
| + } |
| + restart := func(h string) error { |
| + restarted = append(restarted, h) |
| + if len(restarted) == 1 { |
| + return first |
| + } |
| + return nil |
| + } |
| + _ = release.Pass(ctx, reg, s, pub, optDir, restart, |
| + release.WithStartUnit(func(h string) error { started = append(started, h); return nil }), |
| + release.WithRollbackRestart(func(h string) error { recovered = append(recovered, h); return nil })) |
| + live = map[string]string{} |
| + for _, h := range hosts { |
| + live[h], _ = release.LiveVersion(optDir, h) |
| + } |
| + return restarted, recovered, started, live |
| +} |
| + |
| +// A settle that could not observe the unit by its deadline is an unknown |
| +// outcome through adoption: the version is not poisoned (the pass still |
| +// adopts it on the other route) and the route gets no not-up recovery |
| +// (no reset-failed and restart of what runs). The symlink is still put |
| +// back and the plain start offered, as for any restart error. |
| +func TestUnobservedSettleNeitherPoisonsNorRecovers(t *testing.T) { |
| + unobserved := settleUnit(&showErrs{fakeUnits: &fakeUnits{}, err: errors.New("Failed to get properties: Connection timed out")}, |
| + "console-a.service", "old", opts(func() error { return nil })) |
| + restarted, recovered, started, live := settleOutcomeThroughAdoption(t, unobserved) |
| + if len(restarted) != 2 { |
| + t.Fatalf("restarted %v, want both routes: an unknown observation must not poison v2 for the pass", restarted) |
| + } |
| + if len(recovered) != 0 { |
| + t.Fatalf("not-up recovery ran for %v, want none for an unknown observation", recovered) |
| + } |
| + if !slices.Equal(started, restarted[:1]) { |
| + t.Fatalf("started %v, want the plain start for %s alone", started, restarted[0]) |
| + } |
| + if live[restarted[0]] != "v1" || live[restarted[1]] != "v2" { |
| + t.Fatalf("live = %v, want %s back on v1 and %s on v2", live, restarted[0], restarted[1]) |
| + } |
| +} |
| + |
| +// The other side: a unit settle saw fail is a verdict. v2 is poisoned for |
| +// the pass (the second route is not tried) and the route gets the not-up |
| +// recovery, not the plain start. |
| +func TestFailedSettleStillPoisonsAndRecovers(t *testing.T) { |
| + failed := settleUnit(&fakeUnits{shows: []unitProps{{ActiveState: "failed", SubState: "failed", InvocationID: "new"}}}, |
| + "console-a.service", "old", opts(func() error { return nil })) |
| + var nu *release.UnitNotUpError |
| + if !errors.As(failed, &nu) { |
| + t.Fatalf("settle = %v, want UnitNotUpError for a failed unit", failed) |
| + } |
| + restarted, recovered, started, live := settleOutcomeThroughAdoption(t, failed) |
| + if len(restarted) != 1 { |
| + t.Fatalf("restarted %v, want one: a failed build poisons v2 for the pass", restarted) |
| + } |
| + if !slices.Equal(recovered, restarted) || len(started) != 0 { |
| + t.Fatalf("recovered %v, started %v; want the not-up recovery for %s and no plain start", recovered, started, restarted[0]) |
| + } |
| + if live[restarted[0]] != "v1" { |
| + t.Fatalf("live = %v, want %s back on v1", live, restarted[0]) |
| + } |
| +} |
diff --git a/internal/host/settle_unobserved_root_test.go b/internal/host/settle_unobserved_root_test.go| new file mode 100644 |
| index 000000000..7d617aa97 |
| --- /dev/null |
| +++ b/internal/host/settle_unobserved_root_test.go |
| @@ -0,0 +1,81 @@ |
| +package host |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rootstate" |
| +) |
| + |
| +// unobservedAfterRestart is plan14RestartUnits whose show fails once the |
| +// restart has been asked for: systemd took the job and then stopped |
| +// answering, so settle never sees the new invocation. |
| +type unobservedAfterRestart struct { |
| + *plan14RestartUnits |
| + restarted bool |
| +} |
| + |
| +func (u *unobservedAfterRestart) TryRestart(unit string) error { |
| + u.restarted = true |
| + return u.plan14RestartUnits.TryRestart(unit) |
| +} |
| + |
| +func (u *unobservedAfterRestart) Show(unit string) (unitProps, error) { |
| + if u.restarted { |
| + return unitProps{}, errors.New("Failed to get properties: Connection timed out") |
| + } |
| + return u.plan14RestartUnits.Show(unit) |
| +} |
| + |
| +// The root adopt pass's checked restart, when settle cannot observe the unit |
| +// by its deadline: the answer stays an unknown observation (not a |
| +// UnitNotUpError, temporary), and the rollback attempt is settled, not |
| +// recorded failed, so neither adoption nor a later root recovery treats the |
| +// build as one that crashed. |
| +func TestRootRestartUnobservedSettleIsNotAFailedAttempt(t *testing.T) { |
| + t.Parallel() |
| + e, rt, units, c, _ := plan14AdoptionFixture(t) |
| + sys := &unobservedAfterRestart{plan14RestartUnits: units} |
| + forward := rootRestartRouteWith(e.root.reg, sys, units.opt, func(string) string { return "5s" }, e.root.obs.recordSettled(e.bake), c) |
| + if err := release.StageArtifact(units.opt, "bab", "v2", "console", []byte("new build")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.PointLive(units.opt, rt.Host, "bab", "v2", "console"); err != nil { |
| + t.Fatal(err) |
| + } |
| + err := forward(rt.Host) |
| + var nu *release.UnitNotUpError |
| + var temporary interface{ Temporary() bool } |
| + if err == nil || errors.As(err, &nu) || !errors.Is(err, errUnitUnobserved) { |
| + t.Fatalf("forward restart = %v, want the unknown observation, not UnitNotUpError", err) |
| + } |
| + if !errors.As(err, &temporary) || !temporary.Temporary() { |
| + t.Fatalf("forward restart = %v, want it temporary", err) |
| + } |
| + if !sys.restarted { |
| + t.Fatal("the restart was never asked for; the test proves nothing") |
| + } |
| + store, err := c.attempts() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + attempt := readAttempt(t, store, rt.Host) |
| + if attempt.Failed || !attempt.Settled { |
| + t.Fatalf("attempt = Failed %v Settled %v, want settled and not failed", attempt.Failed, attempt.Settled) |
| + } |
| +} |
| + |
| +func readAttempt(t *testing.T, s rootstate.Store, host string) rollbackAttempt { |
| + t.Helper() |
| + raw, err := s.Read(rollbackJournalKey(host)) |
| + if err != nil { |
| + t.Fatalf("no rollback attempt for %s: %v", host, err) |
| + } |
| + var a rollbackAttempt |
| + if err := json.Unmarshal(raw, &a); err != nil { |
| + t.Fatal(err) |
| + } |
| + return a |
| +} |
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go| index 381352f62..6e891c6fc 100644 |
| --- a/internal/host/systemapply.go |
| +++ b/internal/host/systemapply.go |
| @@ -201,24 +201,14 @@ 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) { |
| - c := systemd.Command(systemd.Systemctl, args...) |
| - c.ControlTimeout = systemApplyControlTimeout |
| - out, err := c.CombinedOutput(systemd.Detached()) |
| + // Background: the sysOps seam takes no context. A query is bounded |
| + // by QueryTimeout; a mutation (the edge restart above all) has no |
| + // deadline of its own, as before (internal/systemd). |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(context.Background()) |
| if err != nil { |
| return string(out), fmt.Errorf("systemctl %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) |
| } |
| @@ -256,7 +246,8 @@ func productionSysOps() sysOps { |
| return nil |
| }, |
| edgeStartedThisBoot: func() bool { |
| - out, err := systemd.Command(systemd.Systemctl, "show", "-p", "ActiveEnterTimestampMonotonic", "--value", systemEdgeUnit).Output(systemd.Detached()) |
| + // Background: edgeStartedThisBoot takes no context; QueryTimeout is this query's deadline. |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "ActiveEnterTimestampMonotonic", "--value", systemEdgeUnit).Output(context.Background()) |
| 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 53d004061..cf920974b 100644 |
| --- a/internal/host/systemunits.go |
| +++ b/internal/host/systemunits.go |
| @@ -2,6 +2,7 @@ package host |
| import ( |
| "bytes" |
| + "context" |
| "errors" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/systemd" |
| @@ -324,7 +325,8 @@ 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 := systemd.Command(systemd.Systemctl, args...).Output(systemd.Detached()) |
| + // Background: systemctlProbe takes no context; QueryTimeout is this query's deadline. |
| + out, err := systemd.Command(systemd.Systemctl, args...).Output(context.Background()) |
| return string(out), err |
| } |
diff --git a/internal/host/unitops.go b/internal/host/unitops.go| index c5399e59e..4c960b3ba 100644 |
| --- a/internal/host/unitops.go |
| +++ b/internal/host/unitops.go |
| @@ -6,6 +6,7 @@ package host |
| import ( |
| "bytes" |
| + "context" |
| "fmt" |
| "log" |
| "os" |
| @@ -138,7 +139,8 @@ 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 := systemd.Command(systemd.Systemctl, args...).Output(systemd.Detached()) |
| + // Background: probeUnits takes no context; QueryTimeout is this query's deadline. |
| + out, err := systemd.Command(systemd.Systemctl, args...).Output(context.Background()) |
| if err != nil && len(out) == 0 { |
| return nil, fmt.Errorf("systemctl show: %w", err) |
| } |
| @@ -188,7 +190,8 @@ func parseSystemctlShow(out []byte, units []string) (map[string]appconfig.UnitSt |
| } |
| func daemonReload() error { |
| - out, err := systemd.Command(systemd.Systemctl, "daemon-reload").CombinedOutput(systemd.Detached()) |
| + // Background: daemonReload takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, "daemon-reload").CombinedOutput(context.Background()) |
| if err != nil { |
| return fmt.Errorf("daemon-reload: %w: %s", err, strings.TrimSpace(string(out))) |
| } |
| @@ -199,7 +202,8 @@ 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 := systemd.Command(systemd.Systemctl, "restart", unit).CombinedOutput(systemd.Detached()) |
| + // Background: systemctlRestartUnit takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, "restart", unit).CombinedOutput(context.Background()) |
| 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 91c1bbb86..f87bbedea 100644 |
| --- a/internal/host/unitsettle.go |
| +++ b/internal/host/unitsettle.go |
| @@ -59,8 +59,9 @@ type unitSystem interface { |
| type systemdUnits struct{} |
| func (systemdUnits) Show(unit string) (unitProps, error) { |
| + // Background: unitSystem.Show takes no context; QueryTimeout is this query's deadline. |
| 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()) |
| + "-p", "Id", "-p", "FragmentPath", "-p", "DropInPaths", "-p", "ActiveState", "-p", "SubState", "-p", "InvocationID", "-p", "MainPID", "-p", "NRestarts", "-p", "ExecStart", "-p", "ActiveEnterTimestamp").Output(context.Background()) |
| if err != nil { |
| return unitProps{}, fmt.Errorf("systemctl show %s: %w", unit, err) |
| } |
| @@ -72,7 +73,8 @@ 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, _ := systemd.Command(systemd.Journalctl, "-u", unit, "-o", "cat", "-n", strconv.Itoa(n), "--no-pager").Output(systemd.Detached()) |
| + // Background: unitSystem.JournalTail takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Journalctl, "-u", unit, "-o", "cat", "-n", strconv.Itoa(n), "--no-pager").Output(context.Background()) |
| return strings.TrimSpace(string(out)) |
| } |
| @@ -103,7 +105,8 @@ func (systemdUnits) StartTime(pid int) (string, error) { |
| } |
| func systemctlVerb(verb, unit string) error { |
| - out, err := systemd.Command(systemd.Systemctl, verb, unit).CombinedOutput(systemd.Detached()) |
| + // Background: systemctlVerb takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, verb, unit).CombinedOutput(context.Background()) |
| if err != nil { |
| return fmt.Errorf("systemctl %s %s: %w: %s", verb, unit, err, strings.TrimSpace(string(out))) |
| } |
| @@ -175,6 +178,29 @@ type settleOpts struct { |
| // nothing and restarts nothing. |
| var errUnitStopped = errors.New("unit was stopped during settle") |
| +// errUnitUnobserved is what settleUnit's answer wraps when its deadline |
| +// passed while systemd could not be asked about the unit (the last show |
| +// failed: refused, a D-Bus error, killed at its QueryTimeout). That is an |
| +// unknown observation, not evidence the build failed: it is not a |
| +// *release.UnitNotUpError, so adoption gives the route no not-up recovery, |
| +// and it is temporary, so adoption does not poison the version. A unit |
| +// settle did see fail, run the wrong executable or miss its readiness |
| +// keeps its UnitNotUpError. |
| +var errUnitUnobserved = errors.New("unit could not be observed before the settle deadline") |
| + |
| +// unitUnobservedError is errUnitUnobserved with the unit and the last show |
| +// error. |
| +type unitUnobservedError struct { |
| + unit string |
| + err error |
| +} |
| + |
| +func (e *unitUnobservedError) Error() string { |
| + return fmt.Sprintf("cannot observe %s before the settle deadline: %v", e.unit, e.err) |
| +} |
| +func (e *unitUnobservedError) Unwrap() []error { return []error{errUnitUnobserved, e.err} } |
| +func (e *unitUnobservedError) Temporary() bool { return true } |
| + |
| // settleUnit watches unit after a try-restart. beforeInvocation is the |
| // InvocationID before the restart; "" means the unit was not running, and an |
| // inactive unit is then "nothing started", not a failure. Otherwise a unit |
| @@ -200,10 +226,11 @@ func settleUnit(sys unitSystem, unit, beforeInvocation string, o settleOpts) err |
| p, err := sys.Show(unit) |
| if err != nil { |
| // One failed `systemctl show` says nothing about the build (a |
| - // busy bus, a timed-out D-Bus call). Retried until the deadline, |
| - // and only a deadline that still cannot observe the unit fails. |
| + // busy bus, a timed-out D-Bus call). Retried until the deadline; |
| + // a deadline that still cannot observe the unit is an unknown |
| + // observation (errUnitUnobserved), never a verdict. |
| if !o.Now().Before(deadline) { |
| - return notUp(fmt.Sprintf("cannot observe %s: %v", unit, err)) |
| + return &unitUnobservedError{unit: unit, err: err} |
| } |
| o.Sleep(o.Poll) |
| continue |
diff --git a/internal/host/unitsettle_test.go b/internal/host/unitsettle_test.go| index a6b37e81b..1b1917487 100644 |
| --- a/internal/host/unitsettle_test.go |
| +++ b/internal/host/unitsettle_test.go |
| @@ -16,6 +16,7 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| type fakeUnits struct { |
| @@ -188,15 +189,41 @@ func TestSettleRetriesATransientShowError(t *testing.T) { |
| } |
| } |
| +// A settle whose deadline passes while systemd cannot be asked about the |
| +// unit is an unknown observation, not a verdict on the build: no |
| +// UnitNotUpError (which would send adoption to the not-up recovery), and |
| +// temporary (so adoption does not poison the version), whether the show |
| +// was refused or killed at its bound. The error still names the unit and |
| +// why it could not be observed. |
| func TestSettleShowErrorAtTheDeadline(t *testing.T) { |
| - sys := &showFails{fakeUnits: &fakeUnits{}} |
| - var nu *release.UnitNotUpError |
| - err := settleUnit(sys, "console.service", "old", opts(func() error { return nil })) |
| - if !errors.As(err, &nu) || !strings.Contains(nu.Reason, "cannot observe console.service: Access denied") { |
| - t.Fatalf("settle = %v, want a deadline UnitNotUpError saying the unit could not be observed", err) |
| + for name, showErr := range map[string]error{ |
| + "refused": errors.New("Access denied"), |
| + "timed out": &systemd.TimeoutError{Program: "systemctl", Verb: "show", Units: []string{"console.service"}, After: systemd.QueryTimeout}, |
| + } { |
| + sys := &showErrs{fakeUnits: &fakeUnits{}, err: showErr} |
| + err := settleUnit(sys, "console.service", "old", opts(func() error { return nil })) |
| + var nu *release.UnitNotUpError |
| + var temporary interface{ Temporary() bool } |
| + if err == nil || errors.As(err, &nu) { |
| + t.Errorf("%s: settle = %v, want an unknown observation, not UnitNotUpError", name, err) |
| + continue |
| + } |
| + if !errors.As(err, &temporary) || !temporary.Temporary() { |
| + t.Errorf("%s: settle = %v, want it temporary", name, err) |
| + } |
| + if !strings.Contains(err.Error(), "console.service") || !strings.Contains(err.Error(), showErr.Error()) { |
| + t.Errorf("%s: settle = %v, want it to name the unit and the show's error", name, err) |
| + } |
| } |
| } |
| +type showErrs struct { |
| + *fakeUnits |
| + err error |
| +} |
| + |
| +func (s showErrs) Show(string) (unitProps, error) { return unitProps{}, s.err } |
| + |
| // Final review F2: inactive/dead after the restart is an operator's stop. |
| func TestSettleStoppedUnitIsErrUnitStopped(t *testing.T) { |
| f := &fakeUnits{shows: []unitProps{ |
diff --git a/internal/systemd/command.go b/internal/systemd/command.go| index 5a2b64a9a..657a14701 100644 |
| --- a/internal/systemd/command.go |
| +++ b/internal/systemd/command.go |
| @@ -1,18 +1,30 @@ |
| -// 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. |
| +// Package systemd runs systemctl and journalctl. Every call in the root |
| +// binary goes through Command (TestSystemctlCallsAreBounded), and the verbs |
| +// fall in two classes: |
| // |
| -// 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. |
| +// - A query (show, is-active, is-enabled, list-units, cat, and every |
| +// journalctl call) only reads systemd's state. It runs under the |
| +// caller's context and QueryTimeout, whichever ends first: 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 ask while holding reconcileMu or configSyncMu. At the |
| +// bound the process is killed and the error is a *TimeoutError naming |
| +// the verb and the units. |
| +// - A mutation (start, stop, restart, try-restart, reload, daemon-reload, |
| +// reset-failed, enable, set-property, kill, and any verb not listed as |
| +// a query) gets NO deadline of its own: it runs under the caller's |
| +// context alone, exactly as exec.CommandContext did before this |
| +// package. Killing systemctl does not cancel the job it queued, so a |
| +// timed-out restart is an unknown outcome: the unit may be running the |
| +// new build or still stopping the old one. Every caller today reads a |
| +// mutation's error as "it did not happen" (adoption rolls back and |
| +// starts the old build, which is a no-op over a new process that did |
| +// come up), so bounding mutations needs a way to reconcile the job's |
| +// outcome first. That is follow-up work with its own spec. |
| +// |
| +// When the caller's own context ends a call, the error is os/exec's, |
| +// unchanged. 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, |
| @@ -37,24 +49,11 @@ import ( |
| // 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. |
| +// killWait is a query's 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. A mutation |
| +// sets none, as before. |
| const killWait = time.Second |
| // Program is the program a Command runs. |
| @@ -79,23 +78,9 @@ var programPaths = map[Program]string{ |
| 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. |
| +// Cmd is one 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 |
| @@ -136,21 +121,33 @@ func (c *Cmd) run(ctx context.Context, do func(*exec.Cmd) ([]byte, error)) ([]by |
| 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) { |
| + setup := func(cmd *exec.Cmd) ([]byte, error) { |
| cmd.Env, cmd.Dir = c.Env, c.Dir |
| return do(cmd) |
| - }, c.describe) |
| + } |
| + bound := c.bound() |
| + if bound == 0 { |
| + // A mutation: the caller's context alone, as before (see the |
| + // package comment). |
| + return setup(exec.CommandContext(ctx, path, c.args...)) |
| + } |
| + return bounded(ctx, path, c.args, bound, setup, c.describe) |
| } |
| -// bound is the deadline this command's verb gets. |
| +// bound is the deadline this command's class gets: QueryTimeout for a |
| +// query, 0 (none of its own) for a mutation. |
| func (c *Cmd) bound() time.Duration { |
| - if verb, _ := describe(c.args); c.program == Journalctl || queryVerbs[verb] { |
| + if c.query() { |
| return QueryTimeout |
| } |
| - if c.ControlTimeout > 0 { |
| - return c.ControlTimeout |
| - } |
| - return ControlTimeout |
| + return 0 |
| +} |
| + |
| +// query reports whether the command is in the query class: journalctl, or |
| +// a systemctl verb in queryVerbs. Everything else is a mutation. |
| +func (c *Cmd) query() bool { |
| + verb, _ := describe(c.args) |
| + return c.program == Journalctl || queryVerbs[verb] |
| } |
| // describe names the command for a TimeoutError. |
| @@ -162,8 +159,8 @@ func (c *Cmd) describe() (program, verb string, units []string) { |
| 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 |
| +// bounded runs a query's 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. |
| @@ -180,10 +177,10 @@ func bounded(parent context.Context, path string, args []string, bound time.Dura |
| 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). |
| +// TimeoutError is a query that did not finish within QueryTimeout and was |
| +// killed. It is temporary: the next pass asks again, and an unanswered |
| +// question is not a verdict on a build (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 |
| @@ -213,7 +210,8 @@ 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. |
| +// queryVerbs only read systemd's state: the query class. Every other verb |
| +// is a mutation. |
| 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, |
diff --git a/internal/systemd/command_test.go b/internal/systemd/command_test.go| index eb2ef3ad0..7ab9af3a1 100644 |
| --- a/internal/systemd/command_test.go |
| +++ b/internal/systemd/command_test.go |
| @@ -52,15 +52,18 @@ func gone(t *testing.T, dir string) bool { |
| 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) { |
| +// A query that hangs is killed at the bound, and the error says which verb |
| +// and unit, is a timeout, and is temporary. The bound is QueryTimeout's |
| +// class; the test hands bounded a short one so it need not wait 30 s. |
| +func TestHungQueryIsKilledAtTheBound(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 |
| + c := Command(Systemctl, "show", "-p", "MainPID", "--value", "carlos-app@shop.example.com.service") |
| + if c.bound() != QueryTimeout { |
| + t.Fatalf("show's bound is %s, want QueryTimeout", c.bound()) |
| + } |
| start := time.Now() |
| - _, err := c.CombinedOutput(context.Background()) |
| + _, err := bounded(context.Background(), programPaths[Systemctl], c.args, bound, func(cmd *exec.Cmd) ([]byte, error) { return cmd.Output() }, c.describe) |
| took := time.Since(start) |
| var te *TimeoutError |
| if !errors.As(err, &te) { |
| @@ -69,7 +72,7 @@ func TestHungSystemctlIsKilledAtTheBound(t *testing.T) { |
| 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" |
| + want := "systemctl show carlos-app@shop.example.com.service: no answer within 300ms; killed" |
| if err.Error() != want { |
| t.Fatalf("err = %q, want %q", err, want) |
| } |
| @@ -102,22 +105,44 @@ func TestHungJournalctlIsKilledAtTheBound(t *testing.T) { |
| } |
| } |
| -// SystemctlAbsolute runs the absolute path with no PATH lookup, under the |
| -// same bound. |
| -func TestAbsoluteSystemctlIsBounded(t *testing.T) { |
| +// A verb that changes state gets no deadline of its own: killing systemctl |
| +// does not cancel systemd's job, so a timed-out restart is an unknown |
| +// outcome no caller handles yet. It runs under the caller's context alone, |
| +// as it did before this package: a caller deadline still kills it, with |
| +// os/exec's error and no TimeoutError. |
| +func TestMutatingVerbHasOnlyTheCallersDeadline(t *testing.T) { |
| + for _, args := range [][]string{ |
| + {"restart", "u"}, {"try-restart", "u"}, {"start", "--no-block", "u"}, {"stop", "u"}, |
| + {"reload", "u"}, {"daemon-reload"}, {"reset-failed", "u"}, {"enable", "u"}, {"set-property", "u", "X=1"}, nil, |
| + } { |
| + if b := Command(Systemctl, args...).bound(); b != 0 { |
| + t.Errorf("%v: bound %s, want none", args, b) |
| + } |
| + } |
| fakeSystemctl(t, hang) |
| + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) |
| + defer cancel() |
| + err := Command(SystemctlAbsolute, "restart", "carlos-edge.service").Run(ctx, nil, nil) |
| + var te *TimeoutError |
| + var ee *exec.ExitError |
| + if errors.As(err, &te) || !errors.As(err, &ee) { |
| + t.Fatalf("err = %v (%T), want the killed process's *exec.ExitError from the caller's deadline", err, err) |
| + } |
| +} |
| + |
| +// SystemctlAbsolute runs the absolute path with no PATH lookup. |
| +func TestAbsoluteSystemctlRunsTheFixedPath(t *testing.T) { |
| + fakeSystemctl(t, `echo "abs $*"`) |
| t.Setenv("PATH", "/nonexistent") |
| - c := Command(SystemctlAbsolute, "stop", "carlos-edge.service") |
| - c.ControlTimeout = 200 * time.Millisecond |
| + c := Command(SystemctlAbsolute, "show", "carlos-edge.service") |
| 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) |
| + var out strings.Builder |
| + if err := c.Run(context.Background(), &out, nil); err != nil || out.String() != "abs show carlos-edge.service\n" { |
| + t.Fatalf("out = %q, err = %v", out.String(), err) |
| } |
| } |
| -// A caller whose own deadline ends the call first gets os/exec's error, as |
| +// A caller whose own deadline ends a query first gets os/exec's error, as |
| // before the helper: the bound did not end it. |
| func TestCallerDeadlineKeepsExecError(t *testing.T) { |
| fakeSystemctl(t, hang) |
| @@ -162,34 +187,24 @@ func TestAnswersPassThrough(t *testing.T) { |
| 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}, |
| + {Systemctl, []string{"show", "-p", "MainPID", "--value", "u"}, QueryTimeout}, |
| + {Systemctl, []string{"--no-pager", "list-units", "--all", "carlos-*"}, QueryTimeout}, |
| + {Systemctl, []string{"is-active", "a", "b"}, QueryTimeout}, |
| + {Systemctl, []string{"is-enabled", "a"}, QueryTimeout}, |
| + {Systemctl, []string{"cat", "--no-pager", "u"}, QueryTimeout}, |
| + {SystemctlAbsolute, []string{"list-jobs", "--plain"}, QueryTimeout}, |
| + {Journalctl, []string{"-u", "u"}, QueryTimeout}, |
| + {Systemctl, []string{"restart", "u"}, 0}, |
| + {Systemctl, []string{"daemon-reload"}, 0}, |
| } |
| for _, c := range cases { |
| - cmd := Command(c.program, c.args...) |
| - cmd.ControlTimeout = c.control |
| - if got := cmd.bound(); got != c.want { |
| + if got := Command(c.program, c.args...).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) { |
diff --git a/internal/systemd/guard_test.go b/internal/systemd/guard_test.go| index f18a62b5e..aab1bcc90 100644 |
| --- a/internal/systemd/guard_test.go |
| +++ b/internal/systemd/guard_test.go |
| @@ -9,26 +9,49 @@ import ( |
| "os" |
| "os/exec" |
| "path/filepath" |
| + "regexp" |
| "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 |
| +// unboundedSystemctlAllowlist names root-graph files that may still run |
| +// systemctl or journalctl some other way, and why. Empty: every call goes |
| // through this package. A file added here must say what bounds its call. |
| var unboundedSystemctlAllowlist = map[string]string{} |
| +// remoteScripts names the root-graph files that build a systemctl command |
| +// line for ANOTHER box's shell, and the text that shows it. Neither rule |
| +// below matches them, because no local exec runs the string; the entry |
| +// keeps the exception named and narrow: the test checks the file still |
| +// holds that text and still has no hit. |
| +var remoteScripts = map[string]string{ |
| + // The edge-stop step of a group roll, sent to the member box over SSM |
| + // (NonInteractiveCommands) and bounded there by /usr/bin/timeout. |
| + "internal/grouproll/box.go": "/usr/bin/systemctl stop carlos-edge.service; ", |
| +} |
| + |
| // 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. |
| +// root binary links (linux, amd64 and arm64), outside this package, runs |
| +// systemctl or journalctl other than through Command. Two rules, over the |
| +// file's string constants with simple constant folding (literals, "+" |
| +// concatenation, const and string variables of the same package or |
| +// function, and fmt.Sprintf's format): |
| +// |
| +// - a program name: a string that is exactly "systemctl" or "journalctl" |
| +// or a path ending in /systemctl or /journalctl, wherever it appears |
| +// (exec.Command's name, a seam's first argument, a constant, |
| +// "system"+"ctl"); |
| +// - a local shell: a call whose arguments name a shell (sh, bash, dash, |
| +// by name or path) followed by an argument that holds systemctl or |
| +// journalctl as a word ("sh", "-c", "systemctl restart x"; the same |
| +// string in a variable; fmt.Sprintf("systemctl %s", u)). |
| +// |
| +// A sentence that only mentions a program ("run systemctl restart |
| +// carlos-edge" in a message) is neither and passes. What the folding |
| +// cannot see (a string built by another function, a constant from another |
| +// package handed to a shell) is outside the guard; review holds it. |
| func TestSystemctlCallsAreBounded(t *testing.T) { |
| if testing.Short() { |
| t.Skip("lists the root binary's packages with go list") |
| @@ -38,19 +61,31 @@ func TestSystemctlCallsAreBounded(t *testing.T) { |
| if len(files) < 100 { |
| t.Fatalf("listed only %d root-binary files; the scan would prove nothing", len(files)) |
| } |
| + byDir := map[string][]string{} |
| + for _, rel := range files { |
| + byDir[filepath.Dir(rel)] = append(byDir[filepath.Dir(rel)], rel) |
| + } |
| var bad []string |
| seen := map[string]bool{} |
| - for _, rel := range files { |
| - if strings.HasPrefix(rel, "internal/systemd/") { |
| + scanned := map[string]bool{} |
| + for dir, rels := range byDir { |
| + if dir == "internal/systemd" { |
| continue |
| } |
| - hits := programNames(t, filepath.Join(root, rel)) |
| - if _, ok := unboundedSystemctlAllowlist[rel]; ok { |
| - seen[rel] = len(hits) > 0 |
| - continue |
| + paths := make([]string, len(rels)) |
| + for i, rel := range rels { |
| + paths[i] = filepath.Join(root, rel) |
| } |
| - for _, h := range hits { |
| - bad = append(bad, rel+":"+h) |
| + for i, hits := range unboundedRuns(t, paths) { |
| + rel := rels[i] |
| + scanned[rel] = true |
| + if _, ok := unboundedSystemctlAllowlist[rel]; ok { |
| + seen[rel] = len(hits) > 0 |
| + continue |
| + } |
| + for _, h := range hits { |
| + bad = append(bad, rel+":"+h) |
| + } |
| } |
| } |
| sort.Strings(bad) |
| @@ -59,73 +94,279 @@ func TestSystemctlCallsAreBounded(t *testing.T) { |
| } |
| 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) |
| + t.Errorf("%s is allowlisted but runs neither program (or left the root binary): drop it from the allowlist", rel) |
| + } |
| + } |
| + for rel, text := range remoteScripts { |
| + body, err := os.ReadFile(filepath.Join(root, rel)) |
| + if !scanned[rel] || err != nil || !strings.Contains(string(body), strconv.Quote(text)) { |
| + t.Errorf("%s: its remote systemctl script %q is gone or left the root binary: drop it from remoteScripts", rel, text) |
| } |
| } |
| } |
| -// The scan catches each shape a call has taken, and lets a sentence through. |
| -func TestProgramNamesScan(t *testing.T) { |
| +// The scan catches each shape a local run has taken or could take, and |
| +// lets messages and a remote script through. |
| +func TestUnboundedRunsScan(t *testing.T) { |
| src := `package x |
| import ( |
| "context" |
| + "fmt" |
| + "log" |
| "os/exec" |
| ) |
| const bin = "/usr/bin/systemctl" |
| +const prog = "system" + "ctl" |
| +const restartEdge = "systemctl restart carlos-edge.service" |
| +var pkgScript = "journalctl -u carlos-edge.service" |
| 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") |
| +func f(ctx context.Context, unit string) { |
| + exec.Command("systemctl", "show") // 1 program name |
| + exec.CommandContext(ctx, "journalctl", "-u", "x") // 2 program name |
| + exec.Command(bin) // 3 at the const (line 8) |
| + run(ctx, "journalctl", "--no-pager") // 4 program name |
| + exec.Command("/bin/journalctl") // 5 program name |
| + exec.Command(prog) // 6 at the folded const (line 9) |
| + exec.Command("sh", "-c", "systemctl restart carlos-edge") // 7 local shell |
| + script := "systemctl stop " + unit |
| + exec.Command("/bin/bash", "-c", script) // 8 local shell via a variable |
| + exec.Command("sh", "-c", restartEdge) // 9 local shell via a const |
| + exec.Command("dash", "-c", fmt.Sprintf("systemctl %s", unit)) // 10 local shell via Sprintf |
| + run(ctx, "unshare", "-m", "sh", "-c", pkgScript) // 11 local shell via a package var |
| + exec.Command("sh", "-c", "echo "+"systemctl") // 12 local shell, folded |
| + |
| _ = "run systemctl restart carlos-edge" |
| - _ = "systemctl show" |
| + _ = fmt.Errorf("systemctl show %s: failed", unit) |
| + log.Printf("systemctl %s: %v", unit, nil) |
| + exec.Command("sh", "-c", "echo hello") |
| + exec.Command("nft", "list", "ruleset") |
| + remote := "/usr/bin/systemctl stop carlos-edge.service; " |
| + send(remote) |
| _ = "systemd-journald" |
| } |
| +func send(string) {} |
| ` |
| 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) |
| + got := unboundedRuns(t, []string{path})[0] |
| + if len(got) != 12 { |
| + t.Fatalf("caught %d, want 12:\n%s", len(got), strings.Join(got, "\n")) |
| + } |
| +} |
| + |
| +var ( |
| + shells = map[string]bool{"sh": true, "bash": true, "dash": true} |
| + progWord = regexp.MustCompile(`(^|[^A-Za-z0-9_.@-])(systemctl|journalctl)($|[^A-Za-z0-9_.@-])`) |
| +) |
| + |
| +func programName(v string) bool { |
| + for _, p := range []string{"systemctl", "journalctl"} { |
| + if v == p || strings.HasSuffix(v, "/"+p) { |
| + return true |
| + } |
| } |
| + return false |
| +} |
| + |
| +func shellName(v string) bool { |
| + return shells[v] || shells[v[strings.LastIndex(v, "/")+1:]] && strings.HasPrefix(v, "/") |
| } |
| -// 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 { |
| +// unboundedRuns scans one package's files together (so package constants |
| +// and variables resolve across them) and reports, per file, each hit as |
| +// line: what. |
| +func unboundedRuns(t *testing.T, paths []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 |
| + files := make([]*ast.File, len(paths)) |
| + pkgVals := map[string][]ast.Expr{} // package const and var initializers by name |
| + for i, path := range paths { |
| + f, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution) |
| + if err != nil { |
| + t.Fatalf("parse %s: %v", path, err) |
| + } |
| + files[i] = f |
| + for _, d := range f.Decls { |
| + if g, ok := d.(*ast.GenDecl); ok && (g.Tok == token.CONST || g.Tok == token.VAR) { |
| + for _, spec := range g.Specs { |
| + vs := spec.(*ast.ValueSpec) |
| + for j, n := range vs.Names { |
| + if j < len(vs.Values) { |
| + pkgVals[n.Name] = append(pkgVals[n.Name], vs.Values[j]) |
| + } |
| + } |
| + } |
| + } |
| + } |
| } |
| - 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 |
| + out := make([][]string, len(files)) |
| + for i, f := range files { |
| + imports := map[*ast.BasicLit]bool{} |
| + for _, imp := range f.Imports { |
| + imports[imp.Path] = true |
| } |
| - v, err := strconv.Unquote(lit.Value) |
| - if err != nil { |
| - return true |
| + var hits []string |
| + hit := func(n ast.Node, what string) { |
| + hits = append(hits, fmt.Sprintf("%d: %s", fset.Position(n.Pos()).Line, what)) |
| } |
| - 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)) |
| + // Program names: every literal, and every "+" whose operands fold |
| + // to constants (its own operands are then not checked again). |
| + folded := map[ast.Node]bool{} |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.BinaryExpr: |
| + if folded[n] || n.Op != token.ADD { |
| + return true |
| + } |
| + if v, ok := constString(n, pkgVals, 0); ok { |
| + markFolded(n, folded) |
| + if programName(v) { |
| + hit(n, strconv.Quote(v)) |
| + } |
| + return false |
| + } |
| + case *ast.BasicLit: |
| + if v, err := strconv.Unquote(n.Value); n.Kind == token.STRING && !imports[n] && err == nil && programName(v) { |
| + hit(n, strconv.Quote(v)) |
| + } |
| + } |
| + return true |
| + }) |
| + // Local shells, per function so its variables resolve. |
| + for _, d := range f.Decls { |
| + fn, ok := d.(*ast.FuncDecl) |
| + if !ok || fn.Body == nil { |
| + continue |
| } |
| + vals := map[string][]ast.Expr{} |
| + for k, v := range pkgVals { |
| + vals[k] = v |
| + } |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.AssignStmt: |
| + for j, l := range n.Lhs { |
| + if id, ok := l.(*ast.Ident); ok && j < len(n.Rhs) && len(n.Lhs) == len(n.Rhs) { |
| + vals[id.Name] = append(vals[id.Name], n.Rhs[j]) |
| + } |
| + } |
| + case *ast.ValueSpec: |
| + for j, id := range n.Names { |
| + if j < len(n.Values) { |
| + vals[id.Name] = append(vals[id.Name], n.Values[j]) |
| + } |
| + } |
| + } |
| + return true |
| + }) |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok { |
| + return true |
| + } |
| + shell := false |
| + for _, a := range call.Args { |
| + for _, v := range texts(a, vals, 0) { |
| + if shell && progWord.MatchString(v) { |
| + hit(a, "a local shell runs "+strconv.Quote(v)) |
| + return true |
| + } |
| + if shellName(v) { |
| + shell = true |
| + } |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + out[i] = hits |
| + } |
| + return out |
| +} |
| + |
| +func markFolded(n ast.Node, folded map[ast.Node]bool) { |
| + ast.Inspect(n, func(m ast.Node) bool { |
| + if m != nil { |
| + folded[m] = true |
| } |
| return true |
| }) |
| - return hits |
| +} |
| + |
| +// constString folds e to one constant string: a literal, a parenthesis, a |
| +// "+" of constants, or a name whose only package-level value is one. |
| +func constString(e ast.Expr, pkg map[string][]ast.Expr, depth int) (string, bool) { |
| + if depth > 8 { |
| + return "", false |
| + } |
| + switch e := e.(type) { |
| + case *ast.BasicLit: |
| + if e.Kind != token.STRING { |
| + return "", false |
| + } |
| + v, err := strconv.Unquote(e.Value) |
| + return v, err == nil |
| + case *ast.ParenExpr: |
| + return constString(e.X, pkg, depth+1) |
| + case *ast.BinaryExpr: |
| + if e.Op != token.ADD { |
| + return "", false |
| + } |
| + a, ok := constString(e.X, pkg, depth+1) |
| + if !ok { |
| + return "", false |
| + } |
| + b, ok := constString(e.Y, pkg, depth+1) |
| + return a + b, ok |
| + case *ast.Ident: |
| + if vs := pkg[e.Name]; len(vs) == 1 { |
| + return constString(vs[0], pkg, depth+1) |
| + } |
| + } |
| + return "", false |
| +} |
| + |
| +// texts is every string e may hold, as far as folding sees: the constant |
| +// parts of a "+" (each operand's texts, and their joins), every value a |
| +// name was given in the function or the package, and fmt.Sprintf's format. |
| +func texts(e ast.Expr, vals map[string][]ast.Expr, depth int) []string { |
| + if depth > 8 { |
| + return nil |
| + } |
| + switch e := e.(type) { |
| + case *ast.BasicLit: |
| + if v, err := strconv.Unquote(e.Value); e.Kind == token.STRING && err == nil { |
| + return []string{v} |
| + } |
| + case *ast.ParenExpr: |
| + return texts(e.X, vals, depth+1) |
| + case *ast.BinaryExpr: |
| + if e.Op == token.ADD { |
| + l, r := texts(e.X, vals, depth+1), texts(e.Y, vals, depth+1) |
| + out := append(append([]string{}, l...), r...) |
| + for _, a := range l { |
| + for _, b := range r { |
| + out = append(out, a+b) |
| + } |
| + } |
| + return out |
| + } |
| + case *ast.Ident: |
| + var out []string |
| + for _, v := range vals[e.Name] { |
| + out = append(out, texts(v, vals, depth+1)...) |
| + } |
| + return out |
| + case *ast.CallExpr: |
| + if s, ok := e.Fun.(*ast.SelectorExpr); ok && s.Sel.Name == "Sprintf" && len(e.Args) > 0 { |
| + if id, ok := s.X.(*ast.Ident); ok && id.Name == "fmt" { |
| + return texts(e.Args[0], vals, depth+1) |
| + } |
| + } |
| + } |
| + return nil |
| } |
| func moduleRoot(t *testing.T) string { |