diff --git a/agents.md b/agents.md index cdf855dd4..51baf6f89 100644 --- a/agents.md +++ b/agents.md @@ -88,6 +88,7 @@ An extension bundles plugins: context (system instructions), tool (model tools + ### `cli/` — the terminal (Go) - **`cli/cmd/albedo`** — production wiring, project-root discovery, and final error reporting +- **`cli/internal/loginservice`** — native user-service definitions, publication and manager calls - **`cli/internal/cli`** — Cobra constructors, strict argument validation, and command rendering - **`cli/internal/app`** — typed session, prompt, model, and daemon workflows with lazy connections - **`cli/internal/acp`**. The Agent Client Protocol adapter behind `albedo acp` owns stdio JSON-RPC, prompt and session state, and history replay. See `robot-docs/acp.md`. diff --git a/cli/cmd/albedo/daemon_service.go b/cli/cmd/albedo/daemon_service.go new file mode 100644 index 000000000..da02aaff3 --- /dev/null +++ b/cli/cmd/albedo/daemon_service.go @@ -0,0 +1,353 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "maps" + "os" + "runtime" + "strconv" + "time" + + "albedo/cli/internal/daemon" + "albedo/cli/internal/localdaemon" + "albedo/cli/internal/loginservice" +) + +func (connector *connector) Serve(ctx context.Context) error { + return localdaemon.Serve(ctx, connector.options) +} + +func (connector *connector) Status(ctx context.Context) (localdaemon.ServiceStatus, error) { + view, err := localdaemon.ObserveService(ctx, connector.options.HomeDir) + if err != nil { + return localdaemon.ServiceStatus{}, err + } + mainPID, _ := strconv.Atoi(view.Observation.Properties["MainPID"]) + pid := 0 + if view.Discovery.Kind == localdaemon.Running || view.Discovery.Kind == localdaemon.Stopping { + pid = view.Discovery.Snapshot.Pid + } + return localdaemon.ServiceStatus{Unit: view.Unit.Name(), Class: view.Class, State: view.Observation.Properties["ActiveState"], Pid: pid, MainPID: mainPID, Problem: view.Problem}, nil +} + +func (connector *connector) startService(ctx context.Context) (*daemon.Connection, error) { + lock, err := localdaemon.LockLauncher(ctx, connector.options.HomeDir) + if err != nil { + return nil, err + } + defer lock.Close() + view, err := localdaemon.ObserveService(ctx, connector.options.HomeDir) + if err != nil { + return nil, err + } + if view.Class == localdaemon.ManagedService { + return daemon.Attach(ctx, view.Discovery.Snapshot, func(ctx context.Context) (daemon.ConnectionSnapshot, error) { + return localdaemon.Rediscover(ctx, connector.options.HomeDir) + }) + } + if view.Class == localdaemon.NoService || view.Class == localdaemon.StandaloneBeside { + return nil, &localdaemon.ServicePolicyChanged{} + } + if view.Class != localdaemon.ServiceIdle && view.Class != localdaemon.ServiceTransition { + return nil, view.MutationError() + } + if view.Class == localdaemon.ServiceIdle { + if view.Observation.Properties["ActiveState"] == "failed" { + if err = view.Unit.Run(ctx, "reset-failed"); err != nil { + return nil, err + } + } + if err = view.Unit.Run(ctx, "start"); err != nil { + return nil, fmt.Errorf("start may have been submitted: %w; inspect with albedo daemon status", err) + } + } + return localdaemon.AwaitManaged(ctx, connector.options.HomeDir, view.Discovery.Snapshot) +} + +func (connector *connector) Stop(parent context.Context, kernels bool) error { + ctx, cancel := context.WithTimeout(parent, 5*time.Minute) + defer cancel() + lock, err := localdaemon.LockLauncher(ctx, connector.options.HomeDir) + if err != nil { + return err + } + defer lock.Close() + view, err := localdaemon.ObserveService(ctx, connector.options.HomeDir) + if err != nil { + return err + } + for view.Class == localdaemon.ServiceTransition { + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(100 * time.Millisecond): + } + view, err = localdaemon.ObserveService(ctx, connector.options.HomeDir) + if err != nil { + return err + } + } + return connector.stopObserved(ctx, view, kernels) +} + +func (connector *connector) stopObserved(ctx context.Context, view localdaemon.ServiceView, kernels bool) error { + if view.Class != localdaemon.NoService && view.Class != localdaemon.StandaloneBeside && view.Class != localdaemon.ManagedService && view.Class != localdaemon.ServiceIdle { + return view.MutationError() + } + if view.Class == localdaemon.ServiceIdle || view.Discovery.Kind == localdaemon.Absent || view.Discovery.Kind == localdaemon.Stale { + return nil + } + if view.Discovery.Kind == localdaemon.Stopping { + return daemon.WaitForExit(ctx, view.Discovery.Snapshot.Pid) + } + connection, err := daemon.Attach(ctx, view.Discovery.Snapshot, nil) + if err != nil { + return err + } + defer connection.HTTPClient().CloseIdleConnections() + if err = daemon.StopDaemon(ctx, connection, kernels); err != nil { + return err + } + if err = daemon.WaitForExit(ctx, view.Discovery.Snapshot.Pid); err != nil { + return err + } + if view.Class != localdaemon.ManagedService { + return nil + } + return connector.awaitInactive(ctx, view) +} + +func (connector *connector) awaitInactive(parent context.Context, view localdaemon.ServiceView) error { + ctx, cancel := context.WithTimeout(parent, 10*time.Second) + defer cancel() + for { + observation, err := view.Unit.Observe(ctx) + if err != nil { + return err + } + p := observation.Properties + if observation.File != "owned" || observation.Problem != "" || p["NeedDaemonReload"] != "no" { + return errors.New("service contract changed during shutdown; inspect with albedo daemon status") + } + if id := p["InvocationID"]; id != "" && id != view.Observation.Properties["InvocationID"] { + return errors.New("service invocation changed during shutdown; replacement left untouched") + } + if p["ActiveState"] == "inactive" && p["MainPID"] == "0" && p["Job"] == "" { + return nil + } + if p["ActiveState"] == "failed" { + return fmt.Errorf("service failed during shutdown: %s, status %s", p["Result"], p["ExecMainStatus"]) + } + if p["SubState"] == "auto-restart" { + return errors.New("service restarted after shutdown; inspect with albedo daemon status") + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(100 * time.Millisecond): + } + } +} + +func (connector *connector) Install(parent context.Context) (string, error) { + if runtime.GOOS != "linux" { + return "", errors.New("daemon service installation currently requires Linux systemd user services") + } + if err := localdaemon.ValidateServiceLauncher(connector.options); err != nil { + return "", err + } + if _, err := localdaemon.LocalCommand(parent, connector.options); err != nil { + return "", err + } + ctx, cancel := context.WithTimeout(parent, 5*time.Minute) + defer cancel() + lock, err := localdaemon.LockLauncher(ctx, connector.options.HomeDir) + if err != nil { + return "", err + } + defer lock.Close() + view, err := localdaemon.ObserveService(ctx, connector.options.HomeDir) + if err != nil { + return "", err + } + if !view.Observation.Available { + return "", errors.New("systemd user manager is unavailable") + } + if (view.Discovery.Kind == localdaemon.Absent || view.Discovery.Kind == localdaemon.Stale) && localdaemon.HomeHeld(connector.options.HomeDir) { + return "", errors.New("storage is held by another daemon or maintenance command; nothing installed") + } + observation := view.Observation + installationClass := view.Class + if observation.File == "owned" && observation.Problem == "" && observation.Properties["NeedDaemonReload"] == "yes" { + loaded := observation + loaded.Properties = maps.Clone(observation.Properties) + loaded.Properties["NeedDaemonReload"] = "no" + installationClass = localdaemon.ClassifyService(loaded, view.Discovery) + } + allowed := installationClass == localdaemon.NoService || installationClass == localdaemon.ManagedService || installationClass == localdaemon.ServiceIdle || installationClass == localdaemon.StandaloneBeside || installationClass == localdaemon.UnloadedService + if !allowed { + return "", view.MutationError() + } + if view.Class == localdaemon.NoService && (view.Discovery.Kind == localdaemon.Running || view.Discovery.Kind == localdaemon.Stopping) { + return "", errors.New("nothing installed: stop the standalone daemon with albedo daemon --stop, then run albedo daemon install") + } + definition, err := view.Unit.Capture() + if err != nil { + return "", err + } + data, err := view.Unit.Render(definition) + if err != nil { + return "", err + } + info := observation.Info + changed := !bytes.Equal(observation.Data, data) + if changed { + info, err = view.Unit.Publish(data) + if err != nil { + return "", fmt.Errorf("unit publication may have completed: %w; inspect with albedo daemon status", err) + } + } + attemptedStartOrEnable := false + fail := func(cause error) (string, error) { + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cleanupCancel() + after, observeErr := view.Unit.Observe(cleanupCtx) + details := "configuration left in place; inspect with albedo daemon status" + if observeErr == nil { + details = fmt.Sprintf("configuration left in place: state=%s main_pid=%s enablement=%s; inspect with albedo daemon status", after.Properties["ActiveState"], after.Properties["MainPID"], after.Properties["UnitFileState"]) + } + unchangedProcess := after.Properties["MainPID"] == "0" && observation.Properties["MainPID"] == "0" + if observation.Properties["MainPID"] != "0" && observation.Properties["InvocationID"] != "" { + unchangedProcess = after.Properties["MainPID"] == observation.Properties["MainPID"] && after.Properties["InvocationID"] == observation.Properties["InvocationID"] + } + if !attemptedStartOrEnable && observeErr == nil && unchangedProcess && after.Properties["Job"] == "" && view.Unit.Unchanged(info, data) && changed { + var restoreErr error + if observation.Info == nil { + restoreErr = os.Remove(view.Unit.Path()) + } else { + _, restoreErr = view.Unit.Publish(observation.Data) + } + if restoreErr == nil { + restoreErr = view.Unit.Reload(cleanupCtx) + } + if restoreErr == nil { + details = "previous configuration restored" + } else { + details = "configuration cleanup incomplete: " + restoreErr.Error() + } + } + if observeErr != nil { + details += "; manager state could not be observed: " + observeErr.Error() + } + return "", fmt.Errorf("service installation incomplete: %w; %s", cause, details) + } + if changed || observation.Properties["NeedDaemonReload"] != "no" { + if err = view.Unit.Reload(ctx); err != nil { + return fail(err) + } + } + reloaded, err := localdaemon.ObserveService(ctx, connector.options.HomeDir) + if err != nil { + return fail(err) + } + after := reloaded.Observation + if reloaded.Class == localdaemon.UnknownService { + return fail(reloaded.MutationError()) + } + if after.File != "owned" || after.Problem != "" || after.Properties["LoadState"] != "loaded" || after.Properties["NeedDaemonReload"] != "no" { + if after.Properties["LoadState"] != "loaded" { + return fail(fmt.Errorf("user manager did not load %s; check its unit search path", view.Unit.Path())) + } + return fail(fmt.Errorf("loaded service contract was not accepted: %s", after.Problem)) + } + class := reloaded.Class + if class != localdaemon.ManagedService && class != localdaemon.ServiceIdle && class != localdaemon.StandaloneBeside { + return fail(errors.New("service state changed during installation; inspect with albedo daemon status")) + } + newInstallation := view.Class == localdaemon.NoService || view.Class == localdaemon.UnloadedService + running := reloaded.Discovery.Kind == localdaemon.Running + if !running && newInstallation { + attemptedStartOrEnable = true + if after.Properties["ActiveState"] == "failed" { + if err = view.Unit.Run(ctx, "reset-failed"); err != nil { + return fail(err) + } + } + if err = view.Unit.Run(ctx, "start"); err != nil { + return fail(err) + } + connection, readyErr := localdaemon.AwaitManaged(ctx, connector.options.HomeDir, view.Discovery.Snapshot) + if readyErr != nil { + return fail(readyErr) + } + connection.HTTPClient().CloseIdleConnections() + } + if class != localdaemon.ManagedService && after.Properties["UnitFileState"] != "enabled" { + attemptedStartOrEnable = true + if err = view.Unit.Run(ctx, "enable"); err != nil { + return fail(err) + } + } + if running { + return "service definition refreshed without restarting the daemon; stop it with albedo daemon --stop, then run albedo", nil + } + if !newInstallation { + return "service definition refreshed; the next albedo starts it", nil + } + return "installed " + view.Unit.Name() + "; starts with the user manager or albedo\n" + loginservice.LingerNote(ctx), nil +} + +func (connector *connector) Uninstall(parent context.Context) (string, error) { + if runtime.GOOS != "linux" { + return "", errors.New("daemon service installation currently requires Linux") + } + ctx, cancel := context.WithTimeout(parent, 5*time.Minute) + defer cancel() + lock, err := localdaemon.LockLauncher(ctx, connector.options.HomeDir) + if err != nil { + return "", err + } + defer lock.Close() + view, err := localdaemon.ObserveService(ctx, connector.options.HomeDir) + if err != nil { + return "", err + } + if view.Class == localdaemon.NoService { + return "no daemon service is installed", nil + } + if view.Class != localdaemon.ManagedService && view.Class != localdaemon.ServiceIdle && view.Class != localdaemon.StandaloneBeside && view.Class != localdaemon.UnloadedService { + return "", view.MutationError() + } + if view.Class == localdaemon.ManagedService { + if err = connector.stopObserved(ctx, view, false); err != nil { + return "", err + } + } + after, err := view.Unit.Observe(ctx) + if err != nil { + return "", err + } + if after.Problem != "" || after.File != "owned" || after.Properties["MainPID"] != "0" || after.Properties["Job"] != "" || after.Properties["NeedDaemonReload"] == "yes" || !view.Unit.Unchanged(view.Observation.Info, view.Observation.Data) { + return "", errors.New("service changed during uninstall; registration left intact") + } + if err = view.Unit.Run(ctx, "disable"); err != nil { + return "", fmt.Errorf("disable may have partially applied: %w; inspect with albedo daemon status", err) + } + after, err = view.Unit.Observe(ctx) + if err != nil { + return "", err + } + if after.Problem != "" || after.File != "owned" || after.Properties["NeedDaemonReload"] == "yes" || after.Properties["MainPID"] != "0" || after.Properties["Job"] != "" || !view.Unit.Unchanged(view.Observation.Info, view.Observation.Data) { + return "", errors.New("service changed after disable; file left intact") + } + if err = os.Remove(view.Unit.Path()); err != nil { + return "", err + } + if err = view.Unit.Reload(ctx); err != nil { + return "", fmt.Errorf("service file removed but reload failed: %w", err) + } + return "removed daemon service; kernels are kept and the next albedo starts standalone", nil +} diff --git a/cli/cmd/albedo/lifecycle.go b/cli/cmd/albedo/lifecycle.go index 73e5465bd..afb442a22 100644 --- a/cli/cmd/albedo/lifecycle.go +++ b/cli/cmd/albedo/lifecycle.go @@ -3,7 +3,9 @@ package main import ( "context" "errors" + "fmt" "sync" + "time" "albedo/cli/internal/daemon" "albedo/cli/internal/localdaemon" @@ -40,12 +42,61 @@ func (connector *connector) Connect(ctx context.Context) (*daemon.Connection, er if connector.chosen != nil { return connector.chosen, nil } - found, err := localdaemon.Discover(ctx, connector.options.HomeDir) - if err != nil { - if _, compatibleFailure := errors.AsType[*daemon.CompatibilityError](err); !compatibleFailure || found.Kind != localdaemon.Running { + parent := ctx + ctx, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + for { + view, err := localdaemon.ObserveService(ctx, connector.options.HomeDir) + if err != nil { return nil, err } + if view.Class == localdaemon.NoService { + connection, directErr := connector.connectDirect(parent, view.Discovery) + if _, changed := errors.AsType[*localdaemon.ServicePolicyChanged](directErr); changed { + continue + } + return connection, directErr + } + if view.Discovery.Kind == localdaemon.Running { + if view.Class != localdaemon.ManagedService { + reason := view.Problem + if reason == "" { + reason = "service registration does not match this daemon" + } + fmt.Fprintf(connector.term.Err, "daemon service %s: %s; attaching without restarting the daemon\n", view.Unit.Name(), reason) + } else if !connector.acpMode && daemon.BuildMismatch(daemon.BuildIdentity{Build: view.Discovery.Snapshot.Build, Digest: view.Discovery.Snapshot.Digest}, selectedBuild(connector.options.ProjectRoot)) { + fmt.Fprintf(connector.term.Err, "daemon service %s runs a different build; the build its service would start may differ from this CLI. Restart with albedo daemon --stop, then albedo.\n", view.Unit.Name()) + } + connector.chosen, err = checkedConnection(daemon.Attach(ctx, view.Discovery.Snapshot, func(ctx context.Context) (daemon.ConnectionSnapshot, error) { + return localdaemon.Rediscover(ctx, connector.options.HomeDir) + })) + return connector.chosen, err + } + if view.Class == localdaemon.ServiceTransition { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(100 * time.Millisecond): + continue + } + } + if view.Class != localdaemon.ServiceIdle { + return nil, view.MutationError() + } + connection, err := connector.startService(ctx) + if _, changed := errors.AsType[*localdaemon.ServicePolicyChanged](err); changed { + continue + } + if err != nil { + return nil, err + } + connector.chosen, err = checkedConnection(connection, nil) + return connector.chosen, err } +} + +func (connector *connector) connectDirect(ctx context.Context, found localdaemon.Discovery) (*daemon.Connection, error) { + var err error if found.Kind != localdaemon.Running { connector.chosen, err = checkedConnection(localdaemon.Launch(ctx, connector.options)) return connector.chosen, err diff --git a/cli/cmd/albedo/main.go b/cli/cmd/albedo/main.go index 2c15564aa..63cc13775 100644 --- a/cli/cmd/albedo/main.go +++ b/cli/cmd/albedo/main.go @@ -63,5 +63,5 @@ func run(args []string) error { if err != nil { workspace = "." } - return cli.Execute(ctx, args, cli.Dependencies{Application: application, Storage: store, Terminal: term, Workspace: workspace, ProjectRoot: options.ProjectRoot}, streams) + return cli.Execute(ctx, args, cli.Dependencies{Lifecycle: connection, Application: application, Storage: store, Terminal: term, Workspace: workspace, ProjectRoot: options.ProjectRoot}, streams) } diff --git a/cli/internal/cli/login_service.go b/cli/internal/cli/login_service.go index 2dfdfda71..0f7c191fa 100644 --- a/cli/internal/cli/login_service.go +++ b/cli/internal/cli/login_service.go @@ -1,214 +1,18 @@ package cli import ( - "bytes" - "context" - "crypto/sha256" - "encoding/xml" - "errors" + "albedo/cli/internal/config" + "albedo/cli/internal/loginservice" "fmt" "os" - "os/exec" "path/filepath" - "runtime" - "strconv" - "strings" "syscall" - "time" - - "albedo/cli/internal/config" ) -type loginService struct{ role, path, name, domain string } +type loginService = loginservice.Service func userLoginService(role string) (loginService, error) { - home, err := os.UserHomeDir() - if err != nil { - return loginService{}, err - } - sum := sha256.Sum256([]byte(config.HomeDir())) - name := fmt.Sprintf("systems.albedo.%s-%x", role, sum[:8]) - switch runtime.GOOS { - case "darwin": - return loginService{role, filepath.Join(home, "Library", "LaunchAgents", name+".plist"), name, "gui/" + strconv.Itoa(os.Getuid())}, nil - case "linux": - root := os.Getenv("XDG_CONFIG_HOME") - if root == "" { - root = filepath.Join(home, ".config") - } - return loginService{role, filepath.Join(root, "systemd", "user", name+".service"), name + ".service", ""}, nil - default: - return loginService{}, errors.New("saved services require macOS or Linux") - } -} - -func (s loginService) installed() (bool, error) { - _, err := os.Stat(s.path) - if os.IsNotExist(err) { - return false, nil - } - return err == nil, err -} - -func (s loginService) manager(ctx context.Context, args ...string) (string, error) { - name, override := "systemctl", "ALBEDO_SYSTEMCTL" - if runtime.GOOS == "darwin" { - name, override = "launchctl", "ALBEDO_LAUNCHCTL" - } else { - args = append([]string{"--user"}, args...) - } - if value := os.Getenv(override); value != "" { - name = value - } - ctx, cancel := context.WithTimeout(ctx, 15*time.Second) - defer cancel() - output, err := exec.CommandContext(ctx, name, args...).CombinedOutput() - if err != nil { - return string(output), fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(output))) - } - return string(output), nil -} - -func (s loginService) start(ctx context.Context) error { - if runtime.GOOS == "darwin" { - if _, err := s.manager(ctx, "print", s.domain+"/"+s.name); err != nil { - _, err = s.manager(ctx, "bootstrap", s.domain, s.path) - return err - } - _, err := s.manager(ctx, "kickstart", s.domain+"/"+s.name) - return err - } - _, err := s.manager(ctx, "start", s.name) - return err -} - -func (s loginService) stop(ctx context.Context) error { - if runtime.GOOS == "darwin" { - if _, err := s.manager(ctx, "print", s.domain+"/"+s.name); err != nil { - var exit *exec.ExitError - if errors.As(err, &exit) && exit.ExitCode() == 113 { - return nil - } - return err - } - _, err := s.manager(ctx, "bootout", s.domain+"/"+s.name) - return err - } - _, err := s.manager(ctx, "stop", s.name) - return err -} - -func (s loginService) remove(ctx context.Context) error { - if err := s.stop(ctx); err != nil { - return err - } - if runtime.GOOS == "linux" { - if _, err := s.manager(ctx, "disable", s.name); err != nil { - return err - } - } - if err := os.Remove(s.path); err != nil && !os.IsNotExist(err) { - return err - } - if runtime.GOOS == "linux" { - _, err := s.manager(ctx, "daemon-reload") - return err - } - return nil -} - -// serviceExecutable preserves moving package links instead of pinning their targets. -func serviceExecutable() (string, error) { - if path, err := exec.LookPath(os.Args[0]); err == nil { - return filepath.Abs(path) - } - return os.Executable() -} - -func xmlText(text string) string { - var out bytes.Buffer - _ = xml.EscapeText(&out, []byte(text)) - return out.String() -} - -func unitQuote(text string) string { - return strconv.Quote(strings.ReplaceAll(text, "%", "%%")) -} - -func (s loginService) install(ctx context.Context, options ...string) error { - executable, err := serviceExecutable() - if err != nil { - return err - } - args := append([]string{executable, s.role, "--foreground", "--service"}, options...) - environment := map[string]string{"ALBEDO_HOME": config.HomeDir()} - for _, key := range []string{"PATH", "ALBEDO_ROOT", "ALBEDO_DAEMON", "ALBEDO_WEB_DIST"} { - if value := os.Getenv(key); value != "" { - // Package wrappers supply their current store defaults at each start. - if (key == "ALBEDO_DAEMON" || key == "ALBEDO_WEB_DIST") && strings.HasPrefix(value, "/nix/store/") { - continue - } - environment[key] = value - } - } - logPath := filepath.Join(config.HomeDir(), s.role+".log") - var data strings.Builder - if runtime.GOOS == "darwin" { - fmt.Fprint(&data, ` - - -Label`, xmlText(s.name), ` -ProgramArguments`) - for _, arg := range args { - fmt.Fprint(&data, "", xmlText(arg), "") - } - data.WriteString("EnvironmentVariables") - for key, value := range environment { - fmt.Fprint(&data, "", xmlText(key), "", xmlText(value), "") - } - fmt.Fprint(&data, ` -RunAtLoad -KeepAlive -StandardOutPath`, xmlText(logPath), ` -StandardErrorPath`, xmlText(logPath), ` - -`) - } else { - fmt.Fprint(&data, "[Unit]\nDescription=albedo ", s.role, "\n\n[Service]\nType=simple\nExecStart=") - for _, arg := range args { - fmt.Fprint(&data, unitQuote(strings.ReplaceAll(arg, "$", "$$")), " ") - } - data.WriteString("\nRestart=always\nRestartSec=3\n") - for key, value := range environment { - fmt.Fprintln(&data, "Environment="+unitQuote(key+"="+value)) - } - fmt.Fprint(&data, "StandardOutput=", unitQuote("append:"+logPath), "\nStandardError=", unitQuote("append:"+logPath), "\n\n[Install]\nWantedBy=default.target\n") - } - if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil { - return err - } - if err := os.WriteFile(s.path, []byte(data.String()), 0o600); err != nil { - return err - } - if runtime.GOOS == "linux" { - if _, err := s.manager(ctx, "daemon-reload"); err != nil { - return err - } - _, err := s.manager(ctx, "enable", "--now", s.name) - return err - } - return s.start(ctx) -} - -func serviceLingerNote(ctx context.Context) string { - if runtime.GOOS != "linux" { - return "" - } - output, err := exec.CommandContext(ctx, "loginctl", "show-user", strconv.Itoa(os.Getuid()), "--property=Linger", "--value").Output() - if err != nil || strings.TrimSpace(string(output)) != "yes" { - return "to keep it running after logout and start it at boot, run: loginctl enable-linger\n" - } - return "" + return loginservice.For(role, config.HomeDir()) } // serverLock holds a per-home listener lock until the foreground server exits. diff --git a/cli/internal/cli/proxy_background.go b/cli/internal/cli/proxy_background.go index 41008ec49..4e134e587 100644 --- a/cli/internal/cli/proxy_background.go +++ b/cli/internal/cli/proxy_background.go @@ -65,7 +65,7 @@ func backgroundProxy(cmd *cobra.Command, deps Dependencies, options webui.Option return serviceErr } if serviceErr == nil { - installed, err := service.installed() + installed, err := service.Installed() if err != nil { return err } diff --git a/cli/internal/cli/proxy_service.go b/cli/internal/cli/proxy_service.go index ed0dd18e6..f0921e3e9 100644 --- a/cli/internal/cli/proxy_service.go +++ b/cli/internal/cli/proxy_service.go @@ -1,6 +1,7 @@ package cli import ( + "albedo/cli/internal/loginservice" "context" "errors" "fmt" @@ -18,7 +19,7 @@ import ( func managedProxy(cmd *cobra.Command, deps Dependencies, service loginService, options webui.Options, quiet, rotate, stop, save, installed bool) error { ctx, out := cmd.Context(), cmd.OutOrStdout() if stop { - if err := service.stop(ctx); err != nil { + if err := service.Stop(ctx); err != nil { return err } fmt.Fprintln(out, "stopped albedo proxy. it will return at the next login; forget it with: albedo proxy --save") @@ -52,7 +53,7 @@ func managedProxy(cmd *cobra.Command, deps Dependencies, service loginService, o return fmt.Errorf("cannot save the allowed networks: %w", err) } if installed { - if err := service.remove(ctx); err != nil { + if err := service.Remove(ctx); err != nil { return err } } else if alive { @@ -74,10 +75,10 @@ func managedProxy(cmd *cobra.Command, deps Dependencies, service loginService, o if quiet { args = append(args, "--quiet") } - if err = service.install(ctx, args...); err != nil { + if err = service.Install(ctx, args...); err != nil { return err } - } else if err = service.start(ctx); err != nil { + } else if err = service.Start(ctx); err != nil { return err } ctx, cancel := context.WithTimeout(ctx, webGrace) @@ -96,7 +97,7 @@ func managedProxy(cmd *cobra.Command, deps Dependencies, service loginService, o } } fmt.Fprintln(out, "albedo proxy is running through its login service.") - fmt.Fprint(out, serviceLingerNote(ctx)) + fmt.Fprint(out, loginservice.LingerNote(ctx)) fmt.Fprint(out, "stop it with: albedo proxy --stop\n\n") manifest.Providers, manifest.Unavailable = prepared.Providers, prepared.Unavailable printProxySummary(out, key, manifest) diff --git a/cli/internal/cli/root.go b/cli/internal/cli/root.go index 40aba9187..2cc225091 100644 --- a/cli/internal/cli/root.go +++ b/cli/internal/cli/root.go @@ -17,12 +17,22 @@ import ( "albedo/cli/internal/app" "albedo/cli/internal/daemon" + "albedo/cli/internal/localdaemon" "albedo/cli/internal/storage" "albedo/cli/internal/terminal" "github.com/spf13/cobra" ) +type DaemonLifecycle interface { + Install(context.Context) (string, error) + Uninstall(context.Context) (string, error) + Status(context.Context) (localdaemon.ServiceStatus, error) + Stop(context.Context, bool) error + Serve(context.Context) error +} + type Dependencies struct { + Lifecycle DaemonLifecycle Application *app.Service Storage *storage.Service Terminal *terminal.Service @@ -327,11 +337,20 @@ func newStop(deps Dependencies) *cobra.Command { }} } func newDaemon(deps Dependencies) *cobra.Command { - var stop, kernels bool - command := &cobra.Command{Use: "daemon", Short: "start Albedo in the background or stop it", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { + var stop, kernels, serve bool + command := &cobra.Command{Use: "daemon", Short: "start, stop, or manage the daemon user service", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { + if serve { + if stop || kernels || deps.Lifecycle == nil { + return errors.New("--serve requires the daemon service entry point without stop flags") + } + return deps.Lifecycle.Serve(cmd.Context()) + } if kernels && !stop { return fmt.Errorf("--kernels goes with --stop") } + if stop && deps.Lifecycle != nil { + return deps.Lifecycle.Stop(cmd.Context(), kernels) + } if stop { return deps.Application.StopDaemon(cmd.Context(), kernels) } @@ -344,8 +363,98 @@ func newDaemon(deps Dependencies) *cobra.Command { }} command.Flags().BoolVar(&stop, "stop", false, "stop the running daemon and wait for it to exit") command.Flags().BoolVar(&kernels, "kernels", false, "with --stop, end every Python kernel too instead of leaving them for the next daemon: variables are saved and restored, running jobs end") + command.Flags().BoolVar(&serve, "serve", false, "run the daemon in this process") + _ = command.Flags().MarkHidden("serve") + command.AddCommand(newDaemonInstall(deps), newDaemonUninstall(deps), newDaemonStatus(deps)) + return command +} + +func newDaemonInstall(deps Dependencies) *cobra.Command { + return &cobra.Command{Use: "install", Short: "install or refresh the systemd user service", Long: "Install and start a daemon user service on Linux. Requires a packaged daemon selected by ALBEDO_DAEMON; checkout and AppImage launchers are unsupported. A refresh leaves the running daemon unchanged and a stopped service stopped.", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { + if deps.Lifecycle == nil { + return errors.New("daemon service controls are unavailable") + } + message, err := deps.Lifecycle.Install(cmd.Context()) + if err != nil { + return err + } + _, err = fmt.Fprintln(cmd.OutOrStdout(), message) + return err + }} +} + +func newDaemonUninstall(deps Dependencies) *cobra.Command { + return &cobra.Command{Use: "uninstall", Short: "remove the user service, keeping kernels for reconnection", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { + if deps.Lifecycle == nil { + return errors.New("daemon service controls are unavailable") + } + message, err := deps.Lifecycle.Uninstall(cmd.Context()) + if err != nil { + return err + } + _, err = fmt.Fprintln(cmd.OutOrStdout(), message) + return err + }} +} + +func newDaemonStatus(deps Dependencies) *cobra.Command { + var jsonOutput bool + command := &cobra.Command{Use: "status", Short: "show the daemon and user service status", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { + if deps.Lifecycle == nil { + return errors.New("daemon service controls are unavailable") + } + status, err := deps.Lifecycle.Status(cmd.Context()) + if err != nil { + return err + } + if jsonOutput { + return writeJSON(cmd.OutOrStdout(), status, false) + } + var output strings.Builder + if status.Pid > 0 { + fmt.Fprintf(&output, "daemon: running, pid %d\n", status.Pid) + } else { + output.WriteString("daemon: not running\n") + } + description := "" + switch status.Class { + case localdaemon.NoService: + description = "not installed" + if status.Unit == "" { + description = "not available on this platform" + } + case localdaemon.ManagedService: + description = "running under systemd" + case localdaemon.ServiceIdle: + description = "installed, stopped" + if status.State == "failed" { + description = "failed" + } + case localdaemon.StandaloneBeside: + description = "installed; daemon is running independently" + case localdaemon.ServiceTransition: + description = "starting or stopping" + case localdaemon.UnsafeService: + description = "configuration or daemon identity is unsupported" + case localdaemon.UnloadedService: + description = "installed, not loaded by systemd" + case localdaemon.UnknownService: + description = "systemd user manager is unavailable" + } + fmt.Fprintln(&output, "service: "+description) + if status.Class != localdaemon.NoService && status.Unit != "" { + fmt.Fprintln(&output, "unit: "+status.Unit) + } + if status.Problem != "" { + fmt.Fprintln(&output, status.Problem) + } + _, err = fmt.Fprint(cmd.OutOrStdout(), output.String()) + return err + }} + command.Flags().BoolVar(&jsonOutput, "json", false, "print service status as JSON") return command } + func newLogin(deps Dependencies) *cobra.Command { return &cobra.Command{Use: "login [name]", Short: "set up a model provider in a terminal", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if !deps.Terminal.Capable { diff --git a/cli/internal/cli/web_background.go b/cli/internal/cli/web_background.go index a96d875d8..d4999b73a 100644 --- a/cli/internal/cli/web_background.go +++ b/cli/internal/cli/web_background.go @@ -28,7 +28,7 @@ func backgroundWeb(cmd *cobra.Command, deps Dependencies, options webui.Options, return serviceErr } if serviceErr == nil { - installed, err := service.installed() + installed, err := service.Installed() if err != nil { return err } diff --git a/cli/internal/cli/web_service.go b/cli/internal/cli/web_service.go index dd92b9b10..55ca91b83 100644 --- a/cli/internal/cli/web_service.go +++ b/cli/internal/cli/web_service.go @@ -1,6 +1,7 @@ package cli import ( + "albedo/cli/internal/loginservice" "context" "errors" "fmt" @@ -18,7 +19,7 @@ import ( func managedWeb(cmd *cobra.Command, deps Dependencies, service loginService, options webui.Options, save, stop, rotate, noOpen, installed bool) error { ctx, out := cmd.Context(), cmd.OutOrStdout() if stop { - if err := service.stop(ctx); err != nil { + if err := service.Stop(ctx); err != nil { return err } fmt.Fprintln(out, "stopped albedo web. it will return at the next login; forget it with: albedo web --save") @@ -48,7 +49,7 @@ func managedWeb(cmd *cobra.Command, deps Dependencies, service loginService, opt return fmt.Errorf("cannot save the allowed networks: %w", err) } if installed { - if err = service.remove(ctx); err != nil { + if err = service.Remove(ctx); err != nil { return err } } else if manifest, readErr := webui.ReadManifest(webui.ManifestPath()); readErr == nil && webui.ManifestAlive(manifest) { @@ -62,7 +63,7 @@ func managedWeb(cmd *cobra.Command, deps Dependencies, service loginService, opt } } if rotate { - if err = service.stop(ctx); err != nil { + if err = service.Stop(ctx); err != nil { return err } if err = os.Remove(webui.KeyPath()); err != nil && !os.IsNotExist(err) { @@ -70,10 +71,10 @@ func managedWeb(cmd *cobra.Command, deps Dependencies, service loginService, opt } } if save { - if err = service.install(ctx, "--no-open", "--port", strconv.Itoa(options.Port)); err != nil { + if err = service.Install(ctx, "--no-open", "--port", strconv.Itoa(options.Port)); err != nil { return err } - } else if err = service.start(ctx); err != nil { + } else if err = service.Start(ctx); err != nil { return err } ctx, cancel := context.WithTimeout(ctx, webGrace) @@ -97,6 +98,6 @@ func managedWeb(cmd *cobra.Command, deps Dependencies, service loginService, opt return err } fmt.Fprintln(out, "albedo web is running through its login service.") - fmt.Fprint(out, serviceLingerNote(ctx)) + fmt.Fprint(out, loginservice.LingerNote(ctx)) return printWebLinks(cmd, deps, string(key), manifest, noOpen) } diff --git a/cli/internal/localdaemon/detach_other.go b/cli/internal/localdaemon/detach_other.go index dfb1ca372..fe12f0b6e 100644 --- a/cli/internal/localdaemon/detach_other.go +++ b/cli/internal/localdaemon/detach_other.go @@ -24,3 +24,5 @@ func endpointGone(error) bool { return false } func handOver(*exec.Cmd, *os.File) (*net.UnixConn, <-chan error, bool) { return nil, nil, false } func startStandby(LocalOptions) {} + +func HomeHeld(string) bool { return true } diff --git a/cli/internal/localdaemon/detach_unix.go b/cli/internal/localdaemon/detach_unix.go index e0909a361..c0e00ee66 100644 --- a/cli/internal/localdaemon/detach_unix.go +++ b/cli/internal/localdaemon/detach_unix.go @@ -53,6 +53,22 @@ func ownsHome(home string, pid int) bool { return lock.Type != syscall.F_UNLCK && (lock.Pid == 0 || int(lock.Pid) == pid) } +func HomeHeld(home string) bool { + file, err := os.Open(filepath.Join(home, "daemon.lock")) + if errors.Is(err, os.ErrNotExist) { + return false + } + if err != nil { + return true + } + defer file.Close() + lock := syscall.Flock_t{Type: syscall.F_WRLCK, Whence: io.SeekStart, Start: sqliteLockOffset, Len: 512} + if syscall.FcntlFlock(file.Fd(), syscall.F_GETLK, &lock) != nil { + return true + } + return lock.Type != syscall.F_UNLCK +} + func tryLauncherLock(file *os.File) (bool, error) { err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) if errors.Is(err, syscall.EWOULDBLOCK) || errors.Is(err, syscall.EAGAIN) { diff --git a/cli/internal/localdaemon/lifecycle.go b/cli/internal/localdaemon/lifecycle.go index 1a744bfe0..924c49aa1 100644 --- a/cli/internal/localdaemon/lifecycle.go +++ b/cli/internal/localdaemon/lifecycle.go @@ -389,6 +389,9 @@ func launchHome(parent context.Context, options LocalOptions, approved *daemon.C return nil, &LocalError{Kind: LauncherLockFailure, HomeDir: home, Cause: err} } defer lock.Close() // Closing releases the advisory lock; its inode persists. + if err := checkDirectLaunch(lockCtx, home); err != nil { + return nil, err + } ctx, cancel := context.WithTimeout(parent, startupDelay(startupTimeout)) defer cancel() discovery, discoveryErr := Discover(ctx, home) diff --git a/cli/internal/localdaemon/serve_other.go b/cli/internal/localdaemon/serve_other.go new file mode 100644 index 000000000..fb4446919 --- /dev/null +++ b/cli/internal/localdaemon/serve_other.go @@ -0,0 +1,12 @@ +//go:build !unix + +package localdaemon + +import ( + "context" + "errors" +) + +func Serve(context.Context, LocalOptions) error { return errors.New("daemon services require Linux") } + +func ValidateServiceLauncher(LocalOptions) error { return errors.New("daemon services require Linux") } diff --git a/cli/internal/localdaemon/serve_unix.go b/cli/internal/localdaemon/serve_unix.go new file mode 100644 index 000000000..c6259afca --- /dev/null +++ b/cli/internal/localdaemon/serve_unix.go @@ -0,0 +1,53 @@ +//go:build unix + +package localdaemon + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "syscall" +) + +func ValidateServiceLauncher(options LocalOptions) error { + selected := os.Getenv("ALBEDO_DAEMON") + if selected == "" { + return errors.New("daemon services require ALBEDO_DAEMON pointing to a packaged exec launcher") + } + if os.Getenv("ALBEDO_APPIMAGE_DAEMON") != "" || os.Getenv("APPIMAGE") != "" { + return errors.New("AppImage daemon services are not supported") + } + if options.ProjectRoot != "" { + candidate, _ := filepath.EvalSymlinks(selected) + checkout, _ := filepath.EvalSymlinks(filepath.Join(options.ProjectRoot, "priv/bin/albedo-daemon")) + if candidate != "" && candidate == checkout { + return errors.New("checkout gleam launchers are not supported by daemon services") + } + } + return nil +} + +func Serve(ctx context.Context, options LocalOptions) error { + if err := ValidateServiceLauncher(options); err != nil { + return err + } + cmd, err := LocalCommand(ctx, options) + if err != nil { + return err + } + environment := make([]string, 0, len(cmd.Env)) + for _, entry := range cmd.Env { + key, _, _ := strings.Cut(entry, "=") + if key == "ALBEDO_PARENT_PID" || strings.HasPrefix(key, "ALBEDO_STANDBY") { + continue + } + environment = append(environment, entry) + } + if err = ctx.Err(); err != nil { + return err + } + passFileLimit() + return syscall.Exec(cmd.Path, cmd.Args, environment) +} diff --git a/cli/internal/localdaemon/service.go b/cli/internal/localdaemon/service.go new file mode 100644 index 000000000..c053ca72f --- /dev/null +++ b/cli/internal/localdaemon/service.go @@ -0,0 +1,202 @@ +package localdaemon + +import ( + "context" + "errors" + "fmt" + "os" + "runtime" + "strconv" + "strings" + "time" + + "albedo/cli/internal/daemon" + "albedo/cli/internal/loginservice" +) + +type ServiceClass string + +const ( + NoService ServiceClass = "standalone" + ServiceIdle ServiceClass = "idle" + ManagedService ServiceClass = "managed" + StandaloneBeside ServiceClass = "standalone_beside_service" + ServiceTransition ServiceClass = "transitioning" + UnsafeService ServiceClass = "unsupported" + UnloadedService ServiceClass = "unloaded" + UnknownService ServiceClass = "manager_unavailable" +) + +type ServiceView struct { + Unit loginservice.DaemonUnit + Observation loginservice.Observation + Class ServiceClass + Problem string + Discovery Discovery +} + +func ClassifyService(observation loginservice.Observation, found Discovery) ServiceClass { + p := observation.Properties + if observation.File == "absent" && (!observation.Available || p["LoadState"] == "not-found") { + return NoService + } + if observation.File != "owned" || observation.Problem != "" || p["LoadState"] != "loaded" { + if observation.File == "owned" && observation.Problem == "" && p["LoadState"] == "not-found" { + return UnloadedService + } + return UnsafeService + } + if p["NeedDaemonReload"] != "no" { + return UnsafeService + } + if found.Kind == Stopping || p["ActiveState"] == "activating" || p["ActiveState"] == "deactivating" || p["ActiveState"] == "reloading" || strings.HasPrefix(p["SubState"], "auto-restart") || p["Job"] != "" { + return ServiceTransition + } + if found.Kind == Running && found.Server.Pid == 0 { + return UnsafeService + } + pid, err := strconv.Atoi(p["MainPID"]) + if err != nil { + return UnsafeService + } + if (p["ActiveState"] == "inactive" || p["ActiveState"] == "failed") && pid == 0 { + if found.Kind == Running { + return StandaloneBeside + } + return ServiceIdle + } + if p["ActiveState"] == "active" && found.Kind == Running && found.Server.Pid > 0 && pid == found.Server.Pid && pid == found.Snapshot.Pid { + if p["InvocationID"] == "" { + return UnsafeService + } + return ManagedService + } + if p["ActiveState"] == "active" && found.Kind != Running { + return ServiceTransition + } + return UnsafeService +} + +func ObserveService(ctx context.Context, home string) (ServiceView, error) { + var unit loginservice.DaemonUnit + var before loginservice.Observation + var managerErr error + if runtime.GOOS == "linux" { + var err error + unit, err = loginservice.ForDaemon(home) + if err != nil { + return ServiceView{}, err + } + before, managerErr = unit.Observe(ctx) + } + found, err := Discover(ctx, home) + var compatibility *daemon.CompatibilityError + if err != nil && (!errors.As(err, &compatibility) || found.Kind != Running) { + return ServiceView{Unit: unit, Observation: before, Discovery: found}, err + } + view := ServiceView{Unit: unit, Observation: before, Discovery: found} + if runtime.GOOS != "linux" { + view.Class = NoService + return view, nil + } + if managerErr != nil { + view.Class = UnknownService + view.Problem = managerErr.Error() + return view, nil + } + view.Class = ClassifyService(before, found) + view.Problem = before.Problem + if before.Problem == "" && before.Properties["NeedDaemonReload"] == "yes" { + view.Problem = "unit needs daemon-reload; run albedo daemon install to reconcile its definition" + } + if view.Class == ManagedService { + after, err := unit.Observe(ctx) + if err != nil { + view.Class = UnknownService + view.Problem = err.Error() + } else if after.Properties["MainPID"] != before.Properties["MainPID"] || after.Properties["InvocationID"] != before.Properties["InvocationID"] || ClassifyService(after, found) != ManagedService { + view.Class = ServiceTransition + view.Problem = "service changed while checking daemon identity" + } + } + return view, nil +} + +func (view ServiceView) MutationError() error { + reason := view.Problem + if reason == "" { + reason = "service registration or process does not match this daemon" + } + return fmt.Errorf("%s: %s (%s); inspect with albedo daemon status", view.Unit.Name(), reason, view.Class) +} + +type ServicePolicyChanged struct{} + +func (*ServicePolicyChanged) Error() string { + return "daemon service registration changed during launch" +} + +func checkDirectLaunch(ctx context.Context, home string) error { + if runtime.GOOS != "linux" { + return nil + } + unit, err := loginservice.ForDaemon(home) + if err != nil { + return err + } + observation, err := unit.Observe(ctx) + if err != nil || ClassifyService(observation, Discovery{}) != NoService { + return &ServicePolicyChanged{} + } + return nil +} + +func LockLauncher(ctx context.Context, home string) (*os.File, error) { + return acquireLauncher(ctx, home) +} + +func AwaitManaged(ctx context.Context, home string, dead daemon.ConnectionSnapshot) (*daemon.Connection, error) { + progress := watchStartup(home) + for { + view, err := ObserveService(ctx, home) + if err != nil { + var local *LocalError + if dead.Pid == 0 || view.Discovery.Snapshot != dead || !errors.As(err, &local) || (local.Kind != InvalidDiscovery && local.Kind != AuthenticationFailed) { + return nil, err + } + view.Class = ServiceTransition + } + if view.Class == ManagedService { + return daemon.Attach(ctx, view.Discovery.Snapshot, func(ctx context.Context) (daemon.ConnectionSnapshot, error) { return Rediscover(ctx, home) }) + } + p := view.Observation.Properties + if p["ActiveState"] == "failed" { + return nil, fmt.Errorf("daemon service failed: result=%s status=%s; check %s/daemon.log", p["Result"], p["ExecMainStatus"], home) + } + if view.Class == ServiceIdle && p["ActiveState"] == "inactive" { + return nil, fmt.Errorf("daemon service exited before becoming ready; check %s/daemon.log", home) + } + if view.Class != ServiceTransition && view.Class != ServiceIdle { + return nil, view.MutationError() + } + if progress.stalled() { + return nil, fmt.Errorf("daemon service made no log progress; check %s/daemon.log", home) + } + timer := time.NewTimer(100 * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return nil, ctx.Err() + case <-timer.C: + } + } +} + +type ServiceStatus struct { + Unit string `json:"unit"` + Class ServiceClass `json:"class"` + State string `json:"state"` + Problem string `json:"problem,omitempty"` + Pid int `json:"pid"` + MainPID int `json:"main_pid"` +} diff --git a/cli/internal/localdaemon/service_test.go b/cli/internal/localdaemon/service_test.go new file mode 100644 index 000000000..311c14b78 --- /dev/null +++ b/cli/internal/localdaemon/service_test.go @@ -0,0 +1,116 @@ +// Service policy errors and partial manager observations cannot be arranged +// reliably through a healthy daemon; these values drive the launch decision. +package localdaemon + +import ( + "albedo/cli/internal/daemon" + "albedo/cli/internal/loginservice" + "errors" + "fmt" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +func TestServicePolicyDoesNotTurnUncertaintyIntoDirectLaunch(t *testing.T) { + for _, test := range []struct { + name string + file, load, active, sub, pid, problem string + want ServiceClass + found Discovery + }{ + {name: "no registration", file: "absent", load: "not-found", want: NoService}, + {name: "registered elsewhere", file: "absent", load: "loaded", want: UnsafeService}, + {name: "foreign link", file: "foreign", load: "not-found", want: UnsafeService}, + {name: "unloaded", file: "owned", load: "not-found", want: UnloadedService}, + {name: "invalid main pid", file: "owned", load: "loaded", active: "active", pid: "invalid", want: UnsafeService}, + {name: "idle", file: "owned", load: "loaded", active: "inactive", pid: "0", want: ServiceIdle}, + {name: "waiting restart", file: "owned", load: "loaded", active: "activating", sub: "auto-restart", pid: "0", want: ServiceTransition}, + {name: "unsupported contract", file: "owned", load: "loaded", problem: "KillMode", want: UnsafeService}, + {name: "managed", file: "owned", load: "loaded", active: "active", pid: "123", found: Discovery{Kind: Running, Snapshot: daemon.ConnectionSnapshot{Pid: 123}, Server: daemon.ServerInfo{Pid: 123}}, want: ManagedService}, + {name: "legacy beside inactive registration", file: "owned", load: "loaded", active: "inactive", pid: "0", found: Discovery{Kind: Running, Snapshot: daemon.ConnectionSnapshot{Pid: 123}}, want: UnsafeService}, + {name: "legacy identity", file: "owned", load: "loaded", active: "active", pid: "123", found: Discovery{Kind: Running, Snapshot: daemon.ConnectionSnapshot{Pid: 123}}, want: UnsafeService}, + {name: "other main pid", file: "owned", load: "loaded", active: "active", pid: "124", found: Discovery{Kind: Running, Snapshot: daemon.ConnectionSnapshot{Pid: 123}, Server: daemon.ServerInfo{Pid: 123}}, want: UnsafeService}, + } { + t.Run(test.name, func(t *testing.T) { + observation := loginservice.Observation{File: test.file, Problem: test.problem, Available: true, Properties: map[string]string{"LoadState": test.load, "ActiveState": test.active, "SubState": test.sub, "MainPID": test.pid, "NeedDaemonReload": "no", "InvocationID": "current"}} + if got := ClassifyService(observation, test.found); got != test.want { + t.Fatalf("got %s, want %s", got, test.want) + } + }) + } +} + +func TestRegistrationIsRecheckedAfterLauncherLock(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("systemd policy is Linux-only") + } + home := t.TempDir() + manager := filepath.Join(t.TempDir(), "manager") + registration := filepath.Join(t.TempDir(), "registered") + script := "#!/bin/sh\nif [ -f '" + registration + "' ]; then echo LoadState=loaded; else echo LoadState=not-found; fi\n" + if err := os.WriteFile(manager, []byte(script), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("ALBEDO_SYSTEMCTL", manager) + launcher := filepath.Join(t.TempDir(), "daemon") + if err := os.WriteFile(launcher, []byte("#!/bin/sh\nexit 42\n"), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("ALBEDO_DAEMON", launcher) + view, err := ObserveService(t.Context(), home) + if err != nil || view.Class != NoService { + t.Fatalf("initial policy: %+v %v", view, err) + } + lock, err := LockLauncher(t.Context(), home) + if err != nil { + t.Fatal(err) + } + defer lock.Close() + finished := make(chan error, 1) + go func() { _, launchErr := Launch(t.Context(), LocalOptions{HomeDir: home}); finished <- launchErr }() + if err = os.WriteFile(registration, nil, 0600); err != nil { + t.Fatal(err) + } + lock.Close() + select { + case err := <-finished: + if _, changed := errors.AsType[*ServicePolicyChanged](err); !changed { + t.Fatalf("waiter did not return to service policy: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("launcher did not resume") + } +} + +func TestServiceObservationLeavesCompatibilityDecisionsToConnector(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("ALBEDO_SYSTEMCTL", filepath.Join(t.TempDir(), "no-manager")) + for _, test := range []struct { + name, response string + protocol int + }{ + {"missing capability", strings.Replace(readyServer, `"session_replay":2`, `"session_replay":0`, 1), 3}, + {"other protocol", strings.Replace(readyServer, `"protocol":3`, `"protocol":4`, 1), 4}, + } { + t.Run(test.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, test.response) })) + defer server.Close() + home := t.TempDir() + writeDiscovery(t, home, daemon.ConnectionSnapshot{Port: server.Listener.Addr().(*net.TCPAddr).Port, Pid: os.Getpid(), Token: "token", Version: test.protocol, Build: "verified-build"}) + view, err := ObserveService(t.Context(), home) + if err != nil || view.Class != NoService || view.Discovery.Kind != Running { + t.Fatalf("live incompatible daemon was hidden from connector: %+v %v", view, err) + } + if _, compatible := errors.AsType[*daemon.CompatibilityError](daemon.CheckCompatible(view.Discovery.Server)); !compatible { + t.Fatal("compatibility failure was lost") + } + }) + } +} diff --git a/cli/internal/loginservice/daemon.go b/cli/internal/loginservice/daemon.go new file mode 100644 index 000000000..d7908a96b --- /dev/null +++ b/cli/internal/loginservice/daemon.go @@ -0,0 +1,406 @@ +package loginservice + +import ( + "bytes" + "context" + "errors" + "fmt" + "maps" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "strconv" + "strings" + "time" +) + +const daemonMarker = "# albedo daemon service v1\n" + +type DaemonUnit struct{ path, name, home string } + +func ForDaemon(home string) (DaemonUnit, error) { + service, err := For("daemon", home) + if err != nil { + return DaemonUnit{}, err + } + return DaemonUnit{path: service.path, name: service.name, home: home}, nil +} + +type Definition struct { + Environment map[string]string + Executable string +} + +type Observation struct { + Properties map[string]string + Info os.FileInfo + Definition Definition + File string + Problem string + Data []byte + Available bool +} + +func (s DaemonUnit) Name() string { return s.name } +func (s DaemonUnit) Path() string { return s.path } + +func (s DaemonUnit) Run(ctx context.Context, verb string) error { + budget := 15 * time.Second + if verb == "stop" { + budget = 60 * time.Second + } + _, err := s.command(ctx, budget, verb, s.name) + return err +} + +func (s DaemonUnit) Reload(ctx context.Context) error { + _, err := s.command(ctx, 15*time.Second, "daemon-reload") + return err +} + +func (s DaemonUnit) command(ctx context.Context, budget time.Duration, args ...string) (string, error) { + name := os.Getenv("ALBEDO_SYSTEMCTL") + if name == "" { + name = "systemctl" + } + ctx, cancel := context.WithTimeout(ctx, budget) + defer cancel() + output, err := exec.CommandContext(ctx, name, append([]string{"--user"}, args...)...).CombinedOutput() + if err != nil { + return "", fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(output))) + } + return string(output), nil +} + +const properties = "LoadState,ActiveState,SubState,MainPID,InvocationID,Job,FragmentPath,DropInPaths,TriggeredBy,ExecStart,ExecStartPre,ExecStartPost,ExecStop,ExecStopPost,Environment,EnvironmentFiles,KillMode,Restart,RestartUSec,RestartPreventExitStatus,RestartForceExitStatus,NeedDaemonReload,Type,ExitType,RemainAfterExit,KillSignal,SendSIGHUP,SendSIGKILL,FinalKillSignal,TimeoutStopUSec,TimeoutStopFailureMode,StartLimitIntervalUSec,StartLimitBurst,StandardOutput,StandardError,UnitFileState,Result,NRestarts,ExecMainStatus" + +func (s DaemonUnit) Observe(ctx context.Context) (Observation, error) { + observation := Observation{File: "absent", Properties: map[string]string{}} + if runtime.GOOS != "linux" { + return observation, nil + } + info, err := os.Lstat(s.path) + if err == nil { + observation.Info = info + observation.File = "foreign" + if info.Mode().IsRegular() { + if info.Size() > 64*1024 { + return observation, fmt.Errorf("unit file is too large: %s", s.path) + } + observation.Data, err = os.ReadFile(s.path) + if err != nil { + return observation, err + } + if bytes.HasPrefix(observation.Data, []byte(daemonMarker)) { + observation.File = "owned" + observation.Definition, err = s.parseDefinition(observation.Data) + if err != nil { + observation.Problem = err.Error() + } + } + } + } else if !errors.Is(err, os.ErrNotExist) { + return observation, err + } + name := os.Getenv("ALBEDO_SYSTEMCTL") + if name == "" { + name = "systemctl" + } + if _, err = exec.LookPath(name); (errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist)) && observation.File == "absent" { + return observation, nil + } + if observation.File == "absent" && os.Getenv("ALBEDO_SYSTEMCTL") == "" { + if _, bootErr := os.Stat("/run/systemd/system"); errors.Is(bootErr, os.ErrNotExist) { + return observation, nil + } + } + output, err := s.command(ctx, 15*time.Second, "show", s.name, "--all", "--property="+properties) + if err != nil { + return observation, err + } + observation.Available = true + for line := range strings.SplitSeq(output, "\n") { + key, value, ok := strings.Cut(line, "=") + if ok { + observation.Properties[key] = value + } + } + if observation.Properties["LoadState"] == "" { + return observation, errors.New("systemctl returned no unit load state") + } + if observation.File == "owned" && observation.Problem == "" && observation.Properties["LoadState"] == "loaded" { + observation.Problem = s.contract(observation) + } + return observation, nil +} + +func (s DaemonUnit) Render(definition Definition) ([]byte, error) { + if !filepath.IsAbs(definition.Executable) || strings.ContainsAny(definition.Executable, "\x00\n\r;{}") { + return nil, errors.New("service requires an absolute executable path without control characters or semicolons/braces") + } + if definition.Environment["ALBEDO_HOME"] != s.home { + return nil, errors.New("service home does not match") + } + var data strings.Builder + fmt.Fprintf(&data, "%s[Unit]\nDescription=albedo daemon\nStartLimitIntervalSec=60\nStartLimitBurst=5\n\n[Service]\nType=exec\nExecStart=:%s daemon --serve\n", daemonMarker, unitQuote(definition.Executable)) + keys := make([]string, 0, len(definition.Environment)) + for key := range definition.Environment { + keys = append(keys, key) + } + slices.Sort(keys) + for _, key := range keys { + if key != "ALBEDO_HOME" && key != "PATH" && key != "ALBEDO_DAEMON" && key != "ALBEDO_ROOT" { + return nil, fmt.Errorf("unsupported service environment key %s", key) + } + if strings.ContainsAny(definition.Environment[key], "\x00\n\r") { + return nil, fmt.Errorf("invalid service environment value for %s", key) + } + fmt.Fprintln(&data, "Environment="+unitQuote(key+"="+definition.Environment[key])) + } + fmt.Fprintf(&data, "KillMode=process\nRestart=on-failure\nRestartSec=3\nRestartPreventExitStatus=75\nTimeoutStopSec=45\nStandardOutput=%s\nStandardError=%s\n\n[Install]\nWantedBy=default.target\n", strings.ReplaceAll("append:"+filepath.Join(s.home, "daemon.log"), "%", "%%"), strings.ReplaceAll("append:"+filepath.Join(s.home, "daemon.log"), "%", "%%")) + return []byte(data.String()), nil +} + +func (s DaemonUnit) Capture() (Definition, error) { + executable, err := Executable() + if err != nil { + return Definition{}, err + } + definition := Definition{Executable: executable, Environment: map[string]string{"ALBEDO_HOME": s.home}} + for _, key := range []string{"PATH", "ALBEDO_DAEMON", "ALBEDO_ROOT"} { + value := os.Getenv(key) + if value != "" && (key != "ALBEDO_DAEMON" || !strings.HasPrefix(value, "/nix/store/")) { + definition.Environment[key] = value + } + } + return definition, nil +} + +func (s DaemonUnit) parseDefinition(data []byte) (Definition, error) { + definition := Definition{Environment: map[string]string{}} + for line := range strings.SplitSeq(string(data), "\n") { + if value, ok := strings.CutPrefix(line, "Environment="); ok { + assignment, err := strconv.Unquote(value) + if err != nil { + return definition, errors.New("unrecognized unit environment") + } + key, value, ok := strings.Cut(strings.ReplaceAll(assignment, "%%", "%"), "=") + if !ok { + return definition, errors.New("invalid unit environment") + } + definition.Environment[key] = value + } + if value, ok := strings.CutPrefix(line, "ExecStart=:"); ok { + value, ok = strings.CutSuffix(value, " daemon --serve") + if !ok { + return definition, errors.New("unrecognized unit command") + } + executable, err := strconv.Unquote(value) + if err != nil { + return definition, errors.New("unrecognized unit executable") + } + definition.Executable = strings.ReplaceAll(executable, "%%", "%") + } + } + expected, err := s.Render(definition) + if err != nil { + return definition, err + } + if !bytes.Equal(data, expected) { + return definition, errors.New("unit contains edits outside the generated service format") + } + return definition, nil +} + +func (s DaemonUnit) contract(observation Observation) string { + p := observation.Properties + expected := []struct{ key, value string }{ + {"FragmentPath", s.path}, + {"TriggeredBy", ""}, + {"ExecStartPre", ""}, + {"ExecStartPost", ""}, + {"ExecStop", ""}, + {"ExecStopPost", ""}, + {"EnvironmentFiles", ""}, + {"Type", "exec"}, + {"RemainAfterExit", "no"}, + {"KillMode", "process"}, + {"Restart", "on-failure"}, + {"RestartForceExitStatus", ""}, + {"KillSignal", "15"}, + {"SendSIGHUP", "no"}, + {"SendSIGKILL", "yes"}, + {"FinalKillSignal", "9"}, + {"TimeoutStopUSec", "45s"}, + {"RestartUSec", "3s"}, + {"StartLimitIntervalUSec", "1min"}, + {"StartLimitBurst", "5"}, + {"StandardOutput", "append"}, + {"StandardError", "append"}, + } + for _, property := range expected { + if p[property.key] != property.value { + return "unsupported loaded property " + property.key + } + } + if !allowedDaemonDropIns(p["DropInPaths"]) { + return "unsupported loaded property DropInPaths" + } + stopFailureMode := "terminate" + if p["DropInPaths"] != "" { + stopFailureMode = "abort" + } + if p["TimeoutStopFailureMode"] != stopFailureMode { + return "unsupported loaded property TimeoutStopFailureMode" + } + // Before systemd 250, services always followed the main process. + if p["ExitType"] != "" && p["ExitType"] != "main" { + return "unsupported loaded property ExitType" + } + if p["RestartPreventExitStatus"] != "75" { + return "unsupported loaded property RestartPreventExitStatus" + } + loaded := observation.Definition + if p["NeedDaemonReload"] == "yes" { + command, ok := strings.CutPrefix(p["ExecStart"], "{ path=") + if !ok { + return "unsupported loaded property ExecStart" + } + loaded.Executable, _, ok = strings.Cut(command, " ; argv[]=") + if !ok { + return "unsupported loaded property ExecStart" + } + } + prefix := "{ path=" + loaded.Executable + " ; argv[]=" + loaded.Executable + " daemon --serve ; " + if !strings.HasPrefix(p["ExecStart"], prefix) || strings.Count(p["ExecStart"], "{ path=") != 1 { + return "unsupported loaded property ExecStart" + } + environment, err := splitWords(p["Environment"]) + if err != nil { + return "unrecognized loaded Environment" + } + actualEnvironment := make(map[string]string, len(environment)) + for _, entry := range environment { + key, value, ok := strings.Cut(entry, "=") + if _, duplicate := actualEnvironment[key]; !ok || duplicate { + return "unsupported loaded Environment" + } + actualEnvironment[key] = value + } + if p["NeedDaemonReload"] == "yes" { + loaded.Environment = actualEnvironment + if _, err = s.Render(loaded); err != nil { + return "unsupported loaded Environment or executable" + } + } else if !maps.Equal(actualEnvironment, loaded.Environment) { + return "unsupported loaded Environment" + } + return "" +} + +func allowedDaemonDropIns(value string) bool { + if value == "" { + return true + } + const vendorPath = "/usr/lib/systemd/user/service.d/10-timeout-abort.conf" + if value != vendorPath { + return false + } + data, err := os.ReadFile(vendorPath) + if err != nil { + return false + } + var directives []string + for line := range strings.SplitSeq(string(data), "\n") { + line = strings.TrimSpace(line) + if line != "" && !strings.HasPrefix(line, "#") && !strings.HasPrefix(line, ";") { + directives = append(directives, line) + } + } + return slices.Equal(directives, []string{"[Service]", "TimeoutStopFailureMode=abort"}) +} + +func splitWords(input string) ([]string, error) { + var words []string + for input = strings.TrimSpace(input); input != ""; input = strings.TrimSpace(input) { + if input[0] != '"' { + index := strings.IndexAny(input, " \t") + if index < 0 { + words = append(words, input) + break + } + words = append(words, input[:index]) + input = input[index:] + continue + } + end := 1 + for end < len(input) { + if input[end] == '\\' { + end += 2 + continue + } + if input[end] == '"' { + break + } + end++ + } + if end >= len(input) { + return nil, errors.New("unterminated quoted word") + } + word, err := strconv.Unquote(strings.NewReplacer(`\$`, `$`, "\\`", "`").Replace(input[:end+1])) + if err != nil { + return nil, err + } + words = append(words, word) + input = input[end+1:] + } + return words, nil +} + +func (s DaemonUnit) Publish(data []byte) (os.FileInfo, error) { + directory := filepath.Dir(s.path) + if err := os.MkdirAll(directory, 0700); err != nil { + return nil, err + } + file, err := os.CreateTemp(directory, ".albedo-unit-*") + if err != nil { + return nil, err + } + defer os.Remove(file.Name()) + if err = file.Chmod(0600); err == nil { + _, err = file.Write(data) + } + if err == nil { + err = file.Sync() + } + closeErr := file.Close() + if err == nil { + err = closeErr + } + if err != nil { + return nil, err + } + if err = os.Rename(file.Name(), s.path); err != nil { + return nil, err + } + dir, err := os.Open(directory) + if err != nil { + return nil, err + } + defer dir.Close() + if err = dir.Sync(); err != nil { + return nil, err + } + return os.Lstat(s.path) +} + +func (s DaemonUnit) Unchanged(info os.FileInfo, data []byte) bool { + current, err := os.Lstat(s.path) + if err != nil || !current.Mode().IsRegular() || !os.SameFile(info, current) { + return false + } + bytesNow, err := os.ReadFile(s.path) + return err == nil && bytes.Equal(data, bytesNow) +} diff --git a/cli/internal/loginservice/login.go b/cli/internal/loginservice/login.go new file mode 100644 index 000000000..77bfd9eb1 --- /dev/null +++ b/cli/internal/loginservice/login.go @@ -0,0 +1,210 @@ +// Package loginservice owns native user-service definitions and manager calls. +package loginservice + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/xml" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "time" +) + +type Service struct{ role, path, name, domain, home string } + +func For(role, daemonHome string) (Service, error) { + home, err := os.UserHomeDir() + if err != nil { + return Service{}, err + } + sum := sha256.Sum256([]byte(daemonHome)) + name := fmt.Sprintf("systems.albedo.%s-%x", role, sum[:8]) + switch runtime.GOOS { + case "darwin": + return Service{role, filepath.Join(home, "Library", "LaunchAgents", name+".plist"), name, "gui/" + strconv.Itoa(os.Getuid()), daemonHome}, nil + case "linux": + root := os.Getenv("XDG_CONFIG_HOME") + if root == "" { + root = filepath.Join(home, ".config") + } + return Service{role, filepath.Join(root, "systemd", "user", name+".service"), name + ".service", "", daemonHome}, nil + default: + return Service{}, errors.New("saved services require macOS or Linux") + } +} + +func (s Service) Installed() (bool, error) { + _, err := os.Stat(s.path) + if os.IsNotExist(err) { + return false, nil + } + return err == nil, err +} + +func (s Service) manager(ctx context.Context, args ...string) (string, error) { + name, override := "systemctl", "ALBEDO_SYSTEMCTL" + if runtime.GOOS == "darwin" { + name, override = "launchctl", "ALBEDO_LAUNCHCTL" + } else { + args = append([]string{"--user"}, args...) + } + if value := os.Getenv(override); value != "" { + name = value + } + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + output, err := exec.CommandContext(ctx, name, args...).CombinedOutput() + if err != nil { + return string(output), fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(output))) + } + return string(output), nil +} + +func (s Service) Start(ctx context.Context) error { + if runtime.GOOS == "darwin" { + if _, err := s.manager(ctx, "print", s.domain+"/"+s.name); err != nil { + _, err = s.manager(ctx, "bootstrap", s.domain, s.path) + return err + } + _, err := s.manager(ctx, "kickstart", s.domain+"/"+s.name) + return err + } + _, err := s.manager(ctx, "start", s.name) + return err +} + +func (s Service) Stop(ctx context.Context) error { + if runtime.GOOS == "darwin" { + if _, err := s.manager(ctx, "print", s.domain+"/"+s.name); err != nil { + var exit *exec.ExitError + if errors.As(err, &exit) && exit.ExitCode() == 113 { + return nil + } + return err + } + _, err := s.manager(ctx, "bootout", s.domain+"/"+s.name) + return err + } + _, err := s.manager(ctx, "stop", s.name) + return err +} + +func (s Service) Remove(ctx context.Context) error { + if err := s.Stop(ctx); err != nil { + return err + } + if runtime.GOOS == "linux" { + if _, err := s.manager(ctx, "disable", s.name); err != nil { + return err + } + } + if err := os.Remove(s.path); err != nil && !os.IsNotExist(err) { + return err + } + if runtime.GOOS == "linux" { + _, err := s.manager(ctx, "daemon-reload") + return err + } + return nil +} + +// Executable preserves moving package links instead of pinning their targets. +func Executable() (string, error) { + if path, err := exec.LookPath(os.Args[0]); err == nil { + return filepath.Abs(path) + } + return os.Executable() +} + +func xmlText(text string) string { + var out bytes.Buffer + _ = xml.EscapeText(&out, []byte(text)) + return out.String() +} + +func unitQuote(text string) string { + return strconv.Quote(strings.ReplaceAll(text, "%", "%%")) +} + +func (s Service) Install(ctx context.Context, options ...string) error { + executable, err := Executable() + if err != nil { + return err + } + args := append([]string{executable, s.role, "--foreground", "--service"}, options...) + environment := map[string]string{"ALBEDO_HOME": s.home} + for _, key := range []string{"PATH", "ALBEDO_ROOT", "ALBEDO_DAEMON", "ALBEDO_WEB_DIST"} { + if value := os.Getenv(key); value != "" { + // Package wrappers supply their current store defaults at each start. + if (key == "ALBEDO_DAEMON" || key == "ALBEDO_WEB_DIST") && strings.HasPrefix(value, "/nix/store/") { + continue + } + environment[key] = value + } + } + logPath := filepath.Join(s.home, s.role+".log") + var data strings.Builder + if runtime.GOOS == "darwin" { + fmt.Fprint(&data, ` + + +Label`, xmlText(s.name), ` +ProgramArguments`) + for _, arg := range args { + fmt.Fprint(&data, "", xmlText(arg), "") + } + data.WriteString("EnvironmentVariables") + for key, value := range environment { + fmt.Fprint(&data, "", xmlText(key), "", xmlText(value), "") + } + fmt.Fprint(&data, ` +RunAtLoad +KeepAlive +StandardOutPath`, xmlText(logPath), ` +StandardErrorPath`, xmlText(logPath), ` + +`) + } else { + fmt.Fprint(&data, "[Unit]\nDescription=albedo ", s.role, "\n\n[Service]\nType=simple\nExecStart=") + for _, arg := range args { + fmt.Fprint(&data, unitQuote(strings.ReplaceAll(arg, "$", "$$")), " ") + } + data.WriteString("\nRestart=always\nRestartSec=3\n") + for key, value := range environment { + fmt.Fprintln(&data, "Environment="+unitQuote(key+"="+value)) + } + fmt.Fprint(&data, "StandardOutput=", unitQuote("append:"+logPath), "\nStandardError=", unitQuote("append:"+logPath), "\n\n[Install]\nWantedBy=default.target\n") + } + if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil { + return err + } + if err := os.WriteFile(s.path, []byte(data.String()), 0o600); err != nil { + return err + } + if runtime.GOOS == "linux" { + if _, err := s.manager(ctx, "daemon-reload"); err != nil { + return err + } + _, err := s.manager(ctx, "enable", "--now", s.name) + return err + } + return s.Start(ctx) +} + +func LingerNote(ctx context.Context) string { + if runtime.GOOS != "linux" { + return "" + } + output, err := exec.CommandContext(ctx, "loginctl", "show-user", strconv.Itoa(os.Getuid()), "--property=Linger", "--value").Output() + if err != nil || strings.TrimSpace(string(output)) != "yes" { + return "to keep it running after logout and start it at boot, run: loginctl enable-linger\n" + } + return "" +} diff --git a/cli/test/e2e/daemon_service_test.go b/cli/test/e2e/daemon_service_test.go new file mode 100644 index 000000000..bf68b6db5 --- /dev/null +++ b/cli/test/e2e/daemon_service_test.go @@ -0,0 +1,548 @@ +//go:build linux + +package e2e + +import ( + "bytes" + "context" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "slices" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "albedo/cli/internal/daemon" + "albedo/cli/internal/localdaemon" + "albedo/cli/internal/loginservice" +) + +func daemonServiceFixture(t *testing.T) (string, []string, func(...string) (string, error)) { + t.Helper() + home := filepath.Join(t.TempDir(), "home with % and $") + if err := os.MkdirAll(home, 0700); err != nil { + t.Fatal(err) + } + config := t.TempDir() + env := append(slices.Clone(suite.env), "ALBEDO_HOME="+home, "XDG_CONFIG_HOME="+config, "ALBEDO_SYSTEMCTL="+filepath.Join(suite.root, "cli/test/e2e/login_service_stub.py")) + runContext := func(ctx context.Context, args ...string) (string, error) { + cmd := exec.CommandContext(ctx, suite.cli, args...) + cmd.Env = env + output, err := cmd.CombinedOutput() + return string(output), err + } + run := func(args ...string) (string, error) { return runContext(t.Context(), args...) } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + for _, name := range []string{"daemon-properties.json", "service-stub-fail", "fail-after-start", "fail-after-enable", "reload-fault.json", "replacement-on-exit", "start-reply-gate", "fail-after-disable"} { + _ = os.Remove(filepath.Join(home, name)) + } + snapshot, _ := readDaemonSnapshot(home) + if _, err := os.Stat(filepath.Join(home, "daemon-service-stub.json")); err == nil { + if output, stopErr := runContext(ctx, "daemon", "--stop", "--kernels"); stopErr != nil { + t.Errorf("service cleanup stop: %v %s", stopErr, output) + } + if output, uninstallErr := runContext(ctx, "daemon", "uninstall"); uninstallErr != nil { + t.Errorf("service cleanup uninstall: %v %s", uninstallErr, output) + } + } + if snapshot.Pid > 0 && !awaitExit(snapshot.Pid, 5*time.Second) { + t.Errorf("fixture daemon %d survived cleanup", snapshot.Pid) + } + }) + return home, env, run +} + +func TestDaemonServiceLifecycle(t *testing.T) { + home, _, run := daemonServiceFixture(t) + must := func(args ...string) string { + t.Helper() + output, err := run(args...) + if err != nil { + t.Fatalf("%v: %v: %s", args, err, output) + } + return output + } + status := func() localdaemon.ServiceStatus { + t.Helper() + var value localdaemon.ServiceStatus + if err := json.Unmarshal([]byte(must("daemon", "status", "--json")), &value); err != nil { + t.Fatal(err) + } + return value + } + if output := must("daemon", "status"); !strings.Contains(output, "daemon: not running") || !strings.Contains(output, "service: not installed") { + t.Fatalf("empty home status: %s", output) + } + must("daemon", "install") + first := status() + if first.Class != localdaemon.ManagedService || first.Pid != first.MainPID || first.Pid == 0 { + t.Fatalf("service did not own daemon: %+v", first) + } + must("daemon") + must("daemon", "install") + if status().Pid != first.Pid { + t.Fatal("attach/refresh replaced managed daemon") + } + must("daemon", "--stop", "--kernels") + if stopped := status(); stopped.Class != localdaemon.ServiceIdle || stopped.Pid != 0 { + t.Fatal("HTTP stop did not leave unit idle") + } + must("daemon", "install") + if status().Class != localdaemon.ServiceIdle { + t.Fatal("refresh started a stopped service") + } + must("daemon") + if status().Pid == first.Pid { + t.Fatal("service did not start again") + } + must("daemon", "uninstall") + must("daemon") + if status().Class != localdaemon.NoService { + t.Fatal("uninstall did not restore standalone launch") + } + must("daemon", "--stop") + data, err := os.ReadFile(filepath.Join(home, "service-stub.log")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(data), `["stop",`) { + t.Fatal("lifecycle used a name-addressed stop instead of instance-bound HTTP shutdown") + } +} + +func TestDaemonServiceFailedStartLeavesRegistration(t *testing.T) { + home, _, run := daemonServiceFixture(t) + if err := os.WriteFile(filepath.Join(home, "fail-after-start"), nil, 0600); err != nil { + t.Fatal(err) + } + output, err := run("daemon", "install") + if err == nil || !strings.Contains(output, "configuration left in place") { + t.Fatalf("ambiguous start was not reported: %v %s", err, output) + } + if _, err = os.Stat(filepath.Join(home, "daemon-unit-loaded")); err != nil { + t.Fatal("ambiguous start deleted registration") + } + data, err := os.ReadFile(filepath.Join(home, "service-stub.log")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(data), `["disable",`) || strings.Contains(string(data), `["stop",`) { + t.Fatal("ambiguous start triggered destructive rollback") + } + _ = os.Remove(filepath.Join(home, "fail-after-start")) +} + +func TestDaemonServiceRegisteredElsewhereBlocksDirectLaunch(t *testing.T) { + home, _, run := daemonServiceFixture(t) + if err := os.WriteFile(filepath.Join(home, "daemon-properties.json"), []byte(`{"LoadState":"loaded","FragmentPath":"/etc/systemd/user/foreign.service"}`), 0600); err != nil { + t.Fatal(err) + } + output, err := run("daemon") + if err == nil || !strings.Contains(output, "inspect with albedo daemon status") { + t.Fatalf("foreign registration permitted launch: %v %s", err, output) + } + if _, err = os.Stat(filepath.Join(home, "daemon.json")); !os.IsNotExist(err) { + t.Fatal("a standalone daemon was spawned") + } +} + +func TestDaemonServiceForeignSymlinkIsNeverReplaced(t *testing.T) { + _, env, run := daemonServiceFixture(t) + var home, config string + for _, entry := range env { + if value, ok := strings.CutPrefix(entry, "ALBEDO_HOME="); ok { + home = value + } + if value, ok := strings.CutPrefix(entry, "XDG_CONFIG_HOME="); ok { + config = value + } + } + original := os.Getenv("XDG_CONFIG_HOME") + t.Setenv("XDG_CONFIG_HOME", config) + unit, err := loginservice.ForDaemon(home) + t.Setenv("XDG_CONFIG_HOME", original) + if err != nil { + t.Fatal(err) + } + if err = os.MkdirAll(filepath.Dir(unit.Path()), 0700); err != nil { + t.Fatal(err) + } + target := filepath.Join(t.TempDir(), "missing-target") + if err = os.Symlink(target, unit.Path()); err != nil { + t.Fatal(err) + } + if output, err := run("daemon", "install"); err == nil { + t.Fatalf("foreign symlink accepted: %s", output) + } + if value, err := os.Readlink(unit.Path()); err != nil || value != target { + t.Fatalf("foreign symlink changed: %q %v", value, err) + } +} + +func TestDaemonServiceFailedEnableKeepsEnabledRegistration(t *testing.T) { + home, _, run := daemonServiceFixture(t) + if err := os.WriteFile(filepath.Join(home, "fail-after-enable"), nil, 0600); err != nil { + t.Fatal(err) + } + output, err := run("daemon", "install") + if err == nil || !strings.Contains(output, "configuration left in place") { + t.Fatalf("partial enable was not reported: %v %s", err, output) + } + if _, err = os.Stat(filepath.Join(home, "daemon-unit-enabled")); err != nil { + t.Fatal("partial enable was destructively undone") + } + _ = os.Remove(filepath.Join(home, "fail-after-enable")) +} + +func TestDaemonServiceOverrideRefusesShutdown(t *testing.T) { + home, _, run := daemonServiceFixture(t) + if output, err := run("daemon", "install"); err != nil { + t.Fatalf("install: %v %s", err, output) + } + if err := os.WriteFile(filepath.Join(home, "daemon-properties.json"), []byte(`{"KillMode":"control-group"}`), 0600); err != nil { + t.Fatal(err) + } + if output, err := run("daemon", "--stop", "--kernels"); err == nil || !strings.Contains(output, "KillMode") { + t.Fatalf("unsafe contract permitted shutdown: %v %s", err, output) + } + if output, err := run("daemon"); err != nil { + t.Fatalf("read-only attachment refused: %v %s", err, output) + } +} + +func TestDaemonServiceExecSanitizesInheritedControls(t *testing.T) { + home, env, _ := daemonServiceFixture(t) + env = append(env, "ALBEDO_PARENT_PID=99999999", "ALBEDO_STANDBY_SERVE=/not/a/standby", "ALBEDO_STANDBY_ENV=poison", "ALBEDO_STANDBY_DIR=/not/a/standby", "ALBEDO_MODEL=poison", "ALBEDO_API_KEY=poison") + cmd := exec.CommandContext(t.Context(), suite.cli, "daemon", "install") + cmd.Env = env + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("install with inherited controls: %v %s", err, output) + } + snapshot, err := readDaemonSnapshot(home) + if err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(snapshot.Pid), "environ")) + if err != nil { + t.Fatal(err) + } + for entry := range strings.SplitSeq(string(data), "\x00") { + key, _, _ := strings.Cut(entry, "=") + if key == "ALBEDO_PARENT_PID" || strings.HasPrefix(key, "ALBEDO_STANDBY") || key == "ALBEDO_MODEL" || key == "ALBEDO_API_KEY" { + t.Fatalf("service inherited forbidden control %s", key) + } + } +} + +func TestDaemonServiceCancelledSubmittedStartIsNotUndone(t *testing.T) { + home, env, _ := daemonServiceFixture(t) + if err := syscall.Mkfifo(filepath.Join(home, "start-reply-gate"), 0600); err != nil { + t.Fatal(err) + } + cmd := exec.CommandContext(t.Context(), suite.cli, "daemon", "install") + cmd.Env = env + var output bytes.Buffer + cmd.Stdout = &output + cmd.Stderr = &output + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if cmd.ProcessState == nil { + _ = cmd.Process.Kill() + _ = cmd.Wait() + } + }) + deadline := time.NewTimer(10 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + if _, err := os.Stat(filepath.Join(home, "start-submitted")); err == nil { + break + } + select { + case <-deadline.C: + t.Fatal("start was not submitted") + case <-ticker.C: + } + } + if err := cmd.Process.Signal(os.Interrupt); err != nil { + t.Fatal(err) + } + if err := cmd.Wait(); err == nil || !strings.Contains(output.String(), "configuration left in place") { + t.Fatalf("cancelled install: %v %s", err, output.String()) + } + _ = os.Remove(filepath.Join(home, "start-reply-gate")) + data, err := os.ReadFile(filepath.Join(home, "service-stub.log")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(data), `["stop",`) || strings.Contains(string(data), `["disable",`) { + t.Fatal("cancelled start was destructively undone") + } +} + +func TestDaemonServiceManagerFailureAllowsOnlyAttachment(t *testing.T) { + home, _, run := daemonServiceFixture(t) + if output, err := run("daemon"); err != nil { + t.Fatalf("standalone launch: %v %s", err, output) + } + if err := os.WriteFile(filepath.Join(home, "service-stub-fail"), nil, 0600); err != nil { + t.Fatal(err) + } + if output, err := run("daemon"); err != nil { + t.Fatalf("attachment during manager failure: %v %s", err, output) + } + if output, err := run("daemon", "--stop"); err == nil { + t.Fatalf("shutdown during manager failure: %s", output) + } + _ = os.Remove(filepath.Join(home, "service-stub-fail")) + if output, err := run("daemon", "--stop", "--kernels"); err != nil { + t.Fatalf("stop: %v %s", err, output) + } + if err := os.WriteFile(filepath.Join(home, "service-stub-fail"), nil, 0600); err != nil { + t.Fatal(err) + } + if output, err := run("daemon"); err == nil { + t.Fatalf("launch during manager failure: %s", output) + } +} + +func TestDaemonServicePreStartCleanupPreservesOtherChanges(t *testing.T) { + for _, test := range []struct { + name, fault string + preserve bool + }{ + {"reload failure", `{}`, false}, + {"external edit", `{"external_edit":true}`, true}, + {"failed observation", `{"manager_unavailable":true}`, true}, + } { + t.Run(test.name, func(t *testing.T) { + home, _, run := daemonServiceFixture(t) + if err := os.WriteFile(filepath.Join(home, "reload-fault.json"), []byte(test.fault), 0600); err != nil { + t.Fatal(err) + } + if output, err := run("daemon", "install"); err == nil { + t.Fatalf("faulted install succeeded: %s", output) + } + data, err := os.ReadFile(filepath.Join(home, "daemon-unit-loaded")) + if test.preserve { + if err != nil || len(data) == 0 { + t.Fatalf("uncertain registration was removed: %v", err) + } + } else if !os.IsNotExist(err) { + t.Fatalf("new file was not removed before cleanup reload: %v", err) + } + if test.name == "external edit" { + output, statusErr := run("daemon", "status", "--json") + if statusErr != nil || !strings.Contains(output, "edits outside") { + t.Fatalf("external file edit was overwritten: %v %s", statusErr, output) + } + } + log, err := os.ReadFile(filepath.Join(home, "service-stub.log")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(log), `["start",`) || strings.Contains(string(log), `["enable",`) { + t.Fatal("failed preflight submitted a service job") + } + }) + } +} + +func TestDaemonServiceFailedRefreshRestoresPreviousFileBeforeReload(t *testing.T) { + home, env, run := daemonServiceFixture(t) + if output, err := run("daemon", "install"); err != nil { + t.Fatalf("install: %v %s", err, output) + } + if output, err := run("daemon", "--stop", "--kernels"); err != nil { + t.Fatalf("stop: %v %s", err, output) + } + previous, err := os.ReadFile(filepath.Join(home, "daemon-unit-loaded")) + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(filepath.Join(home, "reload-fault.json"), []byte(`{}`), 0600); err != nil { + t.Fatal(err) + } + cmd := exec.CommandContext(t.Context(), suite.cli, "daemon", "install") + cmd.Env = append(env, "ALBEDO_ROOT="+t.TempDir()) + if output, refreshErr := cmd.CombinedOutput(); refreshErr == nil || !strings.Contains(string(output), "previous configuration restored") { + t.Fatalf("failed refresh: %v %s", refreshErr, output) + } + loaded, err := os.ReadFile(filepath.Join(home, "daemon-unit-loaded")) + if err != nil || !bytes.Equal(previous, loaded) { + t.Fatalf("previous definition was not restored before reload: %v", err) + } +} + +func TestDaemonServiceShutdownDoesNotChaseChangedInvocation(t *testing.T) { + home, _, run := daemonServiceFixture(t) + if output, err := run("daemon", "install"); err != nil { + t.Fatalf("install: %v %s", err, output) + } + if err := os.WriteFile(filepath.Join(home, "replacement-on-exit"), nil, 0600); err != nil { + t.Fatal(err) + } + if output, err := run("daemon", "--stop"); err == nil || !strings.Contains(output, "invocation changed") { + t.Fatalf("changed invocation was not reported: %v %s", err, output) + } + log, err := os.ReadFile(filepath.Join(home, "service-stub.log")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(log), `["stop",`) { + t.Fatal("shutdown chased a replacement with a name-addressed stop") + } +} + +func TestDaemonServiceNonExecWrapperIsNotClaimed(t *testing.T) { + home, env, _ := daemonServiceFixture(t) + var selected string + for _, entry := range env { + if value, ok := strings.CutPrefix(entry, "ALBEDO_DAEMON="); ok { + selected = value + } + } + wrapper := filepath.Join(t.TempDir(), "non-exec-launcher") + command := "#!/bin/sh\n'" + strings.ReplaceAll(selected, "'", "'\\''") + "' &\nwait\n" + if err := os.WriteFile(wrapper, []byte(command), 0700); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + snapshot, err := readDaemonSnapshot(home) + if err != nil { + return + } + connection, err := daemon.Attach(ctx, snapshot, nil) + if err == nil { + _ = daemon.StopDaemon(ctx, connection, true) + _ = daemon.WaitForExit(ctx, snapshot.Pid) + connection.HTTPClient().CloseIdleConnections() + } + }) + cmd := exec.CommandContext(t.Context(), suite.cli, "daemon", "install") + cmd.Env = append(env, "ALBEDO_DAEMON="+wrapper) + if output, err := cmd.CombinedOutput(); err == nil || !strings.Contains(string(output), "configuration left in place") { + t.Fatalf("non-exec launcher was claimed or undone: %v %s", err, output) + } + if _, err := os.Stat(filepath.Join(home, "daemon-unit-loaded")); err != nil { + t.Fatal("unsupported launcher caused registration to be removed") + } +} + +func TestDaemonServiceReconcilesInterruptedRefreshWithoutChangingLifecycle(t *testing.T) { + for _, state := range []string{"idle", "managed", "transitioning"} { + t.Run(state, func(t *testing.T) { + home, _, run := daemonServiceFixture(t) + if output, err := run("daemon", "install"); err != nil { + t.Fatalf("install: %v %s", err, output) + } + switch state { + case "idle": + if output, err := run("daemon", "--stop", "--kernels"); err != nil { + t.Fatalf("stop: %v %s", err, output) + } + case "managed": + if err := os.Remove(filepath.Join(home, "daemon-unit-enabled")); err != nil { + t.Fatal(err) + } + } + data, err := os.ReadFile(filepath.Join(home, "daemon-service-stub.json")) + if err != nil { + t.Fatal(err) + } + var record struct{ Path string } + if err = json.Unmarshal(data, &record); err != nil { + t.Fatal(err) + } + data, err = os.ReadFile(record.Path) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(string(data), "\n") + for index, line := range lines { + if strings.HasPrefix(line, `Environment="ALBEDO_ROOT=`) { + lines[index] = `Environment="ALBEDO_ROOT=/interrupted/root"` + } + } + pending := []byte(strings.Join(lines, "\n")) + if bytes.Equal(pending, data) { + t.Fatal("fixture did not change the unit") + } + if err = os.WriteFile(record.Path, pending, 0600); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if restoreErr := os.WriteFile(record.Path, data, 0600); restoreErr != nil { + t.Errorf("restore fixture definition: %v", restoreErr) + } + }) + if state == "transitioning" { + if err = os.WriteFile(filepath.Join(home, "daemon-properties.json"), []byte(`{"ActiveState":"activating","Job":"1 job"}`), 0600); err != nil { + t.Fatal(err) + } + } + if err = os.WriteFile(filepath.Join(home, "service-stub.log"), nil, 0600); err != nil { + t.Fatal(err) + } + output, installErr := run("daemon", "install") + if (installErr != nil) != (state == "transitioning") { + t.Fatalf("reconcile %s: %v %s", state, installErr, output) + } + log, err := os.ReadFile(filepath.Join(home, "service-stub.log")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(log), `["start",`) || strings.Contains(string(log), `["enable",`) { + t.Fatal("reconciliation changed lifecycle or enablement") + } + if state == "transitioning" { + current, readErr := os.ReadFile(record.Path) + if readErr != nil || !bytes.Equal(current, pending) { + t.Fatal("transitional unit was rewritten") + } + } + }) + } +} + +func TestDaemonServiceFailedRunningRefreshRestoresItsDefinition(t *testing.T) { + home, env, run := daemonServiceFixture(t) + if output, err := run("daemon", "install"); err != nil { + t.Fatalf("install: %v %s", err, output) + } + previous, err := os.ReadFile(filepath.Join(home, "daemon-unit-loaded")) + if err != nil { + t.Fatal(err) + } + before, err := readDaemonSnapshot(home) + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(filepath.Join(home, "reload-fault.json"), []byte(`{}`), 0600); err != nil { + t.Fatal(err) + } + cmd := exec.CommandContext(t.Context(), suite.cli, "daemon", "install") + cmd.Env = append(env, "ALBEDO_ROOT="+t.TempDir()) + if output, refreshErr := cmd.CombinedOutput(); refreshErr == nil || !strings.Contains(string(output), "previous configuration restored") { + t.Fatalf("running refresh: %v %s", refreshErr, output) + } + loaded, err := os.ReadFile(filepath.Join(home, "daemon-unit-loaded")) + if err != nil || !bytes.Equal(loaded, previous) { + t.Fatal("running service definition was not restored") + } + after, err := readDaemonSnapshot(home) + if err != nil || after.Pid != before.Pid { + t.Fatal("running refresh replaced the daemon") + } +} diff --git a/cli/test/e2e/harness_test.go b/cli/test/e2e/harness_test.go index aa95e6023..e8c809b15 100644 --- a/cli/test/e2e/harness_test.go +++ b/cli/test/e2e/harness_test.go @@ -313,6 +313,7 @@ func hermeticEnv(root, home, userHome, scratch, daemonExe, sshBin string) []stri "ALBEDO_ROOT="+root, "ALBEDO_DAEMON="+daemonExe, "ALBEDO_NO_BROWSER=1", + "ALBEDO_SYSTEMCTL="+filepath.Join(scratch, "no-systemctl"), // An OS-picked intake port leaves 8088 to the developer's daemon. "ALBEDO_WEBHOOK_PORT=0", "ALBEDO_IDLE_SECONDS=10", diff --git a/cli/test/e2e/login_service_stub.py b/cli/test/e2e/login_service_stub.py index 2b362cf5e..cca049861 100755 --- a/cli/test/e2e/login_service_stub.py +++ b/cli/test/e2e/login_service_stub.py @@ -13,9 +13,18 @@ import time root = Path(os.environ["ALBEDO_HOME"]) args = [arg for arg in sys.argv[1:] if arg != "--user"] +command = args[0] +service_name = next( + ( + Path(arg).name.removesuffix(".plist") + for arg in args + if Path(arg).name.startswith("systems.albedo.") + ), + args[-1], +) role = ( - Path(args[-1]).name.split(".")[2].split("-")[0] - if args[0] not in {"daemon-reload"} + Path(service_name).name.split(".")[2].split("-")[0] + if service_name.startswith("systems.albedo.") else "proxy" ) state = root / (role + "-service-stub.json") @@ -23,6 +32,178 @@ with (root / "service-stub.log").open("a") as log: log.write(json.dumps(args) + "\n") if (root / "service-stub-fail").exists(): sys.exit("service manager unavailable") +if role == "daemon" or command == "daemon-reload": + import hashlib + + name = ( + "systems.albedo.daemon-" + + hashlib.sha256(str(root).encode()).hexdigest()[:16] + + ".service" + ) + path = ( + Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))) + / "systemd/user" + / name + ) + loaded = root / "daemon-unit-loaded" + enabled = root / "daemon-unit-enabled" + daemon_state = root / "daemon-service-stub.json" + record = json.loads(daemon_state.read_text()) if daemon_state.exists() else {} + + def live(pid): + if not pid: + return False + try: + if Path(f"/proc/{pid}/stat").read_text().split(") ", 1)[1].startswith("Z"): + return False + except FileNotFoundError: + pass + try: + os.kill(pid, 0) + return True + except ProcessLookupError: + return False + + if command == "daemon-reload": + if path.exists(): + loaded.write_text(path.read_text()) + else: + loaded.unlink(missing_ok=True) + fault = root / "reload-fault.json" + if fault.exists(): + options = json.loads(fault.read_text()) + fault.unlink() + if options.get("external_edit"): + with path.open("a") as edited: + edited.write("# external edit\n") + if options.get("manager_unavailable"): + (root / "service-stub-fail").touch() + sys.exit("reload reply failed") + sys.exit(0) + if command == "show": + data = loaded.read_text() if loaded.exists() else "" + pid = record.get("pid", 0) if live(record.get("pid")) else 0 + values = { + "LoadState": "loaded" if data else "not-found", + "ActiveState": "active" if pid else "inactive", + "SubState": "running" if pid else "dead", + "MainPID": str(pid), + "Job": "", + "FragmentPath": str(path) if data else "", + "UnitFileState": "enabled" if enabled.exists() else "disabled", + "InvocationID": record.get("invocation", "") if pid else "", + "NeedDaemonReload": "yes" + if path.exists() and path.read_text() != data + else "no", + "Result": "success", + "NRestarts": "0", + "ExecMainStatus": "0", + } + if data: + argv = shlex.split( + next( + line[10:] + for line in data.splitlines() + if line.startswith("ExecStart=") + ) + ) + argv[0] = argv[0].removeprefix(":") + argv = [arg.replace("%%", "%") for arg in argv] + env = [ + shlex.split(line[12:])[0].replace("%%", "%") + for line in data.splitlines() + if line.startswith("Environment=") + ] + values.update( + { + "Type": "exec", + "ExitType": "main", + "RemainAfterExit": "no", + "DropInPaths": "", + "TriggeredBy": "", + "ExecStartPre": "", + "ExecStartPost": "", + "ExecStop": "", + "ExecStopPost": "", + "EnvironmentFiles": "", + "KillMode": "process", + "Restart": "on-failure", + "RestartPreventExitStatus": "75", + "RestartForceExitStatus": "", + "KillSignal": "15", + "SendSIGHUP": "no", + "SendSIGKILL": "yes", + "FinalKillSignal": "9", + "TimeoutStopUSec": "45s", + "TimeoutStopFailureMode": "terminate", + "RestartUSec": "3s", + "StartLimitIntervalUSec": "1min", + "StartLimitBurst": "5", + "StandardOutput": "append", + "StandardError": "append", + "ExecStart": "{ path=" + + argv[0] + + " ; argv[]=" + + " ".join(argv) + + " ; ignore_errors=no ; }", + "Environment": " ".join(json.dumps(entry) for entry in env), + } + ) + override = root / "daemon-properties.json" + if override.exists(): + values.update(json.loads(override.read_text())) + if not pid and record and (root / "replacement-on-exit").exists(): + values["InvocationID"] = "replacement-invocation" + for key, value in values.items(): + print(key + "=" + value) + sys.exit(0) + if command in {"enable", "disable", "reset-failed"}: + if command == "enable": + enabled.touch() + elif command == "disable": + enabled.unlink(missing_ok=True) + if (root / ("fail-after-" + command)).exists(): + sys.exit("command partially applied") + sys.exit(0) + if command == "start": + if not live(record.get("pid")): + data = loaded.read_text() + argv = shlex.split( + next( + line[10:] + for line in data.splitlines() + if line.startswith("ExecStart=") + ) + ) + argv[0] = argv[0].removeprefix(":") + argv = [arg.replace("%%", "%") for arg in argv] + env = dict(os.environ) + for line in data.splitlines(): + if line.startswith("Environment="): + key, value = shlex.split(line[12:])[0].split("=", 1) + env[key] = value.replace("%%", "%") + with (root / "daemon.log").open("ab") as log: + child = subprocess.Popen( + argv, env=env, stdout=log, stderr=log, start_new_session=True + ) + daemon_state.write_text( + json.dumps( + {"pid": child.pid, "invocation": str(child.pid), "path": str(path)} + ) + ) + gate = root / "start-reply-gate" + if gate.exists(): + (root / "start-submitted").touch() + with gate.open() as stream: + stream.read() + if (root / "fail-after-start").exists(): + sys.exit("start submitted but reply failed") + sys.exit(0) + if command == "stop": + if live(record.get("pid")): + os.kill(record["pid"], signal.SIGTERM) + sys.exit(0) + record = json.loads(state.read_text()) if state.exists() else {} command = args[0] if command == "print": diff --git a/docs/daemon-lifecycle.md b/docs/daemon-lifecycle.md index f8c5e65da..7c8b78163 100644 --- a/docs/daemon-lifecycle.md +++ b/docs/daemon-lifecycle.md @@ -47,6 +47,38 @@ It preserves the record and does not authorize attachment, shutdown, or launch. Stop that daemon with its matching client, then launch the protocol 3 client. The current client does not call older API routes. +## Daemon service + +On Linux, the first `albedo daemon install` creates, starts and enables a systemd user +service. Running it again refreshes the definition without restarting the daemon +or starting a stopped service. Installation requires a packaged daemon selected +by `ALBEDO_DAEMON`; checkout and AppImage launchers are unsupported. Stop a running +standalone daemon before first installation. + +Clients start an installed service through systemd. `albedo daemon --stop` uses +the existing HTTP shutdown and leaves the service stopped until a client or the +user manager starts it. Add `--kernels` to try saving variables before ending the kernels. +`albedo daemon uninstall` removes the service and keeps kernels for reconnection. +Use `albedo daemon status` to inspect it, or `status --json` for structured output. + +The unit uses `KillMode=process` so daemon stops leave kernels alive, and +`Restart=on-failure` so crashes restart. Exit 75 means storage is held elsewhere +and does not restart. Kernels end when the user manager exits or the host reboots. +A managed build mismatch prints a notice instead of offering a restart, because +the CLI cannot establish which build the service would start. + +The CLI can attach to a compatible daemon beside an edited or unsupported unit, +but refuses lifecycle changes. Fedora's unmodified global timeout-abort drop-in +is supported; other drop-ins are refused. On a systemd host, an unreachable user +manager also prevents launch and shutdown. Hosts without systemd, including +macOS, retain standalone launch. Real-manager checks covered systemd 249 and 257. + +A failed or cancelled install can leave a running service or enablement links. +Inspect its status before changing anything by hand. Before trying start or +enable, the installer may restore its unchanged file if the original process +is unchanged and no job appeared. After either attempt, it leaves configuration +in place and reports what it could observe. + ## Authentication and defaults Bearer authentication remains the same. The daemon owns its home directory and diff --git a/robot-docs/proxy.md b/robot-docs/proxy.md index 05ea03df3..e79ba7740 100644 --- a/robot-docs/proxy.md +++ b/robot-docs/proxy.md @@ -29,7 +29,7 @@ Each request logs its model, HTTP status and duration to `$ALBEDO_HOME/proxy.log If the daemon stops, the forwarder stays up and answers 503 with a message explaining how to start it again. A failed connection or daemon 401 refreshes the saved daemon endpoint, so a subsequent request reaches the replacement. A chat POST is never replayed automatically: retry it explicitly. Stopping the forwarder does not stop the daemon, and stopping it does not require a running daemon. -Ownership: `cli/internal/app/proxy.go` reads the extension choice and model catalog; `cli/internal/proxyserver` owns keys, authentication and forwarding; `cli/internal/cli/proxy*.go` owns command rendering and lifecycle. `cli/internal/cli/login_service.go` owns the shared login-service definitions and manager calls; `proxy_service.go` owns the proxy workflow. `ALBEDO_LAUNCHCTL` and `ALBEDO_SYSTEMCTL` can override the manager executables for OS-boundary tests. The listener reuses `webui.Access`, network parsing, tailnet discovery and HTTPS claims, and the CLI's shared detached-process helpers. +Ownership: `cli/internal/app/proxy.go` reads the extension choice and model catalog; `cli/internal/proxyserver` owns keys, authentication and forwarding; `cli/internal/cli/proxy*.go` owns command rendering and lifecycle. `cli/internal/loginservice` owns the shared login-service definitions and manager calls; `proxy_service.go` owns the proxy workflow. `ALBEDO_LAUNCHCTL` and `ALBEDO_SYSTEMCTL` can override the manager executables for OS-boundary tests. The listener reuses `webui.Access`, network parsing, tailnet discovery and HTTPS claims, and the CLI's shared detached-process helpers. ## endpoint diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index 80434c546..9c8ed6458 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -107,6 +107,13 @@ Discovery rejects a recorded pid that differs from the authenticated `/server` r A stalled startup reports the log path and leaves the detached process running; check that log before retrying. A child exit reports its startup log immediately. +The CLI connector sequences Linux daemon service operations; `localdaemon` +classifies daemon and manager observations, and `loginservice` writes and queries +units. Direct launch and upgrade recheck registration under `launcher.lock`. +`daemon --serve` execs the selected launcher without that lock and removes +`ALBEDO_PARENT_PID` and `ALBEDO_STANDBY*`. `LocalCommand` removes provider overrides. +See [daemon services](../docs/daemon-lifecycle.md#daemon-service). + ## standby A sealed build boots from a standby when one is waiting: a VM the CLI started diff --git a/test/e2e/harness.py b/test/e2e/harness.py index a53d4abab..a9e91c262 100644 --- a/test/e2e/harness.py +++ b/test/e2e/harness.py @@ -279,6 +279,7 @@ class Daemon: ALBEDO_HOME=str(self.home), ALBEDO_ROOT=str(ROOT), ALBEDO_NO_BROWSER="1", + ALBEDO_SYSTEMCTL=str(self.root / "no-systemctl"), ALBEDO_PARENT_PID=str(os.getpid()), ALBEDO_STANDBY_DIR=str(STANDBY_DIR), ERL_FLAGS=TEST_VM_FLAGS, diff --git a/test/manual/service_linux.py b/test/manual/service_linux.py new file mode 100644 index 000000000..cbb768185 --- /dev/null +++ b/test/manual/service_linux.py @@ -0,0 +1,229 @@ +"""Exercise production daemon service commands on a private systemd user unit. + +Run inside nix develop after building cli/bin/albedo. ALBEDO_TEST_DAEMON may +select an exec-only snapshot instead of a packaged daemon. Requires a user bus. +""" + +import hashlib +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import threading +import unittest + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "test/e2e")) +from harness import Albedo, Provider, alive, python, text, wait_until, exclusive # noqa: E402 + + +def run(): + actual_config = Path( + os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config")) + ) + cells = [] + + def script(request): + if request["input"][-1].get("role") == "user" and cells: + return python(cells.pop(0)) + return text("done") + + with tempfile.TemporaryDirectory(prefix="albedo service % $ ") as directory: + executable = Path(directory) / "albedo % $" + executable.symlink_to(ROOT / "cli/bin/albedo") + + def prepare(app): + app.env.pop("ALBEDO_SYSTEMCTL", None) + app.env.pop("ALBEDO_PARENT_PID", None) + app.env["XDG_CONFIG_HOME"] = str(actual_config) + app.env["ALBEDO_TEST_CLI"] = str(executable) + app.env["ALBEDO_ROOT"] = str(Path(directory) / "root with % $ `") + app.daemon.boot_action = lambda daemon: daemon.cli("daemon", "install") + + provider = Provider(script) + app = Albedo(provider, protocol="responses", prepare=prepare) + unit = None + home = None + try: + app.__enter__() + home = app.home + unit = ( + "systems.albedo.daemon-" + + hashlib.sha256(str(home).encode()).hexdigest()[:16] + + ".service" + ) + + def state(): + output = subprocess.check_output( + [ + "systemctl", + "--user", + "show", + unit, + "-p", + "MainPID", + "-p", + "ActiveState", + "-p", + "NRestarts", + ], + text=True, + ) + return dict(line.split("=", 1) for line in output.splitlines()) + + def cell(code): + cells.append(code) + app.prompt(session, "run it").close() + app.idle(session) + return [ + json.loads(part["value"]) + for entry in app.history(session)["items"] + if entry["kind"] == "tool_result" + and entry["tool"]["name"] == "python" + for part in entry["content"] + if part["kind"] == "json" and part["field"] == "result" + ][-1] + + session = app.session() + first = cell( + "hold = run('sleep', '120')\nimport os\nsurvivor = 41\nos.getpid()" + ) + kernel_pid = int(first["value"]) + assert int(state()["MainPID"]) == app.connection["pid"] + original = app.connection["pid"] + app.cli("daemon", "install") + assert app.connection["pid"] == original + assert int(state()["MainPID"]) == original + restarts = state()["NRestarts"] + app.cli("daemon", "--stop") + assert state()["ActiveState"] == "inactive" + assert state()["NRestarts"] == restarts + assert alive(kernel_pid) + app.daemon.connection = None + app.cli("daemon") + app.daemon.await_ready() + adopted = cell("survivor += 1\n(survivor, os.getpid())") + assert adopted["value"] == f"(42, {kernel_pid})", adopted + subprocess.run(["systemctl", "--user", "stop", unit], check=True) + assert alive(kernel_pid) + app.daemon.connection = None + app.cli("daemon") + app.daemon.await_ready() + adopted = cell("survivor += 1\n(survivor, os.getpid())") + assert adopted["value"] == f"(43, {kernel_pid})", adopted + app.cli("daemon", "--stop", "--kernels") + wait_until(lambda: not alive(kernel_pid), 10, "kernel survived --kernels") + assert state()["ActiveState"] == "inactive" + app.daemon.connection = None + app.cli("daemon") + app.daemon.await_ready() + assert cell("survivor")["value"] == "43" + old = app.connection["pid"] + os.kill(old, signal.SIGKILL) + wait_until( + lambda: int(state()["MainPID"]) not in (0, old), + 20, + "service did not restart after crash", + ) + app.daemon.connection = None + app.daemon.await_ready() + app.cli("daemon", "--stop", "--kernels") + direct = subprocess.Popen( + [app.env["ALBEDO_DAEMON"]], + env=app.env, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + threading.Thread(target=direct.wait, daemon=True).start() + try: + app.daemon.connection = None + app.daemon.await_ready() + subprocess.run( + ["systemctl", "--user", "reset-failed", unit], check=True + ) + subprocess.run( + ["systemctl", "--user", "start", unit], + check=False, + capture_output=True, + ) + wait_until( + lambda: state()["ActiveState"] == "failed", + 10, + "contended service did not fail", + ) + status = subprocess.check_output( + [ + "systemctl", + "--user", + "show", + unit, + "-p", + "ExecMainStatus", + "-p", + "NRestarts", + ], + text=True, + ) + assert "ExecMainStatus=75" in status and "NRestarts=0" in status, status + app.cli("daemon", "--stop", "--kernels") + direct.wait(timeout=10) + finally: + if direct.poll() is None: + direct.terminate() + direct.wait(timeout=20) + app.cli("daemon", "uninstall") + app.cli("daemon") + app.daemon.connection = None + app.daemon.await_ready() + assert int(state()["MainPID"]) == 0 + app.cli("daemon", "--stop", "--kernels") + print( + "real systemd installation, refresh, shutdown, kernel adoption/save, crash restart and uninstall passed" + ) + finally: + # Only this fixture's conventional unit and processes are touched. + if home is None and getattr(app, "home", None) is not None: + home = app.home + if unit is None and home is not None: + unit = ( + "systems.albedo.daemon-" + + hashlib.sha256(str(home).encode()).hexdigest()[:16] + + ".service" + ) + if unit is not None: + subprocess.run( + ["systemctl", "--user", "stop", unit], capture_output=True + ) + subprocess.run( + ["systemctl", "--user", "disable", unit], capture_output=True + ) + (actual_config / "systemd/user" / unit).unlink(missing_ok=True) + subprocess.run( + ["systemctl", "--user", "daemon-reload"], capture_output=True + ) + subprocess.run( + ["systemctl", "--user", "reset-failed", unit], capture_output=True + ) + app.__exit__(None, None, None) + provider.close() + + +@exclusive +class RealServiceTests(unittest.TestCase): + def test_native_service_lifecycle(self): + run() + + +if __name__ == "__main__": + raise SystemExit( + subprocess.run( + [ + sys.executable, + str(ROOT / "test/e2e/run.py"), + str(Path(__file__).resolve()), + ] + ).returncode + )