subc-daemon 0.44.2

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
//! A supervised child's memory and CPU time, read when `supervisor.list` is
//! answered. Report only: nothing here is sampled on a timer, kept, or acted
//! on. The OS reads live in `subc-os`, the one crate allowed the unsafe calls
//! macOS needs.

use subc_control::{
    ChildMemoryKind, ChildResourceReading, ChildResourceUnavailableReason, ChildResourceUsage,
};

/// The daemon must never include its reaped module children's CPU.
pub(crate) fn read_own(pid: u32) -> ChildResourceUsage {
    match subc_os::resource_usage(pid) {
        Some(usage) => ChildResourceUsage::Measured(reading(usage)),
        None => ChildResourceUsage::Unavailable {
            reason: ChildResourceUnavailableReason::Unreadable,
        },
    }
}

/// The resources of the process the supervisor spawned as `pid`.
///
/// `expected_start_time` is the kernel start time recorded at spawn, where the
/// platform provides one (Linux). When it is known, the pid is re-checked
/// after the read, so a reading taken after the child exited and its pid was
/// handed to another process is refused rather than reported as the module's.
/// Without it (macOS) the reading relies on the pid still naming the child,
/// which holds until the supervisor reaps it and the pid space wraps.
#[cfg(any(not(windows), test))]
pub(crate) fn read(pid: Option<u32>, expected_start_time: Option<u64>) -> ChildResourceUsage {
    #[cfg(windows)]
    {
        let Some(pid) = pid else {
            return ChildResourceUsage::Unavailable {
                reason: ChildResourceUnavailableReason::NotRunning,
            };
        };
        let Some(expected) = expected_start_time else {
            return ChildResourceUsage::Unavailable {
                reason: ChildResourceUnavailableReason::ProcessIdentityUnconfirmed,
            };
        };
        let Ok(Some(process)) = subc_os::Process::open(pid) else {
            return ChildResourceUsage::Unavailable {
                reason: ChildResourceUnavailableReason::Unreadable,
            };
        };
        read_windows_handle(&process, expected)
    }
    #[cfg(not(windows))]
    read_with(pid, expected_start_time, subc_os::resource_usage, |pid| {
        crate::provenance::process_start_time(pid)
    })
}

#[cfg(windows)]
pub(crate) fn read_windows_handle(process: &subc_os::Process, expected: u64) -> ChildResourceUsage {
    if !matches!(process.observe(), Some(observed) if observed.start_time == expected) {
        return ChildResourceUsage::Unavailable {
            reason: ChildResourceUnavailableReason::ProcessIdentityUnconfirmed,
        };
    }
    match process.resource_usage() {
        Some(usage) => ChildResourceUsage::Measured(reading(usage)),
        None => ChildResourceUsage::Unavailable {
            reason: ChildResourceUnavailableReason::Unreadable,
        },
    }
}

#[cfg(any(not(windows), test))]
fn read_with(
    pid: Option<u32>,
    expected_start_time: Option<u64>,
    resource_usage: impl FnOnce(u32) -> Option<subc_os::ResourceUsage>,
    start_time: impl FnOnce(u32) -> Option<u64>,
) -> ChildResourceUsage {
    let unavailable = |reason| ChildResourceUsage::Unavailable { reason };
    let Some(pid) = pid else {
        return unavailable(ChildResourceUnavailableReason::NotRunning);
    };
    if !subc_os::RESOURCE_USAGE_SUPPORTED {
        return unavailable(ChildResourceUnavailableReason::UnsupportedPlatform);
    }
    let Some(usage) = resource_usage(pid) else {
        return unavailable(ChildResourceUnavailableReason::Unreadable);
    };
    if let Some(expected) = expected_start_time {
        if start_time(pid) != Some(expected) {
            return unavailable(ChildResourceUnavailableReason::ProcessIdentityUnconfirmed);
        }
    }
    ChildResourceUsage::Measured(reading(usage))
}

