Skip to content

Commit

Permalink
Only serve metrics under /metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
Ongy committed Jan 7, 2025
1 parent dff27d4 commit ae52331
Showing 1 changed file with 29 additions and 18 deletions.
47 changes: 29 additions & 18 deletions src/metrics/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use bytes::Bytes;
use http_body_util::Full;
use hyper::service::service_fn;
use hyper::{body, Request, Response, Version};
use hyper::{body, Request, Response, StatusCode, Version};
use hyper_util::rt::TokioExecutor;

use opentelemetry_sdk::metrics::SdkMeterProvider;
Expand Down Expand Up @@ -38,25 +38,36 @@ pub async fn setup_metrics_provider(addr: &str) -> anyhow::Result<SdkMeterProvid
.serve_connection(
stream,
service_fn(|req: Request<body::Incoming>| {
// Create handler local registry for ownership
let registry = registry.clone();
async move {
let encoder = TextEncoder::new();
let metric_families = registry.gather();
let mut result = Vec::new();
if let Err(err) = encoder.encode(&metric_families, &mut result) {
error!("Failed to encode prometheus metrics: {:?}", err);
return Err("failed to create metrics export")
}
if req.uri().path() != "/metrics" {
return std::future::ready(
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Default::default()),
);
}

if req.version() != Version::HTTP_11 {
return std::future::ready(
Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Full::<Bytes>::from("Failed to generate metrics")),
);
}

if req.version() == Version::HTTP_11 {
Ok(Response::new(Full::<Bytes>::from(result)))
} else {
// Note: it's usually better to return a Response
// with an appropriate StatusCode instead of an Err.
Err("not HTTP/1.1, abort connection")
}
// Create handler local registry for ownership
let encoder = TextEncoder::new();
let metric_families = registry.gather();
let mut result = Vec::new();
if let Err(err) = encoder.encode(&metric_families, &mut result) {
error!("Failed to encode prometheus metrics: {:?}", err);
return std::future::ready(
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Full::<Bytes>::from("Failed to generate metrics")),
);
}

std::future::ready(Ok(Response::new(Full::<Bytes>::from(result))))
}),
)
.await;
Expand Down

0 comments on commit ae52331

Please sign in to comment.