From 85959907b70cc08d149099d012246d1287e51fcf Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Mon, 21 Sep 2026 15:35:54 +0000 Subject: [PATCH] feat(platform): graceful shutdown and restart recovery (#259) (#301) --- .env.example | 2 + compliance-agent/src/api/server.rs | 17 +- compliance-agent/src/config.rs | 3 + compliance-agent/src/database.rs | 15 ++ compliance-agent/src/lib.rs | 1 + compliance-agent/src/lifecycle.rs | 248 ++++++++++++++++++++++++ compliance-agent/src/main.rs | 37 +++- compliance-agent/src/webhooks/server.rs | 23 ++- compliance-agent/tests/lifecycle.rs | 209 ++++++++++++++++++++ compliance-core/src/config.rs | 3 + compliance-core/src/lib.rs | 2 + compliance-core/src/models/scan.rs | 5 + compliance-core/src/shutdown.rs | 222 +++++++++++++++++++++ compliance-mcp/src/main.rs | 13 +- docs/guide/scanning.md | 1 + 15 files changed, 788 insertions(+), 13 deletions(-) create mode 100644 compliance-agent/src/lifecycle.rs create mode 100644 compliance-agent/tests/lifecycle.rs create mode 100644 compliance-core/src/shutdown.rs diff --git a/.env.example b/.env.example index 4fd5ba4..9c364d2 100644 --- a/.env.example +++ b/.env.example @@ -30,6 +30,8 @@ NVD_API_KEY= # Agent AGENT_PORT=3001 +# Port of the separate webhook listener (Git push / PR events). +WEBHOOK_PORT=3002 # Scans (and PR reviews) running at once across all tenants; each is a clone # plus semgrep and syft. Requests for a target already being scanned coalesce # into one follow-up instead of running in parallel. diff --git a/compliance-agent/src/api/server.rs b/compliance-agent/src/api/server.rs index 33144ba..00590d4 100644 --- a/compliance-agent/src/api/server.rs +++ b/compliance-agent/src/api/server.rs @@ -12,6 +12,7 @@ use tower_http::trace::TraceLayer; use compliance_core::auth::{require_jwt_auth, require_tenant_status, JwksState}; use compliance_core::config::AppEnv; +use compliance_core::shutdown::{self, Shutdown}; use compliance_core::{TenantContext, TenantStatus}; use crate::agent::ComplianceAgent; @@ -135,7 +136,18 @@ fn cors_layer(origins: &[String], app_env: AppEnv) -> CorsLayer { .allow_headers(Any) } -pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), AgentError> { +/// Serve the REST API on `port` until `shutdown` fires, then drain in-flight +/// requests for at most [`shutdown::GRACE_PERIOD`]. +/// +/// # Errors +/// +/// Returns an error if Keycloak is missing in a hardened environment, the port +/// cannot be bound, or serving fails. +pub async fn start_api_server( + agent: ComplianceAgent, + port: u16, + shutdown: Shutdown, +) -> Result<(), AgentError> { let shared = Arc::new(agent.clone()); let jwks_state = match (&agent.config.keycloak_url, &agent.config.keycloak_realm) { (Some(kc_url), Some(kc_realm)) => { @@ -330,9 +342,10 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A .map_err(|e| AgentError::Other(format!("Failed to bind to {addr}: {e}")))?; tracing::info!("REST API listening on {addr}"); - axum::serve(listener, app) + shutdown::serve(listener, app, shutdown, shutdown::GRACE_PERIOD) .await .map_err(|e| AgentError::Other(format!("API server error: {e}")))?; + tracing::info!("REST API stopped"); Ok(()) } diff --git a/compliance-agent/src/config.rs b/compliance-agent/src/config.rs index 5cef9c2..9eecde9 100644 --- a/compliance-agent/src/config.rs +++ b/compliance-agent/src/config.rs @@ -55,6 +55,9 @@ fn build_config(app_env: AppEnv) -> Result { agent_port: env_var_opt("AGENT_PORT") .and_then(|p| p.parse().ok()) .unwrap_or(3001), + webhook_port: env_var_opt("WEBHOOK_PORT") + .and_then(|p| p.parse().ok()) + .unwrap_or(3002), scan_concurrency: env_var_opt("SCAN_CONCURRENCY") .and_then(|v| v.parse::().ok()) .filter(|n| *n > 0) diff --git a/compliance-agent/src/database.rs b/compliance-agent/src/database.rs index 669f0ff..e81a3f5 100644 --- a/compliance-agent/src/database.rs +++ b/compliance-agent/src/database.rs @@ -212,6 +212,21 @@ impl DatabasePool { .collect()) } + /// Every tenant database that exists, opened without creating anything + /// (like [`Self::for_existing_tenant_id`]). Works from the database names + /// themselves, so hash-fallback databases are included, which + /// [`Self::list_tenant_ids`] cannot do. Skips the admin database. + pub async fn existing_tenant_dbs(&self) -> Result, AgentError> { + let admin = self.admin_db_name(); + Ok(self + .list_tenant_db_names() + .await? + .into_iter() + .filter(|name| *name != admin) + .map(|name| Database::from_database(self.client.database(&name))) + .collect()) + } + /// Drop the database for a specific tenant. Used by GDPR delete /// and tenant offboarding. Idempotent — dropping a non-existent /// database is a no-op at the driver level. diff --git a/compliance-agent/src/lib.rs b/compliance-agent/src/lib.rs index 020ed4d..d4e8bb8 100644 --- a/compliance-agent/src/lib.rs +++ b/compliance-agent/src/lib.rs @@ -10,6 +10,7 @@ pub mod demo_seed; pub mod error; pub mod fixtures; pub mod ingest; +pub mod lifecycle; pub mod llm; pub mod pentest; pub mod pipeline; diff --git a/compliance-agent/src/lifecycle.rs b/compliance-agent/src/lifecycle.rs new file mode 100644 index 0000000..879973f --- /dev/null +++ b/compliance-agent/src/lifecycle.rs @@ -0,0 +1,248 @@ +//! Keeps work from staying stuck across an agent restart (#65). +//! +//! A redeploy, crash or out-of-memory kill ends every scan the agent was +//! running without anything recording it, so the run stays `running` forever. +//! [`recover_orphaned_runs`] closes those records once at startup, before +//! anything new can start. [`run_werkbank_sweeper`] returns Werkbank jobs whose +//! runner stopped heartbeating to the queue. +//! +//! Both assume one agent per environment, which is how every Orca deployment +//! runs today. With two replicas, one agent's startup would close runs the +//! other is still working on. + +use std::time::Duration; + +use chrono::{DateTime, Utc}; +use mongodb::bson::{doc, DateTime as BsonDateTime}; +use tokio::time::MissedTickBehavior; + +use compliance_core::shutdown::Shutdown; + +use crate::database::{Database, DatabasePool}; +use crate::error::AgentError; +use crate::werkbank::{JobQueue, SweepOutcome}; + +/// Recorded as `error_message` on every run closed at startup. +pub const INTERRUPTED_MESSAGE: &str = "interrupted by agent restart"; + +/// How often expired Werkbank leases are swept. +pub const WERKBANK_SWEEP_INTERVAL: Duration = Duration::from_secs(60); + +/// A job whose lease has expired this many times is marked `expired` instead +/// of being queued again, so a job that keeps killing its runner stops. +pub const WERKBANK_MAX_ATTEMPTS: u32 = 3; + +/// A kind of run record a stopped agent can leave open, and how it is closed. +struct OrphanRule { + collection: &'static str, + /// Statuses that only a live agent process ever moves on from. + open: &'static [&'static str], + closed_as: &'static str, +} + +/// Code scans are what customers see, so they get their own `interrupted` +/// status. The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and +/// pentest are off in production, and graph and embedding builds are steps of +/// a scan. A paused pentest session can only be resumed through in-memory +/// state, so after a restart it is as dead as a running one. +const ORPHAN_RULES: [OrphanRule; 5] = [ + OrphanRule { + collection: "scan_runs", + open: &["running"], + closed_as: "interrupted", + }, + OrphanRule { + collection: "graph_builds", + open: &["running"], + closed_as: "failed", + }, + OrphanRule { + collection: "embedding_builds", + open: &["running"], + closed_as: "failed", + }, + OrphanRule { + collection: "dast_scan_runs", + open: &["running"], + closed_as: "failed", + }, + OrphanRule { + collection: "pentest_sessions", + open: &["running", "paused"], + closed_as: "failed", + }, +]; + +/// Close every run a previous agent process left open, in every tenant. +/// +/// Call once at startup, before the scheduler and servers start, so no run +/// this process creates can be caught. A tenant whose update fails is logged +/// and skipped, so one bad database cannot leave the others' runs open. +/// +/// # Returns +/// +/// How many records were closed across all tenants. +/// +/// # Errors +/// +/// Returns an error only if the tenant databases cannot be listed. +pub async fn recover_orphaned_runs( + pool: &DatabasePool, + now: DateTime, +) -> Result { + let mut closed = 0; + for db in pool.existing_tenant_dbs().await? { + match close_open_runs(&db, now).await { + Ok(count) => closed += count, + Err(e) => tracing::error!( + database = db.inner().name(), + "closing runs left open by the previous agent failed: {e}" + ), + } + } + Ok(closed) +} + +/// Apply every [`ORPHAN_RULES`] entry to one tenant database. +async fn close_open_runs(db: &Database, now: DateTime) -> Result { + let completed_at = BsonDateTime::from_chrono(now); + let mut closed = 0; + for rule in &ORPHAN_RULES { + let result = db + .raw_collection(rule.collection) + .update_many( + doc! { "status": { "$in": rule.open.to_vec() } }, + doc! { "$set": { + "status": rule.closed_as, + "error_message": INTERRUPTED_MESSAGE, + "completed_at": completed_at, + } }, + ) + .await?; + if result.modified_count > 0 { + tracing::warn!( + database = db.inner().name(), + collection = rule.collection, + count = result.modified_count, + status = rule.closed_as, + "closed runs left open by the previous agent process" + ); + } + closed += result.modified_count; + } + Ok(closed) +} + +/// Sweep expired Werkbank leases in every tenant (see +/// [`JobQueue::sweep_expired`]). A tenant whose sweep fails is logged and +/// skipped. +/// +/// # Errors +/// +/// Returns an error only if the tenant databases cannot be listed. +pub async fn sweep_werkbank_leases( + pool: &DatabasePool, + now: DateTime, + max_attempts: u32, +) -> Result { + let mut total = SweepOutcome::default(); + for db in pool.existing_tenant_dbs().await? { + match JobQueue::new(&db).sweep_expired(now, max_attempts).await { + Ok(outcome) => { + total.requeued += outcome.requeued; + total.expired += outcome.expired; + } + Err(e) => tracing::error!( + database = db.inner().name(), + "Werkbank lease sweep failed: {e}" + ), + } + } + Ok(total) +} + +/// Sweep expired Werkbank leases every [`WERKBANK_SWEEP_INTERVAL`] until +/// `shutdown` fires. The first sweep runs immediately, which also picks up +/// leases that expired while the agent was down. +pub async fn run_werkbank_sweeper(pool: DatabasePool, shutdown: Shutdown) { + let mut ticks = tokio::time::interval(WERKBANK_SWEEP_INTERVAL); + // After a stall, wait a full interval rather than sweeping in a burst. + ticks.set_missed_tick_behavior(MissedTickBehavior::Delay); + let stop = shutdown.wait(); + // `select!` polls this one future again on every loop turn, which Rust + // only allows once the future is pinned (fixed at one memory address). + tokio::pin!(stop); + loop { + tokio::select! { + () = &mut stop => return, + _ = ticks.tick() => {} + } + match sweep_werkbank_leases(&pool, Utc::now(), WERKBANK_MAX_ATTEMPTS).await { + Ok(outcome) if outcome != SweepOutcome::default() => tracing::info!( + requeued = outcome.requeued, + expired = outcome.expired, + "swept expired Werkbank leases" + ), + Ok(_) => {} + Err(e) => tracing::error!("Werkbank lease sweep failed: {e}"), + } + } +} + +#[cfg(test)] +#[allow(clippy::expect_used)] +mod tests { + use super::*; + + use compliance_core::models::dast::DastScanStatus; + use compliance_core::models::embedding::EmbeddingBuildStatus; + use compliance_core::models::graph::GraphBuildStatus; + use compliance_core::models::pentest::PentestStatus; + use compliance_core::models::ScanRunStatus; + + /// Parse a status literal the way Mongo documents are read back. + fn parse(status: &str) -> T { + serde_json::from_value(serde_json::Value::String(status.to_string())) + .expect("status literal matches the enum's serde name") + } + + #[test] + fn rule_statuses_match_the_model_enums() { + // The rules use literals so they can be a `const`; this keeps them in + // step with the serde names of the enums the models read back. + for rule in &ORPHAN_RULES { + for status in rule.open.iter().chain([&rule.closed_as]) { + match rule.collection { + "scan_runs" => { + parse::(status); + } + "graph_builds" => { + parse::(status); + } + "embedding_builds" => { + parse::(status); + } + "dast_scan_runs" => { + parse::(status); + } + "pentest_sessions" => { + parse::(status); + } + other => panic!("no status enum registered for {other}"), + } + } + } + } + + #[test] + fn code_scans_are_interrupted_not_failed() { + let scan_rule = ORPHAN_RULES + .iter() + .find(|r| r.collection == "scan_runs") + .expect("scan_runs rule"); + assert_eq!( + parse::(scan_rule.closed_as), + ScanRunStatus::Interrupted + ); + } +} diff --git a/compliance-agent/src/main.rs b/compliance-agent/src/main.rs index 0d8a729..12b0064 100644 --- a/compliance-agent/src/main.rs +++ b/compliance-agent/src/main.rs @@ -1,4 +1,5 @@ -use compliance_agent::{agent, api, config, database, scheduler, webhooks}; +use compliance_agent::{agent, api, config, database, lifecycle, scheduler, webhooks}; +use compliance_core::shutdown; #[tokio::main] async fn main() -> Result<(), Box> { @@ -27,6 +28,21 @@ async fn main() -> Result<(), Box> { let agent = agent::ComplianceAgent::new(config.clone(), db_pool); + // Before anything can start a new run, close the runs the previous agent + // process left open when it stopped. + match lifecycle::recover_orphaned_runs(&agent.db_pool, chrono::Utc::now()).await { + Ok(0) => {} + Ok(closed) => tracing::warn!(closed, "closed runs left open by the previous agent"), + Err(e) => tracing::error!("closing runs left open by the previous agent failed: {e}"), + } + + // SIGTERM or Ctrl+C fires `stop`; each server then drains on its own. + let (trigger, stop) = shutdown::channel(); + tokio::spawn(async move { + shutdown::signal().await; + trigger.fire(); + }); + tracing::info!("Starting scheduler..."); let scheduler_agent = agent.clone(); let scheduler_handle = tokio::spawn(async move { @@ -35,17 +51,28 @@ async fn main() -> Result<(), Box> { } }); - tracing::info!("Starting webhook server..."); + let sweeper_handle = tokio::spawn(lifecycle::run_werkbank_sweeper( + agent.db_pool.clone(), + stop.clone(), + )); + + tracing::info!("Starting webhook server on port {}...", config.webhook_port); let webhook_agent = agent.clone(); + let webhook_stop = stop.clone(); let webhook_handle = tokio::spawn(async move { - if let Err(e) = webhooks::start_webhook_server(&webhook_agent).await { + if let Err(e) = webhooks::start_webhook_server(&webhook_agent, webhook_stop).await { tracing::error!("Webhook server error: {e}"); } }); tracing::info!("Starting REST API on port {}...", config.agent_port); - api::start_api_server(agent, config.agent_port).await?; + api::start_api_server(agent, config.agent_port, stop).await?; - let _ = tokio::join!(scheduler_handle, webhook_handle); + // The API has drained; the webhook server and sweeper saw the same signal + // and finish within the same grace period. Scans still running are cut + // off here and closed as `interrupted` at the next start. + let _ = tokio::join!(webhook_handle, sweeper_handle); + scheduler_handle.abort(); + tracing::info!("Agent stopped"); Ok(()) } diff --git a/compliance-agent/src/webhooks/server.rs b/compliance-agent/src/webhooks/server.rs index 6e30084..cc633b5 100644 --- a/compliance-agent/src/webhooks/server.rs +++ b/compliance-agent/src/webhooks/server.rs @@ -3,11 +3,23 @@ use std::sync::Arc; use axum::routing::post; use axum::{Extension, Router}; +use compliance_core::shutdown::{self, Shutdown}; + use crate::agent::ComplianceAgent; use crate::error::AgentError; use crate::webhooks::{gitea, github, gitlab}; -pub async fn start_webhook_server(agent: &ComplianceAgent) -> Result<(), AgentError> { +/// Serve the webhook receivers on `agent.config.webhook_port` until `shutdown` +/// fires, then drain in-flight deliveries for at most +/// [`shutdown::GRACE_PERIOD`]. +/// +/// # Errors +/// +/// Returns an error if the port cannot be bound or serving fails. +pub async fn start_webhook_server( + agent: &ComplianceAgent, + shutdown: Shutdown, +) -> Result<(), AgentError> { let app = Router::new() // Per-tenant per-repo webhook URLs: /webhook/{tenant_id}/{platform}/{repo_id} // The tenant_id is resolved from the URL path because webhooks @@ -28,15 +40,16 @@ pub async fn start_webhook_server(agent: &ComplianceAgent) -> Result<(), AgentEr ) .layer(Extension(Arc::new(agent.clone()))); - let addr = "0.0.0.0:3002"; - let listener = tokio::net::TcpListener::bind(addr) + let addr = format!("0.0.0.0:{}", agent.config.webhook_port); + let listener = tokio::net::TcpListener::bind(&addr) .await - .map_err(|e| AgentError::Other(format!("Failed to bind webhook server: {e}")))?; + .map_err(|e| AgentError::Other(format!("Failed to bind webhook server to {addr}: {e}")))?; tracing::info!("Webhook server listening on {addr}"); - axum::serve(listener, app) + shutdown::serve(listener, app, shutdown, shutdown::GRACE_PERIOD) .await .map_err(|e| AgentError::Other(format!("Webhook server error: {e}")))?; + tracing::info!("Webhook server stopped"); Ok(()) } diff --git a/compliance-agent/tests/lifecycle.rs b/compliance-agent/tests/lifecycle.rs new file mode 100644 index 0000000..fa25b15 --- /dev/null +++ b/compliance-agent/tests/lifecycle.rs @@ -0,0 +1,209 @@ +//! Restart recovery and the Werkbank lease sweep across tenants (#259). +//! +//! Runs against a real MongoDB because both walk every tenant database and +//! rely on `update_many` semantics. Skips cleanly when no Mongo is reachable +//! (set `TEST_MONGODB_URI` to point at one; defaults to the local dev cluster). + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use std::time::Duration; + +use chrono::{TimeZone, Utc}; +use mongodb::bson::doc; + +use compliance_agent::database::{Database, DatabasePool}; +use compliance_agent::lifecycle::{ + recover_orphaned_runs, sweep_werkbank_leases, INTERRUPTED_MESSAGE, +}; +use compliance_agent::werkbank::JobQueue; +use compliance_core::models::dast::{DastScanRun, DastScanStatus}; +use compliance_core::models::graph::{GraphBuildRun, GraphBuildStatus}; +use compliance_core::models::pentest::{PentestSession, PentestStatus, PentestStrategy}; +use compliance_core::models::werkbank::{Executor, InputRef, Job, JobStatus}; +use compliance_core::models::{ScanRun, ScanRunStatus, ScanTrigger}; + +const TENANT_A: &str = "00000000-0000-0000-0000-0000000000aa"; +const TENANT_B: &str = "00000000-0000-0000-0000-0000000000bb"; + +/// A pool over a unique db prefix with two tenant databases, or `None` if no +/// Mongo is reachable. +async fn setup() -> Option<(DatabasePool, Database, Database)> { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + // Short and unique: parallel runs must not see each other's tenants, and + // Mongo caps database names at 63 bytes. + let prefix = format!("lc_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]); + let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP lifecycle: no MongoDB reachable at {uri}"); + return None; + }; + let a = pool.for_tenant_id(TENANT_A).await.expect("tenant A db"); + let b = pool.for_tenant_id(TENANT_B).await.expect("tenant B db"); + Some((pool, a, b)) +} + +async fn teardown(pool: &DatabasePool) { + for tenant in [TENANT_A, TENANT_B] { + pool.drop_tenant(tenant).await.ok(); + } +} + +fn run_with(status: ScanRunStatus) -> ScanRun { + let mut run = ScanRun::new("repo-1".into(), ScanTrigger::Manual); + run.status = status; + run +} + +fn session_with(status: PentestStatus) -> PentestSession { + let mut session = PentestSession::new("target-1".into(), PentestStrategy::Quick); + session.status = status; + session +} + +#[tokio::test] +async fn restart_closes_open_runs_in_every_tenant_and_nothing_else() { + let Some((pool, a, b)) = setup().await else { + return; + }; + let now = Utc.timestamp_opt(1_800_000_000, 0).unwrap(); + + // Arrange: tenant A has one open record of each kind plus finished ones + // that must not change; tenant B has a single open scan. + let open_scan = a + .scan_runs() + .insert_one(run_with(ScanRunStatus::Running)) + .await + .unwrap() + .inserted_id; + let done_scan = a + .scan_runs() + .insert_one(run_with(ScanRunStatus::Completed)) + .await + .unwrap() + .inserted_id; + a.graph_builds() + .insert_one(GraphBuildRun::new("repo-1".into())) + .await + .unwrap(); + a.dast_scan_runs() + .insert_one(DastScanRun::new("target-1".into())) + .await + .unwrap(); + let paused = a + .pentest_sessions() + .insert_one(session_with(PentestStatus::Paused)) + .await + .unwrap() + .inserted_id; + a.pentest_sessions() + .insert_one(session_with(PentestStatus::Completed)) + .await + .unwrap(); + let open_in_b = b + .scan_runs() + .insert_one(run_with(ScanRunStatus::Running)) + .await + .unwrap() + .inserted_id; + + // Act + let closed = recover_orphaned_runs(&pool, now).await.unwrap(); + + // Assert: 4 open records in A (scan, graph, DAST, paused pentest) + 1 in B. + assert_eq!(closed, 5); + + let scan = a + .scan_runs() + .find_one(doc! { "_id": &open_scan }) + .await + .unwrap() + .expect("scan run"); + assert_eq!(scan.status, ScanRunStatus::Interrupted); + assert_eq!(scan.error_message.as_deref(), Some(INTERRUPTED_MESSAGE)); + assert_eq!(scan.completed_at, Some(now)); + + let untouched = a + .scan_runs() + .find_one(doc! { "_id": &done_scan }) + .await + .unwrap() + .expect("finished scan run"); + assert_eq!(untouched.status, ScanRunStatus::Completed); + assert_eq!(untouched.error_message, None); + + let graph = a.graph_builds().find_one(doc! {}).await.unwrap().unwrap(); + assert_eq!(graph.status, GraphBuildStatus::Failed); + let dast = a.dast_scan_runs().find_one(doc! {}).await.unwrap().unwrap(); + assert_eq!(dast.status, DastScanStatus::Failed); + assert_eq!(dast.error_message.as_deref(), Some(INTERRUPTED_MESSAGE)); + + let session = a + .pentest_sessions() + .find_one(doc! { "_id": &paused }) + .await + .unwrap() + .expect("paused session"); + assert_eq!(session.status, PentestStatus::Failed); + assert_eq!( + a.pentest_sessions() + .count_documents(doc! { "status": "completed" }) + .await + .unwrap(), + 1 + ); + + let in_b = b + .scan_runs() + .find_one(doc! { "_id": &open_in_b }) + .await + .unwrap() + .expect("tenant B scan run"); + assert_eq!(in_b.status, ScanRunStatus::Interrupted); + + // A second start finds nothing left to close. + assert_eq!(recover_orphaned_runs(&pool, now).await.unwrap(), 0); + + teardown(&pool).await; +} + +#[tokio::test] +async fn sweep_requeues_expired_leases_in_every_tenant() { + let Some((pool, a, b)) = setup().await else { + return; + }; + let t0 = Utc.timestamp_opt(1_800_000_000, 0).unwrap(); + + // Arrange: one leased job per tenant, each with a 10 s lease. + for (db, id) in [(&a, "job-a"), (&b, "job-b")] { + let queue = JobQueue::new(db); + let job = Job::plc_provision(id, "tenant", "target-1", InputRef::blob("sha256:abc"), 180); + queue.enqueue(job, t0).await.unwrap(); + queue + .lease( + "runner-1", + Executor::Docker, + &[], + Duration::from_secs(10), + t0, + ) + .await + .unwrap() + .expect("lease"); + } + + // Act: before the leases expire nothing moves; after, both are requeued. + let early = sweep_werkbank_leases(&pool, t0, 3).await.unwrap(); + let late = sweep_werkbank_leases(&pool, t0 + chrono::Duration::seconds(60), 3) + .await + .unwrap(); + + // Assert + assert_eq!((early.requeued, early.expired), (0, 0)); + assert_eq!((late.requeued, late.expired), (2, 0)); + for (db, id) in [(&a, "job-a"), (&b, "job-b")] { + let record = JobQueue::new(db).get(id).await.unwrap().expect("job"); + assert_eq!(record.status, JobStatus::Queued); + } + + teardown(&pool).await; +} diff --git a/compliance-core/src/config.rs b/compliance-core/src/config.rs index 9d30398..81d3deb 100644 --- a/compliance-core/src/config.rs +++ b/compliance-core/src/config.rs @@ -21,6 +21,8 @@ pub struct AgentConfig { pub searxng_url: Option, pub nvd_api_key: Option, pub agent_port: u16, + /// Port of the separate webhook listener (`WEBHOOK_PORT`, default 3002). + pub webhook_port: u16, /// Most scans (and PR reviews) running at once across all tenants and /// targets (`SCAN_CONCURRENCY`, default 2). Each is a clone plus semgrep and /// syft, so this is what keeps a burst from exhausting the node's memory. @@ -233,6 +235,7 @@ impl Default for AgentConfig { searxng_url: None, nvd_api_key: None, agent_port: 3001, + webhook_port: 3002, scan_concurrency: 2, scan_schedule: "0 0 */6 * * *".to_string(), cve_monitor_schedule: "0 0 * * * *".to_string(), diff --git a/compliance-core/src/lib.rs b/compliance-core/src/lib.rs index 63a701c..b25b7b6 100644 --- a/compliance-core/src/lib.rs +++ b/compliance-core/src/lib.rs @@ -14,6 +14,8 @@ pub mod traits; #[cfg(feature = "axum")] pub mod auth; #[cfg(feature = "axum")] +pub mod shutdown; +#[cfg(feature = "axum")] pub mod tenant_ctx; pub use config::{AgentConfig, AppEnv, DashboardConfig, Features, PlcRuntimeConfig}; diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index abd25a5..9ba5679 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -56,7 +56,12 @@ impl std::fmt::Display for ScanType { pub enum ScanRunStatus { Running, Completed, + /// The scan itself hit an error on the target (clone, tool, pipeline). Failed, + /// The agent stopped (redeploy, crash, out-of-memory kill) while this scan + /// was running. Set at the next startup for runs left `running`. Distinct + /// from `Failed` on purpose: nothing about the customer's code caused it. + Interrupted, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] diff --git a/compliance-core/src/shutdown.rs b/compliance-core/src/shutdown.rs new file mode 100644 index 0000000..e63f0df --- /dev/null +++ b/compliance-core/src/shutdown.rs @@ -0,0 +1,222 @@ +//! Graceful shutdown shared by the agent and the MCP server. +//! +//! Orca stops a container with SIGTERM and kills it a few seconds later, so a +//! server has to stop accepting new connections at once, let requests already +//! in flight finish, and give up on anything still open after a bounded grace +//! period (a streaming MCP session or a slow upload never ends by itself). + +use std::future::IntoFuture; +use std::time::Duration; + +use tokio::sync::watch; + +/// How long in-flight requests get after SIGTERM before remaining connections +/// are dropped. Kept under Docker's default 10 s stop timeout (no service sets +/// a longer one) so the process exits on its own instead of being killed. +pub const GRACE_PERIOD: Duration = Duration::from_secs(8); + +/// Resolve on SIGTERM (container stop) or Ctrl+C (local run). +/// +/// If a handler cannot be installed, that branch never resolves, so the other +/// one still works; the failure is logged rather than ending the process. +pub async fn signal() { + let ctrl_c = async { + if let Err(e) = tokio::signal::ctrl_c().await { + tracing::error!("cannot listen for Ctrl+C: {e}"); + std::future::pending::<()>().await; + } + }; + + #[cfg(unix)] + let terminate = async { + match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { + Ok(mut sigterm) => { + sigterm.recv().await; + } + Err(e) => { + tracing::error!("cannot listen for SIGTERM: {e}"); + std::future::pending::<()>().await; + } + } + }; + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + () = ctrl_c => tracing::info!("Ctrl+C received, shutting down"), + () = terminate => tracing::info!("SIGTERM received, shutting down"), + } +} + +/// Fires the shutdown for every [`Shutdown`] handle made from the same +/// [`channel`]. Dropping it fires it too, so a crashed owner never leaves +/// servers running with nobody left to stop them. +#[derive(Debug)] +pub struct ShutdownTrigger(watch::Sender); + +impl ShutdownTrigger { + /// Tell every server and background loop to stop. + pub fn fire(&self) { + // `send_replace` stores the value even with no receiver left, where + // `send` would fail; either way there is nothing to report. + self.0.send_replace(true); + } +} + +/// A cloneable "has shutdown started?" handle for servers and loops. +#[derive(Debug, Clone)] +pub struct Shutdown(watch::Receiver); + +impl Shutdown { + /// Resolve once shutdown has been fired (or its trigger dropped). + /// + /// Takes `self` by value because axum's `with_graceful_shutdown` wants an + /// owned `'static` future; clone the handle first to wait more than once. + pub async fn wait(mut self) { + // `Err` means the trigger was dropped, which counts as shutdown. + let _ = self.0.wait_for(|stopping| *stopping).await; + } + + /// `true` once shutdown has been fired or its trigger dropped. + pub fn is_fired(&self) -> bool { + *self.0.borrow() || self.0.has_changed().is_err() + } +} + +/// Create a linked trigger and handle. Clone the handle for each server. +pub fn channel() -> (ShutdownTrigger, Shutdown) { + let (tx, rx) = watch::channel(false); + (ShutdownTrigger(tx), Shutdown(rx)) +} + +/// Serve `router` until `shutdown` fires, then stop accepting connections and +/// give in-flight requests `grace` to finish before dropping what is left. +/// +/// # Errors +/// +/// Returns the listener's I/O error if serving fails before shutdown. +pub async fn serve( + listener: tokio::net::TcpListener, + router: axum::Router, + shutdown: Shutdown, + grace: Duration, +) -> std::io::Result<()> { + let server = axum::serve(listener, router).with_graceful_shutdown(shutdown.clone().wait()); + let deadline = async move { + shutdown.wait().await; + tokio::time::sleep(grace).await; + }; + tokio::select! { + result = server.into_future() => result, + () = deadline => { + tracing::warn!( + grace_secs = grace.as_secs(), + "grace period over, dropping connections still open" + ); + Ok(()) + } + } +} + +#[cfg(test)] +#[allow(clippy::expect_used)] +mod tests { + use super::*; + + use axum::routing::get; + use tokio::sync::oneshot; + + /// Bind an ephemeral port and return it with its listener. + async fn listener() -> (tokio::net::TcpListener, std::net::SocketAddr) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind ephemeral port"); + let addr = listener.local_addr().expect("local addr"); + (listener, addr) + } + + #[tokio::test] + async fn dropping_the_trigger_counts_as_shutdown() { + let (trigger, shutdown) = channel(); + assert!(!shutdown.is_fired()); + drop(trigger); + assert!(shutdown.is_fired()); + tokio::time::timeout(Duration::from_secs(1), shutdown.wait()) + .await + .expect("wait resolves once the trigger is gone"); + } + + #[tokio::test] + async fn in_flight_request_finishes_after_shutdown_fires() { + // Arrange: a handler that blocks until the test releases it. + let (release_tx, release_rx) = oneshot::channel::<()>(); + let release_rx = std::sync::Arc::new(tokio::sync::Mutex::new(Some(release_rx))); + let router = axum::Router::new().route( + "/slow", + get(move || { + let release_rx = release_rx.clone(); + async move { + if let Some(rx) = release_rx.lock().await.take() { + let _ = rx.await; + } + "done" + } + }), + ); + let (listener, addr) = listener().await; + let (trigger, shutdown) = channel(); + let server = tokio::spawn(serve(listener, router, shutdown, Duration::from_secs(5))); + + // Act: start the request, fire shutdown while it is in flight, then + // let the handler finish. + let request = tokio::spawn(reqwest::get(format!("http://{addr}/slow"))); + tokio::time::sleep(Duration::from_millis(100)).await; + trigger.fire(); + tokio::time::sleep(Duration::from_millis(100)).await; + let _ = release_tx.send(()); + + // Assert: the request completed and the server then exited on its own. + let body = request + .await + .expect("request task") + .expect("request completes during drain") + .text() + .await + .expect("body"); + assert_eq!(body, "done"); + tokio::time::timeout(Duration::from_secs(2), server) + .await + .expect("server exits after draining") + .expect("server task") + .expect("serve result"); + } + + #[tokio::test] + async fn grace_period_bounds_a_request_that_never_ends() { + let router = axum::Router::new().route( + "/hang", + get(|| async { + std::future::pending::<()>().await; + "never" + }), + ); + let (listener, addr) = listener().await; + let (trigger, shutdown) = channel(); + let server = tokio::spawn(serve( + listener, + router, + shutdown, + Duration::from_millis(200), + )); + + let _request = tokio::spawn(reqwest::get(format!("http://{addr}/hang"))); + tokio::time::sleep(Duration::from_millis(100)).await; + trigger.fire(); + + tokio::time::timeout(Duration::from_secs(2), server) + .await + .expect("server gives up after the grace period") + .expect("server task") + .expect("serve result"); + } +} diff --git a/compliance-mcp/src/main.rs b/compliance-mcp/src/main.rs index cda0d96..466b53b 100644 --- a/compliance-mcp/src/main.rs +++ b/compliance-mcp/src/main.rs @@ -6,6 +6,7 @@ mod tools; use std::sync::Arc; use compliance_core::config::AppEnv; +use compliance_core::shutdown; use database::DatabasePool; use rmcp::transport::{ streamable_http_server::session::local::LocalSessionManager, StreamableHttpServerConfig, @@ -72,7 +73,17 @@ async fn main() -> Result<(), Box> { ); let listener = tokio::net::TcpListener::bind(("0.0.0.0", port)).await?; tracing::info!("MCP HTTP server listening on 0.0.0.0:{port}"); - axum::serve(listener, router).await?; + + // On SIGTERM, tool calls in flight finish; a client's open event + // stream never ends by itself, so it is dropped once the grace period + // is over (the client reconnects to the new container). + let (trigger, stop) = shutdown::channel(); + tokio::spawn(async move { + shutdown::signal().await; + trigger.fire(); + }); + shutdown::serve(listener, router, stop, shutdown::GRACE_PERIOD).await?; + tracing::info!("MCP HTTP server stopped"); } else if app_env.is_hardened() { // stdio synthesises a tenant with no bearer check at all, so a // deployed MCP server must have a port. Fail instead of serving. diff --git a/docs/guide/scanning.md b/docs/guide/scanning.md index 4e2d0f8..87ee74d 100644 --- a/docs/guide/scanning.md +++ b/docs/guide/scanning.md @@ -52,6 +52,7 @@ Each scan progresses through these statuses: | **Running** | Currently executing scan phases | | **Completed** | All phases finished successfully | | **Failed** | Stopped due to an error | +| **Interrupted** | The scanner was restarted (for example by an update) while the scan was running. Nothing in your code caused it; start the scan again. | You can monitor scan progress on the Overview page, which shows the most recent scan runs across all repositories, including the current phase, finding count, and duration.