|
| 1 | +//! Custom wrapper for Command that supports timeouts and contains custom error handling. |
| 2 | +
|
| 3 | +use crate::{Result, TmcError}; |
| 4 | +use std::io::Read; |
| 5 | +use std::ops::{Deref, DerefMut}; |
| 6 | +use std::path::PathBuf; |
| 7 | +use std::process::{Command, ExitStatus, Output, Stdio}; |
| 8 | +use std::thread; |
| 9 | +use std::time::{Duration, Instant}; |
| 10 | + |
| 11 | +// todo: collect args? |
| 12 | +pub struct TmcCommand { |
| 13 | + name: &'static str, |
| 14 | + path: PathBuf, |
| 15 | + command: Command, |
| 16 | +} |
| 17 | + |
| 18 | +impl TmcCommand { |
| 19 | + pub fn new(name: &'static str) -> Self { |
| 20 | + let path = PathBuf::from(name); |
| 21 | + Self { |
| 22 | + command: Command::new(&path), |
| 23 | + name, |
| 24 | + path, |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + pub fn named<P: Into<PathBuf>>(name: &'static str, path: P) -> Self { |
| 29 | + let path = path.into(); |
| 30 | + Self { |
| 31 | + command: Command::new(&path), |
| 32 | + name, |
| 33 | + path, |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + // shadows command's status |
| 38 | + pub fn status(&mut self) -> Result<ExitStatus> { |
| 39 | + self.deref_mut().status().map_err(|e| { |
| 40 | + if let std::io::ErrorKind::NotFound = e.kind() { |
| 41 | + TmcError::CommandNotFound(crate::error::CommandNotFound { |
| 42 | + name: self.name, |
| 43 | + path: self.path.clone(), |
| 44 | + source: e, |
| 45 | + }) |
| 46 | + } else { |
| 47 | + TmcError::CommandFailed(self.name, e) |
| 48 | + } |
| 49 | + }) |
| 50 | + } |
| 51 | + |
| 52 | + // shadows command's output |
| 53 | + pub fn output(&mut self) -> Result<Output> { |
| 54 | + self.deref_mut().output().map_err(|e| { |
| 55 | + if let std::io::ErrorKind::NotFound = e.kind() { |
| 56 | + TmcError::CommandNotFound(crate::error::CommandNotFound { |
| 57 | + name: self.name, |
| 58 | + path: self.path.clone(), |
| 59 | + source: e, |
| 60 | + }) |
| 61 | + } else { |
| 62 | + TmcError::CommandFailed(self.name, e) |
| 63 | + } |
| 64 | + }) |
| 65 | + } |
| 66 | + |
| 67 | + /// Waits with the given timeout. Sets stdout and stderr in order to capture them after erroring. |
| 68 | + pub fn wait_with_timeout(&mut self, timeout: Duration) -> Result<OutputWithTimeout> { |
| 69 | + // spawn process and init timer |
| 70 | + let mut child = self |
| 71 | + .stdout(Stdio::piped()) |
| 72 | + .stderr(Stdio::piped()) |
| 73 | + .spawn() |
| 74 | + .map_err(|e| TmcError::CommandSpawn(self.name, e))?; |
| 75 | + let timer = Instant::now(); |
| 76 | + |
| 77 | + loop { |
| 78 | + match child.try_wait().map_err(TmcError::Process)? { |
| 79 | + Some(_exit_status) => { |
| 80 | + // done, get output |
| 81 | + return child |
| 82 | + .wait_with_output() |
| 83 | + .map(OutputWithTimeout::Output) |
| 84 | + .map_err(|e| { |
| 85 | + if let std::io::ErrorKind::NotFound = e.kind() { |
| 86 | + TmcError::CommandNotFound(crate::error::CommandNotFound { |
| 87 | + name: self.name, |
| 88 | + path: self.path.clone(), |
| 89 | + source: e, |
| 90 | + }) |
| 91 | + } else { |
| 92 | + TmcError::CommandFailed(self.name, e) |
| 93 | + } |
| 94 | + }); |
| 95 | + } |
| 96 | + None => { |
| 97 | + // still running, check timeout |
| 98 | + if timer.elapsed() > timeout { |
| 99 | + log::warn!("command {} timed out", self.name); |
| 100 | + // todo: cleaner method for killing |
| 101 | + child.kill().map_err(TmcError::Process)?; |
| 102 | + |
| 103 | + let mut stdout = vec![]; |
| 104 | + let mut stderr = vec![]; |
| 105 | + let stdout_handle = child.stdout.as_mut().unwrap(); |
| 106 | + let stderr_handle = child.stderr.as_mut().unwrap(); |
| 107 | + stdout_handle.read_to_end(&mut stdout).unwrap(); |
| 108 | + stderr_handle.read_to_end(&mut stderr).unwrap(); |
| 109 | + return Ok(OutputWithTimeout::Timeout { stdout, stderr }); |
| 110 | + } |
| 111 | + |
| 112 | + // TODO: gradually increase sleep duration? |
| 113 | + thread::sleep(Duration::from_millis(100)); |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +impl Deref for TmcCommand { |
| 121 | + type Target = Command; |
| 122 | + |
| 123 | + fn deref(&self) -> &Self::Target { |
| 124 | + &self.command |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +impl DerefMut for TmcCommand { |
| 129 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 130 | + &mut self.command |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +pub enum OutputWithTimeout { |
| 135 | + Output(Output), |
| 136 | + Timeout { stdout: Vec<u8>, stderr: Vec<u8> }, |
| 137 | +} |
| 138 | + |
| 139 | +impl OutputWithTimeout { |
| 140 | + pub fn stdout(&self) -> &[u8] { |
| 141 | + match self { |
| 142 | + Self::Output(output) => &output.stdout, |
| 143 | + Self::Timeout { stdout, .. } => &stdout, |
| 144 | + } |
| 145 | + } |
| 146 | + pub fn stderr(&self) -> &[u8] { |
| 147 | + match self { |
| 148 | + Self::Output(output) => &output.stderr, |
| 149 | + Self::Timeout { stderr, .. } => &stderr, |
| 150 | + } |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +#[cfg(test)] |
| 155 | +mod test { |
| 156 | + use super::*; |
| 157 | + |
| 158 | + #[test] |
| 159 | + fn timeout() { |
| 160 | + let mut cmd = TmcCommand::new("sleep"); |
| 161 | + cmd.arg("1"); |
| 162 | + let res = cmd.wait_with_timeout(Duration::from_millis(100)).unwrap(); |
| 163 | + if let OutputWithTimeout::Timeout { .. } = res { |
| 164 | + } else { |
| 165 | + panic!("unexpected result"); |
| 166 | + } |
| 167 | + } |
| 168 | +} |
0 commit comments