From ee0b71a4accfc42929fdfaf1664c0fb96b62b24a Mon Sep 17 00:00:00 2001 From: Valentin Brandl Date: Sat, 8 Oct 2022 01:28:32 +0200 Subject: [PATCH] Start second server on different port for metrics endpoint (#1444) * Start second server on different port for metrics endpoint * Don't track metrics on metrics server --- examples/prometheus-metrics/src/main.rs | 63 +++++++++++++++++-------- 1 file changed, 44 insertions(+), 19 deletions(-) diff --git a/examples/prometheus-metrics/src/main.rs b/examples/prometheus-metrics/src/main.rs index 1152b3c7..5ab3fbdd 100644 --- a/examples/prometheus-metrics/src/main.rs +++ b/examples/prometheus-metrics/src/main.rs @@ -23,6 +23,46 @@ use std::{ }; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; +fn metrics_app() -> Router { + let recorder_handle = setup_metrics_recorder(); + Router::new().route("/metrics", get(move || ready(recorder_handle.render()))) +} + +fn main_app() -> Router { + Router::new() + .route("/fast", get(|| async {})) + .route( + "/slow", + get(|| async { + tokio::time::sleep(Duration::from_secs(1)).await; + }), + ) + .route_layer(middleware::from_fn(track_metrics)) +} + +async fn start_main_server() { + let app = main_app(); + + let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); + tracing::debug!("listening on {}", addr); + axum::Server::bind(&addr) + .serve(app.into_make_service()) + .await + .unwrap() +} + +async fn start_metrics_server() { + let app = metrics_app(); + + // NOTE: expose metrics enpoint on a different port + let addr = SocketAddr::from(([127, 0, 0, 1], 3001)); + tracing::debug!("listening on {}", addr); + axum::Server::bind(&addr) + .serve(app.into_make_service()) + .await + .unwrap() +} + #[tokio::main] async fn main() { tracing_subscriber::registry() @@ -33,25 +73,10 @@ async fn main() { .with(tracing_subscriber::fmt::layer()) .init(); - let recorder_handle = setup_metrics_recorder(); - - let app = Router::new() - .route("/fast", get(|| async {})) - .route( - "/slow", - get(|| async { - tokio::time::sleep(Duration::from_secs(1)).await; - }), - ) - .route("/metrics", get(move || ready(recorder_handle.render()))) - .route_layer(middleware::from_fn(track_metrics)); - - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) - .await - .unwrap(); + // The `/metrics` endpoint should not be publicly available. If behind a reverse proxy, this + // can be achieved by rejecting requests to `/metrics`. In this example, a second server is + // started on another port to expose `/metrics`. + let (_main_server, _metrics_server) = tokio::join!(start_main_server(), start_metrics_server()); } fn setup_metrics_recorder() -> PrometheusHandle {