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 | |
| 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.
| -rw-r--r-- | CHANGELOG.md | 6 | ||||
| -rw-r--r-- | pkgs/populate/README.md | 68 | ||||
| -rw-r--r-- | pkgs/populate/src/flake.rs | 47 | ||||
| -rw-r--r-- | pkgs/populate/src/flake_input.rs | 15 | ||||
| -rw-r--r-- | pkgs/populate/src/main.rs | 1 | ||||
| -rw-r--r-- | pkgs/populate/src/populate.rs | 424 | ||||
| -rw-r--r-- | pkgs/populate/src/record.rs | 132 | ||||
| -rw-r--r-- | pkgs/populate/src/rsync.rs | 37 | ||||
| -rw-r--r-- | pkgs/populate/src/run.rs | 128 | ||||
| -rw-r--r-- | pkgs/populate/src/sh.rs | 178 | ||||
| -rw-r--r-- | pkgs/populate/tests/lib.sh | 8 | ||||
| -rw-r--r-- | pkgs/populate/tests/scenarios.nix | 77 | ||||
| -rw-r--r-- | pkgs/populate/tests/smoke.nix | 1 |
13 files changed, 914 insertions, 208 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 63f8018..a7fe35b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ each set of arguments. `pkgs.populate-unwrapped` is the program; `pkgs.populate`, `writeDeploy`, and the other functions keep their arguments, and `pkgs.populate` also takes a target string. +- Populate holds a lock on `.populate/lock` while it runs, which consumers + of the target directory can wait for with a shared lock, and writes the + record of each run that delivers everything to `.populate/run.json`: + whether anything changed since the last record, for each source, and + what got delivered. The sentinel is a directory, which a sentinel file + becomes, and the target needs `flock`. - `lib/with.nix` is krops' lib without nixpkgs' lib, which it takes from its caller, e.g. a flake's `nixpkgs.lib`. `pkgs.krops`, `pkgs.populate` and krops' flake use the nixpkgs lib they get, instead of diff --git a/pkgs/populate/README.md b/pkgs/populate/README.md index e0015fa..8e3232d 100644 --- a/pkgs/populate/README.md +++ b/pkgs/populate/README.md @@ -27,9 +27,10 @@ fetches the program's dependencies from [crates.io](https://crates.io). populate runs rsync, ssh, Git, Nix, pass, and passage as the sources need them, found in `PATH`, as well as a POSIX shell, coreutils, and findutils. -The target needs a POSIX shell, coreutils, findutils, rsync, `patch` for -sources with `patches`, Git for `git` sources, and Nix, and, if remote, -ssh access as root, or, with `--sudo`, as a user who may use `sudo`. +The target needs a POSIX shell, coreutils, findutils, `flock`, rsync, +`patch` for sources with `patches`, Git for `git` sources, and Nix, and, if +remote, ssh access as root, or, with `--sudo`, as a user who may use +`sudo`. NixOS has all of them but Git, and rsync as long as `environment.defaultPackages` contains it. Features that say so need Nix with flake support (Nix 2.4 or later) on the machine that uses them. @@ -205,9 +206,61 @@ everything else. It doesn't change or remove anything outside: and replaces lock files it rewrites, by renaming new files into place, and only makes directories writable that it removes. -* Populate keeps its state in the sentinel, `.populate`, which becomes a - directory once there is state to keep. Populating fails if the sentinel, - or a directory populate needs therein, is a symlink. +* Populate keeps its state in the sentinel, `.populate`, a directory, which + a sentinel file becomes. Populating fails if the sentinel, or a directory + populate needs therein, is a symlink. + +### The run record and the lock + +Populate holds an exclusive lock on `.populate/lock`, with `flock`, from +before it changes anything in the target directory until it's done. Runs +wait for each other, and a consumer of the target directory, e.g. a service +building what got deployed, can take a shared lock while it uses what's +there, which populate waits for, saying so, so it never sees a half +delivered target directory: + +```sh +flock --shared /var/src/.populate/lock cp -R /var/src/some-source /build +``` + +After delivering all sources, populate replaces `.populate/run.json` with +the record of the run, which a systemd path unit can watch, e.g.: + +```json +{ + "version": 0, + "populate": "2.0.0", + "started": "2026-11-20T12:34:56Z", + "finished": "2026-11-20T12:35:01Z", + "changed": true, + "sources": { + "nixos-config": { "type": "file", "changed": false }, + "nixpkgs": { "type": "git", "changed": true, "commit": "ac588ef1c914..." }, + "dotnix": { "type": "flake-input", "changed": false, + "storePath": "/nix/store/...-source", "derived": "/nix/store/...-source" }, + "current": { "type": "symlink", "changed": false, "target": "nixos-config" } + } +} +``` + +- `version` is the record's format, and `populate` populate's version. +- `started` and `finished` are in UTC, by the clock of the machine populate + runs on. +- `changed` tells whether anything in the target directory changed since + the last record, also in runs that didn't finish, and so does each + source's. Pruning anything counts as a change of the target directory. + `file`, `pipe`, `pass`, and `passage` sources get nothing else, so the + record holds nothing about secrets. +- What got delivered: `commit` for `git` sources, `storePath` for `flake`, + `flake-input`, and `derivation` sources, `derived` for `flake` and + `flake-input` sources whose copy got patched or got its lock file + rewritten, and `target` for `symlink` sources. + +Until a run finishes, populate keeps a journal in `.populate/journal` of +what it began changing, and what that changed, which the next run that +finishes sums up in its record. A `file` or `git` source whose lock file +populate rewrites in place gets its original lock file back, and rewritten +again, on every run, so it counts as changed every time. ## Source Types @@ -286,8 +339,7 @@ if it lacks any of them, and the target path becomes a symlink to the flake's store path, registered as garbage collector root. For flakes in a subdirectory, e.g. `git+file:/src/mono?dir=sub`, the symlink points at that subdirectory of the store path. The inputs get garbage collector roots in -`.populate/flake-inputs/<name>`, which turns the sentinel file into a -directory. +`.populate/flake-inputs/<name>`. Supported attributes: diff --git a/pkgs/populate/src/flake.rs b/pkgs/populate/src/flake.rs index 85e31a6..9658bff 100644 --- a/pkgs/populate/src/flake.rs +++ b/pkgs/populate/src/flake.rs @@ -7,6 +7,7 @@ //! resolve to, the lock files of flakes, and what tells whether a derived //! copy needs to be made again. +use crate::populate::Outcome; use crate::run::{Context, Failure, Result}; use crate::sh; use crate::spec::{Follows, Source}; @@ -538,13 +539,23 @@ impl<'a> Flakes<'a> { /// Rewrites the lock file of the flake in a file or git source in /// place. - fn rewrite(&self, name: &str) -> Result<()> { + fn rewrite(&self, name: &str) -> Result<Outcome> { let args = self.override_args(name)?; let resolved = self.resolve(&[self.path(name)], false)?; let url = Self::flake_url(name, &resolved[0])?; let mut all = vec![resolved[0].path.as_str(), url.as_str()]; all.extend(args.iter().map(String::as_str)); - self.run(sh::draw::LOCK, true, &all) + self.changed(sh::draw::LOCK, true, &all) + } + + /// Whether snippet, run like run runs it, printed changed. + fn changed(&self, snippet: &str, flakes: bool, args: &[&str]) -> Result<Outcome> { + let output = self + .context + .output(&Self::on_target(snippet, flakes), args)?; + Ok(Outcome::changed( + output.lines().any(|line| line == "changed"), + )) } /// Derives what the target path of a flake or flake-input source gets @@ -557,7 +568,7 @@ impl<'a> Flakes<'a> { /// and others also if the sources they draw inputs from change. The /// key of a copy, in .populate/derived/<name>/key, is the hash of all /// that, see key_text. - fn derive(&self, name: &str) -> Result<()> { + fn derive(&self, name: &str) -> Result<Outcome> { let settings = &self.sources[name].settings; let materialize = bool_setting(settings, "materialize", false); let rewrite_lock = @@ -617,10 +628,11 @@ impl<'a> Flakes<'a> { let unchanged = old_key == key; if materialize { + let mut outcome = Outcome::default(); if !unchanged || target_kind != "directory" { let work = format!("{state}/work"); let key_path = format!("{state}/key"); - self.run( + outcome = self.changed( sh::draw::MATERIALIZE, false, &[ @@ -639,9 +651,9 @@ impl<'a> Flakes<'a> { let url = self.own_url(name)?; let mut all = vec![target_path.as_str(), url.as_str()]; all.extend(args.iter().map(String::as_str)); - self.run(sh::draw::LOCK, true, &all)?; + outcome.changed |= self.changed(sh::draw::LOCK, true, &all)?.changed; } - return Ok(()); + return Ok(outcome); } let (path, subdir) = split_store_path(original); @@ -658,13 +670,18 @@ impl<'a> Flakes<'a> { &key, ]; all.extend(args.iter().map(String::as_str)); - self.run(sh::draw::ADD, rewrite_lock, &all) + let output = self + .context + .output(&Self::on_target(sh::draw::ADD, rewrite_lock), &all)?; + let mut lines = output.lines(); + let derived = lines.next().unwrap_or_default(); + Ok(Outcome::changed(lines.any(|line| line == "changed")).with("derived", derived)) } /// Generates the flake of a source in .populate/flakes/<name>, which /// re-exports the outputs of the flake in the source, with inputs drawn /// from other sources. - fn generate(&self, name: &str) -> Result<()> { + fn generate(&self, name: &str) -> Result<Outcome> { let json = |s: &str| serde_json::to_string(s).expect("serializes"); let url = self.own_url(name)?; let drawn = self.drawn_from(name); @@ -699,7 +716,7 @@ impl<'a> Flakes<'a> { " outputs = inputs: inputs.{};\n}}\n", json(&input_name(name)) ); - self.run( + self.changed( sh::draw::GENERATE, true, &[&self.state("flakes", name), &text], @@ -791,14 +808,20 @@ pub fn flakes(context: &Context, dir: &str, sources: &BTreeMap<String, Source>) .map(|f| f.source.clone()) .collect() }; + // What changes a source goes into the journal like delivering it. + let change = |name: &str, outcome: &dyn Fn() -> Result<Outcome>| -> Result<()> { + context.note(serde_json::json!({ "begin": name })); + outcome()?.note(context, name); + Ok(()) + }; for name in toposort(&names, &drawn_from) { if flakes.derived.contains(name) { - flakes.derive(name)?; + change(name, &|| flakes.derive(name))?; } if flakes.generated.contains(name) { - flakes.generate(name)?; + change(name, &|| flakes.generate(name))?; } else if flakes.drawing.contains(name) && !flakes.derived.contains(name) { - flakes.rewrite(name)?; + change(name, &|| flakes.rewrite(name))?; } } } diff --git a/pkgs/populate/src/flake_input.rs b/pkgs/populate/src/flake_input.rs index 8d3a218..b38965d 100644 --- a/pkgs/populate/src/flake_input.rs +++ b/pkgs/populate/src/flake_input.rs @@ -3,6 +3,7 @@ //! collector roots for its own inputs. use crate::flake::derives_flake; +use crate::populate::Outcome; use crate::rsync::{self, Config}; use crate::run::{self, Context, Failure, Result}; use crate::sh; @@ -273,14 +274,15 @@ fn flag(settings: &Map<String, Value>, key: &str, default: bool) -> bool { } /// Delivers the flake or flake-input source named name to path, preparing -/// what it needs on the deploying machine in workdir. +/// what it needs on the deploying machine in workdir. What a derived +/// source's target path gets, the flakes step tells, see flake::derive. pub fn deliver( context: &Context, name: &str, path: &str, source: &Source, workdir: &Path, -) -> Result<()> { +) -> Result<Outcome> { let settings = &source.settings; let url = setting(settings, "url") .and_then(Value::as_str) @@ -344,7 +346,7 @@ pub fn deliver( } Ok::<_, Failure>(paths) }; - let link = |subdir: &str, paths: &[String]| -> Result<()> { + let link = |subdir: &str, paths: &[String]| -> Result<Outcome> { let link_name = context.name(&link_path); let mut args = vec![ sentinel.as_str(), @@ -355,7 +357,9 @@ pub fn deliver( subdir, ]; args.extend(paths.iter().map(String::as_str)); - context.run(&on_target(sh::flake::LINK, None), &args) + let output = context.output(&on_target(sh::flake::LINK, None), &args)?; + let changed = !derived && output.contains("changed"); + Ok(Outcome::changed(changed).with("storePath", &paths[0])) }; let on_target_output = |what: &'static str| { move |snippet: &str, args: &[&str]| context.output(&on_target(snippet, Some(what)), args) @@ -591,6 +595,7 @@ fn upload_patches( &dir.to_string_lossy(), &format!("{sentinel}/patches/{name}"), ) + .map(|_| ()) } /// Uploads the flake itself to a target that can't fetch it, unless the @@ -610,7 +615,7 @@ fn upload_self(context: &Context, name: &str, sentinel: &str, self_path: &str) - .join("flake-uploads") .join(name) .join("tree"); - rsync::transfer(context, &config, self_path, &upload.to_string_lossy()) + rsync::transfer(context, &config, self_path, &upload.to_string_lossy()).map(|_| ()) } #[cfg(test)] diff --git a/pkgs/populate/src/main.rs b/pkgs/populate/src/main.rs index 684c515..7500707 100644 --- a/pkgs/populate/src/main.rs +++ b/pkgs/populate/src/main.rs @@ -8,6 +8,7 @@ mod cli; mod flake; mod flake_input; mod populate; +mod record; mod rsync; mod run; mod sh; diff --git a/pkgs/populate/src/populate.rs b/pkgs/populate/src/populate.rs index a488cfd..d0189b7 100644 --- a/pkgs/populate/src/populate.rs +++ b/pkgs/populate/src/populate.rs @@ -2,17 +2,19 @@ use crate::flake; use crate::flake_input; +use crate::record; use crate::rsync::{self, Config}; use crate::run::{self, Context, Failure, Result}; use crate::sh; use crate::spec::{Source, Spec}; -use serde_json::{Map, Value}; +use serde_json::{json, Map, Value}; use std::fs; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -/// Checks the sentinel, makes a backup if asked, delivers each source, and -/// prunes if asked. +/// Checks the sentinel, takes the lock on the target directory, makes a +/// backup if asked, delivers each source, prunes if asked, and writes the +/// record of the run, see the record module. pub fn populate(context: &Context, spec: &Spec) -> Result<()> { let dir = &spec.target.path; refuse_copying_with_sudo(context, spec)?; @@ -22,8 +24,10 @@ pub fn populate(context: &Context, spec: &Spec) -> Result<()> { sh::CHECK, &[&sentinel, &context.name(&sentinel), dir, force], )?; + let started = record::now(); + let (lock, previous) = context.lock(&sentinel, json!({ "run": started }))?; if spec.backup { - context.run(&sh::backup(), &[dir, &context.name(&sentinel)])?; + context.run(&sh::backup(), &[dir])?; } for (name, source) in &spec.source { let path = format!("{dir}/{name}"); @@ -32,7 +36,23 @@ pub fn populate(context: &Context, spec: &Spec) -> Result<()> { fs::create_dir_all(&workdir).map_err(|e| { Failure::Message(format!("error: can't create {}: {e}", workdir.display())) })?; - deliver(context, name, source, &path, workdir)?; + let Some(kind) = kind(&source.kind) else { + // The spec's types are all known. + return Err(Failure::Message(format!( + "populate: unknown source type {}", + source.kind + ))); + }; + let delivery = Delivery { + context, + name, + source, + path: &path, + workdir, + }; + context.note(json!({ "begin": name })); + let outcome = kind.deliver(&delivery)?; + outcome.note(context, name); } flake::flakes(context, dir, &spec.source)?; if spec.prune { @@ -47,11 +67,99 @@ pub fn populate(context: &Context, spec: &Spec) -> Result<()> { args.extend(spec.source.keys().map(String::as_str)); args.push("--"); args.extend(flakes); - context.run(&sh::prune(), &args)?; + if context.output(&sh::prune(), &args)?.contains("pruned") { + context.note(json!({ "pruned": true })); + } } + let record = record::record(spec, &started, &previous, &context.entries()); + context.run(sh::RECORD, &[&sentinel, &record.to_string()])?; + drop(lock); Ok(()) } +/// What delivering a source did: whether that changed anything in the +/// target directory, and what got delivered, for the record of the run. +#[derive(Default)] +pub struct Outcome { + pub changed: bool, + pub delivered: Map<String, Value>, +} + +impl Outcome { + pub fn changed(changed: bool) -> Outcome { + Outcome { + changed, + ..Outcome::default() + } + } + + /// With what got delivered, under key, as value. + pub fn with(mut self, key: &str, value: &str) -> Outcome { + self.delivered.insert(key.to_string(), json!(value)); + self + } + + /// Notes the outcome in the journal, ending what began for the source + /// name. + pub fn note(self, context: &Context, name: &str) { + context.note(json!({ + "end": name, + "changed": self.changed, + "delivered": self.delivered, + })); + } +} + +/// A source to deliver, and where. +struct Delivery<'a> { + context: &'a Context, + name: &'a str, + source: &'a Source, + /// The target path. + path: &'a str, + /// Where to prepare files on the deploying machine. + workdir: PathBuf, +} + +impl Delivery<'_> { + fn string(&self, key: &str) -> Result<&str> { + string(&self.source.settings, key) + } + + /// Transfers source_path, prepared on the deploying machine, to the + /// target path, with rsync's default configuration. + fn transfer(&self, source_path: &Path) -> Result<Outcome> { + let changed = rsync::transfer( + self.context, + &Config::default(), + &source_path.to_string_lossy(), + self.path, + )?; + Ok(Outcome::changed(changed)) + } +} + +/// A type of source. +trait Kind { + /// Delivers the source. + fn deliver(&self, delivery: &Delivery) -> Result<Outcome>; +} + +/// The type of source named kind. +fn kind(kind: &str) -> Option<&'static dyn Kind> { + Some(match kind { + "derivation" => &Derivation, + "file" => &File, + "pipe" => &Pipe, + "flake" | "flake-input" => &Flake, + "git" => &Git, + "pass" => &Pass, + "passage" => &Passage, + "symlink" => &Symlink, + _ => return None, + }) +} + /// Fails, before changing anything, if flakes would get copied to a remote /// target using sudo, which nix copy doesn't support: it logs in as the /// target's user. @@ -80,125 +188,171 @@ fn string<'a>(settings: &'a Map<String, Value>, key: &str) -> Result<&'a str> { .ok_or_else(|| Failure::Message(format!("populate: the source has no {key}"))) } -/// Delivers a source to path on the target, using workdir for files it -/// prepares on the deploying machine. -fn deliver( - context: &Context, - name: &str, - source: &Source, - path: &str, - workdir: PathBuf, -) -> Result<()> { - let settings = &source.settings; - match source.kind.as_str() { - "derivation" => context.run( +/// A Nix expression, built on the target, delivered as a link to the result. +struct Derivation; + +impl Kind for Derivation { + fn deliver(&self, d: &Delivery) -> Result<Outcome> { + let output = d.context.output( &sh::derivation(), - &[path, &context.name(path), string(settings, "text")?], - ), - "file" => { - let source_path = string(settings, "path")?; - // Store paths have the same time, so only checksums tell - // different contents apart. - let use_checksum = settings - .get("useChecksum") - .and_then(Value::as_bool) - .unwrap_or(run::is_store_path(source_path)); - let config = Config { - use_checksum, - ..Config::from_settings(settings) - }; - rsync::transfer(context, &config, source_path, path) - } - "pipe" => { - let out = workdir.join("out"); - let file = fs::File::create(&out).map_err(|e| { - Failure::Message(format!("error: can't create {}: {e}", out.display())) - })?; - // Through a shell, which runs a command without #! as a script. - run::status( - run::local_shell("\"$1\"\n", &[string(settings, "command")?], &workdir) - .stdout(file), - )?; - run::status( - Command::new("touch") - .arg("-t") - .arg("300001010000") - .arg(&out), - )?; - // With the fixed modification time, only checksums tell outputs - // of the same size apart. - let config = Config { - use_checksum: true, - ..Config::default() - }; - rsync::transfer(context, &config, &out.to_string_lossy(), path) - } - "flake" | "flake-input" => flake_input::deliver(context, name, path, source, &workdir), - "git" => { - let flag = |key| match settings.get(key).and_then(Value::as_bool) { - Some(true) => "1", - _ => "", - }; - let excludes = settings - .get("clean") - .and_then(|clean| clean.get("exclude")) - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter_map(Value::as_str); - let name = context.name(path); - let mut args = vec![ - path, - &name, - string(settings, "url")?, - string(settings, "ref")?, - flag("shallow"), - flag("fetchAlways"), - flag("reclone"), - ]; - args.extend(excludes); - // With standard input, which Git may ask for credentials on. - let mut command = context.shell(&sh::git(), &args); - command.stdin(Stdio::inherit()); - if run::output(&mut command)? == "checked" { - context.git_checked(path); + &[d.path, &d.context.name(d.path), d.string("text")?], + )?; + let mut lines = output.lines(); + let store_path = lines.next().unwrap_or_default(); + Ok(Outcome::changed(lines.any(|line| line == "changed")).with("storePath", store_path)) + } +} + +/// A file or directory on the deploying machine. +struct File; + +impl Kind for File { + fn deliver(&self, d: &Delivery) -> Result<Outcome> { + let settings = &d.source.settings; + let source_path = d.string("path")?; + // Store paths have the same time, so only checksums tell different + // contents apart. + let use_checksum = settings + .get("useChecksum") + .and_then(Value::as_bool) + .unwrap_or(run::is_store_path(source_path)); + let config = Config { + use_checksum, + ..Config::from_settings(settings) + }; + let changed = rsync::transfer(d.context, &config, source_path, d.path)?; + Ok(Outcome::changed(changed)) + } +} + +/// What a command on the deploying machine prints. +struct Pipe; + +impl Kind for Pipe { + fn deliver(&self, d: &Delivery) -> Result<Outcome> { + let out = d.workdir.join("out"); + let file = fs::File::create(&out) + .map_err(|e| Failure::Message(format!("error: can't create {}: {e}", out.display())))?; + // Through a shell, which runs a command without #! as a script. + run::status( + run::local_shell("\"$1\"\n", &[d.string("command")?], &d.workdir).stdout(file), + )?; + run::status( + Command::new("touch") + .arg("-t") + .arg("300001010000") + .arg(&out), + )?; + // With the fixed modification time, only checksums tell outputs of + // the same size apart. + let config = Config { + use_checksum: true, + ..Config::default() + }; + let changed = rsync::transfer(d.context, &config, &out.to_string_lossy(), d.path)?; + Ok(Outcome::changed(changed)) + } +} + +/// A flake, or an input of one, delivered as a link into the store. +struct Flake; + +impl Kind for Flake { + fn deliver(&self, d: &Delivery) -> Result<Outcome> { + flake_input::deliver(d.context, d.name, d.path, d.source, &d.workdir) + } +} + +/// A Git work tree, with a commit checked out. +struct Git; + +impl Kind for Git { + fn deliver(&self, d: &Delivery) -> Result<Outcome> { + let settings = &d.source.settings; + let flag = |key| match settings.get(key).and_then(Value::as_bool) { + Some(true) => "1", + _ => "", + }; + let excludes = settings + .get("clean") + .and_then(|clean| clean.get("exclude")) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str); + let name = d.context.name(d.path); + let mut args = vec![ + d.path, + &name, + d.string("url")?, + d.string("ref")?, + flag("shallow"), + flag("fetchAlways"), + flag("reclone"), + ]; + args.extend(excludes); + // With standard input, which Git may ask for credentials on. + let mut command = d.context.shell(&sh::git(), &args); + command.stdin(Stdio::inherit()); + let output = run::output(&mut command)?; + let mut outcome = Outcome::default(); + for line in output.lines() { + match line.split_once(' ') { + Some(("commit", commit)) => outcome = outcome.with("commit", commit), + _ if line == "checked" => d.context.git_checked(d.path), + _ if line == "changed" => outcome.changed = true, + _ => {} } - Ok(()) } - "pass" => { - let dir = string(settings, "dir")?; - let name = string(settings, "name")?; - let info = run::output(&mut run::local_shell( - sh::local::PASS_INFO, - &[dir, name], - &workdir, - ))?; - let info = info.trim_end_matches('\n'); - if !info.is_empty() { - let delivered = context.output(sh::PASS_INFO, &[path])?; - if delivered.trim_end_matches('\n') == info { - return Ok(()); - } + Ok(outcome) + } +} + +/// A secret from pass, decrypted on the deploying machine. +struct Pass; + +impl Kind for Pass { + fn deliver(&self, d: &Delivery) -> Result<Outcome> { + let dir = d.string("dir")?; + let name = d.string("name")?; + let info = run::output(&mut run::local_shell( + sh::local::PASS_INFO, + &[dir, name], + &d.workdir, + ))?; + let info = info.trim_end_matches('\n'); + if !info.is_empty() { + let delivered = d.context.output(sh::PASS_INFO, &[d.path])?; + if delivered.trim_end_matches('\n') == info { + return Ok(Outcome::changed(false)); } - run::status(&mut run::local_shell( - sh::local::PASS, - &[dir, name, info], - &workdir, - ))?; - rsync::transfer( - context, - &Config::default(), - &workdir.to_string_lossy(), - path, - ) } - "passage" => { - let host = context.target.host.split('.').next().unwrap_or_default(); - let mut command = run::local_shell(sh::local::PASSAGE, &[host], &workdir); - for (variable, key) in [("PASSAGE_AGE", "age"), ("PASSAGE_DIR", "dir")] { - command.env(variable, string(settings, key)?); - } - let identities = match settings.get("identities_file").and_then(Value::as_str) { + run::status(&mut run::local_shell( + sh::local::PASS, + &[dir, name, info], + &d.workdir, + ))?; + d.transfer(&d.workdir) + } +} + +/// Secrets from passage, decrypted on the deploying machine. +struct Passage; + +impl Kind for Passage { + fn deliver(&self, d: &Delivery) -> Result<Outcome> { + let host = d.context.target.host.split('.').next().unwrap_or_default(); + let mut command = run::local_shell(sh::local::PASSAGE, &[host], &d.workdir); + for (variable, key) in [("PASSAGE_AGE", "age"), ("PASSAGE_DIR", "dir")] { + command.env(variable, d.string(key)?); + } + let identities = + match d + .source + .settings + .get("identities_file") + .and_then(Value::as_str) + { Some(file) => file.to_string(), None => match std::env::var("HOME") { Ok(home) if !home.is_empty() => format!("{home}/.passage/identities"), @@ -208,19 +362,19 @@ fn deliver( )), }, }; - command.env("PASSAGE_IDENTITIES_FILE", identities); - run::status(&mut command)?; - rsync::transfer( - context, - &Config::default(), - &workdir.to_string_lossy(), - path, - ) - } - "symlink" => context.run(sh::SYMLINK, &[path, string(settings, "target")?]), - // The spec's types are all of the above. - kind => Err(Failure::Message(format!( - "populate: unknown source type {kind}" - ))), + command.env("PASSAGE_IDENTITIES_FILE", identities); + run::status(&mut command)?; + d.transfer(&d.workdir) + } +} + +/// A symlink. +struct Symlink; + +impl Kind for Symlink { + fn deliver(&self, d: &Delivery) -> Result<Outcome> { + let target = d.string("target")?; + let output = d.context.output(sh::SYMLINK, &[d.path, target])?; + Ok(Outcome::changed(output.contains("changed")).with("target", target)) } } diff --git a/pkgs/populate/src/record.rs b/pkgs/populate/src/record.rs new file mode 100644 index 0000000..dd52bda --- /dev/null +++ b/pkgs/populate/src/record.rs @@ -0,0 +1,132 @@ +//! The journal of runs, in the sentinel, and the record of the last run +//! that finished, which sums it up, for consumers of the target directory. +//! +//! The journal has a line of JSON for each entry: {"run": STARTED} when a +//! run starts, {"begin": NAME} before delivering the source NAME, or +//! changing it later, {"end": NAME, "changed": CHANGED, "delivered": +//! DELIVERED} after that, and {"pruned": true} after pruning removed +//! anything. A run that doesn't finish leaves it there, and the next run +//! adds to it, so the record of the next run that finishes tells what +//! changed since the last record, also what runs that didn't finish +//! changed. + +use crate::spec::Spec; +use serde_json::{json, Map, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// The version of the record's format. +const VERSION: u64 = 0; + +/// The time now, in UTC, like 2026-11-20T12:34:56Z. +pub fn now() -> String { + let seconds = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or_default(); + timestamp(seconds) +} + +/// seconds since the epoch, in UTC, like 2026-11-20T12:34:56Z. +fn timestamp(seconds: u64) -> String { + let (days, rest) = (seconds / 86400, seconds % 86400); + // The proleptic Gregorian calendar's date of a day since the epoch, + // after Howard Hinnant's civil_from_days, with eras of 400 years + // starting on March 1st. + let z = days as i64 + 719468; + let era = z.div_euclid(146097); + let day_of_era = z.rem_euclid(146097); + let year_of_era = + (day_of_era - day_of_era / 1460 + day_of_era / 36524 - day_of_era / 146096) / 365; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let month_index = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * month_index + 2) / 5 + 1; + let month = if month_index < 10 { + month_index + 3 + } else { + month_index - 9 + }; + let year = year_of_era + era * 400 + i64::from(month <= 2); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", + rest / 3600, + rest % 3600 / 60, + rest % 60 + ) +} + +/// The record of a run that started at started, delivering spec, with the +/// lines of the journal that runs before it left, and its own entries. +pub fn record(spec: &Spec, started: &str, previous: &[String], entries: &[Value]) -> Value { + let mut open = BTreeSet::new(); + let mut changed = BTreeSet::new(); + let mut pruned = false; + let mut delivered: BTreeMap<&str, Map<String, Value>> = BTreeMap::new(); + let mut unreadable = false; + let previous: Vec<Value> = previous + .iter() + .filter(|line| !line.is_empty()) + .filter_map(|line| { + let entry = serde_json::from_str(line).ok(); + unreadable |= entry.is_none(); + entry + }) + .collect(); + let current = previous.len(); + for (i, entry) in previous.iter().chain(entries).enumerate() { + if entry.get("run").is_some() { + // What a run that didn't finish began may have changed. + changed.append(&mut open); + } else if let Some(name) = entry.get("begin").and_then(Value::as_str) { + open.insert(name.to_string()); + } else if let Some(name) = entry.get("end").and_then(Value::as_str) { + open.remove(name); + if entry.get("changed").and_then(Value::as_bool) != Some(false) { + changed.insert(name.to_string()); + } + if i >= current { + if let Some(Value::Object(fields)) = entry.get("delivered") { + let fields = fields.clone().into_iter(); + delivered.entry(name).or_default().extend(fields); + } + } + } else if entry.get("pruned").is_some() { + pruned = true; + } + } + changed.append(&mut open); + let sources: Map<String, Value> = spec + .source + .iter() + .map(|(name, source)| { + let mut fields = Map::new(); + fields.insert("type".to_string(), json!(source.kind)); + fields.insert( + "changed".to_string(), + json!(unreadable || changed.contains(name)), + ); + fields.extend(delivered.remove(name.as_str()).unwrap_or_default()); + (name.clone(), Value::Object(fields)) + }) + .collect(); + json!({ + "version": VERSION, + "populate": env!("CARGO_PKG_VERSION"), + "started": started, + "finished": now(), + "changed": unreadable || pruned || !changed.is_empty(), + "sources": sources, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn timestamps() { + assert_eq!(timestamp(0), "1970-01-01T00:00:00Z"); + assert_eq!(timestamp(951_782_400), "2000-02-29T00:00:00Z"); + assert_eq!(timestamp(1_795_178_096), "2026-11-20T12:34:56Z"); + } +} diff --git a/pkgs/populate/src/rsync.rs b/pkgs/populate/src/rsync.rs index 0ab92e6..7858e4a 100644 --- a/pkgs/populate/src/rsync.rs +++ b/pkgs/populate/src/rsync.rs @@ -84,8 +84,8 @@ impl Config { } /// Transfers source_path, a directory's contents or a file, to path on the -/// target. -pub fn transfer(context: &Context, config: &Config, source_path: &str, path: &str) -> Result<()> { +/// target, returning whether that changed anything there. +pub fn transfer(context: &Context, config: &Config, source_path: &str, path: &str) -> Result<bool> { context.run(&sh::break_hard_links(), &[path, &context.name(path)])?; let mut source = source_path.to_string(); if Path::new(source_path).is_dir() { @@ -123,11 +123,24 @@ pub fn transfer(context: &Context, config: &Config, source_path: &str, path: &st if config.delete_excluded { command.arg("--delete-excluded"); } - command - .arg(&source) - .arg(context.rsync_destination(path)) - .stdout(run::stderr()); - run::status(&mut command) + command.arg(&source).arg(context.rsync_destination(path)); + let mut changed = false; + run::lines(&mut command, |line| { + changed |= itemizes_change(line); + eprintln!("{line}"); + })?; + Ok(changed) +} + +/// Whether a line rsync prints itemizes a change: what --itemize-changes +/// prints for an item, eleven characters, the second the type of the item, +/// or *deleting, followed by a blank. +fn itemizes_change(line: &str) -> bool { + let Some((item, _)) = line.split_once(' ') else { + return false; + }; + item == "*deleting" + || item.len() == 11 && matches!(item.as_bytes()[1], b'f' | b'd' | b'L' | b'D' | b'S') } /// rsync 3.5.0 and later open .rsync-filter files with a stricter walk than @@ -302,6 +315,16 @@ mod tests { use super::*; #[test] + fn itemized_changes() { + assert!(itemizes_change(">f.st...... flake.nix 82/39")); + assert!(itemizes_change("cd+++++++++ .git/objects/25/ 0/4.00K")); + assert!(itemizes_change(".f..t...... x 0/1")); + assert!(itemizes_change("*deleting old")); + assert!(!itemizes_change("skipping non-regular file \"x\"")); + assert!(!itemizes_change("sent 10 bytes")); + } + + #[test] fn versions() { assert!(version_at_least("3.5.0", "3.5.0")); assert!(version_at_least("3.10.1", "3.5.0")); 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)] diff --git a/pkgs/populate/src/sh.rs b/pkgs/populate/src/sh.rs index 66ca04d..ebc1f10 100644 --- a/pkgs/populate/src/sh.rs +++ b/pkgs/populate/src/sh.rs @@ -2,17 +2,17 @@ //! than a POSIX shell and the usual tools. Values come as positional //! parameters, never quoted into the code. -/// The directories below the sentinel, once that is a directory, which have -/// a directory for each source that needs one. Besides, there is backup, -/// which holds copies of the sources. +/// The directories below the sentinel, a directory, which have a directory +/// for each source that needs one. Besides, there is backup, which holds +/// copies of the sources, and the files lock, journal, and run.json, see +/// LOCK and RECORD. pub const STATE_KINDS: &str = "derived flake-inputs flake-uploads flakes patches"; /// Defines use_state SENTINEL NAME..., which prepares keeping state below -/// the sentinel for the sources named NAME. The sentinel only needs to -/// exist, so it may be a file, which becomes a directory. Populate changes -/// and removes what's in its state directories, and a symlink in place of -/// one would make it do that to whatever the link points to, so it refuses -/// to use those. +/// the sentinel for the sources named NAME. Populate changes and removes +/// what's in its state directories, and a symlink in place of one would +/// make it do that to whatever the link points to, so it refuses to use +/// those. pub fn use_state() -> String { format!( r#" @@ -33,10 +33,6 @@ use_state() {{ refuse_link "$sentinel"/"$state_kind"/"$state_name" done done - if test -f "$sentinel"; then - rm "$sentinel" - mkdir "$sentinel" - fi }} "# ) @@ -96,7 +92,8 @@ make_room_for_link() { /// every name, e.g. ones that end in blanks or contain newlines. With LOG /// empty, entries get removed like remove_tree does; for entries of the /// target directory, LOG is the directory's name in the line printed for -/// each entry, and nothing gets made writable first. The names are +/// each entry, which also prints pruned, and nothing gets made writable +/// first. The names are /// portable file names, which mean themselves as patterns of find. pub const REMOVE_OTHERS: &str = r#" remove_others() { @@ -116,6 +113,7 @@ remove_others() { if test -n "$log"; then >&2 printf "pruning '\''%s/%s'\''...\n" "$log" "${path##*/}" rm -fR "$path" + echo pruned elif test -L "$path"; then rm "$path" else @@ -128,8 +126,9 @@ remove_others() { "#; /// check SENTINEL NAME DIR FORCE: fails unless the sentinel exists, creating -/// it and the target directory DIR first if FORCE isn't empty. NAME is the -/// sentinel's name in messages. +/// it and the target directory DIR first if FORCE isn't empty. A sentinel +/// file becomes a directory, which populate keeps its state in. NAME is +/// the sentinel's name in messages. pub const CHECK: &str = r#" sentinel=$1 name=$2 dir=$3 force=$4 # Before anything touches it, which would touch what it points to. @@ -140,26 +139,79 @@ fi if test -n "$force"; then mkdir -vp "$dir" >&2 if ! test -e "$sentinel"; then - touch "$sentinel" + mkdir "$sentinel" fi fi if ! test -e "$sentinel"; then >&2 printf 'error: missing sentinel file: %s\n' "$name" exit 1 fi +if ! test -d "$sentinel"; then + rm "$sentinel" + mkdir "$sentinel" +fi +"#; + +/// lock SENTINEL NAME ENTRY: waits for an exclusive lock on SENTINEL/lock, +/// prints what's in SENTINEL/journal, which is there if a run didn't +/// finish, appends ENTRY to it, and prints locked. Then it keeps the lock +/// until its standard input ends, which consumers of the target directory +/// can wait for by taking a shared lock. NAME is the sentinel's name in +/// messages. Writing to a symlink in place of the lock or the journal +/// would write to what it points to, so it refuses those. +pub const LOCK: &str = r#" +sentinel=$1 name=$2 entry=$3 +for file in lock journal; do + if test -L "$sentinel"/"$file"; then + >&2 printf 'error: %s/%s is a symlink, but populate needs a file of its own there\n' \ + "$name" "$file" + exit 1 + fi +done +exec 9>>"$sentinel"/lock +if ! flock -n 9; then + >&2 printf 'waiting for the lock on %s/lock...\n' "$name" + flock 9 +fi +if test -f "$sentinel"/journal; then + cat "$sentinel"/journal +fi +printf '%s\n' "$entry" >> "$sentinel"/journal +echo locked +exec cat >/dev/null +"#; + +/// record SENTINEL RECORD: writes RECORD to SENTINEL/run.json, replacing +/// what's there at once, and removes the journal, which the record sums +/// up. +pub const RECORD: &str = r#" +sentinel=$1 record=$2 +tmp=$(mktemp "$sentinel"/run.json.XXXXXX) +printf '%s\n' "$record" > "$tmp" +chmod 644 "$tmp" +mv -f "$tmp" "$sentinel"/run.json +rm -f "$sentinel"/journal "#; -/// backup DIR NAME: copies the target directory DIR to the sentinel's -/// backup directory. NAME is the sentinel's name in messages. +/// The shell code adding the lines a command gets before its own arguments +/// to the journal: the journal's path, the number of lines, and the lines. +pub const JOURNAL: &str = r#" +journal=$1 journal_lines=$2 +shift 2 +while test "$journal_lines" -gt 0; do + printf '%s\n' "$1" >> "$journal" + shift + journal_lines=$((journal_lines - 1)) +done +"#; + +/// backup DIR: copies the target directory DIR to the sentinel's backup +/// directory. pub fn backup() -> String { use_state() + r#" -dir=$1 name=$2 +dir=$1 use_state "$dir"/.populate -if ! test -d "$dir"/.populate; then - >&2 printf 'error: sentinel file is not a directory: %s\n' "$name" - exit 1 -fi rsync >&2 \ -aAXF \ --delete \ @@ -172,7 +224,8 @@ rsync >&2 \ /// prune DIR LOG NAME...: removes the entries of the target directory DIR /// that aren't sources named NAME, logging them with LOG for DIR, and -/// populate's state that only sources that are gone needed. The names +/// printing pruned for each, and populate's state that only sources that +/// are gone needed. The names /// after -- are the ones of flake and flake-input sources, whose roots for /// the garbage collector stay. pub fn prune() -> String { @@ -195,7 +248,7 @@ cd "$dir" remove_others . "$log" .populate $names roots=.populate/flake-inputs if test -d "$roots"; then - remove_others "$roots" "" "$@" + remove_others "$roots" "" "$@" >&2 if test -z "$(ls -A "$roots")"; then rmdir "$roots" fi @@ -227,18 +280,30 @@ fi } /// derivation PATH NAME TEXT: builds the Nix expression TEXT on the target, -/// with a link to the result at PATH. +/// with a link to the result at PATH, printing the result, and changed if +/// the link changed. pub fn derivation() -> String { LINKS.to_string() + r#" +old=$(readlink "$1") || old= make_room_for_link "$1" "$2" nix-build -E "$3" -o "$1" >&2 +new=$(readlink "$1") +printf '%s\n' "$new" +if test "$new" != "$old"; then + echo changed +fi "# } -/// symlink PATH TARGET: makes PATH a symlink to TARGET. +/// symlink PATH TARGET: makes PATH a symlink to TARGET, printing changed +/// if it wasn't one. pub const SYMLINK: &str = r#" +old=$(readlink "$1") || old= ln -fnsT -- "$2" "$1" +if test "$old" != "$2"; then + echo changed +fi "#; /// Defines git_problems PATH, which prints why populate can't use the .git @@ -329,7 +394,8 @@ git_problems() ( /// EXCLUDE pattern. SHALLOW, FETCH_ALWAYS, and RECLONE are flags, empty /// for false. NAME is PATH's name in messages. Prints checked if /// git_problems found nothing wrong with the work tree that was there, -/// which then is what's there, and else nothing; what commands print goes +/// which then is what's there, changed if anything changed, and commit and +/// the commit checked out, on lines of their own; what commands print goes /// to standard error. pub fn git() -> String { LINKS.to_string() @@ -337,8 +403,10 @@ pub fn git() -> String { + r#" # What commands print goes to standard error. None of them gets the # standard output, which populate reads to its end, so nothing they leave -# running, e.g. git gc --auto, keeps populate waiting. -checked= +# running, e.g. git gc --auto, keeps populate waiting. What submodule +# updates and cleaning print, which tells whether they changed anything, +# goes through a file, for the same reason. +checked= changed= deliver_git() { path=$1 name=$2 url=$3 ref=$4 shallow=$5 fetch_always=$6 reclone=$7 shift 7 @@ -380,6 +448,7 @@ deliver_git() { fi fi if ! test -e "$path"; then + changed=1 if test -n "$shallow"; then git init "$path" else @@ -431,21 +500,37 @@ deliver_git() { commit=$(git rev-parse --verify --quiet "$hash^{commit}") || commit= changes=$(git status --porcelain --untracked-files=no) || changes=unknown if test -z "$head" || test "$head" != "$commit" || test -n "$changes"; then + changed=1 git reset --hard "$hash" fi - git submodule update --init --recursive + log=$(mktemp) + git submodule update --init --recursive > "$log" + if test -s "$log"; then + changed=1 + cat "$log" + fi n=$# while test "$n" -gt 0; do set -- "$@" -e "$1" shift n=$((n - 1)) done - git clean -dfx "$@" + git clean -dfx "$@" > "$log" + if test -s "$log"; then + changed=1 + cat "$log" + fi + rm "$log" + commit=$(git rev-parse HEAD) } deliver_git "$@" >&2 if test -n "$checked"; then - printf checked + echo checked +fi +if test -n "$changed"; then + echo changed fi +printf 'commit %s\n' "$commit" "# } @@ -710,7 +795,7 @@ fi /// the source NAME. Roots get added before obsolete ones get removed, /// so the inputs stay rooted. LINK_NAME is LINK_PATH's name in /// messages, and DERIVED isn't empty if LINK_PATH is in the source's - /// derived state. + /// derived state. Prints changed if the link changed. pub const LINK: &str = r#" sentinel=$1 name=$2 link_path=$3 link_name=$4 derived=$5 subdir=$6 path=$7 shift 7 @@ -719,12 +804,16 @@ use_state "$sentinel" "$name" if test -n "$derived"; then mkdir -p "$(dirname "$link_path")" fi +old=$(readlink "$link_path") || old= make_room_for_link "$link_path" "$link_name" nix-store --realise "$path" --add-root "$link_path" --indirect >/dev/null # The garbage collector follows the link into the store path. if test -n "$subdir"; then ln -fns "$path/$subdir" "$link_path" fi +if test "$(readlink "$link_path")" != "$old"; then + echo changed +fi # Left behind by an interrupted run, or not needed anymore. remove_upload mkdir -p "$roots_dir" @@ -953,12 +1042,17 @@ rm -R "$empty" "#; /// lock DIR URL ARG...: rewrites the lock file of the flake in DIR, - /// at URL, with nix flake lock's arguments ARG. + /// at URL, with nix flake lock's arguments ARG, printing changed if + /// that changed it. pub const LOCK: &str = r#" dir=$1 url=$2 shift 2 own_lock "$dir" +old=$(cat "$dir"/flake.lock 2>/dev/null) || old= nix flake lock "$@" "$url" >&2 +if test "$(cat "$dir"/flake.lock)" != "$old"; then + echo changed +fi "#; /// derived_state DIR TARGET_PATH PATCH_DIR CHECKED DRAWN...: removes @@ -1021,7 +1115,7 @@ done /// KEY_FILE KEY: puts a copy of ORIGINAL, made in WORK and patched with /// the patches in PATCH_DIR, if that isn't empty, at TARGET_PATH, and /// writes its key. TARGET_NAME is TARGET_PATH's name in messages, and - /// NAME the source's. + /// NAME the source's. Prints changed. pub const MATERIALIZE: &str = r#" original=$1 work=$2 target_path=$3 target_name=$4 patch_dir=$5 name=$6 key_file=$7 key=$8 @@ -1037,6 +1131,7 @@ remove_foreign_link "$target_path" "$target_name" rm -fR "$target_path" mv "$work" "$target_path" write_key "$key_file" "$key" +echo changed "#; /// add DIR PATH SUBDIR TARGET_PATH TARGET_NAME RESULT PATCH_DIR NAME @@ -1047,7 +1142,7 @@ write_key "$key_file" "$key" /// SUBDIR rewritten with nix flake lock's arguments ARG, if any, and /// added to the store, rooted by DIR/result, with its key in DIR/key. /// TARGET_NAME is TARGET_PATH's name in messages, and NAME the - /// source's. + /// source's. Prints the store path, and changed if the link changed. pub const ADD: &str = r#" dir=$1 path=$2 subdir=$3 target_path=$4 target_name=$5 result=$6 patch_dir=$7 name=$8 key=$9 @@ -1074,15 +1169,21 @@ if test -z "$result"; then nix-store --realise "$result" --add-root "$dir"/result --indirect >/dev/null write_key "$dir"/key "$key" fi +old=$(readlink "$target_path") || old= make_room_for_link "$target_path" "$target_name" # The source's derived state roots the store path. ln -fns "$result${subdir:+/$subdir}" "$target_path" +printf '%s\n' "$result" +if test "$result${subdir:+/$subdir}" != "$old"; then + echo changed +fi "#; /// generate DIR TEXT: makes DIR a flake, with TEXT as its flake.nix, /// and locks it anew, so the lock file pins what the inputs are now. /// What Nix prints about creating the lock file only gets printed if - /// it differs from the one there was, since that's on every run. + /// it differs from the one there was, since that's on every run, and so + /// does changed. pub const GENERATE: &str = r#" dir=$1 text=$2 mkdir -p "$(dirname "$dir")" @@ -1103,6 +1204,7 @@ if ! nix flake lock "path:$(url_path "$(pwd -P)")" >&2 2>"$log"; then fi if test "$(cat flake.lock)" != "$old_lock"; then cat "$log" >&2 + echo changed fi rm "$log" "#; diff --git a/pkgs/populate/tests/lib.sh b/pkgs/populate/tests/lib.sh index a8f2594..0e2ae28 100644 --- a/pkgs/populate/tests/lib.sh +++ b/pkgs/populate/tests/lib.sh @@ -18,6 +18,14 @@ nix() { command nix --extra-experimental-features 'nix-command flakes' "$@" } +# usage: record ATTRPATH +# Prints what's at ATTRPATH, e.g. sources.x.changed, in the record of the +# last run in the target directory $T, as JSON. +record() { + nix-instantiate --eval --json --strict -E \ + "(builtins.fromJSON (builtins.readFile $T/.populate/run.json)).$1" +} + # Evaluates a flake output without network access to the fixtures, so all # inputs must be in the store. An empty cache directory keeps Nix from # restoring inputs from its fetcher cache. diff --git a/pkgs/populate/tests/scenarios.nix b/pkgs/populate/tests/scenarios.nix index 4b7a42b..bd3bf83 100644 --- a/pkgs/populate/tests/scenarios.nix +++ b/pkgs/populate/tests/scenarios.nix @@ -813,6 +813,77 @@ in } ]; })) + # The record of a run: what got delivered, and whether anything changed + # since the last record, also in runs that failed, which leave the + # record as it was. + (s "record" (let + sources = { + g.git = { url = gitUrl; ref = gitHead; }; + l.symlink = "x"; + x.file = "/fixtures/alt"; + }; + # Whether x, and g and l, changed. + changed = x: others: '' + expect_eq changed "$(record changed)" ${if x || others then "true" else "false"} + expect_eq "x changed" "$(record sources.x.changed)" ${lib.boolToString x} + expect_eq "g changed" "$(record sources.g.changed)" ${lib.boolToString others} + expect_eq "l changed" "$(record sources.l.changed)" ${lib.boolToString others} + ''; + in { + phases = [ + { + inherit sources; + check = changed true true + '' + expect_eq version "$(record version)" 0 + expect_eq "x type" "$(record sources.x.type)" '"file"' + expect_eq "g commit" "$(record sources.g.commit)" '"${gitHead}"' + expect_eq "l target" "$(record sources.l.target)" '"x"' + test ! -e "$T"/.populate/journal || fail "journal remains" + ''; + } + { + inherit sources; + check = changed false false + '' + cp "$T"/.populate/run.json "$T".record + ''; + mutate = '' + echo changed > "$T"/x/flake.nix + ''; + } + { + # x, which comes before y, gets delivered again. + sources = sources // { y.pipe = "/run/current-system/sw/bin/false"; }; + expect = { fail = ""; status = 1; }; + check = '' + cmp "$T"/.populate/run.json "$T".record || fail "record changed" + test -e "$T"/.populate/journal || fail "journal missing" + ''; + } + { + # What the failed run changed. + inherit sources; + check = changed true false; + } + ]; + })) + # A consumer of the target directory holding a shared lock delays the + # next run. + (s "lock" { + phases = [ + { + sources.x.file = "/fixtures/alt"; + mutate = '' + setsid flock --shared "$T"/.populate/lock sleep 5 \ + </dev/null >/dev/null 2>&1 & + sleep 1 + ''; + } + { + sources.x.file = "/fixtures/alt"; + output = [ "waiting for the lock on" ]; + } + ]; + }) # A materialized input is a writable copy, patched and with a rewritten # lock file, which gets made again only when what it derives from # changes, and becomes a link again when not materialized anymore. @@ -1819,6 +1890,12 @@ in }) (state "backup" { entry = ".populate/backup"; backup = true; }) (map + (file: state file { + entry = ".populate/${file}"; + message = "/.populate/${file} is a symlink, but populate needs a file of its own there"; + }) + [ "lock" "journal" ]) + (map (entry: state (lib.replaceStrings ["/"] ["-"] entry) { entry = ".populate/${entry}"; }) diff --git a/pkgs/populate/tests/smoke.nix b/pkgs/populate/tests/smoke.nix index 0765c7c..a677469 100644 --- a/pkgs/populate/tests/smoke.nix +++ b/pkgs/populate/tests/smoke.nix @@ -15,6 +15,7 @@ "flake-input-dep-remote-fetchOnTarget0-inputsgenerated-materialize0" "flake-input-sub-local-fetchOnTarget0-materialize0" "state-sentinel-local" + "record-sudo" "prune-remote" "names-local" "paths-local" |
