// 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 .
#[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>,
// 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,
}
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, RandomState>,
// Requests per minute for each HTTP host.
http_requests_per_minute: DashMap, RandomState>,
// Connections per minute for each SNI host.
sni_connections_per_minute: DashMap, RandomState>,
// Connections per minute for each local-forwarded alias.
alias_connections_per_minute: DashMap, RandomState>,
// Connections per minute for each admin alias.
admin_alias_connections_per_minute:
DashMap, RandomState>,
// Connections per minute for each TCP port.
tcp_connections_per_minute: DashMap, RandomState>,
// Connections per minute for each UDP port.
udp_connections_per_minute: DashMap, RandomState>,
// Current connections for each SSH alias.
ssh_connections_current: DashMap, RandomState>,
// Current connections for each SNI host.
sni_connections_current: DashMap, RandomState>,
// Current connections for each local-forwarded alias.
alias_connections_current: DashMap, RandomState>,
// Current connections for each admin alias.
admin_alias_connections_current: DashMap, RandomState>,
// Current connections for each TCP port.
tcp_connections_current: DashMap, RandomState>,
// Current connections for each UDP port.
udp_connections_current: DashMap, RandomState>,
// Recorder for Prometheus metrics export.
#[cfg(feature = "prometheus")]
prometheus_recorder: Option,
// 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 {
self.prometheus_recorder
.as_ref()
.map(|recorder| recorder.handle())
}
pub(crate) fn get_ssh_connections_per_minute(&self) -> HashMap {
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 {
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 {
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 {
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 {
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 {
self.tcp_connections_per_minute
.iter()
.map(|entry| (*entry.key(), entry.value().measure()))
.collect()
}
pub(crate) fn get_udp_connections_per_minute(&self) -> HashMap {
self.udp_connections_per_minute
.iter()
.map(|entry| (*entry.key(), entry.value().measure()))
.collect()
}
pub(crate) fn get_current_ssh_connections(&self) -> HashMap {
self.ssh_connections_current
.iter()
.map(|entry| (entry.key().clone(), entry.value().measure()))
.collect()
}
pub(crate) fn get_current_sni_connections(&self) -> HashMap {
self.sni_connections_current
.iter()
.map(|entry| (entry.key().clone(), entry.value().measure()))
.collect()
}
pub(crate) fn get_current_alias_connections(&self) -> HashMap {
self.alias_connections_current
.iter()
.map(|entry| (entry.key().clone(), entry.value().measure()))
.collect()
}
pub(crate) fn get_current_admin_alias_connections(
&self,
) -> HashMap {
self.admin_alias_connections_current
.iter()
.map(|entry| (entry.key().clone(), entry.value().measure()))
.collect()
}
pub(crate) fn get_current_tcp_connections(&self) -> HashMap {
self.tcp_connections_current
.iter()
.map(|entry| (*entry.key(), entry.value().measure()))
.collect()
}
pub(crate) fn get_current_udp_connections(&self) -> HashMap {
self.udp_connections_current
.iter()
.map(|entry| (*entry.key(), entry.value().measure()))
.collect()
}
pub(crate) fn ssh_reactor(&self, aliases: Vec) {
let aliases: HashSet = 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) {
let hostnames: HashSet = hostnames.into_iter().collect();
self.http_requests_per_minute
.retain(|key, _| hostnames.contains(key));
}
pub(crate) fn sni_reactor(&self, hostnames: Vec) {
let hostnames: HashSet = 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) {
let aliases: HashSet = 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) {
let ports: HashSet = 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) {
let ports: HashSet = 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,
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,
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,
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::() {
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::() {
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::() {
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::() {
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::() {
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::() {
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::() {
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::() {
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);
}
}