use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{Context, Result, bail};
use crate::cli::{ScheduleAction, ScheduleArgs};
use crate::layout::{data_root, hex, sha256_file};
use crate::settings;
pub const JOB_LABEL: &str = "app.geolith.datasets-refresh";
pub const INSTALL_BIN: &str = ".local/share/geolith/bin/geolith";
pub const SCHEDULE_TEXT: &str = "daily at 08:30 local time (StartCalendarInterval 8:30, \
RunAtLoad false); a missed run happens at the next wake";
const PLIST_TEMPLATE: &str = include_str!("launchd/app.geolith.datasets-refresh.plist.tmpl");
const SERVICE_TEMPLATE: &str = include_str!("systemd/geolith-datasets-refresh.service.tmpl");
const TIMER_TEMPLATE: &str = include_str!("systemd/geolith-datasets-refresh.timer.tmpl");
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PlistVars {
pub bin: PathBuf,
pub bin_sha256: String,
pub data_root: PathBuf,
pub log_dir: PathBuf,
pub home: PathBuf,
pub path: String,
pub env_file: Option<PathBuf>,
pub config: Option<PathBuf>,
pub hour: u8,
pub minute: u8,
}
impl PlistVars {
#[must_use]
pub fn new(
bin: PathBuf,
bin_sha256: String,
data_root: PathBuf,
log_dir: PathBuf,
home: PathBuf,
path: String,
) -> Self {
Self {
bin,
bin_sha256,
data_root,
log_dir,
home,
path,
env_file: None,
config: None,
hour: 8,
minute: 30,
}
}
#[must_use]
pub fn with_settings(mut self, env_file: Option<PathBuf>, config: Option<PathBuf>) -> Self {
self.env_file = env_file;
self.config = config;
self
}
#[must_use]
pub fn fill(&self, template: &str) -> String {
let plist = template.contains("<plist");
let mut env_vars = String::new();
for (name, path) in [
("GEOLITH_ENV_FILE", &self.env_file),
("GEOLITH_CONFIG", &self.config),
] {
let Some(path) = path else { continue };
let text = path.display().to_string();
if plist {
env_vars.push_str(&format!(
"\n <key>{name}</key>\n <string>{}</string>",
xml_escape(&text)
));
} else {
env_vars.push_str(&format!(
"\nEnvironment={}",
shell_word(&format!("{name}={text}"))
));
}
}
template
.replace("__ENV_VARS__", &env_vars)
.replace("__BIN__", &self.bin.display().to_string())
.replace("__BIN_SHA256__", &self.bin_sha256)
.replace("__DATA_ROOT__", &self.data_root.display().to_string())
.replace("__LOG_DIR__", &self.log_dir.display().to_string())
.replace("__HOME__", &self.home.display().to_string())
.replace("__PATH__", &self.path)
.replace("__HOUR__", &self.hour.to_string())
.replace("__MINUTE__", &self.minute.to_string())
}
}
fn xml_escape(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
}
fn shell_word(text: &str) -> String {
if text
.chars()
.any(|c| c.is_whitespace() || c == '"' || c == '\\')
{
format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
} else {
text.to_owned()
}
}
#[must_use]
pub fn render_plist(vars: &PlistVars) -> String {
vars.fill(PLIST_TEMPLATE)
}
#[must_use]
pub fn render_service(vars: &PlistVars) -> String {
vars.fill(SERVICE_TEMPLATE)
}
#[must_use]
pub fn render_timer() -> String {
TIMER_TEMPLATE.to_owned()
}
pub fn install_binary(from: &Path, to: &Path) -> Result<String> {
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
}
let partial = to.with_extension("part");
fs::copy(from, &partial)
.with_context(|| format!("copying {} to {}", from.display(), partial.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let mode = fs::Permissions::from_mode(0o755);
fs::set_permissions(&partial, mode)
.with_context(|| format!("setting the mode of {}", partial.display()))?;
}
fs::rename(&partial, to).with_context(|| format!("renaming to {}", to.display()))?;
let digest = sha256_file(to)?;
fs::metadata(to).with_context(|| format!("reading {}", to.display()))?;
Ok(hex(&digest))
}
pub fn write_plist(dir: &Path, vars: &PlistVars) -> Result<PathBuf> {
fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
let path = dir.join(format!("{JOB_LABEL}.plist"));
fs::write(&path, render_plist(vars)).with_context(|| format!("writing {}", path.display()))?;
Ok(path)
}
#[must_use]
pub fn status_lines(
plist: &Path,
bin: &Path,
installed: Option<&str>,
running: &str,
history: &[String],
) -> Vec<String> {
let mut lines = vec![format!(
"plist: {} ({})",
plist.display(),
if plist.is_file() {
"installed"
} else {
"not installed"
}
)];
lines.push(match installed {
Some(digest) => format!(
"binary: {} ({}, {})",
bin.display(),
&digest[..digest.len().min(12)],
if digest == running {
"current"
} else {
"stale"
}
),
None => format!("binary: {} (missing)", bin.display()),
});
lines.push(format!("schedule: {SCHEDULE_TEXT}"));
for line in history {
lines.push(format!("history: {line}"));
}
lines
}
fn uid() -> u32 {
Command::new("id")
.arg("-u")
.output()
.ok()
.and_then(|output| String::from_utf8_lossy(&output.stdout).trim().parse().ok())
.unwrap_or(501)
}
fn launchctl(args: &[&str]) -> Result<String> {
let output = Command::new("/bin/launchctl")
.args(args)
.output()
.context("running launchctl")?;
if !output.status.success() {
bail!("{}", String::from_utf8_lossy(&output.stderr).trim());
}
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
fn last_history(data_root: &Path, count: usize) -> Vec<String> {
let path = data_root.join("datasets/refresh/history.jsonl");
let Ok(text) = fs::read_to_string(path) else {
return Vec::new();
};
let lines: Vec<&str> = text
.lines()
.filter(|line| !line.trim().is_empty())
.collect();
lines[lines.len().saturating_sub(count)..]
.iter()
.map(|line| (*line).to_owned())
.collect()
}
fn installed_digest(path: &Path) -> Option<String> {
sha256_file(path).ok().map(|digest| hex(&digest))
}
pub fn run(args: &ScheduleArgs) -> Result<()> {
let root = data_root()?;
let deployment = settings::current();
let home = deployment.home.clone().context("HOME is not set")?;
let dest = home.join(INSTALL_BIN);
let log_dir = root.join("datasets/refresh/logs");
let history = last_history(&root, 3);
let macos = cfg!(target_os = "macos");
let plist_dir = home.join("Library/LaunchAgents");
let plist = plist_dir.join(format!("{JOB_LABEL}.plist"));
let units = home.join(".config/systemd/user");
let running = std::env::current_exe().ok();
let running_digest = running
.as_deref()
.and_then(installed_digest)
.unwrap_or_default();
match args.action {
ScheduleAction::Status => {
let lines = status_lines(
&plist,
&dest,
installed_digest(&dest).as_deref(),
&running_digest,
&history,
);
for line in &lines {
println!("{line}");
}
if macos {
match launchctl(&["print", &format!("gui/{}/{JOB_LABEL}", uid())]) {
Ok(text) => {
let field = |name: &str| {
text.lines()
.find_map(|line| line.trim().strip_prefix(name))
.map(|value| value.trim().to_owned())
.unwrap_or_else(|| "unknown".to_owned())
};
println!(
"job: loaded, state = {}, last exit code = {}",
field("state = "),
field("last exit code = ")
);
}
Err(err) => println!("job: not loaded ({err})"),
}
} else {
println!(
"systemd: {}",
units.join("geolith-datasets-refresh.timer").display()
);
}
Ok(())
}
ScheduleAction::Uninstall => {
if macos {
let _ = launchctl(&["bootout", &format!("gui/{}/{JOB_LABEL}", uid())]);
fs::remove_file(&plist).ok();
println!("schedule: {JOB_LABEL} removed ({})", plist.display());
} else {
for unit in ["timer", "service"] {
fs::remove_file(units.join(format!("geolith-datasets-refresh.{unit}"))).ok();
}
println!(
"schedule: units removed from {}; run `systemctl --user daemon-reload`",
units.display()
);
}
println!("schedule: the binary stays at {}", dest.display());
Ok(())
}
ScheduleAction::Install => {
let from = running.context("cannot find the running binary")?;
let digest = install_binary(&from, &dest)?;
println!("BINARY {} {digest}", dest.display());
let path = deployment.path.clone().unwrap_or_else(|| {
"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin".to_owned()
});
let vars = PlistVars::new(dest.clone(), digest, root, log_dir, home, path)
.with_settings(deployment.env_file.clone(), deployment.config_file.clone());
if macos {
let written = write_plist(&plist_dir, &vars)?;
let _ = launchctl(&["bootout", &format!("gui/{}/{JOB_LABEL}", uid())]);
let domain = format!("gui/{}", uid());
if let Err(err) = launchctl(&["bootstrap", &domain, &written.display().to_string()])
{
eprintln!("schedule: launchctl bootstrap failed: {err}");
println!(
"schedule: fix it by hand: launchctl bootstrap {domain} {}",
written.display()
);
return Err(crate::exit::Exit(1).into());
}
launchctl(&["enable", &format!("{domain}/{JOB_LABEL}")])?;
println!("schedule: installed {}", written.display());
} else {
fs::create_dir_all(&units)
.with_context(|| format!("creating {}", units.display()))?;
fs::write(
units.join("geolith-datasets-refresh.service"),
render_service(&vars),
)
.context("writing the systemd service")?;
fs::write(units.join("geolith-datasets-refresh.timer"), render_timer())
.context("writing the systemd timer")?;
println!("systemctl --user daemon-reload");
println!("systemctl --user enable --now geolith-datasets-refresh.timer");
}
println!("schedule: {SCHEDULE_TEXT}");
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn vars(dir: &Path) -> PlistVars {
PlistVars::new(
dir.join("bin/geolith"),
"9f2c1d4e5a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f".to_owned(),
dir.join("data"),
dir.join("data/datasets/refresh/logs"),
dir.to_path_buf(),
"/usr/bin:/bin".to_owned(),
)
}
#[test]
fn the_plist_runs_the_installed_binary_and_never_the_script_folder() {
let dir = tempfile::tempdir().expect("a temp dir");
let plist = render_plist(&vars(dir.path()));
assert!(!plist.contains("scripts/datasets"), "{plist}");
assert!(!plist.contains("/bin/bash"), "{plist}");
assert!(plist.contains("<string>dataset</string>"));
assert!(plist.contains("<string>refresh</string>"));
assert!(plist.contains(&dir.path().join("bin/geolith").display().to_string()));
}
#[test]
fn the_written_plist_is_the_hand_written_expected_one() {
let dir = tempfile::tempdir().expect("a temp dir");
let home = PathBuf::from("/home/test");
let vars = PlistVars::new(
home.join(INSTALL_BIN),
"0123456789abcdef".to_owned(),
PathBuf::from("/home/test/.data"),
PathBuf::from("/home/test/.data/datasets/refresh/logs"),
home.clone(),
"/usr/bin:/bin".to_owned(),
);
let written = write_plist(dir.path(), &vars).expect("plist");
let text = fs::read_to_string(&written).expect("read the plist");
let expected = "\
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
<key>Label</key>
<string>app.geolith.datasets-refresh</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/caffeinate</string>
<string>-dimsu</string>
<string>/home/test/.local/share/geolith/bin/geolith</string>
<string>dataset</string>
<string>refresh</string>
</array>
<key>WorkingDirectory</key>
<string>/home/test/.data</string>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/usr/bin:/bin</string>
<key>HOME</key>
<string>/home/test</string>
<key>DATA_ROOT</key>
<string>/home/test/.data</string>
<key>GEOLITH_BIN</key>
<string>/home/test/.local/share/geolith/bin/geolith</string>
<key>GEOLITH_BIN_SHA256</key>
<string>0123456789abcdef</string>
</dict>
<key>RunAtLoad</key>
<false/>
<key>StartCalendarInterval</key>
<dict>
<key>Hour</key>
<integer>8</integer>
<key>Minute</key>
<integer>30</integer>
</dict>
<key>StandardOutPath</key>
<string>/home/test/.data/datasets/refresh/logs/launchd.out.log</string>
<key>StandardErrorPath</key>
<string>/home/test/.data/datasets/refresh/logs/launchd.err.log</string>
<key>ProcessType</key>
<string>Background</string>
<key>LowPriorityIO</key>
<true/>
<key>ThrottleInterval</key>
<integer>3600</integer>
</dict>
</plist>
";
let start = text.find("<plist").expect("plist element");
let actual = &text[start..];
let want = &expected[expected.find("<plist").expect("expected plist element")..];
assert_eq!(actual, want);
}
#[test]
fn a_job_with_an_env_file_names_it_in_its_environment_and_not_in_its_arguments() {
let dir = tempfile::tempdir().expect("a temp dir");
let with_env = vars(dir.path()).with_settings(
Some(PathBuf::from("/home/test/geolith/.env")),
Some(PathBuf::from("/home/test/a&b.json")),
);
let plist = render_plist(&with_env);
let want = "\
<key>GEOLITH_BIN_SHA256</key>
<string>9f2c1d4e5a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f</string>
<key>GEOLITH_ENV_FILE</key>
<string>/home/test/geolith/.env</string>
<key>GEOLITH_CONFIG</key>
<string>/home/test/a&b.json</string>
</dict>";
assert!(plist.contains(want), "{plist}");
assert!(!plist.contains("--config"), "{plist}");
assert!(
plist.contains(" <string>dataset</string>\n <string>refresh</string>"),
"{plist}"
);
let plain = render_plist(&vars(dir.path()));
assert!(!plain.contains("GEOLITH_ENV_FILE"), "{plain}");
assert!(!plain.contains("GEOLITH_CONFIG"), "{plain}");
}
#[test]
fn the_systemd_service_sets_the_env_file_and_quotes_a_path_with_a_space() {
let dir = tempfile::tempdir().expect("a temp dir");
let service = render_service(&vars(dir.path()).with_settings(
Some(PathBuf::from("/home/op/my ops/.env")),
Some(PathBuf::from("/home/op/geolith.json")),
));
let lines: Vec<&str> = service.lines().collect();
assert!(
lines.contains(&"Environment=\"GEOLITH_ENV_FILE=/home/op/my ops/.env\""),
"{service}"
);
assert!(
lines.contains(&"Environment=GEOLITH_CONFIG=/home/op/geolith.json"),
"{service}"
);
let exec = lines
.iter()
.find(|line| line.starts_with("ExecStart="))
.expect("an ExecStart line");
assert!(exec.ends_with(" dataset refresh"), "{exec}");
assert!(!service.contains("--config"), "{service}");
}
#[test]
fn the_install_copies_atomically_and_reports_the_digest_of_the_source() {
let dir = tempfile::tempdir().expect("a temp dir");
let from = dir.path().join("geolith");
fs::write(&from, b"binary").expect("write");
let to = dir.path().join("bin/geolith");
let digest = install_binary(&from, &to).expect("install");
assert_eq!(digest, hex(&sha256_file(&from).expect("sha256")));
assert_eq!(fs::read(&to).expect("read"), b"binary");
assert!(!dir.path().join("bin/geolith.part").exists());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let mode = fs::metadata(&to).expect("metadata").permissions().mode();
assert_eq!(mode & 0o777, 0o755);
}
}
#[test]
fn status_says_stale_when_the_installed_digest_differs() {
let dir = tempfile::tempdir().expect("a temp dir");
let plist = write_plist(dir.path(), &vars(dir.path())).expect("plist");
let stale = status_lines(
&plist,
&dir.path().join("bin/geolith"),
Some("aaaa"),
"bbbb",
&[],
);
assert_eq!(stale[0], format!("plist: {} (installed)", plist.display()));
assert!(stale[1].ends_with("(aaaa, stale)"), "{stale:?}");
let current = status_lines(
&plist,
&dir.path().join("bin/geolith"),
Some("bbbb"),
"bbbb",
&[],
);
assert!(current[1].ends_with("(bbbb, current)"), "{current:?}");
let missing = status_lines(&plist, &dir.path().join("bin/geolith"), None, "bbbb", &[]);
assert!(missing[1].ends_with("(missing)"), "{missing:?}");
}
#[test]
fn status_reports_an_uninstalled_plist() {
let dir = tempfile::tempdir().expect("a temp dir");
let lines = status_lines(
&dir.path().join("nope.plist"),
&dir.path().join("bin/geolith"),
None,
"x",
&[],
);
assert!(lines[0].ends_with("(not installed)"), "{lines:?}");
}
#[test]
fn the_systemd_units_run_the_binary_at_half_past_eight() {
let dir = tempfile::tempdir().expect("a temp dir");
let service = render_service(&vars(dir.path()));
assert!(service.contains(&format!(
"ExecStart={} dataset refresh",
dir.path().join("bin/geolith").display()
)));
assert!(service.contains("WorkingDirectory="));
let timer = render_timer();
assert!(timer.contains("OnCalendar=*-*-* 08:30:00"), "{timer}");
assert!(timer.contains("Persistent=true"), "{timer}");
}
}