5 files changed
1use crate::{2 db::{keys::list_hosts, secret::SecretDb, Db, DbData},3 nix::{NixBuild, NixCopy, HOSTS_ATTRIBUTE, SYSTEMS_ATTRIBUTE},4};5use anyhow::Result;6use clap::Clap;7use log::info;89#[derive(Clap)]10pub struct BuildSystems {}1112impl BuildSystems {13 pub fn run(self) -> Result<()> {14 let db = Db::new(".fleet")?;15 let hosts = list_hosts()?;16 let data = SecretDb::open(&db)?.generate_nix_data()?;1718 for host in hosts.iter() {19 info!("Building host {}", host);20 let path = NixBuild::new(format!(21 "{}.{}.config.system.build.toplevel",22 SYSTEMS_ATTRIBUTE, host,23 ))24 .env("SECRET_DATA".into(), data.clone())25 .run()?;26 info!("{:?}", path.path());27 NixCopy::new(path.path().to_owned()).to(format!("ssh://root@{}", host))?;28 std::thread::sleep_ms(9999999)29 }30 Ok(())31 }32}
1use std::process::Command;23use crate::{4 command::CommandExt,5 db::{keys::list_hosts, secret::SecretDb, Db, DbData},6 nix::SYSTEMS_ATTRIBUTE,7};8use anyhow::Result;9use clap::Clap;10use log::{info, warn};1112#[derive(Clap)]13pub struct BuildSystems {14 15 #[clap(long, number_of_values = 1)]16 skip: Vec<String>,17 #[clap(subcommand)]18 subcommand: Option<Subcommand>,19}2021#[derive(Clap)]22enum Subcommand {23 24 Test,25 26 Boot,27 28 Switch,29}3031impl BuildSystems {32 pub fn run(self) -> Result<()> {33 let db = Db::new(".fleet")?;34 let hosts = list_hosts()?;35 let data = SecretDb::open(&db)?.generate_nix_data()?;3637 for host in hosts.iter() {38 if self.skip.contains(host) {39 warn!("Skipping host {}", host);40 continue;41 }42 info!("Building host {}", host);43 let built = tempfile::tempdir()?;44 Command::new("nix")45 .inherit_stdio()46 .arg("build")47 .arg(format!(48 "{}.{}.config.system.build.toplevel",49 SYSTEMS_ATTRIBUTE, host,50 ))51 .arg("--no-link")52 .arg("--out-link")53 .arg(built.path())54 .arg("--impure")55 .env("SECRET_DATA", data.clone())56 .run()?;57 info!("Uploading system closure");58 let full_path = std::fs::canonicalize(built.path())?;59 info!("{:?}", full_path);60 Command::new("nix")61 .inherit_stdio()62 .arg("copy")63 .arg(full_path)64 .arg("--to")65 .arg(format!("ssh://root@{}", host))66 .run()?;67 match self.subcommand {68 Some(Subcommand::Test) => {69 info!("Setting system to test")70 }71 Some(Subcommand::Boot) => {72 info!("Setting system to switch on boot")73 }74 Some(Subcommand::Switch) => {75 info!("Switching to configuration")76 }77 _ => {}78 }79 }80 Ok(())81 }82}
--- a/src/command.rs
+++ b/src/command.rs
@@ -4,31 +4,46 @@
};
use anyhow::{Context, Result};
-use serde::Deserialize;
+use serde::de::DeserializeOwned;
-pub struct CommandOutput(pub Vec<u8>);
-impl CommandOutput {
- pub fn into_json<'d, T: Deserialize<'d>>(&'d self) -> Result<T> {
- let str = self.as_str().ok();
- Ok(serde_json::from_slice(&self.0).with_context(|| format!("{:?}", str))?)
+pub trait CommandExt {
+ fn run(&mut self) -> Result<()>;
+ fn run_json<T: DeserializeOwned>(&mut self) -> Result<T>;
+ fn run_string(&mut self) -> Result<String>;
+ fn inherit_stdio(&mut self) -> &mut Self;
+ fn ssh_on(host: impl AsRef<OsStr>, command: impl AsRef<OsStr>) -> Self;
+}
+
+impl CommandExt for Command {
+ fn inherit_stdio(&mut self) -> &mut Self {
+ self.stderr(Stdio::inherit());
+ self
}
- pub fn as_str(&self) -> Result<&str> {
- Ok(std::str::from_utf8(&self.0)?)
+
+ fn run(&mut self) -> Result<()> {
+ let out = self.output()?;
+ if !out.status.success() {
+ anyhow::bail!("command failed");
+ }
+ Ok(())
}
-}
-pub fn ssh_command<I, S>(host: impl AsRef<OsStr>, command: I) -> Result<CommandOutput>
-where
- I: IntoIterator<Item = S>,
- S: AsRef<OsStr>,
-{
- let out = Command::new("ssh")
- .stderr(Stdio::inherit())
- .arg(host)
- .args(command)
- .output()?;
- if !out.status.success() {
- anyhow::bail!("command failed");
+ fn run_json<T: DeserializeOwned>(&mut self) -> Result<T> {
+ let str = self.run_string()?;
+ Ok(serde_json::from_str(&str).with_context(|| format!("{:?}", str))?)
+ }
+
+ fn run_string(&mut self) -> Result<String> {
+ let out = self.output()?;
+ if !out.status.success() {
+ anyhow::bail!("command failed");
+ }
+ Ok(String::from_utf8(out.stdout)?)
+ }
+
+ fn ssh_on(host: impl AsRef<OsStr>, command: impl AsRef<OsStr>) -> Self {
+ let mut cmd = Command::new("ssh");
+ cmd.arg(host).arg("--").arg(command);
+ cmd
}
- Ok(CommandOutput(out.stdout))
}
--- a/src/db/keys.rs
+++ b/src/db/keys.rs
@@ -1,20 +1,21 @@
-use std::collections::BTreeMap;
+use std::{collections::BTreeMap, process::Command};
use anyhow::Result;
use log::*;
-use crate::{
- command::ssh_command,
- nix::{NixEval, HOSTS_ATTRIBUTE},
-};
+use crate::{command::CommandExt, nix::HOSTS_ATTRIBUTE};
use serde::{Deserialize, Serialize};
use super::db::DbData;
pub fn list_hosts() -> Result<Vec<String>> {
- Ok(NixEval::new(HOSTS_ATTRIBUTE.into())
- .apply("builtins.attrNames".into())
+ Ok(Command::new("nix")
+ .inherit_stdio()
+ .arg("eval")
+ .arg(HOSTS_ATTRIBUTE)
+ .arg("--apply")
+ .arg("builtins.attrNames")
.run_json()?)
}
@@ -29,10 +30,9 @@
impl KeyDb {
pub fn fetch_key(&mut self, host: &str) -> Result<()> {
info!("Fetching key for {}", host);
- let key = ssh_command(host, &["cat", "/etc/ssh/ssh_host_ed25519_key.pub"])?
- .as_str()?
- .trim()
- .to_owned();
+ let key = Command::ssh_on(host, "cat")
+ .arg("/etc/ssh/ssh_host_ed25519_key.pub")
+ .run_string()?;
self.host_keys.insert(host.to_owned(), key);
Ok(())
}
--- a/src/db/secret.rs
+++ b/src/db/secret.rs
@@ -1,9 +1,10 @@
-use crate::nix::{NixBuild, NixEval, SECRETS_ATTRIBUTE};
+use crate::{command::CommandExt, nix::SECRETS_ATTRIBUTE};
use anyhow::{bail, Result};
use log::info;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{
collections::{BTreeMap, BTreeSet, HashMap},
+ process::Command,
time::Instant,
time::SystemTime,
};
@@ -18,14 +19,17 @@
renew_in: Option<u64>,
}
pub fn list_secrets() -> Result<HashMap<String, SecretListData>> {
- NixEval::new(format!("{}", SECRETS_ATTRIBUTE))
- .apply(
+ Command::new("nix")
+ .inherit_stdio()
+ .arg("eval")
+ .arg(SECRETS_ATTRIBUTE)
+ .arg("--apply")
+ .arg(
r#"
s: (builtins.mapAttrs (n: {owners, expireIn, ...}: {
inherit owners expireIn;
}) s)
- "#
- .into(),
+ "#,
)
.run_json()
}
@@ -122,9 +126,17 @@
let renew_at = data
.renew_in
.map(|hours| created_at + Duration::hours(hours as i64));
- let built = NixBuild::new(format!("{}.{}.generator", SECRETS_ATTRIBUTE, secret))
- .env("RAGE_KEYS".into(), rage_keys)
- .env("IMPURITY_SOURCE".into(), format!("{:?}", Instant::now()))
+ let built = tempfile::tempdir()?;
+ Command::new("nix")
+ .inherit_stdio()
+ .arg("build")
+ .arg(format!("{}.{}.generator", SECRETS_ATTRIBUTE, secret))
+ .arg("--no-link")
+ .arg("--out-link")
+ .arg(built.path())
+ .arg("--impure")
+ .env("RAGE_KEYS", rage_keys)
+ .env("IMPURITY_SOURCE", format!("{:?}", Instant::now()))
.run()?;
let path = built.path().to_owned();
let mut secret_data = SecretData {
--- a/src/nix.rs
+++ b/src/nix.rs
@@ -1,172 +1,3 @@
-use std::{
- collections::HashMap,
- ffi::OsStr,
- path::PathBuf,
- process::{Command, Stdio},
-};
-
-use anyhow::Result;
-use serde::de::DeserializeOwned;
-
-use crate::command::CommandOutput;
-
pub const HOSTS_ATTRIBUTE: &str = ".#fleetConfigurations.default.configuredHosts";
pub const SECRETS_ATTRIBUTE: &str = ".#fleetConfigurations.default.configuredSecrets";
pub const SYSTEMS_ATTRIBUTE: &str = ".#fleetConfigurations.default.configuredSystems";
-
-pub struct NixCopy {
- closure: PathBuf,
-}
-impl NixCopy {
- pub fn new(closure: PathBuf) -> Self {
- Self { closure }
- }
- fn run_internal(&self, f: impl Fn(&mut Command)) -> Result<CommandOutput> {
- let mut cmd = Command::new("nix");
- cmd.stderr(Stdio::inherit())
- .arg("copy")
- .arg("--substitute-on-destination")
- .arg(&self.closure);
- f(&mut cmd);
-
- let out = cmd.output()?;
- if !out.status.success() {
- anyhow::bail!("nix copy failed");
- }
- Ok(CommandOutput(out.stdout))
- }
- pub fn from(&self, from: impl AsRef<OsStr>) -> Result<()> {
- let from = from.as_ref();
- self.run_internal(|cmd| {
- cmd.arg("--from").arg(from);
- })?;
- Ok(())
- }
- pub fn to(&self, to: impl AsRef<OsStr>) -> Result<()> {
- let to = to.as_ref();
- self.run_internal(|cmd| {
- cmd.arg("--to").arg(to);
- })?;
- Ok(())
- }
-}
-
-pub struct NixBuild {
- attribute: String,
- impure: bool,
- env: HashMap<String, String>,
-}
-
-impl NixBuild {
- pub fn new(attribute: String) -> Self {
- Self {
- attribute,
- impure: false,
- env: HashMap::new(),
- }
- }
- pub fn env(&mut self, name: String, value: String) -> &mut Self {
- self.impure = true;
- self.env.insert(name, value);
- self
- }
- pub fn run(&self) -> Result<tempfile::TempDir> {
- let dir = tempfile::tempdir()?;
- std::fs::remove_dir(dir.path())?;
- let mut cmd = Command::new("nix");
- cmd.stderr(Stdio::inherit())
- .arg("build")
- .arg(&self.attribute)
- .arg("--no-link")
- .arg("--out-link")
- .arg(dir.path());
- if self.impure {
- cmd.arg("--impure");
- }
- if !self.env.is_empty() {
- cmd.envs(&self.env);
- }
-
- let out = cmd.output()?;
- if !out.status.success() {
- anyhow::bail!("nix eval failed");
- }
- Ok(dir)
- }
-}
-
-#[derive(Default)]
-pub struct NixEval {
- attribute: String,
- impure: bool,
- apply: Option<String>,
- env: HashMap<String, String>,
-}
-
-impl NixEval {
- pub fn new(attribute: String) -> Self {
- Self {
- attribute,
- ..Default::default()
- }
- }
- pub fn impure(&mut self) -> &mut Self {
- self.impure = true;
- self
- }
- /// This is the only and impure way to pass something to flake
- /// - https://github.com/NixOS/nix/issues/3949
- /// - https://github.com/NixOS/nixpkgs/issues/101101
- pub fn env(&mut self, name: String, value: String) -> &mut Self {
- self.impure = true;
- self.env.insert(name, value);
- self
- }
- pub fn apply(&mut self, apply: String) -> &mut Self {
- self.apply = Some(apply);
- self
- }
- fn run_internal(&self, f: impl Fn(&mut Command)) -> Result<CommandOutput> {
- let mut cmd = Command::new("nix");
- cmd.stderr(Stdio::inherit())
- .arg("eval")
- .arg("--show-trace")
- .arg(&self.attribute);
- if let Some(apply) = &self.apply {
- cmd.arg("--apply").arg(apply);
- };
- if self.impure {
- cmd.arg("--impure");
- }
- if !self.env.is_empty() {
- cmd.envs(&self.env);
- }
- f(&mut cmd);
-
- let out = cmd.output()?;
- if !out.status.success() {
- anyhow::bail!("nix eval failed");
- }
- Ok(CommandOutput(out.stdout))
- }
- pub fn run(&self) -> Result<String> {
- Ok(self.run_internal(|_cmd| {})?.as_str()?.to_owned())
- }
- pub fn run_json<T: DeserializeOwned>(&self) -> Result<T> {
- Ok(serde_json::from_slice(
- &self
- .run_internal(|cmd| {
- cmd.arg("--json");
- })?
- .0,
- )?)
- }
- pub fn run_raw(&self) -> Result<String> {
- Ok(self
- .run_internal(|cmd| {
- cmd.arg("--raw");
- })?
- .as_str()?
- .to_owned())
- }
-}