aboutsummaryrefslogtreecommitdiffstats
path: root/pkgs
diff options
context:
space:
mode:
Diffstat (limited to 'pkgs')
-rw-r--r--pkgs/populate/docs/design.md42
-rw-r--r--pkgs/populate/src/main.rs1
-rw-r--r--pkgs/populate/src/populate.rs80
-rw-r--r--pkgs/populate/src/probe.rs240
-rw-r--r--pkgs/populate/src/rsync.rs10
-rw-r--r--pkgs/populate/src/sh.rs64
-rw-r--r--pkgs/populate/tests/scenarios.nix45
7 files changed, 426 insertions, 56 deletions
diff --git a/pkgs/populate/docs/design.md b/pkgs/populate/docs/design.md
index 7d12c55..db8299f 100644
--- a/pkgs/populate/docs/design.md
+++ b/pkgs/populate/docs/design.md
@@ -107,20 +107,34 @@ via `sudo`.
Populate runs rsync, Git, ssh, and Nix as programs, found in `PATH`.
-Each rsync run costs several round trips to the target, and about 45 ms
-of rsync waiting for its own processes, also when there's nothing to
-transfer. So file sources that rsync would find nothing to do for get
-skipped: right after taking the lock, one command lists the target paths
-of the file sources that are directories, compared by size and time, and
-whose lock file the flakes step doesn't rewrite, with find. Each such
-source's turn lists what rsync would transfer, with find if nothing
-excludes or filters anything, else with `rsync --list-only`, the same run
-that checks the `.rsync-filter` files. If both listings have the same
-entries, with mode and path, and for files size and time in whole seconds,
-and for symlinks the target, as far as rsync's quick check goes, neither
-`break_hard_links` nor rsync runs. Entries populate can't compare, e.g.
-paths with control characters, devices, or a source that needs
-`--insecure-links`, make it run rsync.
+Each command on a remote target costs about three round trips (a
+channel, the command, its exit status), and each rsync run several more,
+and about 45 ms of rsync waiting for its own processes, also when there's
+nothing to transfer. So sources with nothing to do get skipped: right
+after taking the lock, one command on the target, the probe (`probe.rs`),
+finds out what's at the target paths of those whose lock file the flakes
+step doesn't rewrite:
+
+- For file sources that are directories, compared by size and time, a
+ listing, with find. Each such source's turn lists what rsync would
+ transfer, with find if nothing excludes or filters anything, else with
+ `rsync --list-only`, the same run that checks the `.rsync-filter`
+ files. If both listings have the same entries, with mode and path, and
+ for files size and time in whole seconds, and for symlinks the target,
+ as far as rsync's quick check goes, neither `break_hard_links` nor rsync
+ runs. Entries populate can't compare, e.g. paths with control
+ characters, devices, or a source that needs `--insecure-links`, make it
+ run rsync.
+- For symlink sources, the symlink there, if any. If it points to the
+ target already, nothing runs.
+- For git sources with a commit as ref, and without `fetchAlways`, the
+ work tree's HEAD, its origin's URL, what `git status --ignored` and `git
+ submodule status` print, but only if `git_problems` finds nothing wrong
+ with it, which keeps guarding every Git command. If the commit is
+ checked out, the URL is the source's, nothing is modified, untracked,
+ or ignored, and the submodules are at their commits, nothing runs, and
+ the flakes step takes the work tree for checked, as after the git
+ script.
## Development
diff --git a/pkgs/populate/src/main.rs b/pkgs/populate/src/main.rs
index 7500707..58b0fc0 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 probe;
mod record;
mod rsync;
mod run;
diff --git a/pkgs/populate/src/populate.rs b/pkgs/populate/src/populate.rs
index 668053a..cab1a91 100644
--- a/pkgs/populate/src/populate.rs
+++ b/pkgs/populate/src/populate.rs
@@ -2,13 +2,13 @@
use crate::flake;
use crate::flake_input;
+use crate::probe;
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::{json, Map, Value};
-use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
@@ -57,7 +57,7 @@ pub fn populate(context: &Context, spec: &Spec) -> Result<()> {
if spec.backup {
context.run(&sh::backup(), &[dir])?;
}
- let listings = target_listings(context, spec)?;
+ let probed = probe::probe(context, spec, probed)?;
for (name, source) in &spec.source {
let path = format!("{dir}/{name}");
eprintln!("populating '{}'...", context.name(&path));
@@ -78,7 +78,7 @@ pub fn populate(context: &Context, spec: &Spec) -> Result<()> {
source,
path: &path,
workdir,
- listing: listings.get(name).and_then(Option::as_ref),
+ target: probed.get(name),
};
context.note(json!({ "begin": name }));
let outcome = kind.deliver(&delivery)?;
@@ -191,9 +191,9 @@ struct Delivery<'a> {
path: &'a str,
/// Where to prepare files on the deploying machine.
workdir: PathBuf,
- /// The listing of the target path, for a file source whose transfer may
- /// find nothing to do, see target_listings.
- listing: Option<&'a rsync::Listing>,
+ /// What the probe found at the target path, for a source whose delivery
+ /// may find nothing to do, see probed.
+ target: Option<&'a probe::Target>,
}
impl Delivery<'_> {
@@ -302,39 +302,25 @@ fn file_config(source: &Source, source_path: &str) -> Config {
}
}
-/// The listings of the target paths of the file sources whose transfer may
-/// find nothing to do, by name, see File::deliver: of directories, that
-/// rsync compares by size and time, not checksum, and that the flakes step
-/// doesn't rewrite a lock file in. One command on the target lists them
-/// all.
-fn target_listings(
- context: &Context,
- spec: &Spec,
-) -> Result<BTreeMap<String, Option<rsync::Listing>>> {
- let dir = &spec.target.path;
- let names: Vec<&String> = spec
- .source
- .iter()
- .filter(|(_, source)| {
- source.kind == "file"
- && in_place_lock(source).is_none()
- && string(&source.settings, "path").is_ok_and(|path| {
- Path::new(path).is_dir() && !file_config(source, path).use_checksum
- })
- })
- .map(|(name, _)| name)
- .collect();
- if names.is_empty() {
- return Ok(BTreeMap::new());
+/// What the probe looks for at a source's target path, see probe::probe:
+/// the listing of a file source that's a directory, that rsync compares by
+/// size and time, not checksum, the symlink of a symlink source, and the
+/// work tree of a git source with a commit as ref. Not where the flakes
+/// step rewrites a lock file in place, which delivering brings back.
+fn probed(_name: &str, source: &Source) -> Option<&'static str> {
+ if in_place_lock(source).is_some() {
+ return None;
+ }
+ match source.kind.as_str() {
+ "file" => string(&source.settings, "path")
+ .is_ok_and(|path| Path::new(path).is_dir() && !file_config(source, path).use_checksum)
+ .then_some("F"),
+ "symlink" => Some("L"),
+ "git" => (string(&source.settings, "ref").is_ok_and(probe::is_commit)
+ && source.settings.get("fetchAlways").and_then(Value::as_bool) != Some(true))
+ .then_some("G"),
+ _ => None,
}
- let paths: Vec<String> = names.iter().map(|name| format!("{dir}/{name}")).collect();
- let args: Vec<&str> = paths.iter().map(String::as_str).collect();
- let mut found = rsync::found(&context.output(sh::LISTINGS, &args)?);
- Ok(names
- .into_iter()
- .zip(&paths)
- .map(|(name, path)| (name.clone(), found.remove(path).flatten()))
- .collect())
}
impl Kind for File {
@@ -343,8 +329,9 @@ impl Kind for File {
let config = file_config(d.source, source_path);
// Nothing to do if what rsync would transfer and what's at the
// target path are the same as far as rsync's quick check goes.
- let prepared = rsync::prepare(&config, source_path, d.listing.is_some())?;
- let changed = if prepared.listing.is_some() && prepared.listing.as_ref() == d.listing {
+ let listing = d.target.and_then(|target| target.listing.as_ref());
+ let prepared = rsync::prepare(&config, source_path, listing.is_some())?;
+ let changed = if prepared.listing.is_some() && prepared.listing.as_ref() == listing {
Vec::new()
} else {
rsync::transfer_prepared(d.context, &config, &prepared, d.path)?
@@ -447,6 +434,15 @@ impl Kind for Git {
.into_iter()
.flatten()
.filter_map(Value::as_str);
+ // Nothing to do if the work tree there, which git_problems found
+ // nothing wrong with, has the commit checked out, and nothing that
+ // git reset, git clean, or updating submodules would change.
+ if let Some(git) = d.target.and_then(|probed| probed.git.as_ref()) {
+ if git.unchanged(d.string("url")?, d.string("ref")?) {
+ d.context.git_checked(d.path);
+ return Ok(Outcome::changed(false).with("commit", git.head.as_str()));
+ }
+ }
let name = d.context.name(d.path);
let mut args = vec![
d.path,
@@ -542,6 +538,10 @@ struct Symlink;
impl Kind for Symlink {
fn deliver(&self, d: &Delivery) -> Result<Outcome> {
let target = d.string("target")?;
+ // Nothing to do if the symlink there points to target already.
+ if d.target.and_then(|probed| probed.link.as_deref()) == Some(target) {
+ return Ok(Outcome::changed(false).with("target", 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/probe.rs b/pkgs/populate/src/probe.rs
new file mode 100644
index 0000000..7228cd2
--- /dev/null
+++ b/pkgs/populate/src/probe.rs
@@ -0,0 +1,240 @@
+//! What's at the target paths of the sources whose delivery may find
+//! nothing to do, found out with one command on the target, right after
+//! taking the lock, so their delivery doesn't need any: file sources, see
+//! rsync's Listing, symlink sources, and git sources with a commit as ref.
+
+use crate::rsync::{self, Listing};
+use crate::run::{Context, Result};
+use crate::sh;
+use crate::spec::Spec;
+use std::collections::BTreeMap;
+
+/// What the probe found at a source's target path.
+#[derive(Debug, Default, PartialEq)]
+pub struct Target {
+ /// For a file source, its listing, if populate can compare it.
+ pub listing: Option<Listing>,
+ /// For a symlink source, the target of the symlink there, if any.
+ pub link: Option<String>,
+ /// For a git source, the state of the work tree there, if it's one
+ /// that git_problems finds nothing wrong with.
+ pub git: Option<Git>,
+}
+
+/// The state of a Git work tree.
+#[derive(Debug, PartialEq)]
+pub struct Git {
+ /// The commit checked out, or empty if none.
+ pub head: String,
+ /// The URL of the remote origin, or empty if none.
+ pub url: String,
+ /// Whether anything is modified, untracked, or ignored, which git reset
+ /// and git clean -dfx would change.
+ pub dirty: bool,
+ /// Whether each submodule, if any, has its commit checked out.
+ pub submodules: bool,
+}
+
+impl Git {
+ /// Whether delivering the work tree with a commit as ref would change
+ /// nothing: that commit is checked out, the URL is the one of the
+ /// origin, nothing is dirty, and the submodules are up to date.
+ pub fn unchanged(&self, url: &str, commit: &str) -> bool {
+ is_commit(commit)
+ && self.head.len() == 40
+ && self.head.starts_with(commit)
+ && self.url == url
+ && !self.dirty
+ && self.submodules
+ }
+}
+
+/// Whether ref is a commit, given by its hash or a prefix thereof, like
+/// the git script tells.
+pub fn is_commit(r#ref: &str) -> bool {
+ (4..=40).contains(&r#ref.len())
+ && r#ref
+ .bytes()
+ .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
+}
+
+/// What's at the target paths of the sources spec delivers, by name, for
+/// those of kinds that kind gives, F, L, or G, see sh::probe: one command
+/// on the target probes them all, and none if there are none.
+pub fn probe(
+ context: &Context,
+ spec: &Spec,
+ kind: impl Fn(&str, &crate::spec::Source) -> Option<&'static str>,
+) -> Result<BTreeMap<String, Target>> {
+ let dir = &spec.target.path;
+ let probed: Vec<(&String, &str, String)> = spec
+ .source
+ .iter()
+ .filter_map(|(name, source)| {
+ kind(name, source).map(|kind| (name, kind, format!("{dir}/{name}")))
+ })
+ .collect();
+ if probed.is_empty() {
+ return Ok(BTreeMap::new());
+ }
+ let mut args = Vec::new();
+ for (_, kind, path) in &probed {
+ args.push(*kind);
+ args.push(path.as_str());
+ }
+ let mut found = parse(&context.output(&sh::probe(), &args)?);
+ Ok(probed
+ .into_iter()
+ .filter_map(|(name, _, path)| found.remove(&path).map(|target| (name.clone(), target)))
+ .collect())
+}
+
+/// What sh::probe printed, by path, for the paths whose exit status is 0.
+fn parse(output: &str) -> BTreeMap<String, Target> {
+ let mut targets = BTreeMap::new();
+ let mut fields = output.split('\0');
+ // The path, what's known about it, and whether its listing is still
+ // comparable.
+ let mut current: Option<(String, Target, bool)> = None;
+ while let Some(field) = fields.next() {
+ let Some((_, target, comparable)) = &mut current else {
+ if field == "P" {
+ current = fields
+ .next()
+ .map(|path| (path.to_string(), Target::default(), true));
+ }
+ continue;
+ };
+ match field {
+ "E" => {
+ let entry: Vec<&str> = fields.by_ref().take(5).collect();
+ let canonical = match entry[..] {
+ [mode, size, time, path, link] => {
+ rsync::canonical_found(mode, size, time, path, link)
+ }
+ _ => None,
+ };
+ match canonical {
+ Some(entry) if *comparable => {
+ target
+ .listing
+ .get_or_insert_with(Listing::new)
+ .insert(entry);
+ }
+ _ => *comparable = false,
+ }
+ }
+ "L" => target.link = fields.next().map(str::to_string),
+ // Dirty until git status says otherwise.
+ "C" => {
+ fields.next();
+ target.git = Some(Git {
+ head: String::new(),
+ url: String::new(),
+ dirty: true,
+ submodules: true,
+ });
+ }
+ "H" | "U" | "D" | "M" => {
+ let value = fields.next().unwrap_or_default();
+ if let Some(git) = &mut target.git {
+ match field {
+ "H" => git.head = value.to_string(),
+ "U" => git.url = value.to_string(),
+ "D" => git.dirty = !value.is_empty(),
+ // A line not starting with a blank is a submodule
+ // not initialized, or not at its commit.
+ _ => git.submodules = value.lines().all(|line| line.starts_with(' ')),
+ }
+ }
+ }
+ "S" => {
+ let ok = fields.next() == Some("0");
+ if let Some((path, mut target, comparable)) = current.take() {
+ if !comparable {
+ target.listing = None;
+ }
+ if ok {
+ targets.insert(path, target);
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ targets
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn output(items: &[&[&str]]) -> String {
+ items
+ .iter()
+ .flat_map(|item| item.iter())
+ .map(|field| format!("{field}\0"))
+ .collect()
+ }
+
+ #[test]
+ fn links() {
+ let found = parse(&output(&[
+ &["P", "/t/a", "L", "../x", "S", "0"],
+ &["P", "/t/b", "S", "0"],
+ ]));
+ assert_eq!(found["/t/a"].link.as_deref(), Some("../x"));
+ assert_eq!(found["/t/b"].link, None);
+ assert!(parse(&output(&[&["P", "/t/a", "L", "x", "S", "1"]])).is_empty());
+ }
+
+ const HEAD: &str = "0123456789abcdef0123456789abcdef01234567";
+
+ fn git(extra: &[&str]) -> Option<Git> {
+ let mut items: Vec<&str> = vec!["P", "/t/g", "C", "", "H", HEAD, "U", "https://x/r"];
+ items.extend(extra);
+ items.extend(["S", "0"]);
+ parse(&output(&[&items]))
+ .remove("/t/g")
+ .and_then(|target| target.git)
+ }
+
+ #[test]
+ fn gits() {
+ let clean = git(&["D", ""]).expect("git");
+ assert!(clean.unchanged("https://x/r", HEAD));
+ assert!(clean.unchanged("https://x/r", &HEAD[..7]));
+ assert!(!clean.unchanged("https://x/other", HEAD));
+ assert!(!clean.unchanged("https://x/r", "master"));
+ assert!(!clean.unchanged("https://x/r", "fedcba98"));
+ // Dirty, without git status's answer, and submodules.
+ assert!(!git(&["D", "?? new"])
+ .expect("git")
+ .unchanged("https://x/r", HEAD));
+ assert!(!git(&[]).expect("git").unchanged("https://x/r", HEAD));
+ let submodule = |line: &str| {
+ git(&["D", "", "M", line])
+ .expect("git")
+ .unchanged("https://x/r", HEAD)
+ };
+ assert!(submodule(" 89abcdef sub (heads/master)"));
+ assert!(!submodule("+89abcdef sub (heads/master)"));
+ assert!(!submodule("-89abcdef sub"));
+ // A work tree that git_problems doesn't accept prints no C.
+ let rejected = parse(&output(&[&["P", "/t/g", "S", "0"]]));
+ assert_eq!(rejected["/t/g"].git, None);
+ }
+
+ #[test]
+ fn listings() {
+ let entry = ["E", "drwxr-xr-x", "4096", "1796060000.1", "", ""];
+ let found = parse(&output(&[&["P", "/t/f"], &entry, &["S", "0"]]));
+ assert_eq!(
+ found["/t/f"].listing,
+ Some(Listing::from(["drwxr-xr-x .".to_string()]))
+ );
+ let device = ["E", "crw-r--r--", "0", "1796060000.1", "null", ""];
+ let found = parse(&output(&[&["P", "/t/f"], &entry, &device, &["S", "0"]]));
+ assert_eq!(found["/t/f"].listing, None);
+ }
+}
diff --git a/pkgs/populate/src/rsync.rs b/pkgs/populate/src/rsync.rs
index 011c021..3a28c23 100644
--- a/pkgs/populate/src/rsync.rs
+++ b/pkgs/populate/src/rsync.rs
@@ -454,7 +454,13 @@ fn canonical_listed(line: &str) -> Option<String> {
/// size, modification time in seconds since the epoch, path relative to
/// where find started, empty for that, and symlink target, or None, like
/// canonical_listed.
-fn canonical_found(mode: &str, size: &str, time: &str, path: &str, target: &str) -> Option<String> {
+pub fn canonical_found(
+ mode: &str,
+ size: &str,
+ time: &str,
+ path: &str,
+ target: &str,
+) -> Option<String> {
let path = if path.is_empty() { "." } else { path };
if mode.len() != 10 || incomparable(path) || incomparable(target) {
return None;
@@ -535,7 +541,7 @@ pub fn found(output: &str) -> BTreeMap<String, Option<Listing>> {
}
/// The listing of source on the deploying machine, with find, as
-/// sh::LISTINGS prints it for the target, or None.
+/// sh::LISTINGS prints it, as the probe does for the target, or None.
fn found_locally(source: &str) -> Option<Listing> {
let output = run::output(
Command::new(run::SH)
diff --git a/pkgs/populate/src/sh.rs b/pkgs/populate/src/sh.rs
index f29b1f1..dc44854 100644
--- a/pkgs/populate/src/sh.rs
+++ b/pkgs/populate/src/sh.rs
@@ -344,6 +344,70 @@ fi
"#
}
+/// probe KIND PATH...: prints, for each pair of KIND and PATH, what
+/// probe::Target takes from it: P and PATH, then, for KIND F, an entry like
+/// listings prints for each thing at and below PATH, for L, if PATH is a
+/// symlink, L and its target, and for G, if PATH is a directory with a .git
+/// directory that git_problems finds nothing wrong with, C, H and HEAD, U and
+/// the origin's URL, D and what git status prints for anything modified,
+/// untracked, or ignored, and, with submodules, M and what git submodule
+/// status prints for them, and S and an exit status, all separated by NULs.
+/// Git runs like the git script runs it, without hooks and file system
+/// monitors, and without writing the index.
+pub fn probe() -> String {
+ GIT_PROBLEMS.to_string()
+ + r#"
+git() {
+ command git -c core.hooksPath=/dev/null -c core.fsmonitor=false \
+ --no-optional-locks "$@"
+}
+while test $# -gt 1; do
+ kind=$1 path=$2
+ shift 2
+ printf 'P\0%s\0' "$path"
+ status=0
+ case $kind in
+ F)
+ if ! find "$path" -printf 'E\0%M\0%s\0%T@\0%P\0%l\0' 2>/dev/null; then
+ status=1
+ fi
+ ;;
+ L)
+ if test -L "$path"; then
+ printf 'L\0%s\0' "$(readlink "$path")"
+ fi
+ ;;
+ G)
+ if ! test -L "$path" && test -d "$path" &&
+ ! test -L "$path"/.git && test -d "$path"/.git &&
+ problems=$(git_problems "$path") && test -z "$problems"
+ then
+ printf 'C\0\0'
+ printf 'H\0%s\0' "$(git -C "$path" rev-parse --verify --quiet HEAD)"
+ printf 'U\0%s\0' "$(git -C "$path" config remote.origin.url)"
+ # Captured first: printf doesn't fail if what it prints did.
+ if dirty=$(git -C "$path" status --porcelain --ignored \
+ --untracked-files=all)
+ then
+ printf 'D\0%s\0' "$dirty"
+ else
+ status=1
+ fi
+ if test -e "$path"/.gitmodules; then
+ if submodules=$(git -C "$path" submodule status --recursive); then
+ printf 'M\0%s\0' "$submodules"
+ else
+ status=1
+ fi
+ fi
+ fi
+ ;;
+ esac
+ printf 'S\0%s\0' "$status"
+done
+"#
+}
+
/// listings PATH...: prints, for each PATH, P and PATH, an entry for each
/// thing at and below PATH, with E, mode, size, modification time in
/// seconds since the epoch, path relative to PATH, and symlink target,
diff --git a/pkgs/populate/tests/scenarios.nix b/pkgs/populate/tests/scenarios.nix
index 96804f8..f7ece9a 100644
--- a/pkgs/populate/tests/scenarios.nix
+++ b/pkgs/populate/tests/scenarios.nix
@@ -1172,6 +1172,51 @@ in
}
];
}))
+ # Symlink and git sources with nothing to do get skipped: the symlink
+ # stays the same file, which ln would replace. A symlink pointing
+ # elsewhere, and a modified file, an untracked one, and another commit
+ # in the work tree make them deliver again.
+ (s "symlink-git-skip" (let
+ sources = {
+ l.symlink = "g";
+ g.git = { url = gitUrl; ref = gitHead; };
+ };
+ delivered = ''
+ expect_eq l "$(readlink "$T"/l)" g
+ expect_eq HEAD "$(git -C "$T"/g rev-parse HEAD)" ${gitHead}
+ expect_eq status "$(git -C "$T"/g status --porcelain --ignored)" ""
+ '';
+ in {
+ phases = [
+ {
+ inherit sources;
+ check = delivered;
+ mutate = ''
+ stat -c %i "$T"/l > "$T"/inode
+ '';
+ }
+ # Nothing to do, so the symlink stays.
+ {
+ inherit sources;
+ check = delivered + ''
+ expect_eq inode "$(stat -c %i "$T"/l)" "$(cat "$T"/inode)"
+ '';
+ mutate = ''
+ ln -sfn elsewhere "$T"/l
+ echo modified >> "$T"/g/flake.nix
+ echo new > "$T"/g/new
+ '';
+ }
+ {
+ inherit sources;
+ check = delivered;
+ mutate = ''
+ git -C "$T"/g -c user.name=x -c user.email=x commit -q --allow-empty -m other
+ '';
+ }
+ { inherit sources; check = delivered; }
+ ];
+ }))
(s "cycle" {
phases = [{
sources = {
[cgit] Unable to lock slot /tmp/cgit/56000000.lock: Permission denied (13)