fn reading(usage: subc_os::ResourceUsage) -> ChildResourceReading {
    let millis =
        |duration: std::time::Duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX);
    ChildResourceReading::new(
        usage.memory_bytes,
        match usage.memory_kind {
            subc_os::MemoryKind::PhysFootprint => ChildMemoryKind::PhysFootprint,
            subc_os::MemoryKind::ResidentSet => ChildMemoryKind::ResidentSet,
            subc_os::MemoryKind::WindowsWorkingSet => ChildMemoryKind::WindowsWorkingSet,
        },
        millis(usage.cpu_user),
        millis(usage.cpu_system),
    )
    .with_swap_bytes(usage.swap_bytes)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(unix)]
    #[test]
    fn own_reader_does_not_charge_a_reaped_cpu_burning_child() {
        let result = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "child_resources::tests::own_reader_fixture",
                "--nocapture",
            ])
            .env("RESOURCE_OWN_FIXTURE", "parent")
            .output()
            .unwrap();
        assert!(
            result.status.success(),
            "isolated own-resource fixture: {}",
            String::from_utf8_lossy(&result.stderr)
        );
    }

    #[cfg(unix)]
    #[test]
    fn own_reader_fixture() {
        let Ok(mode) = std::env::var("RESOURCE_OWN_FIXTURE") else {
            return;
        };
        let pid = std::process::id();
        if mode == "burn" {
            let start = subc_os::resource_usage(pid).unwrap();
            let before = (start.cpu_user + start.cpu_system).as_millis();
            loop {
                for n in 0..100_000_u64 {
                    std::hint::black_box(n.wrapping_mul(97));
                }
                let now = subc_os::resource_usage(pid).unwrap();
                if (now.cpu_user + now.cpu_system).as_millis() >= before + 400 {
                    break;
                }
            }
            return;
        }
        let own = |reading| match reading {
            ChildResourceUsage::Measured(reading) => reading.cpu_user_ms + reading.cpu_system_ms,
            other => panic!("own reading unavailable: {other:?}"),
        };
        let before = own(read_own(pid));
        let child = std::process::Command::new(std::env::current_exe().unwrap())
            .args(["--exact", "child_resources::tests::own_reader_fixture"])
            .env("RESOURCE_OWN_FIXTURE", "burn")
            .output()
            .unwrap();
        assert!(child.status.success());
        let after = own(read_own(pid));
        let table = subc_os::ProcessTable::read().unwrap();
        assert!(table.process(pid).unwrap().reaped_cpu_ms.unwrap() >= 400);
        assert!(
            after.saturating_sub(before) < 400,
            "reaped child CPU was charged to the daemon"
        );
    }

    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
    fn usage() -> subc_os::ResourceUsage {
        use std::time::Duration;

        subc_os::ResourceUsage {
            memory_bytes: 7 * 1024 * 1024,
            memory_kind: subc_os::MemoryKind::ResidentSet,
            swap_bytes: Some(4096),
            cpu_user: Duration::from_millis(1_250),
            cpu_system: Duration::from_micros(310_900),
        }
    }

    #[test]
    fn no_pid_reads_as_not_running() {
        assert_eq!(
            read(None, None),
            ChildResourceUsage::Unavailable {
                reason: ChildResourceUnavailableReason::NotRunning
            }
        );
    }

    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
    #[test]
    fn a_failed_read_is_unreadable_not_zero() {
        assert_eq!(
            read_with(Some(42), None, |_| None, |_| None),
            ChildResourceUsage::Unavailable {
                reason: ChildResourceUnavailableReason::Unreadable
            }
        );
    }

    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
    #[test]
    fn a_pid_now_naming_another_process_is_refused() {
        assert_eq!(
            read_with(Some(42), Some(100), |_| Some(usage()), |_| Some(101)),
            ChildResourceUsage::Unavailable {
                reason: ChildResourceUnavailableReason::ProcessIdentityUnconfirmed
            }
        );
    }

    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
    #[test]
    fn a_confirmed_read_is_reported_in_wire_units() {
        let actual = read_with(Some(42), Some(100), |_| Some(usage()), |_| Some(100));
        assert_eq!(
            serde_json::to_string(&actual).unwrap(),
            r#"{"status":"measured","memory_bytes":7340032,"memory_kind":"resident_set","swap_bytes":4096,"cpu_user_ms":1250,"cpu_system_ms":310}"#
        );
        assert_eq!(
            actual,
            ChildResourceUsage::Measured(
                ChildResourceReading::new(
                    7 * 1024 * 1024,
                    ChildMemoryKind::ResidentSet,
                    1_250,
                    310
                )
                .with_swap_bytes(Some(4096))
            )
        );
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
    #[test]
    fn an_unsupported_platform_says_so() {
        assert_eq!(
            read(Some(std::process::id()), None),
            ChildResourceUsage::Unavailable {
                reason: ChildResourceUnavailableReason::UnsupportedPlatform
            }
        );
    }

    /// The daemon's own process stands in for a child: the read goes through
    /// the real platform source, not a stub.
    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
    #[test]
    fn a_live_process_is_measured() {
        let pid = std::process::id();
        let start_time = crate::provenance::process_start_time(pid);
        match read(Some(pid), start_time) {
            ChildResourceUsage::Measured(reading) => assert!(reading.memory_bytes > 0),
            other => panic!("own process was not measured: {other:?}"),
        }
    }
}