Skip to content

armgit / kanzo

Public Imported from GitHub
0

Self-hosted, sharable kanban for humans and agents. One 4.7 MB binary, 5 MB of RAM, 10 to 60 tokens per agent reply, starts in 3 ms, zero setup.

Run kanzo service on Linux with a systemd user unit

emanuele-emaadd675ce28c
diff --git a/src/service.rs b/src/service.rs
index 1da30d3..8d1574a 100644
--- a/src/service.rs
+++ b/src/service.rs
@@ -1,4 +1,5 @@
-//! `kanzo service`: run the board at login with a macOS LaunchAgent.
+//! `kanzo service`: run the board in the background, started at login.
+//! A LaunchAgent on macOS, a systemd user unit on Linux (a Raspberry Pi, an old laptop).
use std::path::{Path, PathBuf};
use std::process::Command;
@@ -8,13 +9,49 @@ use anyhow::{Context, Result, bail};
use crate::home::Home;
const LABEL: &str = "com.github.emanuele-em.kanzo";
+const UNIT: &str = "kanzo.service";
+
+pub fn install(home: &Home) -> Result<()> {
+ let exe = std::env::current_exe().context("cannot find the kanzo program")?;
+ if cfg!(target_os = "macos") {
+ install_launchd(home, &exe)
+ } else if cfg!(target_os = "linux") {
+ install_systemd(home, &exe)
+ } else {
+ bail!("kanzo service supports macOS and Linux; start `kanzo --no-open` with your own service manager")
+ }
+}
+
+pub fn uninstall() -> Result<()> {
+ if cfg!(target_os = "macos") {
+ uninstall_launchd()
+ } else if cfg!(target_os = "linux") {
+ uninstall_systemd()
+ } else {
+ bail!("kanzo service supports macOS and Linux")
+ }
+}
+
+fn home_dir() -> Result<PathBuf> {
+ dirs::home_dir().context("cannot find your home folder")
+}
+
+/// Runs a command and fails with its own error output.
+fn run(cmd: &str, args: &[&str]) -> Result<()> {
+ let out = Command::new(cmd).args(args).output().with_context(|| format!("cannot run {cmd}"))?;
+ if !out.status.success() {
+ bail!("{cmd} {} failed: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
+ }
+ Ok(())
+}
+
+// macOS
fn plist_path() -> Result<PathBuf> {
- let home = dirs::home_dir().context("cannot find your home folder")?;
- Ok(home.join("Library/LaunchAgents").join(format!("{LABEL}.plist")))
+ Ok(home_dir()?.join("Library/LaunchAgents").join(format!("{LABEL}.plist")))
}
-fn domain() -> Result<String> {
+fn launchd_domain() -> Result<String> {
let uid = Command::new("id").arg("-u").output().context("cannot run id -u")?;
Ok(format!("gui/{}", String::from_utf8_lossy(&uid.stdout).trim()))
}
@@ -58,24 +95,15 @@ fn plist(exe: &Path, dir: &Path, log: &Path) -> String {
)
}
-pub fn install(home: &Home) -> Result<()> {
- if !cfg!(target_os = "macos") {
- bail!("kanzo service only supports macOS; start `kanzo --no-open` with your own init system");
- }
- let exe = std::env::current_exe().context("cannot find the kanzo program")?;
- let log = dirs::home_dir().context("cannot find your home folder")?.join("Library/Logs/kanzo.log");
- let plist = plist(&exe, &home.dir, &log);
-
+fn install_launchd(home: &Home, exe: &Path) -> Result<()> {
+ let log = home_dir()?.join("Library/Logs/kanzo.log");
let path = plist_path()?;
std::fs::create_dir_all(path.parent().expect("plist path has a parent"))?;
- let domain = domain()?;
+ let domain = launchd_domain()?;
// Replace an older install so a changed path or data folder takes effect.
let _ = Command::new("launchctl").args(["bootout", &format!("{domain}/{LABEL}")]).output();
- std::fs::write(&path, plist).with_context(|| format!("cannot write {}", path.display()))?;
- let out = Command::new("launchctl").args(["bootstrap", &domain]).arg(&path).output()?;
- if !out.status.success() {
- bail!("launchctl bootstrap failed: {}", String::from_utf8_lossy(&out.stderr).trim());
- }
+ std::fs::write(&path, plist(exe, &home.dir, &log)).with_context(|| format!("cannot write {}", path.display()))?;
+ run("launchctl", &["bootstrap", &domain, &path.to_string_lossy()])?;
println!(
"Kanzo now starts at login and is running at http://localhost:{}\nLogs: {}",
home.config.port,
@@ -84,9 +112,9 @@ pub fn install(home: &Home) -> Result<()> {
Ok(())
}
-pub fn uninstall() -> Result<()> {
+fn uninstall_launchd() -> Result<()> {
let path = plist_path()?;
- let _ = Command::new("launchctl").args(["bootout", &format!("{}/{LABEL}", domain()?)]).output();
+ let _ = Command::new("launchctl").args(["bootout", &format!("{}/{LABEL}", launchd_domain()?)]).output();
if path.exists() {
std::fs::remove_file(&path).with_context(|| format!("cannot remove {}", path.display()))?;
println!("Removed the Kanzo LaunchAgent; the board no longer starts at login.");
@@ -96,6 +124,68 @@ pub fn uninstall() -> Result<()> {
Ok(())
}
+// Linux
+
+fn unit_path() -> Result<PathBuf> {
+ let config = match std::env::var_os("XDG_CONFIG_HOME").filter(|v| !v.is_empty()) {
+ Some(dir) => PathBuf::from(dir),
+ None => home_dir()?.join(".config"),
+ };
+ Ok(config.join("systemd/user").join(UNIT))
+}
+
+/// Quotes one argument for a systemd `ExecStart=` line.
+fn systemd_quote(s: &str) -> String {
+ format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%"))
+}
+
+fn unit(exe: &Path, dir: &Path) -> String {
+ format!(
+ "[Unit]\n\
+ Description=Kanzo board\n\
+ After=network.target\n\
+ \n\
+ [Service]\n\
+ ExecStart={} --no-open --home {}\n\
+ Restart=on-failure\n\
+ \n\
+ [Install]\n\
+ WantedBy=default.target\n",
+ systemd_quote(&exe.to_string_lossy()),
+ systemd_quote(&dir.to_string_lossy()),
+ )
+}
+
+fn install_systemd(home: &Home, exe: &Path) -> Result<()> {
+ let path = unit_path()?;
+ std::fs::create_dir_all(path.parent().expect("unit path has a parent"))?;
+ std::fs::write(&path, unit(exe, &home.dir)).with_context(|| format!("cannot write {}", path.display()))?;
+ run("systemctl", &["--user", "daemon-reload"])?;
+ run("systemctl", &["--user", "enable", UNIT])?;
+ // Restart rather than start, so a changed path or data folder takes effect.
+ run("systemctl", &["--user", "restart", UNIT])?;
+ println!(
+ "Kanzo now starts at login and is running at http://localhost:{}\n\
+ Logs: journalctl --user -u kanzo\n\
+ To start it at boot without logging in (a board with no screen): sudo loginctl enable-linger $USER",
+ home.config.port
+ );
+ Ok(())
+}
+
+fn uninstall_systemd() -> Result<()> {
+ let path = unit_path()?;
+ let _ = Command::new("systemctl").args(["--user", "disable", "--now", UNIT]).output();
+ if path.exists() {
+ std::fs::remove_file(&path).with_context(|| format!("cannot remove {}", path.display()))?;
+ let _ = Command::new("systemctl").args(["--user", "daemon-reload"]).output();
+ println!("Removed the Kanzo service; the board no longer starts at login.");
+ } else {
+ println!("The Kanzo service was not installed.");
+ }
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -111,4 +201,14 @@ mod tests {
assert!(lint.status.success(), "{}", String::from_utf8_lossy(&lint.stdout));
assert!(text.contains("/Users/a &amp; b/kanzo"));
}
+
+ #[test]
+ fn unit_quotes_paths() {
+ let text = unit(Path::new("/home/pi/.cargo/bin/kanzo"), Path::new("/home/pi/my \"kanzo\" 100%"));
+ assert!(
+ text.contains(r#"ExecStart="/home/pi/.cargo/bin/kanzo" --no-open --home "/home/pi/my \"kanzo\" 100%%""#),
+ "{text}"
+ );
+ assert!(text.contains("WantedBy=default.target"));
+ }
}