//! The closure the swarm declares for an agent: its record in `agent-closures` //! read before a deploy downloads it, the store path a rebuild pinned from it, //! and the marker of the store path the hive last applied, which a changed //! declaration is compared with. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::sync::Mutex; use anyhow::{Context as _, Result, anyhow}; use swarm_wire::agent_closures::AgentClosure; use super::probe; /// `agent`'s record in `agent-closures`; `None` when the builder has recorded /// no build of it. /// /// # Errors /// The queue cannot be reached, or the record cannot be read. pub async fn record(agent: &str) -> Result> { let client = crate::swarm_queue::client() .await .ok_or_else(|| anyhow!("this hive has no connection to the swarm queue"))?; probe::read_record(&client, agent).await } /// Record that `agent` runs the closure at `store_path`. /// /// # Errors /// The marker could not be written. pub fn mark_deployed(agent: &str, store_path: &str) -> Result<()> { mark_deployed_in(&crate::paths::applied_closure_marker(agent), store_path) } /// The store path `agent` runs: its marker, or on the first read after the /// marker was introduced the closure its container profile points at, which is /// then written as the marker. `None` when neither can be read: the hive cannot /// tell what runs. #[must_use] pub fn deployed(agent: &str) -> Option { deployed_or_seed_in( &crate::paths::applied_closure_marker(agent), &crate::paths::container_profile(agent), Path::new(STORE), ) } /// The nix store; a running closure must resolve into it. const STORE: &str = "/nix/store"; fn deployed_or_seed_in(marker: &Path, profile: &Path, store: &Path) -> Option { if let Some(deployed) = deployed_in(marker) { return Some(deployed); } let running = running_in(profile, store)?; if let Err(e) = mark_deployed_in(marker, &running) { tracing::warn!(marker = %marker.display(), error = %format!("{e:#}"), "cannot seed the deployed-closure marker"); } Some(running) } /// The store path `profile` (a container's `system` link) resolves to; `None` /// when the link is absent or unreadable, or does not end in `store`. fn running_in(profile: &Path, store: &Path) -> Option { let resolved: PathBuf = std::fs::canonicalize(profile).ok()?; resolved .starts_with(store) .then(|| resolved.to_str().map(str::to_owned)) .flatten() } /// The store path each agent's running rebuild pinned from its record. static PINNED: Mutex> = Mutex::new(BTreeMap::new()); /// Pin `store_path` as the closure `agent`'s rebuild deploys, replacing any /// earlier pin. pub fn pin(agent: &str, store_path: &str) { PINNED .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .insert(agent.to_owned(), store_path.to_owned()); } /// The store path pinned for `agent`'s rebuild. #[must_use] pub fn pinned(agent: &str) -> Option { PINNED .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .get(agent) .cloned() } /// Drop `agent`'s pin, once its closure is applied. pub fn unpin(agent: &str) { PINNED .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .remove(agent); } /// Written whole to a temp file beside the marker and renamed over it, so a /// reader sees the old marker or the new one. fn mark_deployed_in(marker: &Path, store_path: &str) -> Result<()> { let tmp = marker.with_extension("tmp"); if let Some(dir) = marker.parent() { std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?; } std::fs::write(&tmp, store_path).with_context(|| format!("write {}", tmp.display()))?; std::fs::rename(&tmp, marker) .with_context(|| format!("rename {} to {}", tmp.display(), marker.display())) } fn deployed_in(marker: &Path) -> Option { let stored = std::fs::read_to_string(marker).ok()?; let stored = stored.trim(); (!stored.is_empty()).then(|| stored.to_owned()) } /// Whether the swarm's declared closure is one the hive should now deploy: the /// builder pushed it and it differs from what `deployed` says runs. /// /// An agent whose `deployed` closure is unknown is not pending: the hive cannot /// tell what it runs, so it deploys nothing it was not told to. #[must_use] pub fn pending(record: &AgentClosure, deployed: Option<&str>) -> bool { record.cached && deployed.is_some_and(|deployed| deployed != record.store_path) } /// Whether `deployed` is the closure `record` declares, so deploying it again /// would change nothing. #[must_use] pub fn up_to_date(record: &AgentClosure, deployed: Option<&str>) -> bool { deployed == Some(record.store_path.as_str()) } /// The store path the swarm declares for `agent` when it is [`pending`]. A record /// that cannot be read, or none, is logged and counts as nothing pending: the /// hive then deploys nothing it was not told to. pub async fn pending_path(agent: &str) -> Option { match record(agent).await { Ok(Some(record)) => { pending(&record, deployed(agent).as_deref()).then_some(record.store_path) } Ok(None) => None, Err(e) => { tracing::warn!(%agent, error = %format!("{e:#}"), "cannot read the agent's declared closure"); None } } } /// Whether the closure the swarm declares for `agent` is the one it runs; false /// when that cannot be told, so a deploy request goes ahead. pub async fn is_up_to_date(agent: &str) -> bool { match record(agent).await { Ok(Some(record)) => up_to_date(&record, deployed(agent).as_deref()), _ => false, } } #[cfg(test)] mod tests { use super::*; const DECLARED: &str = "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-nixos-system-alice"; const RUNNING: &str = "/nix/store/zyxwvsrqpnmlkjihgfdcbadfhijklmn-nixos-system-alice"; fn declared(cached: bool) -> AgentClosure { AgentClosure { meta_rev: "a".repeat(40), store_path: DECLARED.to_owned(), system: "x86_64-linux".to_owned(), built_unix: 1, cached, private_users: Some(false), nix_builds: Some(hive_types::NixBuilds::Host), } } #[test] fn a_declaration_other_than_the_running_closure_is_pending() { assert!(pending(&declared(true), Some(RUNNING))); } #[test] fn the_running_closure_is_not_pending() { assert!(!pending(&declared(true), Some(DECLARED))); } #[test] fn a_closure_the_builder_did_not_push_is_not_pending() { assert!(!pending(&declared(false), Some(RUNNING))); } #[test] fn only_the_declared_closure_is_up_to_date() { assert!(up_to_date(&declared(true), Some(DECLARED))); assert!(!up_to_date(&declared(true), Some(RUNNING))); assert!(!up_to_date(&declared(true), None), "unknown is deployed"); } #[test] fn an_agent_with_no_marker_is_not_pending() { assert!(!pending(&declared(true), None)); } #[test] fn the_marker_holds_the_store_path_and_is_replaced_whole() { let dir = tempfile::tempdir().unwrap(); let marker = dir.path().join("applied").join(".alice.closure"); assert_eq!(deployed_in(&marker), None, "no marker yet"); mark_deployed_in(&marker, RUNNING).unwrap(); assert_eq!(deployed_in(&marker).as_deref(), Some(RUNNING)); mark_deployed_in(&marker, DECLARED).unwrap(); assert_eq!(deployed_in(&marker).as_deref(), Some(DECLARED)); } /// A hive that ran the previous marker format has a config commit in its /// old files and none at the new path: the old files are not read, and /// neither seeding nor a deploy touches them. #[test] fn markers_in_the_old_format_are_neither_read_nor_removed() { let dir = tempfile::tempdir().unwrap(); let old = dir.path().join(".alice.config-rev"); std::fs::write(&old, "1111111111111111111111111111111111111111").unwrap(); let marker = dir.path().join(".alice.closure"); assert_eq!(deployed_in(&marker), None); let (store, profile) = profile_running(dir.path(), "run-alice"); let seeded = deployed_or_seed_in(&marker, &profile, &store); assert!(seeded.is_some(), "the running closure seeds the new marker"); assert_eq!( std::fs::read_to_string(&old).unwrap(), "1111111111111111111111111111111111111111", "seeding leaves the old marker as it was" ); mark_deployed_in(&marker, DECLARED).unwrap(); assert!(old.exists(), "a successful deploy leaves old markers alone"); } #[test] fn an_empty_marker_is_unknown() { let dir = tempfile::tempdir().unwrap(); let marker = dir.path().join(".alice.closure"); std::fs::write(&marker, "\n").unwrap(); assert_eq!(deployed_in(&marker), None); } /// A store with one closure, and a profile whose `system` link reaches it /// the way `nix-env --set` leaves it: through a generation link. fn profile_running(dir: &Path, closure: &str) -> (PathBuf, PathBuf) { let store = dir.join("store"); std::fs::create_dir_all(store.join(closure)).unwrap(); let profile = dir.join("profiles").join("h-alice"); std::fs::create_dir_all(&profile).unwrap(); std::os::unix::fs::symlink(store.join(closure), profile.join("system-3-link")).unwrap(); std::os::unix::fs::symlink("system-3-link", profile.join("system")).unwrap(); (store, profile.join("system")) } #[test] fn a_missing_marker_is_seeded_from_the_running_closure() { let dir = tempfile::tempdir().unwrap(); let (store, profile) = profile_running(dir.path(), "run-alice"); let marker = dir.path().join("applied").join(".alice.closure"); let seeded = deployed_or_seed_in(&marker, &profile, &store); let running = std::fs::canonicalize(store.join("run-alice")).unwrap(); assert_eq!(seeded.as_deref(), running.to_str()); assert_eq!(deployed_in(&marker), seeded, "the seed is written"); // The marker wins from then on, whatever the profile says. let (_, other) = profile_running(&dir.path().join("elsewhere"), "run-other"); assert_eq!(deployed_or_seed_in(&marker, &other, &store), seeded); } /// The point of seeding: an agent that runs something other than the /// declaration is pending from the first read. #[test] fn a_seeded_agent_running_another_closure_than_declared_is_pending() { let dir = tempfile::tempdir().unwrap(); let (store, profile) = profile_running(dir.path(), "run-alice"); let marker = dir.path().join(".alice.closure"); let seeded = deployed_or_seed_in(&marker, &profile, &store); assert!(pending(&declared(true), seeded.as_deref())); let record = AgentClosure { store_path: seeded.clone().unwrap(), ..declared(true) }; assert!( !pending(&record, seeded.as_deref()), "control: running what is declared" ); } #[test] fn a_running_closure_that_cannot_be_read_stays_unknown() { let dir = tempfile::tempdir().unwrap(); let (store, _) = profile_running(dir.path(), "run-alice"); let marker = dir.path().join(".alice.closure"); // No profile at all, as for a container that was never created. let absent = dir.path().join("profiles").join("h-bob").join("system"); assert_eq!(deployed_or_seed_in(&marker, &absent, &store), None); // A dangling link, as after a garbage collection. let dangling = dir.path().join("dangling"); std::os::unix::fs::symlink(store.join("gone"), &dangling).unwrap(); assert_eq!(deployed_or_seed_in(&marker, &dangling, &store), None); // A link that leaves the store. let outside = dir.path().join("outside"); std::fs::create_dir_all(&outside).unwrap(); let escape = dir.path().join("escape"); std::os::unix::fs::symlink(&outside, &escape).unwrap(); assert_eq!(deployed_or_seed_in(&marker, &escape, &store), None); assert!(!marker.exists(), "nothing is seeded from an unknown"); assert!(!pending(&declared(true), None)); } #[test] fn a_pin_lasts_until_it_is_dropped() { assert_eq!(pinned("pin-test"), None); pin("pin-test", DECLARED); assert_eq!(pinned("pin-test").as_deref(), Some(DECLARED)); pin("pin-test", RUNNING); assert_eq!( pinned("pin-test").as_deref(), Some(RUNNING), "a new pin replaces" ); unpin("pin-test"); assert_eq!(pinned("pin-test"), None); } }