Something went wrong. Try again.
Expose HTTP/SSH/TCP services through SSH port forwarding. sandhole.com.br
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899// sandhole: Expose HTTP/SSH/TCP services through SSH port forwarding// Copyright (C) 2024-2026 Eric Rodrigues Pires//// This program is free software: you can redistribute it and/or modify it under// the terms of the GNU Affero General Public License as published by the Free// Software Foundation, either version 3 of the License, or (at your option)// any later version.//// This program is distributed in the hope that it will be useful, but WITHOUT// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS// FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for// more details.//// You should have received a copy of the GNU Affero General Public License along// with this program. If not, see <https://www.gnu.org/licenses/>.
#[cfg_attr(not(feature = "prometheus"), allow(unused_imports))]use std::future;use std::{ collections::{HashMap, HashSet, VecDeque}, sync::{ Arc, Mutex, atomic::{AtomicU64, Ordering}, }, time::{Duration, Instant},};
use ahash::RandomState;use dashmap::DashMap;use itertools::Itertools;use metrics::{ Counter, CounterFn, Gauge, GaugeFn, Recorder, Unit, describe_counter, describe_gauge, describe_histogram,};#[cfg(feature = "prometheus")]use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle, PrometheusRecorder};#[cfg_attr(not(feature = "prometheus"), allow(unused_imports))]use tokio::time::sleep;
#[cfg_attr(not(feature = "prometheus"), allow(unused_imports))]use crate::droppable_handle::DroppableHandle;use crate::sock_addr_alias::SockAddrAlias;
// A value that increases with time.struct SlidingWindowCounter { // Inner counter for metrics with a different exporter. inner: Counter, // The history of the value across several instants. history: Mutex<VecDeque<(Instant, u64)>>, // The sliding window of values to consider. window: Duration, // The current value. count: AtomicU64,}
impl CounterFn for SlidingWindowCounter { fn increment(&self, value: u64) { self.inner.increment(value); self.clean(); self.count.fetch_add(value, Ordering::Release); }
fn absolute(&self, value: u64) { self.inner.absolute(value); self.clean(); self.count.swap(value, Ordering::Release); }}
impl SlidingWindowCounter { fn new(counter: Counter, window: Duration) -> Self { SlidingWindowCounter { inner: counter, history: Mutex::new([(Instant::now(), 0)].into_iter().collect()), window, count: AtomicU64::new(0), } }
fn clean(&self) { let mut history = self.history.lock().expect("not poisoned"); while let Some(element) = history.front() && element.0.elapsed() >= self.window { // Don't remove the first element if it is the last one. // Instead, update its instant. // This ensures that the first call to add is counted. if history.len() == 1 { history.front_mut().expect("length check").0 = Instant::now(); break; } else { history.pop_front(); } } }
// Measure the counter, taking the period and window into account. fn measure(&self) -> u64 { let count = self.count.load(Ordering::Acquire); let mut history = self.history.lock().expect("not poisoned"); let measurement = loop { // If there are no elements in the history, return the current count. let Some(element) = history.front() else { break count; }; // If the count hasn't changed, return the current count (rate will be 0). if element.1 == count { history.pop_front(); break 0; // The count has changed; if within window, return the front element. } else if element.0.elapsed() < self.window { break count - element.1; // Element is no longer within window; remove from history. } else { history.pop_front(); } }; // If the last element has a different count value, add the current count to the end. if let Some(element) = history.back() { if element.1 != count { history.push_back((Instant::now(), count)); } // Also add the current count to the end if the history is empty. } else { history.push_back((Instant::now(), count)); } measurement }}
// A value that goes up and down with time.struct TelemetryGauge { // Inner gauge for metrics with a different exporter. inner: Gauge, // The current value. value: Mutex<f64>,}
impl GaugeFn for TelemetryGauge { fn increment(&self, value: f64) { self.inner.increment(value); *self.value.lock().expect("not poisoned") += value; }
fn decrement(&self, value: f64) { self.inner.decrement(value); *self.value.lock().expect("not poisoned") -= value; }
fn set(&self, value: f64) { self.inner.set(value); *self.value.lock().expect("not poisoned") = value; }}
impl TelemetryGauge { fn new(gauge: Gauge) -> Self { TelemetryGauge { inner: gauge, value: Mutex::default(), } }
// Measure the counter, taking the period and window into account. fn measure(&self) -> f64 { *self.value.lock().expect("not poisoned") }}
pub(crate) const TELEMETRY_KEY_HOSTNAME: &str = "hostname";pub(crate) const TELEMETRY_KEY_PORT: &str = "port";pub(crate) const TELEMETRY_KEY_ALIAS: &str = "alias";
pub(crate) const TELEMETRY_COUNTER_SSH_CONNECTIONS: &str = "sandhole_ssh_connections";pub(crate) const TELEMETRY_COUNTER_HTTP_REQUESTS: &str = "sandhole_http_requests";pub(crate) const TELEMETRY_COUNTER_SNI_CONNECTIONS: &str = "sandhole_sni_connections";pub(crate) const TELEMETRY_COUNTER_ALIAS_CONNECTIONS: &str = "sandhole_alias_connections";pub(crate) const TELEMETRY_COUNTER_ADMIN_ALIAS_CONNECTIONS: &str = "sandhole_admin_alias_connections";pub(crate) const TELEMETRY_COUNTER_TCP_CONNECTIONS: &str = "sandhole_tcp_connections";pub(crate) const TELEMETRY_COUNTER_UDP_CONNECTIONS: &str = "sandhole_udp_connections";pub(crate) const TELEMETRY_GAUGE_USED_MEMORY: &str = "system_used_memory";pub(crate) const TELEMETRY_GAUGE_TOTAL_MEMORY: &str = "system_total_memory";pub(crate) const TELEMETRY_COUNTER_NETWORK_TX: &str = "system_network_tx";pub(crate) const TELEMETRY_COUNTER_NETWORK_RX: &str = "system_network_rx";
pub(crate) const TELEMETRY_GAUGE_SSH_CONNECTIONS_CURRENT: &str = "sandhole_ssh_connections_current";pub(crate) const TELEMETRY_GAUGE_SNI_CONNECTIONS_CURRENT: &str = "sandhole_sni_connections_current";pub(crate) const TELEMETRY_GAUGE_ALIAS_CONNECTIONS_CURRENT: &str = "sandhole_alias_connections_current";pub(crate) const TELEMETRY_GAUGE_ADMIN_ALIAS_CONNECTIONS_CURRENT: &str = "sandhole_admin_alias_connections_current";pub(crate) const TELEMETRY_GAUGE_TCP_CONNECTIONS_CURRENT: &str = "sandhole_tcp_connections_current";pub(crate) const TELEMETRY_GAUGE_UDP_CONNECTIONS_CURRENT: &str = "sandhole_udp_connections_current";pub(crate) const TELEMETRY_GAUGE_CPU_USAGE: &str = "system_cpu_usage";
pub(crate) const TELEMETRY_HISTOGRAM_HTTP_ELAPSED_TIME: &str = "sandhole_http_elapsed_time";
// Metadata to display on the admin interface.pub(crate) struct Telemetry { // Connections per minute for each SSH alias. ssh_connections_per_minute: DashMap<String, Arc<SlidingWindowCounter>, RandomState>, // Requests per minute for each HTTP host. http_requests_per_minute: DashMap<String, Arc<SlidingWindowCounter>, RandomState>, // Connections per minute for each SNI host. sni_connections_per_minute: DashMap<String, Arc<SlidingWindowCounter>, RandomState>, // Connections per minute for each local-forwarded alias. alias_connections_per_minute: DashMap<SockAddrAlias, Arc<SlidingWindowCounter>, RandomState>, // Connections per minute for each admin alias. admin_alias_connections_per_minute: DashMap<SockAddrAlias, Arc<SlidingWindowCounter>, RandomState>, // Connections per minute for each TCP port. tcp_connections_per_minute: DashMap<u16, Arc<SlidingWindowCounter>, RandomState>, // Connections per minute for each UDP port. udp_connections_per_minute: DashMap<u16, Arc<SlidingWindowCounter>, RandomState>, // Current connections for each SSH alias. ssh_connections_current: DashMap<String, Arc<TelemetryGauge>, RandomState>, // Current connections for each SNI host. sni_connections_current: DashMap<String, Arc<TelemetryGauge>, RandomState>, // Current connections for each local-forwarded alias. alias_connections_current: DashMap<SockAddrAlias, Arc<TelemetryGauge>, RandomState>, // Current connections for each admin alias. admin_alias_connections_current: DashMap<SockAddrAlias, Arc<TelemetryGauge>, RandomState>, // Current connections for each TCP port. tcp_connections_current: DashMap<u16, Arc<TelemetryGauge>, RandomState>, // Current connections for each UDP port. udp_connections_current: DashMap<u16, Arc<TelemetryGauge>, RandomState>, // Recorder for Prometheus metrics export. #[cfg(feature = "prometheus")] prometheus_recorder: Option<PrometheusRecorder>, // Join handle for the Prometheus upkeep task. #[cfg(feature = "prometheus")] _join_handle: DroppableHandle<()>,}
impl Telemetry { #[cfg_attr(not(feature = "prometheus"), allow(unused_variables))] pub(crate) fn new(enable_prometheus: bool) -> Self { #[cfg(feature = "prometheus")] let (prometheus_recorder, join_handle) = if enable_prometheus { let prometheus_recorder = PrometheusBuilder::new() .set_buckets_for_metric( metrics_exporter_prometheus::Matcher::Full( TELEMETRY_HISTOGRAM_HTTP_ELAPSED_TIME.to_string(), ), &[ 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 25.0, ], ) .expect("values should not be empty") .with_recommended_naming(true) .build_recorder(); let handle = prometheus_recorder.handle(); let join_handle = DroppableHandle(tokio::spawn(async move { loop { sleep(Duration::from_secs(60)).await; handle.run_upkeep(); } })); (Some(prometheus_recorder), join_handle) } else { (None, DroppableHandle(tokio::spawn(future::pending()))) };
Telemetry { ssh_connections_per_minute: DashMap::default(), http_requests_per_minute: DashMap::default(), sni_connections_per_minute: DashMap::default(), alias_connections_per_minute: DashMap::default(), admin_alias_connections_per_minute: DashMap::default(), tcp_connections_per_minute: DashMap::default(), udp_connections_per_minute: DashMap::default(), ssh_connections_current: DashMap::default(), sni_connections_current: DashMap::default(), alias_connections_current: DashMap::default(), admin_alias_connections_current: DashMap::default(), tcp_connections_current: DashMap::default(), udp_connections_current: DashMap::default(), #[cfg(feature = "prometheus")] prometheus_recorder, #[cfg(feature = "prometheus")] _join_handle: join_handle, } }
pub(crate) fn register_metrics(&self) { describe_counter!( TELEMETRY_COUNTER_SSH_CONNECTIONS, "Total connections for SSH aliases" ); describe_counter!( TELEMETRY_COUNTER_HTTP_REQUESTS, "Total requests for HTTP(S) hosts" ); describe_counter!( TELEMETRY_COUNTER_SNI_CONNECTIONS, "Total connections for SNI hosts" ); describe_counter!( TELEMETRY_COUNTER_ALIAS_CONNECTIONS, "Total connections for aliases" ); describe_counter!( TELEMETRY_COUNTER_ADMIN_ALIAS_CONNECTIONS, "Total connections for admin aliases" ); describe_counter!( TELEMETRY_COUNTER_TCP_CONNECTIONS, "Total connections for TCP ports" ); describe_counter!( TELEMETRY_COUNTER_UDP_CONNECTIONS, "Total connections for UDP ports" ); describe_counter!( TELEMETRY_COUNTER_NETWORK_TX, Unit::Bytes, "Network transmitted data" ); describe_counter!( TELEMETRY_COUNTER_NETWORK_RX, Unit::Bytes, "Network received data" );
describe_gauge!( TELEMETRY_GAUGE_SSH_CONNECTIONS_CURRENT, "Current requests for SSH aliases" ); describe_gauge!( TELEMETRY_GAUGE_SNI_CONNECTIONS_CURRENT, "Current requests for SNI hosts" ); describe_gauge!( TELEMETRY_GAUGE_ALIAS_CONNECTIONS_CURRENT, "Current requests for aliases" ); describe_gauge!( TELEMETRY_GAUGE_TCP_CONNECTIONS_CURRENT, "Current requests for TCP ports" ); describe_gauge!( TELEMETRY_GAUGE_UDP_CONNECTIONS_CURRENT, "Current requests for UDP ports" ); describe_gauge!(TELEMETRY_GAUGE_CPU_USAGE, Unit::Percent, "Total CPU usage"); describe_gauge!(TELEMETRY_GAUGE_USED_MEMORY, Unit::Bytes, "Used memory"); describe_gauge!(TELEMETRY_GAUGE_TOTAL_MEMORY, Unit::Bytes, "Total memory");
describe_histogram!( TELEMETRY_HISTOGRAM_HTTP_ELAPSED_TIME, Unit::Seconds, "Time to handle an HTTP request" ); }
#[cfg(feature = "prometheus")] pub(crate) fn prometheus_handle(&self) -> Option<PrometheusHandle> { self.prometheus_recorder .as_ref() .map(|recorder| recorder.handle()) }
pub(crate) fn get_ssh_connections_per_minute(&self) -> HashMap<String, u64, RandomState> { self.ssh_connections_per_minute .iter() .map(|entry| (entry.key().clone(), entry.value().measure())) .collect() }
pub(crate) fn get_http_requests_per_minute(&self) -> HashMap<String, u64, RandomState> { self.http_requests_per_minute .iter() .map(|entry| (entry.key().clone(), entry.value().measure())) .collect() }
pub(crate) fn get_sni_connections_per_minute(&self) -> HashMap<String, u64, RandomState> { self.sni_connections_per_minute .iter() .map(|entry| (entry.key().clone(), entry.value().measure())) .collect() }
pub(crate) fn get_alias_connections_per_minute( &self, ) -> HashMap<SockAddrAlias, u64, RandomState> { self.alias_connections_per_minute .iter() .map(|entry| (entry.key().clone(), entry.value().measure())) .collect() }
pub(crate) fn get_admin_alias_connections_per_minute( &self, ) -> HashMap<SockAddrAlias, u64, RandomState> { self.admin_alias_connections_per_minute .iter() .map(|entry| (entry.key().clone(), entry.value().measure())) .collect() }
pub(crate) fn get_tcp_connections_per_minute(&self) -> HashMap<u16, u64, RandomState> { self.tcp_connections_per_minute .iter() .map(|entry| (*entry.key(), entry.value().measure())) .collect() }
pub(crate) fn get_udp_connections_per_minute(&self) -> HashMap<u16, u64, RandomState> { self.udp_connections_per_minute .iter() .map(|entry| (*entry.key(), entry.value().measure())) .collect() }
pub(crate) fn get_current_ssh_connections(&self) -> HashMap<String, f64, RandomState> { self.ssh_connections_current .iter() .map(|entry| (entry.key().clone(), entry.value().measure())) .collect() }
pub(crate) fn get_current_sni_connections(&self) -> HashMap<String, f64, RandomState> { self.sni_connections_current .iter() .map(|entry| (entry.key().clone(), entry.value().measure())) .collect() }
pub(crate) fn get_current_alias_connections(&self) -> HashMap<SockAddrAlias, f64, RandomState> { self.alias_connections_current .iter() .map(|entry| (entry.key().clone(), entry.value().measure())) .collect() }
pub(crate) fn get_current_admin_alias_connections( &self, ) -> HashMap<SockAddrAlias, f64, RandomState> { self.admin_alias_connections_current .iter() .map(|entry| (entry.key().clone(), entry.value().measure())) .collect() }
pub(crate) fn get_current_tcp_connections(&self) -> HashMap<u16, f64, RandomState> { self.tcp_connections_current .iter() .map(|entry| (*entry.key(), entry.value().measure())) .collect() }
pub(crate) fn get_current_udp_connections(&self) -> HashMap<u16, f64, RandomState> { self.udp_connections_current .iter() .map(|entry| (*entry.key(), entry.value().measure())) .collect() }
pub(crate) fn ssh_reactor(&self, aliases: Vec<String>) { let aliases: HashSet<String> = aliases.into_iter().collect(); self.ssh_connections_per_minute .retain(|key, _| aliases.contains(key)); self.ssh_connections_current .retain(|key, _| aliases.contains(key)); }
pub(crate) fn http_reactor(&self, hostnames: Vec<String>) { let hostnames: HashSet<String> = hostnames.into_iter().collect(); self.http_requests_per_minute .retain(|key, _| hostnames.contains(key)); }
pub(crate) fn sni_reactor(&self, hostnames: Vec<String>) { let hostnames: HashSet<String> = hostnames.into_iter().collect(); self.sni_connections_per_minute .retain(|key, _| hostnames.contains(key)); self.sni_connections_current .retain(|key, _| hostnames.contains(key)); }
pub(crate) fn alias_reactor(&self, aliases: Vec<SockAddrAlias>) { let aliases: HashSet<SockAddrAlias> = aliases.into_iter().collect(); self.alias_connections_per_minute .retain(|key, _| aliases.contains(key)); self.alias_connections_current .retain(|key, _| aliases.contains(key)); }
pub(crate) fn tcp_reactor(&self, ports: Vec<u16>) { let ports: HashSet<u16> = ports.into_iter().collect(); self.tcp_connections_per_minute .retain(|key, _| ports.contains(key)); self.tcp_connections_current .retain(|key, _| ports.contains(key)); }
pub(crate) fn udp_reactor(&self, ports: Vec<u16>) { let ports: HashSet<u16> = ports.into_iter().collect(); self.udp_connections_per_minute .retain(|key, _| ports.contains(key)); self.udp_connections_current .retain(|key, _| ports.contains(key)); }}
impl Recorder for Telemetry { #[cfg_attr(not(feature = "prometheus"), allow(unused_variables))] fn describe_counter( &self, key: metrics::KeyName, unit: Option<Unit>, description: metrics::SharedString, ) { #[cfg(feature = "prometheus")] self.prometheus_recorder .as_ref() .inspect(|recorder| recorder.describe_counter(key, unit, description)); }
#[cfg_attr(not(feature = "prometheus"), allow(unused_variables))] fn describe_gauge( &self, key: metrics::KeyName, unit: Option<Unit>, description: metrics::SharedString, ) { #[cfg(feature = "prometheus")] self.prometheus_recorder .as_ref() .inspect(|recorder| recorder.describe_gauge(key, unit, description)); }
#[cfg_attr(not(feature = "prometheus"), allow(unused_variables))] fn describe_histogram( &self, key: metrics::KeyName, unit: Option<Unit>, description: metrics::SharedString, ) { #[cfg(feature = "prometheus")] self.prometheus_recorder .as_ref() .inspect(|recorder| recorder.describe_histogram(key, unit, description)); }
fn register_counter( &self, key: &metrics::Key, #[cfg_attr(not(feature = "prometheus"), allow(unused_variables))] metadata: &metrics::Metadata<'_>, ) -> metrics::Counter { #[cfg(feature = "prometheus")] let prometheus_counter = self .prometheus_recorder .as_ref() .map(|recorder| recorder.register_counter(key, metadata)) .unwrap_or(metrics::Counter::noop()); #[cfg(not(feature = "prometheus"))] let prometheus_counter = metrics::Counter::noop(); let name = key.name(); let labels: Vec<(&str, &str)> = key .labels() .map(|label| (label.key(), label.value())) .sorted() .collect(); match name { TELEMETRY_COUNTER_SSH_CONNECTIONS => { for (key, value) in labels { if key == TELEMETRY_KEY_ALIAS { return metrics::Counter::from_arc(Arc::clone( self.ssh_connections_per_minute .entry(value.to_string()) .or_insert(Arc::new(SlidingWindowCounter::new( prometheus_counter, Duration::from_secs(60), ))) .value(), )); } } } TELEMETRY_COUNTER_HTTP_REQUESTS => { for (key, value) in labels { if key == TELEMETRY_KEY_HOSTNAME { return metrics::Counter::from_arc(Arc::clone( self.http_requests_per_minute .entry(value.to_string()) .or_insert(Arc::new(SlidingWindowCounter::new( prometheus_counter, Duration::from_secs(60), ))) .value(), )); } } } TELEMETRY_COUNTER_SNI_CONNECTIONS => { for (key, value) in labels { if key == TELEMETRY_KEY_HOSTNAME { return metrics::Counter::from_arc(Arc::clone( self.sni_connections_per_minute .entry(value.to_string()) .or_insert(Arc::new(SlidingWindowCounter::new( prometheus_counter, Duration::from_secs(60), ))) .value(), )); } } } TELEMETRY_COUNTER_ALIAS_CONNECTIONS => { for (key, value) in labels { if key == TELEMETRY_KEY_ALIAS { match value.parse::<SockAddrAlias>() { Ok(alias) => { return metrics::Counter::from_arc(Arc::clone( self.alias_connections_per_minute .entry(alias) .or_insert(Arc::new(SlidingWindowCounter::new( prometheus_counter, Duration::from_secs(60), ))) .value(), )); } Err(error) => { #[cfg(not(coverage_nightly))] tracing::warn!(alias = value, %error, "Invalid TCP alias in telemetry.") } } } } } TELEMETRY_COUNTER_ADMIN_ALIAS_CONNECTIONS => { for (key, value) in labels { if key == TELEMETRY_KEY_ALIAS { match value.parse::<SockAddrAlias>() { Ok(alias) => { return metrics::Counter::from_arc(Arc::clone( self.admin_alias_connections_per_minute .entry(alias) .or_insert(Arc::new(SlidingWindowCounter::new( prometheus_counter, Duration::from_secs(60), ))) .value(), )); } Err(error) => { #[cfg(not(coverage_nightly))] tracing::warn!(alias = value, %error, "Invalid admin alias in telemetry.") } } } } } TELEMETRY_COUNTER_TCP_CONNECTIONS => { for (key, value) in labels { if key == TELEMETRY_KEY_PORT { match value.parse::<u16>() { Ok(port) => { return metrics::Counter::from_arc(Arc::clone( self.tcp_connections_per_minute .entry(port) .or_insert(Arc::new(SlidingWindowCounter::new( prometheus_counter, Duration::from_secs(60), ))) .value(), )); } Err(error) => { #[cfg(not(coverage_nightly))] tracing::warn!(port = value, %error, "Invalid port in telemetry."); } } } } } TELEMETRY_COUNTER_UDP_CONNECTIONS => { for (key, value) in labels { if key == TELEMETRY_KEY_PORT { match value.parse::<u16>() { Ok(port) => { return metrics::Counter::from_arc(Arc::clone( self.udp_connections_per_minute .entry(port) .or_insert(Arc::new(SlidingWindowCounter::new( prometheus_counter, Duration::from_secs(60), ))) .value(), )); } Err(error) => { #[cfg(not(coverage_nightly))] tracing::warn!(port = value, %error, "Invalid port in telemetry."); } } } } } _ => (), } prometheus_counter }
fn register_gauge( &self, key: &metrics::Key, #[cfg_attr(not(feature = "prometheus"), allow(unused_variables))] metadata: &metrics::Metadata<'_>, ) -> metrics::Gauge { #[cfg(feature = "prometheus")] let prometheus_gauge = self .prometheus_recorder .as_ref() .map(|recorder| recorder.register_gauge(key, metadata)) .unwrap_or(metrics::Gauge::noop()); #[cfg(not(feature = "prometheus"))] let prometheus_gauge = metrics::Gauge::noop(); let name = key.name(); let labels: Vec<(&str, &str)> = key .labels() .map(|label| (label.key(), label.value())) .sorted() .collect(); match name { TELEMETRY_GAUGE_SSH_CONNECTIONS_CURRENT => { for (key, value) in labels { if key == TELEMETRY_KEY_ALIAS { return metrics::Gauge::from_arc(Arc::clone( self.ssh_connections_current .entry(value.to_string()) .or_insert(Arc::new(TelemetryGauge::new(prometheus_gauge))) .value(), )); } } } TELEMETRY_GAUGE_SNI_CONNECTIONS_CURRENT => { for (key, value) in labels { if key == TELEMETRY_KEY_HOSTNAME { return metrics::Gauge::from_arc(Arc::clone( self.sni_connections_current .entry(value.to_string()) .or_insert(Arc::new(TelemetryGauge::new(prometheus_gauge))) .value(), )); } } } TELEMETRY_GAUGE_ALIAS_CONNECTIONS_CURRENT => { for (key, value) in labels { if key == TELEMETRY_KEY_ALIAS { match value.parse::<SockAddrAlias>() { Ok(alias) => { return metrics::Gauge::from_arc(Arc::clone( self.alias_connections_current .entry(alias) .or_insert(Arc::new(TelemetryGauge::new(prometheus_gauge))) .value(), )); } Err(error) => { #[cfg(not(coverage_nightly))] tracing::warn!(alias = value, %error, "Invalid admin alias in telemetry.") } } } } } TELEMETRY_GAUGE_ADMIN_ALIAS_CONNECTIONS_CURRENT => { for (key, value) in labels { if key == TELEMETRY_KEY_ALIAS { match value.parse::<SockAddrAlias>() { Ok(alias) => { return metrics::Gauge::from_arc(Arc::clone( self.admin_alias_connections_current .entry(alias) .or_insert(Arc::new(TelemetryGauge::new(prometheus_gauge))) .value(), )); } Err(error) => { #[cfg(not(coverage_nightly))] tracing::warn!(alias = value, %error, "Invalid admin alias in telemetry.") } } } } } TELEMETRY_GAUGE_TCP_CONNECTIONS_CURRENT => { for (key, value) in labels { if key == TELEMETRY_KEY_PORT { match value.parse::<u16>() { Ok(port) => { return metrics::Gauge::from_arc(Arc::clone( self.tcp_connections_current .entry(port) .or_insert(Arc::new(TelemetryGauge::new(prometheus_gauge))) .value(), )); } Err(error) => { #[cfg(not(coverage_nightly))] tracing::warn!(port = value, %error, "Invalid port in telemetry."); } } } } } TELEMETRY_GAUGE_UDP_CONNECTIONS_CURRENT => { for (key, value) in labels { if key == TELEMETRY_KEY_PORT { match value.parse::<u16>() { Ok(port) => { return metrics::Gauge::from_arc(Arc::clone( self.udp_connections_current .entry(port) .or_insert(Arc::new(TelemetryGauge::new(prometheus_gauge))) .value(), )); } Err(error) => { #[cfg(not(coverage_nightly))] tracing::warn!(port = value, %error, "Invalid port in telemetry."); } } } } } _ => (), } prometheus_gauge }
fn register_histogram( &self, #[cfg_attr(not(feature = "prometheus"), allow(unused_variables))] key: &metrics::Key, #[cfg_attr(not(feature = "prometheus"), allow(unused_variables))] metadata: &metrics::Metadata<'_>, ) -> metrics::Histogram { #[cfg(feature = "prometheus")] { self.prometheus_recorder .as_ref() .map(|recorder| recorder.register_histogram(key, metadata)) .unwrap_or(metrics::Histogram::noop()) } #[cfg(not(feature = "prometheus"))] { metrics::Histogram::noop() } }}
#[cfg(test)]#[cfg_attr(coverage_nightly, coverage(off))]mod counter_tests { use std::{thread::sleep, time::Duration};
use metrics::{Counter, CounterFn};
use super::SlidingWindowCounter;
#[test_log::test] fn takes_measurements() { let counter = SlidingWindowCounter::new(Counter::noop(), Duration::from_secs(4)); assert_eq!(counter.measure(), 0); counter.increment(2); let measure_1 = counter.measure(); assert_eq!(measure_1, 2); counter.increment(2); let measure_2 = counter.measure(); assert_eq!(measure_2, 4); counter.absolute(6); let measure_2 = counter.measure(); assert_eq!(measure_2, 6); }
#[test_log::test] fn resets_on_moving_window() { let counter = SlidingWindowCounter::new(Counter::noop(), Duration::from_millis(200)); counter.increment(10); let measure_1 = counter.measure(); assert_eq!(measure_1, 10); sleep(Duration::from_millis(500)); let measure_2 = counter.measure(); assert_eq!(measure_2, 0); counter.increment(10); let measure_3 = counter.measure(); assert_eq!(measure_3, 10); }}