use std::future::IntoFuture;
use std::time::Duration;
use tokio::time::Instant;
use crate::client::{BoxFuture, SshOptions};
use crate::error::{Error, InterruptKind, Result};
use crate::scripts::*;
use crate::vm::{CommandResult, Vm};
use crate::wire::{self, MAX_OUTPUT, MISSING, ProcessState, sh};
#[derive(Clone)]
pub struct Process {
vm: Vm,
name: String,
state: ProcessState,
}
impl std::fmt::Debug for Process {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Process")
.field("vm", &self.vm.name())
.field("name", &self.name)
.field("pid", &self.state.pid)
.field("exit_code", &self.state.exit_code)
.field("lost", &self.state.lost)
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Logs {
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
}
impl Logs {
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()
}
}
impl Process {
pub(crate) fn new(vm: Vm, name: String, state: ProcessState) -> Process {
Process { vm, name, state }
}
pub fn vm(&self) -> &Vm {
&self.vm
}
pub fn name(&self) -> &str {
&self.name
}
pub fn pid(&self) -> u32 {
self.state.pid
}
pub fn exit_code(&self) -> Option<i32> {
self.state.exit_code
}
fn lost(&self) -> Error {
Error::ProcessLost {
process: self.name.clone(),
vm: self.vm.name().to_string(),
}
}
pub async fn poll(&mut self) -> Result<Option<i32>> {
let result = self
.vm
.script(&sh(STATE_SCRIPT, &[&self.name]), MAX_OUTPUT, &[MISSING])
.await?;
if result.exit_code == MISSING {
return Err(self.vm.no_such_process(&self.name));
}
self.state = wire::process_state(&result.stdout_lossy())?;
if self.state.lost {
return Err(self.lost());
}
Ok(self.state.exit_code)
}
pub fn wait(&mut self) -> Wait<'_> {
Wait {
process: self,
timeout: None,
check: false,
capture: true,
max_output: MAX_OUTPUT,
}
}
pub fn logs(&self) -> LogsRequest<'_> {
LogsRequest {
process: self,
tail: None,
}
}
pub async fn send_signal(&self, signal: &str) -> Result<()> {
let command = sh(KILL_SCRIPT, &[&self.name, &wire::signal_name(signal)?]);
let result = self.vm.script(&command, MAX_OUTPUT, &[MISSING]).await?;
if result.exit_code == MISSING {
return Err(self.vm.no_such_process(&self.name));
}
Ok(())
}
pub async fn terminate(&self) -> Result<()> {
self.send_signal("TERM").await
}
pub async fn kill(&self) -> Result<()> {
self.send_signal("KILL").await
}
}
#[must_use = "a request does nothing until it is awaited"]
pub struct Wait<'a> {
process: &'a mut Process,
timeout: Option<Duration>,
check: bool,
capture: bool,
max_output: usize,
}
impl Wait<'_> {
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn check(mut self, check: bool) -> Self {
self.check = check;
self
}
pub fn capture(mut self, capture: bool) -> Self {
self.capture = capture;
self
}
pub fn max_output(mut self, bytes: usize) -> Self {
self.max_output = bytes;
self
}
}
impl<'a> IntoFuture for Wait<'a> {
type Output = Result<CommandResult>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move {
let p = self.process;
let deadline = self.timeout.map(|t| Instant::now() + t);
let nonce = wire::random_hex(8);
let command = sh(WAIT_SCRIPT, &[&p.name, &nonce, if self.capture { "1" } else { "" }]);
let mut backoff = Duration::from_millis(100);
let result = loop {
let remaining = deadline.map(|d| d.saturating_duration_since(Instant::now()));
if remaining.is_some_and(|r| r.is_zero()) {
return Err(Error::ProcessTimeout {
process: p.name.clone(),
vm: p.vm.name().to_string(),
});
}
let options = SshOptions {
max_output: self.max_output,
timeout: remaining,
..SshOptions::default()
};
match p.vm.t.ssh(p.vm.name(), &command, options).await {
Ok(result) => break result,
Err(Error::Interrupted(i)) if i.kind == InterruptKind::Timeout => continue,
Err(Error::Interrupted(i)) if i.kind == InterruptKind::Disconnected => {}
Err(Error::Network { .. }) => {}
Err(err) => return Err(err),
}
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(Duration::from_secs(2));
};
if result.exit_code == 0 && result.stdout == format!("{nonce} missing").as_bytes() {
return Err(p.vm.no_such_process(&p.name));
}
if result.exit_code == 0 && result.stdout == format!("{nonce} lost").as_bytes() {
p.state.lost = true;
return Err(p.lost());
}
p.state.exit_code = Some(result.exit_code);
if self.check { result.check() } else { Ok(result) }
})
}
}
#[must_use = "a request does nothing until it is awaited"]
pub struct LogsRequest<'a> {
process: &'a Process,
tail: Option<usize>,
}
impl LogsRequest<'_> {
pub fn tail(mut self, lines: usize) -> Self {
self.tail = Some(lines);
self
}
}
impl<'a> IntoFuture for LogsRequest<'a> {
type Output = Result<Logs>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move {
let p = self.process;
let tail = self.tail.map(|n| n.to_string()).unwrap_or_default();
let result =
p.vm.script(&sh(LOGS_SCRIPT, &[&p.name, &tail]), usize::MAX, &[MISSING])
.await?;
if result.exit_code == MISSING {
return Err(p.vm.no_such_process(&p.name));
}
Ok(Logs {
stdout: result.stdout,
stderr: result.stderr,
})
})
}
}