use anyhow::{Context, Result}; use libc; use std::collections::HashMap; use std::path::PathBuf; use std::process::Stdio; use std::time::Duration; use tokio::io::{AsyncBufReadExt, BufReader}; use tokio::process::Command; use tokio::time::{sleep, timeout}; use crate::core::config::{DATABASE_SCHEMA, OUTPUT_DIR, REDIS_KEY_PREFIX}; /// Get face processor settings from admin config (priority) or environment variables. /// Returns (min_confidence, min_size, min_capture_quality) as Option. async fn get_face_settings() -> (Option, Option, Option) { let face_config = crate::core::admin_config::get_processor_config("face").await; let min_confidence = face_config .as_ref() .and_then(|c| c.min_confidence) .map(|v| v.to_string()) .or_else(|| std::env::var("FACE_MIN_CONFIDENCE").ok()); let min_size = face_config .as_ref() .and_then(|c| c.min_size) .map(|v| v.to_string()) .or_else(|| std::env::var("FACE_MIN_SIZE").ok()); let min_capture_quality = face_config .as_ref() .and_then(|c| c.min_capture_quality) .map(|v| v.to_string()) .or_else(|| std::env::var("FACE_MIN_CAPTURE_QUALITY").ok()); (min_confidence, min_size, min_capture_quality) } #[derive(Debug, Clone)] pub struct RetryConfig { pub max_attempts: u32, pub initial_delay_ms: u64, pub max_delay_ms: u64, pub backoff_multiplier: f64, } impl Default for RetryConfig { fn default() -> Self { Self { max_attempts: 3, initial_delay_ms: 1000, max_delay_ms: 30000, backoff_multiplier: 2.0, } } } impl RetryConfig { pub fn new(max_attempts: u32) -> Self { Self { max_attempts, ..Default::default() } } pub fn with_delay(mut self, delay_ms: u64) -> Self { self.initial_delay_ms = delay_ms; self } pub fn with_max_delay(mut self, max_delay_ms: u64) -> Self { self.max_delay_ms = max_delay_ms; self } } /// Load SHA256 checksums from checksums.sha256 manifest. /// Returns a map of relative path → expected hash. fn load_checksums(scripts_dir: &PathBuf) -> HashMap { let path = scripts_dir.join("checksums.sha256"); let mut map = HashMap::new(); match std::fs::read_to_string(&path) { Ok(content) => { for line in content.lines() { let line = line.trim(); if line.is_empty() { continue; } if let Some((hash, rel_path)) = line.split_once(' ') { let hash = hash.trim().to_string(); let rel_path = rel_path.trim().to_string(); if !hash.is_empty() && !rel_path.is_empty() { map.insert(rel_path, hash); } } } tracing::info!( "[CHECKSUMS] Loaded {} entries from checksums.sha256", map.len() ); } Err(e) => { tracing::warn!( "[CHECKSUMS] Could not load checksums.sha256: {} — integrity checks disabled", e ); } } map } pub fn validate_python_env() -> Result<()> { let python_path = std::env::var("MOMENTRY_PYTHON_PATH") .unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string()); let python_bin = PathBuf::from(&python_path); if !python_bin.exists() { anyhow::bail!( "Python not found at {} (set MOMENTRY_PYTHON_PATH env var)", python_path ); } let rt = tokio::runtime::Runtime::new()?; let output = rt .block_on(async { Command::new(&python_bin).arg("--version").output().await }) .context("Failed to run Python")?; if !output.status.success() { anyhow::bail!("Python validation failed"); } let version = String::from_utf8_lossy(&output.stdout); tracing::info!("Python version: {}", version.trim()); if !version.contains("3.11") { tracing::warn!("Expected Python 3.11, got: {}", version.trim()); } let scripts_dir = std::env::var("MOMENTRY_SCRIPTS_DIR").unwrap_or_else(|_| { let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR")); manifest.join("scripts").to_string_lossy().to_string() }); let script_path = PathBuf::from(&scripts_dir); if !script_path.exists() { anyhow::bail!("Scripts directory not found at {}", scripts_dir); } tracing::info!("Python environment validated successfully"); Ok(()) } pub struct PythonExecutor { python_path: PathBuf, scripts_dir: PathBuf, checksums: HashMap, } impl PythonExecutor { pub fn new() -> Result { let python_path = std::env::var("MOMENTRY_PYTHON_PATH") .unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string()); let scripts_dir = std::env::var("MOMENTRY_SCRIPTS_DIR").unwrap_or_else(|_| { let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR")); manifest.join("scripts").to_string_lossy().to_string() }); let python_bin = PathBuf::from(&python_path); let scripts_path = PathBuf::from(&scripts_dir); if !python_bin.exists() { anyhow::bail!( "Python not found at {} (set MOMENTRY_PYTHON_PATH env var)", python_path ); } if !scripts_path.exists() { anyhow::bail!( "Scripts directory not found at {} (set MOMENTRY_SCRIPTS_DIR env var)", scripts_dir ); } // Load SHA256 checksums manifest let checksums = load_checksums(&scripts_path); Ok(Self { python_path: python_bin, scripts_dir: scripts_path, checksums, }) } /// Compute 8Hz sample frames from total frames and FPS. /// Returns frames at approximately 8 samples per second. pub fn compute_8hz_frames(total_frames: i64, fps: f64) -> Vec { let interval = (fps / 8.0).round() as i64; let interval = interval.max(1); (0..total_frames).step_by(interval as usize).collect() } pub fn compute_hz_frames(total_frames: i64, fps: f64, hz: f64) -> Vec { let interval = (fps / hz).round() as i64; let interval = interval.max(1); (0..total_frames).step_by(interval as usize).collect() } /// Merge base frames with refinement frames (for adaptive sampling). pub fn merge_refine_frames(base: &[i64], refine: &std::collections::HashSet) -> Vec { let mut combined: std::collections::HashSet = base.iter().cloned().collect(); combined.extend(refine.iter().cloned()); let mut sorted: Vec = combined.into_iter().collect(); sorted.sort(); sorted } /// Format frame list as comma-separated string for --frames argument. pub fn format_frames_arg(frames: &[i64]) -> String { frames .iter() .map(|f| f.to_string()) .collect::>() .join(",") } /// Get the scripts directory path pub fn script_dir(&self) -> &std::path::PathBuf { &self.scripts_dir } /// Verify a script's SHA256 against the checksums manifest before execution. pub fn verify_script_integrity(&self, script_name: &str) -> Result<()> { let script_path = self.scripts_dir.join(script_name); let rel_path = format!("./{}", script_name); if let Some(expected_hash) = self.checksums.get(&rel_path) { let output = std::process::Command::new("shasum") .arg("-a") .arg("256") .arg(&script_path) .output() .context("Failed to run shasum for integrity check")?; let actual = String::from_utf8_lossy(&output.stdout); let actual_hash = actual.split(' ').next().unwrap_or("").trim().to_string(); if actual_hash.is_empty() || actual_hash != *expected_hash { anyhow::bail!( "Script integrity check FAILED for {}: hash mismatch\n Expected: {}\n Actual: {}\n Run: bash scripts/setup/check_momentry.sh", script_name, expected_hash, actual_hash ); } tracing::debug!("[INTEGRITY] {} checksum OK", script_name); } else { tracing::warn!( "[INTEGRITY] {} not in checksums.sha256 manifest — skipping verification", script_name ); } Ok(()) } pub fn validate_env(&self) -> Result<()> { let rt = tokio::runtime::Runtime::new()?; let output = rt .block_on(async { Command::new(&self.python_path) .arg("--version") .output() .await }) .context("Failed to run Python")?; if !output.status.success() { anyhow::bail!("Python validation failed"); } let version = String::from_utf8_lossy(&output.stdout); if !version.contains("3.11") { tracing::warn!("Python version mismatch: {}", version); } Ok(()) } /// Run a Python script. `output_idx` specifies which arg index is the output /// file path (rewritten to `.json.tmp` during execution, promoted on success). /// Pass `None` if the script determines its own output path (e.g. from `--file-uuid`). pub async fn run( &self, script_name: &str, args: &[&str], uuid: Option<&str>, log_prefix: &str, timeout_duration: Option, ) -> Result<()> { self.run_with_output_idx( script_name, args, uuid, log_prefix, timeout_duration, Some(1), ) .await } /// Run a script with optional frame list for 8Hz sampling. /// If frames is provided, passes --frames=0,4,8,... to the script. pub async fn run_with_frames( &self, script_name: &str, args: &[&str], uuid: Option<&str>, log_prefix: &str, timeout_duration: Option, frames: Option<&[i64]>, ) -> Result<()> { let script_path = self.scripts_dir.join(script_name); if !script_path.exists() { anyhow::bail!("Script not found: {:?}", script_path); } self.verify_script_integrity(script_name).context( "Pre-execution integrity check failed — possible version mismatch or corruption", )?; let output_idx = 1; let output_path = args.get(output_idx).map(|p| std::path::PathBuf::from(p)); let tmp_path = output_path.as_ref().map(|p| { let mut tmp = p.to_path_buf(); tmp.set_extension("json.tmp"); tmp }); let mut cmd = Command::new(&self.python_path); cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR); cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX); // Pass Qdrant credentials to Python subprocesses if let Ok(qdrant_url) = std::env::var("QDRANT_URL") { cmd.env("QDRANT_URL", qdrant_url); } if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") { cmd.env("QDRANT_API_KEY", qdrant_api_key); } if let Some(u) = uuid { cmd.env("UUID", u); } // Pass face detection settings to Python subprocesses let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok(); let face_min_size = std::env::var("FACE_MIN_SIZE").ok(); tracing::info!( "[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}", face_min_confidence, face_min_size ); if let Some(ref val) = face_min_confidence { cmd.env("FACE_MIN_CONFIDENCE", val); } if let Some(ref val) = face_min_size { cmd.env("FACE_MIN_SIZE", val); } cmd.arg(&script_path); for (i, arg) in args.iter().enumerate() { // Route the script's declared output path through a .tmp file so the // fresh result is written there and promoted to the real path only on // success (avoids clobbering good output with a stale/partial file). if i == output_idx { if let Some(ref tmp) = tmp_path { cmd.arg(tmp); continue; } } cmd.arg(arg); } if let Some(u) = uuid { cmd.arg("--uuid").arg(u); } // Pass frame list for 8Hz sampling (only if non-empty) if let Some(frames) = frames { if !frames.is_empty() { let frames_str = Self::format_frames_arg(frames); cmd.arg("--frames").arg(&frames_str); tracing::info!("[{}] 8Hz sampling: {} frames", log_prefix, frames.len()); } else { tracing::info!( "[{}] 8Hz sampling: 0 frames (skipping --frames arg)", log_prefix ); } } cmd.stdout(Stdio::piped()); cmd.stderr(Stdio::piped()); cmd.kill_on_drop(true); cmd.process_group(0); tracing::info!("[{}] Starting: {:?}", log_prefix, script_name); let mut child = cmd .spawn() .with_context(|| format!("Failed to run {}", script_name))?; let child_pid = child.id(); let stdout = child.stdout.take().context("Failed to capture stdout")?; let stderr = child.stderr.take().context("Failed to capture stderr")?; let mut stdout_reader = BufReader::new(stdout).lines(); let mut stderr_reader = BufReader::new(stderr).lines(); let run_future = async { let mut stdout_done = false; let mut stderr_done = false; loop { if !stdout_done { match stdout_reader .next_line() .await .context("Failed to read stdout")? { Some(line) => tracing::info!("[{}] {}", log_prefix, line), None => stdout_done = true, } } if !stderr_done { match stderr_reader .next_line() .await .context("Failed to read stderr")? { Some(line) => tracing::warn!("[{}] {}", log_prefix, line), None => stderr_done = true, } } if stdout_done && stderr_done { break; } } let status = child.wait().await?; Ok::<_, anyhow::Error>(status) }; let timeout_duration = timeout_duration.unwrap_or(Duration::from_secs(3600)); let status = timeout(timeout_duration, run_future) .await .map_err(|e| anyhow::anyhow!("Timeout after {}s: {}", timeout_duration.as_secs(), e))? .with_context(|| format!("Failed to run {}", script_name))?; // Kill entire process group on failure if !status.success() { if let Some(pid) = child_pid { unsafe { libc::kill(-(pid as i32), libc::SIGTERM); } } anyhow::bail!("Script {} failed with exit status: {}", script_name, status); } // Rename .json.tmp back to .json on success if let (Some(src), Some(dst)) = (&tmp_path, &output_path) { if src.exists() { let _ = std::fs::rename(src, dst); } } Ok(()) } pub async fn run_with_output_idx( &self, script_name: &str, args: &[&str], uuid: Option<&str>, log_prefix: &str, timeout_duration: Option, output_idx: Option, ) -> Result<()> { let script_path = self.scripts_dir.join(script_name); if !script_path.exists() { anyhow::bail!("Script not found: {:?}", script_path); } // Verify script integrity via SHA256 checksum before execution self.verify_script_integrity(script_name).context( "Pre-execution integrity check failed — possible version mismatch or corruption", )?; let output_path = output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p))); let tmp_path = output_path.as_ref().map(|p| { let mut tmp = p.to_path_buf(); tmp.set_extension("json.tmp"); tmp }); let mut cmd = Command::new(&self.python_path); cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR); cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX); // Pass Qdrant credentials to Python subprocesses if let Ok(qdrant_url) = std::env::var("QDRANT_URL") { cmd.env("QDRANT_URL", qdrant_url); } if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") { cmd.env("QDRANT_API_KEY", qdrant_api_key); } if let Some(u) = uuid { cmd.env("UUID", u); } // Pass face detection settings to Python subprocesses let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok(); let face_min_size = std::env::var("FACE_MIN_SIZE").ok(); tracing::info!( "[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}", face_min_confidence, face_min_size ); if let Some(ref val) = face_min_confidence { cmd.env("FACE_MIN_CONFIDENCE", val); } if let Some(ref val) = face_min_size { cmd.env("FACE_MIN_SIZE", val); } cmd.arg(&script_path); for (i, arg) in args.iter().enumerate() { // Route the script's declared output path through a .tmp file so the // fresh result is written there and promoted to the real path only on // success (avoids clobbering good output with a stale/partial file). if Some(i) == output_idx { if let Some(ref tmp) = tmp_path { cmd.arg(tmp); continue; } } cmd.arg(arg); } if let Some(u) = uuid { cmd.arg("--uuid").arg(u); } cmd.stdout(Stdio::piped()); cmd.stderr(Stdio::piped()); cmd.kill_on_drop(true); // Create new process group for clean termination cmd.process_group(0); tracing::info!("[{}] Starting: {:?}", log_prefix, script_name); tracing::info!("[{}] Full command: {:?}", log_prefix, cmd); let mut child = cmd .spawn() .with_context(|| format!("Failed to run {}", script_name))?; let child_pid = child.id(); let stdout = child.stdout.take().context("Failed to capture stdout")?; let stderr = child.stderr.take().context("Failed to capture stderr")?; let mut stdout_reader = BufReader::new(stdout).lines(); let mut stderr_reader = BufReader::new(stderr).lines(); let run_future = async { let mut stdout_done = false; let mut stderr_done = false; loop { tokio::select! { line = stdout_reader.next_line(), if !stdout_done => { match line { Ok(Some(line)) => { if line.starts_with(&format!("{}_", log_prefix)) { tracing::info!("[{}] {}", log_prefix, line); } } Ok(None) => stdout_done = true, Err(e) => tracing::warn!("[{}] stdout error: {}", log_prefix, e), } } line = stderr_reader.next_line(), if !stderr_done => { match line { Ok(Some(line)) => { if line.starts_with(&format!("{}_", log_prefix)) { tracing::info!("[{}] {}", log_prefix, line); } else if !line.trim().is_empty() { tracing::warn!("[{} stderr] {}", log_prefix, line); } } Ok(None) => stderr_done = true, Err(e) => tracing::warn!("[{}] stderr error: {}", log_prefix, e), } } status = child.wait() => { match status { Ok(status) => { if !status.success() { tracing::error!("[{}] Process failed: {}", log_prefix, status); return Err(anyhow::anyhow!("{} exited with: {}", script_name, status)); } tracing::info!("[{}] Completed successfully", log_prefix); } Err(e) => tracing::error!("[{}] wait error: {}", log_prefix, e), } break; } } } Ok(()) }; // 錯誤時 rename .json.tmp → .json.err(若 .tmp 非有效 JSON) // 若 .tmp 是有效 JSON,保留為 .json(保留部分結果) let mark_failed = || { if let Some(tmp) = &tmp_path { if tmp.exists() { if let Some(out) = &output_path { let is_valid = std::fs::read_to_string(tmp) .ok() .and_then(|c| serde_json::from_str::(&c).ok()) .is_some(); if is_valid { let mut partial_path = out.to_path_buf(); partial_path.set_extension("json.partial"); let _ = std::fs::rename(tmp, &partial_path); tracing::warn!( "[Executor] Partial output preserved: {:?}", partial_path ); } else { let mut err_path = out.to_path_buf(); err_path.set_extension("json.err"); let _ = std::fs::rename(tmp, &err_path); } } } } }; if let Some(duration) = timeout_duration { match timeout(duration, run_future).await { Ok(Ok(())) => {} Ok(Err(e)) => { mark_failed(); return Err(e); } Err(_) => { mark_failed(); if let Some(pid) = child_pid { let pgid = pid as i32; unsafe { libc::killpg(pgid, libc::SIGKILL); } } child.kill().await.context("Failed to kill process")?; anyhow::bail!("{} timed out after {:?}", script_name, duration); } } } else { if let Err(e) = run_future.await { mark_failed(); return Err(e); } } // 成功:.json.tmp → .json(已完成) if let Some(tmp) = &tmp_path { if tmp.exists() { if let Some(out) = &output_path { let _ = std::fs::rename(tmp, out); } } } Ok(()) } /// Run with output_idx and optional frame list for 8Hz sampling. pub async fn run_with_output_idx_and_frames( &self, script_name: &str, args: &[&str], uuid: Option<&str>, log_prefix: &str, timeout_duration: Option, output_idx: Option, frames: Option<&[i64]>, ) -> Result<()> { let script_path = self.scripts_dir.join(script_name); if !script_path.exists() { anyhow::bail!("Script not found: {:?}", script_path); } self.verify_script_integrity(script_name).context( "Pre-execution integrity check failed — possible version mismatch or corruption", )?; let output_path = output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p))); let tmp_path = output_path.as_ref().map(|p| { let mut tmp = p.to_path_buf(); tmp.set_extension("json.tmp"); tmp }); let mut cmd = Command::new(&self.python_path); cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR); cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX); // Pass Qdrant credentials to Python subprocesses if let Ok(qdrant_url) = std::env::var("QDRANT_URL") { cmd.env("QDRANT_URL", qdrant_url); } if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") { cmd.env("QDRANT_API_KEY", qdrant_api_key); } // Pass face detection settings to Python subprocesses let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok(); let face_min_size = std::env::var("FACE_MIN_SIZE").ok(); tracing::info!( "[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}", face_min_confidence, face_min_size ); if let Some(ref val) = face_min_confidence { cmd.env("FACE_MIN_CONFIDENCE", val); } if let Some(ref val) = face_min_size { cmd.env("FACE_MIN_SIZE", val); } cmd.arg(&script_path); for (i, arg) in args.iter().enumerate() { // Route the script's declared output path through a .tmp file so the // fresh result is written there and promoted to the real path only on // success (avoids clobbering good output with a stale/partial file). if Some(i) == output_idx { if let Some(ref tmp) = tmp_path { cmd.arg(tmp); continue; } } cmd.arg(arg); } if let Some(u) = uuid { cmd.arg("--uuid").arg(u); } // Pass frame list for 8Hz sampling (only if non-empty) if let Some(frames) = frames { if !frames.is_empty() { let frames_str = Self::format_frames_arg(frames); cmd.arg("--frames").arg(&frames_str); tracing::info!("[{}] 8Hz sampling: {} frames", log_prefix, frames.len()); } else { tracing::info!( "[{}] 8Hz sampling: 0 frames (skipping --frames arg)", log_prefix ); } } cmd.stdout(Stdio::piped()); cmd.stderr(Stdio::piped()); cmd.kill_on_drop(true); cmd.process_group(0); tracing::info!("[{}] Starting: {:?}", log_prefix, script_name); let mut child = cmd .spawn() .with_context(|| format!("Failed to run {}", script_name))?; let child_pid = child.id(); let stdout = child.stdout.take().context("Failed to capture stdout")?; let stderr = child.stderr.take().context("Failed to capture stderr")?; let mut stdout_reader = BufReader::new(stdout).lines(); let mut stderr_reader = BufReader::new(stderr).lines(); let run_future = async { let mut stdout_done = false; let mut stderr_done = false; loop { tokio::select! { line = stdout_reader.next_line(), if !stdout_done => { match line { Ok(Some(line)) => { if line.starts_with(&format!("{}_", log_prefix)) { tracing::info!("[{}] {}", log_prefix, line); } } Ok(None) => stdout_done = true, Err(e) => tracing::warn!("[{}] stdout error: {}", log_prefix, e), } } line = stderr_reader.next_line(), if !stderr_done => { match line { Ok(Some(line)) => { if line.starts_with(&format!("{}_", log_prefix)) { tracing::info!("[{}] {}", log_prefix, line); } else if !line.trim().is_empty() { tracing::warn!("[{} stderr] {}", log_prefix, line); } } Ok(None) => stderr_done = true, Err(e) => tracing::warn!("[{}] stderr error: {}", log_prefix, e), } } status = child.wait() => { match status { Ok(status) => { if !status.success() { tracing::error!("[{}] Process failed: {}", log_prefix, status); return Err(anyhow::anyhow!("{} exited with: {}", script_name, status)); } tracing::info!("[{}] Completed successfully", log_prefix); } Err(e) => tracing::error!("[{}] wait error: {}", log_prefix, e), } break; } } } Ok(()) }; let mark_failed = || { if let Some(tmp) = &tmp_path { if tmp.exists() { if let Some(out) = &output_path { let is_valid = std::fs::read_to_string(tmp) .ok() .and_then(|c| serde_json::from_str::(&c).ok()) .is_some(); if is_valid { let mut partial_path = out.to_path_buf(); partial_path.set_extension("json.partial"); let _ = std::fs::rename(tmp, &partial_path); tracing::warn!( "[Executor] Partial output preserved: {:?}", partial_path ); } else { let mut err_path = out.to_path_buf(); err_path.set_extension("json.err"); let _ = std::fs::rename(tmp, &err_path); } } } } }; if let Some(duration) = timeout_duration { match timeout(duration, run_future).await { Ok(Ok(())) => {} Ok(Err(e)) => { mark_failed(); return Err(e); } Err(_) => { mark_failed(); if let Some(pid) = child_pid { let pgid = pid as i32; unsafe { libc::killpg(pgid, libc::SIGKILL); } } child.kill().await.context("Failed to kill process")?; anyhow::bail!("{} timed out after {:?}", script_name, duration); } } } else { if let Err(e) = run_future.await { mark_failed(); return Err(e); } } if let Some(tmp) = &tmp_path { if tmp.exists() { if let Some(out) = &output_path { let _ = std::fs::rename(tmp, out); } } } Ok(()) } /// Like `run_with_output_idx_and_frames` but accepts a `CancellationToken` so the caller /// can cleanly abort the Python subprocess without leaking processes. pub async fn run_with_output_idx_and_frames_with_cancel( &self, script_name: &str, args: &[&str], uuid: Option<&str>, log_prefix: &str, timeout_duration: Option, output_idx: Option, frames: Option<&[i64]>, cancel: tokio_util::sync::CancellationToken, ) -> Result<()> { let script_path = self.scripts_dir.join(script_name); if !script_path.exists() { anyhow::bail!("Script not found: {:?}", script_path); } self.verify_script_integrity(script_name).context( "Pre-execution integrity check failed — possible version mismatch or corruption", )?; let output_path = output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p))); let tmp_path = output_path.as_ref().map(|p| { let mut tmp = p.to_path_buf(); tmp.set_extension("json.tmp"); tmp }); let mut cmd = Command::new(&self.python_path); cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR); cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX); if let Ok(qdrant_url) = std::env::var("QDRANT_URL") { cmd.env("QDRANT_URL", qdrant_url); } if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") { cmd.env("QDRANT_API_KEY", qdrant_api_key); } // Pass face detection settings to Python subprocesses let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok(); let face_min_size = std::env::var("FACE_MIN_SIZE").ok(); tracing::info!( "[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}", face_min_confidence, face_min_size ); if let Some(ref val) = face_min_confidence { cmd.env("FACE_MIN_CONFIDENCE", val); } if let Some(ref val) = face_min_size { cmd.env("FACE_MIN_SIZE", val); } cmd.arg(&script_path); for (i, arg) in args.iter().enumerate() { if Some(i) == output_idx { if let Some(ref tmp) = tmp_path { cmd.arg(tmp); continue; } } cmd.arg(arg); } if let Some(u) = uuid { cmd.arg("--uuid").arg(u); } // Append extra args (e.g. --threshold) after --uuid // Pass frame list for 8Hz sampling if let Some(frames) = frames { if !frames.is_empty() { let frames_str = Self::format_frames_arg(frames); cmd.arg("--frames").arg(&frames_str); } } cmd.stdout(Stdio::piped()); cmd.stderr(Stdio::piped()); cmd.kill_on_drop(true); cmd.process_group(0); tracing::info!("[{}] Starting: {:?}", log_prefix, script_name); let mut child = cmd .spawn() .with_context(|| format!("Failed to run {}", script_name))?; let child_pid = child.id(); let stdout = child.stdout.take().context("Failed to capture stdout")?; let stderr = child.stderr.take().context("Failed to capture stderr")?; let mut stdout_reader = BufReader::new(stdout).lines(); let mut stderr_reader = BufReader::new(stderr).lines(); let run_future = async { let mut stdout_done = false; let mut stderr_done = false; loop { tokio::select! { line = stdout_reader.next_line(), if !stdout_done => { match line { Ok(Some(line)) => { if line.starts_with(&format!("{}_", log_prefix)) { tracing::info!("[{}] {}", log_prefix, line); } } Ok(None) => stdout_done = true, Err(e) => tracing::warn!("[{}] stdout error: {}", log_prefix, e), } } line = stderr_reader.next_line(), if !stderr_done => { match line { Ok(Some(line)) => { if line.starts_with(&format!("{}_", log_prefix)) { tracing::info!("[{}] {}", log_prefix, line); } else if !line.trim().is_empty() { tracing::warn!("[{} stderr] {}", log_prefix, line); } } Ok(None) => stderr_done = true, Err(e) => tracing::warn!("[{}] stderr error: {}", log_prefix, e), } } _ = cancel.cancelled() => { tracing::info!("[{}] Cancelled by caller", log_prefix); if let Some(pid) = child_pid { unsafe { libc::killpg(pid as i32, libc::SIGTERM); } } return Err(anyhow::anyhow!("{} cancelled by caller", script_name)); } status = child.wait() => { match status { Ok(status) => { if !status.success() { tracing::error!("[{}] Process failed: {}", log_prefix, status); return Err(anyhow::anyhow!("{} exited with: {}", script_name, status)); } tracing::info!("[{}] Completed successfully", log_prefix); } Err(e) => tracing::error!("[{}] wait error: {}", log_prefix, e), } break; } } } Ok(()) }; let mark_failed = || { if let Some(tmp) = &tmp_path { if tmp.exists() { if let Some(out) = &output_path { let is_valid = std::fs::read_to_string(tmp) .ok() .and_then(|c| serde_json::from_str::(&c).ok()) .is_some(); if is_valid { let mut partial_path = out.to_path_buf(); partial_path.set_extension("json.partial"); let _ = std::fs::rename(tmp, &partial_path); tracing::warn!( "[Executor] Partial output preserved: {:?}", partial_path ); } else { let mut err_path = out.to_path_buf(); err_path.set_extension("json.err"); let _ = std::fs::rename(tmp, &err_path); } } } } }; if let Some(duration) = timeout_duration { match timeout(duration, run_future).await { Ok(Ok(())) => {} Ok(Err(e)) => { mark_failed(); return Err(e); } Err(_) => { mark_failed(); if let Some(pid) = child_pid { unsafe { libc::killpg(pid as i32, libc::SIGKILL); } } child.kill().await.context("Failed to kill process")?; anyhow::bail!("{} timed out after {:?}", script_name, duration); } } } else { if let Err(e) = run_future.await { mark_failed(); return Err(e); } } if let Some(tmp) = &tmp_path { if tmp.exists() { if let Some(out) = &output_path { let _ = std::fs::rename(tmp, out); } } } Ok(()) } pub async fn run_with_output( &self, script_name: &str, args: &[&str], uuid: Option<&str>, log_prefix: &str, timeout_duration: Option, ) -> Result<()> { self.run(script_name, args, uuid, log_prefix, timeout_duration) .await } pub async fn run_with_retry( &self, script_name: &str, args: &[&str], uuid: Option<&str>, log_prefix: &str, timeout_duration: Option, retry_config: Option, ) -> Result<()> { let config = retry_config.unwrap_or_default(); let mut attempt = 0; let mut delay_ms = config.initial_delay_ms; loop { attempt += 1; match self .run(script_name, args, uuid, log_prefix, timeout_duration) .await { Ok(()) => { if attempt > 1 { tracing::info!( "[{}] Succeeded on attempt {}/{}", log_prefix, attempt, config.max_attempts ); } return Ok(()); } Err(e) => { if attempt >= config.max_attempts { tracing::error!( "[{}] Failed after {} attempts: {}", log_prefix, attempt, e ); return Err(e); } tracing::warn!( "[{}] Attempt {}/{} failed: {}. Retrying in {}ms...", log_prefix, attempt, config.max_attempts, e, delay_ms ); sleep(Duration::from_millis(delay_ms)).await; delay_ms = (delay_ms as f64 * config.backoff_multiplier) as u64; delay_ms = delay_ms.min(config.max_delay_ms); } } } } /// Resolve the path to a compiled Rust processor binary. /// Looks under `/rust_processors/target/release/` first, falling /// back to `target/debug/` (mirrors the swift_processors layout convention). pub fn rust_binary_path(&self, bin_name: &str) -> Option { let base = self.scripts_dir.join("rust_processors").join("target"); for profile in ["release", "debug"] { let p = base.join(profile).join(bin_name); if p.exists() { return Some(p); } } None } /// Run a Rust processor binary with the same output-tmp / timeout / process-group /// semantics as the Python scripts. `output_idx` is the arg index for the output /// JSON path; `uuid`/`frames` are appended as `--uuid=X` and `--frames=a,b,c` /// when provided. pub async fn run_rust_with_output_idx_and_frames( &self, bin_path: &std::path::Path, args: &[&str], output_idx: Option, uuid: Option<&str>, frames: Option<&[i64]>, log_prefix: &str, timeout_duration: Option, ) -> Result<()> { if !bin_path.exists() { anyhow::bail!("Rust processor not found: {:?}", bin_path); } let output_path = output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p))); let tmp_path = output_path.as_ref().map(|p| { let mut tmp = p.to_path_buf(); tmp.set_extension("json.tmp"); tmp }); let mut cmd = Command::new(bin_path); cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR); cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX); if let Ok(qdrant_url) = std::env::var("QDRANT_URL") { cmd.env("QDRANT_URL", qdrant_url); } if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") { cmd.env("QDRANT_API_KEY", qdrant_api_key); } for (i, arg) in args.iter().enumerate() { if Some(i) == output_idx { if let Some(ref tmp) = tmp_path { cmd.arg(tmp); continue; } } cmd.arg(arg); } if let Some(frames) = frames { if !frames.is_empty() { let frames_str = Self::format_frames_arg(frames); cmd.arg("--frames").arg(&frames_str); } } if let Some(u) = uuid { cmd.arg("--uuid").arg(u); } cmd.stdout(Stdio::piped()); cmd.stderr(Stdio::piped()); cmd.kill_on_drop(true); cmd.process_group(0); tracing::info!("[{}] Starting rust: {:?}", log_prefix, cmd); let mut child = cmd.spawn().with_context(|| { format!("Failed to run Rust processor {:?}", bin_path) })?; let child_pid = child.id(); let stdout = child.stdout.take().context("Failed to capture stdout")?; let stderr = child.stderr.take().context("Failed to capture stderr")?; let mut stdout_reader = BufReader::new(stdout).lines(); let mut stderr_reader = BufReader::new(stderr).lines(); let run_future = async { let mut stdout_done = false; let mut stderr_done = false; loop { tokio::select! { line = stdout_reader.next_line(), if !stdout_done => { match line { Ok(Some(line)) => { if line.starts_with(&format!("{}_", log_prefix)) { tracing::info!("[{}] {}", log_prefix, line); } } Ok(None) => stdout_done = true, Err(e) => tracing::warn!("[{}] stdout error: {}", log_prefix, e), } } line = stderr_reader.next_line(), if !stderr_done => { match line { Ok(Some(line)) => { if line.starts_with(&format!("{}_", log_prefix)) { tracing::info!("[{}] {}", log_prefix, line); } else if !line.trim().is_empty() { tracing::warn!("[{} stderr] {}", log_prefix, line); } } Ok(None) => stderr_done = true, Err(e) => tracing::warn!("[{}] stderr error: {}", log_prefix, e), } } status = child.wait() => { match status { Ok(status) => { if !status.success() { tracing::error!("[{}] Process failed: {}", log_prefix, status); return Err(anyhow::anyhow!("{} exited with: {}", bin_path.display(), status)); } tracing::info!("[{}] Completed successfully", log_prefix); } Err(e) => tracing::error!("[{}] wait error: {}", log_prefix, e), } break; } } } Ok(()) }; let mark_failed = || { if let Some(tmp) = &tmp_path { if tmp.exists() { if let Some(out) = &output_path { let is_valid = std::fs::read_to_string(tmp) .ok() .and_then(|c| serde_json::from_str::(&c).ok()) .is_some(); if is_valid { let mut partial_path = out.to_path_buf(); partial_path.set_extension("json.partial"); let _ = std::fs::rename(tmp, &partial_path); } else { let mut err_path = out.to_path_buf(); err_path.set_extension("json.err"); let _ = std::fs::rename(tmp, &err_path); } } } } }; if let Some(duration) = timeout_duration { match timeout(duration, run_future).await { Ok(Ok(())) => {} Ok(Err(e)) => { mark_failed(); return Err(e); } Err(_) => { mark_failed(); if let Some(pid) = child_pid { unsafe { libc::killpg(pid as i32, libc::SIGKILL); } } child.kill().await.context("Failed to kill process")?; anyhow::bail!("{} timed out after {:?}", log_prefix, duration); } } } else if let Err(e) = run_future.await { mark_failed(); return Err(e); } if let Some(tmp) = &tmp_path { if tmp.exists() { if let Some(out) = &output_path { let _ = std::fs::rename(tmp, out); } } } Ok(()) } pub fn script_path(&self, script_name: &str) -> PathBuf { self.scripts_dir.join(script_name) } pub fn python_path(&self) -> &PathBuf { &self.python_path } } impl Default for PythonExecutor { fn default() -> Self { Self::new().expect("Failed to create PythonExecutor") } } #[cfg(test)] mod tests { use super::*; use std::process::Stdio; #[tokio::test] async fn test_executor_passes_env_vars() { let executor = PythonExecutor::new().unwrap(); let mut cmd = Command::new(&executor.python_path); cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR); cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA); cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX); // Pass Qdrant credentials to Python subprocesses if let Ok(qdrant_url) = std::env::var("QDRANT_URL") { cmd.env("QDRANT_URL", qdrant_url); } if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") { cmd.env("QDRANT_API_KEY", qdrant_api_key); } cmd.args([ "-c", "import os; print(f'ENV_DATABASE_SCHEMA={os.environ.get(\"DATABASE_SCHEMA\",\"\")}'); print(f'ENV_MOMENTRY_DB_SCHEMA={os.environ.get(\"MOMENTRY_DB_SCHEMA\",\"\")}'); print(f'ENV_MOMENTRY_OUTPUT_DIR={os.environ.get(\"MOMENTRY_OUTPUT_DIR\",\"\")}'); print(f'ENV_MOMENTRY_REDIS_PREFIX={os.environ.get(\"MOMENTRY_REDIS_PREFIX\",\"\")}');", ]); cmd.stdout(Stdio::piped()); cmd.stderr(Stdio::piped()); let output = cmd.output().await.expect("Failed to run inline Python"); let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); println!("stdout: {}", stdout); if !stderr.is_empty() { println!("stderr: {}", stderr); } assert!( output.status.success(), "Python inline script failed: {}", stderr ); assert!( stdout.contains(&format!("ENV_DATABASE_SCHEMA={}", *DATABASE_SCHEMA)), "DATABASE_SCHEMA mismatch:\n{}", stdout ); assert!( stdout.contains(&format!("ENV_MOMENTRY_DB_SCHEMA={}", *DATABASE_SCHEMA)), "MOMENTRY_DB_SCHEMA mismatch:\n{}", stdout ); assert!( stdout.contains(&format!("ENV_MOMENTRY_OUTPUT_DIR={}", *OUTPUT_DIR)), "MOMENTRY_OUTPUT_DIR mismatch:\n{}", stdout ); assert!( stdout.contains(&format!("ENV_MOMENTRY_REDIS_PREFIX={}", *REDIS_KEY_PREFIX)), "MOMENTRY_REDIS_PREFIX mismatch:\n{}", stdout ); } #[test] fn test_python_executor_new() { let executor = PythonExecutor::new(); assert!( executor.is_ok(), "PythonExecutor should create successfully" ); } #[test] fn test_python_executor_paths() { let executor = PythonExecutor::new().unwrap(); let python_path = executor.python_path(); assert!( python_path.exists(), "Python path should exist: {:?}", python_path ); } #[test] fn test_script_path() { let executor = PythonExecutor::new().unwrap(); let script_path = executor.script_path("asr_processor.py"); assert!(script_path.to_string_lossy().contains("scripts")); assert!(script_path.to_string_lossy().contains("asr_processor.py")); } #[test] fn test_script_path_nonexistent() { let executor = PythonExecutor::new().unwrap(); let path = executor.script_path("nonexistent_script.py"); assert!(!path.exists(), "Nonexistent script path should not exist"); } #[test] fn test_python_path_is_executable() { let executor = PythonExecutor::new().unwrap(); let path = executor.python_path(); let metadata = std::fs::metadata(path); assert!(metadata.is_ok(), "Python path should be accessible"); } #[test] fn test_retry_config_default() { let config = RetryConfig::default(); assert_eq!(config.max_attempts, 3); assert_eq!(config.initial_delay_ms, 1000); assert_eq!(config.max_delay_ms, 30000); assert_eq!(config.backoff_multiplier, 2.0); } #[test] fn test_retry_config_builder() { let config = RetryConfig::new(5).with_delay(2000).with_max_delay(60000); assert_eq!(config.max_attempts, 5); assert_eq!(config.initial_delay_ms, 2000); assert_eq!(config.max_delay_ms, 60000); } #[tokio::test] async fn test_retry_config_clone() { let config = RetryConfig::default(); let cloned = config.clone(); assert_eq!(cloned.max_attempts, config.max_attempts); } }