use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
use super::cleanup::cancel_flag;
use super::{runner_dir, validate_name};
use crate::cli::Cli;
use crate::error::{Error, Result};
use crate::runner::process;
const POLL: Duration = Duration::from_millis(200);
pub fn run(cli: &Cli) -> Result<()> {
validate_name(&cli.name)?;
let dir = runner_dir(cli);
let cancelled = cancel_flag()?;
monitor(&dir, &cli.name, &cancelled)
}
pub(crate) fn monitor(dir: &Path, name: &str, cancelled: &AtomicBool) -> Result<()> {
let log_path = process::log_path(dir);
let mut file = File::open(&log_path).map_err(|error| {
Error::Config(format!("could not open {}: {error}", log_path.display()))
})?;
let mut buffer = [0_u8; 8 * 1024];
loop {
if cancelled.load(Ordering::SeqCst) {
tracing::info!("stopped monitoring runner `{name}`");
return Ok(());
}
let length = file.metadata()?.len();
let position = file.stream_position()?;
if length < position {
file.seek(SeekFrom::Start(0))?;
}
let read = file.read(&mut buffer)?;
if read > 0 {
let mut stdout = std::io::stdout();
stdout.write_all(&buffer[..read])?;
stdout.flush()?;
} else {
thread::sleep(POLL);
}
}
}
#[cfg(test)]
mod tests {
use std::fs;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use super::monitor;
#[test]
fn prints_existing_content_then_stops() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join(".octorun.log"), b"hello\n").unwrap();
let cancelled = Arc::new(AtomicBool::new(false));
let setter = Arc::clone(&cancelled);
let handle = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(300));
setter.store(true, Ordering::SeqCst);
});
monitor(dir.path(), "runner", &cancelled).unwrap();
handle.join().unwrap();
}
#[test]
fn stops_when_cancelled() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join(".octorun.log"), b"hello\n").unwrap();
monitor(dir.path(), "runner", &AtomicBool::new(true)).unwrap();
}
#[test]
fn reports_a_missing_log() {
let dir = tempfile::tempdir().unwrap();
assert!(monitor(dir.path(), "runner", &AtomicBool::new(false)).is_err());
}
}