feat: enhance worker status API with PID, uptime, and liveness check

- Added worker_pid (from pgrep)
- Added uptime_secs
- Added last_poll_at (most recent job activity)
- Added poll_interval_secs
- Added is_alive (based on worker process existence)
This commit is contained in:
Accusys
2026-10-18 16:20:46 +08:00
parent 9cd386b720
commit f165dc1425
+308
View File
@@ -0,0 +1,308 @@
//! Monitor API endpoints for Queue/Worker/Pipeline dashboard
use axum::{extract::State, http::StatusCode, response::Json, routing::get, Router};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use sqlx::Row;
use super::types::AppState;
use crate::core::db::PostgresDb;
use crate::core::db::schema;
#[derive(Debug, Serialize)]
pub struct QueueStatsResponse {
pub pending: i64,
pub running: i64,
pub completed: i64,
pub failed: i64,
}
#[derive(Debug, Serialize)]
pub struct RunningJobsResponse {
pub jobs: Vec<JobWithProcessors>,
}
#[derive(Debug, Serialize)]
pub struct JobWithProcessors {
pub job_id: i32,
pub file_uuid: String,
pub file_name: String,
pub status: String,
pub started_at: Option<String>,
pub duration_secs: u64,
pub processors: Vec<ProcessorStatus>,
}
#[derive(Debug, Serialize, Clone)]
pub struct ProcessorStatus {
pub name: String,
pub phase: i32,
pub status: String,
pub progress: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub duration: Option<f64>,
}
#[derive(Debug, Serialize)]
pub struct WorkerStatusResponse {
pub cpu_percent: f32,
pub gpu_percent: f32,
pub memory_mb: u64,
pub memory_percent: f32,
pub active_processors: usize,
pub max_processors: usize,
pub processors: Vec<ActiveProcessor>,
pub worker_pid: u32,
pub uptime_secs: u64,
pub last_poll_at: Option<String>,
pub poll_interval_secs: u64,
pub is_alive: bool,
}
#[derive(Debug, Serialize)]
pub struct ActiveProcessor {
pub name: String,
pub job_id: i32,
pub status: String,
}
pub async fn get_queue_stats(
State(state): State<AppState>,
) -> Result<Json<QueueStatsResponse>, StatusCode> {
let db = &state.db;
let table = schema::table_name("monitor_jobs");
let rows = sqlx::query(&format!(
"SELECT status, COUNT(*) as count FROM {} GROUP BY status",
table
))
.fetch_all(db.pool())
.await
.map_err(|e| {
tracing::error!("Failed to get queue stats: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let mut pending = 0i64;
let mut running = 0i64;
let mut completed = 0i64;
let mut failed = 0i64;
for row in rows {
let status: String = row.get("status");
let count: i64 = row.get("count");
match status.as_str() {
"pending" => pending = count,
"running" => running = count,
"completed" => completed = count,
"failed" => failed = count,
_ => {}
}
}
Ok(Json(QueueStatsResponse {
pending,
running,
completed,
failed,
}))
}
pub async fn get_running_jobs(
State(state): State<AppState>,
) -> Result<Json<RunningJobsResponse>, StatusCode> {
let db = &state.db;
let jobs_table = schema::table_name("monitor_jobs");
let videos_table = schema::table_name("videos");
let jobs = sqlx::query(&format!(
"SELECT j.id, j.uuid, j.status, j.started_at, v.file_name
FROM {} j
LEFT JOIN {} v ON v.file_uuid = j.uuid
WHERE j.status = 'running'
ORDER BY j.started_at DESC",
jobs_table, videos_table
))
.fetch_all(db.pool())
.await
.map_err(|e| {
tracing::error!("Failed to get running jobs: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let mut jobs_with_processors = Vec::new();
for job_row in jobs {
let job_id: i32 = job_row.get("id");
let file_uuid: String = job_row.get("uuid");
let status: String = job_row.get("status");
let started_at: Option<String> = job_row.get("started_at");
let file_name: String = job_row.get("file_name");
let duration_secs = calculate_duration(&started_at);
let pr_table = schema::table_name("processor_results");
let processors = sqlx::query(&format!(
"SELECT processor_type, status, progress_current, progress_total, duration_secs
FROM {}
WHERE job_id = $1
ORDER BY processor_type",
pr_table
))
.bind(job_id)
.fetch_all(db.pool())
.await
.unwrap_or_default();
let processor_status: Vec<ProcessorStatus> = processors
.into_iter()
.map(|row| {
let name: String = row.get("processor_type");
let status: String = row.get("status");
let progress_current: Option<i32> = row.get("progress_current");
let progress_total: Option<i32> = row.get("progress_total");
let duration: Option<f64> = row.get("duration_secs");
let progress = calculate_progress(progress_current, progress_total, &status);
let phase = get_phase(&name);
ProcessorStatus {
name,
phase,
status,
progress,
duration,
}
})
.collect();
jobs_with_processors.push(JobWithProcessors {
job_id,
file_uuid,
file_name,
status,
started_at,
duration_secs,
processors: processor_status,
});
}
Ok(Json(RunningJobsResponse {
jobs: jobs_with_processors,
}))
}
pub async fn get_worker_status(
State(state): State<AppState>,
) -> Result<Json<WorkerStatusResponse>, StatusCode> {
use crate::worker::resources::SystemResources;
let db = &state.db;
let resources = SystemResources::check();
let pr_table = schema::table_name("processor_results");
let jobs_table = schema::table_name("monitor_jobs");
let active = sqlx::query(&format!(
"SELECT pr.processor_type, pr.job_id, pr.status
FROM {} pr
JOIN {} j ON j.id = pr.job_id
WHERE j.status = 'running' AND pr.status = 'running'",
pr_table, jobs_table
))
.fetch_all(db.pool())
.await
.unwrap_or_default();
let processors: Vec<ActiveProcessor> = active
.into_iter()
.map(|row| ActiveProcessor {
name: row.get("processor_type"),
job_id: row.get("job_id"),
status: "running".to_string(),
})
.collect();
let memory_used_mb = resources.memory_total_mb - resources.memory_available_mb;
let memory_percent = resources.memory_used_percent as f32;
// Get worker PID from process table
let worker_pid = std::process::Command::new("pgrep")
.arg("-f")
.arg("momentry worker")
.output()
.ok()
.and_then(|o| {
let stdout = String::from_utf8_lossy(&o.stdout);
stdout.lines().next().and_then(|s| s.parse().ok())
})
.unwrap_or(0);
// Get worker uptime from server start time (approximation)
let uptime_secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
// Last poll time: check the most recent job activity
let last_poll_at: Option<String> = sqlx::query_scalar(&format!(
"SELECT MAX(updated_at)::text FROM {} WHERE status = 'running'",
jobs_table
))
.fetch_optional(db.pool())
.await
.ok()
.flatten();
// Worker is considered alive if we found a worker process
let is_alive = worker_pid > 0;
Ok(Json(WorkerStatusResponse {
cpu_percent: resources.cpu_used_percent as f32,
gpu_percent: resources.gpu_utilization.unwrap_or(0.0) as f32,
memory_mb: memory_used_mb as u64,
memory_percent,
active_processors: processors.len(),
max_processors: 6,
processors,
worker_pid,
uptime_secs,
last_poll_at,
poll_interval_secs: 5,
is_alive,
}))
}
fn get_phase(processor_name: &str) -> i32 {
match processor_name {
"cut" => 1,
"asr" | "asr_asrx" | "face" | "ocr" => 2,
"scene" | "face_trace" | "face_cluster" => 3,
"tkg" => 4,
_ => 0,
}
}
fn calculate_duration(started_at: &Option<String>) -> u64 {
if let Some(started) = started_at {
if let Ok(started_time) = chrono::DateTime::parse_from_rfc3339(started) {
return (chrono::Utc::now() - started_time.with_timezone(&chrono::Utc)).num_seconds() as u64;
}
}
0
}
fn calculate_progress(current: Option<i32>, total: Option<i32>, status: &str) -> i32 {
match (current, total) {
(Some(c), Some(t)) if t > 0 => ((c as f64 / t as f64) * 100.0) as i32,
_ => if status == "completed" { 100 } else { 0 },
}
}
pub fn monitor_routes() -> Router<crate::api::types::AppState> {
Router::new()
.route("/api/v1/monitor/queue_stats", get(get_queue_stats))
.route("/api/v1/monitor/running_jobs", get(get_running_jobs))
.route("/api/v1/monitor/worker_status", get(get_worker_status))
}