diff options
| author | tv <tv@krebsco.de> | 2026-11-20 00:51:27 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-20 00:51:27 +0000 |
| commit | 61840ec59bc13b9b2ae6d29fff7276c849684941 (patch) | |
| tree | 0b5299e337758b34cd4982ed4e0c2d8eb3655f0f /pkgs/populate/src/run.rs | |
| parent | 275b9f6102e6f3011099752ec1023a11b326fc45 (diff) | |
populate: a lock, a journal, and a record of each run
For consumers of the target directory on the target, e.g. a CI service,
which should act after a run that delivered everything, and know what it
delivered.
Populate holds an exclusive flock on .populate/lock from right after
checking the sentinel until it's done. The command holding it runs over
the shared connection, or directly, keeping the lock until its input
ends, which populate's ending ends as well, so no lock stays behind.
Runs wait for each other, and for consumers holding a shared lock,
saying so. The sentinel is a directory, which a sentinel file becomes,
since there's always state to keep now, and the target needs flock.
Populate keeps a journal in .populate/journal, a line of JSON for each
entry: a run starting, beginning to deliver or change a source, what
that changed, and pruning. The entries go with the next command on the
target, before what that changes, so the journal needs no commands of
its own. After delivering everything, populate replaces
.populate/run.json with the record of the run, which sums up the
journal, and removes the journal. A run that doesn't finish leaves it,
so changed in the record means changed since the last record: a source
the journal tells began changing, without what it changed, counts as
changed. The record has, for each source, its type, whether it changed,
and what got delivered: the commit of a git source, the store path of a
flake, flake-input, or derivation source, and the derived one, and a
symlink's target. Nothing about secrets, nor files.
Each source type is a Kind, whose deliver returns the Outcome: whether
anything changed, and what got delivered. rsync tells changes by what
it itemizes, the snippets by printing changed: the git source if it
cloned, reset, or submodule updates or cleaning printed anything, links
if they point elsewhere, and lock files and generated flakes if they
differ. Symlinks in place of the lock or the journal get refused.
A file or git source whose lock file populate rewrites in place counts
as changed on every run, since delivering it brings back the original.
Diffstat (limited to 'pkgs/populate/src/run.rs')
| -rw-r--r-- | pkgs/populate/src/run.rs | 128 |
1 files changed, 125 insertions, 3 deletions
diff --git a/pkgs/populate/src/run.rs b/pkgs/populate/src/run.rs index 7fd73f7..8c32359 100644 --- a/pkgs/populate/src/run.rs +++ b/pkgs/populate/src/run.rs @@ -4,10 +4,10 @@ use crate::spec::Target; use std::fmt; use std::fs; -use std::io::Write; +use std::io::{BufRead, BufReader, Write}; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; -use std::process::{Command, ExitStatus, Stdio}; +use std::process::{Child, Command, ExitStatus, Stdio}; use std::sync::atomic::{AtomicI32, Ordering}; /// Why populate stops before delivering everything. @@ -111,6 +111,25 @@ pub struct Context { /// nothing wrong with during this run, so finding that out, which /// takes looking through all of the work tree, happens only once. git_checked: std::cell::RefCell<std::collections::BTreeSet<String>>, + /// The journal on the target, once populate holds the lock, see lock. + journal: std::cell::RefCell<Option<String>>, + /// This run's entries of the journal, and how many of them are in the + /// journal on the target already. + entries: std::cell::RefCell<(Vec<serde_json::Value>, usize)>, +} + +/// The lock on the target directory, which the command holding it keeps +/// until populate drops this, or ends. +pub struct Lock { + child: Child, +} + +impl Drop for Lock { + fn drop(&mut self) { + // Its input ending ends the command, which releases the lock. + drop(self.child.stdin.take()); + let _ = self.child.wait(); + } } impl Context { @@ -137,6 +156,8 @@ impl Context { ssh_nix, metadata: Default::default(), git_checked: Default::default(), + journal: Default::default(), + entries: Default::default(), }; context.write_ssh(&context.ssh, &context.ssh_options(true))?; context.write_ssh(&context.ssh_nix, &context.ssh_options(false))?; @@ -209,8 +230,30 @@ impl Context { /// A command running the shell code script on the target, with args as /// its positional parameters. Over ssh, the remote shell gets it as /// one quoted command, run via sudo if the target says so. + /// The entries of the journal not in the journal on the target yet get + /// there first, so they precede what the command changes. pub fn shell(&self, script: &str, args: &[&str]) -> Command { - let script = format!("set -efu\n{script}"); + let mut lines = Vec::new(); + if let Some(journal) = &*self.journal.borrow() { + let (entries, flushed) = &mut *self.entries.borrow_mut(); + if *flushed < entries.len() { + lines.push(journal.clone()); + lines.push((entries.len() - *flushed).to_string()); + lines.extend(entries[*flushed..].iter().map(|entry| entry.to_string())); + *flushed = entries.len(); + } + } + let script = if lines.is_empty() { + format!("set -efu\n{script}") + } else { + format!("set -efu\n{}{script}", crate::sh::JOURNAL) + }; + let args: Vec<&str> = lines + .iter() + .map(String::as_str) + .chain(args.iter().copied()) + .collect(); + let args = args.as_slice(); if self.local { let mut command = Command::new("sh"); command.arg("-c").arg(script).arg("sh").args(args); @@ -233,6 +276,64 @@ impl Context { } } + /// Takes the lock on the target directory, whose sentinel is sentinel, + /// adding entry to the journal, which entries go to from now on. + /// Returns the lock, and the lines that runs that didn't finish left in + /// the journal. + pub fn lock(&self, sentinel: &str, entry: serde_json::Value) -> Result<(Lock, Vec<String>)> { + let mut command = self.shell( + crate::sh::LOCK, + &[sentinel, &self.name(sentinel), &entry.to_string()], + ); + command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()); + let mut child = command.spawn().map_err(|e| spawn_error(&command, e))?; + let stdout = child.stdout.take().expect("piped"); + let mut lock = Lock { child }; + let mut previous = Vec::new(); + let mut locked = false; + for line in BufReader::new(stdout).lines() { + let line = line.map_err(|e| { + Failure::Message(format!( + "error: can't read from the command taking the lock: {e}" + )) + })?; + if line == "locked" { + locked = true; + break; + } + previous.push(line); + } + check_signal()?; + if !locked { + drop(lock.child.stdin.take()); + let status = lock.child.wait().map_err(|e| spawn_error(&command, e))?; + return Err(if status.success() { + Failure::Message("error: can't take the lock on the target directory".to_string()) + } else { + failed(status) + }); + } + *self.journal.borrow_mut() = Some(format!("{sentinel}/journal")); + self.entries.borrow_mut().0.push(entry); + self.entries.borrow_mut().1 = 1; + Ok((lock, previous)) + } + + /// Adds entry to the journal, see the record module. + pub fn note(&self, entry: serde_json::Value) { + if self.journal.borrow().is_some() { + self.entries.borrow_mut().0.push(entry); + } + } + + /// This run's entries of the journal. + pub fn entries(&self) -> Vec<serde_json::Value> { + self.entries.borrow().0.clone() + } + /// Runs shell code on the target, with its output going where /// populate's errors go. pub fn run(&self, script: &str, args: &[&str]) -> Result<()> { @@ -374,6 +475,27 @@ pub fn output(command: &mut Command) -> Result<String> { } } +/// Runs a command, passing each line of its output to each, failing like +/// status. +pub fn lines(command: &mut Command, mut each: impl FnMut(&str)) -> Result<()> { + command.stdout(Stdio::piped()); + let mut child = command.spawn().map_err(|e| spawn_error(command, e))?; + let stdout = child.stdout.take().expect("piped"); + for line in BufReader::new(stdout).lines() { + match line { + Ok(line) => each(&line), + Err(_) => break, + } + } + let result = child.wait(); + check_signal()?; + match result { + Ok(status) if status.success() => Ok(()), + Ok(status) => Err(failed(status)), + Err(e) => Err(spawn_error(command, e)), + } +} + /// The user running populate, and the name of the machine it runs on, like /// krops' lib's mkTarget and isLocalTarget take them. #[derive(Clone, Debug)] |
