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
496
497
498
499
500
501
502
503
504
505
|
//! `enstate`: the receptor's commands on a host (`--plan`, `--apply`, `--status`,
//! `--materialize`), and the provider's (`--pack`). Commands are options, like every
//! other, in any order.
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use anyhow::{Context, Result, bail};
use clap::{Arg, ArgAction, ArgGroup, Command};
use config::option::{Kind, OptionSpec, option};
use serde::Deserialize;
use enstate::plan::{self, Plan, ViewOutcome};
use enstate::schema::Schema;
use enstate::store::Store;
use enstate::submission::Submission;
use enstate::view;
const OPTIONS: &[OptionSpec] = &[
option(
"state-dir",
Kind::Text,
"DIR",
Some("/var/lib/enstate"),
"Where snapshots are kept",
),
option(
"run-dir",
Kind::Text,
"DIR",
Some("/run/enstate"),
"Where views are put",
),
option(
"schema",
Kind::Text,
"PATH",
Some("/etc/enstate/schema.json"),
"The schema of the running generation; for --pack, one to check the source list against",
),
OptionSpec {
hidden: true,
..option(
"systemctl",
Kind::Text,
"PATH",
Some("systemctl"),
"What runs reactions",
)
},
];
const SETTINGS: config::option::Schema = config::option::Schema {
options: OPTIONS,
conflicts: &[],
gone: &[],
};
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
struct Settings {
state_dir: Option<PathBuf>,
run_dir: Option<PathBuf>,
schema: Option<PathBuf>,
systemctl: Option<PathBuf>,
}
const COMMANDS: &[(&str, &str)] = &[
(
"plan",
"Say what the submission in PATH would do, changing nothing",
),
(
"apply",
"Apply the submission in PATH, if its plan is accepted",
),
("status", "Show the channels' snapshots and the views"),
(
"materialize",
"Put every view in place from the snapshots (at boot, after a switch)",
),
(
"pack",
"Make a submission in --out from the source list in PATH",
),
];
fn command() -> Command {
let mut command = Command::new("enstate")
.about("State next to the Nix store: plan, apply, and make submissions")
.disable_version_flag(true)
.disable_help_flag(true)
.next_help_heading("Commands");
for (name, help) in COMMANDS {
command = command.arg(
Arg::new(*name)
.long(*name)
.action(ArgAction::SetTrue)
.help(*help),
);
}
command = command
.group(
ArgGroup::new("command")
.args(COMMANDS.iter().map(|(name, _)| *name))
.required(true)
.multiple(false),
)
.next_help_heading("Options")
.arg(
Arg::new("help")
.long("help")
.short('h')
.action(ArgAction::Help)
.help("Print this help"),
)
.arg(
Arg::new("json")
.long("json")
.action(ArgAction::SetTrue)
.help("Print JSON (--plan, --apply, --status, --materialize)"),
)
.arg(
Arg::new("out")
.long("out")
.value_name("DIR")
.help("Where --pack writes the submission"),
)
.arg(
Arg::new("path")
.value_name("PATH")
.help("The submission (--plan, --apply) or source list (--pack)"),
)
.next_help_heading("Settings");
config::arguments::with_print_config(config::arguments::with_options(command, OPTIONS))
}
fn main() -> ExitCode {
match run() {
Ok(code) => code,
Err(error) => {
eprintln!("enstate: {error:#}");
ExitCode::from(2)
}
}
}
fn run() -> Result<ExitCode> {
config::arguments::refuse_gone(std::env::args().skip(1), &SETTINGS)?;
let matches = command().get_matches();
let (layer, files) = config::arguments::merged(&matches, &SETTINGS, &[])?;
if config::arguments::prints_config(&matches) {
let settings = layer
.iter()
.map(|(name, entry)| (name.clone(), entry.value.clone()))
.collect();
let origins = layer
.iter()
.map(|(name, entry)| (name.clone(), entry.origin.clone()))
.collect();
let report = config::report::report(
&SETTINGS,
&settings,
&origins,
&files,
config::report::Values::Interpolated,
);
println!("{}", serde_json::to_string_pretty(&report)?);
return Ok(ExitCode::SUCCESS);
}
let settings: Settings = config::layer::read(&layer)?;
let command = COMMANDS
.iter()
.map(|(name, _)| *name)
.find(|name| matches.get_flag(name))
.expect("clap requires one command");
let json = matches.get_flag("json");
let path = matches.get_one::<String>("path").map(PathBuf::from);
let out = matches.get_one::<String>("out").map(PathBuf::from);
// An option that isn't for the command is an error.
let takes_path = matches!(command, "plan" | "apply" | "pack");
match (&path, takes_path) {
(None, true) => bail!("--{command} needs a PATH"),
(Some(path), false) => bail!("--{command} takes no PATH ({})", path.display()),
_ => {}
}
if out.is_some() && command != "pack" {
bail!("--out is for --pack only");
}
if json && command == "pack" {
bail!("--json is not for --pack");
}
if command == "pack" {
let out = out.context("--pack needs --out DIR")?;
let schema = settings.schema.as_deref().map(Schema::load).transpose()?;
enstate::pack::pack(path.as_deref().unwrap(), &out, schema.as_ref())?;
return Ok(ExitCode::SUCCESS);
}
let store = Store::new(
settings
.state_dir
.as_deref()
.unwrap_or(Path::new("/var/lib/enstate")),
settings
.run_dir
.as_deref()
.unwrap_or(Path::new("/run/enstate")),
);
let schema_path = settings
.schema
.unwrap_or_else(|| PathBuf::from("/etc/enstate/schema.json"));
let schema_bytes = std::fs::read(&schema_path)
.with_context(|| format!("reading {}", schema_path.display()))?;
let schema = Schema::from_slice(&schema_bytes)
.with_context(|| format!("schema {}", schema_path.display()))?;
let systemctl = settings
.systemctl
.unwrap_or_else(|| PathBuf::from("systemctl"));
let _lock = store.lock()?;
match command {
"plan" | "apply" => {
let submission = Submission::load(path.as_deref().unwrap())?;
let planned = plan::plan(&schema, &store, &submission)?;
let plan = if command == "apply" {
planned.apply(&store, &schema_bytes, &systemctl)?
} else {
planned.plan
};
if json {
println!("{}", serde_json::to_string_pretty(&plan)?);
} else {
print_plan(&plan, command == "apply")?;
}
Ok(if !plan.accepted {
ExitCode::from(1)
} else if !plan.failed.is_empty() {
ExitCode::from(3)
} else {
ExitCode::SUCCESS
})
}
"materialize" => {
let views = plan::materialize(&schema, &store)?;
if json {
println!("{}", serde_json::to_string_pretty(&views)?);
} else {
print_views(&mut std::io::stdout().lock(), &views, false)?;
}
Ok(ExitCode::SUCCESS)
}
"status" => {
let status = status(&schema, &store)?;
if json {
println!("{}", serde_json::to_string_pretty(&status)?);
} else {
print_status(&status)?;
}
Ok(ExitCode::SUCCESS)
}
_ => unreachable!(),
}
}
/// Colors, on a terminal, and without `NO_COLOR`.
struct Style {
on: bool,
}
impl Style {
fn new() -> Self {
Self {
on: std::io::stdout().is_terminal()
&& std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty()),
}
}
fn paint(&self, code: &str, text: &str) -> String {
if self.on {
format!("\x1b[{code}m{text}\x1b[0m")
} else {
text.to_owned()
}
}
}
fn print_plan(plan: &Plan, applying: bool) -> Result<()> {
let style = Style::new();
let mut out = std::io::stdout().lock();
let verdict = if plan.accepted {
style.paint("32", "accepted")
} else {
style.paint("31", "refused")
};
writeln!(out, "channel {}: {verdict}", plan.channel)?;
writeln!(
out,
" current snapshot: {}",
plan.current.as_deref().unwrap_or("none")
)?;
if let Some(base) = &plan.base {
writeln!(out, " builds on: {base}")?;
}
for reason in &plan.refused {
writeln!(out, " {} {reason}", style.paint("31", "refused:"))?;
}
if !plan.items.is_empty() {
writeln!(out, "items:")?;
}
for item in &plan.items {
let mark = if item.goes_in {
style.paint("32", "+")
} else {
style.paint("33", "-")
};
let mut what = format!(
"{}, {}",
item.op,
if item.required {
"required"
} else {
"optional"
}
);
if let Some(group) = &item.group {
what.push_str(&format!(", group {group}"));
}
writeln!(out, " {mark} {} ({what})", item.address)?;
for reason in &item.reasons {
writeln!(out, " {reason}")?;
}
}
for warning in &plan.warnings {
writeln!(out, "{} {warning}", style.paint("33", "warning:"))?;
}
print_views(&mut out, &plan.views, true)?;
if !plan.reactions.restart.is_empty() {
writeln!(out, "restart: {}", plan.reactions.restart.join(" "))?;
}
if !plan.reactions.reload.is_empty() {
writeln!(out, "reload: {}", plan.reactions.reload.join(" "))?;
}
if plan.accepted && !plan.changes {
writeln!(out, "nothing changes")?;
}
if applying && plan.accepted {
match &plan.snapshot {
Some(id) => writeln!(out, "applied: snapshot {id}")?,
None if plan.changes => writeln!(out, "applied: the snapshot is unchanged")?,
None => {}
}
for failed in &plan.failed {
writeln!(out, "{} {failed}", style.paint("31", "failed:"))?;
}
}
Ok(())
}
fn print_views(out: &mut impl Write, views: &[ViewOutcome], only_changes: bool) -> Result<()> {
let style = Style::new();
let changing: Vec<_> = views
.iter()
.filter(|view| !only_changes || view.change != view::Change::Unchanged)
.collect();
if changing.is_empty() {
return Ok(());
}
writeln!(out, "views:")?;
for view in changing {
let change = match view.change {
view::Change::Unchanged => "unchanged",
view::Change::Added => "added",
view::Change::Removed => "removed",
view::Change::Changed => "changed",
};
let secret = if view.secret { " (secret)" } else { "" };
writeln!(out, " {}{secret}: {change}", view.name)?;
for file in &view.files {
for line in file.diff.lines() {
let painted = match line.chars().next() {
Some('+') if !line.starts_with("+++") => style.paint("32", line),
Some('-') if !line.starts_with("---") => style.paint("31", line),
_ => line.to_owned(),
};
writeln!(out, " {painted}")?;
}
}
}
Ok(())
}
#[derive(serde::Serialize)]
struct Status {
channels: Vec<ChannelStatus>,
views: Vec<ViewStatus>,
}
#[derive(serde::Serialize)]
struct ChannelStatus {
channel: String,
snapshot: Option<String>,
filled: Vec<String>,
unfilled: Vec<String>,
/// Required, and unfilled.
missing: Vec<String>,
/// Kept, but in no slot of the schema.
kept: Vec<String>,
}
#[derive(serde::Serialize)]
struct ViewStatus {
view: String,
installed: bool,
}
fn status(schema: &Schema, store: &Store) -> Result<Status> {
let mut channels = Vec::new();
let mut names: Vec<String> = schema.channels.keys().cloned().collect();
for channel in store.channels()? {
if !names.contains(&channel) {
names.push(channel);
}
}
for channel in names {
let snapshot = store.current(&channel)?;
let content = snapshot
.as_ref()
.map(|snapshot| snapshot.content.clone())
.unwrap_or_default();
let slots = schema
.channel(&channel)
.map(|spec| spec.slots.clone())
.unwrap_or_default();
channels.push(ChannelStatus {
channel: channel.clone(),
snapshot: snapshot.map(|snapshot| snapshot.id),
filled: slots
.keys()
.filter(|slot| content.contains_key(*slot))
.cloned()
.collect(),
unfilled: slots
.keys()
.filter(|slot| !content.contains_key(*slot))
.cloned()
.collect(),
missing: slots
.iter()
.filter(|(slot, spec)| spec.required && !content.contains_key(*slot))
.map(|(slot, _)| slot.clone())
.collect(),
kept: content
.keys()
.filter(|slot| !slots.contains_key(*slot))
.cloned()
.collect(),
});
}
let views = schema
.views
.keys()
.map(|view| ViewStatus {
view: view.clone(),
installed: store.installed_view(view).is_some(),
})
.collect();
Ok(Status { channels, views })
}
fn print_status(status: &Status) -> Result<()> {
let style = Style::new();
let mut out = std::io::stdout().lock();
for channel in &status.channels {
writeln!(
out,
"channel {}: snapshot {}",
channel.channel,
channel.snapshot.as_deref().unwrap_or("none")
)?;
for slot in &channel.filled {
writeln!(out, " {} {slot}", style.paint("32", "filled"))?;
}
for slot in &channel.unfilled {
let missing = channel.missing.contains(slot);
let label = if missing {
style.paint("31", "missing")
} else {
"unfilled".to_owned()
};
writeln!(out, " {label} {slot}")?;
}
for slot in &channel.kept {
writeln!(out, " {} {slot}", style.paint("33", "kept"))?;
}
}
for view in &status.views {
let state = if view.installed {
style.paint("32", "in place")
} else {
style.paint("33", "not in place")
};
writeln!(out, "view {}: {state}", view.view)?;
}
Ok(())
}
|