a2a_protocol_server/otel/telemetry/
prometheus.rs1use std::convert::Infallible;
31use std::net::{SocketAddr, TcpListener};
32use std::sync::Arc;
33use std::time::Duration;
34
35use bytes::Bytes;
36use http_body_util::Full;
37use hyper::body::Incoming;
38use hyper::{Method, Request, Response, StatusCode};
39use hyper_util::rt::{TokioIo, TokioTimer};
40use opentelemetry_prometheus::PrometheusExporter;
41use prometheus::{Registry, TextEncoder};
42
43use super::TelemetryError;
44use super::config::{Env, Notes};
45use super::runtime::ExportRuntime;
46
47const DEFAULT_PORT: u16 = 9464;
49
50const HEADER_TIMEOUT: Duration = Duration::from_secs(10);
52
53pub(super) const MAX_CONNECTIONS: usize = 16;
56
57pub(super) const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(30);
60
61pub(super) struct Started {
64 pub(super) reader: PrometheusExporter,
65 pub(super) addr: Option<SocketAddr>,
66 pub(super) scrape: PrometheusScrape,
67}
68
69#[derive(Clone)]
76pub struct PrometheusScrape {
77 registry: Registry,
78}
79
80impl std::fmt::Debug for PrometheusScrape {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 f.debug_struct("PrometheusScrape").finish_non_exhaustive()
83 }
84}
85
86impl PrometheusScrape {
87 pub const CONTENT_TYPE: &'static str = "text/plain; version=0.0.4; charset=utf-8";
89
90 pub fn render(&self) -> Result<String, TelemetryError> {
97 TextEncoder::new()
98 .encode_to_string(&self.registry.gather())
99 .map_err(|e| TelemetryError::Export(vec![format!("metrics: {e}")]))
100 }
101}
102
103fn port(env: &Env, notes: &Notes) -> u16 {
106 const PORT: &str = "OTEL_EXPORTER_PROMETHEUS_PORT";
107 let Some(value) = env(PORT) else {
108 return DEFAULT_PORT;
109 };
110 value.trim().parse::<u16>().unwrap_or_else(|_| {
111 notes.ignored(
112 PORT,
113 &value,
114 "is not a port number",
115 &format!("{DEFAULT_PORT} is used"),
116 );
117 DEFAULT_PORT
118 })
119}
120
121pub(super) fn start(
131 env: &Env,
132 runtime: &ExportRuntime,
133 notes: &Notes,
134 listen: bool,
135) -> Result<Started, TelemetryError> {
136 const HOST: &str = "OTEL_EXPORTER_PROMETHEUS_HOST";
137 const PORT: &str = "OTEL_EXPORTER_PROMETHEUS_PORT";
138 let registry = Registry::new();
139 let reader = opentelemetry_prometheus::exporter()
140 .with_registry(registry.clone())
141 .build()
142 .map_err(|e| {
143 TelemetryError::config("OTEL_METRICS_EXPORTER", "prometheus", e.to_string())
144 })?;
145 let scrape = PrometheusScrape {
146 registry: registry.clone(),
147 };
148 if !listen {
149 return Ok(Started {
150 reader,
151 addr: None,
152 scrape,
153 });
154 }
155 let host = env(HOST).unwrap_or_else(|| "localhost".to_owned());
156 let port = port(env, notes);
157 let listener = TcpListener::bind((host.as_str(), port)).map_err(|e| {
160 TelemetryError::config(
161 PORT,
162 &format!("{host}:{port}"),
163 format!("cannot listen there: {e}; set {HOST} and {PORT}"),
164 )
165 })?;
166 listener
167 .set_nonblocking(true)
168 .map_err(|e| TelemetryError::config(PORT, &port.to_string(), e.to_string()))?;
169 let addr = listener
170 .local_addr()
171 .map_err(|e| TelemetryError::config(PORT, &port.to_string(), e.to_string()))?;
172 drop(runtime.handle().spawn(serve(listener, registry)));
173 Ok(Started {
174 reader,
175 addr: Some(addr),
176 scrape,
177 })
178}
179
180async fn serve(listener: TcpListener, registry: Registry) {
181 let Ok(listener) = tokio::net::TcpListener::from_std(listener) else {
182 return;
183 };
184 let slots = Arc::new(tokio::sync::Semaphore::new(MAX_CONNECTIONS));
185 loop {
186 let Ok(slot) = Arc::clone(&slots).acquire_owned().await else {
189 return;
190 };
191 let Ok((stream, _)) = listener.accept().await else {
192 tokio::time::sleep(Duration::from_millis(100)).await;
194 continue;
195 };
196 let registry = registry.clone();
197 drop(tokio::spawn(async move {
198 let _slot = slot;
199 let service = hyper::service::service_fn(move |req: Request<Incoming>| {
200 let response = respond(®istry, &req);
201 async move { Ok::<_, Infallible>(response) }
202 });
203 let connection = hyper::server::conn::http1::Builder::new()
204 .timer(TokioTimer::new())
205 .header_read_timeout(HEADER_TIMEOUT)
206 .keep_alive(false)
207 .serve_connection(TokioIo::new(stream), service);
208 let _ = tokio::time::timeout(EXCHANGE_TIMEOUT, connection).await;
209 }));
210 }
211}
212
213fn plain(status: StatusCode, body: &'static str) -> Response<Full<Bytes>> {
214 let mut response = Response::new(Full::new(Bytes::from_static(body.as_bytes())));
215 *response.status_mut() = status;
216 response
217}
218
219fn respond(registry: &Registry, req: &Request<Incoming>) -> Response<Full<Bytes>> {
222 if req.uri().path() != "/metrics" {
223 return plain(StatusCode::NOT_FOUND, "the metrics are at /metrics\n");
224 }
225 if req.method() != Method::GET && req.method() != Method::HEAD {
226 let mut refused = plain(StatusCode::METHOD_NOT_ALLOWED, "GET /metrics\n");
227 refused.headers_mut().insert(
228 hyper::header::ALLOW,
229 hyper::header::HeaderValue::from_static("GET, HEAD"),
230 );
231 return refused;
232 }
233 TextEncoder::new()
234 .encode_to_string(®istry.gather())
235 .map_or_else(
236 |_| {
237 plain(
238 StatusCode::INTERNAL_SERVER_ERROR,
239 "could not encode the metrics\n",
240 )
241 },
242 |text| {
243 let mut response = Response::new(Full::new(Bytes::from(text)));
244 response.headers_mut().insert(
245 hyper::header::CONTENT_TYPE,
246 hyper::header::HeaderValue::from_static(PrometheusScrape::CONTENT_TYPE),
247 );
248 response
249 },
250 )
251}
252
253#[cfg(test)]
254mod tests;