1use 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
41pub 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
75pub const PROCESS_METRICS: &[MetricDoc] = &[RESIDENT_MEMORY, CPU, OPEN_FDS, START_TIME, BUILD];
78
79#[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#[derive(Debug, Clone)]
95pub struct Starting(Arc<AtomicBool>);
96
97impl Starting {
98 pub fn ready(&self) {
100 self.0.store(true, Ordering::Relaxed);
101 }
102
103 pub fn set(&self, ready: bool) {
105 self.0.store(ready, Ordering::Relaxed);
106 }
107}
108
109impl Health {
110 #[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 #[must_use]
128 pub fn stall(&self) -> Duration {
129 self.checks().stall
130 }
131
132 pub fn watch_loop(&self, name: &'static str, beat: Beat) {
135 self.checks().loops.push((name, beat));
136 }
137
138 #[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 #[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 #[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#[derive(Debug, Clone)]
176pub struct Ops {
177 registry: Arc<Registry>,
178 health: Health,
179}
180
181impl Ops {
182 #[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 #[must_use]
200 pub fn metrics_text(&self) -> String {
201 let mut text = String::new();
202 let _ = prometheus_client::encoding::text::encode(&mut text, &self.registry);
204 text
205 }
206}
207
208pub 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
243pub 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#[derive(Debug, Default)]
262pub struct ProcessMetrics;
263
264#[derive(Debug, Clone, Copy, PartialEq)]
266pub struct ProcessStats {
267 pub resident_bytes: u64,
269 pub cpu_seconds: f64,
271 pub open_fds: u64,
273 pub start_time_seconds: f64,
275}
276
277#[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 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#[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 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
330fn 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#[must_use]
369pub fn ops_line(address: std::net::SocketAddr) -> String {
370 format!("ops on http://{address}")
371}