evobench_tools/run/
stop_start_status.rs

1use anyhow::{Result, bail};
2use std::process::Command;
3
4use crate::{ctx, debug, info};
5
6// Move, where?
7pub fn run_command(cmd: &[String], start_stop: &str) -> Result<()> {
8    assert!(
9        !cmd.is_empty(),
10        "start_stop should have been checked in `check_run_queues` already"
11    );
12    let mut cmd: Vec<&str> = cmd.iter().map(|s| s.as_str()).collect();
13    cmd.push(start_stop);
14    info!("running command {cmd:?}");
15    let mut command = Command::new(cmd[0]);
16    command.args(&cmd[1..]);
17    // XX consistent capture?
18    let status = command.status().map_err(ctx!("running {cmd:?}"))?;
19    if status.success() {
20        Ok(())
21    } else {
22        bail!("command {cmd:?} gave status {status}")
23    }
24}
25
26#[derive(Default)]
27pub struct StopStartStatus {
28    /// A running stop action, if any. To be finished (i.e. "start"
29    /// sent to) on changes.
30    current_stop_start: Option<Box<[String]>>,
31}
32
33impl StopStartStatus {
34    /// Request the status to be the given `stop_start` argument;
35    /// `None` means, no `stop_start` command is to be open, if given
36    /// means the given command is to be open (i.e. between having
37    /// been sent "stop" and "start").
38    pub fn be(&mut self, stop_start: Option<&[String]>) -> Result<()> {
39        if stop_start == self.current_stop_start.as_deref() {
40            debug!("no change in stop_start command, leave it as is");
41            Ok(())
42        } else {
43            if let Some(cmd) = &self.current_stop_start {
44                info!("change in stop_start command: end the previous period");
45                run_command(cmd.as_ref(), "start")?;
46            }
47            if let Some(cmd) = &stop_start {
48                info!("change in stop_start command: begin a new period");
49                run_command(cmd.as_ref(), "stop")?;
50            }
51            self.current_stop_start = stop_start.map(|l| l.into());
52            Ok(())
53        }
54    }
55}