-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathprometheus.rs
More file actions
151 lines (125 loc) · 4.03 KB
/
Copy pathprometheus.rs
File metadata and controls
151 lines (125 loc) · 4.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
use std::sync::LazyLock;
use anyhow::Result;
use axum::{
Router,
http::{StatusCode, header::CONTENT_TYPE},
response::IntoResponse,
routing::get,
};
use prometheus::{
Encoder, IntCounter, IntGauge, TextEncoder, register_int_counter, register_int_gauge,
};
use tokio::net::TcpListener;
use crate::{
config::Config,
service::Transport,
statistics::{Counts, Number, Stats},
};
// The `register_int_counter` macro would be too long if written out in full,
// with too many line breaks after formatting, and this is wrapped directly into
// a macro again.
macro_rules! counter {
($prefix:expr, $operation:expr, $dst:expr) => {
register_int_counter!(
format!("{}_{}_{}", $prefix, $operation, $dst),
format!("The {} amount of {} {}", $prefix, $dst, $operation)
)
};
}
pub static METRICS: LazyLock<Metrics> = LazyLock::new(Metrics::default);
impl Number for IntCounter {
fn add(&self, value: usize) {
self.inc_by(value as u64);
}
fn get(&self) -> usize {
IntCounter::get(self) as usize
}
}
impl Counts<IntCounter> {
fn new(prefix: &str) -> Result<Self> {
Ok(Self {
received_bytes: counter!(prefix, "received", "bytes")?,
send_bytes: counter!(prefix, "sent", "bytes")?,
received_pkts: counter!(prefix, "received", "packets")?,
send_pkts: counter!(prefix, "sent", "packets")?,
error_pkts: counter!(prefix, "error", "packets")?,
})
}
}
/// Summarized metrics data for Global/TCP/UDP.
pub struct Metrics {
pub allocated: IntGauge,
pub total: Counts<IntCounter>,
pub tcp: Counts<IntCounter>,
pub udp: Counts<IntCounter>,
}
impl Default for Metrics {
fn default() -> Self {
Self::new().expect("Unable to initialize Prometheus metrics data!")
}
}
impl Metrics {
fn new() -> Result<Self> {
Ok(Self {
total: Counts::new("total")?,
tcp: Counts::new("tcp")?,
udp: Counts::new("udp")?,
allocated: register_int_gauge!(
"allocated",
"The number of allocated ports, count = 16383"
)?,
})
}
pub fn add(&self, transport: Transport, payload: &Stats) {
self.total.add(payload);
if transport == Transport::Tcp {
self.tcp.add(payload);
} else {
self.udp.add(payload);
}
}
}
/// Generate prometheus metrics data that externally needs to be exposed to
/// the `/metrics` route.
fn generate_metrics(buf: &mut Vec<u8>) -> Result<()> {
TextEncoder::new().encode(&prometheus::gather(), buf)?;
Ok(())
}
pub async fn start_server(config: Config) -> Result<()> {
if let Some(config) = config.prometheus {
let mut metrics_bytes = Vec::with_capacity(4096);
let app = Router::new().route(
"/metrics",
get(|| async move {
metrics_bytes.clear();
if generate_metrics(&mut metrics_bytes).is_err() {
StatusCode::INTERNAL_SERVER_ERROR.into_response()
} else {
([(CONTENT_TYPE, "text/plain")], metrics_bytes).into_response()
}
}),
);
#[cfg(feature = "ssl")]
if let Some(ssl) = &config.ssl {
let server = axum_server::bind_rustls(
config.listen,
axum_server::tls_rustls::RustlsConfig::from_pem_chain_file(
ssl.certificate_chain.clone(),
ssl.private_key.clone(),
)
.await?,
);
log::info!("prometheus server listening={:?}", config.listen);
server.serve(app.into_make_service()).await?;
return Ok(());
}
{
let listener = TcpListener::bind(config.listen).await?;
log::info!("prometheus server listening={:?}", config.listen);
axum::serve(listener, app).await?;
}
} else {
std::future::pending().await
};
Ok(())
}