//! `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, run_dir: Option, schema: Option, systemctl: 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", ), ("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 { 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::("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" | "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, 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, } #[derive(serde::Serialize)] struct ViewStatus { view: String, installed: bool, } fn status(schema: &Schema, store: &Store) -> Result { let mut channels = Vec::new(); let mut names: Vec = 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(()) }