| 1 |
// Copyright (C) 2024 Advanced Micro Devices. All rights reserved. |
| 2 |
// |
| 3 |
// Permission is hereby granted, free of charge, to any person obtaining a copy of |
| 4 |
// this software and associated documentation files (the "Software"), to deal in |
| 5 |
// the Software without restriction, including without limitation the rights to |
| 6 |
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of |
| 7 |
// the Software, and to permit persons to whom the Software is furnished to do so, |
| 8 |
// subject to the following conditions: |
| 9 |
// |
| 10 |
// The above copyright notice and this permission notice shall be included in all |
| 11 |
// copies or substantial portions of the Software. |
| 12 |
// |
| 13 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS |
| 15 |
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR |
| 16 |
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER |
| 17 |
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN |
| 18 |
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 19 |
// |
| 20 |
|
| 21 |
use crate::amdsmi_collectors::AmdsmiCollectors; |
| 22 |
use axum::response::{IntoResponse, Response}; |
| 23 |
use axum::{routing::get, Router}; |
| 24 |
use hyper::Server; |
| 25 |
use prometheus_client::encoding::text::encode; |
| 26 |
use prometheus_client::registry::Registry; |
| 27 |
use std::net::SocketAddr; |
| 28 |
use std::sync::Arc; |
| 29 |
use tokio::sync::Mutex; |
| 30 |
|
| 31 |
async fn serve_req(registry: Arc<Mutex<Registry>>) -> impl IntoResponse { |
| 32 |
let mut buffer = String::new(); |
| 33 |
let registry = registry.lock().await; |
| 34 |
encode(&mut buffer, &*registry).unwrap(); |
| 35 |
Response::builder() |
| 36 |
.header("Content-Type", "text/plain; version=0.0.4") |
| 37 |
.body(buffer) |
| 38 |
.unwrap() |
| 39 |
} |
| 40 |
|
| 41 |
pub async fn run_http_server(collectors: &Arc<Mutex<AmdsmiCollectors>>, addr: SocketAddr) { |
| 42 |
let app = Router::new().route( |
| 43 |
"/metrics", |
| 44 |
get({ |
| 45 |
let collectors = Arc::clone(&collectors); |
| 46 |
move || { |
| 47 |
let collectors = Arc::clone(&collectors); |
| 48 |
async move { |
| 49 |
let mut collectors = collectors.lock().await; |
| 50 |
let registry = Arc::new(Mutex::new(collectors.run_collect())); |
| 51 |
serve_req(registry).await |
| 52 |
} |
| 53 |
} |
| 54 |
}), |
| 55 |
); |
| 56 |
|
| 57 |
println!("Listening on http://{}", addr); |
| 58 |
|
| 59 |
Server::bind(&addr) |
| 60 |
.serve(app.into_make_service()) |
| 61 |
.await |
| 62 |
.unwrap(); |
| 63 |
} |