use std::time::Instant;
use crate::containment::tree_kill::Settled;
use crate::containment::TreeDrain;
use crate::error::Error;
pub(crate) enum DrainEdge<'a> {
#[cfg(target_os = "linux")]
Cgroup(&'a crate::containment::cgroup::CgroupLeaf),
#[cfg(windows)]
Job(&'a crate::containment::windows::JobHandle),
#[cfg(target_os = "macos")]
Marker(&'a crate::containment::fdmarker::Marker),
}
impl DrainEdge<'_> {
pub(crate) fn wait(&self, deadline: Option<Instant>) -> Result<TreeDrain, Error> {
self.wait_past(deadline, &Settled::default())
}
#[cfg_attr(
not(windows),
allow(unused_variables, reason = "only a Job's edge reads what a wait settled")
)]
pub(crate) fn wait_past(&self, deadline: Option<Instant>, settled: &Settled) -> Result<TreeDrain, Error> {
match self {
#[cfg(target_os = "linux")]
DrainEdge::Cgroup(leaf) => leaf.wait_drained(deadline),
#[cfg(windows)]
DrainEdge::Job(job) => job.wait_drained_past(deadline, settled),
#[cfg(target_os = "macos")]
DrainEdge::Marker(m) => m.wait_drained(deadline),
}
}
#[cfg(feature = "tokio")]
pub(crate) async fn wait_async(&self, deadline: Option<Instant>) -> Result<TreeDrain, Error> {
self.wait_async_past(deadline, &Settled::default()).await
}
#[cfg(feature = "tokio")]
#[cfg_attr(
not(windows),
allow(unused_variables, reason = "only a Job's edge reads what a wait settled")
)]
pub(crate) async fn wait_async_past(
&self,
deadline: Option<Instant>,
settled: &Settled,
) -> Result<TreeDrain, Error> {
match self {
#[cfg(target_os = "linux")]
DrainEdge::Cgroup(leaf) => cgroup_wait_tree_drained(leaf, deadline).await,
#[cfg(windows)]
DrainEdge::Job(job) => job_wait_tree_drained(job, deadline, settled).await,
#[cfg(target_os = "macos")]
DrainEdge::Marker(m) => {
m.check_read_end_still_valid()?;
debug_assert_ne!(
crate::containment::marker_eof::write_end_check(m.read_end()),
crate::containment::marker_eof::WriteEndCheck::HeldByUs,
"the supervisor still holds a copy of the marker write end - the tree-drain edge can never fire"
);
wait_tree_deadline(m.read_end(), deadline).await
}
}
}
}
#[cfg(all(feature = "tokio", target_os = "macos"))]
pub(crate) async fn wait_tree_drained(read_end: std::os::fd::BorrowedFd<'_>) -> Result<(), Error> {
wait_tree_drained_watched(read_end, None).await
}
#[cfg(all(feature = "tokio", target_os = "macos"))]
pub(crate) async fn wait_tree_deadline(
read_end: std::os::fd::BorrowedFd<'_>,
deadline: Option<Instant>,
) -> Result<TreeDrain, Error> {
use crate::tokio::wait::{arm_at, tokio_now};
match deadline {
None => {
wait_tree_drained(read_end).await?;
Ok(TreeDrain::AllMarkersClosed)
}
Some(at) => {
if crate::wait::remaining_at(deadline, tokio_now()) == Some(std::time::Duration::ZERO) {
return crate::containment::marker_eof::probe(read_end);
}
match arm_at(at, wait_tree_drained_inner(read_end, false, None)).await {
Some(res) => res.map(|()| TreeDrain::AllMarkersClosed),
None => crate::containment::marker_eof::probe(read_end),
}
}
}
}
#[cfg(all(test, feature = "tokio", target_os = "macos"))]
pub(crate) mod declined_hook {
use std::cell::RefCell;
use ::tokio::sync::mpsc::UnboundedSender;
thread_local! {
static DECLINED: RefCell<Option<UnboundedSender<()>>> = const { RefCell::new(None) };
}
pub(crate) fn notify() {
DECLINED.with(|d| {
if let Some(tx) = d.borrow().as_ref() {
let sent = tx.send(());
debug_assert!(sent.is_ok(), "declined_hook receiver dropped before the hook fired");
}
});
}
#[must_use]
pub(crate) struct DeclinedGuard {
_private: (),
}
impl DeclinedGuard {
pub(crate) fn install(tx: UnboundedSender<()>) -> Self {
DECLINED.with(|d| {
let mut slot = d.borrow_mut();
debug_assert!(slot.is_none(), "a declined_hook is already installed on this thread");
*slot = Some(tx);
});
Self { _private: () }
}
}
impl Drop for DeclinedGuard {
fn drop(&mut self) {
DECLINED.with(|d| {
let prev = d.borrow_mut().take();
debug_assert!(
prev.is_some(),
"declined_hook slot was cleared before its guard dropped"
);
});
}
}
}
#[cfg(all(test, feature = "tokio", target_os = "macos"))]
pub(crate) async fn wait_tree_drained_for_test(
read_end: std::os::fd::BorrowedFd<'_>,
armed: std::sync::mpsc::Sender<std::os::fd::RawFd>,
) -> Result<(), Error> {
wait_tree_drained_watched(read_end, Some(armed)).await
}
#[cfg(all(feature = "tokio", target_os = "macos"))]
async fn wait_tree_drained_watched(
read_end: std::os::fd::BorrowedFd<'_>,
armed: Option<std::sync::mpsc::Sender<std::os::fd::RawFd>>,
) -> Result<(), Error> {
wait_tree_drained_inner(read_end, true, armed).await
}
#[cfg(all(feature = "tokio", target_os = "macos"))]
async fn wait_tree_drained_inner(
read_end: std::os::fd::BorrowedFd<'_>,
unbounded_wait: bool,
armed: Option<std::sync::mpsc::Sender<std::os::fd::RawFd>>,
) -> Result<(), Error> {
use std::os::fd::AsRawFd;
use crate::containment::marker_eof::DrainOutcome;
use crate::tokio::wait::watch_readable;
use ::tokio::io::unix::AsyncFd;
use ::tokio::io::Interest;
let kq = crate::containment::marker_eof::arm(read_end, unbounded_wait)?;
if let Some(tx) = armed {
let sent = tx.send(kq.as_raw_fd());
debug_assert!(
sent.is_ok(),
"the `armed` receiver was dropped before the kqueue was armed"
);
}
let afd = AsyncFd::with_interest(kq, Interest::READABLE).map_err(Error::Io)?;
watch_readable(&afd, move |kq| {
match crate::containment::marker_eof::drain_kqueue(kq, read_end, unbounded_wait)? {
DrainOutcome::Drained(_) => Ok(Some(())),
DrainOutcome::Declined => {
#[cfg(test)]
declined_hook::notify();
Ok(None)
}
DrainOutcome::Spurious => Ok(None),
}
})
.await
}
#[cfg(all(feature = "tokio", target_os = "linux"))]
pub(crate) async fn cgroup_wait_tree_drained(
leaf: &crate::containment::cgroup::CgroupLeaf,
deadline: Option<Instant>,
) -> Result<TreeDrain, Error> {
use crate::containment::cgroup::DrainStep;
use crate::tokio::wait::{arm_at, tokio_now};
loop {
match leaf.drain_step_on(deadline, tokio_now)? {
DrainStep::Done(drain) => return Ok(drain),
DrainStep::Block {
listener,
deadline: None,
} => {
#[cfg(test)]
crate::wait::block_probe::blocking(None, crate::wait::block_probe::WaitObject::DrainAwait);
#[cfg(test)]
crate::tokio::wait::armed_deadline_seam::notify(
crate::tokio::wait::armed_deadline_seam::Armed::Unbounded,
);
listener.await
}
DrainStep::Block {
listener,
deadline: Some(at),
} => {
#[cfg(test)]
crate::wait::block_probe::blocking(
Some(at.saturating_duration_since(tokio_now())),
crate::wait::block_probe::WaitObject::DrainAwait,
);
let _ = arm_at(at, listener).await;
}
}
}
}
#[cfg(all(feature = "tokio", windows))]
async fn snapshot_members_on_pool(
job: &crate::containment::windows::JobHandle,
) -> Result<Vec<crate::containment::windows::Found>, Error> {
use crate::containment::windows::unsignalled_members_of;
use std::os::windows::io::AsHandle as _;
let held = job.handle().try_clone_to_owned().map_err(|e| Error::Unassessable {
detail: "the job's handle could not be duplicated for the snapshot of its members".to_owned(),
source: Some(Error::io_cause(e)),
})?;
crate::tokio::wait::on_blocking_pool("the snapshot of a job's members", move || {
unsignalled_members_of(held.as_handle())
})
.await
.map_err(|unjoined| {
use crate::tokio::wait::Unjoined;
let (detail, cause) = match unjoined {
Unjoined::NotRun(cause) => (
"the snapshot of the job's members did not run, so their exit cannot be observed",
cause,
),
Unjoined::Unknown(cause) => (
"nothing can be said of what the snapshot of the job's members did, so their exit cannot be observed",
cause,
),
};
Error::Unassessable {
detail: detail.to_owned(),
source: Some(std::sync::Arc::new(cause)),
}
})?
}
#[cfg(all(feature = "tokio", windows))]
async fn job_wait_tree_drained(
job: &crate::containment::windows::JobHandle,
deadline: Option<Instant>,
settled: &Settled,
) -> Result<TreeDrain, Error> {
use crate::containment::tree_kill::wait_for_member_async;
use crate::containment::windows::{ConfirmStep, ConfirmWalk, Ended, Round};
use crate::identity::HostKernel;
use crate::os_process::windows::registered_wait::{wait_any, Woke};
let deadline = crate::tokio::wait::to_real_clock(deadline);
loop {
let last_round = deadline.is_some_and(|at| crate::wait::now() >= at);
let round = match job.drain_round(last_round)? {
Round::Watch(watch) => {
let ended = if last_round {
watch.poll()?
} else {
match wait_any(watch.handles(), deadline).await.map_err(Error::Io)? {
Woke::Signalled => Ended::Signalled,
Woke::TimedOut => watch.poll()?,
}
};
match ended {
Ended::Deadline => return Ok(TreeDrain::MembersRemain),
Ended::Signalled => job.after_signalled(&watch)?,
}
}
round => round,
};
match round {
Round::Answer(drain) => return Ok(drain),
Round::Confirm => {
let Some(count) = job.count_to_confirm()? else {
return Ok(TreeDrain::AllMembersExited);
};
let mut walk = ConfirmWalk::new(job, count, snapshot_members_on_pool(job).await, settled);
loop {
match walk.next() {
ConfirmStep::Wait(id) => {
walk.waited(id, wait_for_member_async(&HostKernel, id, deadline).await)
}
ConfirmStep::Done(answer) => return answer,
}
}
}
Round::List | Round::Watch(_) => {}
}
::tokio::task::yield_now().await;
}
}