Something went wrong. Try again.
forked from zhaofengli/colmena
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192use std::collections::HashMap;use std::convert::TryInto;use std::process::Stdio;
use async_trait::async_trait;use tokio::process::Command;
use super::{CopyDirection, CopyOptions, Host, key_uploader};use crate::error::{ColmenaError, ColmenaResult};use crate::job::JobHandle;use crate::nix::{CURRENT_PROFILE, Goal, Key, NixFlags, Profile, SYSTEM_PROFILE, StorePath};use crate::util::{CommandExecution, CommandExt};
/// The local machine running Colmena.////// It may not be capable of realizing some derivations/// (e.g., building Linux derivations on macOS).#[derive(Debug)]pub struct Local { job: Option<JobHandle>, nix_flags: NixFlags, privilege_escalation_command: Option<Vec<String>>,}
impl Local { pub fn new(nix_flags: NixFlags) -> Self { Self { job: None, nix_flags, privilege_escalation_command: None, } }}
#[async_trait]impl Host for Local { async fn copy_closure( &mut self, _closure: &StorePath, _direction: CopyDirection, _options: CopyOptions, ) -> ColmenaResult<()> { Ok(()) }
async fn realize_remote(&mut self, derivation: &StorePath) -> ColmenaResult<Vec<StorePath>> { let command = derivation.realise_command(&self.nix_flags).build();
let mut execution = CommandExecution::new(command);
execution.set_job(self.job.clone());
execution.run().await?; let (stdout, _) = execution.get_logs();
stdout .unwrap() .lines() .map(|p| p.to_string().try_into()) .collect() }
async fn upload_keys( &mut self, keys: &HashMap<String, Key>, 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(); self.make_privileged_command(&argv).passthrough().await?; }
let command = { let activation_command = profile.activation_command(goal).unwrap(); self.make_privileged_command(&activation_command) };
let mut execution = CommandExecution::new(command);
execution.set_job(self.job.clone());
execution.run().await }
async fn get_current_system_profile(&mut self) -> ColmenaResult<Profile> { let paths = Command::new("readlink") .args(["-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<Profile> { let paths = Command::new("sh") .args([ "-c", &format!( "readlink -e {} || readlink -e {}", SYSTEM_PROFILE, 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)) }
fn set_job(&mut self, job: Option<JobHandle>) { self.job = job; }}
impl Local { #[cfg_attr(not(target_os = "linux"), allow(dead_code))] pub fn set_privilege_escalation_command(&mut self, command: Option<Vec<String>>) { self.privilege_escalation_command = command; }
pub fn upcast(self) -> Box<dyn Host> { Box::new(self) }
/// "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!("Deploying key {}", name))?; }
let path = key.path(); let key_script = format!( "'{}'", key_uploader::generate_script(key, path, require_ownership) );
let mut command = self.make_privileged_command(&["sh", "-c", &key_script]); 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 }
/// Constructs a command with privilege escalation. fn make_privileged_command<S: AsRef<str>>(&self, command: &[S]) -> Command { let mut full_command = Vec::new(); if let Some(esc) = &self.privilege_escalation_command { full_command.extend(esc.iter().map(|s| s.as_str())); } full_command.extend(command.iter().map(|s| s.as_ref()));
let mut result = Command::new(full_command[0]); if full_command.len() > 1 { result.args(&full_command[1..]); }
result }}