use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use arc_swap::ArcSwap;
use async_lock::OnceCell;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::tool_runtime::PreparedTools;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SshServer {
pub name: String,
pub target: String,
}
impl SshServer {
#[must_use]
pub fn id(&self) -> &str {
&self.name
}
}
#[derive(Debug, thiserror::Error)]
pub enum SshServerError {
#[error("an SSH server needs a non-empty name and target")]
Blank,
#[error("an SSH server named `{0}` is already configured")]
Duplicate(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SshPlatform {
pub os: String,
pub arch: String,
}
#[derive(Debug, thiserror::Error)]
pub enum SshProbeError {
#[error("could not start ssh: {0}")]
Spawn(#[from] std::io::Error),
#[error("the probe of `{target}` exited with {status}: {stderr}")]
Failed {
target: String,
status: std::process::ExitStatus,
stderr: String,
},
#[error("the probe answered `{0}`, which is not `uname -s -m` output")]
Unreadable(String),
}
pub async fn probe_ssh_os(server: &SshServer) -> Result<SshPlatform, SshProbeError> {
SshClient::default().probe_os(server).await
}
#[derive(Debug, Clone, Default)]
pub struct SshClient {
config: Option<PathBuf>,
}
impl SshClient {
#[cfg(test)]
pub(crate) const fn with_config(config: PathBuf) -> Self {
Self {
config: Some(config),
}
}
pub(crate) fn command(&self, server: &SshServer, script: &str) -> std::process::Command {
let mut command = std::process::Command::new("ssh");
command.args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=10"]);
if let Some(config) = &self.config {
command.arg("-F").arg(config);
}
command
.arg("--")
.arg(&server.target)
.arg(shell_words::join(["sh", "-c", script]));
command
}
pub(crate) async fn probe_os(&self, server: &SshServer) -> Result<SshPlatform, SshProbeError> {
let output = async_process::Command::from(self.command(server, "uname -s -m"))
.stdin(Stdio::null())
.output()
.await?;
if !output.status.success() {
return Err(SshProbeError::Failed {
target: server.target.clone(),
status: output.status,
stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
});
}
let answer = String::from_utf8_lossy(&output.stdout).trim().to_string();
let mut words = answer.split_whitespace();
match (words.next(), words.next(), words.next()) {
(Some(os), Some(arch), None) => Ok(SshPlatform {
os: os.to_string(),
arch: arch.to_string(),
}),
_ => Err(SshProbeError::Unreadable(answer)),
}
}
}
#[derive(Debug, Clone)]
pub struct PreparedSsh {
pub(crate) heel: Option<String>,
pub(crate) tools: PreparedTools<PathBuf>,
}
#[derive(Debug)]
pub struct SshEnvironment {
server: SshServer,
approved: OnceCell<()>,
prepared: OnceCell<PreparedSsh>,
}
impl SshEnvironment {
pub(crate) const fn server(&self) -> &SshServer {
&self.server
}
pub(crate) async fn approve<F, Fut, E>(&self, ask: F) -> Result<(), E>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<(), E>>,
{
self.approved.get_or_try_init(ask).await?;
Ok(())
}
pub(crate) async fn prepared<F, Fut, E>(&self, prepare: F) -> Result<&PreparedSsh, E>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<PreparedSsh, E>>,
{
self.prepared.get_or_try_init(prepare).await
}
#[cfg(test)]
pub(crate) fn set_prepared(&self, prepared: PreparedSsh) {
assert!(
self.prepared.set_blocking(prepared).is_ok(),
"a test server is prepared once"
);
}
#[cfg(test)]
pub(crate) fn is_approved(&self) -> bool {
self.approved.is_initialized()
}
#[cfg(test)]
pub(crate) fn is_prepared(&self) -> bool {
self.prepared.is_initialized()
}
}
#[derive(Debug, Clone, Default)]
pub struct SshEnvironments {
client: SshClient,
servers: Arc<ArcSwap<Vec<Arc<SshEnvironment>>>>,
}
impl SshEnvironments {
#[cfg(test)]
pub(crate) fn with_client(mut self, client: SshClient) -> Self {
self.client = client;
self
}
pub(crate) const fn client(&self) -> &SshClient {
&self.client
}
pub(crate) fn add(&self, server: SshServer) -> Result<(), SshServerError> {
let SshServer { name, target } = server;
let server = SshServer {
name: name.trim().to_string(),
target: target.trim().to_string(),
};
if server.name.is_empty() || server.target.is_empty() {
return Err(SshServerError::Blank);
}
let environment = Arc::new(SshEnvironment {
server,
approved: OnceCell::new(),
prepared: OnceCell::new(),
});
let mut duplicate = false;
self.servers.rcu(|servers| {
duplicate = servers
.iter()
.any(|existing| existing.server.name == environment.server.name);
let mut next = Vec::clone(servers);
if !duplicate {
next.push(Arc::clone(&environment));
}
next
});
if duplicate {
return Err(SshServerError::Duplicate(environment.server.name.clone()));
}
Ok(())
}
pub(crate) fn remove(&self, name: &str) -> Option<SshServer> {
let mut removed = None;
self.servers.rcu(|servers| {
let (gone, kept): (Vec<_>, Vec<_>) = servers
.iter()
.cloned()
.partition(|environment| environment.server.name == name);
removed = gone.into_iter().next();
kept
});
removed.map(|environment| environment.server.clone())
}
pub(crate) fn list(&self) -> Vec<SshServer> {
self.servers
.load()
.iter()
.map(|environment| environment.server.clone())
.collect()
}
pub(crate) fn get(&self, name: &str) -> Option<Arc<SshEnvironment>> {
self.servers
.load()
.iter()
.find(|environment| environment.server.name == name)
.cloned()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn server(name: &str, target: &str) -> SshServer {
SshServer {
name: name.to_string(),
target: target.to_string(),
}
}
#[test]
fn servers_join_and_leave_a_live_set_every_clone_sees() {
let set = SshEnvironments::default();
let clone = set.clone();
set.add(server(" build ", " builder@build.internal "))
.unwrap();
assert_eq!(
clone.list(),
[server("build", "builder@build.internal")],
"names and targets are trimmed and the clone sees the addition"
);
assert!(matches!(
clone.add(server("build", "other@build.internal")),
Err(SshServerError::Duplicate(name)) if name == "build"
));
assert!(matches!(
set.add(server("staging", " ")),
Err(SshServerError::Blank)
));
assert_eq!(
clone.remove("build"),
Some(server("build", "builder@build.internal"))
);
assert_eq!(set.list(), []);
assert_eq!(set.remove("build"), None);
}
#[tokio::test]
async fn a_server_added_again_starts_its_first_use_over() {
let set = SshEnvironments::default();
set.add(server("build", "builder@build.internal")).unwrap();
let first = set.get("build").unwrap();
first.approve(|| async { Ok::<_, ()>(()) }).await.unwrap();
assert!(first.is_approved());
set.remove("build");
set.add(server("build", "builder@build.internal")).unwrap();
assert!(!set.get("build").unwrap().is_approved());
}
#[tokio::test]
async fn a_refused_approval_is_asked_again() {
let set = SshEnvironments::default();
set.add(server("build", "builder@build.internal")).unwrap();
let environment = set.get("build").unwrap();
assert_eq!(environment.approve(|| async { Err("no") }).await, Err("no"));
assert!(!environment.is_approved());
environment
.approve(|| async { Ok::<_, &str>(()) })
.await
.unwrap();
environment
.approve(|| async { Err("asked again") })
.await
.unwrap();
}
}