fix(scheduler): scheduled scans are spread out and at most two clones run per git host #547
No files matched your search
@@ -146,7 +146,8 @@ impl ComplianceAgent {
|
||||
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
|
||||
/// run at once, and a request for a target that is already being scanned is
|
||||
/// coalesced — it becomes the one pending follow-up that this task runs next,
|
||||
/// or it is dropped if a follow-up is already pending. Every trigger
|
||||
/// or it is dropped if a follow-up is already pending. A scheduled scan
|
||||
/// first waits a random [`crate::scan_gate::start_delay`]. Every trigger
|
||||
/// (click, webhook, scheduler, demo seed) comes through here.
|
||||
///
|
||||
/// # Errors
|
||||
@@ -158,6 +159,17 @@ impl ComplianceAgent {
|
||||
target_id: &str,
|
||||
trigger: compliance_core::models::ScanTrigger,
|
||||
) -> Result<(), crate::error::AgentError> {
|
||||
// Scheduled scans spread out before they take a slot or the target.
|
||||
let delay = crate::scan_gate::start_delay(&trigger);
|
||||
if !delay.is_zero() {
|
||||
tracing::debug!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
delay_ms = delay.as_millis(),
|
||||
"scheduled scan waits"
|
||||
);
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
let key = ScanGate::key(tenant_id, target_id);
|
||||
match self.scan_gate.admit(&key, trigger.clone()) {
|
||||
Admission::Run => {}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
//! At most two clones or fetches against one git host at a time.
|
||||
//!
|
||||
//! Every target of a tenant usually lives on the same git host. When scans of
|
||||
//! several of them start together (a git sync creating targets, scans resumed
|
||||
//! after a restart), they would all clone from that host at once; a small
|
||||
//! self-hosted Gitea answers that with an OOM kill and `502`s. The limit is
|
||||
//! held only around the clone or fetch itself, not the rest of the scan, and
|
||||
//! another host's clones go ahead meanwhile.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Condvar, LazyLock, Mutex, PoisonError};
|
||||
|
||||
/// How many clones or fetches may run against one git host at once.
|
||||
pub const CLONES_PER_HOST: usize = 2;
|
||||
|
||||
/// The limiter every clone and fetch of this process goes through.
|
||||
pub static CLONE_SLOTS: LazyLock<HostLimiter> = LazyLock::new(|| HostLimiter::new(CLONES_PER_HOST));
|
||||
|
||||
/// A counting semaphore per git host, for blocking (non-async) callers.
|
||||
#[derive(Debug)]
|
||||
pub struct HostLimiter {
|
||||
per_host: usize,
|
||||
hosts: Mutex<HashMap<String, Arc<HostSlots>>>,
|
||||
}
|
||||
|
||||
/// The slots of one host: how many are taken, and a wake-up for waiters.
|
||||
#[derive(Debug, Default)]
|
||||
struct HostSlots {
|
||||
taken: Mutex<usize>,
|
||||
freed: Condvar,
|
||||
}
|
||||
|
||||
/// One taken slot of a host; dropping it frees the slot.
|
||||
#[derive(Debug)]
|
||||
pub struct HostPermit {
|
||||
slots: Arc<HostSlots>,
|
||||
}
|
||||
|
||||
impl HostLimiter {
|
||||
/// A limiter allowing `per_host` operations per host at once (at least one).
|
||||
pub fn new(per_host: usize) -> Self {
|
||||
Self {
|
||||
per_host: per_host.max(1),
|
||||
hosts: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait until `host` has a free slot and take it.
|
||||
///
|
||||
/// Blocks the calling thread. On the async runtime's worker threads it
|
||||
/// hands the worker's other tasks to another worker first.
|
||||
pub fn acquire(&self, host: &str) -> HostPermit {
|
||||
// The map lock is held only for the lookup, never while waiting.
|
||||
let slots = {
|
||||
let mut hosts = self.hosts.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
Arc::clone(hosts.entry(host.to_ascii_lowercase()).or_default())
|
||||
};
|
||||
let taken = slots.taken.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut taken = if *taken < self.per_host {
|
||||
taken
|
||||
} else {
|
||||
tracing::info!(host, "waiting for a free clone slot on this git host");
|
||||
off_the_runtime(|| {
|
||||
slots
|
||||
.freed
|
||||
.wait_while(taken, |taken| *taken >= self.per_host)
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
})
|
||||
};
|
||||
*taken += 1;
|
||||
drop(taken);
|
||||
HostPermit { slots }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HostPermit {
|
||||
fn drop(&mut self) {
|
||||
let mut taken = self
|
||||
.slots
|
||||
.taken
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
*taken = taken.saturating_sub(1);
|
||||
self.slots.freed.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
/// Run blocking `work` without stalling the async runtime: on a multi-thread
|
||||
/// runtime's worker, `block_in_place` moves the worker's other tasks first.
|
||||
pub(crate) fn off_the_runtime<R>(work: impl FnOnce() -> R) -> R {
|
||||
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(work)
|
||||
} else {
|
||||
work()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::HostLimiter;
|
||||
use std::sync::{mpsc, Arc};
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn a_host_runs_at_most_two_while_another_host_proceeds() {
|
||||
let limiter = Arc::new(HostLimiter::new(2));
|
||||
let first = limiter.acquire("git.example.com");
|
||||
let _second = limiter.acquire("git.example.com");
|
||||
|
||||
// A third clone from the same host waits.
|
||||
let (sent, received) = mpsc::channel();
|
||||
let waiting = Arc::clone(&limiter);
|
||||
let third = std::thread::spawn(move || {
|
||||
let permit = waiting.acquire("GIT.example.com");
|
||||
sent.send(()).expect("send");
|
||||
drop(permit);
|
||||
});
|
||||
assert!(received.recv_timeout(Duration::from_millis(100)).is_err());
|
||||
|
||||
// Another host is not held up by the full one.
|
||||
let _other = limiter.acquire("gitlab.example.org");
|
||||
|
||||
// A freed slot lets the waiting clone go ahead.
|
||||
drop(first);
|
||||
received
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("the third clone runs once a slot is free");
|
||||
third.join().expect("join");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_permit_frees_its_slot() {
|
||||
let limiter = HostLimiter::new(1);
|
||||
drop(limiter.acquire("git.example.com"));
|
||||
// Would block forever if the slot had not been freed.
|
||||
let _again = limiter.acquire("git.example.com");
|
||||
}
|
||||
}
|
||||
@@ -298,6 +298,11 @@ impl GitOps {
|
||||
#[tracing::instrument(skip_all, fields(tenant = %self.tenant_id, repo_name = %repo_name))]
|
||||
pub fn clone_or_fetch(&self, git_url: &str, repo_name: &str) -> Result<PathBuf, AgentError> {
|
||||
reject_ssh_url(git_url)?;
|
||||
// At most two clones or fetches per git host, held to the end of this
|
||||
// one; a refused remote has no host and fails below anyway.
|
||||
let _host_slot = self
|
||||
.remote_host(git_url)
|
||||
.map(|host| crate::pipeline::clone_limit::CLONE_SLOTS.acquire(&host));
|
||||
// Per tenant: two tenants with the same target name get two checkouts.
|
||||
let repo_path = self.clone_path(repo_name);
|
||||
|
||||
|
||||
@@ -108,19 +108,11 @@ pub fn is_transient(error: &git2::Error) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Wait `duration` on this thread, without stalling the async runtime's
|
||||
/// other tasks (clones run on its worker threads).
|
||||
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);
|
||||
if !duration.is_zero() {
|
||||
crate::pipeline::clone_limit::off_the_runtime(|| std::thread::sleep(duration));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ pub mod binary_depth;
|
||||
pub mod build_lifecycle;
|
||||
pub mod change;
|
||||
pub mod clamav;
|
||||
pub mod clone_limit;
|
||||
pub mod code_review;
|
||||
pub mod cppcheck;
|
||||
pub(crate) mod csaf_feed;
|
||||
|
||||
@@ -14,15 +14,34 @@
|
||||
//! scan will pick up the latest code anyway. Ten pushes during a long scan
|
||||
//! therefore cost two scans, not ten. Dropped requests are never billed: only
|
||||
//! a scan that actually ran emits usage.
|
||||
//!
|
||||
//! A scheduled scan also starts after a random delay of up to
|
||||
//! [`SCHEDULED_SCAN_JITTER`], so the scans of a tenant's repositories (often
|
||||
//! all on one git host) do not start in the same second.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use dashmap::mapref::entry::Entry;
|
||||
use dashmap::DashMap;
|
||||
use rand::Rng;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
|
||||
use compliance_core::models::ScanTrigger;
|
||||
|
||||
/// The longest a scheduled scan waits before it starts.
|
||||
pub const SCHEDULED_SCAN_JITTER: Duration = Duration::from_secs(30);
|
||||
|
||||
/// How long a scan with `trigger` waits before it starts: a random delay of
|
||||
/// up to [`SCHEDULED_SCAN_JITTER`] for a scheduled scan, none for a scan a
|
||||
/// webhook or a person started.
|
||||
pub fn start_delay(trigger: &ScanTrigger) -> Duration {
|
||||
match trigger {
|
||||
ScanTrigger::Scheduled => rand::rng().random_range(Duration::ZERO..=SCHEDULED_SCAN_JITTER),
|
||||
ScanTrigger::Webhook | ScanTrigger::Manual | ScanTrigger::Support => Duration::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened to a scan request.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Admission {
|
||||
@@ -153,8 +172,30 @@ impl Drop for HeldTarget<'_> {
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::{Admission, HeldTarget, ScanGate};
|
||||
use super::{start_delay, Admission, HeldTarget, ScanGate, SCHEDULED_SCAN_JITTER};
|
||||
use compliance_core::models::ScanTrigger;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn a_scheduled_scan_waits_within_the_jitter() {
|
||||
let delays: Vec<Duration> = (0..1000)
|
||||
.map(|_| start_delay(&ScanTrigger::Scheduled))
|
||||
.collect();
|
||||
assert!(delays.iter().all(|d| *d <= SCHEDULED_SCAN_JITTER));
|
||||
// Spread out, not one fixed delay.
|
||||
assert!(delays.iter().any(|d| *d != delays[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webhook_manual_and_support_scans_start_at_once() {
|
||||
for trigger in [
|
||||
ScanTrigger::Webhook,
|
||||
ScanTrigger::Manual,
|
||||
ScanTrigger::Support,
|
||||
] {
|
||||
assert_eq!(start_delay(&trigger), Duration::ZERO);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_coalesces_into_one_run_and_one_follow_up() {
|
||||
|
||||
Reference in new issue
Block a user