aboutsummaryrefslogtreecommitdiffstats
path: root/pkgs/populate/src/populate.rs
blob: 1aaf064d50322e48d4b7436fc806055afc808aaa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Delivering the sources of a spec.

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::{json, Map, Value};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

/// The commands populate runs on the target to deliver spec's sources, each
/// followed by the attribute name in nixpkgs of the package that has it.
fn tools(spec: &Spec) -> Vec<&'static str> {
    let sources = || spec.source.values();
    let mut tools = vec!["find", "findutils", "flock", "util-linux"];
    if sources().any(|s| !matches!(s.kind.as_str(), "derivation" | "git" | "symlink")) {
        tools.extend(["rsync", "rsync"]);
    }
    if sources().any(|s| s.kind == "git") {
        tools.extend(["git", "git", "grep", "gnugrep", "sed", "gnused"]);
    }
    let patched = |s: &&Source| {
        s.settings
            .get("patches")
            .and_then(Value::as_array)
            .is_some_and(|patches| !patches.is_empty())
    };
    if sources().any(|s| patched(&s)) {
        tools.extend(["patch", "gnupatch"]);
    }
    tools
}

/// Checks the sentinel, gets what the target lacks of the commands
/// populate runs there from nixpkgs, 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)?;
    let sentinel = format!("{dir}/.populate");
    let force = if spec.force { "1" } else { "" };
    let name = context.name(&sentinel);
    let mut args = vec![sentinel.as_str(), &name, dir, force];
    args.extend(tools(spec));
    let output = context.output(sh::CHECK, &args)?;
    if let Some(path) = output.lines().find_map(|line| line.strip_prefix("path ")) {
        context.add_path(path);
    }
    let started = record::now();
    let (previous, last) = context.lock(&sentinel, json!({ "run": started }))?;
    if spec.backup {
        context.run(&sh::backup(), &[dir])?;
    }
    for (name, source) in &spec.source {
        let path = format!("{dir}/{name}");
        eprintln!("populating '{}'...", context.name(&path));
        let workdir = context.tmpdir.join("workdirs").join(name);
        fs::create_dir_all(&workdir).map_err(|e| {
            Failure::Message(format!("error: can't create {}: {e}", workdir.display()))
        })?;
        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 {
        let flakes = spec
            .source
            .iter()
            .filter(|(_, source)| matches!(source.kind.as_str(), "flake" | "flake-input"))
            .map(|(name, _)| name.as_str());
        let mut args = vec![dir.as_str()];
        let log = context.name(dir);
        args.push(&log);
        args.extend(spec.source.keys().map(String::as_str));
        args.push("--");
        args.extend(flakes);
        if context.output(&sh::prune(), &args)?.contains("pruned") {
            context.note(json!({ "pruned": true }));
        }
    }
    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)]
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: impl Into<Value>) -> Outcome {
        self.delivered.insert(key.to_string(), value.into());
        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.is_empty()))
    }
}

/// 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.
fn refuse_copying_with_sudo(context: &Context, spec: &Spec) -> Result<()> {
    for (name, source) in &spec.source {
        let copying = matches!(source.kind.as_str(), "flake" | "flake-input")
            && source
                .settings
                .get("fetchOnTarget")
                .and_then(Value::as_bool)
                != Some(true);
        if copying && context.target.sudo && !context.local {
            return Err(Failure::Message(format!(
                "krops: source {}/{name}: copying flakes to targets with sudo is not supported",
                spec.target.path
            )));
        }
    }
    Ok(())
}

fn string<'a>(settings: &'a Map<String, Value>, key: &str) -> Result<&'a str> {
    settings
        .get(key)
        .and_then(Value::as_str)
        .ok_or_else(|| Failure::Message(format!("populate: the source has no {key}")))
}

/// The path, relative to the source, of the lock file of the flake in a
/// source, if the flakes step rewrites it in place, see flake::rewrite.
fn in_place_lock(source: &Source) -> Option<&'static str> {
    flake::rewrites_lock(source).then_some("flake.lock")
}

/// 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(),
            &[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)?;
        // 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);
        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()))
    }
}

/// 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.is_empty()))
    }
}

/// 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"),
            in_place_lock(d.source).unwrap_or_default(),
        ];
        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(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],
            &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"),
                    _ => return Err(Failure::Message(
                        "populate: HOME isn't set, so the passage source has no identities_file"
                            .to_string(),
                    )),
                },
            };
        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))
    }
}