Lines
90.24 %
Functions
95.45 %
Branches
100 %
//! Prometheus recorder, series names and the `/metrics` listener shared by the binaries.
//!
//! Names carry the `nomisync_` prefix because the series land in a
//! VictoriaMetrics shared with every other app on the cluster.
pub use metrics_exporter_prometheus::PrometheusHandle;
use metrics_exporter_prometheus::{BuildError, Matcher, PrometheusBuilder, PrometheusRecorder};
use std::io;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::time::{Duration, sleep, timeout};
/// Web request latency in seconds.
pub const HTTP_REQUEST_DURATION: &str = "nomisync_http_requests_duration_seconds";
/// Open SSH sessions.
pub const SSH_SESSIONS_ACTIVE: &str = "nomisync_ssh_sessions_active";
/// SSH sessions opened since start.
pub const SSH_SESSIONS_TOTAL: &str = "nomisync_ssh_sessions_total";
/// Evaluations, labelled `outcome` ok / error / refused.
pub const EVAL_REQUESTS: &str = "nomisync_eval_requests_total";
/// Evaluation latency in seconds.
pub const EVAL_DURATION: &str = "nomisync_eval_duration_seconds";
/// Client-form requests, labelled `form`, `action` and `outcome`.
pub const FORM_REQUESTS: &str = "nomisync_form_requests_total";
/// Script batch items, labelled `outcome` committed / refused / failed.
pub const SCRIPT_BATCH_ITEMS: &str = "nomisync_script_batch_items_total";
/// Database pool connections, labelled `pool` and `state`.
pub const DB_POOL_CONNECTIONS: &str = "nomisync_db_pool_connections";
/// Failed pool acquisitions, labelled `pool` and `reason`.
pub const DB_POOL_ACQUIRE_FAILURES: &str = "nomisync_db_pool_acquire_failures_total";
/// Sub-10ms to 10s: a cached page render up to a slow report query.
const HTTP_BUCKETS: &[f64] = &[
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
];
/// 1ms to 30s: a trivial form up to the longest a script may run.
const EVAL_BUCKETS: &[f64] = &[
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,
const HISTOGRAM_BUCKETS: [(&str, &[f64]); 2] = [
(HTTP_REQUEST_DURATION, HTTP_BUCKETS),
(EVAL_DURATION, EVAL_BUCKETS),
const MAX_REQUEST_HEAD: usize = 8192;
/// A client that stalls mid-request or never reads must not pin a task and fd.
const CONNECTION_DEADLINE: Duration = Duration::from_secs(5);
/// Back-off after a failed `accept`, so fd exhaustion does not spin.
const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
fn builder() -> Result<PrometheusBuilder, BuildError> {
HISTOGRAM_BUCKETS
.into_iter()
.try_fold(PrometheusBuilder::new(), |builder, (name, buckets)| {
builder.set_buckets_for_metric(Matcher::Full(name.to_string()), buckets)
})
}
/// A recorder with the shared bucket configuration, not installed globally.
///
/// # Errors
/// [`BuildError`] if the bucket configuration is rejected.
pub fn build_recorder() -> Result<PrometheusRecorder, BuildError> {
Ok(builder()?.build_recorder())
/// Installs the process-wide Prometheus recorder.
/// [`BuildError`] if the bucket configuration is rejected or a recorder is
/// already installed — both are startup faults, reported rather than panicked.
pub fn install_recorder() -> Result<PrometheusHandle, BuildError> {
builder()?.install_recorder()
/// Serves `GET /metrics` from `handle` on `listener`; accept failures are logged and retried.
pub async fn serve_metrics(listener: TcpListener, handle: PrometheusHandle) {
loop {
match listener.accept().await {
Ok((stream, _)) => {
let handle = handle.clone();
tokio::spawn(async move {
match timeout(CONNECTION_DEADLINE, respond(stream, &handle)).await {
Ok(Ok(())) => {}
Ok(Err(err)) => tracing::debug!("metrics connection failed: {err}"),
Err(_) => tracing::debug!("metrics connection timed out"),
});
Err(err) => {
tracing::warn!("metrics accept failed: {err}");
sleep(ACCEPT_BACKOFF).await;
async fn respond(mut stream: TcpStream, handle: &PrometheusHandle) -> io::Result<()> {
let mut head = Vec::new();
let mut chunk = [0u8; 1024];
while !head.windows(4).any(|w| w == b"\r\n\r\n") && head.len() < MAX_REQUEST_HEAD {
match stream.read(&mut chunk).await? {
0 => break,
n => head.extend_from_slice(&chunk[..n]),
let request_line = head.split(|&b| b == b'\r').next().unwrap_or_default();
let reply = if request_line.starts_with(b"GET /metrics ") {
let body = handle.render();
format!(
"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}",
body.len()
)
} else {
"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n".to_string()
};
stream.write_all(reply.as_bytes()).await?;
stream.shutdown().await