//go:build linux // The systemd service reconciler (install, uninstall, start through Connect, // stop, status) runs here against a fake user manager and fake daemons, over // generated histories that mix CLI commands with crashes, upgrades, // standalone daemons, foreign and declared registrations, drift, and a fault // on one manager call. Every step checks the reconciler's invariants: one // daemon at most, every live daemon reachable through daemon.json, a unit file // that is the previous one or the wanted definition, untouched foreign and // declared files, shutdowns only of daemons the command observed, no // name-addressed stop, no direct launch beside a registration, refusal of // lifecycle changes the CLI cannot prove safe, and a failed command that a // retry completes. Reaching these orderings through a real manager and daemon // costs seconds per case, so one end-to-end journey // (cli/test/e2e/daemon_service_test.go) checks only the wiring. package entrypoint import ( "bytes" "context" "io" "os" "path/filepath" "slices" "strings" "testing" "time" "albedo/cli/internal/localdaemon" "albedo/cli/internal/loginservice" "albedo/cli/internal/property" "albedo/cli/internal/terminal" "albedo/cli/internal/testwire" "pgregory.net/rapid" ) // allowedVerbs bounds what each command may ask of the manager. Install never // stops or disables what it started, uninstall never starts, and stopping is // always an HTTP shutdown of an observed instance. var allowedVerbs = map[string][]string{ "install": {"show", "daemon-reload", "start", "reset-failed", "enable"}, "uninstall": {"show", "disable", "daemon-reload"}, "connect": {"show", "reset-failed", "start"}, "stop": {"show"}, "status": {"show"}, } // faultVerbs weights the verbs a fault lands on toward the mutations that // decide between rollback and leaving configuration in place. var faultVerbs = map[string][]string{ "install": {"show", "daemon-reload", "daemon-reload", "start", "start", "enable", "enable", "reset-failed"}, "uninstall": {"show", "disable", "disable", "daemon-reload", "daemon-reload"}, "connect": {"show", "start", "start", "reset-failed"}, "stop": {"show"}, } // serviceWorld is one generated history's home, manager, and the model's // record of what the test arranged outside the CLI. type serviceWorld struct { t tester rt *rapid.T // draws; nil when a test drives the world without generating cleanup func(func()) manager *fakeManager tally map[string]int home string // launcher and wrapper are the ALBEDO_DAEMON values of an exec and a // non-exec launcher. launcher string wrapper string owned string // the CLI's unit name ownedPath string declared string declPath string declTarget string // foreign holds the bytes, or the link target, of a file at the CLI's // unit path that the CLI does not own. foreign []byte // companion is a regular file under the declared name, not a declaration. companion []byte concurrent []byte // what a concurrent install wrote during the last command foreignLink bool isDeclared bool declMissing bool // the declaration's file was removed while it stays loaded replace bool // the manager starts a replacement as the main process drains } func TestDaemonServiceReconcilerModel(t *testing.T) { checker, err := testwire.NewChecker() if err != nil { t.Fatal(err) } for _, key := range []string{"HOME", "XDG_CONFIG_HOME", "ALBEDO_DAEMON", "ALBEDO_ROOT", "ALBEDO_SYSTEMCTL", "ALBEDO_APPIMAGE_DAEMON", "APPIMAGE"} { t.Setenv(key, "") } // The fake daemons report this build, so no restart is offered. t.Setenv("ALBEDO_BUILD", "fake-build") t.Setenv("ALBEDO_STANDBY", "0") tally := map[string]int{} property.Check(t, func(rt *rapid.T) { world := newServiceWorld(t, rt, rt, rt.Cleanup, checker, tally) defer world.manager.close() // Histories begin from an empty home, a home-manager declaration, or // an installed service. switch rapid.SampledFrom([]string{"empty", "declared", "installed", "installed"}).Draw(rt, "opening") { case "declared": world.event("declare") case "installed": world.command("install") } for range rapid.IntRange(1, 40).Draw(rt, "steps") { world.step() } for _, failure := range checker.Failures() { rt.Fatalf("OpenAPI: %v", failure) } }) // The generator must keep reaching the interactions the invariants are about. requireReached(t, tally, "install new", "install refresh running", "install refresh idle", "install refused before contact", "install refused", "install restored", "install preserved external change", "drift reconciled", "non-exec refused", "uninstall ok", "uninstall refused", "connect started", "connect attached", "connect refused", "direct launch", "declared start", "stop ok", "stop refused", "replacement survived", "retry ok", "fault cancel", "crash restart", ) } // requireReached fails the test for each event no generated case reached, // when properties run as the gate runs them. The events are tuned to the // gate's seed and budget; a fresh seed in a discovery run that misses one // has found no defect, so there it is only logged. func requireReached(t *testing.T, tally map[string]int, events ...string) { t.Helper() for _, event := range events { if tally[event] != 0 { continue } if property.AtGate() { t.Errorf("no generated case reached %q", event) } else { t.Logf("no generated case reached %q under this seed", event) } } t.Logf("events: %v", tally) } // newServiceWorld makes a fresh home and manager. rt is nil when the caller // drives the world without generating. // Every fault one install can meet, from an empty home and from an idle and a // running service whose wanted definition changed, goes through the same // checks as the generated histories. The rollback rules depend on exactly // which call fails and how, which random histories reach too rarely to pin. func TestDaemonServiceInstallFaultMatrix(t *testing.T) { checker, err := testwire.NewChecker() if err != nil { t.Fatal(err) } for _, key := range []string{"HOME", "XDG_CONFIG_HOME", "ALBEDO_DAEMON", "ALBEDO_ROOT", "ALBEDO_SYSTEMCTL", "ALBEDO_APPIMAGE_DAEMON", "APPIMAGE"} { t.Setenv(key, "") } t.Setenv("ALBEDO_BUILD", "fake-build") t.Setenv("ALBEDO_STANDBY", "0") tally := map[string]int{} verbs := []string{"show", "daemon-reload", "start", "enable", "reset-failed"} for _, opening := range []string{"empty", "idle", "running"} { for _, verb := range verbs { calls := []int{1} if verb == "show" { calls = []int{1, 2, 3} } changes := []int{0} if verb == "daemon-reload" { changes = []int{0, 1, 2, 3, 4} } for _, nth := range calls { for mode := faultBefore; mode <= faultCancel; mode++ { for _, choice := range changes { var cleanups []func() world := newServiceWorld(t, t, nil, func(f func()) { cleanups = append(cleanups, f) }, checker, tally) if opening != "empty" { world.execute("install", nil, "") if opening == "idle" { world.execute("stop", nil, "") } setenv(t, "ALBEDO_ROOT", "/opt/albedo-b") } f := &fault{verb: verb, nth: nth, mode: mode} var change string change, f.alongside = world.alongside(choice) t.Logf("%s install with %v %s", opening, f, change) world.execute("install", f, change) world.checkAlways() world.manager.close() for _, cleanup := range cleanups { cleanup() } } } } } } for _, failure := range checker.Failures() { t.Errorf("OpenAPI: %v", failure) } for _, event := range []string{"install restored", "install preserved external change", "retry ok"} { if tally[event] == 0 { t.Errorf("no install fault reached %q", event) } } } func newServiceWorld(t *testing.T, tt tester, rt *rapid.T, cleanup func(func()), checker *testwire.Checker, tally map[string]int) *serviceWorld { root, err := os.MkdirTemp(t.TempDir(), "case") if err != nil { tt.Fatal(err) } // The default home, so a declared registration can serve it, under a // user home whose name needs escaping in a unit. userHome := filepath.Join(root, "user with % and $") home := filepath.Join(userHome, ".albedo") bin := filepath.Join(root, "bin") for _, dir := range []string{home, bin} { if err = os.MkdirAll(dir, 0700); err != nil { tt.Fatal(err) } } // A direct launch only records that it happened. script := []byte("#!/bin/sh\ntouch \"$ALBEDO_HOME/direct-launch\"\nexit 1\n") launcher, wrapper := filepath.Join(bin, "albedo-daemon"), filepath.Join(bin, "non-exec-launcher") for _, path := range []string{launcher, wrapper} { if err = os.WriteFile(path, script, 0700); err != nil { tt.Fatal(err) } } setenv(tt, "HOME", userHome) setenv(tt, "ALBEDO_DAEMON", launcher) setenv(tt, "ALBEDO_ROOT", "/opt/albedo-a") unit, err := loginservice.ForDaemon(home) if err != nil { tt.Fatal(err) } declPath := filepath.Join(filepath.Dir(unit.Path()), "albedo.service") manager := newFakeManager(checker, home, map[string]string{unit.Name(): unit.Path(), "albedo.service": declPath}, wrapper) cleanup(loginservice.UseSystemctl(manager.run)) return &serviceWorld{t: tt, rt: rt, cleanup: cleanup, manager: manager, home: home, launcher: launcher, wrapper: wrapper, owned: unit.Name(), ownedPath: unit.Path(), declared: "albedo.service", declPath: declPath, declTarget: filepath.Join(root, "declared.service"), tally: tally} } // tester is what the model's checks need from *testing.T or *rapid.T. type tester interface { Fatal(args ...any) Fatalf(format string, args ...any) Logf(format string, args ...any) } // setenv changes a variable the test registered with t.Setenv, which // restores it. func setenv(t tester, key, value string) { if err := os.Setenv(key, value); err != nil { t.Fatal(err) } } // wanted is the definition the CLI should install from the current // environment, worked out from the documented capture rules. func (w *serviceWorld) wanted() (string, []string) { executable, err := os.Executable() if err != nil { w.t.Fatal(err) } environment := []string{"ALBEDO_HOME=" + w.home, "PATH=" + os.Getenv("PATH"), "ALBEDO_ROOT=" + os.Getenv("ALBEDO_ROOT"), "ALBEDO_DAEMON=" + os.Getenv("ALBEDO_DAEMON")} slices.Sort(environment) return executable, environment } func (w *serviceWorld) matchesWanted(data []byte) bool { executable, environment, ok := parseUnitCommand(data) slices.Sort(environment) wantExecutable, wantEnvironment := w.wanted() return ok && executable == wantExecutable && slices.Equal(environment, wantEnvironment) } func readOptional(path string) []byte { data, err := os.ReadFile(path) if err != nil { return nil } return data } func (w *serviceWorld) step() { commands := []string{"install", "install", "uninstall", "connect", "connect", "stop", "stop", "status"} events := []string{ "upgrade", "upgrade", "crash", "crash", "standalone", "foreign", "declare", "declared drift", "declaration removed", "unblock", "unblock", "unblock", "drift", "drift", "interrupted refresh", "killmode", "transition", "replacement", "replacement", "elsewhere", "manager down", } choices := commands if rapid.IntRange(0, 2).Draw(w.rt, "event") == 0 { choices = events } kind := rapid.SampledFrom(choices).Draw(w.rt, "operation") if slices.Contains(commands, kind) { w.command(kind) } else { w.event(kind) } w.checkAlways() } // event changes the world the way the user, the manager, or another owner // would between commands. func (w *serviceWorld) event(kind string) { m := w.manager switch kind { case "upgrade": setenv(w.t, "ALBEDO_ROOT", rapid.SampledFrom([]string{"/opt/albedo-a", "/opt/albedo-b"}).Draw(w.rt, "root")) setenv(w.t, "ALBEDO_DAEMON", rapid.SampledFrom([]string{w.launcher, w.launcher, w.wrapper}).Draw(w.rt, "launcher")) return case "crash": restart := rapid.Bool().Draw(w.rt, "restart") for _, name := range []string{w.owned, w.declared} { if m.unit(name).main.isAlive() { m.crash(name, restart) if restart { w.tally["crash restart"]++ } } } for _, d := range m.live() { if rapid.Bool().Draw(w.rt, "crash standalone") { d.exit(true) } } return case "standalone": if len(m.live()) == 0 { if _, err := m.startDaemon(); err != nil { w.t.Fatal(err) } } return case "foreign": if w.foreign != nil || readOptional(w.ownedPath) != nil { return } if err := os.MkdirAll(filepath.Dir(w.ownedPath), 0700); err != nil { w.t.Fatal(err) } if w.foreignLink = rapid.Bool().Draw(w.rt, "symlink"); w.foreignLink { w.foreign = []byte(filepath.Join(w.home, "missing-target")) if err := os.Symlink(string(w.foreign), w.ownedPath); err != nil { w.t.Fatal(err) } } else { w.foreign = []byte("[Service]\nExecStart=/usr/bin/other\n") if err := os.WriteFile(w.ownedPath, w.foreign, 0600); err != nil { w.t.Fatal(err) } } return case "declare": if w.isDeclared || w.companion != nil { return } data := w.declaration() if err := os.MkdirAll(filepath.Dir(w.declPath), 0700); err != nil { w.t.Fatal(err) } if err := os.WriteFile(w.declTarget, data, 0600); err != nil { w.t.Fatal(err) } if err := os.Symlink(w.declTarget, w.declPath); err != nil { w.t.Fatal(err) } m.mu.Lock() m.unit(w.declared).loaded, m.unit(w.declared).enabled = data, true m.mu.Unlock() w.isDeclared = true return case "unblock": // Whoever owns an external registration or state removes it. if w.foreign != nil { _ = os.Remove(w.ownedPath) w.foreign = nil } if w.companion != nil { _ = os.Remove(w.declPath) w.companion = nil } if w.isDeclared && !m.unit(w.declared).main.isAlive() { _ = os.Remove(w.declPath) m.mu.Lock() m.unit(w.declared).loaded = nil m.mu.Unlock() w.isDeclared, w.declMissing = false, false } m.mu.Lock() m.unit(w.owned).override, m.unit(w.owned).transition, m.down, w.replace = nil, 0, false, false m.mu.Unlock() return } m.mu.Lock() defer m.mu.Unlock() owned, declared := m.unit(w.owned), m.unit(w.declared) switch kind { case "declared drift": // The loaded declaration serves another home than the file says. if w.isDeclared { declared.loaded = bytes.Replace(declared.loaded, []byte("ALBEDO_HOME="), []byte("ALBEDO_HOME=/elsewhere"), 1) } case "declaration removed": if w.isDeclared && !w.declMissing { _ = os.Remove(w.declPath) w.declMissing = true } case "drift": // The loaded definition names an executable the file no longer does. if owned.loaded != nil { executable, _, _ := parseUnitCommand(owned.loaded) owned.loaded = bytes.ReplaceAll(owned.loaded, []byte(executable), []byte("/old/bin/albedo")) owned.hideReload = rapid.Bool().Draw(w.rt, "reload flag hidden") } case "interrupted refresh": // A refresh rewrote the file and stopped before its reload. if file := readOptional(w.ownedPath); owned.loaded != nil && w.foreign == nil && bytes.Equal(file, owned.loaded) { edited := strings.Replace(string(file), "ALBEDO_ROOT=", "ALBEDO_ROOT=/interrupted", 1) if err := os.WriteFile(w.ownedPath, []byte(edited), 0600); err != nil { w.t.Fatal(err) } } case "killmode": if owned.loaded != nil { owned.override = map[string]string{"KillMode": "control-group"} } case "transition": if owned.loaded != nil && !owned.main.isAlive() { owned.transition = rapid.IntRange(1, 3).Draw(w.rt, "transition") } case "replacement": w.replace = true case "elsewhere": // The manager loads this name from a file the CLI does not own. if owned.loaded == nil && readOptional(w.ownedPath) == nil && w.foreign == nil { owned.override = map[string]string{"LoadState": "loaded", "FragmentPath": "/etc/systemd/user/" + w.owned} } case "manager down": m.down = true } } // declaration renders the home-manager sample for this home. func (w *serviceWorld) declaration() []byte { executable, _ := w.wanted() quote := func(value string) string { return strings.NewReplacer(`\`, `\\`, `"`, `\"`, "%", "%%").Replace(value) } sample, err := os.ReadFile("../loginservice/testdata/home-manager/daemon.service") if err != nil { w.t.Fatal(err) } return []byte(strings.NewReplacer("@HOME@", quote(w.home), "@EXECUTABLE@", quote(executable), "@PATH@", quote(os.Getenv("PATH"))).Replace(string(sample))) } // state is the model's view of the world when a command begins. type state struct { shutdowns map[*fakeDaemon]int file, loaded []byte live []*fakeDaemon calls int lock bool enabled bool managed bool // a unit runs the live daemon registered bool // the CLI's unit has a file or a loaded definition foreign bool // a file the CLI does not own sits at a name it checks declared bool conflict bool // both names are registered unsupported bool // a state the CLI must not change, though it may attach transition bool replace bool // onlyDrift: the one unsupported thing is a loaded definition that // differs from the CLI's own file, which install reconciles. onlyDrift bool // halfRegistered: the CLI's file without a loaded unit, or a loaded unit // without its file. Install and uninstall reconcile it; nothing else // changes it. halfRegistered bool nonExecWanted bool // the next installation uses a non-exec launcher nonExecLoaded bool // the next start uses a non-exec launcher declMissing bool } func (w *serviceWorld) state() state { m := w.manager m.mu.Lock() defer m.mu.Unlock() owned, declared := m.unit(w.owned), m.unit(w.declared) s := state{file: readOptional(w.ownedPath), loaded: owned.loaded, live: m.live(), calls: len(m.calls), enabled: owned.enabled, managed: owned.main.isAlive() || declared.main.isAlive(), replace: w.replace} _, lockErr := os.Stat(filepath.Join(w.home, "launcher.lock")) s.lock = lockErr == nil s.shutdowns = map[*fakeDaemon]int{} for _, d := range m.daemons { d.mu.Lock() s.shutdowns[d] = d.shutdowns d.mu.Unlock() } s.registered = s.file != nil && w.foreign == nil || owned.loaded != nil s.foreign = w.foreign != nil || w.companion != nil s.declared = w.isDeclared s.conflict = w.isDeclared && s.registered drifted := owned.loaded != nil && s.file != nil && !bytes.Equal(owned.loaded, s.file) // A main process that is a non-exec launcher's, not the daemon's. nonExec := owned.main.isAlive() && owned.wrapper != nil declaredDrift := w.isDeclared && (w.declMissing || !bytes.Equal(declared.loaded, readOptional(w.declTarget))) // A loaded, enabled unit whose file someone removed cannot be disabled. removedEnabled := w.foreign == nil && s.file == nil && owned.loaded != nil && owned.enabled s.unsupported = s.foreign || s.conflict || owned.override != nil || drifted || nonExec || m.down || declaredDrift || removedEnabled s.onlyDrift = drifted && !s.foreign && !s.conflict && owned.override == nil && !nonExec && !m.down && !declaredDrift s.transition = owned.transition > 0 s.halfRegistered = w.foreign == nil && (s.file != nil) != (owned.loaded != nil) s.nonExecWanted = os.Getenv("ALBEDO_DAEMON") == w.wrapper _, loadedEnvironment, _ := parseUnitCommand(owned.loaded) s.nonExecLoaded = slices.Contains(loadedEnvironment, "ALBEDO_DAEMON="+w.wrapper) s.declMissing = w.declMissing return s } func (w *serviceWorld) run(command string, f *fault) error { m := w.manager ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() m.mu.Lock() m.fault, m.fired, m.cancel, m.counts = f, false, cancel, map[string]int{} replace := w.replace m.mu.Unlock() for _, d := range m.live() { d.mu.Lock() d.replaceOnDrain = replace d.mu.Unlock() } defer func() { m.mu.Lock() m.fault, m.cancel = nil, nil m.mu.Unlock() }() // Each command is a fresh CLI process. c := &connector{options: localdaemon.LocalOptions{HomeDir: w.home}, term: &terminal.Service{In: strings.NewReader(""), Out: io.Discard, Err: io.Discard}} switch command { case "install": _, err := c.Install(ctx) return err case "uninstall": _, err := c.Uninstall(ctx) return err case "stop": return c.Stop(ctx, false) case "status": _, err := c.Status(ctx) return err case "connect": connection, err := c.Connect(ctx) if err == nil { connection.HTTPClient().CloseIdleConnections() } return err } panic(command) } // alongside picks what changes outside the CLI while a faulted daemon-reload // is in flight; the installer must then leave everything in place. func (w *serviceWorld) alongside(choice int) (string, func()) { m := w.manager switch choice { case 1: return "external edit", func() { if data := readOptional(w.ownedPath); data != nil { _ = os.WriteFile(w.ownedPath, append(data, "# external edit\n"...), 0600) } } case 2: return "companion", func() { if readOptional(w.declPath) == nil && !w.isDeclared { _ = os.WriteFile(w.declPath, []byte("[Unit]\nDescription=another registration\n"), 0600) } } case 3: return "manager down", func() { m.down = true } case 4: // Another install writes its own valid definition. return "concurrent install", func() { if data := readOptional(w.ownedPath); data != nil { _ = os.WriteFile(w.ownedPath, bytes.Replace(data, []byte("ALBEDO_ROOT="), []byte("ALBEDO_ROOT=/concurrent"), 1), 0600) w.concurrent = readOptional(w.ownedPath) } } } return "", nil } func (w *serviceWorld) command(command string) { var f *fault var change string if command != "status" && rapid.IntRange(0, 2).Draw(w.rt, "faulted") == 0 { f = &fault{ verb: rapid.SampledFrom(faultVerbs[command]).Draw(w.rt, "fault verb"), // Most verbs run once per command; a later call is rarer. nth: rapid.SampledFrom([]int{1, 1, 1, 2, 3, 4}).Draw(w.rt, "fault call"), mode: faultMode(rapid.IntRange(0, 2).Draw(w.rt, "fault mode")), } if command == "install" && f.verb == "daemon-reload" { change, f.alongside = w.alongside(rapid.IntRange(0, alongsideChoices-1).Draw(w.rt, "alongside")) } } w.execute(command, f, change) } // alongsideChoices counts alongside's choices, the first of which is none. const alongsideChoices = 5 // execute runs a command with a fault, if any, and checks the outcome. func (w *serviceWorld) execute(command string, f *fault, change string) { w.concurrent = nil before := w.state() err := w.run(command, f) fired := w.manager.fired w.t.Logf("%s fault=%v %s fired=%v: %v", command, f, change, fired, err) w.checkCommand(command, before) if fired && change != "" { w.adoptExternalChange(change) } switch { case fired && change != "": w.checkExternalChange(before, err, change) case fired: if f.mode == faultCancel { w.tally["fault cancel"]++ } w.checkFaulted(command, before, err, f) if err != nil && w.verdict(command, w.state()) == expectOK { // A failed verb leaves state a plain retry completes. again := w.state() retryErr := w.run(command, nil) w.checkCommand(command, again) if retryErr != nil { w.t.Fatalf("retry of %s after %v: %v", command, f, retryErr) } w.tally["retry ok"]++ w.checkVerdict(command, again, nil) } default: w.checkVerdict(command, before, err) } } // adoptExternalChange records a change made alongside a fault as part of the // world, so later steps hold the CLI to it. func (w *serviceWorld) adoptExternalChange(change string) { switch change { case "external edit": if data := readOptional(w.ownedPath); data != nil && bytes.HasSuffix(data, []byte("# external edit\n")) { w.foreign, w.foreignLink = data, false } case "companion": if data := readOptional(w.declPath); data != nil && !w.isDeclared { w.companion = data } } } type verdict int const ( expectOK verdict = iota expectRefusal expectRefusalBeforeContact expectAny ) // verdict is the model's expected outcome of a command without faults, // derived from the documented service contract. func (w *serviceWorld) verdict(command string, s state) verdict { switch command { case "status": return expectOK case "install", "uninstall": // A file under either name that the CLI does not own refuses before // the launcher lock or the manager is touched. if s.foreign || s.declared && !s.declMissing { return expectRefusalBeforeContact } if command == "uninstall" && s.replace && s.managed { return expectAny } if s.transition || s.unsupported && (command == "uninstall" || !s.onlyDrift) { return expectRefusal } if command == "install" { nonExec := s.nonExecWanted // A first installation needs the home free of standalone daemons, // and a non-exec launcher never yields a daemon the unit owns. if !s.registered && len(s.live) > 0 || !s.registered && nonExec { return expectRefusal } if nonExec { return expectAny } } return expectOK case "stop": if s.unsupported || s.halfRegistered { return expectRefusal } if s.replace && s.managed { return expectRefusal } return expectOK case "connect": if (s.unsupported || s.halfRegistered) && len(s.live) == 0 { return expectRefusal } if !s.registered && !s.declared && len(s.live) == 0 { // The test's launcher refuses a direct launch. return expectRefusal } if s.nonExecLoaded && len(s.live) == 0 { // The start is submitted, then its main process is not the daemon. return expectAny } return expectOK } panic(command) } func (w *serviceWorld) checkVerdict(command string, before state, err error) { after := w.state() switch w.verdict(command, before) { case expectRefusalBeforeContact: if err == nil { w.t.Fatalf("%s accepted a registration the CLI does not own", command) } if after.calls != before.calls || !before.lock && after.lock { w.t.Fatalf("%s contacted the manager or took the launcher lock before refusing", command) } w.tally[command+" refused before contact"]++ return case expectRefusal: if err == nil { w.t.Fatalf("%s succeeded where the CLI must refuse", command) } w.tally[command+" refused"]++ if command == "connect" && slices.Contains(w.callVerbs(before), "start") { w.t.Fatal("connect started a service it could not prove safe") } if command == "stop" && before.replace && before.managed { if len(after.live) == 1 && !slices.Contains(before.live, after.live[0]) { w.tally["replacement survived"]++ } return } if command == "install" && !before.registered && before.nonExecWanted && len(before.live) == 0 && !before.unsupported && !before.transition { // The unit is left in place for inspection. if after.file == nil { w.t.Fatal("install removed the registration of a non-exec launcher") } w.tally["non-exec refused"]++ return } if !slices.Equal(before.live, after.live) { w.t.Fatalf("refused %s changed the running daemons", command) } if command != "connect" && !bytes.Equal(before.file, after.file) { w.t.Fatalf("refused %s rewrote the unit file", command) } return case expectAny: return } if err != nil { w.t.Fatalf("%s failed in a world the CLI owns: %v", command, err) } unit := w.manager.unit(w.owned) switch command { case "install": if !w.matchesWanted(after.file) || !bytes.Equal(after.loaded, after.file) { w.t.Fatalf("installed unit is not the wanted definition loaded by the manager:\n%s", after.file) } if before.loaded != nil && !bytes.Equal(before.loaded, before.file) { w.tally["drift reconciled"]++ } switch { case (before.loaded == nil || before.file == nil) && len(before.live) == 0: // Without both a file and its loaded unit this is a first // installation, completing whatever an earlier attempt left. w.tally["install new"]++ if !unit.main.isAlive() || !after.enabled { w.t.Fatal("first installation did not leave an enabled service running the daemon") } case len(before.live) > 0: w.tally["install refresh running"]++ if !slices.Equal(before.live, after.live) { w.t.Fatal("refreshing the definition replaced a running daemon") } default: w.tally["install refresh idle"]++ if len(after.live) != 0 { w.t.Fatal("refreshing the definition started a stopped service") } } // Every installation ends enabled, including one that completes an // earlier attempt whose start reply was lost. if !after.enabled { w.t.Fatal("install left the service disabled") } case "uninstall": w.tally["uninstall ok"]++ if after.file != nil || after.loaded != nil || after.enabled || unit.main.isAlive() { w.t.Fatal("uninstall left a registration or its daemon") } case "stop": w.tally["stop ok"]++ if len(after.live) != 0 { w.t.Fatal("stop left a daemon running") } case "connect": if len(after.live) != 1 { w.t.Fatalf("connect left %d daemons", len(after.live)) } if len(before.live) > 0 { w.tally["connect attached"]++ if !slices.Equal(before.live, after.live) { w.t.Fatal("connect replaced a running daemon") } } else { w.tally["connect started"]++ if !unit.main.isAlive() && !w.manager.unit(w.declared).main.isAlive() { w.t.Fatal("connect started a daemon outside the service") } } } } func (w *serviceWorld) callVerbs(before state) []string { m := w.manager m.mu.Lock() defer m.mu.Unlock() var verbs []string for _, call := range m.calls[before.calls:] { verbs = append(verbs, call[0]) } return verbs } // checkFaulted: install that fails before any start or enable leaves the // previous file loaded and the daemons as they were, and a submitted start is // never undone. func (w *serviceWorld) checkFaulted(command string, before state, err error, f *fault) { if command != "install" || err == nil { return } verbs := w.callVerbs(before) attempted := slices.Contains(verbs, "start") || slices.Contains(verbs, "enable") || slices.Contains(verbs, "reset-failed") after := w.state() if !attempted { // Either nothing was published, or the previous file was put back and // reloaded. if !bytes.Equal(after.file, before.file) || !bytes.Equal(after.loaded, before.loaded) && !bytes.Equal(after.loaded, before.file) { w.t.Fatalf("install failed at %v before starting anything but left file %q loaded as %q, not the previous %q", f, after.file, after.loaded, before.file) } if !slices.Equal(before.live, after.live) { w.t.Fatalf("install failed at %v and changed the running daemons", f) } if before.file != nil && !w.matchesWanted(before.file) || before.file == nil && slices.Contains(verbs, "daemon-reload") { w.tally["install restored"]++ } } if slices.Contains(verbs, "start") && after.file == nil { w.t.Fatal("install removed its registration after submitting a start") } } // checkExternalChange: when something outside the CLI changes the service // while its reload fails, the installer submits nothing more and leaves the // changed configuration in place. func (w *serviceWorld) checkExternalChange(before state, err error, change string) { if err == nil { w.t.Fatalf("install succeeded although its reload failed during a %s", change) } var mutations []string for _, verb := range w.callVerbs(before) { if verb != "show" { mutations = append(mutations, verb) } } if !slices.Equal(mutations, []string{"daemon-reload"}) { w.t.Fatalf("install submitted %v after a %s", mutations, change) } if change == "concurrent install" && w.concurrent != nil && !bytes.Equal(readOptional(w.ownedPath), w.concurrent) { w.t.Fatal("install overwrote a definition written during its failed reload") } w.tally["install preserved external change"]++ } // checkCommand holds for every command in every world. func (w *serviceWorld) checkCommand(command string, before state) { m := w.manager m.mu.Lock() calls := slices.Clone(m.calls[before.calls:]) m.mu.Unlock() for _, call := range calls { if !slices.Contains(allowedVerbs[command], call[0]) { w.t.Fatalf("%s asked the manager to %v", command, call) } if call[0] != "show" && len(call) > 1 && call[1] == w.declared { // Starting a declared registration is allowed; changing it is not. if call[0] != "start" && call[0] != "reset-failed" { w.t.Fatalf("%s changed the declared registration: %v", command, call) } if call[0] == "start" { w.tally["declared start"]++ } } } direct := filepath.Join(w.home, "direct-launch") if _, statErr := os.Stat(direct); statErr == nil { _ = os.Remove(direct) w.tally["direct launch"]++ if command != "connect" || before.registered || before.declared || before.unsupported || len(before.live) > 0 { w.t.Fatalf("%s launched a daemon directly beside a registration, a daemon, or an unknown manager state", command) } } // Shutdown reaches only daemons that were running when the command began. for d, count := range w.state().shutdowns { if count > before.shutdowns[d] && !slices.Contains(before.live, d) { w.t.Fatalf("%s shut down %s, which started during the command", command, d.instance) } } } // checkAlways holds between any two steps. func (w *serviceWorld) checkAlways() { m := w.manager m.mu.Lock() violations := slices.Clone(m.violations) m.mu.Unlock() if len(violations) > 0 { w.t.Fatalf("manager or daemon contract violated: %v", violations) } live := m.live() if len(live) > 1 { w.t.Fatalf("%d daemons serve one home", len(live)) } if len(live) == 1 { found, err := localdaemon.Discover(context.Background(), w.home) if err != nil || found.Snapshot.InstanceID != live[0].instance { w.t.Fatalf("the live daemon %s is not the one daemon.json names: %+v %v", live[0].instance, found.Snapshot, err) } } switch { case w.foreign != nil && w.foreignLink: if target, err := os.Readlink(w.ownedPath); err != nil || target != string(w.foreign) { w.t.Fatal("a foreign unit symlink changed") } case w.foreign != nil: if data, err := os.ReadFile(w.ownedPath); err != nil || !bytes.Equal(data, w.foreign) { w.t.Fatal("a unit file the CLI does not own changed") } default: if data := readOptional(w.ownedPath); data != nil { if _, _, ok := parseUnitCommand(data); !ok { w.t.Fatalf("the CLI's unit file is not a generated definition:\n%s", data) } } } if w.companion != nil && !bytes.Equal(readOptional(w.declPath), w.companion) { w.t.Fatal("the companion registration changed") } if w.isDeclared && !w.declMissing { if target, err := os.Readlink(w.declPath); err != nil || target != w.declTarget { w.t.Fatal("the declared registration changed") } } entries, _ := os.ReadDir(filepath.Dir(w.ownedPath)) for _, entry := range entries { if strings.HasPrefix(entry.Name(), ".albedo-unit-") { w.t.Fatalf("a temporary unit file was left behind: %s", entry.Name()) } } }