use std::collections::HashMap; use std::convert::TryInto; use std::ffi::OsStr; use std::path::PathBuf; use std::process::Stdio; use std::time::Duration; use async_trait::async_trait; use shell_escape::unix::escape; use tokio::process::Command; use tokio::time::sleep; use super::{CopyDirection, CopyOptions, Host, RebootOptions, key_uploader}; use crate::error::{ColmenaError, ColmenaResult}; use crate::job::JobHandle; use crate::nix::{ CURRENT_PROFILE, Goal, Key, NixCommand, NixFlags, Profile, SYSTEM_PROFILE, StorePath, }; use crate::util::{CommandExecution, CommandExt}; /// A remote machine connected over SSH. #[derive(Debug)] pub struct Ssh { /// The username to use to connect. user: Option, /// The hostname or IP address to connect to. host: String, /// The port to connect to. port: Option, /// Local path to a ssh_config file. ssh_config: Option, /// Command to elevate privileges with. privilege_escalation_command: Vec, /// extra SSH options extra_ssh_options: Vec, /// Whether to use the experimental `nix copy` command. use_nix3_copy: bool, /// Flags to pass to Nix invocations, local and remote. nix_flags: NixFlags, job: Option, } /// An opaque boot ID. #[derive(Debug, Clone, PartialEq, Eq)] struct BootId(String); #[async_trait] impl Host for Ssh { async fn copy_closure( &mut self, closure: &StorePath, direction: CopyDirection, options: CopyOptions, ) -> ColmenaResult<()> { let command = self.nix_copy_closure(closure, direction, options); self.run_command(command).await } async fn realize_remote(&mut self, derivation: &StorePath) -> ColmenaResult> { let argv = derivation.realise_command(&self.nix_flags).into_argv(); let command = self.ssh_argv(argv); let mut execution = CommandExecution::new(command); execution.set_job(self.job.clone()); let paths = execution.capture_output().await?; paths.lines().map(|p| p.to_string().try_into()).collect() } fn set_job(&mut self, job: Option) { self.job = job; } async fn upload_keys( &mut self, keys: &HashMap, require_ownership: bool, ) -> ColmenaResult<()> { for (name, key) in keys { self.upload_key(name, key, require_ownership).await?; } Ok(()) } async fn activate(&mut self, profile: &Profile, goal: Goal) -> ColmenaResult<()> { if !goal.requires_activation() { return Err(ColmenaError::Unsupported); } if goal.should_switch_profile() { let argv = profile.switch_profile_command(&self.nix_flags).into_argv(); let set_profile = self.ssh_argv(argv); self.run_command(set_profile).await?; } let activation_command = profile.activation_command(goal).unwrap(); let command = self.ssh(&activation_command); self.run_command(command).await } async fn get_current_system_profile(&mut self) -> ColmenaResult { let paths = self .ssh(&["readlink", "-e", CURRENT_PROFILE]) .capture_output() .await?; let path = paths .lines() .next() .ok_or(ColmenaError::FailedToGetCurrentProfile)? .to_string() .try_into()?; Ok(Profile::from_store_path_unchecked(path)) } async fn get_main_system_profile(&mut self) -> ColmenaResult { let command = format!( "\"readlink -e {} || readlink -e {}\"", SYSTEM_PROFILE, CURRENT_PROFILE ); let paths = self .ssh(&["sh", "-c", command.as_str()]) .capture_output() .await?; let path = paths .lines() .next() .ok_or(ColmenaError::FailedToGetCurrentProfile)? .to_string() .try_into()?; Ok(Profile::from_store_path_unchecked(path)) } async fn run_command(&mut self, command: &[&str]) -> ColmenaResult<()> { let command = self.ssh(command); self.run_command(command).await } async fn reboot(&mut self, options: RebootOptions) -> ColmenaResult<()> { if !options.wait_for_boot { return self.initate_reboot().await; } let old_id = self.get_boot_id().await?; self.initate_reboot().await?; if let Some(job) = &self.job { job.message("Waiting for reboot".to_string())?; } // Wait for node to come back up loop { // Ignore errors while waiting if let Ok(new_id) = self.get_boot_id().await && new_id != old_id { break; } sleep(Duration::from_secs(2)).await; } // Ensure node has correct system profile if let Some(new_profile) = options.new_profile { let profile = self.get_current_system_profile().await?; if new_profile != profile { return Err(ColmenaError::ActiveProfileUnexpected { profile }); } } Ok(()) } } impl Ssh { pub fn new(user: Option, host: String, nix_flags: NixFlags) -> Self { Self { user, host, port: None, ssh_config: None, privilege_escalation_command: Vec::new(), extra_ssh_options: Vec::new(), use_nix3_copy: false, nix_flags, job: None, } } pub fn set_port(&mut self, port: u16) { self.port = Some(port); } pub fn set_ssh_config(&mut self, ssh_config: PathBuf) { self.ssh_config = Some(ssh_config); } pub fn set_privilege_escalation_command(&mut self, command: Vec) { self.privilege_escalation_command = command; } pub fn set_extra_ssh_options(&mut self, options: Vec) { self.extra_ssh_options = options; } pub fn set_use_nix3_copy(&mut self, enable: bool) { self.use_nix3_copy = enable; } pub fn upcast(self) -> Box { Box::new(self) } /// Returns a Tokio Command to run a generated command on the host. /// /// ssh(1) concatenates its arguments with spaces and lets the remote /// shell re-split them, so each argument is escaped first. This /// matters for Nix flag values that may contain spaces (e.g., /// `--option substituters "https://a https://b"`). fn ssh_argv(&self, argv: Vec) -> Command { let escaped: Vec = argv .into_iter() .map(|arg| escape(arg.into()).into_owned()) .collect(); self.ssh(&escaped) } /// Returns a Tokio Command to run an arbitrary command on the host. pub fn ssh>(&self, command: &[S]) -> Command { let options = self.ssh_options(); let options_str = options.join(" "); let privilege_escalation_command = if self.user.as_deref() != Some("root") { self.privilege_escalation_command.as_slice() } else { &[] }; let mut cmd = Command::new("ssh"); cmd.arg(self.ssh_target()) .args(&options) .arg("--") .args(privilege_escalation_command) .args(command) .env("NIX_SSHOPTS", options_str); cmd } async fn run_command(&mut self, command: Command) -> ColmenaResult<()> { let mut execution = CommandExecution::new(command); execution.set_job(self.job.clone()); execution.run().await } fn ssh_target(&self) -> String { match &self.user { Some(n) => format!("{}@{}", n, self.host), None => self.host.clone(), } } fn nix_copy_closure( &self, path: &StorePath, direction: CopyDirection, options: CopyOptions, ) -> Command { let ssh_options = self.ssh_options(); let ssh_options_str = ssh_options.join(" "); let mut command = if self.use_nix3_copy { // experimental `nix copy` command with ssh-ng:// let mut command = NixCommand::nix(self.nix_flags.clone()).args(["copy", "--no-check-sigs"]); if options.use_substitutes { command = command.args([ "--substitute-on-destination", // needed due to UX bug in ssh-ng:// "--builders-use-substitutes", ]); } if let Some("drv") = path.extension().and_then(OsStr::to_str) { command = command.arg("--derivation"); } command = match direction { CopyDirection::ToRemote => command.arg("--to"), CopyDirection::FromRemote => command.arg("--from"), }; let mut store_uri = format!("ssh-ng://{}", self.ssh_target()); if options.gzip { store_uri += "?compress=true"; } command.arg(store_uri).arg(path.as_path()).build() } else { // nix-copy-closure (ssh://) let mut command = NixCommand::nix_copy_closure(self.nix_flags.clone()); command = match direction { CopyDirection::ToRemote => command.arg("--to"), CopyDirection::FromRemote => command.arg("--from"), }; // FIXME: Host-agnostic abstraction if options.include_outputs { command = command.arg("--include-outputs"); } if options.use_substitutes { command = command.arg("--use-substitutes"); } if options.gzip { command = command.arg("--gzip"); } command.arg(self.ssh_target()).arg(path.as_path()).build() }; command.env("NIX_SSHOPTS", ssh_options_str); command } fn ssh_options(&self) -> Vec { // TODO: Allow configuration of SSH parameters // NOTE: extra_ssh_options needs to come first so that // deployment.sshOptions can override our settings. // // From ssh_config(5): // > Unless noted otherwise, for each parameter, the first obtained // > value will be used. let mut options: Vec = self .extra_ssh_options .iter() .cloned() .chain( [ "-o", "StrictHostKeyChecking=accept-new", "-o", "BatchMode=yes", "-T", ] .map(String::from), ) .collect(); if let Some(port) = self.port { options.push("-p".to_string()); options.push(port.to_string()); } if let Some(ssh_config) = self.ssh_config.as_ref() { options.push("-F".to_string()); options.push(ssh_config.to_str().unwrap().to_string()); } options } /// Uploads a single key. async fn upload_key( &mut self, name: &str, key: &Key, require_ownership: bool, ) -> ColmenaResult<()> { if let Some(job) = &self.job { job.message(format!("Uploading key {}", name))?; } let path = key.path(); let key_script = key_uploader::generate_script(key, path, require_ownership); let mut command = self.ssh(&["sh", "-c", key_script.as_ref()]); command.stdin(Stdio::piped()); command.stderr(Stdio::piped()); command.stdout(Stdio::piped()); let uploader = command.spawn()?; key_uploader::feed_uploader(uploader, key, self.job.clone()).await } /// Returns the current Boot ID. async fn get_boot_id(&mut self) -> ColmenaResult { let boot_id = self .ssh(&["cat", "/proc/sys/kernel/random/boot_id"]) .capture_output() .await?; Ok(BootId(boot_id)) } /// Initiates reboot. async fn initate_reboot(&mut self) -> ColmenaResult<()> { match self.run_command(self.ssh(&["reboot"])).await { Ok(()) => Ok(()), Err(e) => { if let ColmenaError::ChildFailure { exit_code: 255, .. } = e { // Assume it's "Connection closed by remote host" Ok(()) } else { Err(e) } } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_ssh_argv_escapes_for_remote_shell() { let mut flags = NixFlags::default(); flags.add_option( "substituters".to_string(), "https://a https://b".to_string(), ); let host = Ssh::new(Some("root".to_string()), "example.com".to_string(), flags); let argv = NixCommand::nix_store(host.nix_flags.clone()) .args(["--no-gc-warning", "--realise"]) .arg("/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-x") .into_argv(); let command = host.ssh_argv(argv); let args: Vec = command .as_std() .get_args() .map(|arg| arg.to_string_lossy().into_owned()) .collect(); assert!(args.contains(&"'https://a https://b'".to_string())); assert!(args.contains(&"--realise".to_string())); assert!(args.contains(&"nix-store".to_string())); } #[test] fn test_copy_closure_threads_nix_flags() { let mut flags = NixFlags::default(); flags.add_option("cores".to_string(), "4".to_string()); let mut host = Ssh::new(Some("root".to_string()), "example.com".to_string(), flags); let store_path: StorePath = "/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-x" .to_string() .try_into() .unwrap(); for use_nix3_copy in [false, true] { host.set_use_nix3_copy(use_nix3_copy); let command = host.nix_copy_closure(&store_path, CopyDirection::ToRemote, CopyOptions::default()); let args: Vec = command .as_std() .get_args() .map(|arg| arg.to_string_lossy().into_owned()) .collect(); assert!( args.windows(3).any(|w| w == ["--option", "cores", "4"]), "nix_flags not threaded (use_nix3_copy: {}): {:?}", use_nix3_copy, args ); } } }