//! Per-app install flow: download, check, swap, restart, health check, rollback. //! State files in `state_dir`: `{name}.bad` lists rejected sha256s, `{name}.tag` the last tag installed, //! `{name}.sha` the installed sha256 (unpack mode only). use crate::Res; use crate::config::{App, Config}; use crate::forge::Forge; use sha2::{Digest, Sha256}; use std::fs::{self, File, OpenOptions}; use std::io::{ErrorKind, Read, Write}; use std::os::unix::fs::DirBuilderExt; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::thread::sleep; use std::time::{Duration, Instant}; const CHECK_TIMEOUT: Duration = Duration::from_secs(10); const HEALTH_REQUEST_TIMEOUT: Duration = Duration::from_secs(5); const STABLE_FOR: Duration = Duration::from_secs(5); /// Creates the state directory (mode 0700) if it does not exist. pub fn ensure_state_dir(dir: &Path) -> Res<()> { fs::DirBuilder::new() .recursive(true) .mode(0o700) .create(dir) .map_err(|e| format!("state dir {}: {e}", dir.display())) } /// Takes the exclusive run lock (`state_dir/lock`). Fails at once if another run holds it. pub fn lock(dir: &Path) -> Res { let path = dir.join("lock"); let file = File::create(&path).map_err(|e| format!("open {}: {e}", path.display()))?; file.try_lock() .map_err(|_| "another kur run is in progress".to_string())?; Ok(file) } /// `kur status` text for one app (after the name). Changes nothing. pub fn status(forge: &Forge, cfg: &Config, app: &App) -> Res { let (tag, asset) = forge.latest(app)?; let installed = installed_sha(cfg, app)?; let state = if installed.as_deref() == Some(asset.sha256.as_str()) { "up to date" } else if is_bad(cfg, app, &asset.sha256)? { "skipped (bad build)" } else { "update available" }; let inst = match &installed { Some(sha) => format!("installed {}", short(sha)), None => "not installed".to_string(), }; Ok(format!( "{inst}, newest {tag} {}: {state}", short(&asset.sha256) )) } /// Installs the newest release of one app if needed. Returns the status text after the app name. pub fn update(forge: &Forge, cfg: &Config, app: &App) -> Res { let (tag, asset) = forge.latest(app)?; if installed_sha(cfg, app)?.as_deref() == Some(asset.sha256.as_str()) { return Ok(format!("up to date ({tag})")); } if is_bad(cfg, app, &asset.sha256)? { return Ok(format!("skipped (bad build {tag})")); } let staged = app.sibling(".kur-new"); if app.unpack { let archive = app.sibling(".kur-new.tar.gz"); let _ = fs::remove_file(&archive); remove_tree(&staged)?; if let Err(e) = forge.download(&asset, &archive) { let _ = fs::remove_file(&archive); return Err(e); } let unpacked = unpack(&archive, &staged); let _ = fs::remove_file(&archive); if let Err(e) = unpacked { let _ = fs::remove_dir_all(&staged); mark_bad(cfg, app, &asset.sha256)?; return Err(e); } } else { let _ = fs::remove_file(&staged); if let Err(e) = forge.download(&asset, &staged) { let _ = fs::remove_file(&staged); return Err(e); } if let Err(e) = check_binary(app, &staged) { let _ = fs::remove_file(&staged); mark_bad(cfg, app, &asset.sha256)?; return Err(e); } } swap(app, &staged)?; let Some(unit) = app.unit.as_deref() else { record_install(cfg, app, &tag, &asset.sha256)?; return Ok(format!("{tag} installed")); }; match deploy(app, unit) { Ok(()) => { record_install(cfg, app, &tag, &asset.sha256)?; Ok(format!("{tag} installed")) } Err(reason) => { let marked = mark_bad(cfg, app, &asset.sha256); let mut msg = rollback(app, unit, &tag, &reason); if let Err(e) = marked { msg = format!("{msg}; could not record bad build: {e}"); } Err(msg) } } } /// First 12 hex chars of a sha256, for display. fn short(sha: &str) -> &str { sha.get(..12).unwrap_or(sha) } /// sha256 of the installed app: of the file, or in unpack mode the one recorded at install. /// None if nothing is installed. fn installed_sha(cfg: &Config, app: &App) -> Res> { if !app.unpack { return file_sha256(&app.path); } if !app.path.exists() { return Ok(None); } match fs::read_to_string(state_file(cfg, app, "sha")) { Ok(text) => Ok(Some(text.trim().to_string())), Err(e) if e.kind() == ErrorKind::NotFound => Ok(None), Err(e) => Err(format!("read sha: {e}")), } } /// Removes the directory tree at `path`. A missing path is not an error. fn remove_tree(path: &Path) -> Res<()> { match fs::remove_dir_all(path) { Err(e) if e.kind() != ErrorKind::NotFound => Err(format!("remove {}: {e}", path.display())), _ => Ok(()), } } /// Lowercase hex sha256 of the file at `path`, or None if it does not exist. pub(crate) fn file_sha256(path: &Path) -> Res> { let mut file = match File::open(path) { Ok(file) => file, Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None), Err(e) => return Err(format!("open {}: {e}", path.display())), }; let mut hasher = Sha256::new(); let mut buf = vec![0u8; 64 * 1024]; loop { let n = file .read(&mut buf) .map_err(|e| format!("read {}: {e}", path.display()))?; if n == 0 { break; } hasher.update(&buf[..n]); } Ok(Some(hex::encode(hasher.finalize()))) } fn state_file(cfg: &Config, app: &App, ext: &str) -> PathBuf { cfg.state_dir.join(format!("{}.{ext}", app.name)) } /// Whether `sha` is listed in the app's `.bad` file. fn is_bad(cfg: &Config, app: &App, sha: &str) -> Res { match fs::read_to_string(state_file(cfg, app, "bad")) { Ok(text) => Ok(text.lines().any(|line| line.trim() == sha)), Err(e) if e.kind() == ErrorKind::NotFound => Ok(false), Err(e) => Err(format!("read bad list: {e}")), } } fn mark_bad(cfg: &Config, app: &App, sha: &str) -> Res<()> { let path = state_file(cfg, app, "bad"); let mut file = OpenOptions::new() .create(true) .append(true) .open(&path) .map_err(|e| format!("open {}: {e}", path.display()))?; writeln!(file, "{sha}").map_err(|e| format!("write {}: {e}", path.display())) } fn write_tag(cfg: &Config, app: &App, tag: &str) -> Res<()> { let path = state_file(cfg, app, "tag"); fs::write(&path, tag).map_err(|e| format!("write {}: {e}", path.display())) } /// Records a successful install: the tag, and in unpack mode the asset sha256. fn record_install(cfg: &Config, app: &App, tag: &str, sha: &str) -> Res<()> { write_tag(cfg, app, tag)?; if app.unpack { let path = state_file(cfg, app, "sha"); fs::write(&path, sha).map_err(|e| format!("write {}: {e}", path.display()))?; } Ok(()) } /// Unpacks the gzip tar at `archive` into `dir`, which must not exist yet. fn unpack(archive: &Path, dir: &Path) -> Res<()> { fs::create_dir(dir).map_err(|e| format!("create {}: {e}", dir.display()))?; let status = Command::new("tar") .arg("-xzf") .arg(archive) .arg("-C") .arg(dir) .stdin(Stdio::null()) .status() .map_err(|e| format!("cannot run tar: {e}"))?; if status.success() { Ok(()) } else { Err(format!("tar exited with {status}")) } } /// Runs the staged binary with the app's `check` args, if any. Fails on non-zero exit or timeout. fn check_binary(app: &App, staged: &Path) -> Res<()> { let Some(args) = &app.check else { return Ok(()); }; let mut child = Command::new(staged) .args(args) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() .map_err(|e| format!("cannot run staged binary: {e}"))?; let deadline = Instant::now() + CHECK_TIMEOUT; loop { if let Some(status) = child.try_wait().map_err(|e| format!("check: {e}"))? { return if status.success() { Ok(()) } else { Err(format!("check exited with {status}")) }; } if Instant::now() >= deadline { let _ = child.kill(); let _ = child.wait(); return Err("check timed out".into()); } sleep(Duration::from_millis(50)); } } /// Moves the current binary (or directory, in unpack mode) to `.prev` and the staged one into place, /// then fsyncs the dir. fn swap(app: &App, staged: &Path) -> Res<()> { if app.unpack { remove_tree(&app.sibling(".prev"))?; } match fs::rename(&app.path, app.sibling(".prev")) { Err(e) if e.kind() != ErrorKind::NotFound => { return Err(format!("keep previous {}: {e}", app.path.display())); } _ => {} } fs::rename(staged, &app.path).map_err(|e| format!("install {}: {e}", app.path.display()))?; let dir = app.path.parent().unwrap_or(Path::new("/")); File::open(dir) .and_then(|d| d.sync_all()) .map_err(|e| format!("fsync {}: {e}", dir.display())) } /// Restarts `unit` and waits until it is active and healthy, then requires it to stay active. /// Returns the failure reason on error. fn deploy(app: &App, unit: &str) -> Result<(), String> { restart(unit)?; let deadline = Instant::now() + Duration::from_secs(app.health_timeout_secs); while !(is_active(unit) && health_ok(app.health_url.as_deref())) { if Instant::now() >= deadline { return Err("health check timed out".into()); } sleep(Duration::from_secs(1)); } sleep(STABLE_FOR); if !is_active(unit) { return Err(format!("{unit} stopped after health check")); } Ok(()) } /// Restores `.prev` over the failed binary and restarts the unit. Returns the error text. fn rollback(app: &App, unit: &str, tag: &str, reason: &str) -> String { let failed = format!("{tag} failed health check ({reason})"); if app.unpack && let Err(e) = remove_tree(&app.path) { return format!("{failed}, restore failed: {e}"); } match fs::rename(app.sibling(".prev"), &app.path) { Ok(()) => match restart(unit) { Ok(()) => format!("{failed}, rolled back"), Err(e) => format!("{failed}, rolled back but {e}"), }, Err(e) if e.kind() == ErrorKind::NotFound => { format!("{failed}, no previous binary to restore") } Err(e) => format!("{failed}, restore failed: {e}"), } } /// True if `url` is unset or answers 2xx within the request timeout. No token is sent. fn health_ok(url: Option<&str>) -> bool { let Some(url) = url else { return true; }; ureq::get(url) .config() .timeout_global(Some(HEALTH_REQUEST_TIMEOUT)) .build() .call() .is_ok_and(|resp| resp.status().is_success()) } fn restart(unit: &str) -> Result<(), String> { systemctl(&["restart", unit]) } fn is_active(unit: &str) -> bool { systemctl(&["is-active", "--quiet", unit]).is_ok() } /// Runs `systemctl --user` with `args`. Only the user manager of the account kur runs as is used. pub(crate) fn systemctl(args: &[&str]) -> Result<(), String> { let status = Command::new("systemctl") .arg("--user") .args(args) .stdout(Stdio::null()) .status() .map_err(|e| format!("systemctl: {e}"))?; if status.success() { Ok(()) } else { Err(format!("systemctl {} failed", args.join(" "))) } }