-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmetrics_server.rs
45 lines (36 loc) · 1.2 KB
/
metrics_server.rs
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
use hyper::{
header::CONTENT_TYPE,
service::{make_service_fn, service_fn},
Body, Request, Response, Server, StatusCode,
};
use prometheus::{self, Encoder, TextEncoder};
// start the warp server to provide the metrics
pub async fn start_server(port: u16) {
let addr = ([0, 0, 0, 0], port).into();
tracing::info!(?addr, "serving prometheus");
Server::bind(&addr)
.serve(make_service_fn(|_| async {
Ok::<_, hyper::Error>(service_fn(serve_req))
}))
.await
.unwrap()
}
async fn serve_req(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
if req.uri().path() != "/metrics" {
let response = Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap();
return Ok(response);
}
let encoder = TextEncoder::new();
let metric_families = prometheus::gather();
let mut buffer = Vec::with_capacity(4096);
encoder.encode(&metric_families, &mut buffer).unwrap();
let response = Response::builder()
.status(StatusCode::OK)
.header(CONTENT_TYPE, encoder.format_type())
.body(Body::from(buffer))
.unwrap();
Ok(response)
}