use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use super::report::{Check, Context};
use crate::daemon::{Manager, Scope, ServiceRecord};
use crate::{daemon, launchd};
const NAME: &str = "service";
const SETUP: &str = "run `sb setup` to reinstall the service for the installed binaries";
pub(crate) struct ServiceDirs {
pub launch_daemons: PathBuf,
pub systemd_run_dir: PathBuf,
}
pub(crate) fn check(
ctx: &Context,
exec: &mut dyn daemon::Exec,
launchd: &mut dyn launchd::Runner,
) -> Check {
let dirs = ServiceDirs {
launch_daemons: PathBuf::from(launchd::DAEMONS_DIR),
systemd_run_dir: PathBuf::from("/run/systemd/system"),
};
check_in(ctx, &dirs, &daemon::Caller::current(), exec, launchd)
}
fn check_in(
ctx: &Context,
dirs: &ServiceDirs,
caller: &daemon::Caller,
exec: &mut dyn daemon::Exec,
launchd: &mut dyn launchd::Runner,
) -> Check {
let recorded = match daemon::load_record(&ctx.data_dir.join("service.json")) {
Ok(recorded) => recorded,
Err(e) => {
return Check::fail(
NAME,
format!("{e:#}, so `sb start` and `sb stop` cannot tell which service to control"),
"run `sb setup` to record the service again",
);
}
};
let record = daemon::select(ctx.os, recorded);
let systemd = Systemd {
run_dir: &dirs.systemd_run_dir,
caller,
exec,
};
match record.manager {
Manager::Systemd => match record.scope {
Scope::User => user_unit(
&daemon::user_unit_dir(&ctx.home).join(&record.unit),
&record,
systemd,
),
Scope::System => unit_activity("system unit", &record, None, systemd),
},
Manager::Launchd => launch_daemon(
&launchd::Daemon::in_dir(&record.unit, &dirs.launch_daemons),
&record,
&ctx.home,
launchd,
),
}
}
struct Systemd<'a> {
run_dir: &'a Path,
caller: &'a daemon::Caller,
exec: &'a mut dyn daemon::Exec,
}
fn user_unit(unit_path: &Path, record: &ServiceRecord, systemd: Systemd) -> Check {
let program = match unit_program(unit_path) {
Ok(program) => program,
Err(problem) => return Check::fail(NAME, problem, SETUP),
};
unit_activity(
&unit_path.display().to_string(),
record,
Some(&program),
systemd,
)
}
fn unit_program(unit_path: &Path) -> Result<PathBuf, String> {
let unit = read_service_file(unit_path, "systemd")?;
let program = daemon::unit_exec_start(&unit)
.ok_or_else(|| format!("{} has no ExecStart line", unit_path.display()))?;
program_usable(&program, unit_path)?;
Ok(program)
}
fn unit_activity(
located: &str,
record: &ServiceRecord,
program: Option<&Path>,
systemd: Systemd,
) -> Check {
if !systemd.run_dir.is_dir() {
let reason = format!(
"PID 1 is not systemd ({} does not exist)",
systemd.run_dir.display()
);
return no_systemd(record, program, &reason);
}
let cmd = daemon::is_active_command(record, systemd.caller);
let shown = daemon::render(&cmd);
match systemd.exec.output(cmd) {
Ok(out) if out.status.success() => {
Check::ok(NAME, format!("{} is active ({located})", record.unit))
}
Ok(out) => match unit_state(&out) {
Some(state) => Check::fail(
NAME,
format!(
"{} is {state}, so no daemon is serving memories",
record.unit
),
format!(
"run `{}`; if it stops again, `{}` shows why",
start_command(record),
journal_command(record)
),
),
None => query_failed(record, &shown, &failure(&out)),
},
Err(e) if daemon::is_not_found(&e) => {
no_systemd(record, program, "systemctl is not on PATH")
}
Err(e) => query_failed(record, &shown, &format!("{e:#}")),
}
}
fn no_systemd(record: &ServiceRecord, program: Option<&Path>, reason: &str) -> Check {
let run = match program {
Some(program) => format!("`{}`", daemon::render(&Command::new(program))),
None => format!("the program the ExecStart line of {} names", record.unit),
};
Check::warn(
NAME,
format!(
"{reason}, so this host has no systemd to run {}; \
the daemon check shows whether a daemon answers anyway",
record.unit
),
format!(
"run {run} under this host's own supervisor, because a systemd unit cannot run here"
),
)
}
fn unit_state(out: &Output) -> Option<String> {
let state = String::from_utf8_lossy(&out.stdout).trim().to_string();
(!state.is_empty()).then_some(state)
}
fn failure(out: &Output) -> String {
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
if stderr.is_empty() {
out.status.to_string()
} else {
stderr
}
}
fn start_command(record: &ServiceRecord) -> String {
match record.scope {
Scope::User => "sb start".to_string(),
Scope::System => format!("sudo systemctl start {}", record.unit),
}
}
fn journal_command(record: &ServiceRecord) -> String {
match record.scope {
Scope::User => format!("journalctl --user -u {} -n 50", record.unit),
Scope::System => format!("sudo journalctl -u {} -n 50", record.unit),
}
}
fn query_failed(record: &ServiceRecord, command: &str, error: &str) -> Check {
let mut fix = format!(
"run `{}` directly to see why the service manager cannot answer",
daemon::status_hint(record)
);
if matches!(
(&record.manager, &record.scope),
(Manager::Systemd, Scope::User)
) && error.to_ascii_lowercase().contains("bus")
{
fix.push_str(
"; a user unit needs that user's systemd session bus, which sudo and su do not \
reach and ssh reaches only with lingering, so log in as that user directly \
or enable lingering with `loginctl enable-linger`",
);
}
Check::fail(
NAME,
format!("`{command}` failed ({error}), so the service state is unknown"),
fix,
)
}
fn launch_daemon(
target: &launchd::Daemon,
record: &ServiceRecord,
home: &Path,
runner: &mut dyn launchd::Runner,
) -> Check {
if let Err(problem) = plist_program_usable(&target.plist) {
return Check::fail(NAME, problem, SETUP);
}
match launchd::is_loaded(target, runner) {
Ok(true) => Check::ok(
NAME,
format!("{} is loaded ({})", target.label, target.plist.display()),
),
Ok(false) => Check::fail(
NAME,
format!(
"{} is not loaded in launchd, so no daemon is serving memories",
target.label
),
format!(
"run `sb start`; if it stops again, the logs in {} show why",
launchd::log_dir_in(home).display()
),
),
Err(e) => query_failed(record, &daemon::status_hint(record), &format!("{e:#}")),
}
}
fn plist_program_usable(plist_path: &Path) -> Result<(), String> {
let plist = read_service_file(plist_path, "launchd")?;
let program = launchd::plist_program(&plist)
.ok_or_else(|| format!("{} names no program to run", plist_path.display()))?;
program_usable(&program, plist_path)
}
fn read_service_file(path: &Path, manager: &str) -> Result<String, String> {
std::fs::read_to_string(path).map_err(|e| match e.kind() {
ErrorKind::NotFound => format!(
"{} does not exist, so {manager} has no second-brain daemon to run",
path.display()
),
_ => format!("cannot read {}: {e}", path.display()),
})
}
fn program_usable(program: &Path, named_in: &Path) -> Result<(), String> {
daemon::program_usable(program).map_err(|problem| {
format!(
"{} named in {} {problem}, so the daemon cannot start",
program.display(),
named_in.display()
)
})
}
#[cfg(test)]
mod tests {
use std::os::unix::fs::PermissionsExt;
use std::os::unix::process::ExitStatusExt;
use std::path::Path;
use std::process::{Command, ExitStatus, Output};
use std::time::Duration;
use super::super::report::Status;
use super::*;
use crate::daemon::{Caller, Manager, Os, Scope, ServiceRecord};
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()
}
struct FakeExec {
calls: Vec<Vec<String>>,
code: i32,
stdout: &'static str,
stderr: &'static str,
}
impl FakeExec {
fn active() -> Self {
Self {
calls: Vec::new(),
code: 0,
stdout: "active\n",
stderr: "",
}
}
fn inactive() -> Self {
Self {
calls: Vec::new(),
code: 3,
stdout: "inactive\n",
stderr: "",
}
}
fn no_bus() -> Self {
Self {
calls: Vec::new(),
code: 1,
stdout: "",
stderr: "Failed to connect to bus: No medium found\n",
}
}
fn not_booted_with_systemd() -> Self {
Self {
calls: Vec::new(),
code: 1,
stdout: "",
stderr: "System has not been booted with systemd as init system (PID 1). \
Can't operate.\nFailed to connect to bus: Host is down\n",
}
}
}
impl daemon::Exec for FakeExec {
fn output(&mut self, cmd: Command) -> anyhow::Result<Output> {
self.calls.push(argv(&cmd));
Ok(Output {
status: ExitStatus::from_raw(self.code << 8),
stdout: self.stdout.as_bytes().to_vec(),
stderr: self.stderr.as_bytes().to_vec(),
})
}
}
struct BrokenExec;
impl daemon::Exec for BrokenExec {
fn output(&mut self, _cmd: Command) -> anyhow::Result<Output> {
anyhow::bail!("No such file or directory")
}
}
struct NoSystemctl;
impl daemon::Exec for NoSystemctl {
fn output(&mut self, cmd: Command) -> anyhow::Result<Output> {
Err(
anyhow::Error::new(std::io::Error::from(ErrorKind::NotFound))
.context(format!("failed to run {}", daemon::render(&cmd))),
)
}
}
struct BrokenLaunchctl;
impl launchd::Runner for BrokenLaunchctl {
fn status(&mut self, _cmd: Command) -> anyhow::Result<ExitStatus> {
anyhow::bail!("No such file or directory")
}
fn pause(&mut self, duration: Duration) {
panic!("the check must not wait on launchd ({duration:?})");
}
}
struct FakeLaunchctl {
calls: Vec<Vec<String>>,
loaded: bool,
}
impl FakeLaunchctl {
fn new(loaded: bool) -> Self {
Self {
calls: Vec::new(),
loaded,
}
}
}
impl launchd::Runner for FakeLaunchctl {
fn status(&mut self, cmd: Command) -> anyhow::Result<ExitStatus> {
let argv = argv(&cmd);
let code = if argv.get(1).map(String::as_str) == Some("print") && self.loaded {
0
} else {
113
};
self.calls.push(argv);
Ok(ExitStatus::from_raw(code << 8))
}
fn pause(&mut self, duration: Duration) {
panic!("the check must not wait on launchd ({duration:?})");
}
}
struct Machine {
_root: tempfile::TempDir,
ctx: Context,
dirs: ServiceDirs,
}
impl Machine {
fn new(os: Os) -> Self {
let root = tempfile::tempdir().unwrap();
let home = root.path().join("home");
let data_dir = home.join(".second-brain");
std::fs::create_dir_all(&data_dir).unwrap();
let ctx = Context {
os,
sb_bin: home.join(".cargo/bin").join("sb"),
mcp_bin: Ok(home.join(".cargo/bin/second-brain-mcp")),
claude_settings: home.join(".claude/settings.json"),
model_cache: home.join("models"),
data_dir,
home,
};
let dirs = ServiceDirs {
launch_daemons: root.path().join("Library/LaunchDaemons"),
systemd_run_dir: root.path().join("run/systemd/system"),
};
std::fs::create_dir_all(&dirs.systemd_run_dir).unwrap();
Self {
_root: root,
ctx,
dirs,
}
}
fn without_systemd_as_init(&self) {
std::fs::remove_dir_all(&self.dirs.systemd_run_dir).unwrap();
}
fn record(&self, record: &ServiceRecord) {
daemon::save_record(&self.ctx.data_dir.join("service.json"), record).unwrap();
}
fn binary(&self, mode: u32) -> PathBuf {
self.binary_at(
&self.ctx.home.join(".cargo/bin").join("second-brain-api"),
mode,
)
}
fn binary_at(&self, bin: &Path, mode: u32) -> PathBuf {
std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
std::fs::write(bin, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(bin, std::fs::Permissions::from_mode(mode)).unwrap();
bin.to_path_buf()
}
fn user_unit_path(&self, unit: &str) -> PathBuf {
daemon::user_unit_dir(&self.ctx.home).join(unit)
}
fn write_unit(&self, path: &Path, api_bin: &Path) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(
path,
daemon::unit_file(api_bin, &self.ctx.data_dir.join("brain.db")),
)
.unwrap();
}
fn plist_path(&self, label: &str) -> PathBuf {
self.dirs.launch_daemons.join(format!("{label}.plist"))
}
fn write_plist(&self, label: &str, program: &Path) -> PathBuf {
let account = launchd::Account {
name: "alice".to_string(),
home: self.ctx.home.clone(),
};
let plist = launchd::render_plist(&launchd::PlistSpec {
label,
program,
account: &account,
db: &self.ctx.data_dir.join("brain.db"),
bind: daemon::DEFAULT_BIND,
})
.unwrap();
let path = self.plist_path(label);
std::fs::create_dir_all(&self.dirs.launch_daemons).unwrap();
std::fs::write(&path, plist).unwrap();
path
}
fn run(&self, exec: &mut dyn daemon::Exec, launchctl: &mut dyn launchd::Runner) -> Check {
check_in(
&self.ctx,
&self.dirs,
&Caller::with_uid(1000),
exec,
launchctl,
)
}
fn log_dir(&self) -> String {
self.ctx
.home
.join("Library/Logs/second-brain")
.display()
.to_string()
}
}
fn fix(check: &Check) -> &str {
check.fix.as_deref().unwrap_or_default()
}
fn assert_detail(check: &Check, needle: &str) {
assert!(check.detail.contains(needle), "{check:?}");
}
fn assert_fix(check: &Check, needle: &str) {
assert!(fix(check).contains(needle), "{check:?}");
}
fn strings(calls: &[&[&str]]) -> Vec<Vec<String>> {
calls
.iter()
.map(|c| c.iter().map(|a| a.to_string()).collect())
.collect()
}
#[test]
fn an_active_user_unit_passes_naming_its_unit_file() {
let m = Machine::new(Os::Linux);
let unit = m.user_unit_path(daemon::DEFAULT_UNIT);
m.write_unit(&unit, &m.binary(0o755));
let mut exec = FakeExec::active();
let check = m.run(&mut exec, &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Ok, "{check:?}");
assert_detail(&check, &unit.display().to_string());
assert_eq!(check.fix, None);
assert_eq!(
exec.calls,
strings(&[&["systemctl", "--user", "is-active", daemon::DEFAULT_UNIT]])
);
}
#[test]
fn a_missing_user_unit_fails_pointing_at_setup() {
let m = Machine::new(Os::Linux);
m.binary(0o755);
let check = m.run(&mut FakeExec::active(), &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Fail);
assert_detail(
&check,
&m.user_unit_path(daemon::DEFAULT_UNIT).display().to_string(),
);
assert_fix(&check, "sb setup");
}
#[test]
fn a_unit_whose_binary_is_gone_fails_naming_the_binary_even_while_active() {
let m = Machine::new(Os::Linux);
let gone = m.ctx.home.join("old/bin/second-brain-api");
m.write_unit(&m.user_unit_path(daemon::DEFAULT_UNIT), &gone);
let check = m.run(&mut FakeExec::active(), &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Fail);
assert_detail(&check, &gone.display().to_string());
assert_fix(&check, "sb setup");
}
#[test]
fn a_unit_whose_binary_is_not_executable_fails_naming_the_binary() {
let m = Machine::new(Os::Linux);
let bin = m.binary(0o644);
m.write_unit(&m.user_unit_path(daemon::DEFAULT_UNIT), &bin);
let check = m.run(&mut FakeExec::active(), &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Fail);
assert_detail(&check, &bin.display().to_string());
assert_detail(&check, "not executable");
assert_fix(&check, "sb setup");
}
#[test]
fn an_inactive_user_unit_fails_with_start_and_the_journal_command() {
let m = Machine::new(Os::Linux);
m.write_unit(&m.user_unit_path(daemon::DEFAULT_UNIT), &m.binary(0o755));
let mut exec = FakeExec::inactive();
let check = m.run(&mut exec, &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Fail);
assert_detail(&check, daemon::DEFAULT_UNIT);
assert_detail(&check, "inactive");
assert_fix(&check, "sb start");
assert_fix(&check, "journalctl --user -u second-brain.service");
assert_eq!(
exec.calls,
strings(&[&["systemctl", "--user", "is-active", daemon::DEFAULT_UNIT]])
);
}
fn system_unit(m: &Machine) {
m.record(&ServiceRecord {
manager: Manager::Systemd,
unit: "custom-brain.service".to_string(),
scope: Scope::System,
});
}
#[test]
fn a_recorded_system_unit_is_checked_in_the_system_scope() {
let m = Machine::new(Os::Linux);
system_unit(&m);
let mut exec = FakeExec::inactive();
let check = m.run(&mut exec, &mut FakeLaunchctl::new(true));
assert_eq!(check.status, Status::Fail, "{check:?}");
assert_detail(&check, "custom-brain.service");
assert_detail(&check, "inactive");
assert_fix(&check, "sudo systemctl start custom-brain.service");
assert_fix(&check, "sudo journalctl -u custom-brain.service -n 50");
assert!(!fix(&check).contains("--user"), "{check:?}");
assert!(!fix(&check).contains("sb setup"), "{check:?}");
assert_eq!(
exec.calls,
strings(&[&["systemctl", "is-active", "custom-brain.service"]])
);
}
#[test]
fn an_active_system_unit_with_no_unit_file_anywhere_is_ok() {
let m = Machine::new(Os::Linux);
system_unit(&m);
let mut exec = FakeExec::active();
let check = m.run(&mut exec, &mut FakeLaunchctl::new(true));
assert_eq!(check.status, Status::Ok, "{check:?}");
assert_detail(&check, "custom-brain.service");
assert_eq!(check.fix, None);
assert_eq!(
exec.calls,
strings(&[&["systemctl", "is-active", "custom-brain.service"]])
);
}
#[test]
fn a_system_unit_query_that_fails_says_to_run_the_status_command_not_setup() {
let m = Machine::new(Os::Linux);
system_unit(&m);
let check = m.run(&mut FakeExec::no_bus(), &mut FakeLaunchctl::new(true));
assert_eq!(check.status, Status::Fail, "{check:?}");
assert_detail(&check, "Failed to connect to bus");
assert_fix(&check, "systemctl status custom-brain.service");
assert!(!fix(&check).contains("--user"), "{check:?}");
assert!(!fix(&check).contains("sb setup"), "{check:?}");
}
#[test]
fn a_user_unit_query_without_a_session_bus_says_to_reach_the_users_bus() {
let m = Machine::new(Os::Linux);
m.write_unit(&m.user_unit_path(daemon::DEFAULT_UNIT), &m.binary(0o755));
let check = m.run(&mut FakeExec::no_bus(), &mut FakeLaunchctl::new(true));
assert_eq!(check.status, Status::Fail, "{check:?}");
assert_detail(&check, "systemctl --user is-active second-brain.service");
assert_detail(&check, "Failed to connect to bus");
assert_fix(&check, "systemctl --user status second-brain.service");
assert_fix(&check, "bus");
assert_fix(&check, "linger");
assert!(!fix(&check).contains("sb setup"), "{check:?}");
}
#[test]
fn an_unreadable_service_record_fails_with_the_parse_error() {
let m = Machine::new(Os::Linux);
m.write_unit(&m.user_unit_path(daemon::DEFAULT_UNIT), &m.binary(0o755));
std::fs::write(m.ctx.data_dir.join("service.json"), "{").unwrap();
let mut exec = FakeExec::active();
let check = m.run(&mut exec, &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Fail);
assert_detail(&check, "service.json");
assert_fix(&check, "sb setup");
assert!(exec.calls.is_empty(), "{:?}", exec.calls);
}
#[test]
fn a_loaded_launch_daemon_passes_after_one_launchctl_print_without_sudo() {
let m = Machine::new(Os::MacOs);
m.write_plist(launchd::DEFAULT_LABEL, &m.binary(0o755));
let mut launchctl = FakeLaunchctl::new(true);
let check = m.run(&mut FakeExec::active(), &mut launchctl);
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Ok, "{check:?}");
assert_detail(&check, launchd::DEFAULT_LABEL);
assert_eq!(check.fix, None);
assert_eq!(
launchctl.calls,
strings(&[&["launchctl", "print", "system/second-brain.api"]])
);
}
#[test]
fn a_missing_plist_fails_pointing_at_setup() {
let m = Machine::new(Os::MacOs);
m.binary(0o755);
let check = m.run(&mut FakeExec::active(), &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Fail);
assert_detail(
&check,
&m.plist_path(launchd::DEFAULT_LABEL).display().to_string(),
);
assert_fix(&check, "sb setup");
}
#[test]
fn a_plist_whose_program_is_gone_fails_naming_the_program() {
let m = Machine::new(Os::MacOs);
let gone = m.ctx.home.join("old/bin/second-brain-api");
m.write_plist(launchd::DEFAULT_LABEL, &gone);
let check = m.run(&mut FakeExec::active(), &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Fail);
assert_detail(&check, &gone.display().to_string());
assert_fix(&check, "sb setup");
}
#[test]
fn an_unloaded_launch_daemon_fails_with_start_and_the_log_dir() {
let m = Machine::new(Os::MacOs);
m.write_plist(launchd::DEFAULT_LABEL, &m.binary(0o755));
let mut launchctl = FakeLaunchctl::new(false);
let check = m.run(&mut FakeExec::active(), &mut launchctl);
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Fail);
assert_detail(&check, launchd::DEFAULT_LABEL);
assert_fix(&check, "sb start");
assert_fix(&check, &m.log_dir());
assert_eq!(
launchctl.calls,
strings(&[&["launchctl", "print", "system/second-brain.api"]])
);
}
#[test]
fn a_recorded_launch_daemon_wins_over_the_os_default() {
let m = Machine::new(Os::Linux);
m.record(&ServiceRecord::launchd("custom-brain.api"));
m.write_plist("custom-brain.api", &m.binary(0o755));
let mut exec = FakeExec::active();
let mut launchctl = FakeLaunchctl::new(true);
let check = m.run(&mut exec, &mut launchctl);
assert_eq!(check.status, Status::Ok, "{check:?}");
assert_detail(&check, "custom-brain.api");
assert!(exec.calls.is_empty(), "{:?}", exec.calls);
assert_eq!(
launchctl.calls,
strings(&[&["launchctl", "print", "system/custom-brain.api"]])
);
}
#[test]
fn a_systemctl_that_cannot_run_fails_naming_the_command_and_error() {
let m = Machine::new(Os::Linux);
m.write_unit(&m.user_unit_path(daemon::DEFAULT_UNIT), &m.binary(0o755));
let check = m.run(&mut BrokenExec, &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Fail);
assert_detail(&check, "systemctl --user is-active second-brain.service");
assert_detail(&check, "No such file or directory");
assert_fix(&check, "systemctl --user status second-brain.service");
assert!(!fix(&check).contains("sb setup"), "{check:?}");
assert!(!fix(&check).contains("linger"), "{check:?}");
}
#[test]
fn a_user_unit_query_failing_for_another_reason_gives_no_bus_advice() {
let m = Machine::new(Os::Linux);
m.write_unit(&m.user_unit_path(daemon::DEFAULT_UNIT), &m.binary(0o755));
let mut exec = FakeExec {
calls: Vec::new(),
code: 1,
stdout: "",
stderr: "Access denied\n",
};
let check = m.run(&mut exec, &mut FakeLaunchctl::new(true));
assert_eq!(check.status, Status::Fail, "{check:?}");
assert_detail(&check, "Access denied");
assert_fix(&check, "systemctl --user status second-brain.service");
assert!(!fix(&check).contains("bus"), "{check:?}");
assert!(!fix(&check).contains("linger"), "{check:?}");
}
#[test]
fn a_user_unit_without_systemctl_on_path_warns_to_run_the_api_under_the_hosts_supervisor() {
let m = Machine::new(Os::Linux);
let api_bin = m.binary(0o755);
m.write_unit(&m.user_unit_path(daemon::DEFAULT_UNIT), &api_bin);
let check = m.run(&mut NoSystemctl, &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Warn, "{check:?}");
assert_detail(&check, "systemctl is not on PATH");
assert_detail(&check, "systemd");
assert_fix(&check, "supervisor");
let api_bin = api_bin.display().to_string();
assert_fix(&check, &api_bin);
assert!(
!fix(&check).replace(&api_bin, "").contains("bus"),
"{check:?}"
);
assert!(!fix(&check).contains("linger"), "{check:?}");
assert!(!fix(&check).contains("sb setup"), "{check:?}");
}
#[test]
fn without_systemctl_the_supervisor_fix_names_the_program_the_unit_runs() {
let m = Machine::new(Os::Linux);
let unit_program = m.binary_at(&m.ctx.home.join("opt/brain/second-brain-api"), 0o755);
let beside_sb = m.binary(0o755);
m.write_unit(&m.user_unit_path(daemon::DEFAULT_UNIT), &unit_program);
let check = m.run(&mut NoSystemctl, &mut FakeLaunchctl::new(true));
assert_eq!(check.status, Status::Warn, "{check:?}");
assert_fix(&check, "supervisor");
assert_fix(&check, &unit_program.display().to_string());
assert!(
!fix(&check).contains(&*beside_sb.to_string_lossy()),
"{check:?}"
);
}
#[test]
fn a_system_unit_without_systemctl_on_path_warns_instead_of_failing() {
let m = Machine::new(Os::Linux);
system_unit(&m);
let check = m.run(&mut NoSystemctl, &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Warn, "{check:?}");
assert_detail(&check, "systemctl is not on PATH");
assert_detail(&check, "custom-brain.service");
assert_fix(&check, "supervisor");
assert_fix(&check, "ExecStart line of custom-brain.service");
assert!(!fix(&check).contains("second-brain-api"), "{check:?}");
}
#[test]
fn a_user_unit_on_a_host_not_booted_with_systemd_warns_without_querying_systemctl() {
let m = Machine::new(Os::Linux);
m.without_systemd_as_init();
let api_bin = m.binary(0o755);
m.write_unit(&m.user_unit_path(daemon::DEFAULT_UNIT), &api_bin);
let mut exec = FakeExec::not_booted_with_systemd();
let check = m.run(&mut exec, &mut FakeLaunchctl::new(true));
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(exec.calls.is_empty(), "{:?}", exec.calls);
assert_detail(&check, "systemd");
assert_detail(&check, daemon::DEFAULT_UNIT);
assert!(!check.detail.contains("not on PATH"), "{check:?}");
assert_fix(&check, "supervisor");
assert_fix(&check, &api_bin.display().to_string());
assert!(!fix(&check).contains("linger"), "{check:?}");
assert!(!fix(&check).contains("sb setup"), "{check:?}");
}
#[test]
fn a_system_unit_on_a_host_not_booted_with_systemd_warns_without_querying_systemctl() {
let m = Machine::new(Os::Linux);
m.without_systemd_as_init();
system_unit(&m);
let mut exec = FakeExec::not_booted_with_systemd();
let check = m.run(&mut exec, &mut FakeLaunchctl::new(true));
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(exec.calls.is_empty(), "{:?}", exec.calls);
assert_detail(&check, "custom-brain.service");
assert!(!check.detail.contains("not on PATH"), "{check:?}");
assert_fix(&check, "supervisor");
assert_fix(&check, "ExecStart line of custom-brain.service");
assert!(!fix(&check).contains("linger"), "{check:?}");
}
#[test]
fn a_launch_daemon_is_checked_even_where_systemd_is_not_init() {
let m = Machine::new(Os::MacOs);
m.without_systemd_as_init();
m.write_plist(launchd::DEFAULT_LABEL, &m.binary(0o755));
let check = m.run(&mut FakeExec::active(), &mut FakeLaunchctl::new(true));
assert_eq!(check.status, Status::Ok, "{check:?}");
}
#[test]
fn a_launchctl_that_cannot_run_fails_naming_the_command_and_error() {
let m = Machine::new(Os::MacOs);
m.write_plist(launchd::DEFAULT_LABEL, &m.binary(0o755));
let check = m.run(&mut FakeExec::active(), &mut BrokenLaunchctl);
assert_eq!(check.name, "service");
assert_eq!(check.status, Status::Fail);
assert_detail(&check, "launchctl print system/second-brain.api");
assert_detail(&check, "No such file or directory");
assert_fix(&check, "launchctl print system/second-brain.api");
assert!(!fix(&check).contains("sb setup"), "{check:?}");
}
}