git.delta.rocks / jrsonnet / refs/commits / a412d4202830

difftreelog

feat fleetdata

Yaroslav Bolyukin2021-09-18parent: #cd4874a.patch.diff
in: trunk

9 files changed

modifiedsrc/cmds/build_systems.rsdiffbeforeafterboth
--- a/src/cmds/build_systems.rs
+++ b/src/cmds/build_systems.rs
@@ -1,20 +1,13 @@
 use std::process::Command;
 
-use crate::{
-	command::CommandExt,
-	db::{secret::SecretDb, Db, DbData},
-	host::FleetOpts,
-	nix::SYSTEMS_ATTRIBUTE,
-};
+use crate::{command::CommandExt, host::Config, nix::SYSTEMS_ATTRIBUTE};
 use anyhow::Result;
 use clap::Clap;
-use log::{info, warn};
+use log::info;
 
 #[derive(Clap)]
 #[clap(group = clap::ArgGroup::new("target"))]
 pub struct BuildSystems {
-	#[clap(flatten)]
-	fleet_opts: FleetOpts,
 	/// --builders arg for nix
 	#[clap(long)]
 	builders: Option<String>,
@@ -53,18 +46,18 @@
 }
 
 impl BuildSystems {
-	pub fn run(self) -> Result<()> {
-		let fleet = self.fleet_opts.build()?;
-		let db = Db::new(".fleet")?;
-		let hosts = fleet.list_hosts()?;
-		let data = SecretDb::open(&db)?.generate_nix_data()?;
+	pub fn run(self, config: &Config) -> Result<()> {
+		println!("Build");
+		// let db = Db::new(".fleet")?;
+		let hosts = config.list_hosts()?;
+		dbg!(&hosts);
+		// let data = SecretDb::open(&db)?.generate_nix_data()?;
 
 		for host in hosts.iter() {
-			if host.skip() {
-				warn!("Skipping host {}", host.hostname);
+			if config.should_skip(host) {
 				continue;
 			}
-			info!("Building host {}", host.hostname);
+			info!("Building host {}", host);
 			let built = {
 				let dir = tempfile::tempdir()?;
 				dir.path().to_owned()
@@ -82,9 +75,9 @@
 				.arg(&built)
 				.arg(format!(
 					"{}.{}.config.system.build.toplevel",
-					SYSTEMS_ATTRIBUTE, host.hostname,
-				))
-				.env("SECRET_DATA", data.clone());
+					SYSTEMS_ATTRIBUTE, host,
+				));
+			// .env("SECRET_DATA", data.clone());
 
 			if let Some(builders) = &self.builders {
 				println!("Using builders: {}", builders);
@@ -101,11 +94,11 @@
 			nix_build.inherit_stdio().run()?;
 			let built = std::fs::canonicalize(built)?;
 			info!("Built closure: {:?}", built);
-			if !host.is_local() {
+			if !config.is_local(host) {
 				info!("Uploading system closure");
 				Command::new("nix")
 					.args(&["copy", "--to"])
-					.arg(format!("ssh://root@{}", host.hostname))
+					.arg(format!("ssh://root@{}", host))
 					.arg(&built)
 					.inherit_stdio()
 					.run()?;
@@ -113,18 +106,20 @@
 			if let Some(subcommand) = &self.subcommand {
 				if subcommand.should_switch_profile() {
 					info!("Switching generation");
-					host.command_on("nix-env", true)
+					dbg!(&mut config
+						.command_on(host, "nix-env", true)
 						.args(&["-p", "/nix/var/nix/profiles/system", "--set"])
 						.arg(&built)
-						.inherit_stdio()
-						.run()?;
+						.inherit_stdio())
+					.run()?;
 				}
 				info!("Executing activation script");
 				let mut switch_script = built.clone();
 				switch_script.push("bin");
 				switch_script.push("switch-to-configuration");
 				info!("{:?}", switch_script);
-				host.command_on(switch_script, true)
+				config
+					.command_on(host, switch_script, true)
 					.arg(subcommand.name())
 					.inherit_stdio()
 					.run()?;
modifiedsrc/cmds/generate_secrets.rsdiffbeforeafterboth
--- a/src/cmds/generate_secrets.rs
+++ b/src/cmds/generate_secrets.rs
@@ -4,13 +4,19 @@
 use clap::Clap;
 use log::info;
 
-use crate::db::{
-	secret::{list_secrets, SecretDb},
-	Db, DbData,
+use crate::{
+	db::{
+		secret::{list_secrets, SecretDb},
+		Db, DbData,
+	},
+	host::FleetOpts,
 };
 
 #[derive(Clap)]
 pub struct GenerateSecrets {
+	#[clap(flatten)]
+	fleet_opts: FleetOpts,
+
 	/// If set - remove orphaned secrets
 	#[clap(long)]
 	cleanup: bool,
@@ -23,8 +29,8 @@
 
 		let defined_secrets = list_secrets()?;
 		for (secret, data) in defined_secrets.iter() {
-			// let keys = KeyDb::open(&db)?;
-			// secrets.ensure_generated(&keys, &secret, &data)?;
+			//let keys = KeyDb::open(&db)?;
+			secrets.ensure_generated(&self.fleet_opts, secret, data)?;
 		}
 		let key_names = defined_secrets
 			.keys()
modifiedsrc/cmds/mod.rsdiffbeforeafterboth
--- a/src/cmds/mod.rs
+++ b/src/cmds/mod.rs
@@ -1,3 +1,4 @@
 pub mod build_systems;
-pub mod fetch_keys;
+// pub mod fetch_keys;
 pub mod generate_secrets;
+pub mod secrets;
modifiedsrc/command.rsdiffbeforeafterboth
--- a/src/command.rs
+++ b/src/command.rs
@@ -23,14 +23,14 @@
 	fn run(&mut self) -> Result<()> {
 		let out = self.output()?;
 		if !out.status.success() {
-			anyhow::bail!("command failed");
+			anyhow::bail!("command failed with status {}", out.status);
 		}
 		Ok(())
 	}
 
 	fn run_json<T: DeserializeOwned>(&mut self) -> Result<T> {
 		let str = self.run_string()?;
-		Ok(serde_json::from_str(&str).with_context(|| format!("{:?}", str))?)
+		serde_json::from_str(&str).with_context(|| format!("{:?}", str))
 	}
 
 	fn run_string(&mut self) -> Result<String> {
addedsrc/fleetdata.rsdiffbeforeafterboth
--- /dev/null
+++ b/src/fleetdata.rs
@@ -0,0 +1,16 @@
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+
+#[derive(Serialize, Deserialize, Default)]
+pub struct HostData {
+	#[serde(default)]
+	pub encryption_key: String,
+	#[serde(default)]
+	pub encrypted_secrets: BTreeMap<String, String>,
+}
+
+#[derive(Serialize, Deserialize)]
+pub struct FleetData {
+	#[serde(default)]
+	pub hosts: BTreeMap<String, HostData>,
+}
modifiedsrc/host.rsdiffbeforeafterboth
--- a/src/host.rs
+++ b/src/host.rs
@@ -1,4 +1,5 @@
 use std::{
+	cell::{Ref, RefCell, RefMut},
 	env::current_dir,
 	ffi::{OsStr, OsString},
 	ops::Deref,
@@ -10,17 +11,18 @@
 use anyhow::Result;
 use clap::Clap;
 
-use crate::command::CommandExt;
+use crate::{command::CommandExt, fleetdata::FleetData};
 
 pub struct FleetConfigInternals {
 	pub directory: PathBuf,
 	pub opts: FleetOpts,
+	pub data: RefCell<FleetData>,
 }
 
 #[derive(Clone)]
-pub struct FleetConfig(Arc<FleetConfigInternals>);
+pub struct Config(Arc<FleetConfigInternals>);
 
-impl Deref for FleetConfig {
+impl Deref for Config {
 	type Target = FleetConfigInternals;
 
 	fn deref(&self) -> &Self::Target {
@@ -28,70 +30,71 @@
 	}
 }
 
-impl FleetConfig {
-	pub fn data_dir(&self) -> PathBuf {
-		let mut out = self.directory.clone();
-		out.push(".fleet");
-		out
+impl Config {
+	pub fn should_skip(&self, host: &str) -> bool {
+		if !self.opts.skip.is_empty() {
+			self.opts.skip.iter().any(|h| h as &str == host)
+		} else if !self.opts.only.is_empty() {
+			!self.opts.only.iter().any(|h| h as &str == host)
+		} else {
+			false
+		}
+	}
+	pub fn is_local(&self, host: &str) -> bool {
+		self.opts.localhost.as_ref().map(|s| s as &str) == Some(host)
+	}
+
+	pub fn command_on(&self, host: &str, program: impl AsRef<OsStr>, sudo: bool) -> Command {
+		if self.is_local(host) {
+			if sudo {
+				let mut cmd = Command::new("sudo");
+				cmd.arg(program);
+				cmd
+			} else {
+				Command::new(program)
+			}
+		} else {
+			let mut cmd = Command::new("ssh");
+			cmd.arg(host).arg("--");
+			if sudo {
+				cmd.arg("sudo");
+			}
+			cmd.arg(program);
+			cmd
+		}
 	}
 
 	pub fn full_attr_name(&self, attr_name: &str) -> OsString {
 		let mut str = self.directory.as_os_str().to_owned();
 		str.push("#");
 		str.push(attr_name);
+
+		println!("{:?}", str);
 		str
 	}
 
-	pub fn list_host_names(&self) -> Result<Vec<String>> {
-		Ok(Command::new("nix")
+	pub fn list_hosts(&self) -> Result<Vec<String>> {
+		Command::new("nix")
 			.arg("eval")
 			.arg(self.full_attr_name("fleetConfigurations.default.configuredHosts"))
-			.args(&["--apply", "builtins.attrNames", "--json"])
+			.args(&["--apply", "builtins.attrNames", "--json", "--show-trace"])
 			.inherit_stdio()
-			.run_json()?)
+			.run_json()
 	}
 
-	pub fn list_hosts(&self) -> Result<Vec<Host>> {
-		Ok(self
-			.list_host_names()?
-			.into_iter()
-			.map(|hostname| Host {
-				fleet_config: self.clone(),
-				hostname,
-			})
-			.collect())
+	pub fn data(&self) -> Ref<FleetData> {
+		self.data.borrow()
+	}
+	pub fn data_mut(&self) -> RefMut<FleetData> {
+		self.data.borrow_mut()
 	}
-}
 
-pub struct Host {
-	pub fleet_config: FleetConfig,
-
-	pub hostname: String,
-}
-
-impl Host {
-	pub fn skip(&self) -> bool {
-		self.fleet_config.0.opts.should_skip(&self.hostname)
-	}
-	pub fn is_local(&self) -> bool {
-		self.fleet_config.0.opts.is_local(&self.hostname)
-	}
-	pub fn command_on(&self, cmd: impl AsRef<OsStr>, sudo: bool) -> Command {
-		if !self.is_local() {
-			let mut out = Command::new("ssh");
-			out.arg(&self.hostname).arg("--");
-			if sudo {
-				out.arg("sudo");
-			}
-			out.arg(cmd);
-			out
-		} else if sudo {
-			let mut out = Command::new("sudo");
-			out.arg(cmd);
-			out
-		} else {
-			Command::new(cmd)
-		}
+	pub fn save(&self) -> Result<()> {
+		let mut fleet_data_path = self.directory.clone();
+		fleet_data_path.push("fleet.nix");
+		let data = nixlike::serialize(&self.data() as &FleetData)?;
+		std::fs::write(fleet_data_path, data)?;
+		Ok(())
 	}
 }
 
@@ -112,27 +115,22 @@
 }
 
 impl FleetOpts {
-	pub fn should_skip(&self, host: &str) -> bool {
-		if self.skip.len() > 0 {
-			self.skip.iter().find(|h| h as &str == host).is_some()
-		} else if self.only.len() > 0 {
-			self.only.iter().find(|h| h as &str == host).is_none()
-		} else {
-			false
-		}
-	}
-	pub fn is_local(&self, host: &str) -> bool {
-		self.localhost.as_ref().map(|s| &s as &str) == Some(host)
-	}
-	pub fn build(mut self) -> Result<FleetConfig> {
+	pub fn build(mut self) -> Result<Config> {
 		if self.localhost.is_none() {
 			self.localhost
 				.replace(hostname::get().unwrap().to_str().unwrap().to_owned());
 		}
 		let directory = current_dir()?;
-		Ok(FleetConfig(Arc::new(FleetConfigInternals {
+
+		let mut fleet_data_path = directory.clone();
+		fleet_data_path.push("fleet.nix");
+		let bytes = std::fs::read_to_string(fleet_data_path)?;
+		let data = nixlike::parse_str(&bytes)?;
+
+		Ok(Config(Arc::new(FleetConfigInternals {
 			opts: self,
 			directory,
+			data,
 		})))
 	}
 }
modifiedsrc/keys.rsdiffbeforeafterboth
1use std::str::FromStr;
2
1use crate::{3use crate::{command::CommandExt, host::Config};
2 command::CommandExt,
3 host::{FleetConfig, Host},
4};
5use anyhow::Result;4use anyhow::{anyhow, Result};
6use log::warn;5use log::warn;
7use std::{
8 fs::{create_dir_all, metadata, read, read_dir, write},
9 path::PathBuf,
10};
11
12impl FleetConfig {
13 fn host_keys_dir(&self) -> Result<PathBuf> {
14 let mut out = self.data_dir().clone();
15 out.push("host_keys");
16 create_dir_all(&out)?;
17 Ok(out)
18 }
19
20 fn host_key_file(&self, host: &str) -> Result<PathBuf> {
21 let mut dir = self.host_keys_dir()?;
22 dir.push(format!("{}.asc", host));
23 Ok(dir)
24 }
25
26 pub fn list_orphaned_keys(&self) -> Result<Vec<(String, PathBuf)>> {
27 let mut out = Vec::new();
28 let host_names = self.list_host_names()?;
29 for file in read_dir(&self.host_keys_dir()?)? {
30 let file = file?;
31 anyhow::ensure!(
32 file.file_type()?.is_file(),
33 "host_keys dir should contain only files"
34 );
35 let name = file.file_name();
36 let name = name.to_str().unwrap();
37 if let Some(hostname) = name.strip_suffix(".asc") {
38 if !host_names.contains(&hostname.to_owned()) {
39 out.push((hostname.to_owned(), file.path()))
40 }
41 } else {
42 out.push(("<unknown>".to_owned(), file.path()))
43 }
44 }
45
46 Ok(out)
47 }
48}
496
50impl Host {7impl Config {
51 pub fn key(&self) -> anyhow::Result<String> {8 pub fn cached_key(&self, host: &str) -> Option<String> {
9 let data = self.data();
10 let key = data.hosts.get(host).map(|h| &h.encryption_key);
11 if let Some(key) = key {
12 if key.is_empty() {
13 return None;
14 }
15 }
16 key.cloned()
17 }
18 pub fn update_key(&self, host: &str, key: String) {
19 let mut data = self.data_mut();
52 let key_path = self.fleet_config.host_key_file(&self.hostname)?;20 let host = data.hosts.entry(host.to_string()).or_default();
21 host.encryption_key = key.trim().to_string();
22 }
53 if metadata(&key_path).map(|m| m.is_file()).unwrap_or(false) {23 pub fn update_secret(&self, host: &str, name: &str, value: &[u8]) {
24 let mut data = self.data_mut();
25 let host = data.hosts.entry(host.to_string()).or_default();
26 host.encrypted_secrets.insert(
27 name.to_string(),
28 format!("[ENCRYPTED:{}]", base64::encode(value)),
29 );
30 }
31
32 pub fn key(&self, host: &str) -> anyhow::Result<String> {
33 if let Some(key) = self.cached_key(host) {
54 Ok(String::from_utf8(read(key_path)?)?)34 Ok(key)
55 } else {35 } else {
56 warn!("Loading key for {}", self.hostname);36 warn!("Loading key for {}", host);
57 let key = self37 let key = self
58 .command_on("cat", false)38 .command_on("host", "cat", false)
59 .arg("/etc/ssh/ssh_host_ed25519_key.pub")39 .arg("/etc/ssh/ssh_host_ed25519_key.pub")
60 .run_string()?;40 .run_string()?;
61 write(key_path, key.clone())?;41 self.update_key(host, key.clone());
62 Ok(key)42 Ok(key)
63 }43 }
64 }44 }
45 pub fn recipient(&self, host: &str) -> anyhow::Result<age::ssh::Recipient> {
46 let key = self.key(host)?;
47 age::ssh::Recipient::from_str(&key).map_err(|e| anyhow!("parse recipient error: {:?}", e))
48 }
49
50 pub fn orphaned_data(&self) -> Result<Vec<String>> {
51 let mut out = Vec::new();
52 let host_names = self.list_hosts()?;
53 for hostname in self
54 .data()
55 .hosts
56 .iter()
57 .filter(|(_, host)| !host.encryption_key.is_empty())
58 .map(|(n, _)| n)
59 {
60 if !host_names.contains(&hostname.to_owned()) {
61 out.push(hostname.to_owned())
62 }
63 }
64
65 Ok(out)
66 }
65}67}
6668
modifiedsrc/main.rsdiffbeforeafterboth
--- a/src/main.rs
+++ b/src/main.rs
@@ -8,10 +8,14 @@
 pub mod db;
 pub mod nix;
 
+mod fleetdata;
+
 use anyhow::Result;
 use clap::Clap;
-use cmds::{build_systems::BuildSystems, fetch_keys::FetchKeys, generate_secrets::GenerateSecrets};
 
+use cmds::{build_systems::BuildSystems, generate_secrets::GenerateSecrets, secrets::Secrets};
+use host::{Config, FleetOpts};
+
 #[derive(Clap)]
 #[clap(version = "1.0", author = "CertainLach <iam@lach.pw>")]
 enum Opts {
@@ -23,16 +27,38 @@
 	Secrets(Secrets),
 }
 
+#[derive(Clap)]
+struct RootOpts {
+	#[clap(flatten)]
+	fleet_opts: FleetOpts,
+	#[clap(subcommand)]
+	command: Opts,
+}
+
+fn run_command(config: &Config, command: Opts) -> Result<()> {
+	match command {
+		Opts::BuildSystems(c) => c.run(config)?,
+		Opts::GenerateSecrets(c) => c.run()?,
+		Opts::Secrets(s) => s.run(config)?,
+	};
+	Ok(())
+}
+
 fn main() -> Result<()> {
 	env_logger::Builder::new()
 		.filter_level(log::LevelFilter::Info)
 		.init();
-	let opts = Opts::parse();
+	let opts = RootOpts::parse();
+	let config = opts.fleet_opts.build()?;
 
-	match opts {
-		Opts::FetchKeys(c) => c.run()?,
-		Opts::BuildSystems(c) => c.run()?,
-		Opts::GenerateSecrets(c) => c.run()?,
-	};
-	Ok(())
+	match run_command(&config, opts.command) {
+		Ok(()) => {
+			config.save()?;
+			Ok(())
+		}
+		Err(e) => {
+			let _ = config.save();
+			Err(e)
+		}
+	}
 }
addedsrc/nixlike.rsdiffbeforeafterboth

no changes