From 132bc6311f6c4d6a6e587b80290a111fa5f63544 Mon Sep 17 00:00:00 2001 From: rasul Date: Fri, 25 Oct 2019 12:53:26 -0500 Subject: [PATCH] watch for stdout and stderr --- src/main.rs | 81 +++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 66 insertions(+), 15 deletions(-) diff --git a/src/main.rs b/src/main.rs index 487a220..a623d03 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,7 @@ use std::error::Error; use std::fs::File; use std::io::Read; use std::path::PathBuf; -use std::process::{Child, Command, ExitStatus}; +use std::process::{Child, Command, ExitStatus, Stdio}; type SupResult = Result>; @@ -36,24 +36,21 @@ impl App { match command.output() { Ok(output) => { if !output.stdout.is_empty() { - info!( - "[{}] stdout: {}", - &self.name, - String::from_utf8(output.stdout)? - ); + let s = String::from_utf8(output.stdout)?; + for line in s.lines() { + info!("[{}] stdout: {}", &self.name, line); + } } if !output.stderr.is_empty() { - info!( - "[{}] stderr: {}", - &self.name, - String::from_utf8(output.stderr)? - ); + let s = String::from_utf8(output.stderr)?; + for line in s.lines() { + info!("[{}] stderr: {}", &self.name, line); + } } + Ok(()) } - Err(e) => error!("Error starting app: {}: {:?}", &self.name, e), + Err(e) => Err(Box::from(e)), } - - Ok(()) } } @@ -85,12 +82,56 @@ impl Proc { info!("starting application {}", &app.name); let mut command = Command::new(&app.command); + command.stdout(Stdio::piped()); + command.stderr(Stdio::piped()); command.args(&app.args); let child = command.spawn()?; Ok(Proc { app, child }) } + + fn check_stdout(&mut self) -> Option { + let child_stdout = self.child.stdout.as_mut(); + if let Some(stdout) = child_stdout { + let mut buf = String::new(); + match stdout.read_to_string(&mut buf) { + Ok(size) => { + if size > 0 { + return Some(buf); + } else { + return None; + } + } + Err(e) => { + error!("couldn't read stdout from {}: {:?}", &self.app.name, e); + return None; + } + } + } + None + } + + fn check_stderr(&mut self) -> Option { + let child_stderr = self.child.stderr.as_mut(); + if let Some(stderr) = child_stderr { + let mut buf = String::new(); + match stderr.read_to_string(&mut buf) { + Ok(size) => { + if size > 0 { + return Some(buf); + } else { + return None; + } + } + Err(e) => { + error!("couldn't read stderr from {}: {:?}", &self.app.name, e); + return None; + } + } + } + None + } } fn main() { @@ -105,6 +146,7 @@ fn main() { } } +#[allow(clippy::cognitive_complexity)] fn run() -> SupResult<()> { let config = Config::load("sup.toml")?; info!("loaded config: sup.toml"); @@ -159,12 +201,21 @@ fn run() -> SupResult<()> { } } Ok(None) => { + if let Some(s) = &proc.check_stdout() { + for line in s.lines() { + info!("[{}] stdout: {}", &proc.app.name, line); + } + } + if let Some(s) = &proc.check_stderr() { + for line in s.lines() { + info!("[{}] stderr: {}", &proc.app.name, line); + } + } newprocs.push(proc); } Err(e) => error!("error: {:?}", e), } } - procs = newprocs; }