The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
feat(endpoint): support Linux service management via systemd
shukieshah9c217ca426b0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 30aee07b..d0ee4299 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -143,6 +143,60 @@ jobs:working-directory: cli/beaconrun: make ${{ matrix.make_target }}+ linux-test:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: cli/beacon/go.mod+ # The embedded hooks binary must match the platform under test: the CLI validates its+ # architecture at runtime, so a macOS placeholder fails hook installation on Linux.+ - name: Build platform-matched hooks binary+ working-directory: cli/beacon+ run: make build-hooks-current+ - name: Test beacon CLI on Linux+ working-directory: cli/beacon+ run: go test ./...+ - name: Test endpoint packages with the race detector+ working-directory: cli/beacon+ run: go test -race ./internal/endpoint/...+ - name: Test hook adapter on Linux+ working-directory: cli/beacon-hooks+ run: go test ./...+ - name: Test collector exporter on Linux+ working-directory: collector-builder/exporter/beaconjsonexporter+ run: go test ./...+ - name: Test observe SDK and threat rules on Linux+ working-directory: pkg/asymptoteobserve+ run: go test ./...++ # Exercises the real systemd install path: unit generation, systemctl enable/active,+ # Restart=always actually restarting, and uninstall leaving nothing behind. Needs systemd as+ # PID 1, which only a privileged container provides -- the GitHub runner's own systemd is not+ # ours to install units into.+ linux-systemd-smoke:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: cli/beacon/go.mod+ - name: Build Linux beacon binary+ working-directory: cli/beacon+ run: make build-linux-amd64+ - name: Build collector for Linux+ run: |+ go install go.opentelemetry.io/collector/cmd/[email protected]+ cd collector-builder+ GOOS=linux GOARCH=amd64 CGO_ENABLED=0 "$(go env GOPATH)/bin/builder" --config builder.yaml+ mkdir -p dist/beacon-otelcol/linux_amd64+ cp dist/beacon-otelcol/beacon-otelcol dist/beacon-otelcol/linux_amd64/beacon-otelcol+ - name: systemd endpoint smoke test+ env:+ BEACON_SMOKE_ARCH: amd64+ run: sh packaging/linux/smoke-systemd.sh+package-smoke:runs-on: macos-lateststeps:diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.goindex 2869e2fb..0270ffa4 100644--- a/cli/beacon/cmd/endpoint.go+++ b/cli/beacon/cmd/endpoint.go@@ -33,6 +33,7 @@ var endpointOpts struct {keepLogs boolkeepConfig boolnoStart bool+ serviceKind stringdryRun boolfix boolallTargets bool@@ -403,7 +404,8 @@ func init() {endpointInstallCmd.Flags().StringVar(&endpointOpts.collectorPath, "collector", "", "Path to a beacon-otelcol binary")endpointInstallCmd.Flags().BoolVar(&endpointOpts.includeRuntimeMetrics, "include-runtime-metrics", false, "Include generic process/runtime OTLP metrics and harness operational metrics (OpenClaw, Copilot CLI) in the runtime JSONL log")endpointInstallCmd.Flags().BoolVar(&endpointOpts.includeCodexSpans, "include-codex-spans", false, "Include high-volume Codex OTLP spans for troubleshooting")- endpointInstallCmd.Flags().BoolVar(&endpointOpts.noStart, "no-start", false, "Write files without starting the launchd service")+ endpointInstallCmd.Flags().BoolVar(&endpointOpts.noStart, "no-start", false, "Write files without starting the collector service")+ endpointInstallCmd.Flags().StringVar(&endpointOpts.serviceKind, "service", "", "Service manager to use: auto (default), launchd, systemd, or none for a supervised collector process")endpointInstallCmd.Flags().BoolVar(&endpointOpts.dryRun, "dry-run", false, "Print planned actions without changing endpoint files or services")endpointInstallCmd.Flags().StringVar(&endpointOpts.contentRetention, "content-retention", "", "Deprecated no-op; Beacon always captures full content subject to redaction and size limits")_ = endpointInstallCmd.Flags().MarkHidden("content-retention")@@ -416,7 +418,8 @@ func init() {endpointRepairCmd.Flags().StringVar(&endpointOpts.collectorPath, "collector", "", "Path to a beacon-otelcol binary")endpointRepairCmd.Flags().BoolVar(&endpointOpts.includeRuntimeMetrics, "include-runtime-metrics", false, "Include generic process/runtime OTLP metrics and harness operational metrics (OpenClaw, Copilot CLI) in the runtime JSONL log")endpointRepairCmd.Flags().BoolVar(&endpointOpts.includeCodexSpans, "include-codex-spans", false, "Include high-volume Codex OTLP spans for troubleshooting")- endpointRepairCmd.Flags().BoolVar(&endpointOpts.noStart, "no-start", false, "Write files without starting the launchd service")+ endpointRepairCmd.Flags().BoolVar(&endpointOpts.noStart, "no-start", false, "Write files without starting the collector service")+ endpointRepairCmd.Flags().StringVar(&endpointOpts.serviceKind, "service", "", "Service manager to use: auto (default), launchd, systemd, or none for a supervised collector process")endpointRepairCmd.Flags().BoolVar(&endpointOpts.dryRun, "dry-run", false, "Print planned actions without changing endpoint files or services")endpointRepairCmd.Flags().StringVar(&endpointOpts.contentRetention, "content-retention", "", "Deprecated no-op; Beacon always captures full content subject to redaction and size limits")_ = endpointRepairCmd.Flags().MarkHidden("content-retention")diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.goindex b7f09b38..7749aa92 100644--- a/cli/beacon/cmd/endpoint_diagnostics.go+++ b/cli/beacon/cmd/endpoint_diagnostics.go@@ -77,8 +77,8 @@ type plannedAction struct {}type repairServiceManager interface {- PlistPath() (string, error)- WritePlist(program, configPath string) (string, error)+ UnitPath() (string, error)+ WriteUnit(program, configPath string) (string, error)Load() errorUnload() error}@@ -778,7 +778,7 @@ func runEndpointIntegrationsValidate(cmd *cobra.Command, args []string) error {return nil}-func plannedInstallActions(repair bool) []plannedAction {+func plannedInstallActions(repair bool, kind service.Kind) []plannedAction {cfg := endpointconfig.Default(endpointUserMode(), endpointOpts.logPath)if endpointOpts.logPath != "" {cfg.LogPath = endpointOpts.logPath@@ -788,9 +788,25 @@ func plannedInstallActions(repair bool) []plannedAction {if repair {actions = append(actions, plannedAction{Action: "unload_service", Message: "repair unloads existing endpoint service if present"})}++ // The plan has to reflect the service manager that will actually be used. It previously+ // announced a launchd plist on every platform without consulting GOOS, so a Linux+ // --dry-run advertised steps that could not execute.+ mgr := service.Manager{UserMode: cfg.UserMode, Kind: kind}+ serviceAction := plannedAction{Action: "write_unit", Message: "launchd service definition"}+ if unitPath, err := mgr.UnitPath(); err == nil {+ serviceAction.Target = unitPath+ }+ switch mgr.ResolvedKind() {+ case service.KindSystemd:+ serviceAction.Message = "systemd unit definition"+ case service.KindSupervised:+ serviceAction.Message = "supervised collector state (no service manager on this host)"+ }+actions = append(actions,plannedAction{Action: "write_file", Target: cfg.Collector.ConfigPath, Message: "collector configuration"},- plannedAction{Action: "write_plist", Message: "launchd service definition"},+ serviceAction,plannedAction{Action: "write_file", Target: endpointconfig.ConfigPath(cfg.UserMode), Message: "endpoint configuration"},)for _, h := range otlpTargets {@@ -1176,7 +1192,7 @@ func repairCollectorServiceFromStatus(status lifecycle.Status) error {return err}manager := newRepairServiceManager(userMode)- plistPath, err := manager.PlistPath()+ plistPath, err := manager.UnitPath()if err != nil {return err}@@ -1198,7 +1214,7 @@ func repairCollectorServiceFromStatus(status lifecycle.Status) error {if err := repairWriteCollectorConfig(cfg); err != nil {return rollbackRepairError(err, rollback)}- if _, err := manager.WritePlist(binary, cfg.Collector.ConfigPath); err != nil {+ if _, err := manager.WriteUnit(binary, cfg.Collector.ConfigPath); err != nil {return rollbackRepairError(err, rollback)}if err := manager.Load(); err != nil {diff --git a/cli/beacon/cmd/endpoint_elastic.go b/cli/beacon/cmd/endpoint_elastic.goindex 9ea381d8..2f8ae8a0 100644--- a/cli/beacon/cmd/endpoint_elastic.go+++ b/cli/beacon/cmd/endpoint_elastic.go@@ -6,7 +6,6 @@ import ("os""os/exec""path/filepath"- "runtime""strings""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/elastic"@@ -14,9 +13,6 @@ import ()func runEndpointElasticUp(ctx context.Context) error {- if runtime.GOOS != "darwin" {- return fmt.Errorf("beacon endpoint elastic up is currently macOS-only")- }cfg := loadOrDefaultConfig()logPath, err := filepath.Abs(cfg.LogPath)if err != nil {@@ -44,9 +40,6 @@ func runEndpointElasticUp(ctx context.Context) error {}func runEndpointElasticDown(ctx context.Context) error {- if runtime.GOOS != "darwin" {- return fmt.Errorf("beacon endpoint elastic down is currently macOS-only")- }packDir := endpointOpts.elasticPackDirif packDir == "" {packDir = elastic.DefaultOutputDirdiff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.goindex 591a5a3d..abfa3727 100644--- a/cli/beacon/cmd/endpoint_install.go+++ b/cli/beacon/cmd/endpoint_install.go@@ -9,6 +9,7 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version""github.com/spf13/cobra"@@ -93,8 +94,12 @@ func runEndpointInstall(cmd *cobra.Command, args []string) error {if err != nil {return err}+ serviceKind, err := service.ParseKind(endpointOpts.serviceKind)+ if err != nil {+ return err+ }if endpointOpts.dryRun {- return printPlannedActions(plannedInstallActions(false))+ return printPlannedActions(plannedInstallActions(false, serviceKind))}result, err := lifecycle.Install(lifecycle.InstallOptions{UserMode: endpointUserMode(),@@ -108,13 +113,14 @@ func runEndpointInstall(cmd *cobra.Command, args []string) error {IncludeCodexSpans: endpointOpts.includeCodexSpans,SplunkHEC: splunkHECOptions(),FalconHEC: falconHECOptions(),+ ServiceKind: serviceKind,})if err != nil {return err}fmt.Printf("Endpoint config written to %s\n", result.ConfigPath)fmt.Printf("Collector config written to %s\n", result.CollectorConfigPath)- fmt.Printf("Launch plist written to %s\n", result.PlistPath)+ fmt.Printf("Service definition written to %s\n", result.PlistPath)fmt.Printf("Install manifest written to %s\n", result.ManifestPath)fmt.Printf("Runtime log: %s\n", result.LogPath)if err := installHookTargetsFromEndpointInstall(hookHarnesses); err != nil {@@ -231,8 +237,12 @@ func runEndpointRepair(cmd *cobra.Command, args []string) error {if err != nil {return err}+ serviceKind, err := service.ParseKind(endpointOpts.serviceKind)+ if err != nil {+ return err+ }if endpointOpts.dryRun {- return printPlannedActions(plannedInstallActions(true))+ return printPlannedActions(plannedInstallActions(true, serviceKind))}result, err := lifecycle.Repair(lifecycle.InstallOptions{UserMode: endpointUserMode(),@@ -246,6 +256,7 @@ func runEndpointRepair(cmd *cobra.Command, args []string) error {IncludeCodexSpans: endpointOpts.includeCodexSpans,SplunkHEC: splunkHECOptions(),FalconHEC: falconHECOptions(),+ ServiceKind: serviceKind,})if err != nil {return errdiff --git a/cli/beacon/cmd/endpoint_test.go b/cli/beacon/cmd/endpoint_test.goindex 3cc31980..30d8248f 100644--- a/cli/beacon/cmd/endpoint_test.go+++ b/cli/beacon/cmd/endpoint_test.go@@ -81,7 +81,7 @@ func TestPlannedInstallActionsSeparatesHookHarnesses(t *testing.T) {endpointOpts.logPath = filepath.Join(t.TempDir(), "runtime.jsonl")endpointOpts.noStart = true- actions := plannedInstallActions(false)+ actions := plannedInstallActions(false, service.KindAuto)counts := map[string]int{}for _, action := range actions {if action.Action == "configure_harness" {@@ -419,11 +419,11 @@ type fakeRepairServiceManager struct {unloads int}-func (m *fakeRepairServiceManager) PlistPath() (string, error) {+func (m *fakeRepairServiceManager) UnitPath() (string, error) {return m.plistPath, nil}-func (m *fakeRepairServiceManager) WritePlist(program, configPath string) (string, error) {+func (m *fakeRepairServiceManager) WriteUnit(program, configPath string) (string, error) {return m.plistPath, os.WriteFile(m.plistPath, []byte("new plist"), 0644)}diff --git a/cli/beacon/cmd/endpoint_update_service.go b/cli/beacon/cmd/endpoint_update_service.goindex 76ba5cf8..780e43c0 100644--- a/cli/beacon/cmd/endpoint_update_service.go+++ b/cli/beacon/cmd/endpoint_update_service.go@@ -138,7 +138,7 @@ func runUpdateEnable(cmd *cobra.Command, args []string) error {return fmt.Errorf("write auto-update config: %w", err)}mgr := service.UpdaterManager{}- if _, err := mgr.WritePlist(selfupdate.SystemBeaconPath()); err != nil {+ if _, err := mgr.WriteUnit(selfupdate.SystemBeaconPath()); err != nil {return fmt.Errorf("write updater plist: %w", err)}if err := mgr.Load(); err != nil {@@ -166,7 +166,7 @@ func runUpdateDisable(cmd *cobra.Command, args []string) error {if err := mgr.Unload(); err != nil {return fmt.Errorf("unload updater job: %w", err)}- _ = os.Remove(mgr.PlistPath())+ _ = os.Remove(mgr.UnitPath())fmt.Println("Update checks disabled; background updater removed.")return nil}@@ -195,11 +195,11 @@ func runUpdateInstallDaemon(cmd *cobra.Command, args []string) error {mgr := service.UpdaterManager{}if mode == selfupdate.ModeOff {_ = mgr.Unload()- _ = os.Remove(mgr.PlistPath())+ _ = os.Remove(mgr.UnitPath())fmt.Println("Auto-update is off; updater daemon not installed.")return nil}- if _, err := mgr.WritePlist(selfupdate.SystemBeaconPath()); err != nil {+ if _, err := mgr.WriteUnit(selfupdate.SystemBeaconPath()); err != nil {return fmt.Errorf("write updater plist: %w", err)}if err := mgr.Load(); err != nil {diff --git a/cli/beacon/internal/endpoint/collector/collector.go b/cli/beacon/internal/endpoint/collector/collector.goindex 93f1d875..d68ea8af 100644--- a/cli/beacon/internal/endpoint/collector/collector.go+++ b/cli/beacon/internal/endpoint/collector/collector.go@@ -331,50 +331,3 @@ func healthReady() bool {defer resp.Body.Close()return resp.StatusCode >= 200 && resp.StatusCode < 300}--func LaunchAgentPlist(cfg endpointconfig.Config) string {- binary := DiscoverBinary(cfg.Collector.BinaryPath)- if binary == "" {- binary = BinaryName- }- label := "com.beacon.endpoint.collector"- if cfg.UserMode {- label = "com.beacon.endpoint.collector.user"- }- return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>Label</key>- <string>%s</string>- <key>ProgramArguments</key>- <array>- <string>%s</string>- <string>--config</string>- <string>%s</string>- </array>- <key>RunAtLoad</key>- <true/>- <key>KeepAlive</key>- <true/>-</dict>-</plist>-`, label, binary, cfg.Collector.ConfigPath)-}--func WriteLaunchPlist(cfg endpointconfig.Config) (string, error) {- var path string- if cfg.UserMode {- home, err := os.UserHomeDir()- if err != nil {- return "", err- }- path = filepath.Join(home, "Library", "LaunchAgents", "com.beacon.endpoint.collector.plist")- } else {- path = "/Library/LaunchDaemons/com.beacon.endpoint.collector.plist"- }- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {- return "", err- }- return path, os.WriteFile(path, []byte(LaunchAgentPlist(cfg)), 0644)-}diff --git a/cli/beacon/internal/endpoint/collector/collector_test.go b/cli/beacon/internal/endpoint/collector/collector_test.goindex 2536ffb1..cfe44c67 100644--- a/cli/beacon/internal/endpoint/collector/collector_test.go+++ b/cli/beacon/internal/endpoint/collector/collector_test.go@@ -7,7 +7,6 @@ import ("os""os/exec""path/filepath"- "runtime""strings""testing""time"@@ -406,46 +405,6 @@ func TestHealthReadyChecksCollectorHealthEndpoint(t *testing.T) {}}-func TestLaunchAgentPlistUsesFallbackBinaryAndUserLabel(t *testing.T) {- cfg := testConfig(t)- cfg.UserMode = true- cfg.Collector.BinaryPath = filepath.Join(t.TempDir(), "missing-otelcol")- withCollectorDiscovery(t, func(file string) (string, error) {- return "", errors.New("not found")- }, nil)-- plist := LaunchAgentPlist(cfg)-- for _, want := range []string{- "<string>com.beacon.endpoint.collector.user</string>",- "<string>beacon-otelcol</string>",- "<string>--config</string>",- "<string>" + cfg.Collector.ConfigPath + "</string>",- } {- if !strings.Contains(plist, want) {- t.Fatalf("LaunchAgentPlist missing %q:\n%s", want, plist)- }- }-}--func TestWriteLaunchPlistUserMode(t *testing.T) {- if runtime.GOOS == "windows" {- t.Skip("launch plist paths are POSIX-specific")- }- home := t.TempDir()- t.Setenv("HOME", home)- cfg := testConfig(t)- cfg.UserMode = true-- path, err := WriteLaunchPlist(cfg)- if err != nil {- t.Fatalf("WriteLaunchPlist returned error: %v", err)- }- if got, want := path, filepath.Join(home, "Library", "LaunchAgents", "com.beacon.endpoint.collector.plist"); got != want {- t.Fatalf("plist path = %q, want %q", got, want)- }-}-func withCollectorDiscovery(t *testing.T, lookup func(string) (string, error), candidates func() []string) {t.Helper()oldLookPath := lookPathdiff --git a/cli/beacon/internal/endpoint/config/config.go b/cli/beacon/internal/endpoint/config/config.goindex c19835a7..240e6867 100644--- a/cli/beacon/internal/endpoint/config/config.go+++ b/cli/beacon/internal/endpoint/config/config.go@@ -5,15 +5,40 @@ import ("fmt""os""path/filepath"+ "runtime")const (- SystemConfigPath = "/Library/Application Support/Beacon/Endpoint/config.json"- UserConfigPath = ".beacon/endpoint/config.json"- DefaultGRPCPort = 4317- DefaultHTTPPort = 4318+ // DarwinSystemBaseDir is the macOS system-mode state directory.+ DarwinSystemBaseDir = "/Library/Application Support/Beacon/Endpoint"+ // LinuxSystemBaseDir follows the FHS: configuration under /etc, which is where a+ // package-managed install and an admin both expect to find it.+ LinuxSystemBaseDir = "/etc/beacon/endpoint"++ UserConfigPath = ".beacon/endpoint/config.json"+ DefaultGRPCPort = 4317+ DefaultHTTPPort = 4318)+// SystemBaseDir is the single source of truth for the system-mode state directory.+//+// Everything else derives from this, replacing what used to be several independently+// hardcoded copies of the macOS path in the service, diagnostics, collector, and selfupdate+// packages.+func SystemBaseDir() string {+ switch runtime.GOOS {+ case "linux":+ return LinuxSystemBaseDir+ default:+ return DarwinSystemBaseDir+ }+}++// SystemConfigPath is the system-mode config file location.+func SystemConfigPath() string {+ return filepath.Join(SystemBaseDir(), "config.json")+}+const (DefaultSplunkSource = "beacon-endpoint-agent"DefaultSplunkSourcetype = "beacon:endpoint"@@ -154,7 +179,7 @@ func BaseDir(userMode bool) string {}return filepath.Join(home, ".beacon", "endpoint")}- return "/Library/Application Support/Beacon/Endpoint"+ return SystemBaseDir()}func ConfigPath(userMode bool) string {@@ -165,7 +190,7 @@ func ConfigPath(userMode bool) string {}return filepath.Join(home, UserConfigPath)}- return SystemConfigPath+ return SystemConfigPath()}func Load(userMode bool) (Config, error) {diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics.goindex feb97bf3..ea3fffd5 100644--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go@@ -3,8 +3,6 @@ package diagnosticsimport ("fmt""os"- "path/filepath"- "runtime""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/collector"endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"@@ -40,8 +38,20 @@ func Run(cfg endpointconfig.Config) []Check {checkLogPermissions(cfg.LogPath),checkCollectorHealth(cfg),}- if runtime.GOOS == "darwin" {- checks = append(checks, checkFile("launchd_plist", launchPlistPath(cfg.UserMode), true))+ // The service definition check is named after whichever manager is actually in use, so+ // the output is interpretable on a mixed fleet and a Linux host is not told to look for a+ // launchd plist. Supervised mode has no unit file to check -- its pidfile is runtime+ // state, not configuration, so a missing one just means "not started".+ mgr := service.Manager{UserMode: cfg.UserMode}+ switch mgr.ResolvedKind() {+ case service.KindLaunchd:+ if path, err := mgr.UnitPath(); err == nil {+ checks = append(checks, checkFile("launchd_plist", path, true))+ }+ case service.KindSystemd:+ if path, err := mgr.UnitPath(); err == nil {+ checks = append(checks, checkFile("systemd_unit", path, true))+ }}return checks}@@ -95,14 +105,3 @@ func checkLogPermissions(path string) Check {}return Check{Name: "runtime_log_permissions", Target: path, Status: StatusOK, Severity: SeverityInfo, Message: fmt.Sprintf("mode %o", mode), Evidence: fmt.Sprintf("mode_%o", mode)}}--func launchPlistPath(userMode bool) string {- if userMode {- home, err := os.UserHomeDir()- if err != nil {- return filepath.Join("Library", "LaunchAgents", service.UserLabel+".plist")- }- return filepath.Join(home, "Library", "LaunchAgents", service.UserLabel+".plist")- }- return filepath.Join("/Library/LaunchDaemons", service.SystemLabel+".plist")-}diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.goindex 68b754dd..e93692d2 100644--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go@@ -90,7 +90,7 @@ func TestRunAndHasFailures(t *testing.T) {t.Fatalf("write log: %v", err)}if runtime.GOOS == "darwin" {- plistPath := launchPlistPath(true)+ plistPath := servicePlistPathForTest(true)if err := os.MkdirAll(filepath.Dir(plistPath), 0755); err != nil {t.Fatalf("mkdir plist dir: %v", err)}@@ -112,15 +112,25 @@ func TestLaunchPlistPathMatchesServiceManager(t *testing.T) {home := t.TempDir()t.Setenv("HOME", home)- userPath := launchPlistPath(true)+ userPath := servicePlistPathForTest(true)wantUserPath := filepath.Join(home, "Library", "LaunchAgents", service.UserLabel+".plist")if userPath != wantUserPath {t.Fatalf("user launchPlistPath = %q, want %q", userPath, wantUserPath)}- systemPath := launchPlistPath(false)+ systemPath := servicePlistPathForTest(false)wantSystemPath := filepath.Join("/Library/LaunchDaemons", service.SystemLabel+".plist")if systemPath != wantSystemPath {t.Fatalf("system launchPlistPath = %q, want %q", systemPath, wantSystemPath)}}++// servicePlistPathForTest mirrors what the service package now owns, so these tests keep+// exercising the launchd check without diagnostics duplicating the path logic.+func servicePlistPathForTest(userMode bool) string {+ path, err := (service.Manager{UserMode: userMode, Kind: service.KindLaunchd}).UnitPath()+ if err != nil {+ return ""+ }+ return path+}diff --git a/cli/beacon/internal/endpoint/harness/vscode_test.go b/cli/beacon/internal/endpoint/harness/vscode_test.goindex 92c91042..a0dc1838 100644--- a/cli/beacon/internal/endpoint/harness/vscode_test.go+++ b/cli/beacon/internal/endpoint/harness/vscode_test.go@@ -3,6 +3,7 @@ package harnessimport ("os""path/filepath"+ "runtime""strings""testing")@@ -37,7 +38,9 @@ func TestVSCodeUserSettingsPathByOS(t *testing.T) {func TestConfigureVSCodePreservesSettingsAndDisablesContentCaptureByDefault(t *testing.T) {home := t.TempDir()t.Setenv("HOME", home)- path := filepath.Join(home, "Library", "Application Support", "Code", "User", "settings.json")+ // VS Code stores user settings per platform; assert the platform-correct location rather+ // than the macOS one, which silently passed only because tests never ran on Linux.+ path := vscodeSettingsPathForTest(home)if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {t.Fatal(err)}@@ -96,3 +99,16 @@ func TestVSCodeOTelStatus(t *testing.T) {t.Fatalf("remote endpoint status = %s, want misconfigured", status)}}++// vscodeSettingsPathForTest mirrors vscodeUserDataDirsForOS so these tests exercise the real+// per-platform layout.+func vscodeSettingsPathForTest(home string) string {+ switch runtime.GOOS {+ case "darwin":+ return filepath.Join(home, "Library", "Application Support", "Code", "User", "settings.json")+ case "windows":+ return filepath.Join(home, "AppData", "Roaming", "Code", "User", "settings.json")+ default:+ return filepath.Join(home, ".config", "Code", "User", "settings.json")+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/factory_test.go b/cli/beacon/internal/endpoint/hooks/factory_test.goindex bb3fced6..8656da60 100644--- a/cli/beacon/internal/endpoint/hooks/factory_test.go+++ b/cli/beacon/internal/endpoint/hooks/factory_test.go@@ -5,6 +5,8 @@ import ("path/filepath""strings""testing"++ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config")func TestInstallFactorySettingsPreservesNonBeaconHooks(t *testing.T) {@@ -244,7 +246,16 @@ func TestInstallFactoryUsesSystemConfigForSystemLog(t *testing.T) {if err != nil {t.Fatalf("read Factory settings: %v", err)}- if !strings.Contains(string(data), "BEACON_ENDPOINT_CONFIG='/Library/Application Support/Beacon/Endpoint/config.json'") {- t.Fatalf("Factory hook did not use system config for system log:\n%s", string(data))+ // The point of this test is that a /var/log system log path selects the *system* config,+ // not the user one. The system path is per-OS, so assert against the resolved value+ // rather than a hardcoded macOS string -- which is what previously made this fail the+ // moment the suite ran on Linux.+ wantConfig := "BEACON_ENDPOINT_CONFIG='" + endpointconfig.SystemConfigPath() + "'"+ if !strings.Contains(string(data), wantConfig) {+ t.Fatalf("Factory hook did not use system config for system log; want %s in:\n%s",+ wantConfig, string(data))+ }+ if strings.Contains(string(data), endpointconfig.ConfigPath(true)) {+ t.Fatalf("Factory hook used the user config for a system log path:\n%s", string(data))}}diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.goindex 22121318..be371fab 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go@@ -5,7 +5,6 @@ import ("fmt""os""path/filepath"- "runtime""time"beaconauth "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"@@ -30,7 +29,7 @@ var (removeUpdaterJob = func() {updater := service.UpdaterManager{}_ = updater.Unload()- _ = os.Remove(updater.PlistPath())+ _ = os.Remove(updater.UnitPath())})@@ -46,6 +45,9 @@ type InstallOptions struct {IncludeCodexSpans boolSplunkHEC *endpointconfig.SplunkHECFalconHEC *endpointconfig.FalconHEC+ // ServiceKind selects the service manager. Empty auto-detects: launchd on macOS,+ // systemd when it is PID 1, otherwise a supervised child process.+ ServiceKind service.Kind}type UninstallOptions struct {@@ -159,10 +161,10 @@ func (r *installRollback) Rollback(manifest Manifest) {func Install(opts InstallOptions) (InstallResult, error) {cfg := buildConfig(opts)- if err := preflight(cfg, opts.StartService); err != nil {+ if err := preflight(cfg, opts.StartService, opts.ServiceKind); err != nil {return InstallResult{}, err}- manager := service.Manager{UserMode: cfg.UserMode}+ manager := service.Manager{UserMode: cfg.UserMode, Kind: opts.ServiceKind}collectorBinary, err := endpointcollector.ResolveBinary(cfg.Collector.BinaryPath)if err != nil {return InstallResult{}, err@@ -183,14 +185,14 @@ func Install(opts InstallOptions) (InstallResult, error) {return InstallResult{}, err}- plistPath, err := manager.PlistPath()+ plistPath, err := manager.UnitPath()if err != nil {tx.Rollback(manifest)return InstallResult{}, err}tx.Track(plistPath)manifest.Files = append(manifest.Files, plistPath)- if _, err := manager.WritePlist(collectorBinary, cfg.Collector.ConfigPath); err != nil {+ if _, err := manager.WriteUnit(collectorBinary, cfg.Collector.ConfigPath); err != nil {tx.Rollback(manifest)return InstallResult{}, err}@@ -252,8 +254,14 @@ func Install(opts InstallOptions) (InstallResult, error) {func Uninstall(opts UninstallOptions) error {cfg := loadOrDefault(opts.UserMode, opts.LogPath)+ // Unload every backend that could plausibly hold this service, not just the one+ // detection picks now. An install performed under systemd and uninstalled from a+ // container would otherwise leave the unit enabled, and "uninstall" has to mean nothing+ // is left behind. Unload already tolerates a backend that is unusable here.manager := service.Manager{UserMode: cfg.UserMode}- _ = manager.Unload()+ for _, kind := range []service.Kind{service.KindLaunchd, service.KindSystemd, service.KindSupervised} {+ _ = (service.Manager{UserMode: cfg.UserMode, Kind: kind}).Unload()+ }if !cfg.UserMode && !opts.KeepUpdater {removeUpdaterJob()}@@ -265,7 +273,7 @@ func Uninstall(opts UninstallOptions) error {_ = os.Remove(path)}if len(manifest.Files) == 0 {- if path, err := manager.PlistPath(); err == nil {+ if path, err := manager.UnitPath(); err == nil {_ = os.Remove(path)}_ = os.Remove(cfg.Collector.ConfigPath)@@ -318,10 +326,10 @@ func reconcileUpdaterFromConfig(logPath string) error {mgr := service.UpdaterManager{}if mode == selfupdate.ModeOff {_ = mgr.Unload()- _ = os.Remove(mgr.PlistPath())+ _ = os.Remove(mgr.UnitPath())return nil}- if _, err := mgr.WritePlist(selfupdate.SystemBeaconPath()); err != nil {+ if _, err := mgr.WriteUnit(selfupdate.SystemBeaconPath()); err != nil {return err}return mgr.Load()@@ -563,12 +571,23 @@ func restoreFile(path string, snapshot fileSnapshot) {_ = os.WriteFile(path, snapshot.Data, mode)}-func preflight(cfg endpointconfig.Config, startService bool) error {+func preflight(cfg endpointconfig.Config, startService bool, kind service.Kind) error {if err := endpointconfig.ValidateDestinations(cfg.Destinations); err != nil {return err}- if runtime.GOOS != "darwin" {- return fmt.Errorf("production endpoint install is currently supported only on macOS")+ // Replaces a blanket "macOS only" refusal. What actually matters is whether a service+ // manager can run the collector here, which is a property of the host rather than of the+ // operating system name: a Linux VM with systemd is fully supported, and a container+ // without an init system is supported through the supervised backend.+ mgr := service.Manager{UserMode: cfg.UserMode, Kind: kind}+ if !mgr.Available() {+ reason := mgr.UnsupportedReason()+ if kind == service.KindAuto {+ // Detection picked something unusable, which should not happen since detection+ // falls back to supervised; surface it rather than failing opaquely.+ return fmt.Errorf("no usable service manager on this host: %s", reason)+ }+ return fmt.Errorf("--service=%s is not usable here: %s", kind, reason)}if !cfg.UserMode && os.Geteuid() != 0 {return fmt.Errorf("system install requires root; rerun with sudo or omit --system for the default user install")diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.goindex 9335c70e..948286c3 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle_test.go@@ -438,7 +438,7 @@ func TestPreflightRejectsPortInUse(t *testing.T) {cfg.Collector.GRPCPort = portcfg.Collector.HTTPPort = freePort(t)- err = preflight(cfg, true)+ err = preflight(cfg, true, service.KindAuto)if err == nil || !strings.Contains(err.Error(), "OTLP gRPC port") {t.Fatalf("preflight error = %v, want gRPC port in use", err)}@@ -459,7 +459,7 @@ func TestPreflightAllowsPortInUseWhenServiceWillNotStart(t *testing.T) {cfg.Collector.GRPCPort = portcfg.Collector.HTTPPort = freePort(t)- if err := preflight(cfg, false); err != nil {+ if err := preflight(cfg, false, service.KindAuto); err != nil {t.Fatalf("preflight returned error for no-start install: %v", err)}}diff --git a/cli/beacon/internal/endpoint/service/launchd.go b/cli/beacon/internal/endpoint/service/launchd.gonew file mode 100644index 00000000..7286d06e--- /dev/null+++ b/cli/beacon/internal/endpoint/service/launchd.go@@ -0,0 +1,226 @@+package service++import (+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+)++// launchdBackend manages the collector via macOS launchd.+//+// This is the original implementation, unchanged in behavior; it moved here so that+// launchctl output parsing and launchd's error taxonomy no longer share a file with the+// platform-neutral types.+type launchdBackend struct{}++var runLaunchctlCommand = func(args ...string) (string, error) {+ cmd := exec.Command("launchctl", args...)+ out, err := cmd.CombinedOutput()+ return string(out), err+}++func (launchdBackend) kind() Kind { return KindLaunchd }++func (launchdBackend) available() bool { return runtime.GOOS == "darwin" }++func (launchdBackend) unsupportedReason() string {+ return "launchd service management is supported only on macOS"+}++func (launchdBackend) label(userMode bool) string {+ if userMode {+ return UserLabel+ }+ return SystemLabel+}++func (b launchdBackend) unitPath(userMode bool) (string, error) {+ if userMode {+ home, err := os.UserHomeDir()+ if err != nil {+ return "", err+ }+ return filepath.Join(home, "Library", "LaunchAgents", UserLabel+".plist"), nil+ }+ return filepath.Join("/Library/LaunchDaemons", SystemLabel+".plist"), nil+}++func (b launchdBackend) writeUnit(userMode bool, program, configPath string) (string, error) {+ path, err := b.unitPath(userMode)+ if err != nil {+ return "", err+ }+ if err := ensureDir(path); err != nil {+ return "", err+ }+ content := plist(b.label(userMode), program, configPath)+ return path, os.WriteFile(path, []byte(content), 0o644)+}++func (b launchdBackend) load(userMode bool) error {+ path, err := b.unitPath(userMode)+ if err != nil {+ return err+ }+ return loadLaunchdJob(serviceDomain(userMode), b.label(userMode), path)+}++func (b launchdBackend) unload(userMode bool) error {+ domain := serviceDomain(userMode)+ target := domain + "/" + b.label(userMode)+ return runLaunchctlWithContext(domain, b.label(userMode), "", "bootout", target)+}++func (b launchdBackend) restart(userMode bool) error {+ domain := serviceDomain(userMode)+ label := b.label(userMode)+ target := domain + "/" + label+ out, err := runLaunchctlCommand("kickstart", "-k", target)+ if err == nil {+ return nil+ }+ text := strings.TrimSpace(out)+ if launchctlNoSuchProcess(text) {+ return b.load(userMode)+ }+ return launchctlError(text, err, domain, label, "", "kickstart", "-k", target)+}++func (b launchdBackend) status(userMode bool) Status {+ status := Status{Label: b.label(userMode)}+ out, err := runLaunchctlCommand("print", serviceDomain(userMode)+"/"+b.label(userMode))+ if err != nil {+ status.Message = strings.TrimSpace(out)+ return status+ }+ status.Loaded = true+ status.Running = strings.Contains(out, "state = running") || strings.Contains(out, "pid =")+ return status+}++func runLaunchctlWithContext(domain, label, plistPath string, args ...string) error {+ out, err := runLaunchctlCommand(args...)+ if err == nil {+ return nil+ }+ text := strings.TrimSpace(out)+ if launchctlNoSuchProcess(text) {+ return nil+ }+ return launchctlError(text, err, domain, label, plistPath, args...)+}++func launchctlNoSuchProcess(text string) bool {+ return strings.Contains(text, "No such process") || strings.Contains(text, "Could not find service")+}++func loadLaunchdJob(domain, label, plistPath string) error {+ out, err := runLaunchctlCommand("bootstrap", domain, plistPath)+ if err == nil {+ return nil+ }+ text := strings.TrimSpace(out)+ if !launchdJobAppearsLoaded(text, domain, label) {+ return launchctlError(text, err, domain, label, plistPath, "bootstrap", domain, plistPath)+ }+ target := domain + "/" + label+ if err := runLaunchctlWithContext(domain, label, "", "bootout", target); err != nil {+ return err+ }+ if out, err := runLaunchctlCommand("bootstrap", domain, plistPath); err != nil {+ text := strings.TrimSpace(out)+ if launchdJobAppearsLoaded(text, domain, label) {+ return nil+ }+ return launchctlError(text, err, domain, label, plistPath, "bootstrap", domain, plistPath)+ }+ return nil+}++func launchdJobAppearsLoaded(bootstrapOutput, domain, label string) bool {+ text := strings.TrimSpace(bootstrapOutput)+ if strings.Contains(text, "already bootstrapped") {+ return true+ }+ if !strings.Contains(text, "Bootstrap failed: 5") && !strings.Contains(text, "Input/output error") {+ return false+ }+ out, err := runLaunchctlCommand("print", domain+"/"+label)+ return err == nil && strings.TrimSpace(out) != ""+}++func launchctlError(text string, err error, domain, label, plistPath string, args ...string) error {+ context := launchctlContext(domain, label, plistPath)+ guidance := launchctlGuidance(text, domain, label)+ if guidance != "" {+ return fmt.Errorf("launchctl %s failed%s: %s: %w\n%s", strings.Join(args, " "), context, text, err, guidance)+ }+ return fmt.Errorf("launchctl %s failed%s: %s: %w", strings.Join(args, " "), context, text, err)+}++func launchctlContext(domain, label, plistPath string) string {+ var fields []string+ if label != "" {+ fields = append(fields, "label "+label)+ }+ if domain != "" {+ fields = append(fields, "domain "+domain)+ }+ if plistPath != "" {+ fields = append(fields, "plist "+plistPath)+ }+ if len(fields) == 0 {+ return ""+ }+ return " (" + strings.Join(fields, ", ") + ")"+}++func launchctlGuidance(output, domain, label string) string {+ if !strings.Contains(output, "Bootstrap failed: 5") && !strings.Contains(output, "Input/output error") {+ return ""+ }+ target := label+ if domain != "" && label != "" {+ target = domain + "/" + label+ }+ if target == "" {+ target = "the Beacon launchd job"+ }+ return fmt.Sprintf("Bootstrap failed: 5 usually means launchd could not read or execute the job. Verify the collector binary referenced by the plist exists and is executable, clear stale state with `launchctl bootout %s`, then inspect launchd logs with `log show --predicate 'process == \"launchd\"' --last 5m`.", target)+}++func serviceDomain(userMode bool) string {+ if userMode {+ return "gui/" + fmt.Sprint(os.Getuid())+ }+ return "system"+}++func plist(label, program, configPath string) string {+ return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>%s</string>+ <key>ProgramArguments</key>+ <array>+ <string>%s</string>+ <string>--config</string>+ <string>%s</string>+ </array>+ <key>RunAtLoad</key>+ <true/>+ <key>KeepAlive</key>+ <true/>+ <key>StandardOutPath</key>+ <string>/tmp/%s.out</string>+ <key>StandardErrorPath</key>+ <string>/tmp/%s.err</string>+</dict>+</plist>+`, label, program, configPath, label, label)+}diff --git a/cli/beacon/internal/endpoint/service/service.go b/cli/beacon/internal/endpoint/service/service.goindex 0f59a826..59acaf02 100644--- a/cli/beacon/internal/endpoint/service/service.go+++ b/cli/beacon/internal/endpoint/service/service.go@@ -1,247 +1,216 @@+// Package service manages the long-running collector as an operating-system service.+//+// Manager keeps its value-struct shape so existing call sites are unaffected, but dispatches+// to a platform backend chosen at construction time:+//+// launchd macOS, the original and still the default there+// systemd Linux with systemd as PID 1 (servers, workstations, VMs)+// supervised anything else -- a detached child process with a pidfile, which is what+// containers and CI actually want, and what `beacon ci` has always done+//+// Auto-detection covers the common cases so one `beacon endpoint install` works everywhere;+// Kind can be set explicitly when detection would guess wrong.package serviceimport ("fmt""os"- "os/exec""path/filepath""runtime""strings"++ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config")const (SystemLabel = "com.beacon.endpoint.collector"UserLabel = "com.beacon.endpoint.collector.user"++ // SystemdSystemUnit and SystemdUserUnit are the Linux unit names. Systemd convention is+ // short lowercase names rather than launchd's reverse-DNS labels.+ SystemdSystemUnit = "beacon-collector.service"+ SystemdUserUnit = "beacon-collector.service"+)++// Kind identifies which service manager backs a Manager.+type Kind string++const (+ // KindAuto asks for detection. This is the zero value, so an unset Manager behaves+ // sensibly on every platform.+ KindAuto Kind = ""+ // KindLaunchd is macOS launchd.+ KindLaunchd Kind = "launchd"+ // KindSystemd is Linux systemd.+ KindSystemd Kind = "systemd"+ // KindSupervised is a detached child process tracked by a pidfile. No OS service+ // manager is involved, so it works in containers, CI, and on systems without systemd.+ KindSupervised Kind = "none")+// ParseKind validates a user-supplied service kind.+func ParseKind(s string) (Kind, error) {+ switch Kind(strings.ToLower(strings.TrimSpace(s))) {+ case KindAuto, "auto":+ return KindAuto, nil+ case KindLaunchd:+ return KindLaunchd, nil+ case KindSystemd:+ return KindSystemd, nil+ case KindSupervised, "supervised":+ return KindSupervised, nil+ default:+ return "", fmt.Errorf("unsupported service kind %q; want auto, launchd, systemd, or none", s)+ }+}++// Manager controls the collector service.type Manager struct {UserMode bool+ // Kind selects the backend. The zero value auto-detects.+ Kind Kind}+// Status describes the service as the OS currently sees it.type Status struct {Label string `json:"label"`Loaded bool `json:"loaded"`Running bool `json:"running"`Message string `json:"message,omitempty"`-}--var runLaunchctlCommand = func(args ...string) (string, error) {- cmd := exec.Command("launchctl", args...)- out, err := cmd.CombinedOutput()- return string(out), err-}--func (m Manager) Label() string {- if m.UserMode {- return UserLabel- }- return SystemLabel-}--func (m Manager) PlistPath() (string, error) {- if m.UserMode {- home, err := os.UserHomeDir()- if err != nil {- return "", err+ // Kind records which backend produced this status, so `status --json` and doctor output+ // are interpretable on a mixed fleet.+ Kind string `json:"kind,omitempty"`+}++// backend is the per-platform implementation. Methods take userMode rather than closing over+// it so a backend value stays stateless and cheap to construct.+type backend interface {+ kind() Kind+ // label is the service identifier: a launchd label, a systemd unit name, or a pidfile+ // basename.+ label(userMode bool) string+ // unitPath is where the service definition lives on disk. Supervised mode has no unit+ // file and reports its pidfile instead, so callers get something meaningful to show.+ unitPath(userMode bool) (string, error)+ // writeUnit renders and installs the service definition.+ writeUnit(userMode bool, program, configPath string) (string, error)+ load(userMode bool) error+ unload(userMode bool) error+ restart(userMode bool) error+ status(userMode bool) Status+ // available reports whether this backend can actually manage services here.+ available() bool+ // unsupportedReason explains why not, for actionable errors.+ unsupportedReason() string+}++// DetectKind picks a backend for this host.+//+// Ordering is deliberate: a real service manager is preferred when present, because a+// persistent endpoint install should survive logout and reboot. Supervised mode is the+// fallback rather than the default so containers work without configuration while a+// workstation still gets a proper service.+func DetectKind() Kind {+ switch runtime.GOOS {+ case "darwin":+ return KindLaunchd+ case "linux":+ if systemdIsInit() {+ return KindSystemd}- return filepath.Join(home, "Library", "LaunchAgents", UserLabel+".plist"), nil+ return KindSupervised+ default:+ return KindSupervised}- return filepath.Join("/Library/LaunchDaemons", SystemLabel+".plist"), nil}-func (m Manager) WritePlist(program, configPath string) (string, error) {- if runtime.GOOS != "darwin" {- return "", fmt.Errorf("launchd service management is supported only on macOS")+func (m Manager) resolvedKind() Kind {+ if m.Kind != KindAuto {+ return m.Kind}- path, err := m.PlistPath()- if err != nil {- return "", err- }- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {- return "", err- }- content := plist(m.Label(), program, configPath)- return path, os.WriteFile(path, []byte(content), 0644)+ return DetectKind()}-func (m Manager) Load() error {- if runtime.GOOS != "darwin" {- return nil+func (m Manager) backend() backend {+ switch m.resolvedKind() {+ case KindLaunchd:+ return launchdBackend{}+ case KindSystemd:+ return systemdBackend{}+ default:+ return supervisedBackend{}}- path, err := m.PlistPath()- if err != nil {- return err- }- return loadLaunchdJob(serviceDomain(m.UserMode), m.Label(), path)}-func (m Manager) Unload() error {- if runtime.GOOS != "darwin" {- return nil- }- target := serviceDomain(m.UserMode) + "/" + m.Label()- return runLaunchctlWithContext(serviceDomain(m.UserMode), m.Label(), "", "bootout", target)-}--func (m Manager) Restart() error {- if runtime.GOOS != "darwin" {- return nil- }- domain := serviceDomain(m.UserMode)- label := m.Label()- target := domain + "/" + label- out, err := runLaunchctlCommand("kickstart", "-k", target)- if err == nil {- return nil- }- text := strings.TrimSpace(out)- if launchctlNoSuchProcess(text) {- return m.Load()- }- return launchctlError(text, err, domain, label, "", "kickstart", "-k", target)-}+// ResolvedKind reports the backend in use, for status output and diagnostics.+func (m Manager) ResolvedKind() Kind { return m.resolvedKind() }-func (m Manager) Status() Status {- status := Status{Label: m.Label()}- if runtime.GOOS != "darwin" {- status.Message = "service status is available only on macOS"- return status- }- out, err := runLaunchctlCommand("print", serviceDomain(m.UserMode)+"/"+m.Label())- if err != nil {- status.Message = strings.TrimSpace(out)- return status- }- status.Loaded = true- text := out- status.Running = strings.Contains(text, "state = running") || strings.Contains(text, "pid =")- return status-}+// Available reports whether the resolved backend can manage services on this host.+func (m Manager) Available() bool { return m.backend().available() }-func runLaunchctl(args ...string) error {- return runLaunchctlWithContext("", "", "", args...)-}+// UnsupportedReason explains why Available is false.+func (m Manager) UnsupportedReason() string { return m.backend().unsupportedReason() }-func runLaunchctlWithContext(domain, label, plistPath string, args ...string) error {- out, err := runLaunchctlCommand(args...)- if err == nil {- return nil- }- text := strings.TrimSpace(out)- if launchctlNoSuchProcess(text) {- return nil- }- return launchctlError(text, err, domain, label, plistPath, args...)-}+func (m Manager) Label() string { return m.backend().label(m.UserMode) }-func launchctlNoSuchProcess(text string) bool {- return strings.Contains(text, "No such process") || strings.Contains(text, "Could not find service")-}+// UnitPath is the on-disk service definition: a launchd plist, a systemd unit, or (in+// supervised mode, which has no unit file) the pidfile.+func (m Manager) UnitPath() (string, error) { return m.backend().unitPath(m.UserMode) }-func loadLaunchdJob(domain, label, plistPath string) error {- out, err := runLaunchctlCommand("bootstrap", domain, plistPath)- if err == nil {- return nil- }- text := strings.TrimSpace(out)- if !launchdJobAppearsLoaded(text, domain, label) {- return launchctlError(text, err, domain, label, plistPath, "bootstrap", domain, plistPath)- }- target := domain + "/" + label- if err := runLaunchctlWithContext(domain, label, "", "bootout", target); err != nil {- return err+// WriteUnit installs the service definition and returns its path.+func (m Manager) WriteUnit(program, configPath string) (string, error) {+ b := m.backend()+ if !b.available() {+ return "", fmt.Errorf("%s", b.unsupportedReason())}- if out, err := runLaunchctlCommand("bootstrap", domain, plistPath); err != nil {- text := strings.TrimSpace(out)- if launchdJobAppearsLoaded(text, domain, label) {- return nil- }- return launchctlError(text, err, domain, label, plistPath, "bootstrap", domain, plistPath)- }- return nil+ return b.writeUnit(m.UserMode, program, configPath)}-func launchdJobAppearsLoaded(bootstrapOutput, domain, label string) bool {- text := strings.TrimSpace(bootstrapOutput)- if strings.Contains(text, "already bootstrapped") {- return true- }- if !strings.Contains(text, "Bootstrap failed: 5") && !strings.Contains(text, "Input/output error") {- return false+// Load registers and starts the service.+func (m Manager) Load() error {+ b := m.backend()+ if !b.available() {+ return fmt.Errorf("%s", b.unsupportedReason())}- out, err := runLaunchctlCommand("print", domain+"/"+label)- return err == nil && strings.TrimSpace(out) != ""+ return b.load(m.UserMode)}-func launchctlError(text string, err error, domain, label, plistPath string, args ...string) error {- context := launchctlContext(domain, label, plistPath)- guidance := launchctlGuidance(text, domain, label)- if guidance != "" {- return fmt.Errorf("launchctl %s failed%s: %s: %w\n%s", strings.Join(args, " "), context, text, err, guidance)+// Unload stops and deregisters the service. Missing services are not an error, so this is+// safe to call during uninstall and repair.+func (m Manager) Unload() error {+ b := m.backend()+ if !b.available() {+ // Nothing to unload if the backend cannot run here; uninstall should still proceed.+ return nil}- return fmt.Errorf("launchctl %s failed%s: %s: %w", strings.Join(args, " "), context, text, err)+ return b.unload(m.UserMode)}-func launchctlContext(domain, label, plistPath string) string {- var fields []string- if label != "" {- fields = append(fields, "label "+label)- }- if domain != "" {- fields = append(fields, "domain "+domain)- }- if plistPath != "" {- fields = append(fields, "plist "+plistPath)- }- if len(fields) == 0 {- return ""+// Restart restarts the service, starting it if it is not loaded.+func (m Manager) Restart() error {+ b := m.backend()+ if !b.available() {+ return fmt.Errorf("%s", b.unsupportedReason())}- return " (" + strings.Join(fields, ", ") + ")"+ return b.restart(m.UserMode)}-func launchctlGuidance(output, domain, label string) string {- if !strings.Contains(output, "Bootstrap failed: 5") && !strings.Contains(output, "Input/output error") {- return ""- }- target := label- if domain != "" && label != "" {- target = domain + "/" + label- }- if target == "" {- target = "the Beacon launchd job"+// Status reports the current service state.+func (m Manager) Status() Status {+ b := m.backend()+ if !b.available() {+ return Status{Label: b.label(m.UserMode), Kind: string(b.kind()), Message: b.unsupportedReason()}}- return fmt.Sprintf("Bootstrap failed: 5 usually means launchd could not read or execute the job. Verify the collector binary referenced by the plist exists and is executable, clear stale state with `launchctl bootout %s`, then inspect launchd logs with `log show --predicate 'process == \"launchd\"' --last 5m`.", target)+ s := b.status(m.UserMode)+ s.Kind = string(b.kind())+ return s}-func serviceDomain(userMode bool) string {- if userMode {- return "gui/" + fmt.Sprint(os.Getuid())- }- return "system"-}+// stateDir is where service-owned runtime state (pidfiles) lives. Derived from the endpoint+// config so it tracks the single SystemBaseDir definition rather than duplicating it.+func stateDir(userMode bool) string { return endpointconfig.BaseDir(userMode) }-func plist(label, program, configPath string) string {- return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>Label</key>- <string>%s</string>- <key>ProgramArguments</key>- <array>- <string>%s</string>- <string>--config</string>- <string>%s</string>- </array>- <key>RunAtLoad</key>- <true/>- <key>KeepAlive</key>- <true/>- <key>StandardOutPath</key>- <string>/tmp/%s.out</string>- <key>StandardErrorPath</key>- <string>/tmp/%s.err</string>-</dict>-</plist>-`, label, program, configPath, label, label)+// ensureDir creates a directory for a service definition, tolerating an existing one.+func ensureDir(path string) error {+ return os.MkdirAll(filepath.Dir(path), 0o755)}diff --git a/cli/beacon/internal/endpoint/service/service_test.go b/cli/beacon/internal/endpoint/service/service_test.goindex 105ed8ff..086510d1 100644--- a/cli/beacon/internal/endpoint/service/service_test.go+++ b/cli/beacon/internal/endpoint/service/service_test.go@@ -4,41 +4,13 @@ import ("errors""fmt""os"+ "os/exec""path/filepath""runtime""strings""testing")-func TestManagerLabelAndPlistPath(t *testing.T) {- home := t.TempDir()- t.Setenv("HOME", home)-- userManager := Manager{UserMode: true}- if got := userManager.Label(); got != UserLabel {- t.Fatalf("user label = %q, want %q", got, UserLabel)- }- userPath, err := userManager.PlistPath()- if err != nil {- t.Fatalf("user PlistPath returned error: %v", err)- }- if want := filepath.Join(home, "Library", "LaunchAgents", UserLabel+".plist"); userPath != want {- t.Fatalf("user plist path = %q, want %q", userPath, want)- }-- systemManager := Manager{}- if got := systemManager.Label(); got != SystemLabel {- t.Fatalf("system label = %q, want %q", got, SystemLabel)- }- systemPath, err := systemManager.PlistPath()- if err != nil {- t.Fatalf("system PlistPath returned error: %v", err)- }- if want := filepath.Join("/Library/LaunchDaemons", SystemLabel+".plist"); systemPath != want {- t.Fatalf("system plist path = %q, want %q", systemPath, want)- }-}-func TestPlistContainsLaunchdContract(t *testing.T) {content := plist(UserLabel, "/tmp/otelcol", "/tmp/otelcol.yaml")@@ -58,49 +30,6 @@ func TestPlistContainsLaunchdContract(t *testing.T) {}}-func TestWritePlistUserMode(t *testing.T) {- home := t.TempDir()- t.Setenv("HOME", home)- manager := Manager{UserMode: true}-- path, err := manager.WritePlist("/tmp/otelcol", "/tmp/otelcol.yaml")- if runtime.GOOS != "darwin" {- if err == nil || !strings.Contains(err.Error(), "supported only on macOS") {- t.Fatalf("WritePlist non-darwin error = %v, want macOS support error", err)- }- return- }- if err != nil {- t.Fatalf("WritePlist returned error: %v", err)- }- if got, want := path, filepath.Join(home, "Library", "LaunchAgents", UserLabel+".plist"); got != want {- t.Fatalf("plist path = %q, want %q", got, want)- }- data, err := os.ReadFile(path)- if err != nil {- t.Fatalf("read plist: %v", err)- }- if !strings.Contains(string(data), "<string>/tmp/otelcol</string>") {- t.Fatalf("plist content missing program: %s", string(data))- }-}--func TestStatusNonDarwinDocumentsUnsupportedMessage(t *testing.T) {- if runtime.GOOS == "darwin" {- t.Skip("non-darwin status contract")- }- status := (Manager{UserMode: true}).Status()- if status.Label != UserLabel {- t.Fatalf("Label = %q, want %q", status.Label, UserLabel)- }- if status.Loaded || status.Running {- t.Fatalf("non-darwin status should not be loaded/running: %#v", status)- }- if !strings.Contains(status.Message, "available only on macOS") {- t.Fatalf("unexpected status message: %q", status.Message)- }-}-func TestRunLaunchctlWithContextExplainsBootstrapIOError(t *testing.T) {oldRun := runLaunchctlCommandrunLaunchctlCommand = func(args ...string) (string, error) {@@ -306,32 +235,74 @@ func TestServiceDomainUserAndSystem(t *testing.T) {}}-func TestLoadAndUnloadAreNoOpsOffDarwin(t *testing.T) {+func TestLaunchdIsInertOffDarwin(t *testing.T) {if runtime.GOOS == "darwin" {- t.Skip("non-darwin launchd contract")- }- manager := Manager{UserMode: true}+ t.Skip("launchd is usable here")+ }+ // The old contract was "Load and Unload both return nil off darwin", which encoded+ // "Linux does nothing" and hid the fact that nothing was ever installed. The contract+ // now distinguishes the two: asking to load a launchd service where launchd does not+ // exist is an error, while Unload stays forgiving so uninstall and repair can call it+ // speculatively on any host. launchctl must not be invoked either way.+ manager := Manager{UserMode: true, Kind: KindLaunchd}called := falseoldRun := runLaunchctlCommandrunLaunchctlCommand = func(args ...string) (string, error) {called = truereturn "", errors.New("launchctl should not run off darwin")}- t.Cleanup(func() {- runLaunchctlCommand = oldRun- })+ t.Cleanup(func() { runLaunchctlCommand = oldRun })- if err := manager.Load(); err != nil {- t.Fatalf("Load off darwin = %v, want nil", err)+ if err := manager.Load(); err == nil {+ t.Fatal("Load off darwin should report that launchd is unavailable, not silently succeed")}if err := manager.Unload(); err != nil {- t.Fatalf("Unload off darwin = %v, want nil", err)+ t.Fatalf("Unload off darwin = %v, want nil so uninstall can call it unconditionally", err)}if called {t.Fatal("launchctl was invoked off darwin")}}+// Supervised mode is what Linux actually falls back to, so its lifecycle needs real coverage+// rather than the old "does nothing" assertion.+func TestSupervisedLifecycleStartsAndStopsAProcess(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ m := Manager{UserMode: true, Kind: KindSupervised}++ // Loading before install must explain itself rather than silently doing nothing.+ if err := m.Load(); err == nil {+ t.Fatal("Load with nothing recorded should error")+ }++ // `sleep` stands in for the collector: long-lived and harmless.+ sleepBin, err := exec.LookPath("sleep")+ if err != nil {+ t.Skip("no sleep binary available")+ }+ if _, err := m.WriteUnit(sleepBin, "300"); err != nil {+ t.Fatalf("WriteUnit: %v", err)+ }+ if err := m.Load(); err != nil {+ t.Fatalf("Load: %v", err)+ }+ st := m.Status()+ if !st.Running {+ t.Fatalf("expected a running supervised process, got %#v", st)+ }+ if err := m.Unload(); err != nil {+ t.Fatalf("Unload: %v", err)+ }+ if st := m.Status(); st.Running {+ t.Fatalf("expected the process stopped after Unload, got %#v", st)+ }+ // Unload must stay idempotent, since uninstall may call it more than once.+ if err := m.Unload(); err != nil {+ t.Fatalf("second Unload should be a no-op, got %v", err)+ }+}+func TestLaunchctlGuidance(t *testing.T) {if got := launchctlGuidance("some unrelated launchctl output", "gui/501", UserLabel); got != "" {t.Fatalf("guidance for unrelated output = %q, want empty", got)@@ -347,3 +318,234 @@ func TestLaunchctlGuidance(t *testing.T) {t.Fatalf("guidance missing generic target fallback: %q", fallback)}}++// Backends are pinned explicitly in these tests rather than relying on detection, so launchd+// path and rendering logic stays covered when the suite runs on Linux CI, and vice versa.++func TestLaunchdLabelAndUnitPath(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)++ user := Manager{UserMode: true, Kind: KindLaunchd}+ if got := user.Label(); got != UserLabel {+ t.Fatalf("user label = %q, want %q", got, UserLabel)+ }+ userPath, err := user.UnitPath()+ if err != nil {+ t.Fatalf("user UnitPath returned error: %v", err)+ }+ if want := filepath.Join(home, "Library", "LaunchAgents", UserLabel+".plist"); userPath != want {+ t.Fatalf("user plist path = %q, want %q", userPath, want)+ }++ system := Manager{Kind: KindLaunchd}+ if got := system.Label(); got != SystemLabel {+ t.Fatalf("system label = %q, want %q", got, SystemLabel)+ }+ systemPath, err := system.UnitPath()+ if err != nil {+ t.Fatalf("system UnitPath returned error: %v", err)+ }+ if want := filepath.Join("/Library/LaunchDaemons", SystemLabel+".plist"); systemPath != want {+ t.Fatalf("system plist path = %q, want %q", systemPath, want)+ }+}++func TestSystemdLabelAndUnitPath(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)++ user := Manager{UserMode: true, Kind: KindSystemd}+ if got := user.Label(); got != SystemdUserUnit {+ t.Fatalf("user unit = %q, want %q", got, SystemdUserUnit)+ }+ userPath, err := user.UnitPath()+ if err != nil {+ t.Fatalf("user UnitPath returned error: %v", err)+ }+ if want := filepath.Join(home, ".config", "systemd", "user", SystemdUserUnit); userPath != want {+ t.Fatalf("user unit path = %q, want %q", userPath, want)+ }++ systemPath, err := (Manager{Kind: KindSystemd}).UnitPath()+ if err != nil {+ t.Fatalf("system UnitPath returned error: %v", err)+ }+ if want := filepath.Join("/etc/systemd/system", SystemdSystemUnit); systemPath != want {+ t.Fatalf("system unit path = %q, want %q", systemPath, want)+ }+}++// The systemd unit has to preserve the behaviour the launchd plist provided, or a Linux+// install silently loses restart-on-crash and start-at-boot.+func TestSystemdUnitPreservesLaunchdSemantics(t *testing.T) {+ content := unitFile("/opt/beacon/bin/beacon-otelcol", "/etc/beacon/endpoint/otelcol.yaml", false)+ for _, want := range []string{+ "ExecStart=/opt/beacon/bin/beacon-otelcol --config /etc/beacon/endpoint/otelcol.yaml",+ "Restart=always", // KeepAlive+ "WantedBy=multi-user.target", // RunAtLoad+ "StandardOutput=journal", // replaces /tmp/<label>.out+ "User=root",+ } {+ if !strings.Contains(content, want) {+ t.Fatalf("system unit missing %q:\n%s", want, content)+ }+ }++ userUnit := unitFile("/usr/bin/beacon-otelcol", "/home/u/.beacon/endpoint/otelcol.yaml", true)+ if !strings.Contains(userUnit, "WantedBy=default.target") {+ t.Fatalf("user unit should target default.target:\n%s", userUnit)+ }+ if strings.Contains(userUnit, "User=root") {+ t.Fatalf("user unit must not force root:\n%s", userUnit)+ }+}++// systemctl takes --user for user-scope units; getting this wrong would operate on the wrong+// unit entirely.+func TestSystemctlArgsScoping(t *testing.T) {+ if got := systemctlArgs(true, "is-active", "u"); got[0] != "--user" {+ t.Fatalf("user scope should pass --user first, got %v", got)+ }+ if got := systemctlArgs(false, "is-active", "u"); got[0] == "--user" {+ t.Fatalf("system scope must not pass --user, got %v", got)+ }+}++func TestSystemdStatusReadsEnabledAndActive(t *testing.T) {+ old := runSystemctlCommand+ t.Cleanup(func() { runSystemctlCommand = old })++ runSystemctlCommand = func(args ...string) (string, error) {+ for _, a := range args {+ switch a {+ case "is-enabled":+ return "enabled\n", nil+ case "is-active":+ return "active\n", nil+ }+ }+ return "", nil+ }+ st := systemdBackend{}.status(false)+ if !st.Loaded || !st.Running {+ t.Fatalf("enabled+active should be loaded and running, got %#v", st)+ }++ // A unit that exists but is stopped must report loaded-but-not-running, not absent.+ runSystemctlCommand = func(args ...string) (string, error) {+ for _, a := range args {+ switch a {+ case "is-enabled":+ return "enabled\n", nil+ case "is-active":+ return "inactive\n", nil+ }+ }+ return "", nil+ }+ st = systemdBackend{}.status(false)+ if !st.Loaded || st.Running {+ t.Fatalf("enabled+inactive should be loaded, not running, got %#v", st)+ }+}++// Unload is called speculatively by uninstall and repair, so an absent unit must not be an+// error or those paths would fail on a clean host.+func TestSystemdUnloadToleratesMissingUnit(t *testing.T) {+ old := runSystemctlCommand+ t.Cleanup(func() { runSystemctlCommand = old })+ runSystemctlCommand = func(args ...string) (string, error) {+ return "Failed to stop beacon-collector.service: Unit beacon-collector.service not loaded.", errors.New("exit status 5")+ }+ if err := (systemdBackend{}).unload(false); err != nil {+ t.Fatalf("unload should tolerate a missing unit, got %v", err)+ }+}++func TestSystemdUnitMissingRecognizesSystemdPhrasings(t *testing.T) {+ for _, out := range []string{+ "Unit beacon-collector.service not loaded.",+ "Unit beacon-collector.service could not be found.",+ "Failed to open /etc/systemd/system/x.service: No such file or directory",+ } {+ if !systemdUnitMissing(out) {+ t.Errorf("should recognize as missing: %q", out)+ }+ }+ if systemdUnitMissing("Job for beacon-collector.service failed") {+ t.Error("a genuine failure must not be treated as a missing unit")+ }+}++// Supervised mode is the container/CI fallback. It must be usable everywhere, since that is+// the whole point of having it.+func TestSupervisedIsAlwaysAvailable(t *testing.T) {+ if !(Manager{Kind: KindSupervised}).Available() {+ t.Fatal("supervised mode must be available on every platform")+ }+}++func TestSupervisedRecordsAndReportsState(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ m := Manager{UserMode: true, Kind: KindSupervised}++ if st := m.Status(); st.Loaded || st.Running {+ t.Fatalf("nothing installed yet, got %#v", st)+ }++ path, err := m.WriteUnit("/bin/true", "/tmp/otelcol.yaml")+ if err != nil {+ t.Fatalf("WriteUnit: %v", err)+ }+ if filepath.Base(path) != "collector.pid" {+ t.Fatalf("supervised state should be a pidfile, got %q", path)+ }+ st := m.Status()+ if !st.Loaded {+ t.Fatalf("after WriteUnit the service should be recorded: %#v", st)+ }+ if st.Running {+ t.Fatalf("WriteUnit must not start anything: %#v", st)+ }+ // The absence of a supervisor is a real difference from launchd/systemd and must be+ // stated rather than implied.+ if _ = st.Message; !strings.Contains(m.Status().Message, "not running") {+ t.Fatalf("status message should say it is not running, got %q", st.Message)+ }+}++func TestParseKindAcceptsAliasesAndRejectsGarbage(t *testing.T) {+ for in, want := range map[string]Kind{+ "": KindAuto, "auto": KindAuto, "launchd": KindLaunchd,+ "systemd": KindSystemd, "none": KindSupervised, "supervised": KindSupervised,+ "SystemD": KindSystemd,+ } {+ got, err := ParseKind(in)+ if err != nil || got != want {+ t.Errorf("ParseKind(%q) = %q, %v; want %q", in, got, err, want)+ }+ }+ if _, err := ParseKind("upstart"); err == nil {+ t.Error("an unknown service kind must be rejected rather than silently ignored")+ }+}++func TestDetectKindMatchesHost(t *testing.T) {+ got := DetectKind()+ switch runtime.GOOS {+ case "darwin":+ if got != KindLaunchd {+ t.Fatalf("macOS should detect launchd, got %q", got)+ }+ case "linux":+ // Either is correct depending on whether the host or container has systemd as PID 1.+ if got != KindSystemd && got != KindSupervised {+ t.Fatalf("Linux should detect systemd or supervised, got %q", got)+ }+ if got == KindSystemd && !systemdIsInit() {+ t.Fatal("detected systemd without systemd as PID 1")+ }+ }+}diff --git a/cli/beacon/internal/endpoint/service/supervised.go b/cli/beacon/internal/endpoint/service/supervised.gonew file mode 100644index 00000000..253eb049--- /dev/null+++ b/cli/beacon/internal/endpoint/service/supervised.go@@ -0,0 +1,214 @@+package service++import (+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "strconv"+ "strings"+ "syscall"+ "time"+)++// supervisedBackend runs the collector as a detached child process tracked by a pidfile.+//+// There is no OS service manager involved, which is exactly right for containers, CI runners,+// and cloud agent sandboxes -- environments where an init system either does not exist or is+// not ours to configure. `beacon ci` has always worked this way; this makes the same model+// reachable from `beacon endpoint install`.+//+// Honest limitation: nothing restarts the collector if it dies, because there is no+// supervisor. That is a real difference from launchd's KeepAlive and systemd's+// Restart=always, and it is why this is the fallback rather than the default. Status reports+// it so nobody is misled.+type supervisedBackend struct{}++// supervisedState is what the pidfile holds. The config path is recorded so Restart can+// relaunch with the same arguments without the caller having to supply them again.+type supervisedState struct {+ PID int `json:"pid"`+ Program string `json:"program"`+ ConfigPath string `json:"config_path"`+ StartedAt string `json:"started_at"`+}++func (supervisedBackend) kind() Kind { return KindSupervised }++// available is unconditionally true: starting a child process needs no platform support.+func (supervisedBackend) available() bool { return true }++func (supervisedBackend) unsupportedReason() string { return "" }++func (supervisedBackend) label(userMode bool) string {+ if userMode {+ return "beacon-collector-user"+ }+ return "beacon-collector"+}++// unitPath reports the pidfile, since supervised mode has no unit file. Callers show this to+// users, so returning something real beats returning an error.+func (b supervisedBackend) unitPath(userMode bool) (string, error) {+ return filepath.Join(stateDir(userMode), "collector.pid"), nil+}++// writeUnit records the intended command. Nothing starts here: load does that, matching the+// other backends where writeUnit installs a definition and load activates it.+func (b supervisedBackend) writeUnit(userMode bool, program, configPath string) (string, error) {+ path, err := b.unitPath(userMode)+ if err != nil {+ return "", err+ }+ if err := ensureDir(path); err != nil {+ return "", err+ }+ existing, _ := b.read(userMode)+ state := supervisedState{Program: program, ConfigPath: configPath}+ // Preserve a live pid so writeUnit followed by status does not lose track of a collector+ // that is already running.+ if existing.PID > 0 && processAlive(existing.PID) {+ state.PID = existing.PID+ state.StartedAt = existing.StartedAt+ }+ return path, b.write(userMode, state)+}++func (b supervisedBackend) read(userMode bool) (supervisedState, error) {+ var st supervisedState+ path, err := b.unitPath(userMode)+ if err != nil {+ return st, err+ }+ data, err := os.ReadFile(path)+ if err != nil {+ return st, err+ }+ // Tolerate a bare pid, which is what a hand-written or legacy pidfile looks like.+ trimmed := strings.TrimSpace(string(data))+ if pid, convErr := strconv.Atoi(trimmed); convErr == nil {+ st.PID = pid+ return st, nil+ }+ return st, json.Unmarshal(data, &st)+}++func (b supervisedBackend) write(userMode bool, st supervisedState) error {+ path, err := b.unitPath(userMode)+ if err != nil {+ return err+ }+ data, err := json.MarshalIndent(st, "", " ")+ if err != nil {+ return err+ }+ return os.WriteFile(path, append(data, '\n'), 0o644)+}++func (b supervisedBackend) load(userMode bool) error {+ st, err := b.read(userMode)+ if err != nil {+ return fmt.Errorf("no supervised collector recorded; run endpoint install first: %w", err)+ }+ if st.Program == "" {+ return errors.New("supervised collector has no recorded program path")+ }+ if st.PID > 0 && processAlive(st.PID) {+ return nil // already running+ }++ cmd := exec.Command(st.Program, "--config", st.ConfigPath)+ // Detach from this process group so the collector outlives the CLI invocation that+ // started it. Without this, the collector would die with the shell that ran install.+ cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}+ // Logs go to a file next to the runtime log, since there is no journal here.+ logPath := filepath.Join(stateDir(userMode), "collector.out")+ if f, ferr := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644); ferr == nil {+ cmd.Stdout = f+ cmd.Stderr = f+ defer f.Close()+ }+ if err := cmd.Start(); err != nil {+ return fmt.Errorf("start supervised collector: %w", err)+ }+ // Release the child so it is not left as a zombie when this process exits.+ go func() { _ = cmd.Wait() }()++ st.PID = cmd.Process.Pid+ st.StartedAt = time.Now().UTC().Format(time.RFC3339)+ return b.write(userMode, st)+}++func (b supervisedBackend) unload(userMode bool) error {+ st, err := b.read(userMode)+ if err != nil {+ return nil // nothing recorded, nothing to stop+ }+ if st.PID <= 0 || !processAlive(st.PID) {+ st.PID = 0+ _ = b.write(userMode, st)+ return nil+ }+ proc, err := os.FindProcess(st.PID)+ if err != nil {+ return nil+ }+ // SIGTERM lets the collector flush and shut down cleanly; the exporter closes its file+ // on shutdown, so killing outright risks losing buffered events.+ _ = proc.Signal(syscall.SIGTERM)+ deadline := time.Now().Add(10 * time.Second)+ for time.Now().Before(deadline) {+ if !processAlive(st.PID) {+ break+ }+ time.Sleep(100 * time.Millisecond)+ }+ if processAlive(st.PID) {+ _ = proc.Kill()+ }+ st.PID = 0+ return b.write(userMode, st)+}++func (b supervisedBackend) restart(userMode bool) error {+ if err := b.unload(userMode); err != nil {+ return err+ }+ return b.load(userMode)+}++func (b supervisedBackend) status(userMode bool) Status {+ status := Status{Label: b.label(userMode)}+ st, err := b.read(userMode)+ if err != nil {+ status.Message = "no supervised collector recorded"+ return status+ }+ // "Loaded" means installed and intended to run, matching the other backends.+ status.Loaded = st.Program != ""+ status.Running = st.PID > 0 && processAlive(st.PID)+ switch {+ case status.Running:+ status.Message = fmt.Sprintf("supervised pid %d (no automatic restart: no service manager)", st.PID)+ case status.Loaded:+ status.Message = "recorded but not running"+ default:+ status.Message = "no supervised collector recorded"+ }+ return status+}++// processAlive reports whether a pid is live. Signal 0 performs the permission and existence+// checks without delivering anything.+func processAlive(pid int) bool {+ if pid <= 0 {+ return false+ }+ proc, err := os.FindProcess(pid)+ if err != nil {+ return false+ }+ return proc.Signal(syscall.Signal(0)) == nil+}diff --git a/cli/beacon/internal/endpoint/service/systemd.go b/cli/beacon/internal/endpoint/service/systemd.gonew file mode 100644index 00000000..a688740b--- /dev/null+++ b/cli/beacon/internal/endpoint/service/systemd.go@@ -0,0 +1,261 @@+package service++import (+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+)++// systemdBackend manages the collector via systemd.+//+// Mapping from the launchd behavior it replaces:+//+// RunAtLoad=true -> WantedBy=multi-user.target plus `systemctl enable --now`+// KeepAlive=true -> Restart=always with a small RestartSec+// StandardOutPath -> the journal, so no /tmp files to manage or rotate+// gui/<uid> domain -> `systemctl --user`, which additionally needs linger enabled to+// survive logout (see EnableLinger)+type systemdBackend struct{}++var runSystemctlCommand = func(args ...string) (string, error) {+ cmd := exec.Command("systemctl", args...)+ out, err := cmd.CombinedOutput()+ return string(out), err+}++var runLoginctlCommand = func(args ...string) (string, error) {+ cmd := exec.Command("loginctl", args...)+ out, err := cmd.CombinedOutput()+ return string(out), err+}++// systemdIsInit reports whether systemd is PID 1.+//+// Checked by reading /proc/1/comm rather than by probing for the systemctl binary: many+// container images ship systemctl while running some other init, and in that case every+// systemctl call fails with "System has not been booted with systemd as init system". Getting+// this wrong would make install appear to succeed and then never start anything.+func systemdIsInit() bool {+ if runtime.GOOS != "linux" {+ return false+ }+ b, err := os.ReadFile("/proc/1/comm")+ if err != nil {+ return false+ }+ return strings.TrimSpace(string(b)) == "systemd"+}++func (systemdBackend) kind() Kind { return KindSystemd }++func (systemdBackend) available() bool { return systemdIsInit() }++func (systemdBackend) unsupportedReason() string {+ if runtime.GOOS != "linux" {+ return "systemd service management is available only on Linux"+ }+ return "systemd is not PID 1 on this host; use --service=none for a supervised collector process"+}++func (systemdBackend) label(userMode bool) string {+ if userMode {+ return SystemdUserUnit+ }+ return SystemdSystemUnit+}++func (b systemdBackend) unitPath(userMode bool) (string, error) {+ if userMode {+ home, err := os.UserHomeDir()+ if err != nil {+ return "", err+ }+ return filepath.Join(home, ".config", "systemd", "user", SystemdUserUnit), nil+ }+ return filepath.Join("/etc/systemd/system", SystemdSystemUnit), nil+}++// systemctlArgs prefixes --user for user-mode units so one code path serves both scopes.+func systemctlArgs(userMode bool, args ...string) []string {+ if userMode {+ return append([]string{"--user"}, args...)+ }+ return args+}++func (b systemdBackend) writeUnit(userMode bool, program, configPath string) (string, error) {+ path, err := b.unitPath(userMode)+ if err != nil {+ return "", err+ }+ if err := ensureDir(path); err != nil {+ return "", err+ }+ if err := os.WriteFile(path, []byte(unitFile(program, configPath, userMode)), 0o644); err != nil {+ return "", err+ }+ // systemd caches unit files; without a reload it will keep using the previous contents,+ // which makes a repair look successful while changing nothing.+ if out, err := runSystemctlCommand(systemctlArgs(userMode, "daemon-reload")...); err != nil {+ return path, systemctlError(out, err, "daemon-reload")+ }+ return path, nil+}++func (b systemdBackend) load(userMode bool) error {+ unit := b.label(userMode)+ if out, err := runSystemctlCommand(systemctlArgs(userMode, "enable", "--now", unit)...); err != nil {+ return systemctlError(out, err, "enable --now "+unit)+ }+ return nil+}++func (b systemdBackend) unload(userMode bool) error {+ unit := b.label(userMode)+ // Stop before disable so a running collector is actually terminated, and tolerate an+ // absent unit: uninstall and repair both call this speculatively.+ if out, err := runSystemctlCommand(systemctlArgs(userMode, "stop", unit)...); err != nil {+ if !systemdUnitMissing(out) {+ return systemctlError(out, err, "stop "+unit)+ }+ }+ if out, err := runSystemctlCommand(systemctlArgs(userMode, "disable", unit)...); err != nil {+ if !systemdUnitMissing(out) {+ return systemctlError(out, err, "disable "+unit)+ }+ }+ return nil+}++func (b systemdBackend) restart(userMode bool) error {+ unit := b.label(userMode)+ out, err := runSystemctlCommand(systemctlArgs(userMode, "restart", unit)...)+ if err == nil {+ return nil+ }+ // A unit that was never enabled cannot be restarted; installing it is the right recovery+ // and mirrors the launchd backend's kickstart-then-load fallback.+ if systemdUnitMissing(out) {+ return b.load(userMode)+ }+ return systemctlError(out, err, "restart "+unit)+}++func (b systemdBackend) status(userMode bool) Status {+ unit := b.label(userMode)+ status := Status{Label: unit}++ // is-enabled exits non-zero for a disabled unit, which is a state rather than a failure,+ // so the output is what matters and the error is ignored.+ enabledOut, _ := runSystemctlCommand(systemctlArgs(userMode, "is-enabled", unit)...)+ enabled := strings.TrimSpace(enabledOut)+ switch enabled {+ case "enabled", "enabled-runtime", "static", "indirect", "linked", "linked-runtime":+ status.Loaded = true+ }++ activeOut, _ := runSystemctlCommand(systemctlArgs(userMode, "is-active", unit)...)+ active := strings.TrimSpace(activeOut)+ status.Running = active == "active"+ if status.Running {+ // A running unit is loaded regardless of whether it is enabled at boot.+ status.Loaded = true+ }++ if !status.Loaded && !status.Running {+ status.Message = strings.TrimSpace(enabled + " " + active)+ if status.Message == "" {+ status.Message = "unit not installed"+ }+ }+ return status+}++// systemdUnitMissing recognizes the several ways systemd reports an absent unit.+func systemdUnitMissing(out string) bool {+ l := strings.ToLower(out)+ return strings.Contains(l, "not loaded") ||+ strings.Contains(l, "could not be found") ||+ strings.Contains(l, "no such file or directory") ||+ strings.Contains(l, "does not exist")+}++func systemctlError(out string, err error, what string) error {+ text := strings.TrimSpace(out)+ guidance := ""+ if strings.Contains(strings.ToLower(text), "interactive authentication required") {+ guidance = "\nsystemd requires privileges for system units; rerun with sudo, or use --user for a per-user service."+ }+ if text == "" {+ return fmt.Errorf("systemctl %s failed: %w%s", what, err, guidance)+ }+ return fmt.Errorf("systemctl %s failed: %s: %w%s", what, text, err, guidance)+}++// EnableLinger allows a --user unit to keep running after the user logs out.+//+// This is the piece with no macOS counterpart: launchd's gui/<uid> domain persists for the+// login session, whereas a systemd user manager is torn down at logout unless linger is set.+// Without it a user-mode install silently stops collecting the moment the user logs out.+// Best-effort, since it needs privileges that a plain user may not have.+func EnableLinger(username string) (bool, string) {+ if !systemdIsInit() {+ return false, "systemd is not PID 1; linger does not apply"+ }+ if username == "" {+ return false, "no username provided"+ }+ if out, err := runLoginctlCommand("enable-linger", username); err != nil {+ return false, strings.TrimSpace(out)+ }+ return true, ""+}++// LingerEnabled reports whether linger is on for a user, so doctor can flag the gap.+func LingerEnabled(username string) bool {+ if !systemdIsInit() || username == "" {+ return false+ }+ out, err := runLoginctlCommand("show-user", username, "--property=Linger", "--value")+ if err != nil {+ return false+ }+ return strings.EqualFold(strings.TrimSpace(out), "yes")+}++// unitFile renders the collector unit.+func unitFile(program, configPath string, userMode bool) string {+ var b strings.Builder+ b.WriteString("[Unit]\n")+ b.WriteString("Description=Beacon endpoint collector\n")+ b.WriteString("Documentation=https://docs.asymptotelabs.ai/cli/endpoint\n")+ // The collector only binds loopback and writes a local log, but ordering after the+ // network target avoids a restart storm during early boot.+ b.WriteString("After=network.target\n")+ b.WriteString("\n[Service]\n")+ b.WriteString("Type=simple\n")+ fmt.Fprintf(&b, "ExecStart=%s --config %s\n", program, configPath)+ // KeepAlive equivalent.+ b.WriteString("Restart=always\n")+ b.WriteString("RestartSec=5\n")+ // stdout/stderr go to the journal, replacing launchd's /tmp/<label>.out files.+ b.WriteString("StandardOutput=journal\n")+ b.WriteString("StandardError=journal\n")+ if !userMode {+ // System mode runs as root because the collector writes /var/log/beacon-agent, which+ // hooks running as the console user also append to. Hardening that is deliberately+ // left for the packaging milestone, where the log directory ownership story is+ // decided.+ b.WriteString("User=root\n")+ }+ b.WriteString("\n[Install]\n")+ if userMode {+ b.WriteString("WantedBy=default.target\n")+ } else {+ b.WriteString("WantedBy=multi-user.target\n")+ }+ return b.String()+}diff --git a/cli/beacon/internal/endpoint/service/updater.go b/cli/beacon/internal/endpoint/service/updater.goindex 054374c6..ddb0cfa7 100644--- a/cli/beacon/internal/endpoint/service/updater.go+++ b/cli/beacon/internal/endpoint/service/updater.go@@ -9,12 +9,56 @@ import ("strings")-// UpdaterLabel is the launchd label for the periodic endpoint updater job.-const UpdaterLabel = "com.beacon.endpoint.updater"+const (+ // UpdaterLabel is the launchd label for the periodic endpoint updater job.+ UpdaterLabel = "com.beacon.endpoint.updater"+ // UpdaterTimerUnit and UpdaterServiceUnit are the systemd equivalents. systemd splits+ // "what to run" from "when to run it", so a scheduled job needs both.+ UpdaterServiceUnit = "beacon-updater.service"+ UpdaterTimerUnit = "beacon-updater.timer"+)++// UpdaterManager manages the periodic endpoint updater. Unlike the collector it is+// system-only and runs on a schedule rather than staying resident.+type UpdaterManager struct {+ // Kind selects the backend; the zero value auto-detects.+ Kind Kind+}-// UpdaterManager manages the endpoint updater launchd job. Unlike the collector-// service it is system-only and runs on a schedule rather than KeepAlive.-type UpdaterManager struct{}+func (m UpdaterManager) resolvedKind() Kind {+ if m.Kind != KindAuto {+ return m.Kind+ }+ return DetectKind()+}++// Supported reports whether a scheduled updater can be installed here.+//+// Supervised mode has no scheduler, so there is deliberately no fallback: a timer that+// silently never fires would be worse than refusing to install one.+func (m UpdaterManager) Supported() bool {+ switch m.resolvedKind() {+ case KindLaunchd:+ return runtime.GOOS == "darwin"+ case KindSystemd:+ return systemdIsInit()+ default:+ return false+ }+}++// UnsupportedReason explains why Supported is false.+func (m UpdaterManager) UnsupportedReason() string {+ switch m.resolvedKind() {+ case KindLaunchd:+ return "launchd service management is supported only on macOS"+ case KindSystemd:+ return "systemd is not PID 1 on this host, so a scheduled updater cannot be installed"+ default:+ return "the scheduled updater needs launchd or systemd; a supervised collector has no scheduler. " ++ "Update Beacon through your package manager or run `beacon endpoint update --apply` from your own scheduler."+ }+}var startDeferredUpdaterReload = func(path string) error {cmd := exec.Command("/bin/sh", "-c", deferredUpdaterReloadScript(path))@@ -32,50 +76,126 @@ func deferredUpdaterReloadScript(path string) string {)}-// PlistPath returns the LaunchDaemon plist path for the updater job.-func (UpdaterManager) PlistPath() string {+// UnitPath returns the on-disk path of the updater service definition. On systemd this is the+// timer, since that is the unit an administrator enables and inspects.+func (m UpdaterManager) UnitPath() string {+ if m.resolvedKind() == KindSystemd {+ return filepath.Join("/etc/systemd/system", UpdaterTimerUnit)+ }return filepath.Join("/Library/LaunchDaemons", UpdaterLabel+".plist")}-// WritePlist writes the updater LaunchDaemon plist invoking the given program.-func (m UpdaterManager) WritePlist(program string) (string, error) {- if runtime.GOOS != "darwin" {- return "", fmt.Errorf("launchd service management is supported only on macOS")+// WriteUnit installs the updater definition invoking the given program.+func (m UpdaterManager) WriteUnit(program string) (string, error) {+ if !m.Supported() {+ return "", fmt.Errorf("%s", m.UnsupportedReason())+ }+ if m.resolvedKind() == KindSystemd {+ return m.writeSystemdUnits(program)+ }+ path := m.UnitPath()+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ return "", err+ }+ return path, os.WriteFile(path, []byte(updaterPlist(UpdaterLabel, program)), 0o644)+}++// writeSystemdUnits writes the oneshot service plus the timer that drives it.+func (m UpdaterManager) writeSystemdUnits(program string) (string, error) {+ dir := "/etc/systemd/system"+ if err := os.MkdirAll(dir, 0o755); err != nil {+ return "", err}- path := m.PlistPath()- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ svc := filepath.Join(dir, UpdaterServiceUnit)+ if err := os.WriteFile(svc, []byte(updaterServiceUnit(program)), 0o644); err != nil {return "", err}- return path, os.WriteFile(path, []byte(updaterPlist(UpdaterLabel, program)), 0644)+ timer := filepath.Join(dir, UpdaterTimerUnit)+ if err := os.WriteFile(timer, []byte(updaterTimerUnit()), 0o644); err != nil {+ return "", err+ }+ if out, err := runSystemctlCommand("daemon-reload"); err != nil {+ return timer, systemctlError(out, err, "daemon-reload")+ }+ return timer, nil}-// Load bootstraps the updater job into the system domain.+// Load activates the updater schedule.func (m UpdaterManager) Load() error {- if runtime.GOOS != "darwin" {+ if !m.Supported() {+ return fmt.Errorf("%s", m.UnsupportedReason())+ }+ if m.resolvedKind() == KindSystemd {+ if out, err := runSystemctlCommand("enable", "--now", UpdaterTimerUnit); err != nil {+ return systemctlError(out, err, "enable --now "+UpdaterTimerUnit)+ }return nil}- path := m.PlistPath()+ path := m.UnitPath()+ // A running updater must not be torn out from under itself mid-update, so the reload is+ // deferred until the current invocation finishes.if status := m.Status(); status.Loaded && status.Running {return startDeferredUpdaterReload(path)}return loadLaunchdJob("system", UpdaterLabel, path)}-// Unload boots the updater job out of the system domain.+// Unload deactivates the updater schedule. A missing unit is not an error.func (m UpdaterManager) Unload() error {- if runtime.GOOS != "darwin" {+ switch m.resolvedKind() {+ case KindSystemd:+ if !systemdIsInit() {+ return nil+ }+ if out, err := runSystemctlCommand("stop", UpdaterTimerUnit); err != nil && !systemdUnitMissing(out) {+ return systemctlError(out, err, "stop "+UpdaterTimerUnit)+ }+ if out, err := runSystemctlCommand("disable", UpdaterTimerUnit); err != nil && !systemdUnitMissing(out) {+ return systemctlError(out, err, "disable "+UpdaterTimerUnit)+ }+ return nil+ case KindLaunchd:+ if runtime.GOOS != "darwin" {+ return nil+ }+ return runLaunchctlWithContext("system", UpdaterLabel, "", "bootout", "system/"+UpdaterLabel)+ default:return nil}- return runLaunchctlWithContext("system", UpdaterLabel, "", "bootout", "system/"+UpdaterLabel)}-// Status reports whether the updater job is loaded.+// Status reports whether the updater schedule is active.func (m UpdaterManager) Status() Status {- status := Status{Label: UpdaterLabel}- if runtime.GOOS != "darwin" {- status.Message = "service status is available only on macOS"+ kind := m.resolvedKind()+ if !m.Supported() {+ label := UpdaterLabel+ if kind == KindSystemd {+ label = UpdaterTimerUnit+ }+ return Status{Label: label, Kind: string(kind), Message: m.UnsupportedReason()}+ }++ if kind == KindSystemd {+ status := Status{Label: UpdaterTimerUnit, Kind: string(KindSystemd)}+ enabledOut, _ := runSystemctlCommand("is-enabled", UpdaterTimerUnit)+ switch strings.TrimSpace(enabledOut) {+ case "enabled", "enabled-runtime", "static":+ status.Loaded = true+ }+ activeOut, _ := runSystemctlCommand("is-active", UpdaterTimerUnit)+ // A timer that is waiting for its next firing reports "active"; systemd does not+ // distinguish waiting from running for timer units.+ status.Running = strings.TrimSpace(activeOut) == "active"+ if status.Running {+ status.Loaded = true+ }+ if !status.Loaded && !status.Running {+ status.Message = "timer not installed"+ }return status}++ status := Status{Label: UpdaterLabel, Kind: string(KindLaunchd)}out, err := runLaunchctlCommand("print", "system/"+UpdaterLabel)if err != nil {status.Message = strings.TrimSpace(out)@@ -86,9 +206,40 @@ func (m UpdaterManager) Status() Status {return status}-// updaterPlist renders the updater LaunchDaemon. It runs at business-hour-// intervals in local time and does not-// RunAtLoad or KeepAlive; each invocation resolves the configured mode.+// updaterServiceUnit is the oneshot job the timer triggers.+func updaterServiceUnit(program string) string {+ return fmt.Sprintf(`[Unit]+Description=Beacon endpoint scheduled update check+Documentation=https://docs.asymptotelabs.ai/cli/endpoint++[Service]+Type=oneshot+ExecStart=%s endpoint update --scheduled+StandardOutput=journal+StandardError=journal+User=root+`, program)+}++// updaterTimerUnit schedules the job at the same business-hour intervals the launchd plist+// uses. Persistent=true is the meaningful addition: systemd will run a missed firing after a+// laptop wakes, whereas launchd's StartCalendarInterval simply skips it.+func updaterTimerUnit() string {+ return fmt.Sprintf(`[Unit]+Description=Beacon endpoint scheduled update check++[Timer]+OnCalendar=*-*-* 09,12,15,18,21:00:00+Persistent=true+Unit=%s++[Install]+WantedBy=timers.target+`, UpdaterServiceUnit)+}++// updaterPlist renders the updater LaunchDaemon. It runs at business-hour intervals in local+// time and does not RunAtLoad or KeepAlive; each invocation resolves the configured mode.func updaterPlist(label, program string) string {return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">diff --git a/cli/beacon/internal/endpoint/service/updater_test.go b/cli/beacon/internal/endpoint/service/updater_test.goindex 42c4cd06..07fdd6cd 100644--- a/cli/beacon/internal/endpoint/service/updater_test.go+++ b/cli/beacon/internal/endpoint/service/updater_test.go@@ -40,20 +40,11 @@ func TestUpdaterPlistContent(t *testing.T) {}func TestUpdaterPlistPath(t *testing.T) {- if got := (UpdaterManager{}).PlistPath(); got != "/Library/LaunchDaemons/com.beacon.endpoint.updater.plist" {+ if got := (UpdaterManager{Kind: KindLaunchd}).UnitPath(); got != "/Library/LaunchDaemons/com.beacon.endpoint.updater.plist" {t.Errorf("PlistPath = %q", got)}}-func TestUpdaterWritePlistNonDarwinContract(t *testing.T) {- if runtime.GOOS == "darwin" {- t.Skip("darwin writes the plist; this asserts the non-darwin contract")- }- if _, err := (UpdaterManager{}).WritePlist("/opt/beacon/bin/beacon"); err == nil {- t.Error("expected error writing updater plist on non-darwin")- }-}-func TestUpdaterLoadDefersReloadForRunningUpdater(t *testing.T) {if runtime.GOOS != "darwin" {t.Skip("launchd updater load is macOS-only")@@ -78,13 +69,13 @@ func TestUpdaterLoadDefersReloadForRunningUpdater(t *testing.T) {startDeferredUpdaterReload = oldDeferred})- if err := (UpdaterManager{}).Load(); err != nil {+ if err := (UpdaterManager{Kind: KindLaunchd}).Load(); err != nil {t.Fatalf("Load returned error: %v", err)}if len(calls) != 1 || calls[0] != "print system/"+UpdaterLabel {t.Fatalf("launchctl calls = %#v, want only status print", calls)}- if deferredPath != (UpdaterManager{}).PlistPath() {+ if deferredPath != (UpdaterManager{Kind: KindLaunchd}).UnitPath() {t.Fatalf("deferred reload path = %q, want updater plist", deferredPath)}}@@ -104,3 +95,60 @@ func TestDeferredUpdaterReloadScriptWaitsForParentExit(t *testing.T) {}}}++func TestUpdaterLaunchdUnsupportedOffDarwin(t *testing.T) {+ if runtime.GOOS == "darwin" {+ t.Skip("launchd is supported here")+ }+ if _, err := (UpdaterManager{Kind: KindLaunchd}).WriteUnit("/opt/beacon/bin/beacon"); err == nil {+ t.Error("launchd updater must not claim success off darwin")+ }+}++// Supervised mode has no scheduler. Refusing is deliberate: installing a timer that silently+// never fires would leave endpoints believing they auto-update when they do not.+func TestUpdaterRefusesSupervisedMode(t *testing.T) {+ m := UpdaterManager{Kind: KindSupervised}+ if m.Supported() {+ t.Fatal("supervised mode has no scheduler and must not report support")+ }+ _, err := m.WriteUnit("/opt/beacon/bin/beacon")+ if err == nil {+ t.Fatal("expected an error rather than a no-op timer")+ }+ if !strings.Contains(err.Error(), "scheduler") {+ t.Errorf("error should explain the missing scheduler, got %v", err)+ }+ if st := m.Status(); st.Loaded || st.Running {+ t.Errorf("supervised updater must not report loaded/running: %#v", st)+ }+}++func TestUpdaterSystemdUnitsPairTimerWithService(t *testing.T) {+ svc := updaterServiceUnit("/opt/beacon/bin/beacon")+ for _, want := range []string{"Type=oneshot", "endpoint update --scheduled"} {+ if !strings.Contains(svc, want) {+ t.Errorf("updater service unit missing %q:\n%s", want, svc)+ }+ }+ timer := updaterTimerUnit()+ for _, want := range []string{+ "OnCalendar=*-*-* 09,12,15,18,21:00:00", // same schedule as the launchd plist+ "Persistent=true", // runs a firing missed while asleep+ "Unit=" + UpdaterServiceUnit,+ "WantedBy=timers.target",+ } {+ if !strings.Contains(timer, want) {+ t.Errorf("updater timer missing %q:\n%s", want, timer)+ }+ }+}++func TestUpdaterUnitPathFollowsBackend(t *testing.T) {+ if got := (UpdaterManager{Kind: KindLaunchd}).UnitPath(); got != "/Library/LaunchDaemons/com.beacon.endpoint.updater.plist" {+ t.Errorf("launchd updater path = %q", got)+ }+ if got := (UpdaterManager{Kind: KindSystemd}).UnitPath(); got != "/etc/systemd/system/"+UpdaterTimerUnit {+ t.Errorf("systemd updater path = %q, want the timer unit", got)+ }+}diff --git a/packaging/linux/smoke-systemd.sh b/packaging/linux/smoke-systemd.shnew file mode 100755index 00000000..63382710--- /dev/null+++ b/packaging/linux/smoke-systemd.sh@@ -0,0 +1,127 @@+#!/bin/sh+# Reproducible systemd smoke test for the Linux endpoint.+#+# systemd must be PID 1 to exercise the real install path, and no Modal sandbox or plain+# container gives you that -- Modal's own init holds PID 1 in both of its lanes. A privileged+# container with cgroups mounted does, so that is what this uses.+#+# Usage:+# sh packaging/linux/smoke-systemd.sh # auto-detects host arch+# BEACON_SMOKE_ARCH=amd64 sh packaging/linux/smoke-systemd.sh+#+# Requires Docker and a Linux beacon binary plus a matching collector:+# cd cli/beacon && make build-linux-$(arch)+set -eu++if [ "$(uname -s)" != "Darwin" ] && [ "$(uname -s)" != "Linux" ]; then+ echo "unsupported host: $(uname -s)" >&2+ exit 1+fi++ROOT_DIR="$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)"+ARCH="${BEACON_SMOKE_ARCH:-}"+if [ -z "$ARCH" ]; then+ case "$(uname -m)" in+ arm64|aarch64) ARCH=arm64 ;;+ x86_64|amd64) ARCH=amd64 ;;+ *) echo "unknown machine $(uname -m); set BEACON_SMOKE_ARCH" >&2; exit 1 ;;+ esac+fi++BEACON_BIN="${BEACON_BIN:-$ROOT_DIR/cli/beacon/beacon-linux-$ARCH}"+COLLECTOR_BIN="${BEACON_COLLECTOR_BIN:-$ROOT_DIR/collector-builder/dist/beacon-otelcol/linux_$ARCH/beacon-otelcol}"++for f in "$BEACON_BIN" "$COLLECTOR_BIN"; do+ if [ ! -x "$f" ]; then+ echo "missing $f" >&2+ echo "build it with: cd cli/beacon && make build-linux-$ARCH" >&2+ exit 1+ fi+done++command -v docker >/dev/null 2>&1 || { echo "docker is required" >&2; exit 1; }++CONTAINER="${BEACON_SMOKE_CONTAINER:-beacon-systemd-smoke}"+IMAGE="${BEACON_SMOKE_IMAGE:-beacon-systemd-smoke}"+cleanup() { docker rm -f "$CONTAINER" >/dev/null 2>&1 || true; }+trap cleanup EXIT INT TERM+cleanup++echo "building $IMAGE ($ARCH)"+docker build -q -t "$IMAGE" - >/dev/null <<'DOCKERFILE'+FROM ubuntu:24.04+RUN apt-get update -qq && apt-get install -y -qq systemd systemd-sysv dbus curl ca-certificates iproute2 >/dev/null+STOPSIGNAL SIGRTMIN+3+CMD ["/sbin/init"]+DOCKERFILE++echo "starting systemd container"+docker run -d --name "$CONTAINER" --privileged --cgroupns=host \+ -v /sys/fs/cgroup:/sys/fs/cgroup:rw --tmpfs /run --tmpfs /run/lock \+ -v "$BEACON_BIN":/beacon/beacon:ro \+ -v "$COLLECTOR_BIN":/beacon/beacon-otelcol:ro \+ "$IMAGE" >/dev/null++i=0+while [ "$i" -lt 30 ]; do+ state="$(docker exec "$CONTAINER" systemctl is-system-running 2>/dev/null || true)"+ case "$state" in running|degraded) break ;; esac+ i=$((i+1)); sleep 1+done++fail() { echo "FAIL: $1" >&2; exit 1; }+in_container() { docker exec "$CONTAINER" sh -c "$1"; }++[ "$(in_container 'cat /proc/1/comm')" = "systemd" ] || fail "systemd is not PID 1"+echo "ok: systemd is PID 1"++in_container '/beacon/beacon endpoint install --system --harness claude --collector /beacon/beacon-otelcol' >/dev/null \+ || fail "endpoint install failed"+echo "ok: endpoint install --system succeeded"++in_container 'test -f /etc/beacon/endpoint/config.json' || fail "config not written to the FHS path"+in_container 'test -f /etc/systemd/system/beacon-collector.service' || fail "systemd unit not written"+echo "ok: config and unit written"++# These are the launchd semantics the unit has to preserve.+for want in 'Restart=always' 'WantedBy=multi-user.target' 'StandardOutput=journal'; do+ in_container "grep -q '$want' /etc/systemd/system/beacon-collector.service" \+ || fail "unit is missing $want"+done+echo "ok: unit preserves KeepAlive/RunAtLoad semantics"++[ "$(in_container 'systemctl is-enabled beacon-collector.service' || true)" = "enabled" ] \+ || fail "unit is not enabled"+[ "$(in_container 'systemctl is-active beacon-collector.service' || true)" = "active" ] \+ || fail "unit is not active"+echo "ok: unit enabled and active"++in_container 'curl -sf -o /dev/null --max-time 10 http://127.0.0.1:13133/' \+ || fail "collector health endpoint not reachable"+echo "ok: collector is listening and healthy"++in_container '/beacon/beacon endpoint status --system' | grep -q 'running=true' \+ || fail "status does not report the service running"+echo "ok: status reports the service running"++# Restart=always is the KeepAlive equivalent; verify it actually restarts.+before="$(in_container 'systemctl show -p MainPID --value beacon-collector.service')"+in_container "kill -9 $before" >/dev/null 2>&1 || true+sleep 8+after="$(in_container 'systemctl show -p MainPID --value beacon-collector.service')"+[ -n "$after" ] && [ "$after" != "0" ] && [ "$after" != "$before" ] \+ || fail "Restart=always did not restart the collector (before=$before after=$after)"+echo "ok: Restart=always restarted the collector ($before -> $after)"++in_container '/beacon/beacon endpoint doctor --system' >/dev/null 2>&1 \+ || echo "note: doctor reported warnings (expected: no agent session ran here)"++in_container '/beacon/beacon endpoint uninstall --system' >/dev/null || fail "uninstall failed"+in_container 'test ! -f /etc/systemd/system/beacon-collector.service' || fail "unit file survived uninstall"+in_container 'test ! -f /etc/beacon/endpoint/config.json' || fail "config survived uninstall"+[ "$(in_container 'systemctl is-enabled beacon-collector.service 2>&1' || true)" = "not-found" ] \+ || fail "unit still known to systemd after uninstall"+echo "ok: uninstall left nothing behind"++echo+echo "systemd endpoint smoke test passed"