git.delta.rocks / jrsonnet / refs/commits / 1470de8a447c

difftreelog

source

crates/fleet-base/src/opts.rs6.4 KiBsourcehistory
1use std::{2	collections::BTreeMap,3	env::current_dir,4	ffi::OsString,5	str::FromStr,6	sync::{Arc, Mutex},7};89use anyhow::{bail, Context, Result};10use nix_eval::{nix_go, util::assert_warn, NixSessionPool, Value};11use nom::{12	bytes::complete::take_while1,13	character::complete::char,14	combinator::{map, opt},15	multi::separated_list1,16	sequence::{preceded, separated_pair},17	Parser,18};1920use crate::{21	fleetdata::FleetData,22	host::{Config, ConfigHost, FleetConfigInternals},23};2425#[derive(Clone)]26pub enum HostItem {27	Host {28		name: String,29		attrs: BTreeMap<String, String>,30	},31	Tag {32		name: String,33		attrs: BTreeMap<String, String>,34	},35}36fn host_item_parser(input: &str) -> Result<HostItem, String> {37	fn err_to_string(err: nom::Err<nom::error::Error<&str>>) -> String {38		err.to_string()39	}4041	let (input, is_tag) = map(opt(char('@')), |c| c.is_some())42		.parse_complete(input)43		.map_err(err_to_string)?;44	let (input, name) = map(45		take_while1(|v| v != ',' && v != '?' && v != '@'),46		str::to_owned,47	).parse_complete(input)48	.map_err(err_to_string)?;4950	let kw_item = separated_pair(51		map(take_while1(|v| v != '&' && v != '='), str::to_owned),52		char('='),53		map(take_while1(|v| v != '&'), str::to_owned),54	);55	let kw = map(separated_list1(char('&'), kw_item), |vec| {56		vec.into_iter().collect::<BTreeMap<_, _>>()57	});58	let mut opt_kw = map(opt(preceded(char('?'), kw)), Option::unwrap_or_default);5960	let (input, attrs) = opt_kw.parse_complete(input).map_err(err_to_string)?;6162	if !input.is_empty() {63		return Err(format!("unexpected trailing input: {input:?}"));64	}65	Ok(if is_tag {66		HostItem::Tag { name, attrs }67	} else {68		HostItem::Host { name, attrs }69	})70}7172// TODO: Rename to HostSelector73#[derive(clap::Parser, Clone)]74pub struct FleetOpts {75	/// All hosts except those would be skipped76	#[clap(long, number_of_values = 1, value_parser = host_item_parser)]77	pub only: Vec<HostItem>,7879	/// Hosts to skip80	#[clap(long, number_of_values = 1)]81	pub skip: Vec<String>,8283	/// Host, which should be threaten as current machine84	// TODO: Replace with connectivity refactor85	#[clap(long, default_value_t = hostname::get().expect("unknown hostname").to_str().expect("hostname is not utf-8").to_owned())]86	pub localhost: String,8788	/// Override detected system for host, to perform builds via89	/// binfmt-declared qemu instead of trying to crosscompile90	#[clap(long, default_value = env!("NIX_SYSTEM"))]91	pub local_system: String,9293	/// By default fleet continues on single derivation build failure94	/// this flag makes command fail immediately95	///96	/// Opposite of Nix's --keep-going97	#[clap(long)]98	pub fail_fast: bool,99}100101impl FleetOpts {102	pub async fn filter_skipped(103		&self,104		hosts: impl IntoIterator<Item = ConfigHost>,105	) -> Result<Vec<ConfigHost>> {106		let mut out = Vec::new();107		for host in hosts {108			if self.should_skip(&host).await? {109				continue;110			}111			out.push(host);112		}113		Ok(out)114	}115	pub async fn should_skip(&self, host: &ConfigHost) -> Result<bool> {116		if self.skip.iter().any(|h| h as &str == host.name) {117			return Ok(true);118		}119		if self.only.is_empty() {120			return Ok(false);121		}122		let mut have_group_matches = false;123		for item in self.only.iter() {124			match item {125				HostItem::Host { name, .. } if *name == host.name => {126					return Ok(false);127				}128				HostItem::Tag { .. } => {129					have_group_matches = true;130				}131				_ => {}132			}133		}134		if have_group_matches {135			let host_tags = host.tags().await?;136			for item in self.only.iter() {137				match item {138					HostItem::Tag { name, .. } if host_tags.contains(name) => {139						return Ok(false);140					}141					_ => {}142				}143			}144		}145		Ok(true)146	}147	pub async fn action_attr<T: FromStr>(&self, host: &ConfigHost, attr: &str) -> Result<Option<T>>148	where149		T::Err: Sync,150		anyhow::Error: From<T::Err>,151	{152		let str = self.action_attr_str(host, attr).await?;153		Ok(str.map(|v| T::from_str(&v)).transpose()?)154	}155	pub async fn action_attr_str(&self, host: &ConfigHost, attr: &str) -> Result<Option<String>> {156		if self.only.is_empty() {157			return Ok(None);158		}159		let mut have_group_matches = false;160		for item in self.only.iter() {161			match item {162				HostItem::Host { name, attrs }163					if *name == host.name && attrs.contains_key(attr) =>164				{165					return Ok(attrs.get(attr).cloned());166				}167				HostItem::Tag { attrs, .. } if attrs.contains_key(attr) => {168					have_group_matches = true;169				}170				_ => {}171			}172		}173		if have_group_matches {174			let host_tags = host.tags().await?;175			for item in self.only.iter() {176				match item {177					HostItem::Tag { name, attrs }178						if host_tags.contains(name) && attrs.contains_key(attr) =>179					{180						return Ok(attrs.get(attr).cloned());181					}182					_ => {}183				}184			}185		}186		Ok(None)187	}188	pub fn is_local(&self, host: &str) -> bool {189		self.localhost == host190	}191192	// TODO: Config should be detached from opts.193	pub async fn build(&self, nix_args: Vec<OsString>, assert: bool) -> Result<Config> {194		let cwd = current_dir()?;195		let mut directory = cwd.clone();196		let mut fleet_data_path = directory.join("fleet.nix");197		while !fleet_data_path.is_file() {198			// fleet.nix199			fleet_data_path.pop();200			if !directory.pop() || !fleet_data_path.pop() {201				bail!(202					"fleet.nix not found at {} or any of the parent directories",203					cwd.display()204				);205			}206			fleet_data_path.push("fleet.nix");207		}208		let bytes =209			std::fs::read_to_string(&fleet_data_path).context("reading fleet state (fleet.nix)")?;210		let data: Mutex<FleetData> = nixlike::parse_str(&bytes)?;211212		let pool = NixSessionPool::new(213			directory.as_os_str().to_owned(),214			nix_args.clone(),215			self.local_system.clone(),216			self.fail_fast,217		)218		.await?;219		let nix_session = pool.get().await?;220221		let builtins_field = Value::binding(nix_session.clone(), "builtins").await?;222223		let fleet_root = Value::binding(nix_session.clone(), "fleetConfigurations").await?;224		let fleet_field = nix_go!(fleet_root.default({ data }));225226		let config_field = nix_go!(fleet_field.config);227228		if assert {229			assert_warn("fleet config evaluation", &config_field).await?;230		}231232		let import = nix_go!(builtins_field.import);233		let overlays = nix_go!(config_field.nixpkgs.overlays);234		let nixpkgs = nix_go!(config_field.nixpkgs.buildUsing);235		let nixpkgs_imported = nix_go!(nixpkgs | import);236237		let default_pkgs = nix_go!(nixpkgs_imported(Obj {238			overlays,239			system: self.local_system.clone(),240		}));241242		Ok(Config(Arc::new(FleetConfigInternals {243			nix_session,244			directory,245			data,246			local_system: self.local_system.clone(),247			nix_args,248			config_field,249			default_pkgs,250			nixpkgs,251			localhost: self.localhost.to_owned(),252		})))253	}254}