-
-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(shulker-kube-utils): use axum in metrics
- Loading branch information
1 parent
78258f8
commit 9608cfc
Showing
1 changed file
with
22 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,43 @@ | ||
use actix_web::{get, HttpRequest, HttpResponse, Responder}; | ||
use actix_web::{middleware, App, HttpServer}; | ||
use axum::body::Body; | ||
use axum::http::StatusCode; | ||
use axum::response::Response; | ||
use axum::{routing::get, Router}; | ||
use tracing::*; | ||
|
||
pub fn create_http_server(addr: String) -> Result<tokio::task::JoinHandle<()>, anyhow::Error> { | ||
let task = tokio::spawn(async move { | ||
HttpServer::new(move || { | ||
App::new() | ||
.wrap(middleware::Logger::default().exclude("/healthz")) | ||
.service(healthz) | ||
.service(metrics) | ||
}) | ||
.bind(addr) | ||
.unwrap() | ||
.shutdown_timeout(5) | ||
.run() | ||
.await | ||
.unwrap() | ||
let router = Router::new() | ||
.route("/healthz", get(healthz)) | ||
.route("/metrics", get(metrics)); | ||
|
||
let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); | ||
|
||
axum::serve(listener, router).await.unwrap() | ||
}); | ||
|
||
Ok(task) | ||
} | ||
|
||
#[get("/healthz")] | ||
async fn healthz(_: HttpRequest) -> impl Responder { | ||
HttpResponse::Ok().body("ok") | ||
async fn healthz() -> (StatusCode, &'static str) { | ||
(StatusCode::OK, "ok") | ||
} | ||
|
||
#[get("/metrics")] | ||
async fn metrics(_: HttpRequest) -> impl Responder { | ||
async fn metrics() -> Response { | ||
let encoder = prometheus::TextEncoder::new(); | ||
let metric_families = prometheus::gather(); | ||
let metric_str = encoder.encode_to_string(&metric_families); | ||
|
||
match metric_str { | ||
Ok(metric_str) => HttpResponse::Ok() | ||
.content_type("application/json") | ||
.body(metric_str), | ||
Ok(metric_str) => Response::builder() | ||
.status(StatusCode::OK) | ||
.body(Body::from(metric_str)) | ||
.unwrap(), | ||
Err(e) => { | ||
error!("failed to encode prometheus metrics: {}", e); | ||
HttpResponse::InternalServerError().finish() | ||
Response::builder() | ||
.status(StatusCode::INTERNAL_SERVER_ERROR) | ||
.body(Body::from("failed to encode prometheus metrics")) | ||
.unwrap() | ||
} | ||
} | ||
} |