Skip to main content

schedr_bin/
ops.rs

1//! The ops port of every role (see archive/PROJECT.md, Observability): plain HTTP on `[ops] bind` :
2//! `port` with only `/healthz`, `/readyz` and `/metrics`, never data or actions, so probes and
3//! Prometheus need no certificate or credentials. It is started first, so `/readyz` answers
4//! while a role starts.
5//!
6//! - **`/healthz`** (liveness): 503 once a loop the role watches (the master's scheduling
7//!   loop, the worker agent's event loop) hasn't turned for `loop_stall_timeout`; it
8//!   never asks another component (a database or master outage mustn't restart the role).
9//! - **`/readyz`**: 503 until every part of the role has started.
10//! - **`/metrics`**: the role's metrics (`schedr_…`), its process's (`process_…`, from
11//!   `/proc/self`) and `schedr_build_info`, in the `OpenMetrics` text format. A scrape reads
12//!   them only: nothing touches the database.
13
14use std::sync::atomic::{AtomicBool, Ordering};
15use std::sync::{Arc, Mutex, PoisonError};
16use std::time::{Duration, Instant};
17
18use axum::Router;
19use axum::extract::State;
20use axum::http::{StatusCode, header};
21use axum::response::IntoResponse;
22use axum::routing::get;
23use prometheus_client::collector::Collector;
24use prometheus_client::encoding::{DescriptorEncoder, EncodeMetric};
25use prometheus_client::metrics::counter::ConstCounter;
26use prometheus_client::metrics::gauge::ConstGauge;
27use prometheus_client::metrics::info::Info;
28use prometheus_client::registry::Registry;
29use schedr_model::beat::Beat;
30use schedr_model::metric_doc::{MetricDoc, MetricKind};
31use tokio::net::TcpListener;
32use tokio::sync::watch;
33
34use crate::VERSION;
35use crate::app::AppError;
36use crate::roles::until;
37
38#[cfg(test)]
39mod tests;
40
41/// The content type of `/metrics`.
42pub const METRICS_CONTENT_TYPE: &str = "application/openmetrics-text; version=1.0.0; charset=utf-8";
43
44const RESIDENT_MEMORY: MetricDoc = MetricDoc {
45    name: "process_resident_memory_bytes",
46    kind: MetricKind::Gauge,
47    labels: &[],
48    help: "Resident memory of this process",
49};
50const CPU: MetricDoc = MetricDoc {
51    name: "process_cpu_seconds",
52    kind: MetricKind::Counter,
53    labels: &[],
54    help: "CPU time this process used, user and system",
55};
56const OPEN_FDS: MetricDoc = MetricDoc {
57    name: "process_open_fds",
58    kind: MetricKind::Gauge,
59    labels: &[],
60    help: "File descriptors this process has open",
61};
62const START_TIME: MetricDoc = MetricDoc {
63    name: "process_start_time_seconds",
64    kind: MetricKind::Gauge,
65    labels: &[],
66    help: "When this process started, in seconds since the Unix epoch",
67};
68const BUILD: MetricDoc = MetricDoc {
69    name: "schedr_build",
70    kind: MetricKind::Info,
71    labels: &["version"],
72    help: "The schedr version running",
73};
74
75/// The metrics every role serves besides its own, as registered (without a prefix): the
76/// process's and the build's.
77pub const PROCESS_METRICS: &[MetricDoc] = &[RESIDENT_MEMORY, CPU, OPEN_FDS, START_TIME, BUILD];
78
79/// What the health endpoints check (cheap to clone; clones share it).
80#[derive(Debug, Clone)]
81pub struct Health {
82    inner: Arc<Mutex<Checks>>,
83}
84
85#[derive(Debug)]
86struct Checks {
87    stall: Duration,
88    loops: Vec<(&'static str, Beat)>,
89    parts: Vec<(&'static str, Arc<AtomicBool>)>,
90}
91
92/// A part of a role that is starting; ready once told (and not ready again when told, as a
93/// master that isn't leading, B165).
94#[derive(Debug, Clone)]
95pub struct Starting(Arc<AtomicBool>);
96
97impl Starting {
98    /// The part has started.
99    pub fn ready(&self) {
100        self.0.store(true, Ordering::Relaxed);
101    }
102
103    /// The part is ready, or not any more.
104    pub fn set(&self, ready: bool) {
105        self.0.store(ready, Ordering::Relaxed);
106    }
107}
108
109impl Health {
110    /// Health with loops failing liveness after `stall` without turning.
111    #[must_use]
112    pub fn new(stall: Duration) -> Self {
113        Self {
114            inner: Arc::new(Mutex::new(Checks {
115                stall,
116                loops: Vec::new(),
117                parts: Vec::new(),
118            })),
119        }
120    }
121
122    fn checks(&self) -> std::sync::MutexGuard<'_, Checks> {
123        self.inner.lock().unwrap_or_else(PoisonError::into_inner)
124    }
125
126    /// How long a loop may go without turning.
127    #[must_use]
128    pub fn stall(&self) -> Duration {
129        self.checks().stall
130    }
131
132    /// Liveness watches the loop `name` through `beat` (a loop that hasn't turned yet is
133    /// starting, so alive).
134    pub fn watch_loop(&self, name: &'static str, beat: Beat) {
135        self.checks().loops.push((name, beat));
136    }
137
138    /// Readiness waits for the part `name` until it says it is ready.
139    #[must_use]
140    pub fn starting(&self, name: &'static str) -> Starting {
141        let flag = Arc::new(AtomicBool::new(false));
142        self.checks().parts.push((name, flag.clone()));
143        Starting(flag)
144    }
145
146    /// Why the role isn't alive at `now`, if it isn't.
147    #[must_use]
148    pub fn stalled(&self, now: Instant) -> Option<String> {
149        let checks = self.checks();
150        checks.loops.iter().find_map(|(name, beat)| {
151            let since = beat.since(now)?;
152            (since > checks.stall).then(|| {
153                format!(
154                    "the {name} hasn't turned for {} s (limit {} s)",
155                    since.as_secs(),
156                    checks.stall.as_secs()
157                )
158            })
159        })
160    }
161
162    /// The parts still starting.
163    #[must_use]
164    pub fn not_ready(&self) -> Vec<&'static str> {
165        self.checks()
166            .parts
167            .iter()
168            .filter(|(_, ready)| !ready.load(Ordering::Relaxed))
169            .map(|(name, _)| *name)
170            .collect()
171    }
172}
173
174/// What the ops endpoints serve.
175#[derive(Debug, Clone)]
176pub struct Ops {
177    registry: Arc<Registry>,
178    health: Health,
179}
180
181impl Ops {
182    /// The ops endpoints over `registry` (complete: nothing is registered later) and
183    /// `health`; the process's metrics and the build's are added to the registry.
184    #[must_use]
185    pub fn new(mut registry: Registry, health: Health) -> Self {
186        registry.register_collector(Box::new(ProcessMetrics));
187        registry.register(
188            BUILD.name,
189            BUILD.help,
190            Info::new(vec![("version".to_owned(), VERSION.to_owned())]),
191        );
192        Self {
193            registry: Arc::new(registry),
194            health,
195        }
196    }
197
198    /// The registry's text, as `/metrics` serves it.
199    #[must_use]
200    pub fn metrics_text(&self) -> String {
201        let mut text = String::new();
202        // Writing into a String can't fail.
203        let _ = prometheus_client::encoding::text::encode(&mut text, &self.registry);
204        text
205    }
206}
207
208/// The ops routes.
209pub fn router(ops: Ops) -> Router {
210    Router::new()
211        .route("/healthz", get(healthz))
212        .route("/readyz", get(readyz))
213        .route("/metrics", get(metrics))
214        .with_state(ops)
215}
216
217async fn healthz(State(ops): State<Ops>) -> impl IntoResponse {
218    match ops.health.stalled(Instant::now()) {
219        None => (StatusCode::OK, "ok\n".to_owned()),
220        Some(why) => (StatusCode::SERVICE_UNAVAILABLE, format!("{why}\n")),
221    }
222}
223
224async fn readyz(State(ops): State<Ops>) -> impl IntoResponse {
225    let starting = ops.health.not_ready();
226    if starting.is_empty() {
227        (StatusCode::OK, "ok\n".to_owned())
228    } else {
229        (
230            StatusCode::SERVICE_UNAVAILABLE,
231            format!("starting: {}\n", starting.join(", ")),
232        )
233    }
234}
235
236async fn metrics(State(ops): State<Ops>) -> impl IntoResponse {
237    (
238        [(header::CONTENT_TYPE, METRICS_CONTENT_TYPE)],
239        ops.metrics_text(),
240    )
241}
242
243/// Serves the ops endpoints on `listener` until `stop`.
244///
245/// # Errors
246///
247/// [`AppError::BadArgument`] if the HTTP server fails.
248pub async fn serve_ops(
249    listener: TcpListener,
250    ops: Ops,
251    stop: watch::Receiver<u32>,
252) -> Result<(), AppError> {
253    axum::serve(listener, router(ops))
254        .with_graceful_shutdown(until(stop))
255        .await
256        .map_err(|e| AppError::BadArgument(format!("ops server: {e}")))
257}
258
259/// The process's own metrics, read from `/proc/self` at each scrape (absent without
260/// `/proc`).
261#[derive(Debug, Default)]
262pub struct ProcessMetrics;
263
264/// What `/proc/self` says about this process.
265#[derive(Debug, Clone, Copy, PartialEq)]
266pub struct ProcessStats {
267    /// Resident memory, in bytes.
268    pub resident_bytes: u64,
269    /// CPU time used (user and system), in seconds.
270    pub cpu_seconds: f64,
271    /// Open file descriptors.
272    pub open_fds: u64,
273    /// When the process started, in seconds since the Unix epoch.
274    pub start_time_seconds: f64,
275}
276
277/// Reads this process's stats from `/proc`; `None` where there is no `/proc`.
278#[must_use]
279pub fn process_stats() -> Option<ProcessStats> {
280    let stat = std::fs::read_to_string("/proc/self/stat").ok()?;
281    let statm = std::fs::read_to_string("/proc/self/statm").ok()?;
282    let boot = std::fs::read_to_string("/proc/stat").ok()?;
283    // The listing's own descriptor is among the entries.
284    let open_fds = std::fs::read_dir("/proc/self/fd")
285        .ok()?
286        .count()
287        .saturating_sub(1);
288    parse_stats(
289        &stat,
290        &statm,
291        &boot,
292        u64::try_from(open_fds).unwrap_or(0),
293        u64::try_from(rustix::param::page_size()).unwrap_or(4096),
294        rustix::param::clock_ticks_per_second(),
295    )
296}
297
298/// The stats in `/proc/self/stat`, `/proc/self/statm` and `/proc/stat` (for the boot time).
299#[must_use]
300pub fn parse_stats(
301    stat: &str,
302    statm: &str,
303    boot: &str,
304    open_fds: u64,
305    page: u64,
306    ticks: u64,
307) -> Option<ProcessStats> {
308    // Fields after the command (field 2, in parentheses): 3 is the first.
309    let fields: Vec<&str> = stat[stat.rfind(')')? + 1..].split_whitespace().collect();
310    let field = |n: usize| -> Option<u64> { fields.get(n - 3)?.parse().ok() };
311    #[expect(clippy::cast_precision_loss, reason = "seconds from clock ticks")]
312    let seconds = |t: u64| t as f64 / ticks.max(1) as f64;
313    let boot_time: u64 = boot
314        .lines()
315        .find_map(|line| line.strip_prefix("btime "))?
316        .trim()
317        .parse()
318        .ok()?;
319    let resident_pages: u64 = statm.split_whitespace().nth(1)?.parse().ok()?;
320    #[expect(clippy::cast_precision_loss, reason = "a Unix time in seconds")]
321    let boot_seconds = boot_time as f64;
322    Some(ProcessStats {
323        resident_bytes: resident_pages * page,
324        cpu_seconds: seconds(field(14)? + field(15)?),
325        open_fds,
326        start_time_seconds: boot_seconds + seconds(field(22)?),
327    })
328}
329
330/// Help text ending as `Registry::register` ends it.
331fn help(doc: MetricDoc) -> String {
332    format!("{}.", doc.help)
333}
334
335impl Collector for ProcessMetrics {
336    fn encode(&self, mut encoder: DescriptorEncoder) -> Result<(), std::fmt::Error> {
337        let Some(stats) = process_stats() else {
338            return Ok(());
339        };
340        let resident = ConstGauge::new(i64::try_from(stats.resident_bytes).unwrap_or(i64::MAX));
341        resident.encode(encoder.encode_descriptor(
342            RESIDENT_MEMORY.name,
343            &help(RESIDENT_MEMORY),
344            None,
345            resident.metric_type(),
346        )?)?;
347        let cpu = ConstCounter::new(stats.cpu_seconds);
348        cpu.encode(encoder.encode_descriptor(CPU.name, &help(CPU), None, cpu.metric_type())?)?;
349        let fds = ConstGauge::new(i64::try_from(stats.open_fds).unwrap_or(i64::MAX));
350        fds.encode(encoder.encode_descriptor(
351            OPEN_FDS.name,
352            &help(OPEN_FDS),
353            None,
354            fds.metric_type(),
355        )?)?;
356        let start = ConstGauge::new(stats.start_time_seconds);
357        start.encode(encoder.encode_descriptor(
358            START_TIME.name,
359            &help(START_TIME),
360            None,
361            start.metric_type(),
362        )?)?;
363        Ok(())
364    }
365}
366
367/// The ops address's line for a role's log.
368#[must_use]
369pub fn ops_line(address: std::net::SocketAddr) -> String {
370    format!("ops on http://{address}")
371}