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

difftreelog

source

cmds/fleet/src/main.rs5.9 KiBsourcehistory
1#![recursion_limit = "512"]23pub(crate) mod cmds;4// pub(crate) mod command;5pub(crate) mod extra_args;67use std::{ffi::OsString, process::ExitCode};89use anyhow::{bail, Result};10use clap::{CommandFactory, Parser};11use cmds::{12	build_systems::{BuildSystems, Deploy},13	rollback::RollbackSingle,14	complete::Complete,15	info::Info,16	secrets::Secret,17	tf::Tf,18};19use fleet_base::{host::Config, opts::FleetOpts};20use futures::{future::LocalBoxFuture, stream::FuturesUnordered, TryStreamExt};21// use host::Config;22#[cfg(feature = "indicatif")]23use human_repr::HumanCount;24#[cfg(feature = "indicatif")]25use indicatif::{ProgressState, ProgressStyle};26use tracing::{error, info, info_span, Instrument};27#[cfg(feature = "indicatif")]28use tracing_indicatif::IndicatifLayer;29use tracing_subscriber::{prelude::*, EnvFilter};3031#[derive(Parser)]32struct Prefetch {}33impl Prefetch {34	async fn run(&self, config: &Config) -> Result<()> {35		let mut prefetch_dir = config.directory.to_path_buf();36		prefetch_dir.push("prefetch");37		if !prefetch_dir.is_dir() {38			info!("nothing to prefetch: no prefetch directory");39			return Ok(());40		}41		let tasks = <FuturesUnordered<LocalBoxFuture<Result<()>>>>::new();42		for entry in std::fs::read_dir(&prefetch_dir)? {43			tasks.push(Box::pin(async {44				let entry = entry?;45				if !entry.metadata()?.is_file() {46					bail!("only files should exist in prefetch directory");47				}48				let span = info_span!(49					"prefetching",50					name = entry.file_name().to_string_lossy().as_ref()51				);52				let mut path = OsString::new();53				path.push("file://");54				path.push(entry.path());5556				let mut status = config.local_host().cmd("nix").await?;57				status.args(&config.nix_args);58				status.arg("store").arg("prefetch-file").arg(path);59				status.run_nix_string().instrument(span).await?;60				Ok(())61			}));62		}63		tasks.try_collect::<Vec<()>>().await?;64		Ok(())65	}66}6768#[derive(Parser)]69enum Opts {70	/// Build system closures71	BuildSystems(BuildSystems),72	/// Upload and switch system closures73	Deploy(Deploy),74	/// Rollback remote machine by redeploying old generation as the new one75	RollbackSingle(RollbackSingle),76	/// Secret management77	#[clap(subcommand)]78	Secret(Secret),79	/// Upload prefetch directory to the nix store80	Prefetch(Prefetch),81	/// Config parsing82	Info(Info),83	/// Command completions84	#[clap(hide(true))]85	Complete(Complete),86	/// Compile and evaluate terranix configuration87	Tf(Tf),88}8990#[derive(Parser)]91#[clap(version, author)]92struct RootOpts {93	#[clap(flatten)]94	fleet_opts: FleetOpts,95	#[clap(subcommand)]96	command: Opts,97}9899async fn run_command(config: &Config, opts: FleetOpts, command: Opts) -> Result<()> {100	match command {101		Opts::BuildSystems(c) => c.run(config, &opts).await?,102		Opts::Deploy(d) => d.run(config, &opts).await?,103		Opts::RollbackSingle(r) => r.run(config, &opts).await?,104		Opts::Secret(s) => s.run(config, &opts).await?,105		Opts::Info(i) => i.run(config).await?,106		Opts::Prefetch(p) => p.run(config).await?,107		Opts::Tf(t) => t.run(config).await?,108		// TODO: actually parse commands before starting the async runtime109		Opts::Complete(c) => {110			tokio::task::spawn_blocking(move || c.run(RootOpts::command())).await?111		}112	};113	Ok(())114}115116fn setup_logging() {117	#[cfg(feature = "indicatif")]118	let indicatif_layer = {119		use std::time::Duration;120121		IndicatifLayer::new().with_progress_style(122			ProgressStyle::with_template(123				"{color_start}{span_child_prefix} {span_name}{{{span_fields}}}{color_end} {wide_msg} {color_start}{download_progress} {elapsed}{color_end}",124			)125				.unwrap()126				.with_key("download_progress", |state: &ProgressState, writer: &mut dyn std::fmt::Write| {127					let Some(len) = state.len() else {128						return;129					};130					let pos = state.pos();131					if pos > len {132						let _ = write!(writer, "{}", pos.human_count_bare());133					} else {134						let _ = write!(writer, "{} / {}", pos.human_count_bare(), len.human_count_bare());135					}136				})137				.with_key(138					"color_start",139					|state: &ProgressState, writer: &mut dyn std::fmt::Write| {140						let elapsed = state.elapsed();141142						if elapsed > Duration::from_secs(60) {143							// Red144							let _ = write!(writer, "\x1b[{}m", 1 + 30);145						} else if elapsed > Duration::from_secs(30) {146							// Yellow147							let _ = write!(writer, "\x1b[{}m", 3 + 30);148						}149					},150				)151				.with_key(152					"color_end",153					|state: &ProgressState, writer: &mut dyn std::fmt::Write| {154						if state.elapsed() > Duration::from_secs(30) {155							let _ = write!(writer, "\x1b[0m");156						}157					},158				),159		)160	};161162	let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));163164	let reg = tracing_subscriber::registry().with({165		let sub = tracing_subscriber::fmt::layer()166			.without_time()167			.with_target(false);168		#[cfg(feature = "indicatif")]169		let sub = sub.with_writer(indicatif_layer.get_stderr_writer());170		sub.with_filter(filter) // .without,171	});172	// #[cfg(feature = "indicatif")]173	#[cfg(feature = "indicatif")]174	let reg = reg.with(indicatif_layer);175	reg.init();176}177178fn main() -> ExitCode {179	let opts = RootOpts::parse();180	if let Opts::Complete(c) = &opts.command {181		c.run(RootOpts::command());182		return ExitCode::SUCCESS;183	}184185	setup_logging();186	async_main(opts)187}188189#[tokio::main]190async fn async_main(opts: RootOpts) -> ExitCode {191	if let Err(e) = main_real(opts).await {192		error!("{e:#}");193		return ExitCode::FAILURE;194	}195	ExitCode::SUCCESS196}197198async fn main_real(opts: RootOpts) -> Result<()> {199	nix_eval::init_tokio();200201	let nix_args = std::env::var_os("NIX_ARGS")202		.map(|a| extra_args::parse_os(&a))203		.transpose()?204		.unwrap_or_default();205	let config = opts206		.fleet_opts207		.build(208			nix_args,209			matches!(opts.command, Opts::Deploy(_) | Opts::BuildSystems(_)),210		)211		.await?;212213	match run_command(&config, opts.fleet_opts, opts.command).await {214		Ok(()) => {215			config.save()?;216			Ok(())217		}218		Err(e) => {219			let _ = config.save();220			Err(e)221		}222	}223}224225#[cfg(test)]226mod tests {227	use super::*;228229	#[test]230	fn verify_command() {231		use clap::CommandFactory;232		RootOpts::command().debug_assert();233	}234}