//! The server's metrics, in Prometheus' text format, version 0.0.4, on //! `127.0.0.1:PDS_METRICS_PORT` (`spec/OPERATIONS.md`), and as `_stats` //! answers them (`stats`). Every label's values are bounded: the routes //! served, statuses, and the outbound targets. use super::trace::Target; use crate::{Shared, read}; use axum::body::Body; use axum::http::{Method, Response, StatusCode, header}; use serde_json::{Map, Value as Json, json}; use std::collections::BTreeMap; use std::fmt::Write; use std::sync::{Mutex, PoisonError}; use std::time::Duration; const REQUEST_BUCKETS: &[f64] = &[ 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, ]; const FSYNC_BUCKETS: &[f64] = &[ 0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 1.0, ]; struct Histogram { bounds: &'static [f64], /// Each bucket's own observations, not yet cumulative. counts: Vec, count: u64, sum: f64, } impl Histogram { fn new(bounds: &'static [f64]) -> Histogram { Histogram { bounds, counts: vec![0; bounds.len()], count: 0, sum: 0.0, } } fn observe(&mut self, v: f64) { if let Some(i) = self.bounds.iter().position(|b| v <= *b) { self.counts[i] += 1; } self.count += 1; self.sum += v; } /// Its samples, with `labels` before `le`, each `name_bucket`, `_sum`, `_count`. fn render(&self, out: &mut String, name: &str, labels: &str) { let sep = if labels.is_empty() { "" } else { "," }; let mut seen = 0; for (b, n) in self.bounds.iter().zip(&self.counts) { seen += n; let _ = writeln!(out, "{name}_bucket{{{labels}{sep}le=\"{b}\"}} {seen}"); } let _ = writeln!( out, "{name}_bucket{{{labels}{sep}le=\"+Inf\"}} {}", self.count ); let braces = if labels.is_empty() { String::new() } else { format!("{{{labels}}}") }; let _ = writeln!(out, "{name}_sum{braces} {}", self.sum); let _ = writeln!(out, "{name}_count{braces} {}", self.count); } } struct Inner { requests: BTreeMap<(&'static str, u16), u64>, durations: BTreeMap<&'static str, Histogram>, limited: BTreeMap<&'static str, u64>, fsync: Histogram, outbound: BTreeMap<(&'static str, &'static str), u64>, outbound_durations: BTreeMap<&'static str, Histogram>, } /// The counters and histograms, from the start of the process. pub(super) struct Metrics(Mutex); impl Default for Metrics { fn default() -> Metrics { Metrics(Mutex::new(Inner { requests: BTreeMap::new(), durations: BTreeMap::new(), limited: BTreeMap::new(), fsync: Histogram::new(FSYNC_BUCKETS), outbound: BTreeMap::new(), outbound_durations: BTreeMap::new(), })) } } impl Metrics { fn lock(&self) -> std::sync::MutexGuard<'_, Inner> { self.0.lock().unwrap_or_else(PoisonError::into_inner) } /// A request answered, on `route`, taking `secs`. pub fn request(&self, route: &'static str, status: u16, secs: f64) { let mut m = self.lock(); *m.requests.entry((route, status)).or_default() += 1; m.durations .entry(route) .or_insert_with(|| Histogram::new(REQUEST_BUCKETS)) .observe(secs); if status == 429 { *m.limited.entry(route).or_default() += 1; } } pub fn fsync(&self, d: Duration) { self.lock().fsync.observe(d.as_secs_f64()); } /// A request the server made, answered with a 2xx (`ok`) or not. pub fn outbound(&self, target: Target, ok: bool, secs: f64) { let mut m = self.lock(); *m.outbound .entry((target.label(), if ok { "ok" } else { "error" })) .or_default() += 1; m.outbound_durations .entry(target.label()) .or_insert_with(|| Histogram::new(REQUEST_BUCKETS)) .observe(secs); } /// The exposition, with the gauges read from `svc` now. fn render(&self, svc: &Shared) -> String { let g = Gauges::of(svc); let mut out = String::with_capacity(8192); let family = |out: &mut String, name: &str, ty: &str, help: &str| { let _ = writeln!(out, "# HELP {name} {help}\n# TYPE {name} {ty}"); }; let m = self.lock(); family( &mut out, "pds_requests_total", "counter", "Requests answered.", ); for ((route, status), n) in &m.requests { let _ = writeln!( out, "pds_requests_total{{method=\"{}\",status=\"{status}\"}} {n}", escape(route) ); } family( &mut out, "pds_request_duration_seconds", "histogram", "Each request's time, from reading its head to its log line.", ); for (route, h) in &m.durations { h.render( &mut out, "pds_request_duration_seconds", &format!("method=\"{}\"", escape(route)), ); } family( &mut out, "pds_rate_limited_total", "counter", "Requests refused by a rate limit.", ); for (route, n) in &m.limited { let _ = writeln!( out, "pds_rate_limited_total{{method=\"{}\"}} {n}", escape(route) ); } family( &mut out, "pds_firehose_seq", "gauge", "The seq of the firehose's last event.", ); let _ = writeln!(out, "pds_firehose_seq {}", g.seq); family( &mut out, "pds_firehose_subscribers", "gauge", "subscribeRepos connections open.", ); let _ = writeln!(out, "pds_firehose_subscribers {}", g.subscribers); family( &mut out, "pds_accounts", "gauge", "The accounts the server holds.", ); let _ = writeln!(out, "pds_accounts {}", g.accounts); family( &mut out, "pds_log_bytes", "gauge", "The bytes of the logs the server keeps its state in.", ); let _ = writeln!(out, "pds_log_bytes {}", g.log_bytes); family( &mut out, "pds_fsync_duration_seconds", "histogram", "Each sync of written data to the disk.", ); m.fsync.render(&mut out, "pds_fsync_duration_seconds", ""); family( &mut out, "pds_outbound_requests_total", "counter", "Requests the server made.", ); for ((target, outcome), n) in &m.outbound { let _ = writeln!( out, "pds_outbound_requests_total{{target=\"{target}\",outcome=\"{outcome}\"}} {n}" ); } family( &mut out, "pds_outbound_request_duration_seconds", "histogram", "Each request the server made, until its answer or failure.", ); for (target, h) in &m.outbound_durations { h.render( &mut out, "pds_outbound_request_duration_seconds", &format!("target=\"{target}\""), ); } out } /// What `_stats` answers (`spec/OPERATIONS.md`, "_stats"): the same /// counters, the gauges read from `svc` now, `started` the time of /// this start's `start` line. pub fn stats(&self, svc: &Shared, started: &str) -> Json { let g = Gauges::of(svc); let m = self.lock(); let ms = |h: &Histogram| { if h.count == 0 { 0.0 } else { h.sum / h.count as f64 * 1000.0 } }; let mut routes: Vec<(&str, &Histogram)> = m.durations.iter().map(|(r, h)| (*r, h)).collect(); routes.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(b.0))); let routes: Vec = routes .into_iter() .map(|(route, h)| { let statuses: Map = m .requests .range((route, 0)..=(route, u16::MAX)) .map(|((_, status), n)| (status.to_string(), json!(n))) .collect(); json!({ "method": route, "count": h.count, "statuses": statuses, "rateLimited": m.limited.get(route).copied().unwrap_or(0), "meanMs": ms(h), }) }) .collect(); let outbound: Vec = m .outbound_durations .iter() .map(|(target, h)| { let n = |outcome| m.outbound.get(&(*target, outcome)).copied().unwrap_or(0); json!({ "target": target, "ok": n("ok"), "error": n("error"), "meanMs": ms(h) }) }) .collect(); json!({ "version": super::VERSION, "started": started, "accounts": g.accounts, "logBytes": g.log_bytes, "firehose": { "seq": g.seq, "subscribers": g.subscribers }, "routes": routes, "outbound": outbound, "fsync": { "count": m.fsync.count, "meanMs": ms(&m.fsync) }, }) } } /// The gauges, as they are now. struct Gauges { accounts: u64, log_bytes: u64, seq: u64, subscribers: u64, } impl Gauges { fn of(svc: &Shared) -> Gauges { // As `listRepos` lists them: the count the directory keeps. The // accounts' files are found by DID, of an account loaded or not. let (accounts, dids) = { let d = read(&svc.directory); (d.count(), d.dids()) }; // Every generation's log not yet folded away, and the checkpoints: // of an account or a store not loaded, as its files' sizes are, // which loads none; and the journal's records, as a log's frames. let log_bytes = svc.log.log_bytes() + svc.log.checkpoint_bytes() + svc.ctx.files.journal().map_or(0, |j| j.bytes()) + dids .iter() .map(|did| { let loaded = read(&svc.directory).by_did.get(did).cloned(); match loaded { Some(a) => a.store.log_bytes(), None => crate::directory::files_bytes(&svc.dir, did), } }) .sum::(); Gauges { accounts, log_bytes, seq: svc.events.last_event(), subscribers: svc.events.subscribers() as u64, } } } fn escape(v: &str) -> String { v.replace('\\', "\\\\") .replace('"', "\\\"") .replace('\n', "\\n") } /// Serve `GET /metrics` on `listener`, and `404` to anything else. pub(super) async fn serve(listener: tokio::net::TcpListener, svc: Shared) { let app = axum::Router::new().fallback(move |method: Method, uri: axum::http::Uri| { let svc = svc.clone(); async move { let mut res = Response::new(Body::empty()); if method == Method::GET && uri.path() == "/metrics" { res = Response::new(Body::from(super::ops().metrics.render(&svc))); res.headers_mut().insert( header::CONTENT_TYPE, header::HeaderValue::from_static("text/plain; version=0.0.4; charset=utf-8"), ); } else { *res.status_mut() = StatusCode::NOT_FOUND; } res } }); let _ = axum::serve(listener, app).await; } #[cfg(test)] mod tests { use super::*; /// A histogram's buckets are cumulative, each bound as Prometheus reads /// it, then `+Inf`, `_sum` and `_count`. #[test] fn histograms() { let mut h = Histogram::new(FSYNC_BUCKETS); for v in [0.00005, 0.0003, 0.0003, 2.0] { h.observe(v); } let mut out = String::new(); h.render(&mut out, "x", ""); let lines: Vec<&str> = out.lines().collect(); assert_eq!(lines[0], "x_bucket{le=\"0.0001\"} 1"); assert_eq!(lines[2], "x_bucket{le=\"0.0005\"} 3"); assert_eq!(lines[11], "x_bucket{le=\"1\"} 3"); assert_eq!(lines[12], "x_bucket{le=\"+Inf\"} 4"); assert!( (lines[13] .strip_prefix("x_sum ") .unwrap() .parse::() .unwrap() - 2.00065) .abs() < 1e-9 ); assert_eq!(lines[14], "x_count 4"); let mut out = String::new(); Histogram::new(REQUEST_BUCKETS).render(&mut out, "y", "method=\"_health\""); assert!(out.starts_with("y_bucket{method=\"_health\",le=\"0.005\"} 0\n")); assert!(out.ends_with("y_sum{method=\"_health\"} 0\ny_count{method=\"_health\"} 0\n")); } }