mod system;
use crate::disk::{AnyDiskReader, DiskPressure, DiskThresholds, DiskWatch};
use crate::runaway::RunawayGuard;
use std::fmt;
use std::time::Duration;
use aither_sandbox::{ForegroundWait, JobFootprint, MemoryDomain, MemorySize};
use askama::Template;
use async_channel::{Receiver, Sender};
use crate::clock::{AnyClock, Instant};
pub use system::{SystemReader, psi_memory_pressure};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
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")
}
}
#[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,
) -> Receiver<HostLoadEvent>
where
R: HostReader,
E: executor_core::Executor,
{
use executor_core::Task;
let (sender, receiver) = async_channel::unbounded();
executor.spawn(run(monitor, guard, clock, sender)).detach();
receiver
}
async fn run<R: HostReader>(
mut monitor: HostLoadMonitor<R>,
mut guard: Option<RunawayGuard>,
clock: AnyClock,
events: Sender<HostLoadEvent>,
) {
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");
if events.send(event).await.is_err() {
return;
}
}
async_io::Timer::after(interval).await;
}
}
#[cfg(test)]
mod tests;