1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use chrono::Local;
use log::{debug, trace};
use serde::{Deserialize, Serialize};
use std::{io::Read, time::Duration};
use subprocess::{Popen, PopenConfig, Redirection};
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize, Clone)]
pub struct Command {
pub(crate) name: String,
pub(crate) title: Option<String>,
pub(crate) description: Option<String>,
pub(crate) command: String,
#[serde(rename = "timeout")]
pub(crate) timeout_sec: Option<u64>,
pub(crate) links: Option<Vec<Link>>,
}
impl Command {
pub fn new<T: Into<String>>(name: T, command: T) -> Command {
Command {
name: name.into(),
title: None,
description: None,
command: command.into(),
timeout_sec: None,
links: None,
}
}
pub fn name(&self) -> &str { &self.name }
pub fn command(&self) -> &str { &self.command }
pub fn title(&self) -> Option<&str> { self.title.as_ref().map(|x| x.as_str()) }
pub fn description(&self) -> Option<&str> { self.description.as_ref().map(|x| x.as_str()) }
pub fn with_title<T: Into<String>>(self, title: T) -> Command {
Command {
title: Some(title.into()),
..self
}
}
pub fn with_timeout<T: Into<Option<u64>>>(self, timeout_sec: T) -> Command {
Command {
timeout_sec: timeout_sec.into(),
..self
}
}
pub fn with_description<T: Into<String>, S: Into<Option<T>>>(self, description: S) -> Command {
Command {
description: description.into().map(Into::into),
..self
}
}
pub fn with_links<T: Into<Option<Vec<Link>>>>(self, links: T) -> Command {
Command {
links: links.into(),
..self
}
}
pub fn exec(self) -> CommandResult {
let args: Vec<_> = self.command.split(' ').collect();
let popen_config = PopenConfig {
stdout: Redirection::Pipe,
..Default::default()
};
let start_time = Local::now();
let popen = Popen::create(&args, popen_config);
let mut p = match popen {
Ok(p) => p,
Err(err) => {
return CommandResult::Error {
command: self,
reason: err.to_string(),
};
}
};
debug!("Running '{:?}' as '{:?}'", args, p);
let wait = p.wait_timeout(Duration::new(self.timeout_sec.unwrap_or(1), 0));
let run_time_ms = (Local::now() - start_time).num_milliseconds() as u64;
match wait {
Ok(Some(status)) if status.success() => {
trace!("process successfully finished as {:?}", status);
let mut stdout = String::new();
let _ = p.stdout.as_ref().unwrap().read_to_string(&mut stdout);
debug!("stdout '{}'", stdout);
CommandResult::Success {
command: self,
run_time_ms,
stdout,
}
}
Ok(Some(status)) => {
trace!("process successfully finished as {:?}", status);
CommandResult::Failed {
command: self,
run_time_ms,
}
}
Ok(None) => {
trace!("process timed out and will be killed");
self.terminate(&mut p);
CommandResult::Timeout {
command: self,
run_time_ms,
}
}
Err(err) => {
trace!("process failed '{:?}'", err);
self.terminate(&mut p);
CommandResult::Error {
command: self,
reason: err.to_string(),
}
}
}
}
fn terminate(&self, p: &mut Popen) {
p.kill().expect("failed to kill command");
p.wait().expect("failed to wait for command to finish");
trace!("process killed");
}
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize, Clone)]
pub struct Link {
pub(crate) name: String,
pub(crate) url: String,
}
impl Link {
pub fn new<T: Into<String>>(name: T, url: T) -> Link {
Link {
name: name.into(),
url: url.into(),
}
}
pub fn name(&self) -> &str { &self.name }
pub fn url(&self) -> &str { &self.url }
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize, Clone)]
pub enum CommandResult {
Success {
command: Command,
run_time_ms: u64,
stdout: String,
},
Failed { command: Command, run_time_ms: u64 },
Timeout { command: Command, run_time_ms: u64 },
Error { command: Command, reason: String },
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::*;
use spectral::prelude::*;
#[test]
fn execution_ok() {
init();
#[cfg(target_os = "macos")]
let command = Command::new("true", r#"/usr/bin/true"#);
#[cfg(target_os = "linux")]
let command = Command::new("true", r#"/bin/true"#);
let res = command.exec();
asserting("executing command successfully")
.that(&res)
.is_success_contains("");
}
#[test]
fn execution_failed() {
init();
#[cfg(target_os = "macos")]
let command = Command::new("false", r#"/usr/bin/false"#);
#[cfg(target_os = "linux")]
let command = Command::new("false", r#"/bin/false"#);
let res = command.exec();
asserting("executing command successfully").that(&res).is_failed();
}
#[test]
fn execution_timeout() {
init();
let command = Command::new("sleep", r#"/bin/sleep 5"#).with_timeout(1);
let res = command.exec();
asserting("executing command successfully").that(&res).is_timeout();
}
#[test]
fn execution_error() {
init();
let command = Command::new("no_such_command", r#"/no_such_command"#);
let res = command.exec();
asserting("executing command errors")
.that(&res)
.is_error_contains("No such file or directory")
}
}