diff options
Diffstat (limited to 'pkgs/populate/src')
| -rw-r--r-- | pkgs/populate/src/populate.rs | 75 | ||||
| -rw-r--r-- | pkgs/populate/src/record.rs | 2 | ||||
| -rw-r--r-- | pkgs/populate/src/rsync.rs | 323 | ||||
| -rw-r--r-- | pkgs/populate/src/sh.rs | 18 |
4 files changed, 381 insertions, 37 deletions
diff --git a/pkgs/populate/src/populate.rs b/pkgs/populate/src/populate.rs index 0659fe7..668053a 100644 --- a/pkgs/populate/src/populate.rs +++ b/pkgs/populate/src/populate.rs @@ -8,6 +8,7 @@ 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}; @@ -56,6 +57,7 @@ pub fn populate(context: &Context, spec: &Spec) -> Result<()> { if spec.backup { context.run(&sh::backup(), &[dir])?; } + let listings = target_listings(context, spec)?; for (name, source) in &spec.source { let path = format!("{dir}/{name}"); eprintln!("populating '{}'...", context.name(&path)); @@ -76,6 +78,7 @@ pub fn populate(context: &Context, spec: &Spec) -> Result<()> { source, path: &path, workdir, + listing: listings.get(name).and_then(Option::as_ref), }; context.note(json!({ "begin": name })); let outcome = kind.deliver(&delivery)?; @@ -188,6 +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>, } impl Delivery<'_> { @@ -281,21 +287,68 @@ impl Kind for Derivation { /// A file or directory on the deploying machine. struct File; +/// The configuration of a file source's transfer of source_path. +fn file_config(source: &Source, source_path: &str) -> Config { + // Store paths have the same time, so only checksums tell different + // contents apart. + let use_checksum = source + .settings + .get("useChecksum") + .and_then(Value::as_bool) + .unwrap_or(run::is_store_path(source_path)); + Config { + use_checksum, + ..Config::from_settings(&source.settings) + } +} + +/// 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()); + } + 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 { 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 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 { + Vec::new() + } else { + rsync::transfer_prepared(d.context, &config, &prepared, d.path)? }; - let changed = rsync::transfer(d.context, &config, source_path, d.path)?; // The lock file the flakes step rewrites, which delivering brings // back, changed if the flakes step says so. let lock = in_place_lock(d.source); diff --git a/pkgs/populate/src/record.rs b/pkgs/populate/src/record.rs index dd52bda..b927317 100644 --- a/pkgs/populate/src/record.rs +++ b/pkgs/populate/src/record.rs @@ -28,7 +28,7 @@ pub fn now() -> String { } /// seconds since the epoch, in UTC, like 2026-11-20T12:34:56Z. -fn timestamp(seconds: u64) -> String { +pub 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 diff --git a/pkgs/populate/src/rsync.rs b/pkgs/populate/src/rsync.rs index ccb2400..011c021 100644 --- a/pkgs/populate/src/rsync.rs +++ b/pkgs/populate/src/rsync.rs @@ -3,6 +3,7 @@ use crate::run::{self, Context, Failure, Result}; use crate::sh; use serde_json::{Map, Value}; +use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; use std::process::Command; @@ -83,6 +84,70 @@ impl Config { } } +/// What the deploying machine finds out about a transfer before it runs, +/// see prepare. +pub struct Prepared { + /// source_path as rsync gets it: a directory's with a trailing slash, + /// so rsync transfers its contents. + source: String, + /// Whether rsync needs --insecure-links, see insecure_links. + insecure_links: bool, + /// What rsync would transfer, if asked for, and populate can tell. + pub listing: Option<Listing>, +} + +/// Checks the .rsync-filter files that apply to source_path, see +/// insecure_links, and, if listing, lists what rsync would transfer of it: +/// with find, if nothing excludes or filters anything, else with rsync +/// --list-only, which the check uses itself, if it runs rsync. Not when +/// rsync needs --insecure-links, nor for what isn't a directory. +pub fn prepare(config: &Config, source_path: &str, listing: bool) -> Result<Prepared> { + let directory = Path::new(source_path).is_dir(); + let mut source = source_path.to_string(); + if directory { + source.push('/'); + } + // Also with older versions of rsync, so a source that's missing, or + // that contains a directory find can't read, fails before rsync runs. + let filtered = config.filter_files && filtered(&source)?; + let (insecure_links, log) = if filtered { + insecure_links(config, &source)? + } else { + (false, None) + }; + let listing = if !listing || !directory || insecure_links { + None + } else if let Some(log) = log { + listed(&log) + } else if !filtered && config.exclude.is_empty() && config.filters.is_empty() { + found_locally(&source) + } else { + list_only(config, &source) + }; + Ok(Prepared { + source, + insecure_links, + listing, + }) +} + +/// What rsync --list-only prints for source, with the config's filters, +/// in UTC, and paths as they are, or None if it fails. +fn list_only(config: &Config, source: &str) -> Option<Listing> { + let output = Command::new("rsync") + .env("TZ", "UTC0") + .args(["-8", "--list-only"]) + .args(config.filter_args()) + .arg("-rlptD") + .arg(source) + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .output() + .ok() + .filter(|output| output.status.success())?; + listed(&String::from_utf8_lossy(&output.stdout)) +} + /// Transfers source_path, a directory's contents or a file, to path on the /// target, returning the paths, relative to path, of what that changed /// there. @@ -92,16 +157,20 @@ pub fn transfer( source_path: &str, path: &str, ) -> Result<Vec<String>> { + let prepared = prepare(config, source_path, false)?; + transfer_prepared(context, config, &prepared, path) +} + +/// Transfers what prepare prepared, like transfer. +pub fn transfer_prepared( + context: &Context, + config: &Config, + prepared: &Prepared, + path: &str, +) -> Result<Vec<String>> { context.run(&sh::break_hard_links(), &[path, &context.name(path)])?; - let mut source = source_path.to_string(); - if Path::new(source_path).is_dir() { - source.push('/'); - } - let insecure_links = if config.filter_files { - insecure_links(context, config, &source)? - } else { - false - }; + let source = &prepared.source; + let insecure_links = prepared.insecure_links; let mut command = Command::new("rsync"); if config.use_checksum { command.arg("--checksum"); @@ -135,7 +204,7 @@ pub fn transfer( if config.delete_excluded { command.arg("--delete-excluded"); } - command.arg(&source).arg(context.rsync_destination(path)); + command.arg(source).arg(context.rsync_destination(path)); let mut changed = Vec::new(); run::lines(&mut command, |line| { changed.extend(changed_path(line)); @@ -176,28 +245,25 @@ fn changed_path(line: &str) -> Option<String> { /// config's insecure_links decides: populate fails with an error if it's /// None, syncs without them if it's false, and makes rsync open them like /// the files it transfers with --insecure-links if it's true, both with a -/// warning. Returns whether rsync needs --insecure-links. -fn insecure_links(context: &Context, config: &Config, source: &str) -> Result<bool> { - // Also with older versions of rsync, so a source that's missing, or - // that contains a directory find can't read, fails before rsync runs. - if !filtered(source)? { - return Ok(false); - } +/// warning. Returns whether rsync needs --insecure-links, and, if it +/// asked rsync, what rsync --list-only printed: the listing of what it +/// would transfer, see listed, in UTC, and its debugging lines. +fn insecure_links(config: &Config, source: &str) -> Result<(bool, Option<String>)> { let version = rsync_version()?; if !version_at_least(&version, "3.5.0") { - return Ok(false); + return Ok((false, None)); } - // A dry run of the same transfer, as far as filtering goes. + // Listing what the transfer would send, as far as filtering goes. let log = run::output( Command::new(run::SH) + .env("TZ", "UTC0") .arg("-c") .arg(r#"rsync "$@" 2>&1 || :"#) .arg("sh") - .args(["--dry-run", "--debug=FILTER2"]) + .args(["-8", "--list-only", "--debug=FILTER2"]) .args(config.filter_args()) .arg("-rlptD") - .arg(source) - .arg(context.tmpdir.join("rsync-filter-check")), + .arg(source), )?; let mut parsed = false; let mut ignored = None; @@ -227,7 +293,7 @@ fn insecure_links(context: &Context, config: &Config, source: &str) -> Result<bo ); } let Some(ignored) = ignored else { - return Ok(false); + return Ok((false, Some(log))); }; match config.insecure_links { None => Err(Failure::Message(format!( @@ -237,13 +303,13 @@ fn insecure_links(context: &Context, config: &Config, source: &str) -> Result<bo eprintln!( "warning: rsync {version} can't read {ignored}; it reads it with --insecure-links anyway, because insecureLinks is true." ); - Ok(true) + Ok((true, Some(log))) } Some(false) => { eprintln!( "warning: rsync {version} can't read {ignored}, so it syncs {source} without it, because insecureLinks is false." ); - Ok(false) + Ok((false, Some(log))) } } } @@ -345,10 +411,217 @@ fn unescape(escaped: &str) -> std::path::PathBuf { std::ffi::OsString::from_vec(out).into() } +/// A listing of a directory: an entry for each thing in it, and for the +/// directory itself, as ".", in a form that is the same for both sides of a +/// transfer exactly if rsync's quick check finds nothing to do between them: +/// the mode and the path, and, for files, also the size and the +/// modification time in whole seconds, and, for symlinks, the target. +/// rsync doesn't keep the times of directories and symlinks +/// (--omit-dir-times, --omit-link-times), nor owners (-rlptD). +pub type Listing = BTreeSet<String>; + +/// Whether populate can't compare an entry's path or link target: one that +/// rsync --list-only escapes, with control characters, or that isn't +/// UTF-8, which reading it as UTF-8 replaced. +fn incomparable(text: &str) -> bool { + text.chars() + .any(|c| c.is_control() || c == '\u{fffd}' || c == '\\') +} + +/// The canonical form of an entry that rsync --list-only, with -8 and in +/// UTC, prints as MODE SIZE DATE TIME PATH, with " -> TARGET" for a +/// symlink, or None if it's something else, or something populate doesn't +/// compare: devices, FIFOs, sockets, and paths it can't compare. +fn canonical_listed(line: &str) -> Option<String> { + let (mode, rest) = line.split_once(' ')?; + let (size, rest) = rest.trim_start().split_once(' ')?; + let (date, rest) = rest.split_once(' ')?; + let (time, path) = rest.split_once(' ')?; + if mode.len() != 10 || incomparable(path) { + return None; + } + match mode.as_bytes()[0] { + b'd' | b'l' => Some(format!("{mode} {path}")), + b'-' => Some(format!( + "{mode} {} {date} {time} {path}", + size.replace(',', "") + )), + _ => None, + } +} + +/// The canonical form of an entry find prints in sh::LISTINGS: its mode, +/// 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> { + let path = if path.is_empty() { "." } else { path }; + if mode.len() != 10 || incomparable(path) || incomparable(target) { + return None; + } + match mode.as_bytes()[0] { + b'd' => Some(format!("{mode} {path}")), + b'l' => Some(format!("{mode} {path} -> {target}")), + b'-' => { + let seconds: f64 = time.parse().ok()?; + if seconds < 0.0 { + return None; + } + // Like 2026/11/30 13:57:55, as rsync prints it. + let stamp = crate::record::timestamp(seconds as u64); + let (date, time) = stamp.trim_end_matches('Z').split_once('T')?; + Some(format!( + "{mode} {size} {} {time} {path}", + date.replace('-', "/") + )) + } + _ => None, + } +} + +/// The listing in what rsync --list-only printed, skipping its debugging +/// lines, which start with [, or None if a line is anything else, e.g. an +/// error, or an entry populate doesn't compare. +fn listed(output: &str) -> Option<Listing> { + output + .lines() + .filter(|line| !line.starts_with('[')) + .map(canonical_listed) + .collect() +} + +/// The listings of the paths in what sh::LISTINGS printed, by path: None +/// for a path where find failed, or that has an entry populate doesn't +/// compare. +pub fn found(output: &str) -> BTreeMap<String, Option<Listing>> { + let mut listings = BTreeMap::new(); + let mut fields = output.split('\0'); + let mut current: Option<(String, Option<Listing>)> = None; + while let Some(field) = fields.next() { + match field { + "P" => { + current = fields + .next() + .map(|path| (path.to_string(), Some(Listing::new()))) + } + "E" => { + let entry: Vec<&str> = fields.by_ref().take(5).collect(); + if let Some((_, listing)) = &mut current { + let canonical = match entry[..] { + [mode, size, time, path, target] => { + canonical_found(mode, size, time, path, target) + } + _ => None, + }; + match (listing.as_mut(), canonical) { + (Some(entries), Some(entry)) => { + entries.insert(entry); + } + _ => *listing = None, + } + } + } + "S" => { + let status = fields.next(); + if let Some((path, listing)) = current.take() { + let ok = status == Some("0"); + listings.insert(path, listing.filter(|_| ok)); + } + } + _ => {} + } + } + listings +} + +/// The listing of source on the deploying machine, with find, as +/// sh::LISTINGS prints it for the target, or None. +fn found_locally(source: &str) -> Option<Listing> { + let output = run::output( + Command::new(run::SH) + .arg("-c") + .arg(sh::LISTINGS) + .arg("sh") + .arg(source), + ) + .ok()?; + found(&output).remove(source).flatten() +} + #[cfg(test)] mod tests { use super::*; + // What rsync --list-only and find print for the same directory, with a + // directory, a file, and a symlink, as in the test of the listings. + const LISTED: &str = "\ +[sender] parse_filter_file(/src/.rsync-filter,c00,4) +drwxr-xr-x 4,096 2026/11/30 17:52:48 . +lrwxrwxrwx 6 2026/11/30 17:52:48 link -> a/keep +drwxr-x--- 4,096 2026/11/30 17:52:48 a +-rw-r--r-- 1,234 2026/11/30 17:52:48 a/keep +"; + + fn found_output(path: &str, entries: &[[&str; 5]], status: &str) -> String { + let mut output = format!("P\0{path}\0"); + for entry in entries { + output.push_str("E\0"); + for field in entry { + output.push_str(field); + output.push('\0'); + } + } + output + &format!("S\0{status}\0") + } + + const FOUND: [[&str; 5]; 4] = [ + ["drwxr-xr-x", "4096", "1796060000.1", "", ""], + ["lrwxrwxrwx", "6", "1796060001.2", "link", "a/keep"], + ["drwxr-x---", "4096", "1796060002.3", "a", ""], + ["-rw-r--r--", "1234", "1796060000.9", "a/keep", ""], + ]; + + #[test] + fn listings() { + // 1796060000 is 2026/11/30 17:33:20 in UTC. + let expected = listed(&LISTED.replace("17:52:48", "17:33:20")).expect("listed"); + let all = found(&found_output("/t/x", &FOUND, "0")); + assert_eq!(all.get("/t/x"), Some(&Some(expected.clone()))); + // A file's time, size, or mode, or a link's target, makes a + // difference, directories' and links' times don't. + let differs = |i: usize, field: usize, value: &str| { + let mut entries = FOUND; + entries[i][field] = value; + found(&found_output("/t/x", &entries, "0"))["/t/x"] != Some(expected.clone()) + }; + assert!(differs(3, 2, "1796060001.0")); + assert!(differs(3, 1, "1235")); + assert!(differs(3, 0, "-rw-------")); + assert!(differs(1, 4, "a")); + assert!(differs(0, 0, "drwx------")); + assert!(!differs(0, 2, "1")); + assert!(!differs(1, 2, "1")); + // A missing entry, a failing find, and paths populate doesn't + // compare. + assert_ne!( + found(&found_output("/t/x", &FOUND[..3], "0"))["/t/x"], + Some(expected.clone()) + ); + assert_eq!(found(&found_output("/t/x", &FOUND, "1"))["/t/x"], None); + let mut entries = FOUND; + entries[3][3] = "a/new\nline"; + assert_eq!(found(&found_output("/t/x", &entries, "0"))["/t/x"], None); + assert_eq!(listed("rsync: [sender] change_dir failed\n"), None); + assert_eq!( + listed("crw-r--r-- 1,3 2026/11/30 17:33:20 null\n"), + None + ); + assert_eq!( + listed("-rw-r--r-- 1 2026/11/30 17:33:20 a\\#012b\n"), + None + ); + } + #[test] fn changed_paths() { let path = |line| changed_path(line); diff --git a/pkgs/populate/src/sh.rs b/pkgs/populate/src/sh.rs index 52d41ac..f29b1f1 100644 --- a/pkgs/populate/src/sh.rs +++ b/pkgs/populate/src/sh.rs @@ -344,6 +344,24 @@ fi "# } +/// 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, +/// and S and find's exit status, all separated by NULs, so any path comes +/// through. rsync::found reads it. find follows no symlinks, also not +/// PATH itself, so a symlink at PATH shows as such. +pub const LISTINGS: &str = r#" +for path; do + printf 'P\0%s\0' "$path" + if find "$path" -printf 'E\0%M\0%s\0%T@\0%P\0%l\0' 2>/dev/null; then + status=0 + else + status=$? + fi + printf 'S\0%s\0' "$status" +done +"#; + /// symlink PATH TARGET: makes PATH a symlink to TARGET, printing changed /// if it wasn't one. What else is at PATH, e.g. the Git work tree of a /// source that had another type, gets removed first: ln -f replaces files |
