diff --git a/CHANGELOG.md b/CHANGELOG.md index f457e308..26b28484 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,15 @@ and listed with their assets on the ### Added +- **A pool node keeps a store of what `prepare` makes** (ADR-0062, #277), + per member and repository: a lane on the node reads it (read-only) and + copies an entry with the same inputs, platform and lane image instead of + running `npm ci`; what it prepares goes into its slot's outbox, and the + node takes it into the store within 15 s. Entries go after the node's + retention for kept lanes, count with the member's kept lanes (the least + recently used go first over the room) and go with the member. Needs the + node on this version. + - **The worktree of a lane on a node gets `prepare.link` too** (ADR-0063, #277): a pre-commit hook with `npx eslint` there no longer needs a hand-run `npm ci`. With `outputs`, devstack checks the worktree's inputs diff --git a/Cargo.lock b/Cargo.lock index 58490709..80e1e86b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -578,6 +578,7 @@ dependencies = [ "devstack-config", "devstack-proc", "globset", + "junction", "serde", "serde_json", "tempfile", @@ -709,6 +710,7 @@ dependencies = [ "axum", "blake3", "bytes", + "devstack-build", "devstack-compose", "devstack-config", "devstack-proc", diff --git a/crates/devstack-build/Cargo.toml b/crates/devstack-build/Cargo.toml index 62644251..b36f32db 100644 --- a/crates/devstack-build/Cargo.toml +++ b/crates/devstack-build/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "devstack-build" -description = "Snapshots, builds in a lane, artifacts and build ids (ADR-0002, ADR-0003, ADR-0020)" +description = "Snapshots, builds in a lane, artifacts and build ids, the store of what prepare makes (ADR-0002, ADR-0003, ADR-0020, ADR-0062)" version.workspace = true license.workspace = true edition.workspace = true @@ -16,6 +16,9 @@ serde.workspace = true serde_json.workspace = true thiserror.workspace = true +[target.'cfg(windows)'.dependencies] +junction.workspace = true + [dev-dependencies] tempfile.workspace = true diff --git a/crates/devstack-build/src/lib.rs b/crates/devstack-build/src/lib.rs index 8de972f7..e122e1c4 100644 --- a/crates/devstack-build/src/lib.rs +++ b/crates/devstack-build/src/lib.rs @@ -14,6 +14,7 @@ //! ``` pub mod snapshot; +pub mod store; use devstack_config::interpolate::{self, Placeholder, Resolve}; use devstack_config::model::Service; diff --git a/crates/devstack-daemon/src/store.rs b/crates/devstack-build/src/store.rs similarity index 61% rename from crates/devstack-daemon/src/store.rs rename to crates/devstack-build/src/store.rs index bb9a91c3..65101517 100644 --- a/crates/devstack-daemon/src/store.rs +++ b/crates/devstack-build/src/store.rs @@ -4,6 +4,10 @@ //! temporary directory, its metadata written last, renamed to its key. A hit //! is copied into a copy, never shared with one: tools write into what //! `prepare` made. +//! +//! On a node (ADR-0062 points 3, 4) a lane's daemon reads the member's store +//! mounted read-only and writes what it adds into an outbox in its slot +//! ([`Store::with_outbox`]); the node's agent takes it in ([`Store::take_in`]). use serde::{Deserialize, Serialize}; use std::collections::BTreeSet; @@ -25,6 +29,9 @@ const COPY_THREADS: usize = 32; /// A temporary directory this old is left over from a daemon that ended /// while it wrote an entry. const TMP_STALE: Duration = Duration::from_secs(24 * 3600); +/// In an outbox: the notes of hits on entries of the store +/// (`/.used//`, the copy's milliseconds). +const USED_NOTES: &str = ".used"; /// What an entry holds and how it came about. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -63,31 +70,86 @@ pub struct Swept { pub struct Store { root: PathBuf, + /// Where new entries and the notes of hits go when `root` is not this + /// process's to write (a node's store, mounted read-only into a lane). + outbox: Option, +} + +/// Unix milliseconds. +fn now_ms() -> u128 { + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0) } impl Store { pub fn new(root: impl Into) -> Self { - Self { root: root.into() } + Self { + root: root.into(), + outbox: None, + } + } + + /// A store read at `root` and written to `outbox`, whose entries the + /// owner of `root` takes in ([`Self::take_in`]): a lane on a node. + pub fn with_outbox(root: impl Into, outbox: impl Into) -> Self { + Self { + root: root.into(), + outbox: Some(outbox.into()), + } } pub fn root(&self) -> &Path { &self.root } + /// Whether this process writes the store itself (and sweeps it). + pub fn owned(&self) -> bool { + self.outbox.is_none() + } + fn entry(&self, service: &str, key: &str) -> PathBuf { self.root.join(service).join(key) } + /// Where the entry of `key` is, and what it says: the store's, else + /// one in the outbox not taken in yet. + fn found(&self, service: &str, key: &str) -> Option<(PathBuf, Meta)> { + let at = self.entry(service, key); + if let Some(m) = read_meta(&at) { + return Some((at, m)); + } + let at = self.outbox.as_ref()?.join(service).join(key); + read_meta(&at).map(|m| (at, m)) + } + /// The entry of `key`, if it is complete. pub fn get(&self, service: &str, key: &str) -> Option { - read_meta(&self.entry(service, key)) + self.found(service, key).map(|(_, m)| m) + } + + /// The note of a hit on `key` in the outbox. + fn used_note(&self, service: &str, key: &str) -> Option { + Some( + self.outbox + .as_ref()? + .join(USED_NOTES) + .join(service) + .join(key), + ) } /// How long the last copy out of the entry took. pub fn copy_ms(&self, service: &str, key: &str) -> Option { - std::fs::read_to_string(self.entry(service, key).join(USED)) - .ok() - .and_then(|s| s.trim().parse().ok()) + let read = |p: PathBuf| { + std::fs::read_to_string(p) + .ok() + .and_then(|s| s.trim().parse().ok()) + }; + self.used_note(service, key) + .and_then(read) + .or_else(|| read(self.entry(service, key).join(USED))) } /// The key, for this process: one `prepare` of a key at a time, the @@ -125,25 +187,24 @@ impl Store { outputs: &[String], prepare: Duration, ) -> io::Result { - let entry = self.entry(service, key); - if let Some(meta) = read_meta(&entry) { + if let Some((_, meta)) = self.found(service, key) { return Ok(meta); } - let dir = self.root.join(service); + // Links point to where the entry is read from, as the store's: not + // to `tmp`, nor to the outbox it passes through. + let home = self.entry(service, key); + let base = self.outbox.as_ref().unwrap_or(&self.root); + let entry = base.join(service).join(key); + let dir = base.join(service); std::fs::create_dir_all(&dir)?; - let tmp = dir.join(format!( - ".tmp-{key}-{}-{}", - std::process::id(), - crate::state::now_ms() - )); + let tmp = dir.join(format!(".tmp-{key}-{}-{}", std::process::id(), now_ms())); let written = (|| { - // Links point to where the entry will be, not to `tmp`. - let stats = copy_dirs(from, &tmp, &entry, outputs)?; + let stats = copy_dirs(from, from, &tmp, &home, outputs)?; let meta = Meta { service: service.to_string(), key: key.to_string(), outputs: outputs.to_vec(), - created: crate::state::now_ms(), + created: now_ms(), prepare_ms: prepare.as_millis() as u64, files: stats.files, bytes: stats.bytes, @@ -169,56 +230,152 @@ impl Store { /// Copy the entry's outputs into the copy at `to` (its repository /// root), replacing what is there under those paths. pub fn copy_into(&self, service: &str, key: &str, to: &Path) -> io::Result { - let entry = self.entry(service, key); - let meta = read_meta(&entry) + let (at, meta) = self + .found(service, key) .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no such entry"))?; for rel in &meta.outputs { remove_path(&to.join(rel))?; } - let stats = copy_dirs(&entry, to, to, &meta.outputs)?; - let _ = std::fs::write( - entry.join(USED), - (stats.elapsed.as_millis() as u64).to_string(), - ); + let stats = copy_dirs(&at, &self.entry(service, key), to, to, &meta.outputs)?; + let ms = (stats.elapsed.as_millis() as u64).to_string(); + match self.used_note(service, key) { + Some(note) => { + if let Some(dir) = note.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = std::fs::write(note, ms); + } + None => { + let _ = std::fs::write(at.join(USED), ms); + } + } Ok(stats) } - /// Entries not used for `older_than`, removed unless `dry_run`; and - /// temporary directories a daemon that ended left behind. - pub fn sweep(&self, older_than: Duration, dry_run: bool) -> Vec { - let now = SystemTime::now(); + /// What a lane put into `outbox` ([`Self::with_outbox`]), taken into + /// this store: complete entries moved in (one the store has already is + /// dropped), notes of hits applied to their entries. The keys taken in. + /// `outbox` and the store are on one filesystem: a move is a rename. + pub fn take_in(&self, outbox: &Path) -> Vec<(String, String)> { let mut out = Vec::new(); - let Ok(services) = std::fs::read_dir(&self.root) else { + let Ok(services) = std::fs::read_dir(outbox) else { return out; }; for svc in services.flatten() { + let service = svc.file_name().to_string_lossy().into_owned(); + if service == USED_NOTES { + continue; + } let Ok(keys) = std::fs::read_dir(svc.path()) else { continue; }; for k in keys.flatten() { - let path = k.path(); - let name = k.file_name().to_string_lossy().into_owned(); - let age = |p: &Path| { - std::fs::metadata(p) - .and_then(|m| m.modified()) - .ok() - .and_then(|t| now.duration_since(t).ok()) - }; - if name.starts_with(".tmp-") { - if !dry_run && age(&path).is_some_and(|a| a >= TMP_STALE) { - let _ = std::fs::remove_dir_all(&path); + let key = k.file_name().to_string_lossy().into_owned(); + if key.starts_with(".tmp-") { + if age(&k.path()).is_some_and(|a| a >= TMP_STALE) { + let _ = std::fs::remove_dir_all(k.path()); } continue; } - let Some(meta) = read_meta(&path) else { - continue; - }; - let idle = age(&path.join(USED)) - .or_else(|| age(&path.join(META))) - .unwrap_or_default(); - if idle < older_than { + // Not done yet, or not an entry: left alone. + if read_meta(&k.path()).is_none() { continue; } + let to = self.entry(&service, &key); + let moved = read_meta(&to).is_none() + && std::fs::create_dir_all(self.root.join(&service)).is_ok() + && (!to.exists() || std::fs::remove_dir_all(&to).is_ok()) + && rename_dir(&k.path(), &to).is_ok(); + if moved { + out.push((service.clone(), key)); + } else { + let _ = std::fs::remove_dir_all(k.path()); + } + } + } + let notes = outbox.join(USED_NOTES); + for svc in std::fs::read_dir(¬es).into_iter().flatten().flatten() { + for n in std::fs::read_dir(svc.path()) + .into_iter() + .flatten() + .flatten() + { + let entry = self.root.join(svc.file_name()).join(n.file_name()); + if entry.join(META).is_file() + && let Ok(ms) = std::fs::read_to_string(n.path()) + { + let _ = std::fs::write(entry.join(USED), ms); + } + let _ = std::fs::remove_file(n.path()); + } + } + out + } + + /// The store's complete entries: what each takes, and how long it was + /// not used. + pub fn entries(&self) -> Vec<(Meta, Duration)> { + let mut out = Vec::new(); + for svc in std::fs::read_dir(&self.root) + .into_iter() + .flatten() + .flatten() + { + for k in std::fs::read_dir(svc.path()) + .into_iter() + .flatten() + .flatten() + { + let path = k.path(); + if let Some(meta) = read_meta(&path) { + let idle = age(&path.join(USED)) + .or_else(|| age(&path.join(META))) + .unwrap_or_default(); + out.push((meta, idle)); + } + } + } + out + } + + /// What the store's entries take. + pub fn bytes(&self) -> u64 { + self.entries().iter().map(|(m, _)| m.bytes).sum() + } + + /// The entry of `key` removed: moved out of the way first, so a copy + /// that starts meanwhile finds none rather than half of one. + pub fn remove(&self, service: &str, key: &str) -> io::Result<()> { + let path = self.entry(service, key); + let gone = self.root.join(service).join(format!(".tmp-gone-{key}")); + rename_dir(&path, &gone).and_then(|()| std::fs::remove_dir_all(&gone)) + } + + /// Entries not used for `older_than`, removed unless `dry_run`; and + /// temporary directories a daemon that ended left behind. + pub fn sweep(&self, older_than: Duration, dry_run: bool) -> Vec { + if !dry_run { + for svc in std::fs::read_dir(&self.root) + .into_iter() + .flatten() + .flatten() + { + for k in std::fs::read_dir(svc.path()) + .into_iter() + .flatten() + .flatten() + { + let stale = age(&k.path()).is_some_and(|a| a >= TMP_STALE); + if k.file_name().to_string_lossy().starts_with(".tmp-") && stale { + let _ = std::fs::remove_dir_all(k.path()); + } + } + } + } + self.entries() + .into_iter() + .filter(|(_, idle)| *idle >= older_than) + .map(|(meta, idle)| { let mut swept = Swept { service: meta.service, key: meta.key, @@ -228,18 +385,14 @@ impl Store { error: None, }; if !dry_run { - // Out of the way first: a copy that starts meanwhile - // finds no entry rather than half of one. - let gone = svc.path().join(format!(".tmp-gone-{name}")); - match rename_dir(&path, &gone).and_then(|()| std::fs::remove_dir_all(&gone)) { + match self.remove(&swept.service, &swept.key) { Ok(()) => swept.removed = true, Err(e) => swept.error = Some(e.to_string()), } } - out.push(swept); - } - } - out + swept + }) + .collect() } } @@ -257,6 +410,12 @@ impl Drop for KeyGuard { } } +/// How long ago `p` was last written. +fn age(p: &Path) -> Option { + let t = std::fs::metadata(p).and_then(|m| m.modified()).ok()?; + SystemTime::now().duration_since(t).ok() +} + fn read_meta(entry: &Path) -> Option { let bytes = std::fs::read(entry.join(META)).ok()?; serde_json::from_slice(&bytes).ok() @@ -300,12 +459,13 @@ fn remove_path(p: &Path) -> io::Result<()> { } /// The directories `rels` of `from` copied to the same paths under `to`, -/// files many at once. A link stays a link; one that points into `from` -/// points to the same place under `links_to` (npm's links to a workspace's -/// packages are absolute junctions on Windows): `to` itself, or where `to` -/// is renamed to. +/// files many at once. A link stays a link; one that points into +/// `links_from` (where `from` is as its links see it) points to the same +/// place under `links_to` (where `to` is as its links will see it). npm's +/// links to a workspace's packages are absolute junctions on Windows. pub fn copy_dirs( from: &Path, + links_from: &Path, to: &Path, links_to: &Path, rels: &[String], @@ -320,7 +480,7 @@ pub fn copy_dirs( format!("`{rel}` is no directory in {}", from.display()), )); } - walk(from, links_to, &src, &to.join(rel), &mut files)?; + walk(links_from, links_to, &src, &to.join(rel), &mut files)?; } let next = AtomicUsize::new(0); let bytes = AtomicU64::new(0); @@ -537,6 +697,62 @@ mod tests { assert!(store.get("web", "k").is_none()); } + #[test] + fn a_lane_on_a_node_writes_its_outbox_and_the_agent_takes_it_in() { + let d = tempfile::tempdir().unwrap(); + let (a, b) = (d.path().join("a"), d.path().join("b")); + tree(&a); + std::fs::create_dir_all(b.join("packages/shared")).unwrap(); + std::fs::write(b.join("packages/shared/index.js"), "b's shared").unwrap(); + let (root, outbox) = (d.path().join("store"), d.path().join("slot/out")); + std::fs::create_dir_all(&root).unwrap(); + let lane = Store::with_outbox(&root, &outbox); + assert!(!lane.owned()); + let outputs = vec!["web/node_modules".to_string()]; + lane.put("web", "k", &a, &outputs, Duration::from_secs(20)) + .unwrap(); + assert!( + !root.join("web/k").exists(), + "the store is not the lane's to write" + ); + // The lane finds its own entry before the agent took it in. + assert!(lane.get("web", "k").is_some()); + lane.copy_into("web", "k", &b).unwrap(); + assert_eq!( + std::fs::read_to_string(b.join("web/node_modules/shared/index.js")).unwrap(), + "b's shared" + ); + // The agent takes it in; the note of the hit goes with it. + let agent = Store::new(&root); + assert_eq!( + agent.take_in(&outbox), + vec![("web".to_string(), "k".to_string())] + ); + assert!(agent.get("web", "k").is_some()); + assert!(agent.copy_ms("web", "k").is_some()); + assert!(!outbox.join("web/k").exists()); + assert_eq!(agent.bytes(), agent.get("web", "k").unwrap().bytes); + // The next lane hits the store itself, links and all. + let c = d.path().join("c"); + std::fs::create_dir_all(c.join("packages/shared")).unwrap(); + std::fs::write(c.join("packages/shared/index.js"), "c's shared").unwrap(); + let next = Store::with_outbox(&root, d.path().join("slot2/out")); + next.copy_into("web", "k", &c).unwrap(); + assert_eq!( + std::fs::read_to_string(c.join("web/node_modules/shared/index.js")).unwrap(), + "c's shared" + ); + // A second lane's entry for a key the store has: dropped. + let again = Store::with_outbox(d.path().join("other"), &outbox); + again + .put("web", "k", &a, &outputs, Duration::from_secs(1)) + .unwrap(); + assert!(agent.take_in(&outbox).is_empty()); + assert!(!outbox.join("web/k").exists()); + agent.remove("web", "k").unwrap(); + assert!(agent.entries().is_empty()); + } + #[test] fn a_key_is_prepared_by_one_at_a_time() { let d = tempfile::tempdir().unwrap(); diff --git a/crates/devstack-daemon/src/lib.rs b/crates/devstack-daemon/src/lib.rs index 5645d759..12347a88 100644 --- a/crates/devstack-daemon/src/lib.rs +++ b/crates/devstack-daemon/src/lib.rs @@ -16,7 +16,6 @@ pub mod registry; pub mod remote; pub mod state; pub mod staticsrv; -pub mod store; pub mod supervisor; pub mod tcpfwd; pub mod telemetry; diff --git a/crates/devstack-daemon/src/supervisor/copy.rs b/crates/devstack-daemon/src/supervisor/copy.rs index 1c8e73ae..d311fed9 100644 --- a/crates/devstack-daemon/src/supervisor/copy.rs +++ b/crates/devstack-daemon/src/supervisor/copy.rs @@ -2,8 +2,8 @@ use super::{COPY_QUIET, KEEP_BUILD_LOGS, STOPPED, Supervisor, tail}; use crate::state::{NoticeLevel, now_ms}; -use crate::store::Store; use devstack_build::Snapshot; +use devstack_build::store::Store; use devstack_config::model::{Prepare, Service}; use devstack_proc::Spec; use std::collections::BTreeMap; @@ -72,6 +72,9 @@ impl Supervisor { /// The store of what `prepare` makes (ADR-0062): in the main tree's /// state, shared by its builds and its lanes. pub(crate) fn store(&self) -> Store { + if let Some((root, outbox)) = node_store() { + return Store::with_outbox(root, outbox); + } let devstack = self .layout .artifacts_root @@ -82,10 +85,10 @@ impl Supervisor { /// Whether `prepare` of `name` goes through the store: it names /// `outputs`, none of them is tracked by git (a copy from the store - /// would overwrite the source), and the lane is on this machine (a - /// node's store is the node's). + /// would overwrite the source), and, in a lane on a node, the node + /// gives it the member's store (an older node does not). fn store_use(&self, name: &str, p: &Prepare, snap: &Snapshot) -> Option { - if p.outputs.is_empty() || crate::remote_lane() { + if p.outputs.is_empty() || (crate::remote_lane() && node_store().is_none()) { return None; } let id = format!("prepare.store.{name}"); @@ -739,9 +742,31 @@ fn store_key_of(key: &str, version: Option<&str>) -> String { if let Some(v) = version { h.update(v.trim().as_bytes()); } + // In a lane on a node, what its toolchain is (ADR-0062 point 2). + if let Some(image) = std::env::var("DEVSTACK_LANE_IMAGE") + .ok() + .filter(|i| !i.is_empty()) + { + h.update(image.as_bytes()); + } h.finalize().to_hex()[..20].to_string() } +/// In a lane on a node: the member's store the node mounts read-only +/// (`DEVSTACK_STORE`), and the outbox in the lane's slot its agent takes new +/// entries from (`DEVSTACK_STORE_OUT`), ADR-0062 points 3, 4. +fn node_store() -> Option<(PathBuf, PathBuf)> { + if !crate::remote_lane() { + return None; + } + let var = |k: &str| { + std::env::var_os(k) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + }; + Some((var("DEVSTACK_STORE")?, var("DEVSTACK_STORE_OUT")?)) +} + /// A `prepare` that goes through the store. struct StoreUse { /// The copy's root, where `outputs` are. @@ -760,6 +785,10 @@ const STORE_KEEP: Duration = Duration::from_secs(14 * 24 * 3600); /// starts, then daily. fn sweep_store(store: &Store) { static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + // A node's store is its agent's to sweep. + if !store.owned() { + return; + } { let mut last = LAST.lock().unwrap(); if last.is_some_and(|t| t.elapsed() < Duration::from_secs(24 * 3600)) { diff --git a/crates/devstack-node/Cargo.toml b/crates/devstack-node/Cargo.toml index eb25c6d0..bf7cc7f5 100644 --- a/crates/devstack-node/Cargo.toml +++ b/crates/devstack-node/Cargo.toml @@ -13,6 +13,7 @@ axum.workspace = true blake3.workspace = true devstack-proc.workspace = true bytes.workspace = true +devstack-build.workspace = true devstack-compose.workspace = true devstack-config.workspace = true http-body-util = { workspace = true, features = ["channel"] } diff --git a/crates/devstack-node/src/lanerun.rs b/crates/devstack-node/src/lanerun.rs index f60e9d08..78f791d8 100644 --- a/crates/devstack-node/src/lanerun.rs +++ b/crates/devstack-node/src/lanerun.rs @@ -80,8 +80,18 @@ pub struct LaneRun { /// A secret of this node, so names of images built here cannot be /// guessed by another lane (and used in its `FROM` or `image:`). pub secret: String, + /// The member's store of what `prepare` makes for this repository + /// (ADR-0062 point 3), mounted read-only at [`STORE_MOUNT`]; `None`: + /// the lane gets none. + pub store: Option, } +/// Where a lane's container sees its member's store (read-only). +pub const STORE_MOUNT: &str = "/store"; +/// Where a lane writes what it adds to the store, in its slot: its agent +/// takes it in ([`LaneRun::outbox`]). +const STORE_OUTBOX: &str = ".devstack/store-out"; + /// Where the lane's daemon is reached, and its token. #[derive(Debug, Clone, Serialize)] pub struct DaemonAddr { @@ -435,6 +445,12 @@ fn remove_project(p: &Project, volumes: bool) { } impl LaneRun { + /// What the lane added to its member's store, waiting in its slot for + /// the agent to take it in (ADR-0062 point 4). + pub fn outbox(&self) -> PathBuf { + self.src().join(STORE_OUTBOX) + } + pub fn src(&self) -> PathBuf { self.dir.join("src") } @@ -923,6 +939,23 @@ impl LaneRun { if let Some(p) = &profile_env { args.extend(["-e", p.as_str()]); } + // The member's store, read-only, and the outbox in its slot for + // what the lane adds; the image's id keys the entries (ADR-0062). + let store_args = self.store.as_ref().map(|dir| { + let image_id = docker(&["image", "inspect", "--format", "{{.Id}}", &image]) + .map(|s| s.trim().to_string()) + .unwrap_or_else(|_| image.clone()); + [ + format!("{}:{STORE_MOUNT}:ro", dir.display()), + format!("DEVSTACK_STORE={STORE_MOUNT}"), + format!("DEVSTACK_STORE_OUT=/src/{STORE_OUTBOX}"), + format!("DEVSTACK_LANE_IMAGE={image_id}"), + ] + }); + if let Some([mount, store, out, image]) = &store_args { + args.extend(["-v", mount.as_str(), "-e", store.as_str()]); + args.extend(["-e", out.as_str(), "-e", image.as_str()]); + } if let Some(n) = networks.first() { args.extend(["--network", n.as_str()]); } @@ -1323,6 +1356,7 @@ mod tests { cpu_limit: None, network: Network::Lan, secret: "s".into(), + store: None, }; let g = run.mirror_group(&lane, "app"); // Every call of the group gets them: the node's own (`group`) too. diff --git a/crates/devstack-node/src/node.rs b/crates/devstack-node/src/node.rs index b24dc01d..3184d8e7 100644 --- a/crates/devstack-node/src/node.rs +++ b/crates/devstack-node/src/node.rs @@ -57,6 +57,11 @@ const KEEP_DEDICATED: Duration = Duration::from_secs(7 * 24 * 3600); const KEEP_OTHER: Duration = Duration::from_secs(24 * 3600); /// What one member's kept lanes may take here, unless the policy says. const KEEP_GIB: u64 = 20; +/// In a member's store of what `prepare` makes: whose it is. +const STORE_NOTE: &str = "store.json"; +/// An entry of a member's store here: the store, its service and key, what +/// it takes, how long no lane used it. +type StoreEntry = (PathBuf, String, String, u64, Duration); /// The largest list of files (or hashes) one sync sends: about 250 000. const MAX_LIST: usize = 32 << 20; /// How long the node trusts its last list of members while the coordinator @@ -658,6 +663,30 @@ impl Inner { { remove_lane_images(&self.owner(), |_| true); } + // The members' stores of what `prepare` makes (ADR-0062 point 9): + // entries no lane used for as long as a stopped lane is kept go; + // the rest counts with the member's kept lanes. + let mut stored: HashMap> = HashMap::new(); + for (dir, member) in self.prepare_stores() { + let store = devstack_build::store::Store::new(&dir); + for s in store.sweep(keep_for, false) { + eprintln!( + "store of {member}: {}/{} goes, not used for {} h", + s.service, + s.key, + s.idle.as_secs() / 3600 + ); + } + for (meta, idle) in store.entries() { + stored.entry(member.clone()).or_default().push(( + dir.clone(), + meta.service, + meta.key, + meta.bytes, + idle, + )); + } + } let mut by_member: HashMap> = HashMap::new(); for (slot, info) in kept { if self.in_use(&slot) { @@ -676,10 +705,34 @@ impl Inner { } *self.kept_use.lock().unwrap() = Some(crate::coordinator::Kept { lanes: by_member.values().map(Vec::len).sum(), - bytes: by_member.values().flatten().map(|s| s.2).sum(), + bytes: by_member.values().flatten().map(|s| s.2).sum::() + + stored.values().flatten().map(|e| e.3).sum::(), }); - for (_, mut slots) in by_member { - let mut total: u64 = slots.iter().map(|s| s.2).sum(); + // A member with only a store here counts too. + for member in stored.keys() { + by_member.entry(member.clone()).or_default(); + } + for (member, mut slots) in by_member { + let mut entries = stored.remove(&member).unwrap_or_default(); + let mut total: u64 = + slots.iter().map(|s| s.2).sum::() + entries.iter().map(|e| e.3).sum::(); + // Over the room: the store's least recently used entries go + // first, a copy of what a lane can make again. + entries.sort_by_key(|e| std::cmp::Reverse(e.4)); + for (dir, service, key, bytes, _) in entries { + if total <= room { + break; + } + if devstack_build::store::Store::new(&dir) + .remove(&service, &key) + .is_ok() + { + eprintln!( + "store of {member}: {service}/{key} goes, the member's kept data take more than this node keeps" + ); + total = total.saturating_sub(bytes); + } + } // The least recently used first. slots.sort_by_key(|s| s.1.used); for (slot, info, bytes) in slots { @@ -987,6 +1040,12 @@ impl Inner { self.purge_slot(&slot, &info, "the pool no longer lists its member"); } } + for (dir, member) in self.prepare_stores() { + if !approved.contains(&member) && !holding.contains(&member) { + eprintln!("store of {member}: goes, the pool no longer lists its member"); + let _ = std::fs::remove_dir_all(dir); + } + } // The lane images built for them (ADR-0028). remove_lane_images(&self.owner(), |m| { !approved.contains(m) && !holding.contains(m) @@ -1054,6 +1113,74 @@ impl Inner { memory_limit: None, cpu_limit: None, network: crate::policy::Network::Lan, + store: self.prepare_store(&l.member, &l.repo), + } + } + + fn stores(&self) -> PathBuf { + self.root.join("stores") + } + + /// `member`'s store of what `prepare` makes for `repo` here (ADR-0062 + /// point 3): a name only this node can tell, like a slot's, so a lane + /// reaches its own member's entries and nobody else's. Made with a note + /// of whose it is, for the sweep. + fn prepare_store(&self, member: &str, repo: &str) -> Option { + let dir = self.stores().join(crate::lanerun::secret_name( + &self.secret, + &["store", member, repo], + )); + std::fs::create_dir_all(&dir).ok()?; + let note = dir.join(STORE_NOTE); + if !note.is_file() { + let info = serde_json::json!({ "member": member, "repo": repo }); + std::fs::write(¬e, info.to_string()).ok()?; + } + Some(dir) + } + + /// The stores here, with their member. + fn prepare_stores(&self) -> Vec<(PathBuf, String)> { + std::fs::read_dir(self.stores()) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| { + let note: serde_json::Value = + serde_json::from_slice(&std::fs::read(e.path().join(STORE_NOTE)).ok()?).ok()?; + Some((e.path(), note["member"].as_str()?.to_string())) + }) + .collect() + } + + /// What the lanes here added to their member's store, taken in from + /// their slots (ADR-0062 point 4): the running leases' and the kept + /// lanes'. A move within one filesystem; done every round, so the next + /// lane with the same inputs finds the entry soon. + fn take_in_stores(&self) { + let mut runs: Vec = self + .leases + .lock() + .unwrap() + .values() + .map(|l| self.run(l)) + .collect(); + runs.extend( + self.kept() + .iter() + .map(|(slot, info)| self.slot_run(slot, info)), + ); + for run in runs { + let outbox = run.outbox(); + if !outbox.is_dir() { + continue; + } + let Some(dir) = run.store.as_ref() else { + continue; + }; + for (service, key) in devstack_build::store::Store::new(dir).take_in(&outbox) { + eprintln!("store of `{}`: took in {service}/{key}", run.lane); + } } } @@ -3404,6 +3531,11 @@ async fn background(s: Shared) { cpus: a.cpus + b.cpus, memory: a.memory + b.memory, }); + // What the lanes added to their member's store (ADR-0062 point 4). + { + let s2 = s.clone(); + let _ = tokio::task::spawn_blocking(move || s2.take_in_stores()).await; + } if disk_at.is_none_or(|t| t.elapsed() >= DISK_EVERY) { disk_at = Some(Instant::now()); let s2 = s.clone(); diff --git a/crates/devstack-node/tests/lanerun.rs b/crates/devstack-node/tests/lanerun.rs index 2724b8f8..5c392d91 100644 --- a/crates/devstack-node/tests/lanerun.rs +++ b/crates/devstack-node/tests/lanerun.rs @@ -84,6 +84,7 @@ volumes: cpu_limit: None, network: Network::Lan, secret: "s".into(), + store: None, }; let project = format!("dsltest-{tag}"); let label = format!("label=com.docker.compose.project={project}"); diff --git a/crates/devstack/tests/remote_lane.rs b/crates/devstack/tests/remote_lane.rs index 2590710a..2d368320 100644 --- a/crates/devstack/tests/remote_lane.rs +++ b/crates/devstack/tests/remote_lane.rs @@ -197,6 +197,7 @@ fn a_lane_runs_on_a_node_of_the_pool() { let wt = repo.path().join("wt"); copy_fixture(&main); slow_db(&main); + with_prepare(&main); git(&main, &["init", "-q"]); git(&main, &["add", "-A"]); git( @@ -345,6 +346,66 @@ fn a_lane_runs_on_a_node_of_the_pool() { ) .expect("the lane answers"); assert!(!again.contains("daemon_start"), "taken once: {again}"); + + // What `prepare` made is linked into the worktree here, from a copy on + // this machine (ADR-0063), and a git hook there finds it (#277). + let until = Instant::now() + Duration::from_secs(120); + loop { + let links = api("/v1/lanes") + .and_then(|v| v.as_array()?.iter().find(|l| l["name"] == "wt").cloned()) + .map(|l| l["links"].clone()); + if links + .as_ref() + .and_then(|l| l.as_array()?.first().cloned()) + .is_some_and(|l| l["state"].as_str().is_some_and(|s| s.starts_with("linked"))) + { + break; + } + assert!( + Instant::now() < until, + "the worktree was not linked: {links:?}" + ); + std::thread::sleep(Duration::from_millis(500)); + } + assert_eq!( + std::fs::read_to_string(wt.join("deps/made.txt")) + .unwrap() + .trim(), + "made" + ); + let hook = main.join(".git/hooks/pre-commit"); + std::fs::write(&hook, "#!/bin/sh\ntest -f deps/made.txt\n").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + std::fs::write(wt.join("note.txt"), "hooked").unwrap(); + git(&wt, &["add", "note.txt"]); + git( + &wt, + &[ + "-c", + "user.email=ci@example.invalid", + "-c", + "user.name=ci", + "commit", + "-qm", + "a commit through the hook", + ], + ); + assert!( + cli(&wt, &["status"]).contains("deps linked"), + "status names the link" + ); + // The node took what the lane's `prepare` made into the member's store + // (ADR-0062 points 3, 4). + let until = Instant::now() + Duration::from_secs(120); + while store_entries(node.path()) == 0 { + assert!(Instant::now() < until, "the node's store took nothing in"); + std::thread::sleep(Duration::from_secs(1)); + } + let status = child.wait().unwrap(); let up = format!("{}{}", out.join().unwrap(), err.join().unwrap()); assert!(status.success(), "devstack up --on ci-node: {up}"); @@ -542,6 +603,20 @@ fn a_lane_runs_on_a_node_of_the_pool() { assert!(log.contains("\"remote_lane_unfollowed\""), "{log}"); node_is_clear(); + // Its data thrown away, the lane starts afresh on the node: its build's + // `prepare` comes from the member's store there (ADR-0062). + cli(&main, &["lane", "reset", "wt"]); + cli(&wt, &["up", "--on", "ci-node"]); + let (st, body) = api_request( + &main, + state.path(), + "POST", + "/v1/lanes/wt/v1/telemetry/take", + ) + .expect("the lane answers"); + assert_eq!(st, 200, "{body}"); + assert!(body.contains("prepare_store_hit"), "{body}"); + // `down --all`: the daemon ends, and the lane on the node goes with it // (ADR-0025 point 7). cli(&main, &["down", "--all"]); @@ -685,6 +760,49 @@ fn slow_db(main: &Path) { .unwrap(); } +/// The fixture's API gets a `prepare` whose outputs are kept in the store +/// and linked into a worktree (ADR-0062, ADR-0063); git ignores the link. +fn with_prepare(main: &Path) { + let file = main.join("devstack.toml"); + let toml = std::fs::read_to_string(&file).unwrap(); + let port = "port = 5080\n"; + assert!(toml.contains(port), "{toml}"); + let toml = toml.replacen( + port, + &format!( + "{port}prepare = {{ run = \"mkdir -p deps && echo made > deps/made.txt\", cwd = \".\", inputs = [\"src/Api/Api.csproj\"], outputs = [\"deps\"], link = [\"deps\"] }}\n" + ), + 1, + ); + std::fs::write(&file, toml).unwrap(); + let ignore = main.join(".gitignore"); + let mut text = std::fs::read_to_string(&ignore).unwrap(); + text.push_str("deps\n"); + std::fs::write(&ignore, text).unwrap(); +} + +/// The entries of every member store the node agent keeps under `dir`. +fn store_entries(dir: &Path) -> usize { + fn count(p: &Path, in_stores: bool) -> usize { + std::fs::read_dir(p) + .into_iter() + .flatten() + .flatten() + .map(|e| { + let path = e.path(); + if in_stores && path.join(".devstack-store.json").is_file() { + 1 + } else if path.is_dir() && !path.is_symlink() { + count(&path, in_stores || e.file_name() == "stores") + } else { + 0 + } + }) + .sum() + } + count(dir, false) +} + /// `GET ` of the requester's daemon (the main tree's), as its JSON; /// `None` while it does not answer. fn api_get(main: &Path, state: &Path, path: &str) -> Option { diff --git a/docs/adr/0062-what-prepare-makes-is-kept-in-a-store-per-machine-and-repository-keyed-by-its-inputs.md b/docs/adr/0062-what-prepare-makes-is-kept-in-a-store-per-machine-and-repository-keyed-by-its-inputs.md index ba49e1f5..33e5ca86 100644 --- a/docs/adr/0062-what-prepare-makes-is-kept-in-a-store-per-machine-and-repository-keyed-by-its-inputs.md +++ b/docs/adr/0062-what-prepare-makes-is-kept-in-a-store-per-machine-and-repository-keyed-by-its-inputs.md @@ -1,6 +1,6 @@ # ADR-0062: What `prepare` makes is kept in a store per machine and repository, keyed by its inputs -- **Status:** Accepted (2026-10-26); measured and built on the developer's machine, noted 2026-10-26 +- **Status:** Accepted (2026-10-26); measured and built on the developer's machine, noted 2026-10-26; built on nodes, noted 2026-10-26 - **Date:** 2026-10-26 - **Deciders:** project owner - **Related:** [#277](https://github.com/nuetzliches/devstack/issues/277), [ADR-0002](0002-processes-run-from-immutable-artifacts.md), [ADR-0024](0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md) (a lane runs from a copy), [ADR-0028](0028-lane-images.md) (point 3), [ADR-0033](0033-a-node-decides-what-runs-on-it.md), [ADR-0034](0034-a-machine-can-belong-to-several-pools.md), [ADR-0038](0038-a-lanes-data-outlives-its-lease.md) (slots, the member's disk cap), [ADR-0044](0044-a-lanes-prepared-directories-can-be-linked-into-its-worktree.md), [ADR-0049](0049-a-lanes-need-is-measured-disk-included.md), [ADR-0063](0063-a-lane-on-a-node-links-its-worktree-to-a-copy-from-the-local-store.md) @@ -161,6 +161,25 @@ built: the store on a node (point 3's second half, point 4's last sentence, point 9's node part), the lane start naming the hit in the dashboard (`prepare-*.log` and the diagnostic log do). +*The store on a node, as built, noted 2026-10-26.* The store module moved to +`crates/devstack-build/src/store.rs`, shared by the daemon and the node +agent: `Store::with_outbox` (a lane reads the store and writes new entries +and notes of its hits into an outbox; links in an entry point to where it +is read from), `take_in`, `entries`, `remove`. The node agent +(`crates/devstack-node/src/node.rs`): a store per member and repository in +`/stores/` with a note of whose +it is (`prepare_store`); every round (15 s) the outboxes of the running and +kept lanes' slots are taken in (`take_in_stores`); the sweep removes entries +unused for the node's retention, counts the rest with the member's kept +lanes, evicts the store's least recently used entries first over the room, +and removes a gone member's stores (`sweep_slots`, `purge_gone_members`). +`crates/devstack-node/src/lanerun.rs`: the store mounted read-only at +`/store`, `DEVSTACK_STORE`, `DEVSTACK_STORE_OUT` (`/src/.devstack/store-out`) +and `DEVSTACK_LANE_IMAGE` (the image's id, part of the key). The lane's +daemon (`supervisor/copy.rs`, `node_store`) uses the store when the node +gives it one, and does not sweep it. Still not built: the hit named in the +dashboard (#291). + ## What this ADR does not say - That the main working tree uses the store. It runs in place, with the diff --git a/docs/adr/README.md b/docs/adr/README.md index f43aa0e1..eabbc320 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -110,6 +110,6 @@ stay. | [0059](0059-a-services-stop-command-ends-what-its-run-started.md) | A service's `stop` command ends what its `run` started outside its process tree | Accepted | | [0060](0060-the-tray-is-a-client-of-the-hub.md) | The tray is a client of the hub, a process of its own, on every desktop | Accepted | | [0061](0061-the-dashboard-opens-in-its-installed-app.md) | The dashboard opens in its installed app, when there is one | Accepted | -| [0062](0062-what-prepare-makes-is-kept-in-a-store-per-machine-and-repository-keyed-by-its-inputs.md) | What `prepare` makes is kept in a store per machine and repository, keyed by its inputs | Accepted; measured and built on the developer's machine, noted 2026-10-26 | +| [0062](0062-what-prepare-makes-is-kept-in-a-store-per-machine-and-repository-keyed-by-its-inputs.md) | What `prepare` makes is kept in a store per machine and repository, keyed by its inputs | Accepted; measured and built on the developer's machine, and on nodes, noted 2026-10-26 | | [0063](0063-a-lane-on-a-node-links-its-worktree-to-a-copy-from-the-local-store.md) | A lane on a node links its worktree to a copy from the local store | Accepted; built, noted 2026-10-26 | | [0064](0064-every-compose-call-is-told-the-lane-it-runs-for.md) | Every Compose call is told the lane it runs for | Accepted; addendum 2026-10-26 (a lane on a node: native `{lane}`, `{lane_suffix}`, `DEVSTACK_LANE` follow its name) | diff --git a/docs/pool.md b/docs/pool.md index 3eb274c7..edf30a58 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -343,7 +343,13 @@ The node keeps a stopped lane a week if it is dedicated, a day otherwise (`keep_lanes_hours` in its policy), and at most 20 GiB of one member's kept lanes, mirrors, builds and volumes together (`keep_lanes_gib`; the least recently used goes first); it removes them at once when the pool no longer -lists the member. The images Compose built for a lane go with its slot, and +lists the member. A member's store of what `prepare` makes +([ADR-0062](adr/0062-what-prepare-makes-is-kept-in-a-store-per-machine-and-repository-keyed-by-its-inputs.md)), +one per repository on the node, counts with its kept lanes: an entry no lane +used for as long as a stopped lane is kept goes, and over the room the +store's least recently used entries go before a kept lane does. A lane's +container reads the store read-only; what it adds waits in its slot until +the node takes it in. The images Compose built for a lane go with its slot, and the lane images built from `[lanes] dockerfile` with the member, or when the node has less than 10 GiB free. A node takes no lane without the disk it needs there and 5 GiB to spare (see "What a lane needs"). A stack with `[lanes] diff --git a/docs/stack-file.md b/docs/stack-file.md index 6812d92e..3cbc179a 100644 --- a/docs/stack-file.md +++ b/docs/stack-file.md @@ -605,10 +605,18 @@ status` and the dashboard say per path `linked`, `linked (store)`, says so. The links go when the lane stops on its node, moves or goes; the copy stays for its next start. -Built so far: the store on the developer's machine, for lanes, builds and -the worktrees of lanes on nodes. A lane on a node prepares in its copy there -as before (no store on the node yet). A file with `outputs` or `version` -should say `requires = "0.23.0"` in `[stack]`. +**On a node** the member has a store of its own per repository: the lane's +container reads it (mounted read-only), and what a lane prepares there goes +into it through the lane's slot, taken in by the node within seconds, so +the next lane of the member with the same inputs, platform and lane image +copies it there instead of running `prepare`. The node keeps entries no +lane used for as long as it keeps a stopped lane, counts them with the +member's kept lanes, and lets them go first when the member is over its +room ([pool.md](pool.md)). A node of an older devstack has no store: its +lanes prepare in every copy. + +A file with `outputs` or `version` should say `requires = "0.23.0"` in +`[stack]`. ## `[lanes]`: other worktrees ([ADR-0024](adr/0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md), [ADR-0030](adr/0030-each-lane-has-its-own-infrastructure.md); on other machines [ADR-0025](adr/0025-a-lane-can-run-on-another-node.md), [ADR-0028](adr/0028-lane-images.md), [ADR-0029](adr/0029-source-sync-and-port-forwarding-for-remote-lanes.md), [ADR-0035](adr/0035-lanes-can-be-shared-with-the-pool.md), and [pool.md](pool.md))