server/telemetry/
recorder.rs1pub 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
13pub const HTTP_REQUEST_DURATION: &str = "nomisync_http_requests_duration_seconds";
15
16pub const SSH_SESSIONS_ACTIVE: &str = "nomisync_ssh_sessions_active";
18
19pub const SSH_SESSIONS_TOTAL: &str = "nomisync_ssh_sessions_total";
21
22pub const EVAL_REQUESTS: &str = "nomisync_eval_requests_total";
24
25pub const EVAL_DURATION: &str = "nomisync_eval_duration_seconds";
27
28pub const FORM_REQUESTS: &str = "nomisync_form_requests_total";
30
31pub const SCRIPT_BATCH_ITEMS: &str = "nomisync_script_batch_items_total";
33
34pub const DB_POOL_CONNECTIONS: &str = "nomisync_db_pool_connections";
36
37pub const DB_POOL_ACQUIRE_FAILURES: &str = "nomisync_db_pool_acquire_failures_total";
39
40const 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
45const 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
57const CONNECTION_DEADLINE: Duration = Duration::from_secs(5);
59
60const 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
71pub fn build_recorder() -> Result<PrometheusRecorder, BuildError> {
76 Ok(builder()?.build_recorder())
77}
78
79pub fn install_recorder() -> Result<PrometheusHandle, BuildError> {
85 builder()?.install_recorder()
86}
87
88pub 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}