use std::cell::Cell;
use super::dir::WalkStep;
type Hook = Box<dyn FnOnce()>;
thread_local! {
static ON_TAKE_PLACEMENT: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static AFTER_PROCS_READ: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static AFTER_TERMINATE_PIN: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static MEMBER_TERMS: std::cell::RefCell<Vec<MemberTerm>> = const { std::cell::RefCell::new(Vec::new()) };
static AFTER_SHUT_READ: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = std::cell::RefCell::new(None);
static WAIT_POLLING: std::cell::RefCell<Option<std::sync::mpsc::Sender<()>>> = const { std::cell::RefCell::new(None) };
static ON_WAIT: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static BEFORE_STATE_READ: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static WAITED_PIDFD: Cell<Option<std::os::fd::RawFd>> = const { Cell::new(None) };
static FORCE_KILL_SUPPORTED: Cell<bool> = const { Cell::new(false) };
static FORCE_REPORT_CHANNEL_FAILURE: Cell<bool> = const { Cell::new(false) };
static FORCE_PLACEMENT_WRITE_RESULT: Cell<Option<isize>> = const { Cell::new(None) };
static FORCE_OCCUPY_BEFORE_UNWIND: Cell<bool> = const { Cell::new(false) };
static DRAIN_BLOCKING: std::cell::RefCell<Option<std::sync::mpsc::Sender<()>>> = const { std::cell::RefCell::new(None) };
static DRAIN_ZERO_REMAINING: std::cell::RefCell<Option<std::sync::mpsc::Sender<()>>> = const { std::cell::RefCell::new(None) };
static WAIT_SITE_PARK: std::cell::RefCell<Option<std::sync::mpsc::Sender<WaitSitePark>>> = const { std::cell::RefCell::new(None) };
static WAIT_DEADLINE_ARG: std::cell::RefCell<Option<std::sync::mpsc::Sender<std::time::Instant>>> = const { std::cell::RefCell::new(None) };
static LEAF_STEPS: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
static FORCE_INOTIFY_FAILURE: Cell<bool> = const { Cell::new(false) };
static FORCE_KILL_CHECK_ERRNO: Cell<Option<i32>> = const { Cell::new(None) };
static FORCE_LEAF_OPEN_FAILURE: Cell<bool> = const { Cell::new(false) };
static FAIL_KILL_WRITES: Cell<bool> = const { Cell::new(false) };
static REFUSED_KILL_WRITES: Cell<u32> = const { Cell::new(0) };
static FAIL_NEXT_KILL_WRITE: Cell<bool> = const { Cell::new(false) };
static PIDFD_INFO_MISSING: Cell<bool> = const { Cell::new(false) };
static PROC_HIDDEN: Cell<bool> = const { Cell::new(false) };
static BEFORE_KILL_WRITE: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static AFTER_KILL_WRITE: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static FORCED_PIDFD_CGROUP_ID: Cell<Option<u64>> = const { Cell::new(None) };
static BEFORE_WALK_OPEN: std::cell::RefCell<Option<WalkHook>> = const { std::cell::RefCell::new(None) };
static BEFORE_SWEEP_REMOVE: std::cell::RefCell<Option<WalkHook>> = const { std::cell::RefCell::new(None) };
static BEFORE_DRAIN_BLOCK: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static AFTER_DRAIN_WARN: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static WALK_FAILURE: std::cell::RefCell<Option<WalkFailure>> = const { std::cell::RefCell::new(None) };
static PROC_HIDDEN_AS: Cell<Option<i32>> = const { Cell::new(None) };
static PIDFD_INFO_FAILS: Cell<Option<i32>> = const { Cell::new(None) };
static PROBE_DUMPABLE: Cell<bool> = const { Cell::new(false) };
static PROBE_CLOSE_RANGE_ALLOWED: Cell<Option<u32>> = const { Cell::new(None) };
static PROBE_FD_DIR_FAILS: Cell<bool> = const { Cell::new(false) };
static BEFORE_PROBE_KILL: crate::oneshot_hook::OneShotHook<libc::pid_t, Option<i32>> = const { crate::oneshot_hook::OneShotHook::new() };
static PROBE_STEPS: std::cell::RefCell<Vec<ProbeStep>> = const { std::cell::RefCell::new(Vec::new()) };
static CGROUP_ID_FAILS: Cell<Option<i32>> = const { Cell::new(None) };
static LIVENESS_READ_FAILS: Cell<Option<i32>> = const { Cell::new(None) };
static SUBTREE_FAILS: Cell<Option<i32>> = const { Cell::new(None) };
static TERMINATE_FAILS: Cell<Option<(TerminateStep, i32, bool)>> = const { Cell::new(None) };
static RMDIR_HOOK: std::cell::RefCell<Option<RmdirHook>> = std::cell::RefCell::new(None);
static FORCE_KILL_ON_DROP_WAITID_EINTR: Cell<bool> = const { Cell::new(false) };
static FORCE_KILL_ON_DROP_KILL_FAILURE: Cell<bool> = const { Cell::new(false) };
static AFTER_FORK_STILL_LOCKED: std::cell::RefCell<Option<Hook>> = std::cell::RefCell::new(None);
static ON_FORK_RUNNING_LOCK_CONTENDED: std::cell::RefCell<Option<Hook>> = std::cell::RefCell::new(None);
static FORK_RUNNING_LOCK_HELD_REPORT_FD: Cell<Option<std::os::fd::RawFd>> = const { Cell::new(None) };
}
type RmdirHook = Box<dyn FnMut(&std::path::Path) -> std::io::Result<()>>;
pub(crate) fn fail_kill_writes() -> FailKillWrites {
arm_fail_kill_writes(None)
}
pub(crate) fn fail_kill_writes_releasing_on_unwritten_kill(release: impl FnOnce() + 'static) -> FailKillWrites {
arm_fail_kill_writes(Some((Box::new(release), ReleaseAt::UnwrittenKill)))
}
pub(crate) fn fail_kill_writes_releasing_at_wait(release: impl FnOnce() + 'static) -> FailKillWrites {
arm_fail_kill_writes(Some((Box::new(release), ReleaseAt::EveryWait)))
}
enum ReleaseAt {
UnwrittenKill,
EveryWait,
}
fn arm_fail_kill_writes(release: Option<(Box<dyn FnOnce()>, ReleaseAt)>) -> FailKillWrites {
FAIL_KILL_WRITES.with(|f| f.set(true));
REFUSED_KILL_WRITES.with(|n| n.set(0));
FailKillWrites {
_no_drain_wait: set_before_drain_block(|| {
fail_once_unwinding(
"a teardown whose cgroup.kill failed waited for the leaf's drain, which its members may never end",
);
}),
_no_unwritten_kill: crate::child::spawn::fault::set_between_kill_and_wait(move || {
let unwritten = REFUSED_KILL_WRITES.with(Cell::get) == 0;
if let Some((release, at)) = release {
if unwritten || matches!(at, ReleaseAt::EveryWait) {
release();
}
}
if unwritten {
fail_once_unwinding(
"a teardown took a kill as delivered and waited for its child, though no cgroup.kill was written",
);
}
}),
}
}
fn fail_once_unwinding(message: &str) {
if !std::thread::panicking() {
panic!("{message}");
}
}
#[must_use = "the writes succeed again as soon as the guard is dropped"]
pub(crate) struct FailKillWrites {
_no_drain_wait: crate::oneshot_hook::Armed,
_no_unwritten_kill: crate::oneshot_hook::Armed,
}
impl Drop for FailKillWrites {
fn drop(&mut self) {
FAIL_KILL_WRITES.with(|f| f.set(false));
}
}
pub(crate) fn kill_writes_fail() -> bool {
let fails = FAIL_KILL_WRITES.with(Cell::get);
if fails {
REFUSED_KILL_WRITES.with(|n| n.set(n.get() + 1));
}
fails
}
pub(crate) fn fail_next_kill_write() -> FailNextKillWrite {
FAIL_NEXT_KILL_WRITE.with(|f| f.set(true));
FailNextKillWrite(())
}
#[must_use = "the failure is cleared as soon as the guard is dropped"]
pub(crate) struct FailNextKillWrite(());
impl Drop for FailNextKillWrite {
fn drop(&mut self) {
FAIL_NEXT_KILL_WRITE.with(|f| f.set(false));
}
}
pub(crate) fn take_next_kill_write_failure() -> bool {
FAIL_NEXT_KILL_WRITE.with(|f| f.replace(false))
}
pub(crate) fn miss_pidfd_info() -> MissPidfdInfo {
PIDFD_INFO_MISSING.with(|f| f.set(true));
MissPidfdInfo(())
}
#[must_use = "PIDFD_GET_INFO is back as soon as the guard is dropped"]
pub(crate) struct MissPidfdInfo(());
impl Drop for MissPidfdInfo {
fn drop(&mut self) {
PIDFD_INFO_MISSING.with(|f| f.set(false));
}
}
pub(crate) fn pidfd_info_missing() -> bool {
PIDFD_INFO_MISSING.with(Cell::get)
}
pub(crate) fn hide_proc() -> HideProc {
PROC_HIDDEN.with(|f| f.set(true));
HideProc(())
}
#[must_use = "/proc is visible again as soon as the guard is dropped"]
pub(crate) struct HideProc(());
impl Drop for HideProc {
fn drop(&mut self) {
PROC_HIDDEN.with(|f| f.set(false));
}
}
pub(crate) fn hide_proc_as(errno: i32) -> HideProcAs {
PROC_HIDDEN_AS.with(|f| f.set(Some(errno)));
HideProcAs(())
}
#[must_use = "/proc is visible again as soon as the guard is dropped"]
pub(crate) struct HideProcAs(());
impl Drop for HideProcAs {
fn drop(&mut self) {
PROC_HIDDEN_AS.with(|f| f.set(None));
}
}
pub(crate) fn proc_hidden_as() -> Option<i32> {
PROC_HIDDEN_AS
.with(Cell::get)
.or_else(|| PROC_HIDDEN.with(Cell::get).then_some(libc::ENOENT))
}
pub(crate) fn fail_pidfd_info() -> FailPidfdInfo {
fail_pidfd_info_with(libc::EIO)
}
pub(crate) fn fail_pidfd_info_with(errno: i32) -> FailPidfdInfo {
PIDFD_INFO_FAILS.with(|f| f.set(Some(errno)));
FailPidfdInfo(())
}
#[must_use = "PIDFD_GET_INFO answers again as soon as the guard is dropped"]
pub(crate) struct FailPidfdInfo(());
impl Drop for FailPidfdInfo {
fn drop(&mut self) {
PIDFD_INFO_FAILS.with(|f| f.set(None));
}
}
pub(crate) fn pidfd_info_fails() -> Option<i32> {
PIDFD_INFO_FAILS.with(Cell::get)
}
pub(crate) fn keep_probe_dumpable() -> KeepProbeDumpable {
PROBE_DUMPABLE.with(|f| f.set(true));
KeepProbeDumpable(())
}
#[must_use = "the probe's child is made non-dumpable again as soon as the guard is dropped"]
pub(crate) struct KeepProbeDumpable(());
impl Drop for KeepProbeDumpable {
fn drop(&mut self) {
PROBE_DUMPABLE.with(|f| f.set(false));
}
}
pub(crate) fn probe_kept_dumpable() -> bool {
PROBE_DUMPABLE.with(Cell::get)
}
pub(crate) fn refuse_probe_close_range() -> RefuseProbeCloseRange {
refuse_probe_close_range_after(0)
}
pub(crate) fn refuse_probe_close_range_after(allowed: u32) -> RefuseProbeCloseRange {
PROBE_CLOSE_RANGE_ALLOWED.with(|f| f.set(Some(allowed)));
RefuseProbeCloseRange(())
}
#[must_use = "close_range is allowed again as soon as the guard is dropped"]
pub(crate) struct RefuseProbeCloseRange(());
impl Drop for RefuseProbeCloseRange {
fn drop(&mut self) {
PROBE_CLOSE_RANGE_ALLOWED.with(|f| f.set(None));
}
}
pub(crate) fn probe_close_range_refused() -> bool {
PROBE_CLOSE_RANGE_ALLOWED.with(|f| match f.get() {
None => false,
Some(0) => true,
Some(allowed) => {
f.set(Some(allowed - 1));
false
}
})
}
pub(crate) fn fail_probe_fd_dir() -> FailProbeFdDir {
PROBE_FD_DIR_FAILS.with(|f| f.set(true));
FailProbeFdDir(())
}
#[must_use = "the directory opens again as soon as the guard is dropped"]
pub(crate) struct FailProbeFdDir(());
impl Drop for FailProbeFdDir {
fn drop(&mut self) {
PROBE_FD_DIR_FAILS.with(|f| f.set(false));
}
}
pub(crate) fn probe_fd_dir_fails() -> bool {
PROBE_FD_DIR_FAILS.with(Cell::get)
}
pub(crate) type ProbeHook = crate::oneshot_hook::Armed<libc::pid_t, Option<i32>>;
pub(crate) fn set_before_probe_kill(hook: impl FnOnce(libc::pid_t) -> Option<i32> + 'static) -> ProbeHook {
crate::oneshot_hook::arm_with(&BEFORE_PROBE_KILL, hook)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ProbeStep {
Kill(i32),
Reap(super::reach::ProbeEnd),
}
pub(crate) fn record_probe_step(step: ProbeStep) {
PROBE_STEPS.with(|s| s.borrow_mut().push(step));
}
pub(crate) fn take_probe_steps() -> Vec<ProbeStep> {
PROBE_STEPS.with(|s| std::mem::take(&mut *s.borrow_mut()))
}
pub(crate) fn run_before_probe_kill(pid: libc::pid_t) -> Option<i32> {
crate::oneshot_hook::fire_with(&BEFORE_PROBE_KILL, pid).flatten()
}
pub(crate) fn set_before_kill_write(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&BEFORE_KILL_WRITE, hook)
}
pub(crate) fn run_before_kill_write() {
crate::oneshot_hook::fire(&BEFORE_KILL_WRITE);
}
pub(crate) fn set_after_kill_write(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&AFTER_KILL_WRITE, hook)
}
pub(crate) fn run_after_kill_write() {
crate::oneshot_hook::fire(&AFTER_KILL_WRITE);
}
pub(crate) fn set_force_leaf_open_failure(on: bool) {
FORCE_LEAF_OPEN_FAILURE.with(|f| f.set(on));
}
pub(crate) fn take_force_leaf_open_failure() -> bool {
FORCE_LEAF_OPEN_FAILURE.with(|f| f.replace(false))
}
pub(crate) fn set_force_kill_check_errno(errno: i32) {
FORCE_KILL_CHECK_ERRNO.with(|f| f.set(Some(errno)));
}
pub(crate) fn take_force_kill_check_errno() -> Option<i32> {
FORCE_KILL_CHECK_ERRNO.with(|f| f.take())
}
pub(crate) fn set_force_inotify_failure(on: bool) {
FORCE_INOTIFY_FAILURE.with(|f| f.set(on));
}
pub(crate) fn take_force_inotify_failure() -> bool {
FORCE_INOTIFY_FAILURE.with(|f| f.replace(false))
}
pub(crate) fn set_rmdir_hook(hook: impl FnMut(&std::path::Path) -> std::io::Result<()> + 'static) {
RMDIR_HOOK.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
}
pub(crate) fn take_rmdir_hook() {
RMDIR_HOOK.with(|h| h.borrow_mut().take());
}
pub(crate) fn run_rmdir_hook(path: &std::path::Path) -> Option<std::io::Result<()>> {
let mut hook = RMDIR_HOOK.with(|h| h.borrow_mut().take())?;
let result = hook(path);
RMDIR_HOOK.with(|h| *h.borrow_mut() = Some(hook));
Some(result)
}
pub(crate) fn set_drain_blocking_notifier(notify: std::sync::mpsc::Sender<()>) {
DRAIN_BLOCKING.with(|d| *d.borrow_mut() = Some(notify));
}
pub(crate) fn take_drain_blocking_notifier() {
DRAIN_BLOCKING.with(|d| d.borrow_mut().take());
}
pub(crate) fn set_before_drain_block(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&BEFORE_DRAIN_BLOCK, hook)
}
#[cfg(feature = "tokio")]
pub(crate) fn set_after_drain_warn(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&AFTER_DRAIN_WARN, hook)
}
pub(crate) fn run_after_drain_warn() {
crate::oneshot_hook::fire(&AFTER_DRAIN_WARN);
}
pub(crate) fn notify_drain_blocking() {
crate::oneshot_hook::fire(&BEFORE_DRAIN_BLOCK);
DRAIN_BLOCKING.with(|d| {
if let Some(notify) = d.borrow().as_ref() {
let sent = notify.send(());
debug_assert!(sent.is_ok(), "drain-blocking notifier's receiver was dropped");
}
});
}
pub(crate) fn set_drain_zero_remaining_notifier(notify: std::sync::mpsc::Sender<()>) {
DRAIN_ZERO_REMAINING.with(|d| *d.borrow_mut() = Some(notify));
}
pub(crate) fn take_drain_zero_remaining_notifier() {
DRAIN_ZERO_REMAINING.with(|d| d.borrow_mut().take());
}
pub(crate) fn notify_drain_zero_remaining() {
DRAIN_ZERO_REMAINING.with(|d| {
if let Some(notify) = d.borrow().as_ref() {
let sent = notify.send(());
debug_assert!(sent.is_ok(), "zero-remaining notifier's receiver was dropped");
}
});
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct WaitSitePark {
pub(crate) deadline: Option<std::time::Instant>,
pub(crate) woken: bool,
}
pub(crate) fn set_wait_site_park_notifier(notify: std::sync::mpsc::Sender<WaitSitePark>) {
WAIT_SITE_PARK.with(|p| *p.borrow_mut() = Some(notify));
}
pub(crate) fn take_wait_site_park_notifier() {
WAIT_SITE_PARK.with(|p| p.borrow_mut().take());
}
pub(crate) fn notify_wait_site_park(park: WaitSitePark) {
WAIT_SITE_PARK.with(|p| {
if let Some(notify) = p.borrow().as_ref() {
let sent = notify.send(park);
debug_assert!(sent.is_ok(), "wait-site-park notifier's receiver was dropped");
}
});
}
pub(crate) fn set_wait_deadline_arg_notifier(notify: std::sync::mpsc::Sender<std::time::Instant>) {
WAIT_DEADLINE_ARG.with(|p| *p.borrow_mut() = Some(notify));
}
pub(crate) fn take_wait_deadline_arg_notifier() {
WAIT_DEADLINE_ARG.with(|p| p.borrow_mut().take());
}
pub(crate) fn notify_wait_deadline_arg(at: std::time::Instant) {
WAIT_DEADLINE_ARG.with(|p| {
if let Some(notify) = p.borrow().as_ref() {
let sent = notify.send(at);
debug_assert!(sent.is_ok(), "wait-deadline-arg notifier's receiver was dropped");
}
});
}
pub(crate) fn record_leaf_steps() {
LEAF_STEPS.with(|s| *s.borrow_mut() = Some(Vec::new()));
}
pub(crate) fn take_leaf_steps() -> Vec<String> {
LEAF_STEPS.with(|s| s.borrow_mut().take()).unwrap_or_default()
}
pub(crate) fn peek_leaf_steps() -> Vec<String> {
LEAF_STEPS.with(|s| s.borrow().clone()).unwrap_or_default()
}
pub(crate) fn record_leaf_step(step: impl FnOnce() -> String) {
LEAF_STEPS.with(|s| {
if let Some(steps) = s.borrow_mut().as_mut() {
steps.push(step());
}
});
}
pub(crate) fn set_force_kill_supported(on: bool) {
FORCE_KILL_SUPPORTED.with(|f| f.set(on));
}
pub(crate) fn take_force_kill_supported() -> bool {
FORCE_KILL_SUPPORTED.with(|f| f.replace(false))
}
pub(crate) fn kill_supported_armed() -> bool {
FORCE_KILL_SUPPORTED.with(|f| f.get())
}
pub(crate) fn set_force_report_channel_failure(on: bool) {
FORCE_REPORT_CHANNEL_FAILURE.with(|f| f.set(on));
}
pub(crate) fn take_force_report_channel_failure() -> bool {
FORCE_REPORT_CHANNEL_FAILURE.with(|f| f.replace(false))
}
pub(crate) fn report_channel_failure_armed() -> bool {
FORCE_REPORT_CHANNEL_FAILURE.with(|f| f.get())
}
pub(crate) fn set_force_placement_write_result(ret: isize) {
FORCE_PLACEMENT_WRITE_RESULT.with(|f| f.set(Some(ret)));
}
pub(crate) fn take_force_placement_write_result() -> Option<isize> {
FORCE_PLACEMENT_WRITE_RESULT.with(|f| f.take())
}
pub(crate) fn set_force_occupy_before_unwind(on: bool) {
FORCE_OCCUPY_BEFORE_UNWIND.with(|f| f.set(on));
}
pub(crate) fn take_force_occupy_before_unwind() -> bool {
FORCE_OCCUPY_BEFORE_UNWIND.with(|f| f.replace(false))
}
pub(crate) fn occupy_before_unwind_armed() -> bool {
FORCE_OCCUPY_BEFORE_UNWIND.with(|f| f.get())
}
pub(crate) fn set_wait_polling_notifier(notify: std::sync::mpsc::Sender<()>) {
WAIT_POLLING.with(|w| *w.borrow_mut() = Some(notify));
}
pub(crate) fn notify_wait_polling() {
if let Some(notify) = WAIT_POLLING.with(|w| w.borrow_mut().take()) {
_ = notify.send(());
}
}
pub(crate) fn set_on_wait(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&ON_WAIT, hook)
}
pub(crate) fn notify_wait_entry(pidfd: std::os::fd::RawFd) {
WAITED_PIDFD.with(|p| p.set(Some(pidfd)));
crate::oneshot_hook::fire(&ON_WAIT);
}
pub(crate) fn waited_pidfd() -> Option<std::os::fd::RawFd> {
WAITED_PIDFD.with(|p| p.get())
}
pub(crate) fn set_after_shut_read(hook: impl FnOnce() + 'static) {
AFTER_SHUT_READ.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
}
pub(crate) fn run_after_shut_read() {
if let Some(hook) = AFTER_SHUT_READ.with(|h| h.borrow_mut().take()) {
hook();
}
}
#[must_use = "dropping this immediately clears the armed hook; bind it for the scope that needs it"]
pub(crate) struct AfterForkStillLockedGuard(());
impl Drop for AfterForkStillLockedGuard {
fn drop(&mut self) {
AFTER_FORK_STILL_LOCKED.with(|h| *h.borrow_mut() = None);
}
}
pub(crate) fn set_after_fork_still_locked(hook: impl FnOnce() + 'static) -> AfterForkStillLockedGuard {
AFTER_FORK_STILL_LOCKED.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
AfterForkStillLockedGuard(())
}
pub(crate) fn run_after_fork_still_locked() {
if let Some(hook) = AFTER_FORK_STILL_LOCKED.with(|h| h.borrow_mut().take()) {
hook();
}
}
#[must_use = "dropping this immediately clears the armed hook; bind it for the scope that needs it"]
pub(crate) struct ForkRunningLockContendedGuard(());
impl Drop for ForkRunningLockContendedGuard {
fn drop(&mut self) {
ON_FORK_RUNNING_LOCK_CONTENDED.with(|h| *h.borrow_mut() = None);
}
}
pub(crate) fn set_fork_running_lock_contended(hook: impl FnOnce() + 'static) -> ForkRunningLockContendedGuard {
ON_FORK_RUNNING_LOCK_CONTENDED.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
ForkRunningLockContendedGuard(())
}
pub(crate) fn run_fork_running_lock_contended() {
if let Some(hook) = ON_FORK_RUNNING_LOCK_CONTENDED.with(|h| h.borrow_mut().take()) {
hook();
}
}
#[must_use = "dropping this immediately clears the registered fd; bind it for the scope that needs it"]
pub(crate) struct ForkRunningLockHeldReportFdGuard(());
impl Drop for ForkRunningLockHeldReportFdGuard {
fn drop(&mut self) {
FORK_RUNNING_LOCK_HELD_REPORT_FD.with(|f| f.set(None));
}
}
pub(crate) fn set_fork_running_lock_held_report_fd(fd: std::os::fd::RawFd) -> ForkRunningLockHeldReportFdGuard {
FORK_RUNNING_LOCK_HELD_REPORT_FD.with(|f| f.set(Some(fd)));
ForkRunningLockHeldReportFdGuard(())
}
pub(crate) fn take_fork_running_lock_held_report_fd() -> Option<std::os::fd::RawFd> {
FORK_RUNNING_LOCK_HELD_REPORT_FD.with(|f| f.take())
}
pub(crate) fn set_after_procs_read(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&AFTER_PROCS_READ, hook)
}
pub(crate) fn run_after_procs_read() {
crate::oneshot_hook::fire(&AFTER_PROCS_READ);
}
pub(crate) fn set_after_terminate_pin(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&AFTER_TERMINATE_PIN, hook)
}
pub(crate) fn run_after_terminate_pin() {
crate::oneshot_hook::fire(&AFTER_TERMINATE_PIN);
}
pub(crate) type MemberTerm = (Option<u32>, crate::send_log::Via, i32);
pub(crate) fn record_member_term(sys: crate::containment::unix::Sys<'_>, pid: u32, signo: i32) {
use crate::containment::unix::Sys;
use crate::identity::{pidfd_pid_in, HostKernel, PidfdTarget, ProcDir};
use crate::send_log::Via;
let entry = match sys {
Sys::Pidfd(pidfd, _) => {
let pid = ProcDir::open()
.and_then(|dir| pidfd_pid_in(&HostKernel, &dir, pidfd))
.map_err(|why| {
log::debug!(
"record_member_term: the pidfd's pid was not read: {report}",
report = crate::error::Report(&why)
);
})
.ok()
.and_then(|target| match target {
PidfdTarget::Pid(pid) if pid > 0 => Some(pid),
PidfdTarget::Pid(_) | PidfdTarget::Reaped => None,
});
(pid, Via::Pidfd, signo)
}
Sys::Group(_) | Sys::Process(_) => (Some(pid), Via::Pid, signo),
};
MEMBER_TERMS.with(|t| t.borrow_mut().push(entry));
}
pub(crate) fn take_member_terms() -> Vec<MemberTerm> {
MEMBER_TERMS.with(|t| std::mem::take(&mut *t.borrow_mut()))
}
static PUMPS: std::sync::Mutex<Vec<(std::ffi::OsString, bool)>> = std::sync::Mutex::new(Vec::new());
pub(crate) fn record_pump(name: &std::ffi::OsStr, ended: bool) {
PUMPS
.lock()
.unwrap_or_else(|e| e.into_inner())
.push((name.to_os_string(), ended));
}
pub(crate) fn pumps_of(name: &str) -> (usize, usize) {
let pumps = PUMPS.lock().unwrap_or_else(|e| e.into_inner());
let of = |ended| {
pumps
.iter()
.filter(|(n, e)| n.as_os_str() == name && *e == ended)
.count()
};
(of(false), of(true))
}
static ARMS: std::sync::Mutex<Vec<std::ffi::OsString>> = std::sync::Mutex::new(Vec::new());
pub(crate) fn record_arm(name: &std::ffi::OsStr) {
ARMS.lock().unwrap_or_else(|e| e.into_inner()).push(name.to_os_string());
}
#[cfg(feature = "tokio")]
pub(crate) fn arms_of(name: &str) -> usize {
ARMS.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.filter(|n| n.as_os_str() == name)
.count()
}
static PUMP_SEAMS: std::sync::Mutex<Vec<(std::ffi::OsString, PumpSeam)>> = std::sync::Mutex::new(Vec::new());
enum PumpSeam {
Fail,
Batches(std::sync::mpsc::Sender<bool>),
}
pub(crate) fn set_force_pump_failure(name: &str) {
PUMP_SEAMS
.lock()
.unwrap_or_else(|e| e.into_inner())
.push((name.into(), PumpSeam::Fail));
}
pub(crate) fn take_force_pump_failure(name: &std::ffi::OsStr) -> bool {
let mut seams = PUMP_SEAMS.lock().unwrap_or_else(|e| e.into_inner());
let at = seams
.iter()
.position(|(n, s)| n.as_os_str() == name && matches!(s, PumpSeam::Fail));
at.map(|at| seams.remove(at)).is_some()
}
pub(crate) fn set_pump_batch_notifier(name: &str, notify: std::sync::mpsc::Sender<bool>) {
PUMP_SEAMS
.lock()
.unwrap_or_else(|e| e.into_inner())
.push((name.into(), PumpSeam::Batches(notify)));
}
pub(crate) fn notify_pump_batch(name: &std::ffi::OsStr, notified: bool) {
for (n, seam) in PUMP_SEAMS.lock().unwrap_or_else(|e| e.into_inner()).iter() {
if let (true, PumpSeam::Batches(notify)) = (n.as_os_str() == name, seam) {
_ = notify.send(notified);
}
}
}
pub(crate) fn set_force_kill_on_drop_waitid_eintr(on: bool) {
FORCE_KILL_ON_DROP_WAITID_EINTR.with(|f| f.set(on));
}
pub(crate) fn take_force_kill_on_drop_waitid_eintr() -> bool {
FORCE_KILL_ON_DROP_WAITID_EINTR.with(|f| f.replace(false))
}
pub(crate) fn set_force_kill_on_drop_kill_failure(on: bool) {
FORCE_KILL_ON_DROP_KILL_FAILURE.with(|f| f.set(on));
}
pub(crate) fn take_force_kill_on_drop_kill_failure() -> bool {
FORCE_KILL_ON_DROP_KILL_FAILURE.with(|f| f.replace(false))
}
pub(crate) fn set_on_take_placement(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&ON_TAKE_PLACEMENT, hook)
}
pub(crate) fn run_on_take_placement() {
crate::oneshot_hook::fire(&ON_TAKE_PLACEMENT);
}
pub(crate) fn set_before_state_read(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&BEFORE_STATE_READ, hook)
}
pub(crate) fn run_before_state_read() {
crate::oneshot_hook::fire(&BEFORE_STATE_READ);
}
pub(crate) fn force_pidfd_cgroup_id(id: u64) -> ForcedPidfdCgroupId {
FORCED_PIDFD_CGROUP_ID.with(|f| f.set(Some(id)));
ForcedPidfdCgroupId(())
}
#[must_use = "the id is read again as soon as the guard is dropped"]
pub(crate) struct ForcedPidfdCgroupId(());
impl Drop for ForcedPidfdCgroupId {
fn drop(&mut self) {
FORCED_PIDFD_CGROUP_ID.with(|f| f.set(None));
}
}
pub(crate) fn forced_pidfd_cgroup_id() -> Option<u64> {
FORCED_PIDFD_CGROUP_ID.with(Cell::get)
}
pub(crate) fn fail_subtree(errno: i32) -> FailSubtree {
SUBTREE_FAILS.with(|f| f.set(Some(errno)));
FailSubtree(())
}
#[must_use = "the subtree is captured again as soon as the guard is dropped"]
pub(crate) struct FailSubtree(());
impl Drop for FailSubtree {
fn drop(&mut self) {
SUBTREE_FAILS.with(|f| f.set(None));
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TerminateStep {
Pin,
Exited,
Send,
}
pub(crate) fn fail_terminate(step: TerminateStep, errno: i32) -> FailTerminate {
TERMINATE_FAILS.with(|f| f.set(Some((step, errno, false))));
FailTerminate(())
}
pub(crate) fn fail_terminate_once(step: TerminateStep, errno: i32) -> FailTerminate {
TERMINATE_FAILS.with(|f| f.set(Some((step, errno, true))));
FailTerminate(())
}
#[must_use = "terminate's steps run again as soon as the guard is dropped"]
pub(crate) struct FailTerminate(());
impl Drop for FailTerminate {
fn drop(&mut self) {
TERMINATE_FAILS.with(|f| f.set(None));
}
}
pub(crate) fn terminate_fails(step: TerminateStep) -> Option<i32> {
let (failing, errno, once) = TERMINATE_FAILS.with(Cell::get)?;
if failing != step {
return None;
}
if once {
TERMINATE_FAILS.with(|f| f.set(None));
}
Some(errno)
}
pub(crate) fn subtree_fails() -> Option<i32> {
SUBTREE_FAILS.with(Cell::get)
}
type WalkHook = Box<dyn FnMut(&std::path::Path)>;
pub(crate) fn set_before_walk_open(hook: impl FnMut(&std::path::Path) + 'static) -> BeforeWalkOpen {
BEFORE_WALK_OPEN.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
BeforeWalkOpen(())
}
#[must_use = "the hook is cleared as soon as the guard is dropped"]
pub(crate) struct BeforeWalkOpen(());
impl Drop for BeforeWalkOpen {
fn drop(&mut self) {
BEFORE_WALK_OPEN.with(|h| h.borrow_mut().take());
}
}
pub(crate) fn run_before_walk_open(path: &std::path::Path) {
let hook = BEFORE_WALK_OPEN.with(|h| h.borrow_mut().take());
if let Some(mut hook) = hook {
hook(path);
BEFORE_WALK_OPEN.with(|h| {
h.borrow_mut().get_or_insert(hook);
});
}
}
type WalkFailure = (std::path::PathBuf, WalkStep, i32, usize);
pub(crate) fn fail_walk_step(path: &str, step: WalkStep, errno: i32) -> FailWalkStep {
fail_walk_step_after(path, step, errno, 0)
}
pub(crate) fn fail_walk_step_after(path: &str, step: WalkStep, errno: i32, passes: usize) -> FailWalkStep {
WALK_FAILURE.with(|f| *f.borrow_mut() = Some((path.into(), step, errno, passes)));
FailWalkStep(())
}
#[must_use = "the step succeeds again as soon as the guard is dropped"]
pub(crate) struct FailWalkStep(());
impl Drop for FailWalkStep {
fn drop(&mut self) {
WALK_FAILURE.with(|f| f.borrow_mut().take());
}
}
pub(crate) fn walk_step_failure(path: &std::path::Path, step: WalkStep) -> Option<i32> {
WALK_FAILURE.with(|f| match &mut *f.borrow_mut() {
Some((at, failing, errno, passes)) if at == path && *failing == step => {
if *passes == 0 {
Some(*errno)
} else {
*passes -= 1;
None
}
}
_ => None,
})
}
pub(crate) fn set_before_sweep_remove(hook: impl FnMut(&std::path::Path) + 'static) -> BeforeSweepRemove {
BEFORE_SWEEP_REMOVE.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
BeforeSweepRemove(())
}
#[must_use = "the hook is cleared as soon as the guard is dropped"]
pub(crate) struct BeforeSweepRemove(());
impl Drop for BeforeSweepRemove {
fn drop(&mut self) {
BEFORE_SWEEP_REMOVE.with(|h| h.borrow_mut().take());
}
}
pub(crate) fn run_before_sweep_remove(path: &std::path::Path) {
let hook = BEFORE_SWEEP_REMOVE.with(|h| h.borrow_mut().take());
if let Some(mut hook) = hook {
hook(path);
BEFORE_SWEEP_REMOVE.with(|h| {
h.borrow_mut().get_or_insert(hook);
});
}
}
pub(crate) fn fail_cgroup_id(errno: i32) -> FailCgroupId {
CGROUP_ID_FAILS.with(|f| f.set(Some(errno)));
FailCgroupId(())
}
#[must_use = "the id reads again as soon as the guard is dropped"]
pub(crate) struct FailCgroupId(());
impl Drop for FailCgroupId {
fn drop(&mut self) {
CGROUP_ID_FAILS.with(|f| f.set(None));
}
}
pub(crate) fn cgroup_id_fails() -> Option<i32> {
CGROUP_ID_FAILS.with(Cell::get)
}
pub(crate) fn fail_liveness_read(errno: i32) -> FailLivenessRead {
LIVENESS_READ_FAILS.with(|f| f.set(Some(errno)));
FailLivenessRead(())
}
#[must_use = "the liveness reads again as soon as the guard is dropped"]
pub(crate) struct FailLivenessRead(());
impl Drop for FailLivenessRead {
fn drop(&mut self) {
LIVENESS_READ_FAILS.with(|f| f.set(None));
}
}
pub(crate) fn liveness_read_fails() -> Option<i32> {
LIVENESS_READ_FAILS.with(Cell::get)
}