use super::*;
use crate::live_children::{ContainerEnd, ContainerEndReason};
#[cfg(target_os = "linux")]
use std::path::Path;
use std::sync::Weak;
pub(crate) type Slot = Arc<Mutex<Option<Arc<CarriedContainment>>>>;
#[derive(Debug)]
pub(crate) struct CarriedContainment {
#[cfg(unix)]
binding_retirement: Mutex<Option<super::program_binding::ProgramBindingRetirement>>,
module_id: String,
end_log: Mutex<Option<ContainerEnd>>,
#[cfg(unix)]
counters: crate::observability::DaemonCounters,
#[cfg(unix)]
cleanup_block: Mutex<Option<crate::live_children::RetainedReason>>,
#[cfg(all(test, unix))]
group_signals: Mutex<Option<Arc<Mutex<Vec<rustix::process::Signal>>>>>,
resource: Resource,
roster: Mutex<Option<crate::child_roster::RosterGuard>>,
terminated: std::sync::atomic::AtomicBool,
ending: std::sync::atomic::AtomicBool,
admitting: std::sync::atomic::AtomicBool,
admission_changed: tokio::sync::Notify,
cleanup_finished: tokio::sync::Notify,
hard_killed: std::sync::atomic::AtomicBool,
kill_notify: tokio::sync::Notify,
}
#[derive(Debug)]
enum Resource {
#[cfg(unix)]
Group {
pgid: u32,
created_start_time: Option<u64>,
identity: LaunchIdentity,
anchor_lost: std::sync::atomic::AtomicBool,
pin: ReapLock,
pending_pin: std::sync::atomic::AtomicBool,
},
#[cfg(target_os = "linux")]
Cgroup {
placement: subc_cgroup::Placement,
name: String,
path: PathBuf,
identity: LaunchIdentity,
},
#[cfg(windows)]
Job(Arc<Mutex<subc_jobobject::JobObject>>),
}
#[cfg(unix)]
type ReapLock = Arc<Mutex<Option<Pin>>>;
#[cfg(unix)]
#[derive(Debug, Clone)]
pub(super) struct LaunchIdentity {
pub(super) boot_id: String,
pub(super) session_id: u32,
}
#[cfg(unix)]
#[derive(Debug)]
pub(super) enum Pin {
Spawned(Child),
#[cfg(any(target_os = "linux", target_os = "macos"))]
Inherited { pid: u32, owner: PinOwner },
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) type PinOwner = Option<Arc<super::live_upgrade::VerifiedChild>>;
#[cfg(unix)]
impl Pin {
fn id(&self) -> Option<u32> {
match self {
Self::Spawned(child) => child.id(),
#[cfg(any(target_os = "linux", target_os = "macos"))]
Self::Inherited { pid, .. } => Some(*pid),
}
}
fn try_wait(&mut self) -> io::Result<Option<()>> {
match self {
Self::Spawned(child) => child.try_wait().map(|status| status.map(|_| ())),
#[cfg(any(target_os = "linux", target_os = "macos"))]
Self::Inherited { .. } => Err(io::Error::other(
"an inherited process-group pin is reaped only after its container settles",
)),
}
}
fn start_kill(&mut self) -> io::Result<()> {
match self {
Self::Spawned(child) => child.start_kill(),
#[cfg(any(target_os = "linux", target_os = "macos"))]
Self::Inherited { .. } => Err(io::Error::other(
"an inherited process-group pin is signalled through its adopted child",
)),
}
}
}
#[cfg(unix)]
pub(super) fn group_pin_birth(pgid: u32) -> io::Result<u64> {
#[cfg(target_os = "macos")]
{
subc_os::owned_child_start_time(pgid)
}
#[cfg(not(target_os = "macos"))]
{
subc_os::process_group::inspect(pgid).and_then(|identity| {
identity.map(|identity| identity.start_time).ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"process-group pin identity is missing",
)
})
})
}
}
#[cfg(unix)]
impl LaunchIdentity {
pub(super) fn capture() -> io::Result<Self> {
Ok(Self {
boot_id: subc_os::boot_id::current()?,
session_id: subc_os::process_group::session_id(std::process::id())?
.ok_or_else(|| io::Error::other("daemon session identity is unavailable"))?,
})
}
}
impl CarriedContainment {
pub(crate) fn note_end_reason(&self, reason: ContainerEndReason) {
self.update_end_log(|end| {
if matches!(end.reason, ContainerEndReason::SupervisorFailure) {
end.reason = reason;
}
});
}
fn update_end_log(&self, update: impl FnOnce(&mut ContainerEnd)) {
if let Some(end) = self
.end_log
.lock()
.unwrap_or_else(|p| p.into_inner())
.as_mut()
{
update(end);
}
}
fn log_end(&self) {
let end = self
.end_log
.lock()
.unwrap_or_else(|p| p.into_inner())
.take();
if let Some(end) = end {
end.log(&self.module_id);
}
}
#[cfg(unix)]
fn launch_identity(&self) -> &LaunchIdentity {
match &self.resource {
Resource::Group { identity, .. } => identity,
#[cfg(target_os = "linux")]
Resource::Cgroup { identity, .. } => identity,
}
}
fn claim_failed_admission(&self, failure: crate::child_roster::AdmissionError) -> io::Error {
let (source, guard) = failure.into_parts();
*self.roster.lock().unwrap_or_else(|p| p.into_inner()) = Some(guard);
source
}
#[cfg(unix)]
fn note_observation_error(&self, pid: u32, error: &io::Error) {
#[allow(irrefutable_let_patterns)]
let Resource::Group {
pgid,
created_start_time,
anchor_lost,
..
} = &self.resource
else {
return;
};
if *pgid == pid
&& error.raw_os_error() == Some(rustix::io::Errno::CHILD.raw_os_error())
&& !anchor_lost.swap(true, std::sync::atomic::Ordering::AcqRel)
{
self.counters.increment_carried_containment_anchor_lost();
error!(module_id = %self.module_id, pgid, ?created_start_time, %error,
"carried process-group anchor was unexpectedly reaped; group-wide signals refused");
}
}
#[cfg(unix)]
fn recorded_group(&self) -> Option<crate::group_recovery::RecordedGroup<'_>> {
match &self.resource {
Resource::Group {
pgid,
created_start_time: Some(created_start_time),
identity,
..
} => Some(crate::group_recovery::RecordedGroup {
pgid: *pgid,
created_start_time: *created_start_time,
boot_id: &identity.boot_id,
session_id: identity.session_id,
}),
#[allow(unreachable_patterns)]
_ => None,
}
}
#[cfg(unix)]
fn signal_pinned_group(&self, signal: rustix::process::Signal) -> bool {
#[allow(irrefutable_let_patterns)]
let Resource::Group {
pgid,
pin,
anchor_lost,
..
} = &self.resource
else {
return false;
};
let pin = pin.lock().unwrap_or_else(|p| p.into_inner());
if !self.owns_pin(*pgid, &pin, anchor_lost) {
return false;
}
#[cfg(test)]
if let Some(signals) = self
.group_signals
.lock()
.unwrap_or_else(|p| p.into_inner())
.as_ref()
{
signals
.lock()
.unwrap_or_else(|p| p.into_inner())
.push(signal);
self.update_end_log(|end| {
end.signal(if signal == rustix::process::Signal::TERM {
"TERM"
} else {
"KILL"
})
});
return true;
}
let delivered = signal_group(*pgid, signal);
self.update_end_log(|end| match delivered {
Ok(true) => end.signal(if signal == rustix::process::Signal::TERM {
"TERM"
} else {
"KILL"
}),
Ok(false) | Err(rustix::io::Errno::SRCH) => {}
Err(_) => end.failed = true,
});
true
}
#[cfg(unix)]
fn owns_pin(
&self,
pgid: u32,
pin: &Option<Pin>,
anchor_lost: &std::sync::atomic::AtomicBool,
) -> bool {
let pending = matches!(&self.resource, Resource::Group { pending_pin, .. }
if pending_pin.load(std::sync::atomic::Ordering::Acquire));
if anchor_lost.load(std::sync::atomic::Ordering::Acquire)
|| (pin.as_ref().and_then(Pin::id) != Some(pgid) && !pending)
{
return false;
}
if let Err(error) = subc_os::child_exit::observe(pgid) {
self.note_observation_error(pgid, &error);
warn!(module_id = %self.module_id, pgid, %error, "cannot verify the process-group pin; refusing a group-wide signal");
return false;
}
let Some(record) = self.recorded_group() else {
return false;
};
match group_pin_birth(pgid) {
Ok(actual) if actual == record.created_start_time => {}
actual => {
error!(module_id = %self.module_id, pgid, expected = record.created_start_time,
?actual, "cannot verify the exact process-group pin birth; refusing signal or join");
return false;
}
}
true
}
#[cfg(unix)]
pub(super) fn verified_join_group(&self) -> io::Result<Option<u32>> {
#[allow(irrefutable_let_patterns)]
if let Resource::Group {
pgid,
pin,
anchor_lost,
..
} = &self.resource
{
let pin = pin.lock().unwrap_or_else(|p| p.into_inner());
if !self.owns_pin(*pgid, &pin, anchor_lost) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"cannot join a carried process group without its exact owned pin identity",
));
}
return Ok(Some(*pgid));
}
Ok(None)
}
#[cfg(unix)]
async fn recover_group(&self) {
let Some(record) = self.recorded_group() else {
*self.cleanup_block.lock().unwrap_or_else(|p| p.into_inner()) =
Some(crate::live_children::RetainedReason::ContainerUnverifiable(
"unpinned group has no recorded creation identity".into(),
));
return;
};
let mut end = ContainerEnd::default();
let decision = crate::group_recovery::sweep(
record,
crate::live_children::SweepBounds::default(),
&mut end,
)
.await;
self.update_end_log(|log| log.merge(end));
*self.cleanup_block.lock().unwrap_or_else(|p| p.into_inner()) = match decision {
crate::live_children::SweepDecision::Unverifiable(error) => Some(
crate::live_children::RetainedReason::ContainerUnverifiable(error),
),
crate::live_children::SweepDecision::ContainerSurvivors(pids) => Some(
crate::live_children::RetainedReason::ContainerSurvivors(pids),
),
_ => None,
};
}
fn release_roster(&self) {
let guard = self.roster.lock().unwrap_or_else(|p| p.into_inner()).take();
#[cfg(unix)]
let reason = self
.cleanup_block
.lock()
.unwrap_or_else(|p| p.into_inner())
.take();
#[cfg(unix)]
if let Some(reason) = reason {
if let Some(guard) = guard {
guard.retain(reason);
}
return;
}
drop(guard);
}
pub(crate) fn group(&self) -> Option<u32> {
match &self.resource {
#[cfg(unix)]
Resource::Group { pgid, .. } => Some(*pgid),
#[allow(unreachable_patterns)]
_ => None,
}
}
#[cfg(target_os = "linux")]
pub(super) fn cgroup(&self) -> Option<(&subc_cgroup::Placement, &str)> {
match &self.resource {
Resource::Cgroup {
placement, name, ..
} => Some((placement, name)),
_ => None,
}
}
#[cfg(target_os = "linux")]
pub(super) fn cgroup_path(&self) -> Option<&Path> {
match &self.resource {
Resource::Cgroup { path, .. } => Some(path),
_ => None,
}
}
#[cfg(target_os = "linux")]
async fn end_cgroup(&self, placement: &subc_cgroup::Placement, path: &Path) {
let mut end = ContainerEnd::default();
let decision = crate::cgroup_recovery::sweep(
Some(placement),
path,
crate::live_children::SweepBounds::default(),
&mut end,
)
.await;
self.update_end_log(|log| log.merge(end));
let reason = match decision {
crate::live_children::SweepDecision::Unverifiable(error) => Some(
crate::live_children::RetainedReason::ContainerUnverifiable(error),
),
other => other.retained_reason(),
};
*self.cleanup_block.lock().unwrap_or_else(|p| p.into_inner()) = reason;
}
#[cfg(windows)]
pub(super) fn job(&self) -> Arc<Mutex<subc_jobobject::JobObject>> {
match &self.resource {
Resource::Job(job) => Arc::clone(job),
}
}
pub(crate) fn hard_kill(&self) {
if self.terminated.load(std::sync::atomic::Ordering::Acquire) {
return;
}
self.hard_killed
.store(true, std::sync::atomic::Ordering::Release);
self.kill_notify.notify_waiters();
match &self.resource {
#[cfg(unix)]
Resource::Group { .. } => {
self.signal_pinned_group(rustix::process::Signal::KILL);
*self.cleanup_block.lock().unwrap_or_else(|p| p.into_inner()) =
self.recheck_group(crate::group_recovery::signal_recorded_anchor);
}
#[cfg(target_os = "linux")]
Resource::Cgroup {
placement, path, ..
} => {
let mut end = ContainerEnd::default();
*self.cleanup_block.lock().unwrap_or_else(|p| p.into_inner()) =
crate::cgroup_recovery::recheck_reported(Some(placement), path, &mut end);
self.update_end_log(|log| log.merge(end));
}
#[cfg(windows)]
Resource::Job(job) => {
let result = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
self.update_end_log(|end| match result {
Ok(()) => end.signal("TerminateJobObject"),
Err(_) => end.failed = true,
});
}
}
}
#[cfg(unix)]
fn recheck_group(
&self,
signal_anchor: impl FnOnce(
crate::group_recovery::RecordedGroup<'_>,
subc_os::Signal,
) -> io::Result<bool>,
) -> Option<crate::live_children::RetainedReason> {
#[allow(irrefutable_let_patterns)]
let Resource::Group { pin, .. } = &self.resource
else {
unreachable!("only Unix process groups have a recorded anchor");
};
self.recorded_group().map_or_else(
|| {
Some(crate::live_children::RetainedReason::ContainerUnverifiable(
"unpinned group has no recorded creation identity".into(),
))
},
|record| {
let mut end = ContainerEnd::default();
let retained = crate::group_recovery::recheck_with(
record,
|record, signal| {
let _reap = pin.lock().unwrap_or_else(|p| p.into_inner());
signal_anchor(record, signal)
},
&mut end,
);
self.update_end_log(|log| log.merge(end));
retained
},
)
}
pub(super) async fn stop_members(&self) {
if self.terminated.load(std::sync::atomic::Ordering::Acquire) {
return;
}
match &self.resource {
#[cfg(unix)]
Resource::Group { .. } => {
if self.signal_pinned_group(rustix::process::Signal::TERM) {
self.grace(crate::child_roster::TERM_TO_KILL).await;
} else {
self.recover_group().await;
}
}
#[cfg(target_os = "linux")]
Resource::Cgroup {
placement, path, ..
} => {
self.end_cgroup(placement, path).await;
}
#[cfg(windows)]
Resource::Job(_) => {}
}
self.hard_kill();
}
pub(super) async fn terminate(&self) {
if self.ending.swap(true, std::sync::atomic::Ordering::AcqRel) {
while !self.terminated.load(std::sync::atomic::Ordering::Acquire) {
let changed = self.cleanup_finished.notified();
tokio::pin!(changed);
changed.as_mut().enable();
if !self.terminated.load(std::sync::atomic::Ordering::Acquire) {
changed.await;
}
}
return;
}
while self.admitting.load(std::sync::atomic::Ordering::Acquire) {
self.hard_kill();
let changed = self.admission_changed.notified();
tokio::pin!(changed);
changed.as_mut().enable();
if self.admitting.load(std::sync::atomic::Ordering::Acquire) {
changed.await;
}
}
if self.terminated.load(std::sync::atomic::Ordering::Acquire) {
return;
}
match &self.resource {
#[cfg(unix)]
Resource::Group { pin, .. } => {
if self.signal_pinned_group(rustix::process::Signal::TERM) {
self.grace(crate::child_roster::TERM_TO_KILL).await;
} else {
self.recover_group().await;
}
self.hard_kill();
let owned_pin = pin.lock().unwrap_or_else(|p| p.into_inner()).take();
#[cfg(any(target_os = "linux", target_os = "macos"))]
let (owned_pin, inherited_pin) = match owned_pin {
Some(Pin::Inherited { pid, owner }) => {
self.await_inherited_pin_exit(pid).await;
(None, Some((pid, owner)))
}
other => (other, None),
};
if let Some(mut child) = owned_pin {
loop {
let reaped = {
let _reap = pin.lock().unwrap_or_else(|p| p.into_inner());
child.try_wait()
};
match reaped {
Ok(Some(_)) => {
let binding = self
.binding_retirement
.lock()
.unwrap_or_else(|p| p.into_inner())
.as_ref()
.and_then(|hook| hook.upgrade());
if let Some(binding) = &binding {
binding.retire();
}
#[cfg(all(test, target_os = "linux"))]
if let Some(binding) = &binding {
binding.pause_after_wait_for_test().await;
}
break;
}
Ok(None) => sleep(Duration::from_millis(1)).await,
Err(error) => {
warn!(module_id = %self.module_id, %error, "carried process-group pin reap failed");
let binding = self
.binding_retirement
.lock()
.unwrap_or_else(|p| p.into_inner())
.as_ref()
.and_then(|hook| hook.upgrade());
if let Some(binding) = &binding {
binding.retire();
}
#[cfg(all(test, target_os = "linux"))]
if let Some(binding) = &binding {
binding.pause_after_wait_for_test().await;
}
break;
}
}
}
}
self.recover_group().await;
#[cfg(any(target_os = "linux", target_os = "macos"))]
if let Some((pid, owner)) = inherited_pin {
self.settle_inherited_pin(pid, owner, Arc::clone(pin));
}
}
#[cfg(target_os = "linux")]
Resource::Cgroup {
placement, path, ..
} => {
self.end_cgroup(placement, path).await;
}
#[cfg(windows)]
Resource::Job(_) => self.hard_kill(),
}
self.finish_end_log();
self.release_roster();
self.terminated
.store(true, std::sync::atomic::Ordering::Release);
self.cleanup_finished.notify_waiters();
}
pub(crate) fn finish_end_log(&self) {
#[cfg(unix)]
{
let retained = self.cleanup_block.lock().unwrap_or_else(|p| p.into_inner());
if retained
.as_ref()
.is_some_and(crate::live_children::RetainedReason::blocks_fresh_copy)
{
self.update_end_log(|end| end.failed = true);
}
}
self.log_end();
}
#[cfg(unix)]
async fn grace(&self, duration: Duration) {
let killed = self.kill_notify.notified();
tokio::pin!(killed);
killed.as_mut().enable();
if self.hard_killed.load(std::sync::atomic::Ordering::Acquire) {
return;
}
tokio::select! { _ = sleep(duration) => {}, _ = killed => {} }
}
}
impl Drop for CarriedContainment {
fn drop(&mut self) {
self.hard_kill();
self.finish_end_log();
self.release_roster();
}
}
#[cfg(unix)]
fn signal_group(pgid: u32, signal: rustix::process::Signal) -> rustix::io::Result<bool> {
let Some(group) = i32::try_from(pgid)
.ok()
.filter(|pid| *pid > 1)
.and_then(rustix::process::Pid::from_raw)
else {
return Ok(false);
};
let result = rustix::process::kill_process_group(group, signal);
if let Err(error) = result {
if !matches!(error, rustix::io::Errno::SRCH | rustix::io::Errno::PERM) {
warn!(pgid, errno = error.raw_os_error(), %error, "carried process-group signal failed");
}
}
result.map(|()| true)
}
pub(super) fn current(slot: &Slot) -> Option<Arc<CarriedContainment>> {
slot.lock().unwrap_or_else(|p| p.into_inner()).clone()
}
pub(super) fn note_end_reason(slot: &Slot, reason: ContainerEndReason) {
if let Some(container) = current(slot) {
container.note_end_reason(reason);
}
}
pub(super) async fn terminate(slot: &Slot) {
let owned = slot.lock().unwrap_or_else(|p| p.into_inner()).take();
if let Some(container) = owned {
container.terminate().await;
}
}
pub(super) fn terminate_blocking(slot: &Slot) {
let owned = slot.lock().unwrap_or_else(|p| p.into_inner()).take();
if let Some(container) = owned {
#[cfg(unix)]
if container
.admitting
.load(std::sync::atomic::Ordering::Acquire)
{
container.hard_kill();
std::thread::spawn(move || finish_admission_cleanup(container));
return;
}
std::thread::scope(|scope| {
let result = scope
.spawn(move || {
match tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
{
Ok(runtime) => runtime.block_on(container.terminate()),
Err(error) => {
warn!(%error, "could not create carried-container cleanup driver")
}
}
})
.join();
if result.is_err() {
warn!("carried-container cleanup thread panicked");
}
});
}
}
#[derive(Debug)]
pub(super) enum ProcessChild {
Spawned(ProcessFields),
#[cfg(any(target_os = "linux", target_os = "macos"))]
Adopted(ProcessFields, super::live_upgrade::AdoptedProcess),
}
#[derive(Debug)]
pub(super) struct ProcessFields {
process: Option<Child>,
#[cfg(unix)]
pub(super) plain_group: Option<Arc<super::plain_group::PlainGroup>>,
container: Weak<CarriedContainment>,
slot: Weak<Mutex<Option<Arc<CarriedContainment>>>>,
#[cfg(unix)]
pid: u32,
#[cfg(unix)]
observed: Option<ExitStatus>,
settled: bool,
}
impl std::ops::Deref for ProcessChild {
type Target = ProcessFields;
fn deref(&self) -> &Self::Target {
match self {
Self::Spawned(fields) => fields,
#[cfg(any(target_os = "linux", target_os = "macos"))]
Self::Adopted(fields, _) => fields,
}
}
}
impl std::ops::DerefMut for ProcessChild {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
Self::Spawned(fields) => fields,
#[cfg(any(target_os = "linux", target_os = "macos"))]
Self::Adopted(fields, _) => fields,
}
}
}
impl ProcessChild {
pub(super) fn reject(&mut self, #[cfg(unix)] group: GroupTarget) {
#[cfg(unix)]
if let Some(owned) = &self.plain_group {
owned.close();
}
if let Some(child) = &mut self.process {
super::kill_and_reap_rejected_child(
child,
#[cfg(unix)]
group,
);
}
}
pub(super) fn plain(process: Child, pid: u32) -> Self {
let _ = pid;
Self::Spawned(ProcessFields {
process: Some(process),
#[cfg(unix)]
plain_group: None,
container: Weak::new(),
slot: Weak::new(),
#[cfg(unix)]
pid,
#[cfg(unix)]
observed: None,
settled: false,
})
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) fn adopted(
pid: u32,
watcher: super::live_upgrade::AdoptedProcess,
plain_group: Option<Arc<super::plain_group::PlainGroup>>,
) -> Self {
Self::Adopted(
ProcessFields {
process: None,
plain_group,
container: Weak::new(),
slot: Weak::new(),
pid,
observed: None,
settled: false,
},
watcher,
)
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) fn verified_adoptee(&self) -> Option<&Arc<super::live_upgrade::VerifiedChild>> {
match self {
Self::Adopted(_, process) => Some(process.verified()),
Self::Spawned(_) => None,
}
}
pub(super) fn container(&self) -> Option<Arc<CarriedContainment>> {
self.container.upgrade()
}
pub(super) async fn terminate_container(&self) {
if let Some(slot) = self.slot.upgrade() {
terminate(&slot).await;
}
}
#[cfg(unix)]
pub(super) fn id(&self) -> Option<u32> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
if let Self::Adopted(fields, _) = self {
return Some(fields.pid);
}
if self.container().is_some() {
Some(self.pid)
} else {
self.process.as_ref().and_then(Child::id)
}
}
pub(super) fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
if let Self::Adopted(_, watcher) = self {
return watcher.try_wait();
}
#[cfg(unix)]
if let Some(group) = &self.plain_group {
if self.observed.is_none() {
self.observed = group.observe()?;
}
return Ok(self.observed);
}
#[cfg(unix)]
if self.container().is_some() {
if self.observed.is_none() {
self.observed = match subc_os::child_exit::observe(self.pid) {
Ok(observed) => observed,
Err(error) => {
if let Some(container) = self.container() {
container.note_observation_error(self.pid, &error);
}
return Err(error);
}
};
}
return Ok(self.observed);
}
self.process
.as_mut()
.ok_or_else(|| io::Error::other("process-group pin is no longer owned"))?
.try_wait()
}
pub(super) async fn wait(&mut self) -> io::Result<ExitStatus> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
if let Self::Adopted(_, watcher) = self {
return watcher.wait().await;
}
#[cfg(unix)]
if let Some(group) = &self.plain_group {
if self.observed.is_none() {
self.observed = Some(group.wait_for_exit().await?);
}
return Ok(self.observed.expect("plain group exit was observed"));
}
#[cfg(unix)]
if self.container().is_some() {
loop {
if let Some(status) = self.try_wait()? {
return Ok(status);
}
sleep(Duration::from_millis(50)).await;
}
}
self.process
.as_mut()
.ok_or_else(|| io::Error::other("process-group pin is no longer owned"))?
.wait()
.await
}
pub(super) fn start_kill(&mut self) -> io::Result<()> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
if let Self::Adopted(fields, watcher) = self {
return watcher.kill(fields.plain_group.as_deref());
}
#[cfg(unix)]
if let Some(group) = &self.plain_group {
return group.signal(rustix::process::Signal::KILL);
}
#[cfg(unix)]
if let Some(container) = self.container() {
if let Err(error) = subc_os::child_exit::observe(self.pid) {
container.note_observation_error(self.pid, &error);
return Err(error);
}
}
if let Some(process) = &mut self.process {
return process.start_kill();
}
#[cfg(unix)]
if let Some(container) = self.container() {
match &container.resource {
Resource::Group { pin, .. } => {
if let Some(pin) = pin.lock().unwrap_or_else(|p| p.into_inner()).as_mut() {
return pin.start_kill();
}
}
#[cfg(target_os = "linux")]
Resource::Cgroup { .. } => {}
}
}
Err(io::Error::other("process-group pin is no longer owned"))
}
pub(super) async fn reap(&mut self) -> io::Result<()> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
if let Self::Adopted(fields, watcher) = self {
if let Some(group) = &fields.plain_group {
group.close();
}
return watcher.reap();
}
if self.settled {
return Ok(());
}
#[cfg(unix)]
if let Some(group) = &self.plain_group {
group.settle().await;
group.close();
}
if let Some(process) = &mut self.process {
process.wait().await?;
}
self.settled = true;
Ok(())
}
}
pub(super) fn adopt(
child: &mut SupervisedChild,
spec: &ModuleSpec,
roster: &ChildRoster,
) -> Result<(), SuperviseError> {
#[cfg(test)]
if roster.take_adoption_failure_for_test() {
return Err(SuperviseError::Spawn {
program: spec.program.clone(),
source: io::Error::other("test rejected carried adoption"),
cgroup_path: None,
});
}
let container = current(&roster.containment);
if container.is_none() && !spec.carry_containment {
return Ok(());
}
#[cfg(unix)]
let container = container.ok_or_else(|| SuperviseError::Spawn {
program: spec.program.clone(),
source: io::Error::other("carried container identity was lost before final adoption"),
cgroup_path: None,
})?;
#[cfg(windows)]
let container = match container {
Some(container) => container,
None => adopt_suspended_job(child, spec, roster)?,
};
if container.ending.load(std::sync::atomic::Ordering::Acquire) {
return Err(SuperviseError::Spawn {
program: spec.program.clone(),
source: io::Error::other("carried container ended during admission"),
cgroup_path: None,
});
}
#[cfg(unix)]
#[allow(irrefutable_let_patterns)]
if let Resource::Group {
pgid,
pin,
pending_pin,
..
} = &container.resource
{
if *pgid == child.pid {
let mut pin = pin.lock().unwrap_or_else(|p| p.into_inner());
if container.ending.load(std::sync::atomic::Ordering::Acquire) {
return Err(SuperviseError::Spawn {
program: spec.program.clone(),
source: io::Error::other("carried container ended before pin transfer"),
cgroup_path: None,
});
}
if pending_pin.swap(false, std::sync::atomic::Ordering::AcqRel) {
*pin = child.child.process.take().map(Pin::Spawned);
}
}
}
child.child.container = Arc::downgrade(&container);
#[cfg(unix)]
if let Some(binding) = &child._program_binding {
*container
.binding_retirement
.lock()
.unwrap_or_else(|p| p.into_inner()) = Some(binding.retirement_hook());
}
child.child.slot = Arc::downgrade(&roster.containment);
#[cfg(windows)]
{
child.job = None;
}
Ok(())
}
#[cfg(unix)]
pub(super) fn prepare_before_exec(
spec: &ModuleSpec,
roster: &ChildRoster,
pid: u32,
birth: u64,
identity: LaunchIdentity,
#[cfg(target_os = "linux")] cgroup: Option<(subc_cgroup::Placement, String, PathBuf)>,
) -> Arc<CarriedContainment> {
let group = || Resource::Group {
pgid: pid,
created_start_time: Some(birth),
identity: identity.clone(),
anchor_lost: std::sync::atomic::AtomicBool::new(false),
pin: Arc::new(Mutex::new(None)),
pending_pin: std::sync::atomic::AtomicBool::new(true),
};
#[cfg(target_os = "linux")]
let resource = match cgroup {
Some((placement, name, path)) => Resource::Cgroup {
placement,
name,
path,
identity,
},
None => group(),
};
#[cfg(not(target_os = "linux"))]
let resource = group();
let owned = Arc::new(CarriedContainment {
binding_retirement: Mutex::new(None),
module_id: spec.module_id.clone(),
counters: roster.counters.clone(),
cleanup_block: Mutex::new(None),
#[cfg(test)]
group_signals: Mutex::new(None),
resource,
end_log: Mutex::new(Some(ContainerEnd::default())),
roster: Mutex::new(None),
terminated: std::sync::atomic::AtomicBool::new(false),
ending: std::sync::atomic::AtomicBool::new(false),
admitting: std::sync::atomic::AtomicBool::new(false),
admission_changed: tokio::sync::Notify::new(),
cleanup_finished: tokio::sync::Notify::new(),
hard_killed: std::sync::atomic::AtomicBool::new(false),
kill_notify: tokio::sync::Notify::new(),
});
*roster.containment.lock().unwrap_or_else(|p| p.into_inner()) = Some(Arc::clone(&owned));
owned
}
#[cfg(windows)]
fn adopt_suspended_job(
child: &mut SupervisedChild,
spec: &ModuleSpec,
roster: &ChildRoster,
) -> Result<Arc<CarriedContainment>, SuperviseError> {
let owned = Arc::new(CarriedContainment {
module_id: spec.module_id.clone(),
resource: Resource::Job(
child
.job
.take()
.expect("suspended child was assigned to its job"),
),
end_log: Mutex::new(Some(ContainerEnd::default())),
roster: Mutex::new(None),
terminated: std::sync::atomic::AtomicBool::new(false),
ending: std::sync::atomic::AtomicBool::new(false),
admitting: std::sync::atomic::AtomicBool::new(false),
admission_changed: tokio::sync::Notify::new(),
cleanup_finished: tokio::sync::Notify::new(),
hard_killed: std::sync::atomic::AtomicBool::new(false),
kill_notify: tokio::sync::Notify::new(),
});
*roster.containment.lock().unwrap_or_else(|p| p.into_inner()) = Some(Arc::clone(&owned));
let recorded = crate::child_roster::RecordedIdentity {
start_time: child.process_start_time,
container: Some(crate::live_children::ContainerIdentity {
created_start_time: child.process_start_time,
..Default::default()
}),
..Default::default()
};
match roster.admit(
spec.module_id.clone(),
child.pid,
child.protocol,
child.process_start_time,
recorded,
) {
Ok(guard) => *owned.roster.lock().unwrap_or_else(|p| p.into_inner()) = Some(guard),
Err(failure) => {
let source = owned.claim_failed_admission(failure);
owned.note_end_reason(ContainerEndReason::SpawnFailed);
terminate_blocking(&roster.containment);
return Err(SuperviseError::Spawn {
program: spec.program.clone(),
source,
cgroup_path: None,
});
}
}
Ok(owned)
}
#[cfg(target_os = "linux")]
pub(super) fn prepare_cgroup_path(
placement: &subc_cgroup::Placement,
name: &str,
) -> io::Result<PathBuf> {
let path = placement.module_path(name)?;
let canonical = std::fs::canonicalize(&path)?;
placement.existing_module_path(&canonical)?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"new cgroup disappeared before spawn",
)
})
}
#[cfg(unix)]
impl CarriedContainment {
pub(super) fn admit_before_exec(
self: &Arc<Self>,
spec: &ModuleSpec,
roster: &ChildRoster,
pid: u32,
birth: u64,
) -> io::Result<()> {
let recorded = crate::child_roster::RecordedIdentity {
start_time: Some(birth),
executable: None,
cgroup_name: {
#[cfg(target_os = "linux")]
{
self.cgroup().map(|(_, name)| name.to_owned())
}
#[cfg(not(target_os = "linux"))]
{
None
}
},
container: Some(crate::live_children::ContainerIdentity {
pgid: self.group(),
created_start_time: Some(birth),
boot_id: Some(self.launch_identity().boot_id.clone()),
session_id: Some(self.launch_identity().session_id),
cgroup_path: {
#[cfg(target_os = "linux")]
{
self.cgroup_path().map(Path::to_owned)
}
#[cfg(not(target_os = "linux"))]
{
None
}
},
}),
carried: Some(Arc::downgrade(self)),
plain_group: None,
#[cfg(target_os = "linux")]
cgroup_placement: self.cgroup().map(|(placement, _)| placement.clone()),
};
match roster.admit(
spec.module_id.clone(),
pid,
spec.protocol,
Some(birth),
recorded,
) {
Ok(guard) => {
*self.roster.lock().unwrap_or_else(|p| p.into_inner()) = Some(guard);
Ok(())
}
Err(failure) => Err(self.claim_failed_admission(failure)),
}
}
pub(super) fn begin_admission(&self) {
self.admitting
.store(true, std::sync::atomic::Ordering::Release);
}
pub(super) fn end_admission(&self) {
self.admitting
.store(false, std::sync::atomic::Ordering::Release);
self.admission_changed.notify_waiters();
}
pub(super) fn is_ending(&self) -> bool {
self.ending.load(std::sync::atomic::Ordering::Acquire)
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
impl CarriedContainment {
async fn await_inherited_pin_exit(&self, pid: u32) {
loop {
match subc_os::child_exit::observe(pid) {
Ok(None) => sleep(Duration::from_millis(1)).await,
Ok(Some(_)) => break,
Err(error) => {
warn!(module_id = %self.module_id, pid, %error,
"cannot observe the inherited process-group pin; leaving it unreaped");
break;
}
}
}
let binding = self
.binding_retirement
.lock()
.unwrap_or_else(|p| p.into_inner())
.as_ref()
.and_then(|hook| hook.upgrade());
if let Some(binding) = &binding {
binding.retire();
}
}
fn settle_inherited_pin(&self, pid: u32, owner: PinOwner, reap_lock: ReapLock) {
let Some(record) = self.recorded_group() else {
return;
};
let pin = InheritedPin {
pid,
birth: record.created_start_time,
boot_id: record.boot_id.to_owned(),
session_id: record.session_id,
owner,
reap_lock: Some(reap_lock),
};
let mut end = ContainerEnd::default();
let result = settle_inherited_group_reported(&pin, &mut end);
end.failed |= result.is_err();
self.update_end_log(|log| log.merge(end));
let unsettled = match result {
Ok(()) => return,
Err(unsettled) => unsettled,
};
let reason = unsettled.reason();
warn!(module_id = %self.module_id, pgid = pid, reason = %reason.waiting_message(pid),
"the ended carried container is not proven settled; its module stays held");
let guard = self.roster.lock().unwrap_or_else(|p| p.into_inner()).take();
let Some(held) = guard.and_then(|guard| guard.hold_carried(reason)) else {
return;
};
let module = self.module_id.clone();
let retry = async move {
hold_until_settled_inner(&module, &pin, held, |_| {}, None).await;
};
match tokio::runtime::Handle::try_current() {
Ok(runtime) => {
runtime.spawn(retry);
}
Err(_) => {
std::thread::spawn(move || {
if let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
runtime.block_on(retry);
}
});
}
}
}
pub(super) fn still_holds_member(&self, module_pid: u32) -> bool {
#[allow(irrefutable_let_patterns)]
let Resource::Group {
pgid,
pin,
anchor_lost,
..
} = &self.resource
else {
return false;
};
let pin = pin.lock().unwrap_or_else(|p| p.into_inner());
self.owns_pin(*pgid, &pin, anchor_lost)
&& subc_os::process_group::pgid(module_pid).ok().flatten() == Some(*pgid)
}
pub(super) fn handover_witness(
&self,
child_pid: u32,
) -> Option<super::handover::CarriedContainerWitness> {
use std::sync::atomic::Ordering::Acquire;
#[allow(irrefutable_let_patterns)]
let Resource::Group {
pgid,
created_start_time: Some(created_start_time),
identity,
anchor_lost,
pin,
pending_pin,
} = &self.resource
else {
return None;
};
if self.ending.load(Acquire)
|| self.terminated.load(Acquire)
|| self.admitting.load(Acquire)
|| pending_pin.load(Acquire)
{
return None;
}
let pin = pin.lock().unwrap_or_else(|p| p.into_inner());
if !self.owns_pin(*pgid, &pin, anchor_lost)
|| subc_os::process_group::pgid(child_pid).ok().flatten() != Some(*pgid)
{
return None;
}
Some(super::handover::CarriedContainerWitness {
pgid: *pgid,
pin_pid: *pgid,
created_start_time: *created_start_time,
boot_id: identity.boot_id.clone(),
session_id: identity.session_id,
})
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[derive(Debug)]
pub(super) struct InheritedPin {
pub(super) pid: u32,
pub(super) birth: u64,
pub(super) boot_id: String,
pub(super) session_id: u32,
pub(super) owner: PinOwner,
reap_lock: Option<ReapLock>,
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
impl InheritedPin {
pub(super) fn from_witness(
witness: &super::handover::CarriedContainerWitness,
owner: PinOwner,
) -> Self {
Self {
pid: witness.pin_pid,
birth: witness.created_start_time,
boot_id: witness.boot_id.clone(),
session_id: witness.session_id,
owner,
reap_lock: None,
}
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[derive(Debug)]
pub(super) enum Unsettled {
Survivors(Vec<u32>),
Unproven(io::Error),
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
impl Unsettled {
pub(super) fn reason(&self) -> crate::live_children::RetainedReason {
match self {
Self::Survivors(pids) => {
crate::live_children::RetainedReason::ContainerSurvivors(pids.clone())
}
Self::Unproven(error) => {
crate::live_children::RetainedReason::ContainerUnverifiable(error.to_string())
}
}
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
impl From<io::Error> for Unsettled {
fn from(error: io::Error) -> Self {
Self::Unproven(error)
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn exact_exited_pin(pid: u32, birth: u64, boot_id: &str) -> io::Result<()> {
if !subc_os::boot_id::is_current(boot_id)? {
return Err(io::Error::other(
"the process-group pin belongs to another boot",
));
}
if subc_os::child_exit::observe(pid)?.is_none() {
return Err(io::Error::new(
io::ErrorKind::WouldBlock,
"the process-group pin has not exited",
));
}
let actual = group_pin_birth(pid)?;
if actual != birth {
return Err(io::Error::other(format!(
"the process-group pin's birth differs: recorded {birth}, observed {actual}"
)));
}
Ok(())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn reap_exact_pin(pin: &InheritedPin) -> io::Result<()> {
exact_exited_pin(pin.pid, pin.birth, &pin.boot_id)?;
#[cfg(test)]
if settle_faults::take_failed_reap(pin.pid) {
return Err(io::Error::other("injected transient pin wait failure"));
}
let raw = i32::try_from(pin.pid)
.ok()
.filter(|pid| *pid > 1)
.and_then(rustix::process::Pid::from_raw)
.ok_or_else(|| io::Error::other("invalid process-group pin pid"))?;
loop {
match rustix::process::waitpid(Some(raw), rustix::process::WaitOptions::NOHANG) {
Ok(Some(_)) => return Ok(()),
Ok(None) => return Err(io::Error::other("the process-group pin has not exited")),
Err(rustix::io::Errno::INTR) => {}
Err(error) => return Err(error.into()),
}
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) fn require_complete_process_view(pgid: u32) -> io::Result<()> {
#[cfg(target_os = "linux")]
{
#[cfg(test)]
let injected = settle_faults::mountinfo(pgid);
#[cfg(not(test))]
let injected: Option<String> = None;
let mountinfo = match injected {
Some(text) => text,
None => std::fs::read_to_string("/proc/self/mountinfo")?,
};
if let Some(restriction) = proc_view_restriction(&mountinfo) {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("the process list cannot show every process: {restriction}"),
));
}
let own = std::fs::read_link("/proc/self")?;
if own.to_str().and_then(|pid| pid.parse::<u32>().ok()) != Some(std::process::id()) {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"/proc belongs to another PID namespace",
));
}
}
let _ = pgid;
Ok(())
}
#[cfg(any(target_os = "linux", test))]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(super) fn proc_view_restriction(mountinfo: &str) -> Option<String> {
let mut options = None;
for line in mountinfo.lines() {
let Some((mount, filesystem)) = line.split_once(" - ") else {
continue;
};
let mount: Vec<_> = mount.split(' ').collect();
let mut filesystem = filesystem.split(' ');
let (Some(fstype), _, superblock) =
(filesystem.next(), filesystem.next(), filesystem.next())
else {
continue;
};
if mount.get(4) == Some(&"/proc") && fstype == "proc" {
options = Some(format!(
"{},{}",
mount.get(5).unwrap_or(&""),
superblock.unwrap_or("")
));
}
}
let Some(options) = options else {
return Some("no proc filesystem is mounted at /proc".into());
};
options
.split(',')
.find_map(|option| match option.split_once('=') {
Some(("hidepid", "0" | "off")) => None,
Some(("hidepid", _)) | Some(("subset", _)) => {
Some(format!("/proc is mounted with {option}"))
}
_ => None,
})
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn live_group_members(pgid: u32) -> io::Result<Vec<u32>> {
require_complete_process_view(pgid)?;
let mut live = Vec::new();
for pid in subc_os::process_group::members(pgid)? {
if pid == pgid {
continue;
}
if subc_os::process_group::inspect(pid)?
.is_some_and(|member| member.pgid == pgid && !member.exited)
{
live.push(pid);
}
}
Ok(live)
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
pub(super) fn settle_inherited_group(pin: &InheritedPin) -> Result<(), Unsettled> {
settle_inherited_group_reported(pin, &mut ContainerEnd::default())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn settle_inherited_group_reported(
pin: &InheritedPin,
end: &mut ContainerEnd,
) -> Result<(), Unsettled> {
if subc_os::process_group::session_id(std::process::id())? != Some(pin.session_id) {
return Err(
io::Error::other("the handed-over container belongs to another session").into(),
);
}
exact_exited_pin(pin.pid, pin.birth, &pin.boot_id)?;
let mut live = live_group_members(pin.pid)?;
end.observe_members(live.len());
let deadline = std::time::Instant::now() + Duration::from_secs(2);
while !live.is_empty() {
if std::time::Instant::now() >= deadline {
return Err(Unsettled::Survivors(live));
}
exact_exited_pin(pin.pid, pin.birth, &pin.boot_id)?;
match signal_group(pin.pid, rustix::process::Signal::KILL) {
Ok(true) => end.signal("KILL"),
Ok(false) | Err(rustix::io::Errno::SRCH) => {}
Err(_) => end.failed = true,
}
std::thread::sleep(Duration::from_millis(20));
live = live_group_members(pin.pid)?;
}
let _reap = pin
.reap_lock
.as_ref()
.map(|lock| lock.lock().unwrap_or_else(|p| p.into_inner()));
match &pin.owner {
Some(owner) => owner.reap_as_pin(|| reap_exact_pin(pin))?,
None => reap_exact_pin(pin)?,
}
Ok(())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
const HELD_RETRY: Duration = Duration::from_millis(100);
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) async fn record_held_fence(
module: &str,
pgid: u32,
held: &crate::child_roster::HeldContainerRow,
) -> bool {
while !held.daemon_closing() {
if held.persist_fence().is_ok() {
tracing::info!(module_id = %module, pgid, "recorded the held carried container fence");
return true;
}
sleep(HELD_RETRY).await;
}
false
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) async fn hold_until_settled(
module: &str,
pin: &InheritedPin,
held: crate::child_roster::HeldContainerRow,
report: impl Fn(&crate::live_children::RetainedReason),
) -> bool {
hold_until_settled_inner(module, pin, held, report, Some(ContainerEnd::default())).await
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
async fn hold_until_settled_inner(
module: &str,
pin: &InheritedPin,
held: crate::child_roster::HeldContainerRow,
report: impl Fn(&crate::live_children::RetainedReason),
mut end: Option<ContainerEnd>,
) -> bool {
use tokio::signal::unix::{signal, SignalKind};
let mut child_events = signal(SignalKind::child()).ok();
let mut reported: Option<crate::live_children::RetainedReason> = None;
loop {
let attempt = {
let mut ignored = ContainerEnd::default();
let mut work =
|| settle_inherited_group_reported(pin, end.as_mut().unwrap_or(&mut ignored));
if tokio::runtime::Handle::try_current().is_ok_and(|handle| {
handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread
}) {
tokio::task::block_in_place(work)
} else {
work()
}
};
match attempt {
Ok(()) => {
if let Some(end) = end {
end.log(module);
}
loop {
match held.release() {
Ok(_) => return true,
Err(error) => warn!(module_id = %module, pgid = pin.pid, %error,
"settled the carried container but could not remove its record row"),
}
if held.daemon_closing() {
return false;
}
sleep(HELD_RETRY).await;
}
}
Err(unsettled) => {
let reason = unsettled.reason();
if reported.as_ref() != Some(&reason) {
warn!(module_id = %module, pgid = pin.pid,
reason = %reason.waiting_message(pin.pid),
"held: the carried container is not proven settled");
held.report(reason.clone());
report(&reason);
reported = Some(reason);
}
}
}
if held.daemon_closing() {
if let Some(mut end) = end {
end.failed = true;
end.log(module);
}
return false;
}
tokio::select! {
_ = sleep(HELD_RETRY) => {}
_ = async {
match &mut child_events {
Some(events) => { events.recv().await; }
None => std::future::pending::<()>().await,
}
} => {}
}
}
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
pub(super) mod settle_faults {
use std::collections::BTreeMap;
use std::sync::Mutex;
#[derive(Default)]
struct Faults {
#[cfg(target_os = "linux")]
mountinfo: BTreeMap<u32, String>,
failed_reaps: BTreeMap<u32, usize>,
}
static FAULTS: Mutex<Option<Faults>> = Mutex::new(None);
#[cfg(target_os = "linux")]
const COMPLETE_VIEW: &str = "25 1 0:23 / /proc rw - proc proc rw\n";
#[cfg(target_os = "linux")]
pub(crate) struct CompleteView(u32);
#[cfg(target_os = "linux")]
impl Drop for CompleteView {
fn drop(&mut self) {
set_mountinfo(self.0, None);
}
}
#[cfg(target_os = "linux")]
pub(crate) fn complete_view(pgid: u32) -> CompleteView {
set_mountinfo(pgid, Some(COMPLETE_VIEW));
CompleteView(pgid)
}
fn with<T>(work: impl FnOnce(&mut Faults) -> T) -> T {
work(
FAULTS
.lock()
.unwrap_or_else(|p| p.into_inner())
.get_or_insert_with(Faults::default),
)
}
#[cfg(target_os = "linux")]
pub(crate) fn set_mountinfo(pgid: u32, text: Option<&str>) {
with(|faults| match text {
Some(text) => {
faults.mountinfo.insert(pgid, text.to_owned());
}
None => {
faults.mountinfo.remove(&pgid);
}
});
}
pub(crate) fn fail_reaps(pgid: u32, count: usize) {
with(|faults| {
faults.failed_reaps.insert(pgid, count);
});
}
#[cfg(target_os = "linux")]
pub(super) fn mountinfo(pgid: u32) -> Option<String> {
with(|faults| faults.mountinfo.get(&pgid).cloned())
}
pub(super) fn take_failed_reap(pgid: u32) -> bool {
with(|faults| match faults.failed_reaps.get_mut(&pgid) {
Some(count) if *count > 0 => {
*count -= 1;
true
}
_ => false,
})
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) fn adopt_after_upgrade(
module_id: &str,
module_pid: u32,
roster: &ChildRoster,
slot: &Slot,
witness: &super::handover::CarriedContainerWitness,
record: &crate::live_children::RecordedChild,
pin_owner: PinOwner,
) -> io::Result<Arc<CarriedContainment>> {
if current(slot).is_some() {
return Err(io::Error::other(
"the module already has a carried container",
));
}
let container = Arc::new(CarriedContainment {
binding_retirement: Mutex::new(None),
module_id: module_id.to_owned(),
counters: roster.counters.clone(),
cleanup_block: Mutex::new(None),
#[cfg(test)]
group_signals: Mutex::new(None),
resource: Resource::Group {
pgid: witness.pgid,
created_start_time: Some(witness.created_start_time),
identity: LaunchIdentity {
boot_id: witness.boot_id.clone(),
session_id: witness.session_id,
},
anchor_lost: std::sync::atomic::AtomicBool::new(false),
pin: Arc::new(Mutex::new(Some(Pin::Inherited {
pid: witness.pin_pid,
owner: pin_owner,
}))),
pending_pin: std::sync::atomic::AtomicBool::new(false),
},
end_log: Mutex::new(Some(ContainerEnd::default())),
roster: Mutex::new(None),
terminated: std::sync::atomic::AtomicBool::new(false),
ending: std::sync::atomic::AtomicBool::new(false),
admitting: std::sync::atomic::AtomicBool::new(false),
admission_changed: tokio::sync::Notify::new(),
cleanup_finished: tokio::sync::Notify::new(),
hard_killed: std::sync::atomic::AtomicBool::new(false),
kill_notify: tokio::sync::Notify::new(),
});
let proven = match &container.resource {
Resource::Group {
pgid,
pin,
anchor_lost,
..
} => {
container.owns_pin(
*pgid,
&pin.lock().unwrap_or_else(|p| p.into_inner()),
anchor_lost,
) && subc_os::process_group::pgid(module_pid).ok().flatten() == Some(*pgid)
}
#[cfg(target_os = "linux")]
Resource::Cgroup { .. } => false,
};
let guard = if proven {
*slot.lock().unwrap_or_else(|p| p.into_inner()) = Some(Arc::clone(&container));
roster.admit_adopted_container(record, Arc::downgrade(&container))
} else {
Err(io::Error::other(
"the inherited process-group pin or the module's membership in its group is no longer proven",
))
};
match guard {
Ok(guard) => {
*container.roster.lock().unwrap_or_else(|p| p.into_inner()) = Some(guard);
Ok(container)
}
Err(error) => {
slot.lock().unwrap_or_else(|p| p.into_inner()).take();
container
.terminated
.store(true, std::sync::atomic::Ordering::Release);
Err(error)
}
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(super) fn attach_after_upgrade(
child: &mut SupervisedChild,
container: &Arc<CarriedContainment>,
roster: &ChildRoster,
) {
child.child.container = Arc::downgrade(container);
child.child.slot = Arc::downgrade(&roster.containment);
if let Some(binding) = &child._program_binding {
*container
.binding_retirement
.lock()
.unwrap_or_else(|p| p.into_inner()) = Some(binding.retirement_hook());
}
}
pub(super) fn terminate_deferred(slot: &Slot) {
let owned = slot.lock().unwrap_or_else(|p| p.into_inner()).take();
if let Some(container) = owned {
container.hard_kill();
std::thread::spawn(move || {
match tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
{
Ok(runtime) => runtime.block_on(container.terminate()),
Err(error) => warn!(%error, "could not start deferred carried-container cleanup"),
}
});
}
}
#[cfg(unix)]
pub(super) fn finish_admission_cleanup(container: Arc<CarriedContainment>) {
match tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
{
Ok(runtime) => runtime.block_on(container.terminate()),
Err(error) => warn!(%error, "could not finish carried admission cleanup"),
}
}
#[cfg(unix)]
#[derive(Clone)]
pub(super) enum GroupTarget {
OwnLeader,
Pinned(Arc<CarriedContainment>),
NoGroup,
}
#[cfg(unix)]
impl GroupTarget {
pub(super) fn signal_rejected(&self, child: &Child) {
match self {
Self::OwnLeader => {
if let Some(pid) = child
.id()
.filter(|pid| *pid > 1 && subc_os::child_exit::observe(*pid).is_ok())
{
let _ = signal_group(pid, rustix::process::Signal::KILL);
}
}
Self::Pinned(container) => container.hard_kill(),
Self::NoGroup => {}
}
}
}
impl Drop for ProcessChild {
fn drop(&mut self) {
#[cfg(any(target_os = "linux", target_os = "macos"))]
if matches!(self, Self::Adopted(..)) {
return;
}
if !self.settled {
#[cfg(unix)]
if let Some(group) = &self.plain_group {
let _ = group.signal(rustix::process::Signal::KILL);
group.close();
}
if let Some(container) = self.container() {
container.hard_kill();
let _ = self.start_kill();
}
}
}
}
#[cfg(all(test, unix))]
mod anchor_tests {
use super::*;
#[cfg(target_os = "linux")]
#[tokio::test]
async fn config_recovery_r5_carried_pin_wait_error_retires_before_cleanup() {
let mut command = Command::new("/bin/sleep");
command.arg("600").process_group(0).kill_on_drop(true);
let mut leader = command.spawn().unwrap();
let pid = leader.id().unwrap();
let birth = subc_os::process_group::inspect(pid)
.unwrap()
.unwrap()
.start_time;
let handle = SupervisorHandle::new();
handle.set_spawn_nonce("pin-error", "dead".into());
handle.set_reserved_nonce("pin-error", "dead".into());
let publication = handle
.begin_program_binding("pin-error", SpawnRole::Plain)
.unwrap();
handle.release_program_binding_witnesses_for_test();
leader.start_kill().unwrap();
rustix::process::waitpid(
rustix::process::Pid::from_raw(pid as i32),
rustix::process::WaitOptions::empty(),
)
.unwrap();
let container = Arc::new(CarriedContainment {
binding_retirement: Mutex::new(Some(publication.retirement_hook())),
module_id: "pin-error".into(),
counters: crate::observability::DaemonCounters::default(),
cleanup_block: Mutex::new(None),
group_signals: Mutex::new(None),
resource: Resource::Group {
identity: LaunchIdentity::capture().unwrap(),
pgid: pid,
created_start_time: Some(birth),
anchor_lost: std::sync::atomic::AtomicBool::new(false),
pin: Arc::new(Mutex::new(Some(Pin::Spawned(leader)))),
pending_pin: std::sync::atomic::AtomicBool::new(false),
},
end_log: Mutex::new(Some(ContainerEnd::default())),
roster: Mutex::new(None),
terminated: std::sync::atomic::AtomicBool::new(false),
ending: std::sync::atomic::AtomicBool::new(false),
admitting: std::sync::atomic::AtomicBool::new(false),
admission_changed: tokio::sync::Notify::new(),
cleanup_finished: tokio::sync::Notify::new(),
hard_killed: std::sync::atomic::AtomicBool::new(false),
kill_notify: tokio::sync::Notify::new(),
});
let (uncertain, release) = handle.pause_program_binding_exit_for_test("pin-error", "dead");
let terminating = tokio::spawn({
let container = container.clone();
async move { container.terminate().await }
});
tokio::time::timeout(Duration::from_secs(5), uncertain)
.await
.unwrap()
.unwrap();
let handler =
crate::ControlHandler::new(Arc::new(Registry::default())).with_supervisor(handle);
let hello = subc_protocol::ModuleHelloBody {
module_capabilities: None,
resume_token: None,
manifest: subc_protocol::manifest::ModuleManifest::builder("pin-error", "1.0.0")
.build(),
protocol_ver: subc_protocol::PROTOCOL_VERSION,
control_ops: None,
launch_nonce: Some("dead".into()),
};
let reply = handler
.handle_control(
ConnectionId::new(99),
subc_protocol::Frame::build(
subc_protocol::FrameType::Hello,
control_flags(),
0,
0,
1,
serde_json::to_vec(&hello).unwrap(),
)
.unwrap(),
)
.unwrap();
release.send(()).unwrap();
terminating.await.unwrap();
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&reply[0].body).unwrap()["code"],
"program_refused",
"pin wait errors must revoke before group recovery awaits"
);
}
#[tokio::test]
async fn mismatched_pin_birth_refuses_every_group_signal_and_join() {
let mut command = Command::new("/bin/sleep");
command.arg("600").process_group(0).kill_on_drop(true);
let leader = command.spawn().unwrap();
let pgid = leader.id().unwrap();
let actual = subc_os::process_group::inspect(pgid)
.unwrap()
.unwrap()
.start_time;
let group_signals = Arc::new(Mutex::new(Vec::new()));
let container = CarriedContainment {
binding_retirement: Mutex::new(None),
module_id: "mismatched-pin-birth".into(),
counters: crate::observability::DaemonCounters::default(),
cleanup_block: Mutex::new(None),
group_signals: Mutex::new(Some(Arc::clone(&group_signals))),
resource: Resource::Group {
identity: LaunchIdentity::capture().unwrap(),
pgid,
created_start_time: Some(actual + 1),
anchor_lost: std::sync::atomic::AtomicBool::new(false),
pin: Arc::new(Mutex::new(Some(Pin::Spawned(leader)))),
pending_pin: std::sync::atomic::AtomicBool::new(false),
},
end_log: Mutex::new(Some(ContainerEnd::default())),
roster: Mutex::new(None),
terminated: std::sync::atomic::AtomicBool::new(false),
ending: std::sync::atomic::AtomicBool::new(false),
admitting: std::sync::atomic::AtomicBool::new(false),
admission_changed: tokio::sync::Notify::new(),
cleanup_finished: tokio::sync::Notify::new(),
hard_killed: std::sync::atomic::AtomicBool::new(false),
kill_notify: tokio::sync::Notify::new(),
};
let joined = container.verified_join_group();
let signalled = container.signal_pinned_group(rustix::process::Signal::TERM);
assert!(joined.is_err() && !signalled && group_signals.lock().unwrap().is_empty(),
"an owned child with a different birth must authorize neither joining nor group signalling");
assert!(subc_os::child_exit::observe(pgid).unwrap().is_none());
}
#[tokio::test]
async fn failed_container_admission_keeps_the_guard_for_unverifiable_cleanup() {
let dir = cortexkit_test_support::ScratchDir::new("failed-container-admission");
let path = dir.join("record.json");
let roster = ChildRoster::default();
roster.record_to(path.clone());
std::fs::create_dir(path).unwrap();
let container = Arc::new(CarriedContainment {
binding_retirement: Mutex::new(None),
module_id: "unverifiable-admission".into(),
counters: crate::observability::DaemonCounters::default(),
cleanup_block: Mutex::new(None),
group_signals: Mutex::new(None),
resource: Resource::Group {
identity: LaunchIdentity::capture().unwrap(),
pgid: u32::MAX,
created_start_time: None,
anchor_lost: std::sync::atomic::AtomicBool::new(false),
pin: Arc::new(Mutex::new(None)),
pending_pin: std::sync::atomic::AtomicBool::new(false),
},
end_log: Mutex::new(Some(ContainerEnd::default())),
roster: Mutex::new(None),
terminated: std::sync::atomic::AtomicBool::new(false),
ending: std::sync::atomic::AtomicBool::new(false),
admitting: std::sync::atomic::AtomicBool::new(false),
admission_changed: tokio::sync::Notify::new(),
cleanup_finished: tokio::sync::Notify::new(),
hard_killed: std::sync::atomic::AtomicBool::new(false),
kill_notify: tokio::sync::Notify::new(),
});
let failure = roster
.admit(
"unverifiable-admission".into(),
u32::MAX,
ModuleProtocol::None,
None,
crate::child_roster::RecordedIdentity {
container: Some(crate::live_children::ContainerIdentity {
pgid: Some(u32::MAX),
cgroup_path: None,
created_start_time: None,
..crate::live_children::ContainerIdentity::test_metadata()
}),
..Default::default()
},
)
.unwrap_err();
let _error = container.claim_failed_admission(failure);
container.terminate().await;
assert!(
roster.previous_instance("unverifiable-admission").is_some(),
"failed durable admission must retain its guard when cleanup cannot prove emptiness"
);
}
#[tokio::test]
async fn drop_retains_the_container_when_kill_acceptance_is_not_exit_proof() {
let dir = cortexkit_test_support::ScratchDir::new("drop-container-retention");
let record = dir.join("record.json");
let roster = ChildRoster::default();
roster.record_to(record.clone());
let mut command = Command::new("/bin/sleep");
command.arg("600").process_group(0).kill_on_drop(true);
let leader = command.spawn().unwrap();
let pgid = leader.id().unwrap();
let facts = subc_os::process_group::inspect(pgid).unwrap().unwrap();
let mut command = Command::new("/bin/sleep");
command
.arg("600")
.process_group(pgid as i32)
.kill_on_drop(true);
let mut holder = command.spawn().unwrap();
let group_signals = Arc::new(Mutex::new(Vec::new()));
let container = Arc::new(CarriedContainment {
binding_retirement: Mutex::new(None),
module_id: "drop-retention".into(),
counters: crate::observability::DaemonCounters::default(),
cleanup_block: Mutex::new(None),
group_signals: Mutex::new(Some(Arc::clone(&group_signals))),
resource: Resource::Group {
identity: LaunchIdentity::capture().unwrap(),
pgid,
created_start_time: Some(facts.start_time),
anchor_lost: std::sync::atomic::AtomicBool::new(false),
pin: Arc::new(Mutex::new(Some(Pin::Spawned(leader)))),
pending_pin: std::sync::atomic::AtomicBool::new(false),
},
end_log: Mutex::new(Some(ContainerEnd::default())),
roster: Mutex::new(None),
terminated: std::sync::atomic::AtomicBool::new(false),
ending: std::sync::atomic::AtomicBool::new(false),
admitting: std::sync::atomic::AtomicBool::new(false),
admission_changed: tokio::sync::Notify::new(),
cleanup_finished: tokio::sync::Notify::new(),
hard_killed: std::sync::atomic::AtomicBool::new(false),
kill_notify: tokio::sync::Notify::new(),
});
let guard = roster
.admit(
"drop-retention".into(),
pgid,
ModuleProtocol::None,
Some(facts.start_time),
crate::child_roster::RecordedIdentity {
container: Some(crate::live_children::ContainerIdentity {
pgid: Some(pgid),
cgroup_path: None,
created_start_time: Some(facts.start_time),
..crate::live_children::ContainerIdentity::test_metadata()
}),
carried: Some(Arc::downgrade(&container)),
..Default::default()
},
)
.unwrap();
*container.roster.lock().unwrap() = Some(guard);
drop(container);
assert_eq!(
*group_signals.lock().unwrap(),
vec![rustix::process::Signal::KILL]
);
assert!(
crate::live_children::read_record(&record)
.unwrap()
.iter()
.any(|entry| entry.module_id == "drop-retention" && entry.container.is_some()),
"accepting KILL must not erase the only record before members are proven gone"
);
let (pid, reason) = roster
.previous_instance("drop-retention")
.expect("an unrecorded survivor must hold the module");
assert!(reason
.waiting_message(pid)
.contains(&format!("pid {} (", holder.id().unwrap())));
assert!(holder.try_wait().unwrap().is_none());
holder.start_kill().unwrap();
holder.wait().await.unwrap();
}
#[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn hard_kill_recheck_serializes_identity_and_delivery_with_pin_reap() {
let mut command = Command::new("/bin/sleep");
command.arg("600").process_group(0).kill_on_drop(true);
let leader = command.spawn().unwrap();
let pgid = leader.id().unwrap();
let birth = group_pin_birth(pgid).unwrap();
let container = CarriedContainment {
binding_retirement: Mutex::new(None),
module_id: "recheck-lock".into(),
counters: crate::observability::DaemonCounters::default(),
cleanup_block: Mutex::new(None),
group_signals: Mutex::new(None),
resource: Resource::Group {
identity: LaunchIdentity::capture().unwrap(),
pgid,
created_start_time: Some(birth),
anchor_lost: std::sync::atomic::AtomicBool::new(false),
pin: Arc::new(Mutex::new(Some(Pin::Spawned(leader)))),
pending_pin: std::sync::atomic::AtomicBool::new(false),
},
end_log: Mutex::new(Some(ContainerEnd::default())),
roster: Mutex::new(None),
terminated: std::sync::atomic::AtomicBool::new(false),
ending: std::sync::atomic::AtomicBool::new(false),
admitting: std::sync::atomic::AtomicBool::new(false),
admission_changed: tokio::sync::Notify::new(),
cleanup_finished: tokio::sync::Notify::new(),
hard_killed: std::sync::atomic::AtomicBool::new(false),
kill_notify: tokio::sync::Notify::new(),
};
let Resource::Group { pin, .. } = &container.resource else {
unreachable!()
};
std::thread::scope(|scope| {
let (try_reap, reap_requested) = std::sync::mpsc::channel();
let (attempted, reap_blocked) = std::sync::mpsc::channel();
let reaper = scope.spawn(move || {
reap_requested.recv_timeout(Duration::from_secs(5)).unwrap();
attempted.send(pin.try_lock().is_err()).unwrap();
pin.lock().unwrap().as_mut().unwrap().try_wait().unwrap();
});
let delivered = std::cell::Cell::new(false);
container.recheck_group(|record, signal| {
crate::group_recovery::signal_recorded_anchor_using(
record,
signal,
subc_os::process_group::session_id,
|pid| {
try_reap.send(()).unwrap();
assert!(
reap_blocked.recv_timeout(Duration::from_secs(5)).unwrap(),
"pin reaper could enter during the final identity check"
);
subc_os::process_group::inspect(pid)
},
|process, signal| {
assert!(
pin.try_lock().is_err(),
"reap lock released before delivery"
);
delivered.set(true);
process.signal(signal)
},
)
});
reaper.join().unwrap();
assert!(delivered.get(), "recheck did not attempt anchor delivery");
});
container.terminate().await;
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
async fn retained_container_does_not_block_shutdown_behind_a_stalled_fence_write() {
use crate::child_roster::RecordedIdentity;
use crate::live_children::{ContainerIdentity, LiveChild, RecordedChild, RetainedReason};
let dir = cortexkit_test_support::ScratchDir::new("stalled-fence-container-retain");
let record = dir.join("children.json");
let roster = ChildRoster::default();
roster.record_to(record.clone());
let mut command = Command::new("/bin/sleep");
command.arg("60").process_group(0).kill_on_drop(true);
let mut leader = command.spawn().unwrap();
let pgid = leader.id().unwrap();
let birth = group_pin_birth(pgid).unwrap();
command.process_group(pgid as i32);
let mut survivor = command.spawn().unwrap();
leader.kill().await.unwrap();
let identity = LaunchIdentity::capture().unwrap();
let container = Arc::new(CarriedContainment {
binding_retirement: Mutex::new(None),
module_id: "retiring".into(),
counters: crate::observability::DaemonCounters::default(),
cleanup_block: Mutex::new(Some(RetainedReason::ContainerSurvivors(vec![survivor
.id()
.unwrap()]))),
group_signals: Mutex::new(None),
resource: Resource::Group {
pgid,
created_start_time: Some(birth),
identity,
anchor_lost: std::sync::atomic::AtomicBool::new(true),
pin: Arc::new(Mutex::new(None)),
pending_pin: std::sync::atomic::AtomicBool::new(false),
},
end_log: Mutex::new(Some(ContainerEnd::default())),
roster: Mutex::new(None),
terminated: std::sync::atomic::AtomicBool::new(false),
ending: std::sync::atomic::AtomicBool::new(true),
admitting: std::sync::atomic::AtomicBool::new(false),
admission_changed: tokio::sync::Notify::new(),
cleanup_finished: tokio::sync::Notify::new(),
hard_killed: std::sync::atomic::AtomicBool::new(false),
kill_notify: tokio::sync::Notify::new(),
});
let guard = roster
.admit(
"retiring".into(),
pgid,
ModuleProtocol::Subc,
Some(birth),
RecordedIdentity {
container: Some(ContainerIdentity {
pgid: Some(pgid),
created_start_time: Some(birth),
..ContainerIdentity::test_metadata()
}),
carried: Some(Arc::downgrade(&container)),
..Default::default()
},
)
.unwrap();
*container.roster.lock().unwrap() = Some(guard);
command.process_group(0);
let mut other = command.spawn().unwrap();
let other_pid = other.id().unwrap();
let _other_guard = roster
.admit(
"other".into(),
other_pid,
ModuleProtocol::Subc,
Some(group_pin_birth(other_pid).unwrap()),
RecordedIdentity::default(),
)
.unwrap();
roster.hold_unrecorded_fence(
RecordedChild {
child: LiveChild {
module_id: "pending".into(),
pid: 42,
protocol: ModuleProtocol::Subc,
start_time: Some(123),
executable: None,
cgroup_name: None,
container: Some(ContainerIdentity {
pgid: Some(42),
created_start_time: Some(123),
..ContainerIdentity::test_metadata()
}),
},
resume_token_sha256: None,
},
Duration::from_millis(750),
);
let (entered, writing) = std::sync::mpsc::channel();
let (release, blocked) = std::sync::mpsc::channel();
let first_write = Mutex::new(Some((entered, blocked)));
roster.set_record_write_hook_for_test(move |_| {
if let Some((entered, blocked)) = first_write.lock().unwrap().take() {
entered.send(()).unwrap();
let _ = blocked.recv_timeout(Duration::from_secs(5));
}
});
let retaining = std::thread::spawn({
let container = Arc::clone(&container);
move || {
writing.recv_timeout(Duration::from_secs(5)).unwrap();
container.release_roster();
}
});
tokio::time::timeout(
Duration::from_secs(3),
crate::child_roster::end_children_for_daemon_shutdown(&roster, false, async {
while container
.cleanup_block
.try_lock()
.is_ok_and(|state| state.is_some())
{
sleep(Duration::from_millis(1)).await;
}
}),
)
.await
.expect("carried-container retain blocked shutdown behind the record write");
assert!(!retaining.is_finished(), "the retain must still be pending");
release
.send(())
.expect("the fence write must still be parked");
retaining.join().unwrap();
assert!(container
.hard_killed
.load(std::sync::atomic::Ordering::Acquire));
assert!(
other.try_wait().unwrap().is_some(),
"escalation must reach the other live child"
);
assert!(
survivor.try_wait().unwrap().is_none(),
"the unrecorded survivor must not be signalled"
);
let (_, reasons) = crate::live_children::read_record_with_reasons(&record).unwrap();
assert_eq!(
reasons.get(&pgid),
Some(&RetainedReason::ContainerSurvivors(vec![survivor
.id()
.unwrap()]))
);
survivor.kill().await.unwrap();
}
#[tokio::test]
#[allow(irrefutable_let_patterns)]
async fn lost_first_anchor_keeps_unrecorded_members_held_without_signalling() {
let mut leader_command = Command::new("/bin/sleep");
leader_command
.arg("600")
.process_group(0)
.kill_on_drop(true);
let leader = leader_command.spawn().unwrap();
let pgid = leader.id().unwrap();
let facts = subc_os::process_group::inspect(pgid).unwrap().unwrap();
let mut holder_command = Command::new("/bin/sleep");
holder_command
.arg("600")
.process_group(pgid as i32)
.kill_on_drop(true);
let mut holder = holder_command.spawn().unwrap();
let mut sentinel_command = Command::new("/bin/sleep");
sentinel_command
.arg("600")
.process_group(0)
.kill_on_drop(true);
let mut sentinel = sentinel_command.spawn().unwrap();
let group_signals = Arc::new(Mutex::new(Vec::new()));
let counters = crate::observability::DaemonCounters::default();
let container = Arc::new(CarriedContainment {
binding_retirement: Mutex::new(None),
module_id: "lost-anchor-fixture".into(),
counters: counters.clone(),
cleanup_block: Mutex::new(None),
group_signals: Mutex::new(Some(Arc::clone(&group_signals))),
resource: Resource::Group {
identity: LaunchIdentity::capture().unwrap(),
pgid,
created_start_time: Some(facts.start_time),
anchor_lost: std::sync::atomic::AtomicBool::new(false),
pin: Arc::new(Mutex::new(Some(Pin::Spawned(leader)))),
pending_pin: std::sync::atomic::AtomicBool::new(false),
},
end_log: Mutex::new(Some(ContainerEnd::default())),
roster: Mutex::new(None),
terminated: std::sync::atomic::AtomicBool::new(false),
ending: std::sync::atomic::AtomicBool::new(false),
admitting: std::sync::atomic::AtomicBool::new(false),
admission_changed: tokio::sync::Notify::new(),
cleanup_finished: tokio::sync::Notify::new(),
hard_killed: std::sync::atomic::AtomicBool::new(false),
kill_notify: tokio::sync::Notify::new(),
});
let mut observed = ProcessChild::Spawned(ProcessFields {
process: None,
plain_group: None,
container: Arc::downgrade(&container),
slot: Weak::new(),
pid: pgid,
observed: None,
settled: false,
});
if let Resource::Group { pin, .. } = &container.resource {
pin.lock().unwrap().as_mut().unwrap().start_kill().unwrap();
}
timeout(Duration::from_secs(2), async {
loop {
let reaped = if let Resource::Group { pin, .. } = &container.resource {
pin.lock()
.unwrap()
.as_mut()
.unwrap()
.try_wait()
.unwrap()
.is_some()
} else {
unreachable!()
};
if reaped {
break;
}
sleep(Duration::from_millis(1)).await;
}
})
.await
.unwrap();
assert_eq!(
observed.try_wait().unwrap_err().raw_os_error(),
Some(rustix::io::Errno::CHILD.raw_os_error())
);
container.hard_kill();
container.stop_members().await;
container.terminate().await;
assert!(
group_signals.lock().unwrap().is_empty(),
"an already-reaped P1 must never authorize a group-wide signal"
);
assert_eq!(counters.snapshot()["carried_containment_anchor_lost"], 1);
assert!(
holder.try_wait().unwrap().is_none(),
"losing the pin also loses signal authority over unrecorded members"
);
assert!(
sentinel.try_wait().unwrap().is_none(),
"a separate owned group is not part of the container"
);
sentinel.start_kill().unwrap();
sentinel.wait().await.unwrap();
holder.start_kill().unwrap();
holder.wait().await.unwrap();
observed.settled = true;
}
}
#[cfg(all(test, target_os = "linux"))]
mod cgroup_policy_tests {
use super::*;
use cortexkit_test_support::ScratchDir;
#[test]
fn carried_cgroup_preflight_normalizes_noncanonical_and_relative_roots_before_fork() {
let root = ScratchDir::new("carried-cgroup-path-preflight");
let canonical = std::fs::canonicalize(&*root).unwrap();
std::fs::write(canonical.join("cgroup.procs"), "").unwrap();
let dotted = PathBuf::from(format!("{}/.", canonical.display()));
let relative = std::env::current_dir().unwrap().join("target/scratch");
std::fs::create_dir_all(&relative).unwrap();
let child = relative.join(format!(
"carried-cgroup-relative-{}-{}",
std::process::id(),
unix_ms_now()
));
std::fs::create_dir(&child).unwrap();
std::fs::write(child.join("cgroup.procs"), "").unwrap();
let relative_name = child
.strip_prefix(std::env::current_dir().unwrap())
.unwrap();
for root in [&dotted, relative_name] {
let placement = subc_cgroup::prepare_at(root).unwrap().unwrap();
let path = prepare_cgroup_path(&placement, "preflight").unwrap();
assert!(path.is_absolute());
assert_eq!(path, std::fs::canonicalize(&path).unwrap());
assert_eq!(
placement.existing_module_path(&path).unwrap(),
Some(path.clone()),
"a path accepted before fork must already satisfy recovery/adoption validation"
);
std::fs::remove_dir(path).unwrap();
}
std::fs::remove_dir(child.join("subc-modules")).unwrap();
std::fs::remove_file(child.join("cgroup.procs")).unwrap();
std::fs::remove_dir(child).unwrap();
}
#[tokio::test]
async fn carried_cgroup_hard_kill_never_signals_a_process_group() {
let dir = ScratchDir::new("carried-cgroup-hard-kill-policy");
std::fs::write(dir.join("cgroup.procs"), "").unwrap();
let placement = subc_cgroup::prepare_at(&dir).unwrap().unwrap();
let path = placement.module_path("owned").unwrap();
std::fs::write(path.join("cgroup.kill"), "0").unwrap();
std::fs::write(path.join("cgroup.events"), "populated 1\n").unwrap();
std::fs::write(path.join("cgroup.procs"), "").unwrap();
let mut leader = Command::new("/bin/sleep");
leader.arg("600").process_group(0).kill_on_drop(true);
let mut leader = leader.spawn().unwrap();
let signals = Arc::new(Mutex::new(Vec::new()));
let container = Arc::new(CarriedContainment {
binding_retirement: Mutex::new(None),
module_id: "carried-cgroup-policy".into(),
resource: Resource::Cgroup {
identity: LaunchIdentity::capture().unwrap(),
placement,
name: "owned".into(),
path: path.clone(),
},
counters: crate::observability::DaemonCounters::default(),
cleanup_block: Mutex::new(None),
group_signals: Mutex::new(Some(Arc::clone(&signals))),
end_log: Mutex::new(Some(ContainerEnd::default())),
roster: Mutex::new(None),
terminated: std::sync::atomic::AtomicBool::new(false),
ending: std::sync::atomic::AtomicBool::new(false),
admitting: std::sync::atomic::AtomicBool::new(false),
admission_changed: tokio::sync::Notify::new(),
cleanup_finished: tokio::sync::Notify::new(),
hard_killed: std::sync::atomic::AtomicBool::new(false),
kill_notify: tokio::sync::Notify::new(),
});
assert_eq!(container.group(), None, "a cgroup has no reserved PGID");
assert!(!container.signal_pinned_group(rustix::process::Signal::KILL));
container.hard_kill();
assert_eq!(
std::fs::read(path.join("cgroup.kill")).unwrap(),
b"1",
"cgroup cleanup must use the trusted kernel interface, never substitute killpg"
);
assert!(signals.lock().unwrap().is_empty());
assert!(
leader.try_wait().unwrap().is_none(),
"a separate process group is not a cgroup member"
);
container.hard_kill();
leader.start_kill().unwrap();
leader.wait().await.unwrap();
}
}