aboutsummaryrefslogtreecommitdiffstats
path: root/pkgs
diff options
context:
space:
mode:
Diffstat (limited to 'pkgs')
-rw-r--r--pkgs/populate/README.md31
-rw-r--r--pkgs/populate/lib/types/populate.nix17
-rw-r--r--pkgs/populate/src/check.rs6
-rw-r--r--pkgs/populate/src/flake_input.rs2
-rw-r--r--pkgs/populate/src/populate.rs90
-rw-r--r--pkgs/populate/src/run.rs19
-rw-r--r--pkgs/populate/src/sh.rs29
-rw-r--r--pkgs/populate/tests/scenarios.nix49
8 files changed, 222 insertions, 21 deletions
diff --git a/pkgs/populate/README.md b/pkgs/populate/README.md
index a947c60..6ceb610 100644
--- a/pkgs/populate/README.md
+++ b/pkgs/populate/README.md
@@ -254,7 +254,12 @@ the record of the run, which a systemd path unit can watch, e.g.:
- 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.
+ rewritten, and `target` for `symlink` sources. A `file` source's `record`
+ setting can add `commit`, `dirty`, and `digest`.
+
+The record tells what populate delivered, which is what's there unless
+something else changed the target directory meanwhile, which populate
+doesn't notice.
The lock ends with the command holding it, which ends with populate, or
with the ssh connection, which keepalives end a minute after the target
@@ -322,6 +327,30 @@ Supported attributes:
the target path of a local target; with `false`, rsync syncs without them.
Both print a warning. Older versions of rsync aren't affected.
+* `record` (optional) -
+ what the [run record](#the-run-record-and-the-lock) tells about what got
+ delivered, besides whether it changed, an attribute set of flags, which
+ default to `false`, so nothing about a source that may hold secrets gets
+ recorded unless asked for:
+
+ * `commit`: if `path` is in a Git work tree, the commit `HEAD` names, as
+ `commit`, and whether `git status` lists anything in `path`, as
+ `dirty`: changes of tracked files, or untracked files that Git doesn't
+ ignore. Files that rsync's filters exclude, or that Git ignores but
+ rsync delivers, don't count, so `dirty` tells whether `path` is the
+ commit as Git sees it. Git runs on the deploying machine, without
+ hooks and file system monitors, on every run.
+ * `digest`: the hash of what's at the target path, after drawing inputs,
+ as `nix-hash --type sha256 --sri` prints it. Populate only computes it
+ when the source changed since the last record, which takes reading all
+ of it, and else takes it from that record.
+
+ rsync can leave out what Git ignores, with `:- .gitignore` in a
+ `.rsync-filter` file in `path`, which reads the `.gitignore` files
+ therein as exclude patterns, though not exactly as Git does: rsync takes
+ a line `!` for clearing the patterns, not for including again, and it
+ doesn't read `.git/info/exclude`, or `core.excludesFile`.
+
* `inputs` (optional) -
inputs of the flake in this source to draw from other sources, see
[Flake inputs from sources](#flake-inputs-from-sources).
diff --git a/pkgs/populate/lib/types/populate.nix b/pkgs/populate/lib/types/populate.nix
index 8e74c5e..eeb4a84 100644
--- a/pkgs/populate/lib/types/populate.nix
+++ b/pkgs/populate/lib/types/populate.nix
@@ -133,6 +133,23 @@
default = false;
type = lib.types.bool;
};
+ # What the run record tells about what got delivered, besides
+ # whether it changed, see populate's README.
+ record = lib.mkOption {
+ default = null;
+ type = lib.types.nullOr (lib.types.submodule {
+ options = {
+ commit = lib.mkOption {
+ default = false;
+ type = lib.types.bool;
+ };
+ digest = lib.mkOption {
+ default = false;
+ type = lib.types.bool;
+ };
+ };
+ });
+ };
exclude = lib.mkOption {
apply = x:
if x != [] then
diff --git a/pkgs/populate/src/check.rs b/pkgs/populate/src/check.rs
index 155565f..b272446 100644
--- a/pkgs/populate/src/check.rs
+++ b/pkgs/populate/src/check.rs
@@ -51,6 +51,8 @@ enum Kind {
Clean,
/// file's filters, each with type include or exclude, and a pattern.
Filters,
+ /// file's record, with commit and digest, flags.
+ Record,
/// Inputs drawn from other sources, each with follows, a string, and
/// inputs, again inputs.
Inputs,
@@ -71,6 +73,7 @@ fn known_settings(kind: &str) -> &'static [(&'static str, Kind, bool)] {
("insecureLinks", Bool, false),
("inputs", Inputs, false),
("rewriteLock", Bool, false),
+ ("record", Record, false),
],
"flake" => &[
("url", String, true),
@@ -129,6 +132,9 @@ fn is_kind(value: &Value, kind: Kind) -> bool {
Kind::Clean => value
.as_object()
.is_some_and(|o| only(o, &["exclude"]) && o.get("exclude").map_or(true, strings)),
+ Kind::Record => value
+ .as_object()
+ .is_some_and(|o| only(o, &["commit", "digest"]) && o.values().all(Value::is_boolean)),
Kind::Filters => value.as_array().is_some_and(|a| {
a.iter().all(|f| {
f.as_object().is_some_and(|o| {
diff --git a/pkgs/populate/src/flake_input.rs b/pkgs/populate/src/flake_input.rs
index 9763ade..8763c47 100644
--- a/pkgs/populate/src/flake_input.rs
+++ b/pkgs/populate/src/flake_input.rs
@@ -359,7 +359,7 @@ pub fn deliver(
args.extend(paths.iter().map(String::as_str));
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]))
+ Ok(Outcome::changed(changed).with("storePath", paths[0].as_str()))
};
let on_target_output = |what: &'static str| {
move |snippet: &str, args: &[&str]| context.output(&on_target(snippet, Some(what)), args)
diff --git a/pkgs/populate/src/populate.rs b/pkgs/populate/src/populate.rs
index efcf5c3..0366c53 100644
--- a/pkgs/populate/src/populate.rs
+++ b/pkgs/populate/src/populate.rs
@@ -25,7 +25,7 @@ pub fn populate(context: &Context, spec: &Spec) -> Result<()> {
&[&sentinel, &context.name(&sentinel), dir, force],
)?;
let started = record::now();
- let previous = context.lock(&sentinel, json!({ "run": started }))?;
+ let (previous, last) = context.lock(&sentinel, json!({ "run": started }))?;
if spec.backup {
context.run(&sh::backup(), &[dir])?;
}
@@ -71,12 +71,54 @@ pub fn populate(context: &Context, spec: &Spec) -> Result<()> {
context.note(json!({ "pruned": true }));
}
}
- let record = record::record(spec, &started, &previous, &context.entries());
+ let mut record = record::record(spec, &started, &previous, &context.entries());
+ digests(context, spec, &mut record, &last.join("\n"))?;
context.run(sh::RECORD, &[&sentinel, &record.to_string()])?;
context.unlock();
Ok(())
}
+/// Adds the digest of each file source whose record setting asks for it to
+/// the record: of what's at its target path now, after the flakes step,
+/// only if it changed since the last record, last, and else the one the
+/// last record has, so a run that changes nothing reads nothing more.
+fn digests(context: &Context, spec: &Spec, record: &mut Value, last: &str) -> Result<()> {
+ let last: Value = serde_json::from_str(last).unwrap_or(Value::Null);
+ let mut names = Vec::new();
+ let mut paths = Vec::new();
+ for (name, source) in &spec.source {
+ if !record_setting(source, "digest") {
+ continue;
+ }
+ let entry = &mut record["sources"][name];
+ let digest = &last["sources"][name]["digest"];
+ if entry["changed"] == json!(false) && digest.is_string() {
+ entry["digest"] = digest.clone();
+ } else {
+ names.push(name);
+ paths.push(format!("{}/{name}", spec.target.path));
+ }
+ }
+ if !paths.is_empty() {
+ let args: Vec<&str> = paths.iter().map(String::as_str).collect();
+ let output = context.output(sh::DIGESTS, &args)?;
+ for (name, digest) in names.iter().zip(output.lines()) {
+ record["sources"][name.as_str()]["digest"] = json!(digest);
+ }
+ }
+ Ok(())
+}
+
+/// Whether a source's record setting has key set.
+fn record_setting(source: &Source, key: &str) -> bool {
+ source
+ .settings
+ .get("record")
+ .and_then(|r| r.get(key))
+ .and_then(Value::as_bool)
+ == Some(true)
+}
+
/// 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)]
@@ -94,8 +136,8 @@ impl Outcome {
}
/// 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));
+ pub fn with(mut self, key: &str, value: impl Into<Value>) -> Outcome {
+ self.delivered.insert(key.to_string(), value.into());
self
}
@@ -230,9 +272,43 @@ impl Kind for File {
// 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);
- Ok(Outcome::changed(
- changed.iter().any(|path| Some(path.as_str()) != lock),
- ))
+ let outcome = Outcome::changed(changed.iter().any(|path| Some(path.as_str()) != lock));
+ if !record_setting(d.source, "commit") {
+ return Ok(outcome);
+ }
+ // What the work tree's Git says, without its hooks and file system
+ // monitors, and without writing the index.
+ let git = |args: &[&str]| {
+ Command::new("git")
+ .args([
+ "-c",
+ "core.hooksPath=/dev/null",
+ "-c",
+ "core.fsmonitor=false",
+ ])
+ .args(["--no-optional-locks", "-C", source_path])
+ .args(args)
+ .stdin(Stdio::null())
+ .stderr(Stdio::null())
+ .output()
+ .ok()
+ .filter(|output| output.status.success())
+ .map(|output| {
+ String::from_utf8_lossy(&output.stdout)
+ .trim_end()
+ .to_string()
+ })
+ };
+ // Nothing, if the path isn't in a Git work tree.
+ let Some(commit) = git(&["rev-parse", "--verify", "--quiet", "HEAD"]) else {
+ return Ok(outcome);
+ };
+ let status = git(&["status", "--porcelain", "--", "."]).ok_or_else(|| {
+ Failure::Message(format!("error: can't tell the Git status of {source_path}"))
+ })?;
+ Ok(outcome
+ .with("commit", commit)
+ .with("dirty", !status.is_empty()))
}
}
diff --git a/pkgs/populate/src/run.rs b/pkgs/populate/src/run.rs
index acbf279..9817b78 100644
--- a/pkgs/populate/src/run.rs
+++ b/pkgs/populate/src/run.rs
@@ -281,8 +281,12 @@ 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, until
/// unlock. Returns the lines that runs that didn't finish left in the
- /// journal.
- pub fn lock(&self, sentinel: &str, entry: serde_json::Value) -> Result<Vec<String>> {
+ /// journal, and the lines of the last run's record.
+ pub fn lock(
+ &self,
+ sentinel: &str,
+ entry: serde_json::Value,
+ ) -> Result<(Vec<String>, Vec<String>)> {
let mut command = self.shell(
crate::sh::LOCK,
&[sentinel, &self.name(sentinel), &entry.to_string()],
@@ -293,7 +297,8 @@ impl Context {
.stderr(Stdio::inherit());
let mut child = command.spawn().map_err(|e| spawn_error(&command, e))?;
let stdout = child.stdout.take().expect("piped");
- let mut previous = Vec::new();
+ let mut journal = Vec::new();
+ let mut record = None;
let mut locked = false;
for line in BufReader::new(stdout).lines() {
let line = line.map_err(|e| {
@@ -305,7 +310,11 @@ impl Context {
locked = true;
break;
}
- previous.push(line);
+ match &mut record {
+ None if line == "record" => record = Some(Vec::new()),
+ None => journal.push(line),
+ Some(record) => record.push(line),
+ }
}
if !locked {
drop(child.stdin.take());
@@ -322,7 +331,7 @@ impl Context {
*self.journal.borrow_mut() = Some(format!("{sentinel}/journal"));
self.entries.borrow_mut().0.push(entry);
self.entries.borrow_mut().1 = 1;
- Ok(previous)
+ Ok((journal, record.unwrap_or_default()))
}
/// Fails if the command holding the lock ended, e.g. killed on the
diff --git a/pkgs/populate/src/sh.rs b/pkgs/populate/src/sh.rs
index 3df2cc4..040ec0a 100644
--- a/pkgs/populate/src/sh.rs
+++ b/pkgs/populate/src/sh.rs
@@ -154,11 +154,13 @@ 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.
+/// finish, appends ENTRY to it, prints record and what's in
+/// SENTINEL/run.json, the last run's record, if any, 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
@@ -177,6 +179,10 @@ if test -f "$sentinel"/journal; then
cat "$sentinel"/journal
fi
printf '%s\n' "$entry" >> "$sentinel"/journal
+echo record
+if test -f "$sentinel"/run.json; then
+ cat "$sentinel"/run.json
+fi
echo locked
exec cat >/dev/null
"#;
@@ -193,6 +199,14 @@ mv -f "$tmp" "$sentinel"/run.json
rm -f "$sentinel"/journal
"#;
+/// digests PATH...: prints the hash of what's at each PATH, as Nix hashes
+/// store paths, in SRI format, on lines of their own.
+pub const DIGESTS: &str = r#"
+for path; do
+ nix-hash --type sha256 --sri "$path"
+done
+"#;
+
/// 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#"
@@ -312,8 +326,9 @@ fi
/// which names another repository, no linked work trees, and only the
/// configuration they write: the repository's format, the remote, branches,
/// and submodules, whose repositories have their work tree in the work
-/// tree. Hooks don't matter: populate's Git doesn't run them. And each .git below the work tree, which Git uses for a
-/// submodule there, is a file naming a repository in .git/modules.
+/// tree. Hooks don't matter: populate's Git doesn't run them. And each
+/// .git below the work tree, which Git uses for a submodule there, is a
+/// file naming a repository in .git/modules.
pub const GIT_PROBLEMS: &str = r#"
git_problems() (
path=$1
diff --git a/pkgs/populate/tests/scenarios.nix b/pkgs/populate/tests/scenarios.nix
index fbcae73..33a2171 100644
--- a/pkgs/populate/tests/scenarios.nix
+++ b/pkgs/populate/tests/scenarios.nix
@@ -870,6 +870,55 @@ in
}
];
}))
+ # A file source's record setting: the commit of the Git work tree, and
+ # whether it's dirty, on every run, and the digest, computed when the
+ # source changed, and else taken from the last record.
+ (s "record-file" (let
+ sources.x.file = {
+ path = "/tmp/record-file";
+ record = { commit = true; digest = true; };
+ };
+ digest = ''
+ expect_eq digest "$(record sources.x.digest)" \
+ "\"$(nix-hash --type sha256 --sri "$T"/x)\""
+ '';
+ in {
+ prepareDeployer = ''
+ rm -fR /tmp/record-file
+ git init -q /tmp/record-file
+ echo a > /tmp/record-file/a
+ git -C /tmp/record-file add a
+ git -C /tmp/record-file -c user.name=krops -c user.email=spam@krebsco.de \
+ commit -q -m a
+ '';
+ phases = [
+ {
+ inherit sources;
+ check = digest + ''
+ expect_eq dirty "$(record sources.x.dirty)" false
+ record sources.x.commit > "$T".commit
+ grep -Eqx '"[0-9a-f]{40}"' "$T".commit || fail "no commit"
+ '';
+ }
+ {
+ inherit sources;
+ check = digest + ''
+ expect_eq changed "$(record sources.x.changed)" false
+ '';
+ mutateDeployer = ''
+ echo b > /tmp/record-file/b
+ '';
+ }
+ {
+ inherit sources;
+ check = digest + ''
+ expect_eq changed "$(record sources.x.changed)" true
+ expect_eq dirty "$(record sources.x.dirty)" true
+ expect_eq commit "$(record sources.x.commit)" "$(cat "$T".commit)"
+ '';
+ }
+ ];
+ }))
# A consumer of the target directory holding a shared lock delays the
# next run.
(s "lock" {