1use std::process::Command;23use crate::{4 command::CommandExt,5 db::{secret::SecretDb, Db, DbData},6 host::FleetOpts,7 nix::SYSTEMS_ATTRIBUTE,8};9use anyhow::Result;10use clap::Clap;11use log::{info, warn};1213#[derive(Clap)]14#[clap(group = clap::ArgGroup::new("target"))]15pub struct BuildSystems {16 #[clap(flatten)]17 fleet_opts: FleetOpts,18 19 #[clap(long)]20 builders: Option<String>,21 22 #[clap(long)]23 jobs: Option<usize>,24 25 #[clap(long)]26 fail_fast: bool,27 #[clap(long)]28 privileged_build: bool,29 #[clap(subcommand)]30 subcommand: Option<Subcommand>,31}3233#[derive(Clap)]34enum Subcommand {35 36 Test,37 38 Boot,39 40 Switch,41}42impl Subcommand {43 fn should_switch_profile(&self) -> bool {44 matches!(self, Self::Test | Self::Switch)45 }46 fn name(&self) -> &'static str {47 match self {48 Self::Test => "test",49 Self::Boot => "boot",50 Self::Switch => "switch",51 }52 }53}5455impl BuildSystems {56 pub fn run(self) -> Result<()> {57 let fleet = self.fleet_opts.build()?;58 let db = Db::new(".fleet")?;59 let hosts = fleet.list_hosts()?;60 let data = SecretDb::open(&db)?.generate_nix_data()?;6162 for host in hosts.iter() {63 if host.skip() {64 warn!("Skipping host {}", host.hostname);65 continue;66 }67 info!("Building host {}", host.hostname);68 let built = {69 let dir = tempfile::tempdir()?;70 dir.path().to_owned()71 };7273 let mut nix_build = if self.privileged_build {74 let mut out = Command::new("sudo");75 out.arg("nix");76 out77 } else {78 Command::new("nix")79 };80 nix_build81 .args(&["build", "--impure", "--no-link", "--out-link"])82 .arg(&built)83 .arg(format!(84 "{}.{}.config.system.build.toplevel",85 SYSTEMS_ATTRIBUTE, host.hostname,86 ))87 .env("SECRET_DATA", data.clone());8889 if let Some(builders) = &self.builders {90 println!("Using builders: {}", builders);91 nix_build.arg("--builders").arg(builders);92 }93 if let Some(jobs) = &self.jobs {94 nix_build.arg("--max-jobs");95 nix_build.arg(format!("{}", jobs));96 }97 if !self.fail_fast {98 nix_build.arg("--keep-going");99 }100101 nix_build.inherit_stdio().run()?;102 let built = std::fs::canonicalize(built)?;103 info!("Built closure: {:?}", built);104 if !host.is_local() {105 info!("Uploading system closure");106 Command::new("nix")107 .args(&["copy", "--to"])108 .arg(format!("ssh://root@{}", host.hostname))109 .arg(&built)110 .inherit_stdio()111 .run()?;112 }113 if let Some(subcommand) = &self.subcommand {114 if subcommand.should_switch_profile() {115 info!("Switching generation");116 host.command_on("nix-env", true)117 .args(&["-p", "/nix/var/nix/profiles/system", "--set"])118 .arg(&built)119 .inherit_stdio()120 .run()?;121 }122 info!("Executing activation script");123 let mut switch_script = built.clone();124 switch_script.push("bin");125 switch_script.push("switch-to-configuration");126 info!("{:?}", switch_script);127 host.command_on(switch_script, true)128 .arg(subcommand.name())129 .inherit_stdio()130 .run()?;131 }132 }133 Ok(())134 }135}