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

            
6
pub use metrics_exporter_prometheus::PrometheusHandle;
7
use metrics_exporter_prometheus::{BuildError, Matcher, PrometheusBuilder, PrometheusRecorder};
8
use std::io;
9
use tokio::io::{AsyncReadExt, AsyncWriteExt};
10
use tokio::net::{TcpListener, TcpStream};
11
use tokio::time::{Duration, sleep, timeout};
12

            
13
/// Web request latency in seconds.
14
pub const HTTP_REQUEST_DURATION: &str = "nomisync_http_requests_duration_seconds";
15

            
16
/// Open SSH sessions.
17
pub const SSH_SESSIONS_ACTIVE: &str = "nomisync_ssh_sessions_active";
18

            
19
/// SSH sessions opened since start.
20
pub const SSH_SESSIONS_TOTAL: &str = "nomisync_ssh_sessions_total";
21

            
22
/// Evaluations, labelled `outcome` ok / error / refused.
23
pub const EVAL_REQUESTS: &str = "nomisync_eval_requests_total";
24

            
25
/// Evaluation latency in seconds.
26
pub const EVAL_DURATION: &str = "nomisync_eval_duration_seconds";
27

            
28
/// Client-form requests, labelled `form`, `action` and `outcome`.
29
pub const FORM_REQUESTS: &str = "nomisync_form_requests_total";
30

            
31
/// Script batch items, labelled `outcome` committed / refused / failed.
32
pub const SCRIPT_BATCH_ITEMS: &str = "nomisync_script_batch_items_total";
33

            
34
/// Database pool connections, labelled `pool` and `state`.
35
pub const DB_POOL_CONNECTIONS: &str = "nomisync_db_pool_connections";
36

            
37
/// Failed pool acquisitions, labelled `pool` and `reason`.
38
pub 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.
41
const 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.
46
const 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

            
50
const HISTOGRAM_BUCKETS: [(&str, &[f64]); 2] = [
51
    (HTTP_REQUEST_DURATION, HTTP_BUCKETS),
52
    (EVAL_DURATION, EVAL_BUCKETS),
53
];
54

            
55
const MAX_REQUEST_HEAD: usize = 8192;
56

            
57
/// A client that stalls mid-request or never reads must not pin a task and fd.
58
const CONNECTION_DEADLINE: Duration = Duration::from_secs(5);
59

            
60
/// Back-off after a failed `accept`, so fd exhaustion does not spin.
61
const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
62

            
63
4510
fn builder() -> Result<PrometheusBuilder, BuildError> {
64
4510
    HISTOGRAM_BUCKETS
65
4510
        .into_iter()
66
9020
        .try_fold(PrometheusBuilder::new(), |builder, (name, buckets)| {
67
9020
            builder.set_buckets_for_metric(Matcher::Full(name.to_string()), buckets)
68
9020
        })
69
4510
}
70

            
71
/// A recorder with the shared bucket configuration, not installed globally.
72
///
73
/// # Errors
74
/// [`BuildError`] if the bucket configuration is rejected.
75
4150
pub fn build_recorder() -> Result<PrometheusRecorder, BuildError> {
76
4150
    Ok(builder()?.build_recorder())
77
4150
}
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.
84
360
pub fn install_recorder() -> Result<PrometheusHandle, BuildError> {
85
360
    builder()?.install_recorder()
86
360
}
87

            
88
/// Serves `GET /metrics` from `handle` on `listener`; accept failures are logged and retried.
89
182
pub async fn serve_metrics(listener: TcpListener, handle: PrometheusHandle) {
90
    loop {
91
366
        match listener.accept().await {
92
            Ok((stream, _)) => {
93
184
                let handle = handle.clone();
94
184
                tokio::spawn(async move {
95
184
                    match timeout(CONNECTION_DEADLINE, respond(stream, &handle)).await {
96
183
                        Ok(Ok(())) => {}
97
                        Ok(Err(err)) => tracing::debug!("metrics connection failed: {err}"),
98
1
                        Err(_) => tracing::debug!("metrics connection timed out"),
99
                    }
100
184
                });
101
            }
102
            Err(err) => {
103
                tracing::warn!("metrics accept failed: {err}");
104
                sleep(ACCEPT_BACKOFF).await;
105
            }
106
        }
107
    }
108
}
109

            
110
184
async fn respond(mut stream: TcpStream, handle: &PrometheusHandle) -> io::Result<()> {
111
184
    let mut head = Vec::new();
112
184
    let mut chunk = [0u8; 1024];
113
5671
    while !head.windows(4).any(|w| w == b"\r\n\r\n") && head.len() < MAX_REQUEST_HEAD {
114
184
        match stream.read(&mut chunk).await? {
115
            0 => break,
116
183
            n => head.extend_from_slice(&chunk[..n]),
117
        }
118
    }
119
4024
    let request_line = head.split(|&b| b == b'\r').next().unwrap_or_default();
120
183
    let reply = if request_line.starts_with(b"GET /metrics ") {
121
182
        let body = handle.render();
122
182
        format!(
123
182
            "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
182
            body.len()
125
        )
126
    } else {
127
1
        "HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n".to_string()
128
    };
129
183
    stream.write_all(reply.as_bytes()).await?;
130
183
    stream.shutdown().await
131
183
}