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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
use chrono::Local;
use log::{debug, trace};
use serde::{Deserialize, Serialize};
use std::{
    io::{Read, Seek, SeekFrom},
    rc::Rc,
    time::Duration,
};
use subprocess::{Popen, PopenConfig, Redirection};
use tempfile;

/// Run a CLI command and store its stdout.
///
/// # Example
/// ```
/// # use usereport::command::{Command, CommandResult};
/// #[cfg(target_os = "macos")]
/// let command = Command::new("uname", r#"/usr/bin/uname -a"#)
///     .with_title("Host OS")
///     .with_timeout(5);
/// #[cfg(target_os = "linux")]
/// let command = Command::new("true", r#"/bin/true"#)
///     .with_title("Just a successful command")
///     .with_timeout(5);
/// match command.exec() {
///     CommandResult::Success {
///         command: _,
///         run_time_ms: _,
///         stdout: stdout,
///     } => println!("Command output '{}'", stdout),
///     CommandResult::Failed {
///         command: _,
///         run_time_ms: _,
///         stdout: stdout,
///     } => println!("Command failed with output '{}'", stdout),
///     CommandResult::Timeout {
///         command: _,
///         run_time_ms: _,
///     } => println!("Command timed out"),
///     CommandResult::Error {
///         command: _,
///         reason: reason,
///     } => println!("Command errored because {}", reason),
/// };
/// ```
#[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")]
    /// Timeout for command execution, defaults to 1 sec if not set
    pub(crate) timeout_sec: Option<u64>,
    pub(crate) links:       Option<Vec<Link>>,
}

impl Command {
    /// Create new command with default values
    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,
        }
    }

    /// Get name of command
    pub fn name(&self) -> &str { &self.name }

    /// Get command args
    pub fn command(&self) -> &str { &self.command }

    /// Get title of command
    pub fn title(&self) -> Option<&str> { self.title.as_ref().map(|x| x.as_str()) }

    /// Get description of command
    pub fn description(&self) -> Option<&str> { self.description.as_ref().map(|x| x.as_str()) }

    /// Set title of command
    pub fn with_title<T: Into<String>>(self, title: T) -> Command {
        Command {
            title: Some(title.into()),
            ..self
        }
    }

    /// Set title of command
    pub fn with_timeout<T: Into<Option<u64>>>(self, timeout_sec: T) -> Command {
        Command {
            timeout_sec: timeout_sec.into(),
            ..self
        }
    }

    /// Set description of command
    pub fn with_description<T: Into<String>, S: Into<Option<T>>>(self, description: S) -> Command {
        Command {
            description: description.into().map(Into::into),
            ..self
        }
    }

    /// Set Links of command
    pub fn with_links<T: Into<Option<Vec<Link>>>>(self, links: T) -> Command {
        Command {
            links: links.into(),
            ..self
        }
    }

    /// Execute this command; may panic
    ///
    /// Standard output and error will be written to a temporary file, because a pipe may only
    /// contain up 64 KB data; cf. http://man7.org/linux/man-pages/man7/pipe.7.html.
    pub fn exec(self) -> CommandResult {
        let args = match self.args() {
            Ok(args) => args,
            Err(_) => return self.fail("failed to split command into arguments"),
        };
        let mut tmpfile = match tempfile::tempfile() {
            Ok(f) => Rc::new(f),
            Err(err) => return self.fail(err),
        };
        let popen_config = PopenConfig {
            stdout: Redirection::RcFile(Rc::clone(&tmpfile)),
            stderr: Redirection::Merge,
            ..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 self.fail(err),
        };
        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;

        if let Err(err) = Rc::get_mut(&mut tmpfile).unwrap().seek(SeekFrom::Start(0)) {
            // TODO: unwrap is unsafe
            return self.fail(err);
        };
        match wait {
            Ok(Some(status)) if status.success() => {
                debug!(
                    "{:?} process successfully finished as {:?} with {} bytes output",
                    args,
                    status,
                    tmpfile.metadata().unwrap().len()
                );
                let mut stdout = String::new();
                if let Err(err) = Rc::get_mut(&mut tmpfile).unwrap().read_to_string(&mut stdout) {
                    // TODO: unwrap is unsafe
                    return self.fail(err);
                };
                trace!("stdout '{}'", stdout);

                CommandResult::Success {
                    command: self,
                    run_time_ms,
                    stdout,
                }
            }
            Ok(Some(status)) => {
                debug!("{:?} process finished as {:?}", args, status);
                let mut stdout = String::new();
                if let Err(err) = Rc::get_mut(&mut tmpfile).unwrap().read_to_string(&mut stdout) {
                    // TODO: unwrap is unsafe
                    return self.fail(err);
                };
                trace!("stdout '{}'", stdout);
                CommandResult::Failed {
                    command: self,
                    run_time_ms,
                    stdout,
                }
            }
            Ok(None) => {
                debug!("{:?} process timed out and will be killed", args);
                self.terminate(&mut p);
                CommandResult::Timeout {
                    command: self,
                    run_time_ms,
                }
            }
            Err(err) => {
                debug!("{:?} process failed '{:?}'", args, err);
                self.terminate(&mut p);
                CommandResult::Error {
                    command: self,
                    reason:  err.to_string(),
                }
            }
        }
    }

    /// Fail with error message
    fn fail<T: ToString>(self, reason: T) -> CommandResult {
        CommandResult::Error {
            command: self,
            reason:  reason.to_string(),
        }
    }

    fn args(&self) -> Result<Vec<String>, shellwords::MismatchedQuotes> { shellwords::split(&self.command) }

    /// Panics
    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 }
}

/// Encapsulates a command execution result
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize, Clone)]
pub enum CommandResult {
    /// `Command` has been executed successfully and `String` contains stdout.
    Success {
        command:     Command,
        run_time_ms: u64,
        stdout:      String,
    },
    /// `Command` failed to execute
    Failed {
        command:     Command,
        run_time_ms: u64,
        stdout:      String,
    },
    /// `Command` execution exceeded specified timeout
    Timeout { command: Command, run_time_ms: u64 },
    /// `Command` could not be executed
    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")
    }

    #[test]
    fn command_split() {
        init();

        let command = Command::new("no_such_command", r#"/bin/sleep 5"#);
        let args = command.args();

        asserting("splitting command into args")
            .that(&args)
            .is_ok()
            .has_length(2);
    }

    #[test]
    fn command_split_single_quotes() {
        init();

        let command = Command::new("no_such_command", r#"sh -c 'dmesg -T | grep "failed"'"#);
        let args = command.args();

        asserting("splitting command into args")
            .that(&args)
            .is_ok()
            .has_length(3);
    }

    #[test]
    fn command_split_double_quotes() {
        init();

        let command = Command::new("no_such_command", r#"sh -c "dmesg -T | tail""#);
        let args = command.args();

        asserting("splitting command into args")
            .that(&args)
            .is_ok()
            .has_length(3);
    }
}