use std::ffi::OsString;
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::time::Duration;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use crate::launchd;
pub const DEFAULT_UNIT: &str = "second-brain.service";
pub const DEFAULT_BIND: &str = "127.0.0.1:7200";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Manager {
Systemd,
Launchd,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Os {
Linux,
MacOs,
}
impl Os {
pub fn current() -> Self {
if cfg!(target_os = "macos") {
Os::MacOs
} else {
Os::Linux
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
Start,
Stop,
Restart,
}
impl Action {
fn as_str(self) -> &'static str {
match self {
Action::Start => "start",
Action::Stop => "stop",
Action::Restart => "restart",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Scope {
User,
System,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceRecord {
pub manager: Manager,
pub unit: String,
pub scope: Scope,
}
impl ServiceRecord {
pub fn user_default() -> Self {
Self {
manager: Manager::Systemd,
unit: DEFAULT_UNIT.to_string(),
scope: Scope::User,
}
}
pub fn launchd(label: &str) -> Self {
Self {
manager: Manager::Launchd,
unit: label.to_string(),
scope: Scope::System,
}
}
fn default_for(os: Os) -> Self {
match os {
Os::Linux => Self::user_default(),
Os::MacOs => Self::launchd(launchd::DEFAULT_LABEL),
}
}
}
pub fn select(os: Os, recorded: Option<ServiceRecord>) -> ServiceRecord {
recorded.unwrap_or_else(|| ServiceRecord::default_for(os))
}
pub fn check_setup_caller(os: Os, uid: u32) -> Result<()> {
if os == Os::MacOs && uid == 0 {
anyhow::bail!(
"run `sb setup` as the user who will own the daemon, not as root; \
it calls sudo itself to install the LaunchDaemon"
);
}
Ok(())
}
pub fn status_hint(record: &ServiceRecord) -> String {
match (&record.manager, &record.scope) {
(Manager::Systemd, Scope::User) => format!("systemctl --user status {}", record.unit),
(Manager::Systemd, Scope::System) => format!("systemctl status {}", record.unit),
(Manager::Launchd, _) => format!("launchctl print system/{}", record.unit),
}
}
pub struct Caller {
pub uid: u32,
runtime_dir: Option<OsString>,
}
impl Caller {
pub fn current() -> Self {
Self {
uid: unsafe { libc::getuid() },
runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
}
}
#[cfg(test)]
pub fn with_uid(uid: u32) -> Self {
Self {
uid,
runtime_dir: None,
}
}
}
pub fn unit_file(api_bin: &Path, db_path: &Path) -> String {
format!(
"[Unit]\n\
Description=second-brain memory daemon (SQLite store, embedder, transcript watcher)\n\
After=network.target\n\
StartLimitIntervalSec=0\n\
\n\
[Service]\n\
Type=simple\n\
ExecStart={api}\n\
Environment=SECOND_BRAIN_DB={db}\n\
Environment=SECOND_BRAIN_BIND={bind}\n\
Restart=on-failure\n\
RestartSec=5\n\
TimeoutStartSec=60\n\
\n\
[Install]\n\
WantedBy=default.target\n",
api = api_bin.display(),
db = db_path.display(),
bind = DEFAULT_BIND,
)
}
pub fn record_path() -> Result<PathBuf> {
Ok(second_brain_core::machine::data_dir()?.join("service.json"))
}
pub fn save_record(path: &Path, record: &ServiceRecord) -> Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
}
let json = serde_json::to_string_pretty(record)?;
std::fs::write(path, json + "\n").with_context(|| format!("writing {}", path.display()))
}
fn load_record(path: &Path) -> Result<Option<ServiceRecord>> {
let content = match std::fs::read_to_string(path) {
Ok(content) => content,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
};
serde_json::from_str(&content)
.map(Some)
.with_context(|| format!("parsing {}", path.display()))
}
pub fn control(action: Action) -> Result<()> {
let path = record_path()?;
let recorded = load_record(&path)?;
let from_record = recorded.is_some();
let record = select(Os::current(), recorded);
let caller = Caller::current();
match record.manager {
Manager::Systemd => systemd_control(
&record,
from_record.then_some(path.as_path()),
action,
&caller,
),
Manager::Launchd => launchd::control(
action,
&launchd::Daemon::new(&record.unit),
&caller,
&mut launchd::System,
),
}
}
fn systemd_control(
record: &ServiceRecord,
recorded_in: Option<&Path>,
action: Action,
caller: &Caller,
) -> Result<()> {
let probe = load_state_command(record, caller)
.output()
.context("failed to run systemctl")?;
check_loaded(record, recorded_in, &probe)?;
let mut cmd = action_command(record, action.as_str(), caller);
let shown = render(&cmd);
let status = cmd
.status()
.with_context(|| format!("failed to run {shown}"))?;
if !status.success() {
anyhow::bail!("{shown} failed");
}
Ok(())
}
fn systemctl(scope: &Scope, caller: &Caller) -> Command {
let mut cmd = Command::new("systemctl");
if *scope == Scope::User {
cmd.arg("--user");
if caller.runtime_dir.as_ref().is_none_or(|d| d.is_empty()) {
cmd.env("XDG_RUNTIME_DIR", format!("/run/user/{}", caller.uid));
}
}
cmd
}
fn load_state_command(record: &ServiceRecord, caller: &Caller) -> Command {
let mut cmd = systemctl(&record.scope, caller);
cmd.args(["show", "--property=LoadState", "--value", &record.unit]);
cmd
}
fn action_command(record: &ServiceRecord, action: &str, caller: &Caller) -> Command {
let mut cmd = if record.scope == Scope::System && caller.uid != 0 {
let mut sudo = Command::new("sudo");
sudo.arg("systemctl");
sudo
} else {
systemctl(&record.scope, caller)
};
cmd.args([action, &record.unit]);
cmd
}
fn check_loaded(record: &ServiceRecord, recorded_in: Option<&Path>, probe: &Output) -> Result<()> {
let scope = match record.scope {
Scope::User => "user",
Scope::System => "system",
};
let unit = &record.unit;
if !probe.status.success() {
anyhow::bail!(
"could not query the {scope} unit {unit}: {}",
String::from_utf8_lossy(&probe.stderr).trim()
);
}
let state = String::from_utf8_lossy(&probe.stdout);
let state = state.trim();
if state == "loaded" {
return Ok(());
}
match recorded_in {
Some(path) => anyhow::bail!(
"the {scope} unit {unit} recorded in {} is not loaded (LoadState={state}); \
reinstall that service or remove the record",
path.display()
),
None => anyhow::bail!(
"the {scope} unit {unit} is not loaded (LoadState={state}); \
install it with `sb setup`"
),
}
}
pub trait Exec {
fn output(&mut self, cmd: Command) -> Result<Output>;
}
pub struct SystemExec;
impl Exec for SystemExec {
fn output(&mut self, mut cmd: Command) -> Result<Output> {
cmd.output()
.with_context(|| format!("failed to run {}", render(&cmd)))
}
}
const CONNECT_TIMEOUT: Duration = Duration::from_millis(500);
pub fn check_bind_free(
bind: &str,
our_service_running: impl FnOnce() -> Result<bool>,
holder: impl FnOnce(u16) -> Option<String>,
) -> Result<()> {
let addr: SocketAddr = bind
.parse()
.with_context(|| format!("parsing bind address {bind}"))?;
if TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).is_err() || our_service_running()? {
return Ok(());
}
let lookup = render(&holder_command(addr.port()));
let found = match holder(addr.port()) {
Some(listing) => format!(":\n{listing}\n"),
None => format!(" (find it with `{lookup}`)"),
};
anyhow::bail!(
"{bind} is already in use by a process that is not the daemon `sb setup` manages{found}\
stop it (and disable its service so it does not start again), then rerun `sb setup`; \
`{lookup}` shows what holds the port"
)
}
pub fn holder_command(port: u16) -> Command {
let mut cmd = Command::new("lsof");
cmd.args(["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN"]);
cmd
}
pub fn port_holder(port: u16, exec: &mut dyn Exec) -> Option<String> {
let out = exec.output(holder_command(port)).ok()?;
let listing = String::from_utf8_lossy(&out.stdout).trim().to_string();
(out.status.success() && !listing.is_empty()).then_some(listing)
}
pub fn user_unit_active(caller: &Caller, exec: &mut dyn Exec) -> bool {
let mut cmd = systemctl(&Scope::User, caller);
cmd.args(["is-active", DEFAULT_UNIT]);
exec.output(cmd).is_ok_and(|out| out.status.success())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Start {
Started,
Restarted,
Failed { command: String, detail: String },
}
fn start_steps(active: bool) -> Vec<Vec<&'static str>> {
if active {
vec![
vec!["daemon-reload"],
vec!["enable", DEFAULT_UNIT],
vec!["restart", DEFAULT_UNIT],
]
} else {
vec![vec!["daemon-reload"], vec!["enable", "--now", DEFAULT_UNIT]]
}
}
pub fn start_user_unit(active: bool, caller: &Caller, exec: &mut dyn Exec) -> Start {
for args in start_steps(active) {
let mut cmd = systemctl(&Scope::User, caller);
cmd.args(&args);
if let Err(detail) = run_checked(exec, cmd) {
return Start::Failed {
command: format!("systemctl --user {}", args.join(" ")),
detail,
};
}
}
if active {
Start::Restarted
} else {
Start::Started
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Linger {
AlreadyOn,
Enabled,
Failed(String),
}
pub fn ensure_linger(user: &str, exec: &mut dyn Exec) -> Linger {
let mut probe = Command::new("loginctl");
probe.args(["show-user", user, "-p", "Linger"]);
if exec
.output(probe)
.is_ok_and(|out| String::from_utf8_lossy(&out.stdout).trim() == "Linger=yes")
{
return Linger::AlreadyOn;
}
let mut enable = Command::new("loginctl");
enable.args(["enable-linger", user]);
let shown = render(&enable);
match run_checked(exec, enable) {
Ok(()) => Linger::Enabled,
Err(detail) => Linger::Failed(format!(
"could not enable linger ({detail}), so the daemon stops when you log out; \
run `{shown}` to keep it running"
)),
}
}
pub(crate) fn run_checked(exec: &mut dyn Exec, cmd: Command) -> std::result::Result<(), String> {
match exec.output(cmd) {
Ok(out) if out.status.success() => Ok(()),
Ok(out) => {
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
Err(if stderr.is_empty() {
out.status.to_string()
} else {
stderr
})
}
Err(e) => Err(format!("{e:#}")),
}
}
pub(crate) fn render(cmd: &Command) -> String {
std::iter::once(cmd.get_program())
.chain(cmd.get_args())
.map(|a| shell_word(&a.to_string_lossy()))
.collect::<Vec<_>>()
.join(" ")
}
fn shell_word(arg: &str) -> String {
let plain = |c: char| c.is_ascii_alphanumeric() || "_-./=:@,+%".contains(c);
if !arg.is_empty() && arg.chars().all(plain) {
arg.to_string()
} else {
format!("'{}'", arg.replace('\'', r"'\''"))
}
}
#[cfg(test)]
mod tests {
use std::os::unix::process::ExitStatusExt;
use std::process::ExitStatus;
use super::*;
fn caller(uid: u32, runtime_dir: Option<&str>) -> Caller {
Caller {
uid,
runtime_dir: runtime_dir.map(OsString::from),
}
}
fn system_record() -> ServiceRecord {
ServiceRecord {
manager: Manager::Systemd,
unit: "custom-brain.service".to_string(),
scope: Scope::System,
}
}
fn argv(cmd: &Command) -> Vec<String> {
std::iter::once(cmd.get_program())
.chain(cmd.get_args())
.map(|a| a.to_string_lossy().into_owned())
.collect()
}
fn runtime_env(cmd: &Command) -> Option<Option<OsString>> {
cmd.get_envs()
.find(|(k, _)| *k == "XDG_RUNTIME_DIR")
.map(|(_, v)| v.map(OsString::from))
}
fn probe(code: i32, stdout: &str, stderr: &str) -> Output {
Output {
status: ExitStatus::from_raw(code << 8),
stdout: stdout.as_bytes().to_vec(),
stderr: stderr.as_bytes().to_vec(),
}
}
#[test]
fn missing_record_means_no_record() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(load_record(&dir.path().join("service.json")).unwrap(), None);
}
#[test]
fn saved_record_loads_back() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nested/service.json");
save_record(&path, &system_record()).unwrap();
assert_eq!(load_record(&path).unwrap(), Some(system_record()));
}
#[test]
fn record_file_uses_plain_lowercase_names() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("service.json");
std::fs::write(
&path,
r#"{"manager":"systemd","unit":"second-brain-api.service","scope":"system"}"#,
)
.unwrap();
assert_eq!(
load_record(&path).unwrap(),
Some(ServiceRecord {
manager: Manager::Systemd,
unit: "second-brain-api.service".to_string(),
scope: Scope::System,
})
);
}
#[test]
fn malformed_record_is_an_error_naming_the_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("service.json");
std::fs::write(&path, "{").unwrap();
let err = format!("{:#}", load_record(&path).unwrap_err());
assert!(err.contains("service.json"), "{err}");
}
#[test]
fn default_record_is_the_user_unit_setup_installs() {
assert_eq!(
ServiceRecord::user_default(),
ServiceRecord {
manager: Manager::Systemd,
unit: DEFAULT_UNIT.to_string(),
scope: Scope::User,
}
);
}
#[test]
fn user_systemctl_fills_runtime_dir_when_unset_or_empty() {
for unset in [None, Some("")] {
let cmd = systemctl(&Scope::User, &caller(1000, unset));
assert_eq!(argv(&cmd), ["systemctl", "--user"]);
assert_eq!(
runtime_env(&cmd),
Some(Some(OsString::from("/run/user/1000")))
);
}
}
#[test]
fn user_systemctl_keeps_an_existing_runtime_dir() {
let cmd = systemctl(&Scope::User, &caller(1000, Some("/custom")));
assert_eq!(runtime_env(&cmd), None);
}
#[test]
fn system_systemctl_never_touches_the_runtime_dir() {
let cmd = systemctl(&Scope::System, &caller(1000, None));
assert_eq!(argv(&cmd), ["systemctl"]);
assert_eq!(runtime_env(&cmd), None);
}
#[test]
fn user_action_targets_the_recorded_unit() {
let record = ServiceRecord {
scope: Scope::User,
..system_record()
};
let cmd = action_command(&record, "stop", &caller(1000, None));
assert_eq!(
argv(&cmd),
["systemctl", "--user", "stop", "custom-brain.service"]
);
assert_eq!(
runtime_env(&cmd),
Some(Some(OsString::from("/run/user/1000")))
);
}
#[test]
fn render_quotes_arguments_a_shell_would_split_or_expand() {
let mut cmd = Command::new("claude");
cmd.args([
"add",
"SECOND_BRAIN_API=http://127.0.0.1:7200",
"--",
"/Users/a b/bin/mcp",
"it's",
"~/x",
"$HOME",
"",
]);
assert_eq!(
render(&cmd),
"claude add SECOND_BRAIN_API=http://127.0.0.1:7200 -- '/Users/a b/bin/mcp' \
'it'\\''s' '~/x' '$HOME' ''"
);
}
#[test]
fn system_action_goes_through_sudo_unless_root() {
let record = system_record();
assert_eq!(
argv(&action_command(&record, "restart", &caller(1000, None))),
["sudo", "systemctl", "restart", "custom-brain.service"]
);
assert_eq!(
argv(&action_command(&record, "restart", &caller(0, None))),
["systemctl", "restart", "custom-brain.service"]
);
}
#[test]
fn load_state_probe_asks_the_recorded_manager_scope() {
let record = system_record();
assert_eq!(
argv(&load_state_command(&record, &caller(1000, None))),
[
"systemctl",
"show",
"--property=LoadState",
"--value",
"custom-brain.service"
]
);
let user = ServiceRecord::user_default();
assert_eq!(
argv(&load_state_command(&user, &caller(1000, None)))[..2],
["systemctl", "--user"]
);
}
#[test]
fn loaded_unit_passes() {
check_loaded(&system_record(), None, &probe(0, "loaded\n", "")).unwrap();
}
#[test]
fn unloaded_recorded_unit_names_the_unit_state_and_record() {
let err = check_loaded(
&system_record(),
Some(Path::new("/data/service.json")),
&probe(0, "not-found\n", ""),
)
.unwrap_err()
.to_string();
assert!(err.contains("custom-brain.service"), "{err}");
assert!(err.contains("not-found"), "{err}");
assert!(err.contains("/data/service.json"), "{err}");
}
#[test]
fn unloaded_default_unit_points_at_setup() {
let err = check_loaded(
&ServiceRecord::user_default(),
None,
&probe(0, "not-found\n", ""),
)
.unwrap_err()
.to_string();
assert!(err.contains(DEFAULT_UNIT), "{err}");
assert!(err.contains("sb setup"), "{err}");
}
#[test]
fn failed_probe_reports_systemctl_stderr() {
let err = check_loaded(
&ServiceRecord::user_default(),
None,
&probe(1, "", "Failed to connect to bus: No medium found\n"),
)
.unwrap_err()
.to_string();
assert!(err.contains("No medium found"), "{err}");
}
fn launchd_record() -> ServiceRecord {
ServiceRecord::launchd("custom-brain.api")
}
#[test]
fn launchd_record_round_trips_as_plain_lowercase_names() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("service.json");
save_record(&path, &launchd_record()).unwrap();
let text = std::fs::read_to_string(&path).unwrap();
let json: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(
json,
serde_json::json!({"manager": "launchd", "unit": "custom-brain.api", "scope": "system"})
);
assert_eq!(load_record(&path).unwrap(), Some(launchd_record()));
}
#[test]
fn linux_without_a_record_uses_the_user_unit() {
assert_eq!(select(Os::Linux, None), ServiceRecord::user_default());
}
#[test]
fn macos_without_a_record_uses_the_launchd_daemon() {
assert_eq!(
select(Os::MacOs, None),
ServiceRecord {
manager: Manager::Launchd,
unit: launchd::DEFAULT_LABEL.to_string(),
scope: Scope::System,
}
);
}
#[test]
fn a_record_wins_on_linux() {
assert_eq!(select(Os::Linux, Some(launchd_record())), launchd_record());
}
#[test]
fn a_record_wins_on_macos() {
assert_eq!(select(Os::MacOs, Some(system_record())), system_record());
}
#[test]
fn macos_setup_refuses_root() {
let err = check_setup_caller(Os::MacOs, 0).unwrap_err().to_string();
assert!(err.contains("sudo"), "{err}");
check_setup_caller(Os::MacOs, 501).unwrap();
}
#[test]
fn linux_setup_allows_any_uid() {
check_setup_caller(Os::Linux, 0).unwrap();
check_setup_caller(Os::Linux, 1000).unwrap();
}
#[test]
fn status_hint_names_the_manager_setup_used() {
assert_eq!(
status_hint(&ServiceRecord::user_default()),
"systemctl --user status second-brain.service"
);
assert_eq!(
status_hint(&system_record()),
"systemctl status custom-brain.service"
);
assert_eq!(
status_hint(&launchd_record()),
"launchctl print system/custom-brain.api"
);
}
#[test]
fn caller_uid_is_the_real_uid() {
assert_eq!(Caller::current().uid, unsafe { libc::getuid() });
}
fn section<'a>(unit: &'a str, name: &str) -> Vec<&'a str> {
unit.lines()
.skip_while(|l| *l != format!("[{name}]"))
.skip(1)
.take_while(|l| !l.starts_with('['))
.collect()
}
#[test]
fn the_unit_never_stops_restarting_and_names_the_real_store() {
let unit = unit_file(
Path::new("/opt/sb/second-brain-api"),
Path::new("/h/brain.db"),
);
assert!(
section(&unit, "Unit").contains(&"StartLimitIntervalSec=0"),
"{unit}"
);
assert!(
section(&unit, "Service").contains(&"Restart=on-failure"),
"{unit}"
);
assert!(
section(&unit, "Service").contains(&"ExecStart=/opt/sb/second-brain-api"),
"{unit}"
);
assert!(
section(&unit, "Service").contains(&"Environment=SECOND_BRAIN_DB=/h/brain.db"),
"{unit}"
);
assert!(!unit.to_lowercase().contains("kuzu"), "{unit}");
}
type Reply = Box<dyn FnMut(&[String]) -> Result<Output>>;
struct FakeExec {
calls: Vec<Vec<String>>,
reply: Reply,
}
impl FakeExec {
fn new(reply: impl FnMut(&[String]) -> Result<Output> + 'static) -> Self {
Self {
calls: Vec::new(),
reply: Box::new(reply),
}
}
}
impl Exec for FakeExec {
fn output(&mut self, cmd: Command) -> Result<Output> {
let argv = argv(&cmd);
let out = (self.reply)(&argv);
self.calls.push(argv);
out
}
}
fn ok(stdout: &str) -> Result<Output> {
Ok(probe(0, stdout, ""))
}
fn held_port() -> (std::net::TcpListener, String) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let bind = listener.local_addr().unwrap().to_string();
(listener, bind)
}
fn free_port() -> String {
let (listener, bind) = held_port();
drop(listener);
bind
}
#[test]
fn a_held_port_without_our_running_service_is_refused_naming_the_holder() {
let (_listener, bind) = held_port();
let port = bind.rsplit(':').next().unwrap().to_string();
let mut asked = None;
let err = check_bind_free(
&bind,
|| Ok(false),
|p| {
asked = Some(p);
Some("other-daemon 4242 me 9u IPv4 TCP 127.0.0.1:7200 (LISTEN)".to_string())
},
)
.unwrap_err()
.to_string();
assert_eq!(asked.map(|p| p.to_string()), Some(port.clone()));
assert!(err.contains(&bind), "{err}");
assert!(err.contains("other-daemon 4242"), "{err}");
assert!(
err.contains(&format!("lsof -nP -iTCP:{port} -sTCP:LISTEN")),
"{err}"
);
assert!(err.contains("stop it"), "{err}");
}
#[test]
fn a_refusal_without_lsof_output_still_says_where_to_look() {
let (_listener, bind) = held_port();
let port = bind.rsplit(':').next().unwrap();
let err = check_bind_free(&bind, || Ok(false), |_| None)
.unwrap_err()
.to_string();
assert!(
err.contains(&format!("lsof -nP -iTCP:{port} -sTCP:LISTEN")),
"{err}"
);
}
#[test]
fn a_held_port_passes_when_our_service_is_running_there() {
let (_listener, bind) = held_port();
check_bind_free(&bind, || Ok(true), |_| panic!("no lookup")).unwrap();
}
#[test]
fn a_free_port_passes_without_probing_the_service() {
let bind = free_port();
check_bind_free(&bind, || panic!("no probe"), |_| panic!("no lookup")).unwrap();
}
#[test]
fn holder_lookup_lists_tcp_listeners_on_the_port() {
assert_eq!(
argv(&holder_command(7200)),
["lsof", "-nP", "-iTCP:7200", "-sTCP:LISTEN"]
);
}
#[test]
fn is_active_probe_asks_the_user_manager() {
let mut exec = FakeExec::new(|_| ok("active\n"));
assert!(user_unit_active(&caller(1000, None), &mut exec));
assert_eq!(
exec.calls,
[["systemctl", "--user", "is-active", DEFAULT_UNIT]]
);
}
#[test]
fn an_inactive_or_unreachable_unit_is_not_active() {
let mut inactive = FakeExec::new(|_| Ok(probe(3, "inactive\n", "")));
assert!(!user_unit_active(&caller(1000, None), &mut inactive));
let mut missing = FakeExec::new(|_| Err(anyhow::anyhow!("no systemctl")));
assert!(!user_unit_active(&caller(1000, None), &mut missing));
}
fn user(args: &[&str]) -> Vec<String> {
["systemctl", "--user"]
.iter()
.chain(args)
.map(|s| s.to_string())
.collect()
}
#[test]
fn a_fresh_install_enables_and_starts_the_unit() {
let mut exec = FakeExec::new(|_| ok(""));
let outcome = start_user_unit(false, &caller(1000, None), &mut exec);
assert_eq!(outcome, Start::Started);
assert_eq!(
exec.calls,
[
user(&["daemon-reload"]),
user(&["enable", "--now", DEFAULT_UNIT])
]
);
}
#[test]
fn a_reinstall_over_a_running_unit_restarts_it_on_the_new_binary() {
let mut exec = FakeExec::new(|_| ok(""));
let outcome = start_user_unit(true, &caller(1000, None), &mut exec);
assert_eq!(outcome, Start::Restarted);
assert_eq!(
exec.calls,
[
user(&["daemon-reload"]),
user(&["enable", DEFAULT_UNIT]),
user(&["restart", DEFAULT_UNIT]),
]
);
}
#[test]
fn a_failing_restart_is_reported_like_a_failing_enable() {
let failing = |verb: &'static str| {
move |argv: &[String]| {
if argv.iter().any(|a| a == verb) {
Ok(probe(1, "", "Unit failed\n"))
} else {
ok("")
}
}
};
let mut exec = FakeExec::new(failing("restart"));
let restart = start_user_unit(true, &caller(1000, None), &mut exec);
let mut exec = FakeExec::new(failing("enable"));
let enable = start_user_unit(false, &caller(1000, None), &mut exec);
for (outcome, verb) in [(restart, "restart"), (enable, "enable")] {
match outcome {
Start::Failed { command, detail } => {
assert!(command.contains(verb), "{command}");
assert!(detail.contains("Unit failed"), "{detail}");
}
other => panic!("{verb}: {other:?}"),
}
}
}
#[test]
fn a_failing_daemon_reload_stops_before_enable() {
let mut exec = FakeExec::new(|_| Err(anyhow::anyhow!("systemctl not found")));
let outcome = start_user_unit(true, &caller(1000, None), &mut exec);
assert!(
matches!(&outcome, Start::Failed { command, detail }
if command.contains("daemon-reload") && detail.contains("not found")),
"{outcome:?}"
);
assert_eq!(exec.calls.len(), 1);
}
#[test]
fn linger_already_on_is_left_alone() {
let mut exec = FakeExec::new(|_| ok("Linger=yes\n"));
assert_eq!(ensure_linger("alice", &mut exec), Linger::AlreadyOn);
assert_eq!(
exec.calls,
[["loginctl", "show-user", "alice", "-p", "Linger"]]
);
}
#[test]
fn linger_off_is_enabled_without_sudo() {
let mut exec = FakeExec::new(|argv| {
ok(if argv[1] == "show-user" {
"Linger=no\n"
} else {
""
})
});
assert_eq!(ensure_linger("alice", &mut exec), Linger::Enabled);
assert_eq!(
exec.calls,
[
vec!["loginctl", "show-user", "alice", "-p", "Linger"],
vec!["loginctl", "enable-linger", "alice"],
]
);
}
#[test]
fn a_failed_linger_probe_still_tries_to_enable_it() {
let mut exec = FakeExec::new(|argv| {
if argv[1] == "show-user" {
Ok(probe(1, "", "User alice is not logged in or lingering\n"))
} else {
ok("")
}
});
assert_eq!(ensure_linger("alice", &mut exec), Linger::Enabled);
assert_eq!(exec.calls.len(), 2);
}
#[test]
fn a_failing_enable_linger_warns_with_the_exact_command() {
let mut exec = FakeExec::new(|argv| {
if argv[1] == "show-user" {
ok("Linger=no\n")
} else {
Ok(probe(1, "", "Access denied\n"))
}
});
match ensure_linger("alice", &mut exec) {
Linger::Failed(warning) => {
assert!(
warning.contains("loginctl enable-linger alice"),
"{warning}"
);
assert!(warning.contains("Access denied"), "{warning}");
}
other => panic!("{other:?}"),
}
}
}