Support aggregating engine metrics in sgl-router (#11456)
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
use anyhow::ensure;
|
||||
use openmetrics_parser::{MetricFamily, MetricsExposition, PrometheusType, PrometheusValue};
|
||||
use tracing::warn;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MetricPack {
|
||||
pub labels: Vec<(String, String)>,
|
||||
pub metrics_text: String,
|
||||
}
|
||||
|
||||
type PrometheusExposition = MetricsExposition<PrometheusType, PrometheusValue>;
|
||||
type PrometheusFamily = MetricFamily<PrometheusType, PrometheusValue>;
|
||||
|
||||
/// Aggregate Prometheus metrics scraped from multiple sources into a unified one
|
||||
pub fn aggregate_metrics(metric_packs: Vec<MetricPack>) -> anyhow::Result<String> {
|
||||
let mut expositions = vec![];
|
||||
for metric_pack in metric_packs {
|
||||
let metrics_text = &metric_pack.metrics_text;
|
||||
// Hacky workaround since the parser do not understand `:`, should improve later
|
||||
let metrics_text = metrics_text.replace(":", "_");
|
||||
|
||||
let exposition = match openmetrics_parser::prometheus::parse_prometheus(&metrics_text) {
|
||||
Ok(x) => x,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"aggregate_metrics error when parsing text: pack={:?} err={:?}",
|
||||
metric_pack, err
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let exposition = transform_metrics(exposition, &metric_pack.labels);
|
||||
expositions.push(exposition);
|
||||
}
|
||||
|
||||
let text = try_reduce(expositions.into_iter(), merge_exposition)?
|
||||
.map(|x| format!("{x}"))
|
||||
.unwrap_or_default();
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
fn transform_metrics(
|
||||
mut exposition: PrometheusExposition,
|
||||
extra_labels: &[(String, String)],
|
||||
) -> PrometheusExposition {
|
||||
for family in exposition.families.values_mut() {
|
||||
*family = family.with_labels(extra_labels.iter().map(|(k, v)| (k.as_str(), v.as_str())));
|
||||
}
|
||||
exposition
|
||||
}
|
||||
|
||||
fn merge_exposition(
|
||||
a: PrometheusExposition,
|
||||
b: PrometheusExposition,
|
||||
) -> anyhow::Result<PrometheusExposition> {
|
||||
let mut ans = a;
|
||||
for (name, family_b) in b.families.into_iter() {
|
||||
let family_merged = if let Some(family_a) = ans.families.remove(&name) {
|
||||
merge_family(family_a, family_b)?
|
||||
} else {
|
||||
family_b
|
||||
};
|
||||
ans.families.insert(name, family_merged);
|
||||
}
|
||||
Ok(ans)
|
||||
}
|
||||
|
||||
fn merge_family(a: PrometheusFamily, b: PrometheusFamily) -> anyhow::Result<PrometheusFamily> {
|
||||
ensure!(
|
||||
a.get_label_names() == b.get_label_names(),
|
||||
"Label names should agree a={:?} b={:?}",
|
||||
a.get_label_names(),
|
||||
b.get_label_names()
|
||||
);
|
||||
a.with_samples(b.into_iter_samples())
|
||||
.map_err(|e| anyhow::anyhow!("failed to merge samples: {e:?}"))
|
||||
}
|
||||
|
||||
pub fn try_reduce<I, T, E, F>(iterable: I, f: F) -> Result<Option<T>, E>
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
F: FnMut(T, T) -> Result<T, E>,
|
||||
{
|
||||
let mut it = iterable.into_iter();
|
||||
let first = match it.next() {
|
||||
None => return Ok(None),
|
||||
Some(x) => x,
|
||||
};
|
||||
|
||||
Ok(Some(it.try_fold(first, f)?))
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
pub mod circuit_breaker;
|
||||
pub mod error;
|
||||
pub mod job_queue;
|
||||
pub mod metrics_aggregator;
|
||||
pub mod retry;
|
||||
pub mod token_bucket;
|
||||
pub mod worker;
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
|
||||
use std::{collections::HashMap, sync::Arc, time::Duration};
|
||||
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use futures::future;
|
||||
use http::{Method, StatusCode};
|
||||
use serde_json::Value;
|
||||
use tokio::{
|
||||
sync::{watch, Mutex},
|
||||
@@ -14,7 +16,7 @@ use tokio::{
|
||||
use tracing::{debug, error, info, warn};
|
||||
|
||||
use crate::{
|
||||
core::{ConnectionMode, WorkerRegistry, WorkerType},
|
||||
core::{metrics_aggregator::MetricPack, ConnectionMode, WorkerRegistry, WorkerType},
|
||||
policies::PolicyRegistry,
|
||||
protocols::worker_spec::{FlushCacheResult, WorkerLoadInfo, WorkerLoadsResult},
|
||||
};
|
||||
@@ -234,6 +236,90 @@ impl WorkerManager {
|
||||
failed,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_engine_metrics(
|
||||
worker_registry: &WorkerRegistry,
|
||||
client: &reqwest::Client,
|
||||
) -> Response {
|
||||
let engine_responses =
|
||||
match Self::fan_out_simple_request(worker_registry, client, "metrics", Method::GET)
|
||||
.await
|
||||
{
|
||||
Ok(x) => x,
|
||||
Err(e) => return e,
|
||||
};
|
||||
let engine_responses = engine_responses
|
||||
.into_iter()
|
||||
.map(|(worker_base_url, metrics_text)| MetricPack {
|
||||
labels: vec![("worker_addr".into(), worker_base_url)],
|
||||
metrics_text,
|
||||
})
|
||||
.collect();
|
||||
let text = match crate::core::metrics_aggregator::aggregate_metrics(engine_responses) {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
let error_msg = format!("Failed to aggregate metrics: {}", e);
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, error_msg).into_response();
|
||||
}
|
||||
};
|
||||
(StatusCode::OK, text).into_response()
|
||||
}
|
||||
|
||||
async fn fan_out_simple_request(
|
||||
worker_registry: &WorkerRegistry,
|
||||
client: &reqwest::Client,
|
||||
endpoint: &str,
|
||||
method: Method,
|
||||
) -> Result<Vec<(String, String)>, Response> {
|
||||
let workers = worker_registry.get_all();
|
||||
if workers.is_empty() {
|
||||
return Err((StatusCode::SERVICE_UNAVAILABLE, "No available workers").into_response());
|
||||
}
|
||||
|
||||
let mut responses = vec![];
|
||||
// May do parallel requests later
|
||||
for worker in workers {
|
||||
let worker_url = worker.url().to_string();
|
||||
|
||||
let url = format!("{}/{}", worker_url, endpoint);
|
||||
let mut request_builder = match method {
|
||||
Method::GET => client.get(url),
|
||||
Method::POST => client.post(url),
|
||||
_ => {
|
||||
return Err((
|
||||
StatusCode::METHOD_NOT_ALLOWED,
|
||||
"Unsupported method for simple routing",
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(api_key) = worker.api_key() {
|
||||
request_builder =
|
||||
request_builder.header("Authorization", format!("Bearer {}", api_key));
|
||||
}
|
||||
|
||||
match request_builder.send().await {
|
||||
Ok(res) => {
|
||||
let status = StatusCode::from_u16(res.status().as_u16())
|
||||
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
match res.text().await {
|
||||
Ok(body_text) => {
|
||||
if status.is_success() {
|
||||
responses.push((worker_url, body_text));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("fan_out_simple_request failed when reading text: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => warn!("fan_out_simple_request failed when sending: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(responses)
|
||||
}
|
||||
}
|
||||
|
||||
/// Load monitoring service that periodically fetches worker loads
|
||||
|
||||
Reference in New Issue
Block a user