mod system;
use crate::disk::{AnyDiskReader, DiskPressure, DiskThresholds, DiskWatch};
use crate::runaway::RunawayGuard;
use std::collections::HashMap;
use std::fmt;
use std::time::Duration;
use aither_sandbox::{ForegroundWait, JobFootprint, MemoryDomain, MemorySize};
use askama::Template;
use async_channel::{Receiver, Sender};
use serde::{Deserialize, Serialize};
use crate::clock::{AnyClock, Instant};
pub use system::{SystemReader, psi_memory_pressure};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum MemoryPressure {
Normal,
Warning,
Critical,
}
impl fmt::Display for MemoryPressure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Normal => "normal",
Self::Warning => "warning",
Self::Critical => "critical",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct MachineLoad(pub f64);
impl MachineLoad {
#[must_use]
pub fn percent(self) -> u64 {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let percent = (self.0 * 100.0).round().max(0.0) as u64;
percent
}
}
#[derive(Debug, thiserror::Error)]
pub enum ReadError {
#[error("reading {what} failed: {source}")]
Io {
what: &'static str,
source: std::io::Error,
},
#[error("{what} answered `{content}`, which is not understood")]
Malformed {
what: &'static str,
content: String,
},
#[error("{what} is not available on this host")]
Unsupported {
what: &'static str,
},
#[error(transparent)]
Container(#[from] aither_sandbox::ContainerProbeError),
}
pub trait HostReader: Send + 'static {
fn memory_pressure(&mut self) -> Result<MemoryPressure, ReadError>;
fn machine_load(&mut self) -> Result<MachineLoad, ReadError>;
}
fn log_failed_read(error: &ReadError, what: &str) {
if matches!(error, ReadError::Unsupported { .. }) {
tracing::trace!(%error, "{what} is not available on this host");
} else {
tracing::warn!(%error, "{what} could not be read");
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct UnwatchedHost;
impl HostReader for UnwatchedHost {
fn memory_pressure(&mut self) -> Result<MemoryPressure, ReadError> {
Err(ReadError::Unsupported {
what: "host memory pressure",
})
}
fn machine_load(&mut self) -> Result<MachineLoad, ReadError> {
Err(ReadError::Unsupported {
what: "host machine load",
})
}
}
pub struct AnyHostReader(Box<dyn HostReader>);
impl AnyHostReader {
#[must_use]
pub fn new(reader: impl HostReader) -> Self {
Self(Box::new(reader))
}
}
impl HostReader for AnyHostReader {
fn memory_pressure(&mut self) -> Result<MemoryPressure, ReadError> {
self.0.memory_pressure()
}
fn machine_load(&mut self) -> Result<MachineLoad, ReadError> {
self.0.machine_load()
}
}
impl fmt::Debug for AnyHostReader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AnyHostReader")
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct HostLoadConfig {
pub load_threshold: MachineLoad,
pub start_after: Duration,
pub end_after: Duration,
pub poll_interval: Duration,
pub high_load_foreground_wait: Duration,
}
impl HostLoadConfig {
#[must_use]
pub const fn new() -> Self {
Self {
load_threshold: MachineLoad(SystemReader::DEFAULT_LOAD_THRESHOLD),
start_after: Duration::from_secs(30),
end_after: Duration::from_secs(60),
poll_interval: Duration::from_secs(5),
high_load_foreground_wait: Duration::from_secs(60),
}
}
#[must_use]
pub const fn load_threshold(mut self, threshold: MachineLoad) -> Self {
self.load_threshold = threshold;
self
}
#[must_use]
pub const fn start_after(mut self, window: Duration) -> Self {
self.start_after = window;
self
}
#[must_use]
pub const fn end_after(mut self, window: Duration) -> Self {
self.end_after = window;
self
}
#[must_use]
pub const fn poll_interval(mut self, interval: Duration) -> Self {
self.poll_interval = interval;
self
}
#[must_use]
pub const fn high_load_foreground_wait(mut self, window: Duration) -> Self {
self.high_load_foreground_wait = window;
self
}
}
impl Default for HostLoadConfig {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum HostLoadEvent {
LoadHigh {
load: MachineLoad,
foreground_wait: Duration,
},
LoadEnded {
load: MachineLoad,
foreground_wait: Duration,
},
MemoryYellow {
domain: MemoryDomain,
jobs: Vec<JobFootprint>,
},
MemoryRed {
domain: MemoryDomain,
jobs: Vec<JobFootprint>,
},
MemoryFinalWarning {
domain: MemoryDomain,
job: JobFootprint,
window: Duration,
capacity: MemorySize,
},
MemoryDroppedBack {
domain: MemoryDomain,
level: MemoryPressure,
jobs: Vec<JobFootprint>,
},
JobKilledForMemory {
domain: MemoryDomain,
task_id: String,
command: String,
footprint: MemorySize,
capacity: MemorySize,
},
DiskPressureRose {
volume: String,
level: DiskPressure,
free: MemorySize,
},
DiskPressureDroppedBack {
volume: String,
level: DiskPressure,
free: MemorySize,
},
}
#[derive(Template)]
#[template(path = "host_load_alert.txt", escape = "none")]
struct HostLoadAlert<'a> {
event: &'a HostLoadEvent,
}
impl HostLoadEvent {
pub(crate) fn alert_text(&self) -> String {
HostLoadAlert { event: self }
.render()
.expect("host load alert template must render")
}
pub(crate) fn condition(&self) -> Option<(HostCondition, HostLevel)> {
match self {
Self::LoadHigh { .. } => Some((HostCondition::Load, HostLevel::Load { high: true })),
Self::LoadEnded { .. } => Some((HostCondition::Load, HostLevel::Load { high: false })),
Self::MemoryYellow { domain, .. } => Some((
HostCondition::Memory(*domain),
HostLevel::Memory(MemoryPressure::Warning),
)),
Self::MemoryRed { domain, .. } => Some((
HostCondition::Memory(*domain),
HostLevel::Memory(MemoryPressure::Critical),
)),
Self::MemoryDroppedBack { domain, level, .. } => {
Some((HostCondition::Memory(*domain), HostLevel::Memory(*level)))
}
Self::DiskPressureRose { volume, level, .. }
| Self::DiskPressureDroppedBack { volume, level, .. } => {
Some((HostCondition::Disk(volume.clone()), HostLevel::Disk(*level)))
}
Self::MemoryFinalWarning { .. } | Self::JobKilledForMemory { .. } => None,
}
}
pub(crate) fn for_change(
condition: &HostCondition,
seen: Option<HostLevel>,
now: HostLevel,
reading: &Self,
) -> Self {
match (condition, now) {
(_, HostLevel::Load { high }) => {
let (Self::LoadHigh {
load,
foreground_wait,
}
| Self::LoadEnded {
load,
foreground_wait,
}) = *reading
else {
unreachable!("a load level comes from a load event")
};
if high {
Self::LoadHigh {
load,
foreground_wait,
}
} else {
Self::LoadEnded {
load,
foreground_wait,
}
}
}
(HostCondition::Memory(domain), HostLevel::Memory(level)) => {
let (Self::MemoryYellow { jobs, .. }
| Self::MemoryRed { jobs, .. }
| Self::MemoryDroppedBack { jobs, .. }) = reading
else {
unreachable!("a memory level comes from a memory event")
};
let domain = *domain;
let jobs = jobs.clone();
match level {
MemoryPressure::Normal => Self::MemoryDroppedBack {
domain,
level,
jobs,
},
MemoryPressure::Warning
if seen == Some(HostLevel::Memory(MemoryPressure::Critical)) =>
{
Self::MemoryDroppedBack {
domain,
level,
jobs,
}
}
MemoryPressure::Warning => Self::MemoryYellow { domain, jobs },
MemoryPressure::Critical => Self::MemoryRed { domain, jobs },
}
}
(HostCondition::Disk(volume), HostLevel::Disk(level)) => {
let (Self::DiskPressureRose { free, .. }
| Self::DiskPressureDroppedBack { free, .. }) = *reading
else {
unreachable!("a disk level comes from a disk event")
};
let volume = volume.clone();
let fell = matches!(seen, Some(HostLevel::Disk(before)) if before > level);
if fell || level == DiskPressure::Normal {
Self::DiskPressureDroppedBack {
volume,
level,
free,
}
} else {
Self::DiskPressureRose {
volume,
level,
free,
}
}
}
_ => unreachable!("a condition and its level are of one kind"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HostCondition {
Load,
Memory(MemoryDomain),
Disk(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum HostLevel {
Load {
high: bool,
},
Memory(MemoryPressure),
Disk(DiskPressure),
}
impl HostLevel {
const fn is_normal(self) -> bool {
matches!(
self,
Self::Load { high: false }
| Self::Memory(MemoryPressure::Normal)
| Self::Disk(DiskPressure::Normal)
)
}
}
#[derive(Debug, Clone)]
pub struct HostLoadSenders {
conditions: Sender<HostLoadEvent>,
events: Sender<HostLoadEvent>,
}
impl HostLoadSenders {
pub async fn send(&self, event: HostLoadEvent) {
let channel = if event.condition().is_some() {
&self.conditions
} else {
&self.events
};
channel.send(event).await.ok();
}
fn is_closed(&self) -> bool {
self.conditions.is_closed() && self.events.is_closed()
}
}
#[derive(Debug)]
pub struct HostLoadChannels {
conditions: Receiver<HostLoadEvent>,
events: Receiver<HostLoadEvent>,
}
impl HostLoadChannels {
pub fn register(
self,
notices: &crate::AnyNotices,
states: &mut Vec<crate::context::AnyStateSource>,
events: &mut Vec<crate::context::AnyEventSource>,
) {
states.insert(
0,
crate::context::AnyStateSource::new(HostConditions {
receiver: self.conditions,
readings: HashMap::new(),
notices: notices.clone(),
}),
);
events.insert(
0,
crate::context::AnyEventSource::new(HostEvents {
receiver: self.events,
notices: notices.clone(),
}),
);
}
}
pub fn channels() -> (HostLoadSenders, HostLoadChannels) {
let (conditions, condition_receiver) = async_channel::unbounded();
let (events, event_receiver) = async_channel::unbounded();
(
HostLoadSenders { conditions, events },
HostLoadChannels {
conditions: condition_receiver,
events: event_receiver,
},
)
}
pub struct HostConditions {
receiver: Receiver<HostLoadEvent>,
readings: HashMap<HostCondition, HostLoadEvent>,
notices: crate::AnyNotices,
}
impl crate::context::StateSource for HostConditions {
const ID: &'static str = "host_conditions";
type Key = HostCondition;
type Value = HostLevel;
fn poll(&mut self) -> impl Future<Output = Vec<(HostCondition, HostLevel)>> + Send {
let mut changed = Vec::new();
while let Ok(event) = self.receiver.try_recv() {
let (condition, level) = event
.condition()
.expect("the monitor sends only conditions to the state channel");
changed.push((condition.clone(), level));
self.readings.insert(condition, event);
}
std::future::ready(changed)
}
fn is_normal(&self, _: &HostCondition, level: &HostLevel) -> bool {
level.is_normal()
}
fn announce(
&self,
change: &crate::context::StateChange<'_, HostCondition, HostLevel>,
) -> crate::context::Block {
let reading = self
.readings
.get(change.key())
.expect("a condition with a level has the event that set it");
crate::context::Block::new(
"system-reminder",
self.notices.host_condition(
change.key(),
change.seen().copied(),
*change.now(),
reading,
),
)
}
}
pub struct HostEvents {
receiver: Receiver<HostLoadEvent>,
notices: crate::AnyNotices,
}
impl crate::context::EventSource for HostEvents {
type Event = HostLoadEvent;
fn take(&mut self) -> impl Future<Output = Vec<HostLoadEvent>> + Send {
std::future::ready(std::iter::from_fn(|| self.receiver.try_recv().ok()).collect())
}
fn announce(&self, event: &HostLoadEvent) -> crate::context::Block {
crate::context::Block::new("system-reminder", self.notices.host_load(event))
}
}
#[derive(Debug, Default)]
struct Condition {
active: bool,
contrary_since: Option<Instant>,
}
#[derive(Debug, PartialEq, Eq)]
enum Transition {
Started,
Ended,
}
impl Condition {
fn observe(
&mut self,
now: Instant,
high: bool,
start_after: Duration,
end_after: Duration,
) -> Option<Transition> {
if high == self.active {
self.contrary_since = None;
return None;
}
let since = *self.contrary_since.get_or_insert(now);
let window = if self.active { end_after } else { start_after };
if now.duration_since(since) < window {
return None;
}
self.contrary_since = None;
self.active = high;
Some(if high {
Transition::Started
} else {
Transition::Ended
})
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HostSample {
memory: Option<MemoryPressure>,
load: Option<MachineLoad>,
}
impl HostSample {
#[must_use]
pub const fn new(memory: Option<MemoryPressure>, load: Option<MachineLoad>) -> Self {
Self { memory, load }
}
}
#[derive(Debug)]
pub struct HostLoadMonitor<R> {
reader: R,
config: HostLoadConfig,
foreground_wait: ForegroundWait,
load: Condition,
disk: Option<DiskWatch>,
}
impl<R: HostReader> HostLoadMonitor<R> {
#[must_use]
pub fn with_disk(
mut self,
thresholds: DiskThresholds,
readers: impl IntoIterator<Item = AnyDiskReader>,
) -> Self {
self.disk = Some(DiskWatch::new(thresholds, readers));
self
}
pub fn read_disks(&self) -> impl Future<Output = Vec<Option<u64>>> + Send + use<R> {
let readers = self.disk.as_ref().map(DiskWatch::readers);
async move { crate::disk::read_free_bytes(readers.unwrap_or_default()).await }
}
pub fn observe_disks(&mut self, free: &[Option<u64>]) -> Vec<HostLoadEvent> {
self.disk
.as_mut()
.map_or_else(Vec::new, |disk| disk.observe(free))
}
#[must_use]
pub fn new(reader: R, config: HostLoadConfig, foreground_wait: ForegroundWait) -> Self {
Self {
reader,
config,
foreground_wait,
load: Condition::default(),
disk: None,
}
}
pub fn read(&mut self) -> HostSample {
let memory = self
.reader
.memory_pressure()
.inspect_err(|error| log_failed_read(error, "memory pressure"))
.ok();
let load = self
.reader
.machine_load()
.inspect_err(|error| log_failed_read(error, "machine load"))
.ok();
HostSample { memory, load }
}
pub fn observe(&mut self, now: Instant, sample: HostSample) -> Vec<HostLoadEvent> {
let config = &self.config;
let mut events = Vec::new();
if let Some(load) = sample.load {
let high = load >= config.load_threshold;
match self
.load
.observe(now, high, config.start_after, config.end_after)
{
Some(Transition::Started) => {
let window = config.high_load_foreground_wait;
self.foreground_wait.extend(window);
events.push(HostLoadEvent::LoadHigh {
load,
foreground_wait: window,
});
}
Some(Transition::Ended) => {
self.foreground_wait.restore();
events.push(HostLoadEvent::LoadEnded {
load,
foreground_wait: self.foreground_wait.normal(),
});
}
None => {}
}
}
events
}
pub fn tick(&mut self, clock: &AnyClock) -> Vec<HostLoadEvent> {
let sample = self.read();
self.observe(clock.now(), sample)
}
}
pub fn spawn<R, E>(
executor: &E,
monitor: HostLoadMonitor<R>,
guard: Option<RunawayGuard>,
clock: AnyClock,
) -> HostLoadChannels
where
R: HostReader,
E: executor_core::Executor,
{
use executor_core::Task;
let (senders, channels) = channels();
executor.spawn(run(monitor, guard, clock, senders)).detach();
channels
}
async fn run<R: HostReader>(
mut monitor: HostLoadMonitor<R>,
mut guard: Option<RunawayGuard>,
clock: AnyClock,
events: HostLoadSenders,
) {
let interval = monitor.config.poll_interval;
while !events.is_closed() {
let (back, sample) = blocking::unblock(move || {
let sample = monitor.read();
(monitor, sample)
})
.await;
monitor = back;
let now = clock.now();
let mut raised = monitor.observe(now, sample);
let (disks, guarded) = futures::join!(monitor.read_disks(), async {
match guard.as_mut() {
Some(guard) => guard.observe(now, sample.memory).await,
None => Vec::new(),
}
});
raised.extend(guarded);
raised.extend(monitor.observe_disks(&disks));
for event in raised {
tracing::info!(?event, "host load condition changed");
events.send(event).await;
}
async_io::Timer::after(interval).await;
}
}
#[cfg(test)]
mod tests;