Add Baedernames to metrics output

This commit is contained in:
clerie 2024-07-20 19:26:59 +02:00
parent 5abbe686cf
commit 72fc8fb588

View File

@ -1,4 +1,5 @@
use axum::{ use axum::{
extract::State,
routing::get, routing::get,
Router, Router,
}; };
@ -61,6 +62,10 @@ async fn get_baeder_names() -> Result<HashMap<String, String>, String> {
} }
#[derive(Clone)]
struct AppState {
baedernames: HashMap<String, String>,
}
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
@ -92,14 +97,20 @@ async fn main() {
let baedernames = get_baeder_names().await.unwrap_or(HashMap::new()); let baedernames = get_baeder_names().await.unwrap_or(HashMap::new());
println!("Baedernames:"); println!("Baedernames:");
for (id, name) in baedernames { for (id, name) in &baedernames {
println!("{id}: {name}"); println!("{id}: {name}");
} }
println!(""); println!("");
let state = AppState {
baedernames,
};
let app = Router::new() let app = Router::new()
.route("/", get(route_index)) .route("/", get(route_index))
.route("/metrics", get(route_metrics)); .route("/metrics", get(route_metrics))
.with_state(state);
let listener = tokio::net::TcpListener::bind(listen).await.unwrap(); let listener = tokio::net::TcpListener::bind(listen).await.unwrap();
println!("Server listening on: http://{}", listener.local_addr().unwrap()); println!("Server listening on: http://{}", listener.local_addr().unwrap());
@ -111,7 +122,9 @@ async fn route_index() -> String {
return String::from("Prometheus exporter for Berlinerbaeder occupancy"); return String::from("Prometheus exporter for Berlinerbaeder occupancy");
} }
async fn route_metrics() -> Result<String, String> { async fn route_metrics(
State(state): State<AppState>,
) -> Result<String, String> {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let trafficdata_req = client.get(String::from("https://www.berlinerbaeder.de/traffic/trafficdata.json")) let trafficdata_req = client.get(String::from("https://www.berlinerbaeder.de/traffic/trafficdata.json"))
.send().await .send().await
@ -130,7 +143,7 @@ async fn route_metrics() -> Result<String, String> {
let mut out = String::new(); let mut out = String::new();
for bad in trafficdata { for bad in trafficdata {
out.push_str(&format!("berlinerbaeder_occupation{{bad=\"{}\"}} {}\n", bad.id, bad.counter.unwrap_or(-1))); out.push_str(&format!("berlinerbaeder_occupation{{bad=\"{}\" badname=\"{}\"}} {}\n", bad.id, state.baedernames.get(&bad.id).unwrap_or(&String::new()), bad.counter.unwrap_or(-1)));
} }
return Ok(out); return Ok(out);