Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
394 lines
14 KiB
Rust
394 lines
14 KiB
Rust
//! OpenSSH transport preflight. Does not install or start anything on the host.
|
|
use crate::hardware::{Hardware, Memory, parse_nvidia};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::{
|
|
path::Path,
|
|
process::Stdio,
|
|
time::{Duration, SystemTime, UNIX_EPOCH},
|
|
};
|
|
use tokio::{
|
|
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
|
|
process::Command,
|
|
};
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct SshProfile {
|
|
pub schema_version: u32,
|
|
pub id: String,
|
|
pub host: String,
|
|
pub user: Option<String>,
|
|
pub port: Option<u16>,
|
|
/// Reference only. Private key contents never enter the profile or protocol.
|
|
pub identity_file: Option<String>,
|
|
}
|
|
#[derive(Debug, Serialize)]
|
|
pub struct RemoteInventory {
|
|
pub schema_version: u32,
|
|
pub node_id: String,
|
|
pub transport: &'static str,
|
|
pub hardware: Hardware,
|
|
/// SSH user's current/home filesystem; recheck actual model destination before install.
|
|
pub home_disk_available_bytes: Option<u64>,
|
|
}
|
|
impl SshProfile {
|
|
pub fn arguments(&self) -> Result<Vec<String>, String> {
|
|
let ident = |s: &str| {
|
|
!s.is_empty()
|
|
&& s.len() <= 128
|
|
&& s.as_bytes()[0].is_ascii_alphanumeric()
|
|
&& s.bytes()
|
|
.all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b))
|
|
};
|
|
if self.schema_version != 1
|
|
|| !ident(&self.id)
|
|
|| self.host.is_empty()
|
|
|| self.host.len() > 253
|
|
|| !self.host.as_bytes()[0].is_ascii_alphanumeric()
|
|
|| !self
|
|
.host
|
|
.bytes()
|
|
.all(|b| b.is_ascii_alphanumeric() || b"._-:".contains(&b))
|
|
|| self.user.as_ref().is_some_and(|s| !ident(s))
|
|
|| self.port == Some(0)
|
|
{
|
|
return Err("invalid SSH profile".into());
|
|
}
|
|
let mut args = vec![
|
|
"-T",
|
|
"-o",
|
|
"BatchMode=yes",
|
|
"-o",
|
|
"StrictHostKeyChecking=yes",
|
|
"-o",
|
|
"ForwardAgent=no",
|
|
"-o",
|
|
"ClearAllForwardings=yes",
|
|
"-o",
|
|
"PermitLocalCommand=no",
|
|
"-o",
|
|
"ConnectTimeout=8",
|
|
]
|
|
.into_iter()
|
|
.map(str::to_owned)
|
|
.collect::<Vec<_>>();
|
|
if let Some(port) = self.port {
|
|
args.extend(["-p".into(), port.to_string()]);
|
|
}
|
|
if let Some(user) = &self.user {
|
|
args.extend(["-l".into(), user.clone()]);
|
|
}
|
|
if let Some(path) = &self.identity_file {
|
|
if !Path::new(path).is_absolute()
|
|
|| path.len() > 4096
|
|
|| path.chars().any(char::is_control)
|
|
{
|
|
return Err("SSH identity must be an absolute key-file reference".into());
|
|
}
|
|
args.extend(["-i".into(), path.clone()]);
|
|
}
|
|
args.extend(["--".into(), self.host.clone(), "sh".into(), "-s".into()]);
|
|
Ok(args)
|
|
}
|
|
}
|
|
// Static stdin only: no profile values interpolated into this remote shell program.
|
|
const PROBE: &str = r#"export LC_ALL=C
|
|
printf 'os\t'; uname -s
|
|
if [ "$(uname -s)" != Linux ]; then exit 0; fi
|
|
printf 'arch\t'; uname -m
|
|
printf 'cpus\t'; getconf _NPROCESSORS_ONLN
|
|
awk -F: '/^model name/ {sub(/^[ \t]+/, "", $2); print "cpu\t" $2; exit}' /proc/cpuinfo
|
|
awk -F: '/^(flags|Features)[ \t]*:/ {print "features\t" $2; exit}' /proc/cpuinfo
|
|
awk '/^MemTotal:/ {print "total_kib\t" $2} /^MemAvailable:/ {print "available_kib\t" $2}' /proc/meminfo
|
|
df -Pk . 2>/dev/null | awk 'NR==2 {print "disk_available_kib\t" $4}'
|
|
if command -v nvidia-smi >/dev/null 2>&1; then
|
|
nvidia-smi --query-gpu=name,memory.total,memory.free,driver_version --format=csv,noheader,nounits 2>/dev/null | sed 's/^/gpu\t/'
|
|
fi
|
|
printf 'end\tok\n'
|
|
"#;
|
|
async fn bounded(reader: impl AsyncRead + Unpin) -> Result<Vec<u8>, String> {
|
|
let mut data = Vec::new();
|
|
reader
|
|
.take(128 * 1024 + 1)
|
|
.read_to_end(&mut data)
|
|
.await
|
|
.map_err(|_| "SSH read failed")?;
|
|
if data.len() > 128 * 1024 {
|
|
return Err("SSH output limit exceeded".into());
|
|
}
|
|
Ok(data)
|
|
}
|
|
pub async fn inspect(profile: &SshProfile) -> Result<RemoteInventory, String> {
|
|
inspect_with_program(profile, "ssh", Duration::from_secs(15)).await
|
|
}
|
|
async fn inspect_with_program(
|
|
profile: &SshProfile,
|
|
program: &str,
|
|
limit: Duration,
|
|
) -> Result<RemoteInventory, String> {
|
|
let args = profile.arguments()?;
|
|
let mut child = Command::new(program)
|
|
.args(args)
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::piped())
|
|
.kill_on_drop(true)
|
|
.spawn()
|
|
.map_err(|_| "OpenSSH is unavailable")?;
|
|
let mut input = child.stdin.take().ok_or("SSH stdin missing")?;
|
|
let output = child.stdout.take().ok_or("SSH stdout missing")?;
|
|
let error = child.stderr.take().ok_or("SSH stderr missing")?;
|
|
let run = async {
|
|
let write = async move {
|
|
input
|
|
.write_all(PROBE.as_bytes())
|
|
.await
|
|
.map_err(|_| "SSH input failed".to_string())?;
|
|
drop(input); // Close the pipe: remote `sh -s` must receive EOF.
|
|
Ok::<(), String>(())
|
|
};
|
|
let (_, output, error) = tokio::try_join!(write, bounded(output), bounded(error))?;
|
|
let status = child.wait().await.map_err(|_| "SSH wait failed")?;
|
|
if !status.success() {
|
|
let error = String::from_utf8_lossy(&error);
|
|
return Err(if error.contains("Host key verification failed")
|
|
|| error.contains("REMOTE HOST IDENTIFICATION HAS CHANGED")
|
|
{
|
|
"SSH host identity is not trusted or has changed"
|
|
} else if error.contains("Permission denied") {
|
|
"SSH authentication failed"
|
|
} else {
|
|
"SSH preflight failed; verify connection and host configuration"
|
|
}
|
|
.to_string());
|
|
}
|
|
parse(
|
|
profile,
|
|
&String::from_utf8(output).map_err(|_| "SSH output is not UTF-8")?,
|
|
)
|
|
};
|
|
match tokio::time::timeout(limit, run).await {
|
|
Ok(Ok(result)) => Ok(result),
|
|
failure => {
|
|
let _ = child.kill().await;
|
|
match failure {
|
|
Ok(Err(e)) => Err(e),
|
|
_ => Err("SSH preflight timed out".into()),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
fn parse(profile: &SshProfile, data: &str) -> Result<RemoteInventory, String> {
|
|
let mut fields = std::collections::HashMap::new();
|
|
let mut gpus = Vec::new();
|
|
for line in data.lines() {
|
|
let Some((key, value)) = line.split_once('\t') else {
|
|
return Err("unexpected SSH probe output".into());
|
|
};
|
|
if key == "gpu" {
|
|
gpus.push(value);
|
|
} else if fields.insert(key, value).is_some() {
|
|
return Err("duplicate SSH probe field".into());
|
|
}
|
|
}
|
|
if fields.get("os") != Some(&"Linux") {
|
|
return Err("remote worker preflight currently supports Linux only".into());
|
|
}
|
|
if fields.get("end") != Some(&"ok") {
|
|
return Err("incomplete SSH probe".into());
|
|
}
|
|
let kib = |key: &str| {
|
|
fields
|
|
.get(key)
|
|
.and_then(|s| s.parse::<u64>().ok())
|
|
.and_then(|n| n.checked_mul(1024))
|
|
};
|
|
let memory = Memory {
|
|
total_bytes: kib("total_kib"),
|
|
available_bytes: kib("available_kib"),
|
|
};
|
|
if memory.total_bytes.is_none_or(|n| n == 0)
|
|
|| matches!((memory.total_bytes,memory.available_bytes),(Some(t),Some(a)) if a>t)
|
|
{
|
|
return Err("invalid remote RAM inventory".into());
|
|
}
|
|
let architecture = match fields.get("arch").copied() {
|
|
Some("x86_64") => "x86_64",
|
|
Some("aarch64" | "arm64") => "aarch64",
|
|
_ => return Err("unsupported remote CPU architecture".into()),
|
|
};
|
|
let cpus = fields
|
|
.get("cpus")
|
|
.and_then(|s| s.parse::<usize>().ok())
|
|
.filter(|n| *n > 0)
|
|
.ok_or("invalid remote CPU count")?;
|
|
let flags = fields
|
|
.get("features")
|
|
.copied()
|
|
.unwrap_or("")
|
|
.split_whitespace()
|
|
.collect::<std::collections::HashSet<_>>();
|
|
let cpu_features = [
|
|
("avx2", "avx2"),
|
|
("avx512f", "avx512f"),
|
|
("fma", "fma"),
|
|
("asimd", "neon"),
|
|
("asimddp", "dotprod"),
|
|
]
|
|
.into_iter()
|
|
.filter(|(flag, _)| flags.contains(flag))
|
|
.map(|(_, name)| name.to_owned())
|
|
.collect();
|
|
let mut warnings =
|
|
vec!["NPU and inference-provider support require a separate capability check.".into()];
|
|
let accelerators = match parse_nvidia(&gpus.join("\n")) {
|
|
Ok(g) => g,
|
|
Err(e) => {
|
|
warnings.push(e);
|
|
vec![]
|
|
}
|
|
};
|
|
if accelerators.is_empty() {
|
|
warnings.push("No NVIDIA inventory; other accelerators are not probed yet.".into());
|
|
}
|
|
Ok(RemoteInventory {
|
|
schema_version: 1,
|
|
node_id: profile.id.clone(),
|
|
transport: "ssh",
|
|
home_disk_available_bytes: kib("disk_available_kib"),
|
|
hardware: Hardware {
|
|
schema_version: 1,
|
|
sampled_at_unix_ms: SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.map(|t| t.as_millis() as u64)
|
|
.unwrap_or(0),
|
|
os: "linux".into(),
|
|
architecture: architecture.into(),
|
|
cpu_name: fields.get("cpu").copied().unwrap_or("unknown").into(),
|
|
logical_cpus: cpus,
|
|
cpu_features,
|
|
memory,
|
|
accelerators,
|
|
warnings,
|
|
},
|
|
})
|
|
}
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
fn profile() -> SshProfile {
|
|
SshProfile {
|
|
schema_version: 1,
|
|
id: "server-a".into(),
|
|
host: "gpu-server".into(),
|
|
user: None,
|
|
port: None,
|
|
identity_file: None,
|
|
}
|
|
}
|
|
#[test]
|
|
fn hostile_options_and_secrets_are_not_configuration() {
|
|
for host in [
|
|
"-oProxyCommand=evil",
|
|
"user@host",
|
|
"host;touch x",
|
|
"host\ncommand",
|
|
"$(id)",
|
|
] {
|
|
let mut p = profile();
|
|
p.host = host.into();
|
|
assert!(p.arguments().is_err());
|
|
}
|
|
let mut p = profile();
|
|
p.user = Some("-root".into());
|
|
assert!(p.arguments().is_err());
|
|
p = profile();
|
|
p.identity_file = Some("relative-key".into());
|
|
assert!(p.arguments().is_err());
|
|
assert!(
|
|
serde_json::from_str::<SshProfile>(
|
|
r#"{"schema_version":1,"id":"a","host":"h","password":"secret"}"#
|
|
)
|
|
.is_err()
|
|
);
|
|
let args = profile().arguments().unwrap();
|
|
assert!(args.contains(&"StrictHostKeyChecking=yes".into()));
|
|
assert!(args.contains(&"ForwardAgent=no".into()));
|
|
}
|
|
#[test]
|
|
fn parses_server_memory_and_unknown_accelerators() {
|
|
let data = "os\tLinux\narch\tx86_64\ncpus\t8\ncpu\tFixture CPU\nfeatures\tavx2 fma\ntotal_kib\t33554432\navailable_kib\t16777216\ndisk_available_kib\t1024\nend\tok\n";
|
|
let r = parse(&profile(), data).unwrap();
|
|
assert_eq!(
|
|
r.hardware.memory.available_bytes,
|
|
Some(16 * 1024 * 1024 * 1024)
|
|
);
|
|
assert!(r.hardware.accelerators.is_empty());
|
|
assert_eq!(r.home_disk_available_bytes, Some(1024 * 1024));
|
|
assert!(parse(&profile(), &data.replace("Linux", "Darwin")).is_err());
|
|
assert!(parse(&profile(), &data.replace("end\tok\n", "")).is_err());
|
|
assert!(
|
|
parse(
|
|
&profile(),
|
|
&data.replace("16777216", "9999999999999999999999")
|
|
)
|
|
.unwrap()
|
|
.hardware
|
|
.memory
|
|
.available_bytes
|
|
.is_none()
|
|
);
|
|
}
|
|
#[tokio::test]
|
|
async fn probe_output_is_bounded() {
|
|
assert!(bounded(&vec![b'x'; 128 * 1024 + 1][..]).await.is_err());
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[tokio::test]
|
|
async fn ssh_stdin_closes_and_hung_probe_times_out() {
|
|
use std::{io::Write, os::unix::fs::PermissionsExt};
|
|
struct Temp(std::path::PathBuf);
|
|
impl Drop for Temp {
|
|
fn drop(&mut self) {
|
|
let _ = std::fs::remove_file(&self.0);
|
|
}
|
|
}
|
|
let path =
|
|
Temp(std::env::temp_dir().join(format!("strata-ssh-test-{}", std::process::id())));
|
|
let script = "#!/bin/sh\ncat >/dev/null\nprintf 'os\\tLinux\\narch\\tx86_64\\ncpus\\t1\\ntotal_kib\\t1024\\nend\\tok\\n'\n";
|
|
let mut file = std::fs::OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.open(&path.0)
|
|
.unwrap();
|
|
file.write_all(script.as_bytes()).unwrap();
|
|
drop(file);
|
|
std::fs::set_permissions(&path.0, std::fs::Permissions::from_mode(0o700)).unwrap();
|
|
let p = path.0.to_str().unwrap();
|
|
assert!(
|
|
inspect_with_program(&profile(), p, Duration::from_secs(2))
|
|
.await
|
|
.is_ok()
|
|
);
|
|
std::fs::write(&path.0, "#!/bin/sh\nexec sleep 5\n").unwrap();
|
|
assert_eq!(
|
|
inspect_with_program(&profile(), p, Duration::from_millis(20))
|
|
.await
|
|
.unwrap_err(),
|
|
"SSH preflight timed out"
|
|
);
|
|
std::fs::write(
|
|
&path.0,
|
|
"#!/bin/sh\ncat >/dev/null\necho 'Host key verification failed' >&2\nexit 255\n",
|
|
)
|
|
.unwrap();
|
|
assert_eq!(
|
|
inspect_with_program(&profile(), p, Duration::from_secs(2))
|
|
.await
|
|
.unwrap_err(),
|
|
"SSH host identity is not trusted or has changed"
|
|
);
|
|
}
|
|
}
|