#[cfg(feature = "vcs")]
use std::collections::BTreeSet;
use std::collections::HashMap;
#[cfg(feature = "vcs")]
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[cfg(feature = "vcs")]
use std::sync::{LazyLock, Mutex, PoisonError};
#[cfg(feature = "vcs")]
use std::time::Duration;
#[cfg(feature = "vcs")]
use shep_core::protocol::Vcs;
use shep_core::protocol::{Lamb, ProcessInfo};
#[cfg(feature = "vcs")]
use tokio::sync::Semaphore;
use crate::limits::stats::StatsState;
use super::context::RpcContext;
#[cfg(feature = "vcs")]
use crate::supervisor::SupervisorHandle;
#[cfg(feature = "vcs")]
use crate::vcs::{Absent, revision_of};
#[cfg(feature = "vcs")]
const VCS_READ_TIMEOUT: Duration = Duration::from_secs(1);
#[cfg(feature = "vcs")]
#[derive(Debug, Default)]
pub(super) struct VcsReads {
slots: Mutex<HashMap<PathBuf, Arc<Semaphore>>>,
}
#[cfg(feature = "vcs")]
impl VcsReads {
fn slot(&self, dir: &Path) -> Arc<Semaphore> {
let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner);
Arc::clone(
slots
.entry(dir.to_path_buf())
.or_insert_with(|| Arc::new(Semaphore::new(1))),
)
}
fn forget_idle(&self) {
let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner);
slots.retain(|_, slot| Arc::strong_count(slot) > 1);
}
}
pub(super) async fn dog_staleness(ctx: &RpcContext) -> (Vec<String>, Vec<String>) {
let stale = ctx.dog_refusals.stale();
let mut pending = ctx.dog_refusals.restarting();
if let Ok(infos) = ctx.supervisor.list_checked().await {
pending.extend(crate::dogs::silent_dogs(&infos, &ctx.dog_refusals));
}
pending.sort();
pending.dedup();
(stale, pending)
}
#[cfg(unix)]
pub(super) async fn handover_refusal(ctx: &RpcContext) -> Option<String> {
match ctx.supervisor.handover_fitness().await {
Ok(crate::handover::Fitness::Carryable) => None,
Ok(crate::handover::Fitness::Refused(reason)) => Some(reason.to_string()),
Err(err) => Some(format!(
"this shepherd could not check whether its flock can be handed over ({err})"
)),
}
}
#[cfg(windows)]
#[expect(
clippy::unused_async,
reason = "one signature for both platforms; the unix arm awaits the supervisor"
)]
pub(super) async fn handover_refusal(_ctx: &RpcContext) -> Option<String> {
Some(
"this shepherd runs on Windows, which has no `execve`, so its flock cannot be handed to \
a successor in place"
.to_string(),
)
}
pub(super) async fn with_live_stats(
stats: &Arc<StatsState>,
mut infos: Vec<ProcessInfo>,
) -> Vec<ProcessInfo> {
let stats = Arc::clone(stats);
let Ok(sample) = tokio::task::spawn_blocking(move || stats.sample_now()).await else {
return infos;
};
for info in &mut infos {
if let Some(reading) = info.pid.and_then(|pid| sample.get(&pid)) {
info.cpu_percent = reading.cpu_percent;
info.memory_bytes = Some(reading.memory_bytes);
info.cpu_ms = Some(reading.cpu_ms);
}
}
infos
}
pub(super) fn with_dog_contact(
refusals: &crate::dogs::DogRefusals,
mut infos: Vec<ProcessInfo>,
) -> Vec<ProcessInfo> {
let stale = refusals.stale();
for info in &mut infos {
if info.dog.is_some() {
info.handshook = Some(refusals.has_handshook(&info.name));
info.dog_stale = Some(stale.contains(&info.name));
}
}
infos
}
pub(super) async fn with_lambs(
stats: &Arc<StatsState>,
mut infos: Vec<ProcessInfo>,
) -> Vec<ProcessInfo> {
if infos.iter().all(|info| info.pid.is_none()) {
return infos;
}
let stats = Arc::clone(stats);
let pids: Vec<u32> = infos.iter().filter_map(|info| info.pid).collect();
let Ok(walked) = tokio::task::spawn_blocking(move || {
let index = stats.lamb_index();
pids.into_iter()
.map(|pid| (pid, stats.lambs_of(&index, pid)))
.collect::<HashMap<u32, Vec<Lamb>>>()
})
.await
else {
return infos;
};
for info in &mut infos {
if let Some(lambs) = info.pid.and_then(|pid| walked.get(&pid)) {
info.lambs = Some(lambs.clone());
}
}
infos
}
#[cfg(feature = "vcs")]
pub(super) async fn with_vcs(
supervisor: &SupervisorHandle,
infos: Vec<ProcessInfo>,
) -> Vec<ProcessInfo> {
let Ok(dirs) = supervisor.working_dirs().await else {
return infos;
};
static READS: LazyLock<VcsReads> = LazyLock::new(VcsReads::default);
fill_vcs(
infos,
&dirs,
VCS_READ_TIMEOUT,
&READS,
Arc::new(revision_of),
)
.await
}
#[cfg(feature = "vcs")]
pub(super) async fn fill_vcs<R>(
mut infos: Vec<ProcessInfo>,
dirs: &HashMap<u32, PathBuf>,
timeout: Duration,
reads: &VcsReads,
read: Arc<R>,
) -> Vec<ProcessInfo>
where
R: Fn(&Path) -> Result<Vcs, Absent> + Send + Sync + 'static,
{
let distinct: BTreeSet<&PathBuf> = infos.iter().filter_map(|info| dirs.get(&info.id)).collect();
let pending = distinct.into_iter().map(|dir| {
let dir = dir.clone();
let read = Arc::clone(&read);
let slot = reads.slot(&dir);
async move {
let outcome = tokio::time::timeout(timeout, async {
let permit = slot.acquire_owned().await.ok()?;
let target = dir.clone();
tokio::task::spawn_blocking(move || {
let found = read(&target);
drop(permit);
found
})
.await
.ok()
})
.await;
(dir, outcome)
}
});
let mut found: HashMap<PathBuf, Vcs> = HashMap::new();
for (dir, outcome) in futures_util::future::join_all(pending).await {
match outcome {
Ok(Some(Ok(vcs))) => {
found.insert(dir, vcs);
}
Ok(Some(Err(absent))) => {
tracing::debug!(dir = %dir.display(), %absent, "no revision to report")
}
Ok(None) => tracing::debug!(dir = %dir.display(), "revision read did not finish"),
Err(_) => tracing::debug!(
dir = %dir.display(),
"revision read timed out, or an earlier read of it is still stuck"
),
}
}
reads.forget_idle();
for info in &mut infos {
match dirs.get(&info.id) {
Some(dir) => info.vcs = found.get(dir).cloned(),
None => tracing::debug!(sheep = %info.name, "no cwd, so no revision to report"),
}
}
infos
}