use std::future::IntoFuture;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use futures_util::TryStreamExt as _;
use serde_json::Value;
use tokio::time::Instant;
use crate::client::{BoxFuture, SshOptions, Transport, find};
use crate::error::{ApiErrorKind, CommandError, Error, InterruptKind, Result, VmNotReady, error_code};
use crate::process::Process;
use crate::scripts::*;
use crate::types::EgressPolicy;
use crate::wire::{
self, Command, IS_DIRECTORY, MAX_OUTPUT, MISSING, PARALLEL, PART_SIZE, RUNNING, SetupState, VmInfo, sh,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum WaitUntil {
#[default]
Ssh,
Setup,
Created,
}
impl WaitUntil {
pub(crate) fn timeout(self, timeout: Option<Duration>) -> Result<Duration> {
match timeout {
Some(t) if t.is_zero() => Err(Error::invalid("timeout must be positive")),
Some(t) => Ok(t),
None if self == WaitUntil::Setup => Ok(Duration::from_secs(600)),
None => Ok(Duration::from_secs(60)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandResult {
pub exit_code: i32,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub captured: bool,
}
impl CommandResult {
pub fn success(&self) -> bool {
self.exit_code == 0
}
pub fn stdout_lossy(&self) -> String {
String::from_utf8_lossy(&self.stdout).into_owned()
}
pub fn stderr_lossy(&self) -> String {
String::from_utf8_lossy(&self.stderr).into_owned()
}
pub fn check(self) -> Result<CommandResult> {
if self.success() {
Ok(self)
} else {
Err(Error::Command(Box::new(CommandError { result: self })))
}
}
}
#[derive(Clone)]
pub struct Vm {
pub(crate) t: Arc<Transport>,
pub(crate) info: VmInfo,
}
impl std::fmt::Debug for Vm {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Vm")
.field("name", &self.info.name)
.field("status", &self.info.status)
.finish_non_exhaustive()
}
}
impl Vm {
pub(crate) fn new(t: Arc<Transport>, info: VmInfo) -> Vm {
Vm { t, info }
}
pub fn name(&self) -> &str {
&self.info.name
}
pub fn status(&self) -> &str {
&self.info.status
}
pub fn ssh_dest(&self) -> &str {
&self.info.ssh_dest
}
pub fn https_url(&self) -> &str {
&self.info.https_url
}
pub fn tags(&self) -> &[String] {
&self.info.tags
}
pub fn comment(&self) -> &str {
&self.info.comment
}
pub fn region(&self) -> Option<&str> {
self.info.region.as_deref()
}
pub fn egress(&self) -> Option<EgressPolicy> {
self.info.egress.clone()
}
pub fn created_at(&self) -> Option<&str> {
self.info.created_at.as_deref()
}
pub fn prompt_error(&self) -> Option<&str> {
self.info.prompt_error.as_deref()
}
pub fn url(&self, port: Option<u16>, path: &str) -> Result<String> {
if port == Some(0) {
return Err(Error::invalid("port must be from 1 to 65535"));
}
if !path.starts_with('/') {
return Err(Error::invalid("path must start with /"));
}
let url = &self.info.https_url;
let (scheme, rest) = url.split_once("://").ok_or_else(|| Error::protocol("https_url"))?;
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let authority = match port {
None => authority.to_string(),
Some(port) => {
let host = match authority.rsplit_once(':') {
Some((host, p)) if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => host,
_ => authority,
};
format!("{host}:{port}")
}
};
Ok(format!("{scheme}://{authority}{path}"))
}
pub(crate) fn absorb(&mut self, result: &Value) {
let Some(obj) = result.as_object() else { return };
if obj.get("vm_name").and_then(Value::as_str) != Some(self.info.name.as_str()) {
return;
}
if let Some(status) = obj.get("status").and_then(Value::as_str) {
self.info.status = status.to_string();
}
if let Some(comment) = obj.get("comment").and_then(Value::as_str) {
self.info.comment = comment.to_string();
}
if let Some(egress) = wire::egress_policy(obj.get("egress_policy")) {
self.info.egress = Some(egress);
}
if let Some(tags) = obj.get("tags").and_then(Value::as_array)
&& let Some(tags) = tags
.iter()
.map(|t| t.as_str().map(str::to_string))
.collect::<Option<Vec<_>>>()
{
self.info.tags = tags;
}
}
pub(crate) fn renamed(&mut self, result: &Value) -> Result<()> {
let get = |key: &str| result.get(key).and_then(Value::as_str).filter(|s| !s.is_empty());
let (Some(name), Some(ssh_dest), Some(https_url)) = (get("new_name"), get("ssh_dest"), get("https_url")) else {
return Err(Error::protocol("rename"));
};
if !wire::is_vm_name(name) {
return Err(Error::protocol("rename"));
}
self.info.name = name.to_string();
self.info.ssh_dest = ssh_dest.to_string();
self.info.https_url = https_url.to_string();
Ok(())
}
pub fn run(&self, command: impl Into<Command>) -> Run<'_> {
Run {
vm: self,
command: command.into(),
check: false,
cwd: None,
env: Vec::new(),
options: SshOptions::default(),
}
}
async fn fit(&self, line: String, make: impl Fn(&str) -> String) -> Result<String> {
let command = make(&line);
if wire::fits(&self.info.name, &command) {
return Ok(command);
}
let path = format!("/tmp/.exedev-command-{}", wire::random_hex(8));
self.write_file(&path, line.into_bytes()).await?;
Ok(make(&UPLOADED_COMMAND.replace("{path}", &path)))
}
pub(crate) async fn script(&self, command: &str, max_output: usize, ok: &[i32]) -> Result<CommandResult> {
let options = SshOptions {
max_output,
..SshOptions::default()
};
let result = self.t.ssh(&self.info.name, command, options).await?;
if result.exit_code != 0 && !ok.contains(&result.exit_code) {
return Err(Error::Command(Box::new(CommandError { result })));
}
Ok(result)
}
fn file_error(&self, exit_code: i32, path: &str) -> Result<()> {
let (vm, path) = (self.info.name.clone(), path.to_string());
match exit_code {
MISSING => Err(Error::FileNotFound { vm, path }),
IS_DIRECTORY => Err(Error::IsADirectory { vm, path }),
_ => Ok(()),
}
}
pub fn write_file(&self, path: &str, data: impl Into<Vec<u8>>) -> WriteFile<'_> {
WriteFile {
vm: self,
path: path.to_string(),
data: data.into(),
mode: None,
}
}
async fn write(&self, path: &str, data: &[u8], mode: Option<u32>) -> Result<()> {
let remote = wire::remote_path(path)?;
let mode = match mode {
None => String::new(),
Some(m) if m <= 0o7777 => format!("{m:o}"),
Some(_) => return Err(Error::invalid("mode must be at most 0o7777")),
};
let (packed, gz) = wire::pack(data);
let encoded = wire::b64(&packed);
let gz = if gz { "gz" } else { "" };
let command = sh(WRITE_SCRIPT, &[&remote, &encoded, &mode, gz, ""]);
if wire::fits(&self.info.name, &command) {
self.script(&command, MAX_OUTPUT, &[]).await?;
return Ok(());
}
drop(command);
let parts = format!("/tmp/.exedev-upload-{}", wire::random_hex(8));
let commands: Vec<String> = encoded
.as_bytes()
.chunks(PART_SIZE)
.enumerate()
.map(|(i, chunk)| {
let chunk = std::str::from_utf8(chunk).expect("base64");
sh(PART_SCRIPT, &[&parts, &format!("{i:06}"), chunk])
})
.collect();
let sent = futures_util::stream::iter(commands.iter().map(Ok))
.try_for_each_concurrent(PARALLEL, |command| async move {
self.script(command, MAX_OUTPUT, &[]).await.map(drop)
})
.await;
if let Err(err) = sent {
let options = SshOptions {
capture: false,
timeout: Some(Duration::from_secs(30)),
..SshOptions::default()
};
let _ = self.t.ssh(&self.info.name, &format!("rm -rf {parts}"), options).await;
return Err(err);
}
self.script(&sh(WRITE_SCRIPT, &[&remote, "", &mode, gz, &parts]), MAX_OUTPUT, &[])
.await?;
Ok(())
}
pub async fn read_file(&self, path: &str) -> Result<Vec<u8>> {
let command = sh(READ_SCRIPT, &[&wire::remote_path(path)?]);
let result = self.script(&command, usize::MAX, &[MISSING, IS_DIRECTORY]).await?;
self.file_error(result.exit_code, path)?;
Ok(result.stdout)
}
pub fn upload(&self, local: impl AsRef<Path>, remote: &str) -> Upload<'_> {
Upload {
vm: self,
local: local.as_ref().to_path_buf(),
remote: remote.to_string(),
exclude: Vec::new(),
}
}
pub async fn download(&self, remote: &str, local: impl AsRef<Path>) -> Result<()> {
let command = sh(DOWNLOAD_SCRIPT, &[&wire::remote_path(remote)?]);
let mut result = self.script(&command, usize::MAX, &[MISSING]).await?;
self.file_error(result.exit_code, remote)?;
let local = local.as_ref().to_path_buf();
let data = std::mem::take(&mut result.stdout);
match data.first() {
Some(b'D') => tokio::task::spawn_blocking(move || crate::archive::untar(&data[1..], &local))
.await
.map_err(|_| Error::protocol("download"))?,
Some(b'F') => tokio::fs::write(&local, &data[1..])
.await
.map_err(|e| Error::io(format!("writing {}", local.display()), e)),
_ => Err(Error::protocol("download")),
}
}
pub fn spawn(&self, command: impl Into<Command>) -> Spawn<'_> {
Spawn {
vm: self,
command: command.into(),
name: None,
cwd: None,
env: Vec::new(),
}
}
pub async fn process(&self, name: &str) -> Result<Process> {
let command = sh(STATE_SCRIPT, &[wire::process_name(name)?]);
let result = self.script(&command, MAX_OUTPUT, &[MISSING]).await?;
if result.exit_code == MISSING {
return Err(self.no_such_process(name));
}
let state = wire::process_state(&result.stdout_lossy())?;
Ok(Process::new(self.clone(), name.to_string(), state))
}
pub(crate) fn no_such_process(&self, name: &str) -> Error {
Error::NoSuchProcess {
process: name.to_string(),
vm: self.info.name.clone(),
}
}
pub async fn processes(&self) -> Result<Vec<Process>> {
let result = self.script(&sh(LIST_SCRIPT, &[]), MAX_OUTPUT, &[]).await?;
let mut processes = Vec::new();
for line in result.stdout_lossy().lines() {
let (name, state) = line.split_once(' ').ok_or_else(|| Error::protocol("processes"))?;
let name = wire::process_name(name).map_err(|_| Error::protocol("processes"))?;
processes.push(Process::new(
self.clone(),
name.to_string(),
wire::process_state(state)?,
));
}
Ok(processes)
}
pub async fn refresh(&mut self) -> Result<()> {
self.info = find(&self.t, &self.info.name).await?;
Ok(())
}
pub fn wait_until_ready(&mut self) -> WaitUntilReady<'_> {
WaitUntilReady {
vm: self,
until: WaitUntil::Ssh,
timeout: None,
}
}
fn not_ready(&self, failure: impl Into<String>, source: Option<Error>) -> Error {
Error::VmNotReady(Box::new(VmNotReady {
name: self.info.name.clone(),
vm: Some(self.clone()),
failure: failure.into(),
setup: None,
source,
}))
}
async fn wait(&mut self, until: WaitUntil, timeout: Duration) -> Result<()> {
let deadline = Instant::now() + timeout;
let mut backoff = Duration::from_millis(100);
let setup = until == WaitUntil::Setup;
let probe = if setup { SETUP_PROBE } else { "true" };
let mut last = None;
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
break;
}
let options = SshOptions {
capture: setup,
max_output: 1 << 20,
timeout: Some(remaining),
..SshOptions::default()
};
match self.t.ssh(&self.info.name, probe, options).await {
Ok(result) => {
if result.exit_code != 0 {
return Err(self.not_ready("is not SSH-ready", Some(Error::protocol("ssh readiness probe"))));
}
let state = if setup {
wire::setup_state(&result.stdout_lossy())
.map_err(|e| self.not_ready("is not SSH-ready", Some(e)))?
} else {
SetupState::Done
};
match state {
SetupState::Done => {
self.info.status = "running".to_string();
return Ok(());
}
SetupState::Failed(failure) => {
let mut err = VmNotReady::setup_failed(&self.info.name, failure);
err.vm = Some(self.clone());
return Err(Error::VmNotReady(Box::new(err)));
}
SetupState::Pending => backoff = backoff.max(Duration::from_secs(1)),
}
}
Err(Error::Interrupted(i)) if i.kind == InterruptKind::Timeout => {
last = Some(Error::Interrupted(i));
break;
}
Err(Error::Interrupted(i)) if i.kind == InterruptKind::Disconnected => {
last = Some(Error::Interrupted(i))
}
Err(err @ Error::Network { .. }) => last = Some(err),
Err(Error::Api(err)) if err.kind() == ApiErrorKind::PermissionDenied => {
return Err(self.not_ready(
"is not known to be ready: this token may not run ssh, which readiness needs \
(use WaitUntil::Created)",
Some(Error::Api(err)),
));
}
Err(Error::Api(err))
if err.status == 422 && error_code(&err.body).as_deref() == Some("vm_unreachable") =>
{
last = Some(Error::Api(err));
}
Err(err @ (Error::Api(_) | Error::Interrupted(_) | Error::Protocol { .. })) => {
return Err(self.not_ready("is not SSH-ready", Some(err)));
}
Err(err) => return Err(err),
}
let remaining = deadline.saturating_duration_since(Instant::now());
tokio::time::sleep(backoff.min(remaining)).await;
backoff = (backoff * 2).min(Duration::from_secs(2));
}
let what = if setup {
"setup did not finish in time"
} else {
"SSH readiness timed out"
};
Err(self.not_ready(format!("is not ready: {what}"), last))
}
pub(crate) async fn ready(&mut self, until: WaitUntil, timeout: Option<Duration>) -> Result<()> {
let timeout = until.timeout(timeout)?;
if until == WaitUntil::Created {
return Ok(());
}
self.wait(until, timeout).await
}
pub(crate) async fn created(
mut self,
until: WaitUntil,
timeout: Option<Duration>,
keep_on_failure: bool,
) -> Result<Vm> {
let mut guard = DeleteGuard {
t: Some(self.t.clone()),
name: self.info.name.clone(),
};
match self.ready(until, timeout).await {
Ok(()) => {
guard.t = None;
Ok(self)
}
Err(err @ Error::VmNotReady(_)) if keep_on_failure => {
guard.t = None;
Err(err)
}
Err(mut err) => {
guard.t = None;
self.t.remove(&self.info.name).await;
if let Error::VmNotReady(e) = &mut err {
e.vm = None;
}
Err(err)
}
}
}
pub(crate) async fn flush(&self) {
let options = SshOptions {
capture: false,
timeout: Some(Duration::from_secs(60)),
..SshOptions::default()
};
let _ = self.t.ssh(&self.info.name, &sh(FLUSH_SCRIPT, &[]), options).await;
}
}
struct DeleteGuard {
t: Option<Arc<Transport>>,
name: String,
}
impl Drop for DeleteGuard {
fn drop(&mut self) {
let Some(t) = self.t.take() else { return };
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
return;
};
let name = std::mem::take(&mut self.name);
runtime.spawn(async move { t.remove(&name).await });
}
}
#[must_use = "a command does nothing until it is awaited"]
pub struct Run<'a> {
vm: &'a Vm,
command: Command,
check: bool,
cwd: Option<String>,
env: Vec<(String, String)>,
options: SshOptions<'a>,
}
impl<'a> Run<'a> {
pub fn check(mut self, check: bool) -> Self {
self.check = check;
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.options.timeout = Some(timeout);
self
}
pub fn cwd(mut self, dir: impl Into<String>) -> Self {
self.cwd = Some(dir.into());
self
}
pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.env.push((key.into(), value.into()));
self
}
pub fn on_stdout(mut self, f: impl FnMut(&str) + Send + 'a) -> Self {
self.options.on_stdout = Some(Box::new(f));
self
}
pub fn on_stderr(mut self, f: impl FnMut(&str) + Send + 'a) -> Self {
self.options.on_stderr = Some(Box::new(f));
self
}
pub fn on_stdout_bytes(mut self, f: impl FnMut(&[u8]) + Send + 'a) -> Self {
self.options.on_stdout_bytes = Some(Box::new(f));
self
}
pub fn on_stderr_bytes(mut self, f: impl FnMut(&[u8]) + Send + 'a) -> Self {
self.options.on_stderr_bytes = Some(Box::new(f));
self
}
pub fn capture(mut self, capture: bool) -> Self {
self.options.capture = capture;
self
}
pub fn max_output(mut self, bytes: usize) -> Self {
self.options.max_output = bytes;
self
}
}
impl<'a> IntoFuture for Run<'a> {
type Output = Result<CommandResult>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move {
let line = wire::shell_command(&self.command, self.cwd.as_deref(), &self.env)?;
let script = self.vm.fit(line, |line| sh(RUN_SCRIPT, &[line])).await?;
let result = self.vm.t.ssh(&self.vm.info.name, &script, self.options).await?;
if self.check { result.check() } else { Ok(result) }
})
}
}
#[must_use = "a request does nothing until it is awaited"]
pub struct WriteFile<'a> {
vm: &'a Vm,
path: String,
data: Vec<u8>,
mode: Option<u32>,
}
impl WriteFile<'_> {
pub fn mode(mut self, mode: u32) -> Self {
self.mode = Some(mode);
self
}
}
impl<'a> IntoFuture for WriteFile<'a> {
type Output = Result<()>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move { self.vm.write(&self.path, &self.data, self.mode).await })
}
}
#[must_use = "a request does nothing until it is awaited"]
pub struct Upload<'a> {
vm: &'a Vm,
local: PathBuf,
remote: String,
exclude: Vec<String>,
}
impl Upload<'_> {
pub fn exclude<I, S>(mut self, patterns: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.exclude.extend(patterns.into_iter().map(Into::into));
self
}
}
impl<'a> IntoFuture for Upload<'a> {
type Output = Result<()>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move {
let destination = wire::remote_path(&self.remote)?;
let local = self.local.clone();
let meta = tokio::fs::metadata(&local)
.await
.map_err(|e| Error::io(format!("reading {}", local.display()), e))?;
if meta.is_dir() {
let exclude = self.exclude.clone();
let archive = tokio::task::spawn_blocking(move || crate::archive::tar_directory(&local, &exclude))
.await
.map_err(|_| Error::invalid("archiving failed"))??;
let temporary = format!("/tmp/.exedev-upload-{}.tgz", wire::random_hex(8));
self.vm.write(&temporary, &archive, None).await?;
self.vm
.script(&sh(UNTAR_SCRIPT, &[&temporary, &destination]), MAX_OUTPUT, &[])
.await?;
return Ok(());
}
let data = tokio::fs::read(&local)
.await
.map_err(|e| Error::io(format!("reading {}", local.display()), e))?;
self.vm
.write(&self.remote, &data, Some(crate::archive::file_mode(&meta)))
.await
})
}
}
#[must_use = "a request does nothing until it is awaited"]
pub struct Spawn<'a> {
vm: &'a Vm,
command: Command,
name: Option<String>,
cwd: Option<String>,
env: Vec<(String, String)>,
}
impl Spawn<'_> {
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn cwd(mut self, dir: impl Into<String>) -> Self {
self.cwd = Some(dir.into());
self
}
pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.env.push((key.into(), value.into()));
self
}
}
impl<'a> IntoFuture for Spawn<'a> {
type Output = Result<Process>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move {
let name = self.name.unwrap_or_else(|| wire::random_hex(4));
wire::process_name(&name)?;
let line = wire::shell_command(&self.command, self.cwd.as_deref(), &self.env)?;
let script = self.vm.fit(line, |line| sh(SPAWN_SCRIPT, &[&name, line])).await?;
let result = self.vm.script(&script, MAX_OUTPUT, &[RUNNING]).await?;
if result.exit_code == RUNNING {
return Err(Error::invalid(format!(
"a process named {name} is already running on VM {}",
self.vm.name()
)));
}
let pid = result
.stdout_lossy()
.trim()
.parse()
.map_err(|_| Error::protocol("spawn"))?;
let state = wire::ProcessState {
pid,
exit_code: None,
lost: false,
};
Ok(Process::new(self.vm.clone(), name, state))
})
}
}
#[must_use = "a request does nothing until it is awaited"]
pub struct WaitUntilReady<'a> {
vm: &'a mut Vm,
until: WaitUntil,
timeout: Option<Duration>,
}
impl WaitUntilReady<'_> {
pub fn until(mut self, until: WaitUntil) -> Self {
self.until = until;
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
}
impl<'a> IntoFuture for WaitUntilReady<'a> {
type Output = Result<()>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move { self.vm.ready(self.until, self.timeout).await })
}
}
#[cfg(test)]
mod tests {
use super::*;
fn vm(https_url: &str) -> Vm {
let client = crate::Client::new("t").unwrap();
Vm::new(
client.t,
VmInfo {
name: "box".into(),
status: "running".into(),
ssh_dest: "box.exe.xyz".into(),
https_url: https_url.into(),
tags: vec![],
region: None,
comment: String::new(),
created_at: None,
egress: None,
prompt_error: None,
},
)
}
#[test]
fn urls() {
let v = vm("https://box.exe.xyz/");
assert_eq!(v.url(None, "/").unwrap(), "https://box.exe.xyz/");
assert_eq!(v.url(Some(8080), "/api").unwrap(), "https://box.exe.xyz:8080/api");
assert!(v.url(None, "x").is_err());
let v = vm("http://localhost:1234");
assert_eq!(v.url(Some(3000), "/").unwrap(), "http://localhost:3000/");
}
#[test]
fn absorbing() {
let mut v = vm("https://box.exe.xyz/");
v.absorb(&serde_json::json!({"vm_name": "box", "status": "paused", "tags": ["a"], "egress_policy": "all"}));
assert_eq!(
(v.status(), v.tags(), v.egress()),
("paused", &["a".to_string()][..], Some(EgressPolicy::All))
);
v.absorb(&serde_json::json!({"vm_name": "other", "status": "running"}));
assert_eq!(v.status(), "paused");
v.renamed(&serde_json::json!({"new_name": "b2", "ssh_dest": "b2.exe.xyz", "https_url": "https://b2.exe.xyz/"}))
.unwrap();
assert_eq!(v.name(), "b2");
assert!(v.renamed(&serde_json::json!({"new_name": "b3"})).is_err());
}
#[test]
fn results() {
let r = CommandResult {
exit_code: 1,
stdout: b"out".to_vec(),
stderr: b"first\nlast line\n".to_vec(),
captured: true,
};
assert!(!r.success());
let err = r.check().unwrap_err();
assert_eq!(err.to_string(), "command exited with status 1: last line");
}
}