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
|
//! 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};
/// 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)?;
let sentinel = format!("{dir}/.populate");
let force = if spec.force { "1" } else { "" };
context.run(
sh::CHECK,
&[&sentinel, &context.name(&sentinel), dir, force],
)?;
let started = record::now();
let previous = 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 record = record::record(spec, &started, &previous, &context.entries());
context.run(sh::RECORD, &[&sentinel, &record.to_string()])?;
context.unlock();
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.
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}")))
}
/// 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)?;
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(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))
}
}
|