1
//! SSH session series and the optional `/metrics` listener.
2

            
3
use server::telemetry::recorder::{
4
    PrometheusHandle, SSH_SESSIONS_ACTIVE, SSH_SESSIONS_TOTAL, serve_metrics,
5
};
6
use std::io;
7
use std::net::SocketAddr;
8
use tokio::net::TcpListener;
9
use tokio::task::JoinHandle;
10

            
11
/// Counts one open session; dropping it, on any close path, takes it back off the gauge.
12
pub struct SessionGauge;
13

            
14
impl SessionGauge {
15
26
    pub fn open() -> Self {
16
26
        metrics::counter!(SSH_SESSIONS_TOTAL).increment(1);
17
26
        metrics::gauge!(SSH_SESSIONS_ACTIVE).increment(1.0);
18
26
        Self
19
26
    }
20
}
21

            
22
impl Drop for SessionGauge {
23
26
    fn drop(&mut self) {
24
26
        metrics::gauge!(SSH_SESSIONS_ACTIVE).decrement(1.0);
25
26
    }
26
}
27

            
28
/// Obtains the recorder handle via `install` and serves `/metrics` on `bind`;
29
/// `None` installs and opens nothing.
30
///
31
/// # Errors
32
/// The recorder cannot be installed or `bind` cannot be bound.
33
2
pub async fn start(
34
2
    bind: Option<SocketAddr>,
35
2
    install: impl FnOnce() -> io::Result<PrometheusHandle>,
36
2
) -> io::Result<Option<(SocketAddr, JoinHandle<()>)>> {
37
2
    let Some(bind) = bind else {
38
1
        return Ok(None);
39
    };
40
1
    let handle = install()?;
41
1
    let listener = TcpListener::bind(bind).await?;
42
1
    let addr = listener.local_addr()?;
43
1
    tracing::info!("nomisync-sshd metrics on {addr}");
44
1
    Ok(Some((addr, tokio::spawn(serve_metrics(listener, handle)))))
45
2
}