From 27194b7b003be5214e2a25ce2e9bf142f3ea5106 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 11:54:44 +0100 Subject: [PATCH] [linux] Linux target: release dirs, atomic symlink switch, systemctl restart, health check, auto rollback, pruning --- crates/linux/src/lib.rs | 599 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 598 insertions(+), 1 deletion(-) diff --git a/crates/linux/src/lib.rs b/crates/linux/src/lib.rs index ebf61a3..7588e79 100644 --- a/crates/linux/src/lib.rs +++ b/crates/linux/src/lib.rs @@ -1 +1,598 @@ -//! Legatus Linux target (code follows its tests). +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Legatus's Linux (systemd) target (docs/01_legatus.md): +//! +//! ```text +//! //releases// one dir per release, unpacked from the signed artifact +//! //current -> releases/ +//! //sums/ the artifact's SHA-256 the dir was made from +//! //history versions switched to, oldest first +//! ``` +//! +//! [`unpack`] makes a release dir from a `.tar.gz` (which the agent has already checked against +//! the signed manifest). [`LinuxBackend::deploy`] switches `current` atomically, restarts the +//! unit, checks health, and rolls back to the previous release when the check fails. +//! +//! The caller has verified the release's signature before any of this runs. + +use std::fs; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use legatus_protocol::{ + ArchiveError, EntryKind, MAX_ARCHIVE_BYTES, MAX_ARCHIVE_ENTRIES, check_entry, msg::valid_unit, + valid_version, +}; + +/// Where apps live by default. +pub const DEFAULT_ROOT: &str = "/var/lib/legatus/apps"; + +/// The paths of the release layout under one root. +#[derive(Debug, Clone)] +pub struct Layout { + root: PathBuf, +} + +impl Layout { + /// A layout under `root` (normally [`DEFAULT_ROOT`]). + pub fn new(root: impl Into) -> Layout { + Layout { root: root.into() } + } + + /// `/`. + pub fn app_dir(&self, app: &str) -> PathBuf { + self.root.join(app) + } + + /// `//releases`. + pub fn releases_dir(&self, app: &str) -> PathBuf { + self.app_dir(app).join("releases") + } + + /// `//releases/`. + pub fn release_dir(&self, app: &str, version: &str) -> PathBuf { + self.releases_dir(app).join(version) + } + + /// `//current`. + pub fn current_link(&self, app: &str) -> PathBuf { + self.app_dir(app).join("current") + } + + fn sum_file(&self, app: &str, version: &str) -> PathBuf { + self.app_dir(app).join("sums").join(version) + } + + fn history_file(&self, app: &str) -> PathBuf { + self.app_dir(app).join("history") + } + + /// The version `current` points at, if any. + pub fn current(&self, app: &str) -> Option { + let target = fs::read_link(self.current_link(app)).ok()?; + let mut parts = target.components(); + let first = parts.next()?.as_os_str().to_str()?; + let v = parts.next()?.as_os_str().to_str()?.to_owned(); + (first == "releases" && parts.next().is_none() && valid_version(&v)).then_some(v) + } + + /// The release dir `current` points at, if any. + pub fn current_dir(&self, app: &str) -> Option { + self.current(app).map(|v| self.release_dir(app, &v)) + } + + fn history(&self, app: &str) -> Vec { + fs::read_to_string(self.history_file(app)) + .unwrap_or_default() + .lines() + .filter(|l| valid_version(l)) + .map(str::to_owned) + .collect() + } +} + +/// Why a release dir was not made. Nothing that runs was changed. +#[derive(Debug, thiserror::Error)] +pub enum UnpackError { + /// An app or version name that cannot be a path. + #[error("the app or version name cannot be used")] + Name, + /// This version is already here with other content. + #[error("this version is already on this host with different content")] + VersionClash, + /// The archive is refused. + #[error("{0}")] + Archive(#[from] ArchiveError), + /// The disk. + #[error("the release could not be written: {0}")] + Io(String), +} + +fn io_err(e: io::Error) -> UnpackError { + UnpackError::Io(e.to_string()) +} + +static NONCE: AtomicU64 = AtomicU64::new(0); + +fn nonce() -> String { + let n = NONCE.fetch_add(1, Ordering::Relaxed); + let t = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.subsec_nanos()) + .unwrap_or(0); + format!("{}-{n}-{t}", std::process::id()) +} + +/// Unpack a `.tar.gz` into `releases/` (atomically: a staging dir renamed into place), +/// remembering that it was made from an artifact with SHA-256 `sha256`. The same version with +/// the same SHA-256 again is reused; with another one it is refused. +pub fn unpack( + layout: &Layout, + app: &str, + version: &str, + archive: impl Read, + sha256: &str, +) -> Result { + if !domi_like_id(app) || !valid_version(version) { + return Err(UnpackError::Name); + } + let dir = layout.release_dir(app, version); + let sum_file = layout.sum_file(app, version); + if dir.exists() { + return match fs::read_to_string(&sum_file) { + Ok(s) if s.trim() == sha256 => Ok(dir), + _ => Err(UnpackError::VersionClash), + }; + } + let releases = layout.releases_dir(app); + fs::create_dir_all(&releases).map_err(io_err)?; + let staging = releases.join(format!(".incoming-{version}-{}", nonce())); + fs::create_dir(&staging).map_err(io_err)?; + let result = extract(archive, &staging).and_then(|()| { + fs::rename(&staging, &dir).map_err(io_err)?; + write_atomic(&sum_file, sha256.as_bytes()).map_err(io_err) + }); + if let Err(e) = result { + let _ = fs::remove_dir_all(&staging); + return Err(e); + } + Ok(dir) +} + +/// App ids are domi-pki ids (`a-z 0-9 -`). +fn domi_like_id(id: &str) -> bool { + (1..=40).contains(&id.len()) + && id + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + && !id.starts_with('-') + && !id.ends_with('-') +} + +fn extract(archive: impl Read, into: &Path) -> Result<(), UnpackError> { + let gz = flate2::read::GzDecoder::new(archive); + let mut tar = tar::Archive::new(gz); + let entries = tar.entries().map_err(|_| ArchiveError::Corrupt)?; + let (mut count, mut total, mut files) = (0usize, 0u64, 0usize); + for entry in entries { + let mut entry = entry.map_err(|_| ArchiveError::Corrupt)?; + count += 1; + if count > MAX_ARCHIVE_ENTRIES { + return Err(ArchiveError::TooMany.into()); + } + let kind = match entry.header().entry_type() { + tar::EntryType::Regular | tar::EntryType::Continuous => EntryKind::File, + tar::EntryType::Directory => EntryKind::Dir, + tar::EntryType::Symlink => EntryKind::Symlink, + tar::EntryType::Link => EntryKind::Hardlink, + _ => EntryKind::Other, + }; + let size = entry.header().size().map_err(|_| ArchiveError::Corrupt)?; + let path_bytes = entry.path_bytes().into_owned(); + let path = std::str::from_utf8(&path_bytes).map_err(|_| ArchiveError::Path)?; + let parts = check_entry(kind, path, size)?; + total = total.saturating_add(size); + if total > MAX_ARCHIVE_BYTES { + return Err(ArchiveError::TooLarge.into()); + } + let mut target = into.to_path_buf(); + for p in &parts { + target.push(p); + } + match kind { + EntryKind::Dir => fs::create_dir_all(&target).map_err(io_err)?, + _ => { + if let Some(parent) = target.parent() { + fs::create_dir_all(parent).map_err(io_err)?; + } + let mode = entry.header().mode().unwrap_or(0o644); + let mut out = create_new(&target, mode & 0o111 != 0).map_err(io_err)?; + let written = io::copy(&mut (&mut entry).take(size), &mut out).map_err(io_err)?; + if written != size { + return Err(ArchiveError::Corrupt.into()); + } + out.sync_all().map_err(io_err)?; + files += 1; + } + } + } + if files == 0 { + return Err(ArchiveError::Corrupt.into()); + } + Ok(()) +} + +fn create_new(path: &Path, exec: bool) -> io::Result { + let mut o = fs::OpenOptions::new(); + o.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + o.mode(if exec { 0o755 } else { 0o644 }); + } + #[cfg(not(unix))] + let _ = exec; + o.open(path) +} + +fn write_atomic(path: &Path, data: &[u8]) -> io::Result<()> { + let parent = path + .parent() + .ok_or_else(|| io::Error::other("no parent dir"))?; + fs::create_dir_all(parent)?; + let tmp = parent.join(format!(".tmp-{}", nonce())); + fs::write(&tmp, data)?; + fs::rename(&tmp, path) +} + +// ------------------------------------------------------------------ services and health + +/// systemd, as the backend needs it. +pub trait Services { + /// `systemctl restart `. + fn restart(&self, unit: &str) -> Result<(), String>; + /// `systemctl is-active `. + fn is_active(&self, unit: &str) -> bool; +} + +/// The local health endpoint. +pub trait Health { + /// One attempt: does `url` answer 2xx? + fn check(&self, url: &str) -> bool; +} + +/// The real systemd, through `systemctl`. +#[derive(Debug, Default, Clone, Copy)] +pub struct Systemctl; + +impl Services for Systemctl { + fn restart(&self, unit: &str) -> Result<(), String> { + if !valid_unit(unit) { + return Err("the unit name is not valid".into()); + } + let out = std::process::Command::new("systemctl") + .args(["restart", "--", unit]) + .output() + .map_err(|e| format!("systemctl could not run: {e}"))?; + if out.status.success() { + Ok(()) + } else { + let msg: String = String::from_utf8_lossy(&out.stderr) + .chars() + .take(300) + .collect(); + Err(format!("systemctl restart {unit} failed: {}", msg.trim())) + } + } + + fn is_active(&self, unit: &str) -> bool { + valid_unit(unit) + && std::process::Command::new("systemctl") + .args(["is-active", "--quiet", "--", unit]) + .status() + .is_ok_and(|s| s.success()) + } +} + +/// A plain HTTP/1.1 GET to a local URL (the protocol only allows 127.0.0.1, localhost, [::1]). +#[derive(Debug, Default, Clone, Copy)] +pub struct HttpHealth; + +impl Health for HttpHealth { + fn check(&self, url: &str) -> bool { + http_status(url).is_some_and(|s| (200..300).contains(&s)) + } +} + +fn http_status(url: &str) -> Option { + use std::io::Write; + use std::net::ToSocketAddrs; + if !legatus_protocol::msg::local_http_url(url) { + return None; + } + let rest = url.strip_prefix("http://")?; + let (auth, path) = match rest.find('/') { + Some(i) => rest.split_at(i), + None => (rest, "/"), + }; + let addr = if auth.starts_with('[') || auth.contains(':') { + auth.to_owned() + } else { + format!("{auth}:80") + }; + let sock = addr.to_socket_addrs().ok()?.next()?; + let t = Duration::from_secs(2); + let mut s = std::net::TcpStream::connect_timeout(&sock, t).ok()?; + s.set_read_timeout(Some(t)).ok()?; + s.set_write_timeout(Some(t)).ok()?; + write!(s, "GET {path} HTTP/1.1\r\nHost: {auth}\r\nConnection: close\r\nUser-Agent: legatus-health\r\n\r\n").ok()?; + let mut buf = [0u8; 64]; + let n = s.read(&mut buf).ok()?; + let line = std::str::from_utf8(buf.get(..n)?).ok()?; + let mut words = line.split_whitespace(); + if !words.next()?.starts_with("HTTP/1.") { + return None; + } + words.next()?.parse().ok() +} + +// ------------------------------------------------------------------ deploying + +/// One deploy, as the job gives it. +#[derive(Debug, Clone)] +pub struct Plan<'a> { + /// App id. + pub app: &'a str, + /// Version. + pub version: &'a str, + /// The systemd unit. + pub unit: &'a str, + /// A local health URL, if any. + pub health_url: Option<&'a str>, + /// How long the health check may take. + pub health_timeout: Duration, + /// Releases kept. + pub keep: u32, +} + +/// How a deploy ended. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + /// The new release runs and is healthy. + Succeeded { + /// The release that ran before, if any. + previous: Option, + }, + /// The new release failed; `current` points at `to` again and it was restarted. + RolledBack { + /// The release running again. + to: String, + /// Did the rolled-back release pass its health check? + healthy: bool, + /// Why the new release failed. + reason: String, + }, + /// The new release failed and there was nothing to roll back to. + Failed { + /// Why. + reason: String, + }, +} + +impl Outcome { + /// Why it failed ("" when it did not). + pub fn reason(&self) -> &str { + match self { + Outcome::Succeeded { .. } => "", + Outcome::RolledBack { reason, .. } | Outcome::Failed { reason } => reason, + } + } +} + +/// Why a deploy did not start: nothing that runs was changed. +#[derive(Debug, thiserror::Error)] +pub enum DeployError { + /// The archive or the names. + #[error("{0}")] + Unpack(#[from] UnpackError), + /// The unit name. + #[error("the unit name is not valid")] + Unit, + /// The symlink could not be switched. + #[error("the release could not be switched: {0}")] + Switch(String), +} + +/// The Linux target. +pub struct LinuxBackend { + layout: Layout, + services: S, + health: H, + poll: Duration, +} + +impl LinuxBackend { + /// A backend over `layout` with these services and health check. + pub fn new(layout: Layout, services: S, health: H) -> LinuxBackend { + LinuxBackend { + layout, + services, + health, + poll: Duration::from_secs(1), + } + } + + /// How often the health check is tried (tests make it short). + pub fn with_poll(mut self, poll: Duration) -> Self { + self.poll = poll; + self + } + + /// The layout. + pub fn layout(&self) -> &Layout { + &self.layout + } + + /// The services. + pub fn services(&self) -> &S { + &self.services + } + + /// Every app with a current release: `(app, version)`, sorted. + pub fn deployed(&self) -> Vec<(String, String)> { + let mut out = Vec::new(); + if let Ok(rd) = fs::read_dir(&self.layout.root) { + for e in rd.flatten() { + let Some(app) = e.file_name().to_str().map(str::to_owned) else { + continue; + }; + if let Some(v) = self.layout.current(&app) { + out.push((app, v)); + } + } + } + out.sort(); + out + } + + /// Point `current` at `releases/` atomically: a new symlink renamed over the old + /// one, so `current` always names a whole release. Returns the version it pointed at before. + #[cfg(unix)] + pub fn switch(&self, app: &str, version: &str) -> Result, DeployError> { + if !domi_like_id(app) || !valid_version(version) { + return Err(UnpackError::Name.into()); + } + let sw = |e: io::Error| DeployError::Switch(e.to_string()); + if !self.layout.release_dir(app, version).is_dir() { + return Err(DeployError::Switch(format!( + "release {version} is not on disk" + ))); + } + let previous = self.layout.current(app); + let app_dir = self.layout.app_dir(app); + let tmp = app_dir.join(format!(".current-{}", nonce())); + std::os::unix::fs::symlink(Path::new("releases").join(version), &tmp).map_err(sw)?; + if let Err(e) = fs::rename(&tmp, self.layout.current_link(app)) { + let _ = fs::remove_file(&tmp); + return Err(sw(e)); + } + fs::File::open(&app_dir) + .and_then(|d| d.sync_all()) + .map_err(sw)?; + let mut history = self.layout.history(app); + history.retain(|v| v != version); + history.push(version.to_owned()); + let keep_from = history.len().saturating_sub(100); + let text: String = history[keep_from..] + .iter() + .map(|v| format!("{v}\n")) + .collect(); + write_atomic(&self.layout.history_file(app), text.as_bytes()).map_err(sw)?; + Ok(previous) + } + + /// Not available off Unix. + #[cfg(not(unix))] + pub fn switch(&self, _app: &str, _version: &str) -> Result, DeployError> { + Err(DeployError::Switch( + "the Linux target runs on Linux only".into(), + )) + } + + /// Wait until the unit is active and the health URL answers, twice in a row, within the + /// timeout. + fn wait_healthy(&self, plan: &Plan<'_>) -> Result<(), String> { + let deadline = Instant::now() + plan.health_timeout; + let mut passes = 0; + loop { + let active = self.services.is_active(plan.unit); + let healthy = active && plan.health_url.is_none_or(|u| self.health.check(u)); + passes = if healthy { passes + 1 } else { 0 }; + if passes >= 2 { + return Ok(()); + } + if Instant::now() >= deadline { + return Err(if active { + format!( + "the health check did not pass within {} s", + plan.health_timeout.as_secs_f32() + ) + } else { + format!("{} is not active", plan.unit) + }); + } + std::thread::sleep(self.poll); + } + } + + fn start(&self, plan: &Plan<'_>) -> Result<(), String> { + self.services.restart(plan.unit)?; + self.wait_healthy(plan) + } + + /// Deploy: unpack (or reuse) the release, switch, restart, check health, and roll back to the + /// previous release when the check fails. `archive` must already match the signed manifest. + pub fn deploy( + &self, + plan: &Plan<'_>, + archive: impl Read, + sha256: &str, + ) -> Result { + if !valid_unit(plan.unit) { + return Err(DeployError::Unit); + } + unpack(&self.layout, plan.app, plan.version, archive, sha256)?; + let previous = self.switch(plan.app, plan.version)?; + match self.start(plan) { + Ok(()) => { + self.prune( + plan.app, + plan.keep, + &[Some(plan.version), previous.as_deref()], + ); + Ok(Outcome::Succeeded { previous }) + } + Err(reason) => match previous.filter(|p| p != plan.version) { + Some(to) => { + self.switch(plan.app, &to)?; + let healthy = self.start(plan).is_ok(); + Ok(Outcome::RolledBack { + to, + healthy, + reason, + }) + } + None => Ok(Outcome::Failed { reason }), + }, + } + } + + /// Remove old releases: keep the newest `keep` from the history and everything in `protect`. + fn prune(&self, app: &str, keep: u32, protect: &[Option<&str>]) { + let history = self.layout.history(app); + let keep_n = usize::try_from(keep.max(1)).unwrap_or(1); + let mut kept: Vec<&str> = history + .iter() + .rev() + .take(keep_n) + .map(String::as_str) + .collect(); + kept.extend(protect.iter().flatten()); + let Ok(rd) = fs::read_dir(self.layout.releases_dir(app)) else { + return; + }; + for e in rd.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + if name.starts_with('.') || !valid_version(&name) || kept.contains(&name.as_str()) { + continue; + } + if fs::remove_dir_all(e.path()).is_ok() { + let _ = fs::remove_file(self.layout.sum_file(app, &name)); + } + } + } +}