Move starting of tasks into a helper struct

This commit is contained in:
Dennis
2024-06-02 16:34:05 +02:00
parent 9fff420a1a
commit 7f7aa3dc2c
3 changed files with 80 additions and 38 deletions
+1
View File
@@ -5,3 +5,4 @@ pub mod osm;
pub mod osm_db;
pub mod osrm_world;
pub mod scenario_id;
pub mod task_starter;
+65
View File
@@ -0,0 +1,65 @@
use std::{
io::{BufRead, BufReader},
process::{Child, Command, Stdio},
};
#[derive(Default)]
pub struct TaskStarter {
ready: bool,
command: String,
arguments: Vec<String>,
child: Option<Child>,
}
impl TaskStarter {
pub fn new(command: &str) -> Self {
Self {
ready: false,
command: command.into(),
arguments: Vec::new(),
child: None,
}
}
pub fn is_ready(&self) -> bool {
self.ready
}
pub fn arg(&mut self, argument: &str) -> &mut Self {
self.arguments.push(argument.into());
self
}
pub fn spawn_wait_till_ready(&mut self, ready_token: &str) {
// TODO: move the child handling into a convenience struct
let mut command = &mut Command::new(&self.command);
for argument in &self.arguments {
command = command.arg(argument);
}
match command.stdout(Stdio::piped()).spawn() {
Ok(o) => self.child = Some(o),
Err(e) => panic!("cannot spawn task: {e}"),
}
if let Some(output) = &mut self.child.as_mut().unwrap().stdout {
// implement with a timeout
let mut reader = BufReader::new(output);
let mut line = String::new();
while let Ok(_count) = reader.read_line(&mut line) {
// println!("count: {count} ->{line}");
if line.contains(ready_token) {
self.ready = true;
break;
}
}
}
}
}
impl Drop for TaskStarter {
fn drop(&mut self) {
if let Err(e) = self.child.as_mut().expect("can't access child").kill() {
panic!("shutdown failed: {e}");
}
}
}