Skip to main content

server/telemetry/
recorder.rs

1//! Prometheus recorder, series names and the `/metrics` listener shared by the binaries.
2//!
3//! Names carry the `nomisync_` prefix because the series land in a
4//! VictoriaMetrics shared with every other app on the cluster.
5
6pub use metrics_exporter_prometheus::PrometheusHandle;
7use metrics_exporter_prometheus::{BuildError, Matcher, PrometheusBuilder, PrometheusRecorder};
8use std::io;
9use tokio::io::{AsyncReadExt, AsyncWriteExt};
10use tokio::net::{TcpListener, TcpStream};
11use tokio::time::{Duration, sleep, timeout};
12
13/// Web request latency in seconds.
14pub const HTTP_REQUEST_DURATION: &str = "nomisync_http_requests_duration_seconds";
15
16/// Open SSH sessions.
17pub const SSH_SESSIONS_ACTIVE: &str = "nomisync_ssh_sessions_active";
18
19/// SSH sessions opened since start.
20pub const SSH_SESSIONS_TOTAL: &str = "nomisync_ssh_sessions_total";
21
22/// Evaluations, labelled `outcome` ok / error / refused.
23pub const EVAL_REQUESTS: &str = "nomisync_eval_requests_total";
24
25/// Evaluation latency in seconds.
26pub const EVAL_DURATION: &str = "nomisync_eval_duration_seconds";
27
28/// Client-form requests, labelled `form`, `action` and `outcome`.
29pub const FORM_REQUESTS: &str = "nomisync_form_requests_total";
30
31/// Script batch items, labelled `outcome` committed / refused / failed.
32pub const SCRIPT_BATCH_ITEMS: &str = "nomisync_script_batch_items_total";
33
34/// Database pool connections, labelled `pool` and `state`.
35pub const DB_POOL_CONNECTIONS: &str = "nomisync_db_pool_connections";
36
37/// Failed pool acquisitions, labelled `pool` and `reason`.
38pub const DB_POOL_ACQUIRE_FAILURES: &str = "nomisync_db_pool_acquire_failures_total";
39
40/// Sub-10ms to 10s: a cached page render up to a slow report query.
41const HTTP_BUCKETS: &[f64] = &[
42    0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
43];
44
45/// 1ms to 30s: a trivial form up to the longest a script may run.
46const EVAL_BUCKETS: &[f64] = &[
47    0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0,
48];
49
50const HISTOGRAM_BUCKETS: [(&str, &[f64]); 2] = [
51    (HTTP_REQUEST_DURATION, HTTP_BUCKETS),
52    (EVAL_DURATION, EVAL_BUCKETS),
53];
54
55const MAX_REQUEST_HEAD: usize = 8192;
56
57/// A client that stalls mid-request or never reads must not pin a task and fd.
58const CONNECTION_DEADLINE: Duration = Duration::from_secs(5);
59
60/// Back-off after a failed `accept`, so fd exhaustion does not spin.
61const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
62
63fn builder() -> Result<PrometheusBuilder, BuildError> {
64    HISTOGRAM_BUCKETS
65        .into_iter()
66        .try_fold(PrometheusBuilder::new(), |builder, (name, buckets)| {
67            builder.set_buckets_for_metric(Matcher::Full(name.to_string()), buckets)
68        })
69}
70
71/// A recorder with the shared bucket configuration, not installed globally.
72///
73/// # Errors
74/// [`BuildError`] if the bucket configuration is rejected.
75pub fn build_recorder() -> Result<PrometheusRecorder, BuildError> {
76    Ok(builder()?.build_recorder())
77}
78
79/// Installs the process-wide Prometheus recorder.
80///
81/// # Errors
82/// [`BuildError`] if the bucket configuration is rejected or a recorder is
83/// already installed — both are startup faults, reported rather than panicked.
84pub fn install_recorder() -> Result<PrometheusHandle, BuildError> {
85    builder()?.install_recorder()
86}
87
88/// Serves `GET /metrics` from `handle` on `listener`; accept failures are logged and retried.
89pub async fn serve_metrics(listener: TcpListener, handle: PrometheusHandle) {
90    loop {
91        match listener.accept().await {
92            Ok((stream, _)) => {
93                let handle = handle.clone();
94                tokio::spawn(async move {
95                    match timeout(CONNECTION_DEADLINE, respond(stream, &handle)).await {
96                        Ok(Ok(())) => {}
97                        Ok(Err(err)) => tracing::debug!("metrics connection failed: {err}"),
98                        Err(_) => tracing::debug!("metrics connection timed out"),
99                    }
100                });
101            }
102            Err(err) => {
103                tracing::warn!("metrics accept failed: {err}");
104                sleep(ACCEPT_BACKOFF).await;
105            }
106        }
107    }
108}
109
110async fn respond(mut stream: TcpStream, handle: &PrometheusHandle) -> io::Result<()> {
111    let mut head = Vec::new();
112    let mut chunk = [0u8; 1024];
113    while !head.windows(4).any(|w| w == b"\r\n\r\n") && head.len() < MAX_REQUEST_HEAD {
114        match stream.read(&mut chunk).await? {
115            0 => break,
116            n => head.extend_from_slice(&chunk[..n]),
117        }
118    }
119    let request_line = head.split(|&b| b == b'\r').next().unwrap_or_default();
120    let reply = if request_line.starts_with(b"GET /metrics ") {
121        let body = handle.render();
122        format!(
123            "HTTP/1.1 200 OK\r\ncontent-type: text/plain; version=0.0.4\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
124            body.len()
125        )
126    } else {
127        "HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n".to_string()
128    };
129    stream.write_all(reply.as_bytes()).await?;
130    stream.shutdown().await
131}