diff --git a/compliance-agent/src/pipeline/git.rs b/compliance-agent/src/pipeline/git.rs index 330ccf2..0cfb22b 100644 --- a/compliance-agent/src/pipeline/git.rs +++ b/compliance-agent/src/pipeline/git.rs @@ -5,6 +5,7 @@ use git2::{Cred, FetchOptions, RemoteCallbacks, RemoteRedirect, Repository}; use compliance_core::NetGuard; use crate::error::AgentError; +use crate::pipeline::git_retry::Backoff; use crate::tenant_path::{name_segment, tenant_segment}; /// The directory a tenant's checkout of `repo_name` lives in. @@ -173,6 +174,8 @@ pub struct GitOps { net_guard: NetGuard, /// How long and how large a clone or fetch may be. limits: CloneLimits, + /// When a clone or fetch the host failed briefly is tried again. + backoff: Backoff, } impl GitOps { @@ -188,6 +191,7 @@ impl GitOps { credentials, net_guard, limits: CloneLimits::from_env(), + backoff: Backoff::default(), } } @@ -198,6 +202,18 @@ impl GitOps { self } + /// The same operations with another retry schedule (tests). + #[cfg(test)] + fn with_backoff(mut self, backoff: Backoff) -> Self { + self.backoff = backoff; + self + } + + /// When this instance tries a failed clone or fetch again. + pub(crate) fn backoff(&self) -> &Backoff { + &self.backoff + } + /// Fetch options for one bounded transfer: the credentials, no /// redirects, and a progress check that stops the transfer once it /// exceeds [`CloneLimits`], leaving the reason in `stopped`. @@ -290,7 +306,8 @@ impl GitOps { // every scan after it (#486). if repo_path.exists() && prepare_entry(&repo_path) { tracing::info!("fetching updates for existing repo"); - match self.fetch(&repo_path) { + // A 502 is retried before it can be taken for a broken entry. + match self.backoff.retry("fetch", || self.fetch(&repo_path)) { Ok(()) => return Ok(repo_path), Err(AgentError::Git(e)) if is_corruption(&e) => { tracing::warn!( @@ -315,7 +332,8 @@ impl GitOps { // Before creating anything: a refused remote must not leave an entry // behind for the next run to try to fetch. self.check_remote(git_url)?; - self.clone_atomically(git_url, &repo_path)?; + self.backoff + .retry("clone", || self.clone_atomically(git_url, &repo_path))?; tracing::info!("Cloned {git_url} to {}", repo_path.display()); Ok(repo_path) } @@ -833,6 +851,44 @@ mod tests { ); } + #[test] + fn a_clone_the_host_answers_with_502_is_tried_four_times() { + // A git host that answers every request with 502, counting them. + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); + let port = listener.local_addr().expect("addr").port(); + let requests = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let counted = std::sync::Arc::clone(&requests); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { break }; + counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let mut buf = [0u8; 4096]; + let _ = std::io::Read::read(&mut stream, &mut buf); + let _ = std::io::Write::write_all( + &mut stream, + b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ); + } + }); + let scratch = + Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4()))); + let ops = GitOps::new( + &scratch.0.to_string_lossy(), + "tenant-a", + RepoCredentials::default(), + NetGuard::allow_private(), + ) + .with_backoff(crate::pipeline::git_retry::Backoff::immediate()); + + let err = ops + .clone_or_fetch(&format!("http://127.0.0.1:{port}/org/repo.git"), "flaky") + .expect_err("the host never recovers"); + + assert!(err.to_string().contains("502"), "{err}"); + assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 4); + assert!(!ops.clone_path("flaky").exists()); + } + #[test] fn a_fetch_rechecks_the_stored_remote() { // An existing checkout whose `origin` now points somewhere private (a diff --git a/compliance-agent/src/pipeline/git_retry.rs b/compliance-agent/src/pipeline/git_retry.rs new file mode 100644 index 0000000..c5a23b2 --- /dev/null +++ b/compliance-agent/src/pipeline/git_retry.rs @@ -0,0 +1,246 @@ +//! Retrying a clone or fetch the git host failed for a passing reason. +//! +//! A git host that restarts (an OOM kill, a redeploy) answers `502` or +//! refuses connections for a few seconds; every scan that clones in that +//! window would fail. A clone or fetch that fails with a 5xx status or a +//! network error is tried again after 5, 15 and 30 seconds. One that fails +//! for a reason another try cannot change (authentication, 403, 404, a +//! missing reference, a download limit) fails at once. + +use std::time::Duration; + +use git2::{ErrorClass, ErrorCode}; + +use crate::error::AgentError; + +/// The waits between the tries of one clone or fetch: one retry per entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Backoff { + schedule: [Duration; 3], +} + +impl Default for Backoff { + /// Three retries, after 5, 15 and 30 seconds. + fn default() -> Self { + Self { + schedule: [5, 15, 30].map(Duration::from_secs), + } + } +} + +impl Backoff { + /// The same number of retries without waiting (tests). + #[cfg(test)] + pub(crate) fn immediate() -> Self { + Self { + schedule: [Duration::ZERO; 3], + } + } + + /// Run `op`, and run it again after each wait of the schedule while it + /// fails with a [transient](is_transient) error. + /// + /// # Arguments + /// + /// * `what` - What `op` does, for the log (`"clone"`, `"fetch"`). + /// * `op` - The clone or fetch; it must be safe to run again after it failed. + /// + /// # Errors + /// + /// The first error that is not transient, or the last one once the + /// schedule is used up. + pub fn retry( + &self, + what: &str, + mut op: impl FnMut() -> Result, + ) -> Result { + // `iter()` yields `&Duration`, one wait per retry, in order. + let mut waits = self.schedule.iter(); + let mut attempt = 1; + loop { + match op() { + Ok(value) => return Ok(value), + Err(error) => { + let Some(wait) = waits.next().filter(|_| is_retryable(&error)) else { + return Err(error); + }; + tracing::warn!( + attempt, + wait_secs = wait.as_secs(), + error = %error, + "git {what} failed for a passing reason; trying again" + ); + sleep(*wait); + attempt += 1; + } + } + } + } +} + +/// Whether `error` is a git error another try may not see. +fn is_retryable(error: &AgentError) -> bool { + matches!(error, AgentError::Git(e) if is_transient(e)) +} + +/// Whether a git error comes from the host or the network being briefly +/// unavailable: a 5xx status, a timeout, or a connection that failed. +pub fn is_transient(error: &git2::Error) -> bool { + if error.code() == ErrorCode::Auth { + return false; + } + if error.code() == ErrorCode::Timeout { + return true; + } + match error.class() { + // libgit2: "unexpected http status code: 502". + ErrorClass::Http => error + .message() + .strip_prefix("unexpected http status code: ") + .and_then(|status| status.trim().parse::().ok()) + .is_some_and(|status| (500..=599).contains(&status)), + // Every network error libgit2 raises is a failed connection, read or + // write, except these three about the URL itself. + ErrorClass::Net => !["invalid url", "invalid scp-style path", "cannot redirect"] + .iter() + .any(|prefix| error.message().starts_with(prefix)), + _ => false, + } +} + +/// Wait `duration` on this thread. Clones run on the async runtime's worker +/// threads; `block_in_place` hands this worker's other tasks to another +/// worker first, so a waiting retry does not stall them. +fn sleep(duration: Duration) { + if duration.is_zero() { + return; + } + let on_multi_thread_runtime = tokio::runtime::Handle::try_current() + .is_ok_and(|h| h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread); + if on_multi_thread_runtime { + tokio::task::block_in_place(|| std::thread::sleep(duration)); + } else { + std::thread::sleep(duration); + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::{is_transient, Backoff}; + use crate::error::AgentError; + use git2::{ErrorClass, ErrorCode}; + + fn git_error(code: ErrorCode, class: ErrorClass, message: &str) -> git2::Error { + git2::Error::new(code, class, message) + } + + fn http_status(status: u16) -> git2::Error { + git_error( + ErrorCode::GenericError, + ErrorClass::Http, + &format!("unexpected http status code: {status}"), + ) + } + + #[test] + fn a_5xx_status_is_transient() { + assert!(is_transient(&http_status(502))); + assert!(is_transient(&http_status(503))); + assert!(is_transient(&http_status(500))); + } + + #[test] + fn a_failed_connection_or_timeout_is_transient() { + let refused = git_error( + ErrorCode::GenericError, + ErrorClass::Net, + "failed to connect to git.example.com: Connection refused", + ); + let timeout = git_error( + ErrorCode::Timeout, + ErrorClass::Net, + "could not read from socket: timed out", + ); + let unresolved = git_error( + ErrorCode::GenericError, + ErrorClass::Net, + "failed to resolve address for git.example.com: Name or service not known", + ); + assert!(is_transient(&refused)); + assert!(is_transient(&timeout)); + assert!(is_transient(&unresolved)); + } + + #[test] + fn auth_not_found_and_bad_refs_are_not_transient() { + let unauthorized = git_error( + ErrorCode::Auth, + ErrorClass::Http, + "unexpected authentication failure", + ); + let missing_ref = git_error( + ErrorCode::NotFound, + ErrorClass::Reference, + "reference 'refs/heads/nope' not found", + ); + let bad_url = git_error(ErrorCode::GenericError, ErrorClass::Net, "invalid url: x"); + let redirect = git_error( + ErrorCode::GenericError, + ErrorClass::Net, + "cannot redirect from 'a' to 'b'", + ); + assert!(!is_transient(&unauthorized)); + assert!(!is_transient(&http_status(401))); + assert!(!is_transient(&http_status(403))); + assert!(!is_transient(&http_status(404))); + assert!(!is_transient(&missing_ref)); + assert!(!is_transient(&bad_url)); + assert!(!is_transient(&redirect)); + } + + /// An operation that fails with `error` its first `failures` runs, and + /// how often it ran. + fn run_failing(failures: usize, error: fn() -> AgentError) -> (Result, usize) { + let mut runs = 0; + let result = Backoff::immediate().retry("fetch", || { + runs += 1; + if runs <= failures { + Err(error()) + } else { + Ok(7) + } + }); + (result, runs) + } + + #[test] + fn two_502s_then_success_succeeds_on_the_third_try() { + let (result, runs) = run_failing(2, || AgentError::Git(http_status(502))); + assert_eq!(result.unwrap(), 7); + assert_eq!(runs, 3); + } + + #[test] + fn four_502s_fail_after_three_retries() { + let (result, runs) = run_failing(4, || AgentError::Git(http_status(502))); + assert!(matches!(result, Err(AgentError::Git(e)) if e.message().contains("502"))); + assert_eq!(runs, 4); + } + + #[test] + fn a_permanent_error_is_not_retried() { + let (result, runs) = run_failing(4, || AgentError::Git(http_status(404))); + assert!(result.is_err()); + assert_eq!(runs, 1); + let (limit, runs) = run_failing(4, || AgentError::Other("download limit".to_string())); + assert!(limit.is_err()); + assert_eq!(runs, 1); + } + + #[test] + fn the_default_schedule_waits_5_15_and_30_seconds() { + let secs = Backoff::default().schedule.map(|d| d.as_secs()); + assert_eq!(secs, [5, 15, 30]); + } +} diff --git a/compliance-agent/src/pipeline/git_submodules.rs b/compliance-agent/src/pipeline/git_submodules.rs index f328800..901fb4f 100644 --- a/compliance-agent/src/pipeline/git_submodules.rs +++ b/compliance-agent/src/pipeline/git_submodules.rs @@ -91,10 +91,12 @@ impl GitOps { } else { &anonymous }; - let mut options = SubmoduleUpdateOptions::new(); - options.fetch(credentials.fetch_options()); - submodule.update(true, Some(&mut options))?; - Ok(()) + self.backoff().retry("submodule fetch", || { + let mut options = SubmoduleUpdateOptions::new(); + options.fetch(credentials.fetch_options()); + submodule.update(true, Some(&mut options))?; + Ok(()) + }) } } diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 399302a..7bd5f6a 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -17,6 +17,7 @@ pub mod embedded_versions; pub mod finding_store; pub mod firmware_sbom; pub mod git; +pub mod git_retry; pub mod git_submodules; pub mod gitleaks; mod graph_build;