//! `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::parser::ValueSource; 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", ), option( "unit", Kind::Text, "UNIT", None, "The systemd unit that runs --migrate at boot and after switches: --apply starts it again if it failed", ), OptionSpec { hidden: true, ..option( "systemctl", Kind::Text, "PATH", Some("systemctl"), "What runs reactions", ) }, ]; /// Read first, if it exists. const SYSTEM_CONFIG: &str = "/etc/enstate/config.json"; const SETTINGS: config::option::Schema = config::option::Schema { options: OPTIONS, conflicts: &[], gone: &[], }; #[derive(Deserialize)] #[serde(rename_all = "kebab-case")] struct Settings { state_dir: Option, run_dir: Option, schema: Option, systemctl: Option, unit: Option, } 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", ), ( "stage", "Like --apply, for the generation of --schema before switching to it: the snapshot only, no views, no reactions", ), ("status", "Show the channels' snapshots and the views"), ( "materialize", "Put every view in place from the snapshots (at boot, after a switch)", ), ( "migrate", "Serve the generation of --schema from the snapshots: what it sees, its views, their reactions", ), ( "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, --stage, --status, --materialize, --migrate)"), ) .arg( Arg::new("dry-run") .long("dry-run") .action(ArgAction::SetTrue) .help("With --migrate: say what it would do, changing nothing"), ) .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, --stage) 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 { config::arguments::refuse_gone(std::env::args().skip(1), &SETTINGS)?; let matches = command().get_matches(); // The system's configuration, if it has one (the NixOS module writes it), then // --config files, then arguments. let system: Vec = [Path::new(SYSTEM_CONFIG)] .into_iter() .filter(|path| path.exists()) .map(Path::to_owned) .collect(); let (layer, files) = config::arguments::merged(&matches, &SETTINGS, &system)?; 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::("path").map(PathBuf::from); let out = matches.get_one::("out").map(PathBuf::from); // An option that isn't for the command is an error. let takes_path = matches!(command, "plan" | "apply" | "stage" | "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 matches.get_flag("dry-run") && command != "migrate" { bail!("--dry-run is for --migrate only"); } if json && command == "pack" { bail!("--json is not for --pack"); } // A setting given as an argument that the command doesn't use is an error; from a // configuration file, which holds them for every command, it isn't. for spec in OPTIONS { if matches.value_source(spec.name) == Some(ValueSource::CommandLine) && !uses(command, spec.name) { bail!("--{} is not for --{command}", spec.name); } } if command == "pack" { let out = out.context("--pack needs --out DIR")?; let schema = settings.schema.as_deref().map(Schema::load).transpose()?; for warning in enstate::pack::pack(path.as_deref().unwrap(), &out, schema.as_ref())? { eprintln!("enstate: warning: {warning}"); } 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" | "stage" => { let submission = Submission::load(path.as_deref().unwrap())?; let planned = plan::plan(&schema, &store, &submission)?; let mut plan = if command == "apply" { planned.apply(&store, &schema_bytes, &systemctl, lock)? } else if command == "stage" { planned.stage(&store, &schema_bytes, lock)? } else { planned.plan }; // A unit that failed for want of the state applied now (at boot, say) // gets to serve the views, and is no longer failed. if command == "apply" && plan.accepted && let Some(unit) = &settings.unit && let Some(failed) = plan::start_if_failed(unit, &systemctl) { plan.failed.push(failed); } if json { println!("{}", serde_json::to_string_pretty(&plan)?); } else { print_plan(&plan, command != "plan")?; } Ok(if !plan.accepted { ExitCode::from(1) } else if !plan.failed.is_empty() { ExitCode::from(3) } else { ExitCode::SUCCESS }) } "materialize" => { let views = enstate::migrate::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) } "migrate" => { let migration = enstate::migrate::migrate( &schema, &schema_bytes, &store, matches.get_flag("dry-run"), &systemctl, )?; if json { println!("{}", serde_json::to_string_pretty(&migration)?); } else { print_migration(&migration)?; } Ok(if !migration.accepted { ExitCode::from(1) } else if !migration.failed.is_empty() { ExitCode::from(3) } else { 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) if plan.staged => writeln!( out, "staged: snapshot {id}; views and reactions come with the switch" )?, Some(id) => writeln!(out, "applied: snapshot {id}")?, None if plan.changes && !plan.staged => { 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, views: Vec, } #[derive(serde::Serialize)] struct ChannelStatus { channel: String, snapshot: Option, filled: Vec, unfilled: Vec, /// Required, and unfilled. missing: Vec, /// Kept, but in no slot of the schema. kept: Vec, /// Where entries came from, what can't be taken. notes: Vec, } #[derive(serde::Serialize)] struct ViewStatus { view: String, installed: bool, } 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 note in &channel.notes { writeln!(out, " {note}")?; } } 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(()) } fn status(schema: &Schema, store: &Store) -> Result { let mut channels = Vec::new(); for (channel, seen) in enstate::migrate::seen_all(schema, store)? { let slots = schema .channel(&channel) .map(|spec| spec.slots.clone()) .unwrap_or_default(); let content = &seen.content; channels.push(ChannelStatus { channel: channel.clone(), snapshot: store.current(&channel)?.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: seen.kept_names(), notes: seen.notes.clone(), }); } 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_migration(migration: &enstate::migrate::Migration) -> Result<()> { let style = Style::new(); let mut out = std::io::stdout().lock(); let verdict = if migration.accepted { style.paint("32", "every required slot is filled") } else { style.paint("31", "refused") }; let dry_run = if migration.dry_run { " (dry run)" } else { "" }; writeln!(out, "migration{dry_run}: {verdict}")?; for reason in &migration.refused { writeln!(out, " {} {reason}", style.paint("31", "refused:"))?; } for incoming in &migration.incoming { let what = match (&incoming.plan, migration.dry_run) { (Some(plan), true) if plan.accepted => "would go in".to_owned(), (Some(plan), false) if plan.accepted => match &plan.snapshot { Some(id) => format!("went in: snapshot {id}"), None => "went in, changing nothing".to_owned(), }, _ => style.paint("31", "refused"), }; writeln!(out, "incoming {}: {what}", incoming.name)?; } for (channel, channel_migration) in &migration.channels { writeln!( out, "channel {channel}: snapshot {}", channel_migration.snapshot.as_deref().unwrap_or("none") )?; for note in &channel_migration.seen.notes { writeln!(out, " {note}")?; } for slot in &channel_migration.kept { writeln!(out, " {} {channel}/{slot}", style.paint("33", "kept"))?; } } print_views(&mut out, &migration.views, true)?; if !migration.reactions.restart.is_empty() { writeln!(out, "restart: {}", migration.reactions.restart.join(" "))?; } if !migration.reactions.reload.is_empty() { writeln!(out, "reload: {}", migration.reactions.reload.join(" "))?; } for failed in &migration.failed { writeln!(out, "{} {failed}", style.paint("31", "failed:"))?; } Ok(()) } /// Whether `command` uses the setting `setting`. fn uses(command: &str, setting: &str) -> bool { match setting { // Where the snapshots and views are: everything but making a submission. "state-dir" | "run-dir" => command != "pack", // The schema to plan against, or, for --pack, to check against. "schema" => true, // Reactions run. "systemctl" => matches!(command, "apply" | "migrate"), "unit" => command == "apply", _ => true, } }