1#[cfg(not(windows))]
16pub(crate) mod jemalloc;
17
18use std::task::{Context, Poll};
19use std::time::Instant;
20
21use axum::extract::{MatchedPath, Request};
22use axum::middleware::Next;
23use axum::response::IntoResponse;
24use lazy_static::lazy_static;
25use prometheus::{
26 Histogram, HistogramVec, IntCounter, IntCounterVec, IntGauge, register_histogram,
27 register_histogram_vec, register_int_counter, register_int_counter_vec, register_int_gauge,
28};
29use session::context::QueryContext;
30use tonic::body::Body;
31use tower::{Layer, Service};
32
33pub(crate) const METRIC_DB_LABEL: &str = "db";
34pub(crate) const METRIC_CODE_LABEL: &str = "code";
35pub(crate) const METRIC_TYPE_LABEL: &str = "type";
36pub(crate) const METRIC_PROTOCOL_LABEL: &str = "protocol";
37pub(crate) const METRIC_ERROR_COUNTER_LABEL_MYSQL: &str = "mysql";
38pub(crate) const METRIC_MYSQL_SUBPROTOCOL_LABEL: &str = "subprotocol";
39pub(crate) const METRIC_MYSQL_BINQUERY: &str = "binquery";
40pub(crate) const METRIC_MYSQL_TEXTQUERY: &str = "textquery";
41pub(crate) const METRIC_POSTGRES_SUBPROTOCOL_LABEL: &str = "subprotocol";
42pub(crate) const METRIC_POSTGRES_SIMPLE_QUERY: &str = "simple";
43pub(crate) const METRIC_POSTGRES_EXTENDED_QUERY: &str = "extended";
44pub(crate) const METRIC_METHOD_LABEL: &str = "method";
45pub(crate) const METRIC_PATH_LABEL: &str = "path";
46pub(crate) const METRIC_RESULT_LABEL: &str = "result";
47pub(crate) const METRIC_VERSION_LABEL: &str = "version";
48
49pub(crate) const METRIC_SUCCESS_VALUE: &str = "success";
50pub(crate) const METRIC_FAILURE_VALUE: &str = "failure";
51
52lazy_static! {
53
54 pub static ref HTTP_REQUEST_COUNTER: IntCounterVec = register_int_counter_vec!(
55 "greptime_servers_http_request_counter",
56 "servers http request counter",
57 &[METRIC_METHOD_LABEL, METRIC_PATH_LABEL, METRIC_CODE_LABEL, METRIC_DB_LABEL]
58 ).unwrap();
59
60 pub static ref METRIC_ERROR_COUNTER: IntCounterVec = register_int_counter_vec!(
61 "greptime_servers_error",
62 "servers error",
63 &[METRIC_PROTOCOL_LABEL]
64 )
65 .unwrap();
66 pub static ref METRIC_HTTP_SQL_ELAPSED: HistogramVec = register_histogram_vec!(
68 "greptime_servers_http_sql_elapsed",
69 "servers http sql elapsed",
70 &[METRIC_DB_LABEL],
71 vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
72 )
73 .unwrap();
74 pub static ref METRIC_HTTP_PROMQL_ELAPSED: HistogramVec = register_histogram_vec!(
76 "greptime_servers_http_promql_elapsed",
77 "servers http promql elapsed",
78 &[METRIC_DB_LABEL],
79 vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
80 )
81 .unwrap();
82 pub static ref METRIC_HTTP_LOGS_ELAPSED: HistogramVec = register_histogram_vec!(
84 "greptime_servers_http_logs_elapsed",
85 "servers http logs elapsed",
86 &[METRIC_DB_LABEL],
87 vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
88 )
89 .unwrap();
90 pub static ref METRIC_AUTH_FAILURE: IntCounterVec = register_int_counter_vec!(
91 "greptime_servers_auth_failure_count",
92 "servers auth failure count",
93 &[METRIC_CODE_LABEL]
94 )
95 .unwrap();
96 pub static ref METRIC_HTTP_INFLUXDB_WRITE_ELAPSED: HistogramVec = register_histogram_vec!(
98 "greptime_servers_http_influxdb_write_elapsed",
99 "servers http influxdb write elapsed",
100 &[METRIC_DB_LABEL],
101 vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
102 )
103 .unwrap();
104 pub static ref METRIC_HTTP_PROM_STORE_WRITE_ELAPSED: HistogramVec = register_histogram_vec!(
106 "greptime_servers_http_prometheus_write_elapsed",
107 "servers http prometheus write elapsed",
108 &[METRIC_DB_LABEL, METRIC_VERSION_LABEL],
109 vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
110 )
111 .unwrap();
112 pub static ref METRIC_HTTP_PROM_STORE_CODEC_ELAPSED: HistogramVec = register_histogram_vec!(
114 "greptime_servers_http_prometheus_codec_elapsed",
115 "servers http prometheus request codec duration",
116 &["type", METRIC_VERSION_LABEL],
117 )
118 .unwrap();
119 pub static ref PROM_STORE_REMOTE_WRITE_SAMPLES: IntCounterVec = register_int_counter_vec!(
121 "greptime_servers_prometheus_remote_write_samples",
122 "frontend prometheus remote write samples",
123 &[METRIC_DB_LABEL, METRIC_VERSION_LABEL]
124 )
125 .unwrap();
126 pub static ref PROM_STORE_REMOTE_WRITE_HISTOGRAMS: IntCounterVec = register_int_counter_vec!(
128 "greptime_servers_prometheus_remote_write_histograms",
129 "frontend prometheus remote write native histograms",
130 &[METRIC_DB_LABEL, METRIC_VERSION_LABEL]
131 )
132 .unwrap();
133 pub static ref PENDING_BATCHES: IntGauge = register_int_gauge!(
134 "greptime_prom_store_pending_batches",
135 "Number of pending batches waiting to be flushed"
136 )
137 .unwrap();
138 pub static ref PENDING_ROWS: IntGauge = register_int_gauge!(
139 "greptime_prom_store_pending_rows",
140 "Number of pending rows waiting to be flushed"
141 )
142 .unwrap();
143 pub static ref PENDING_WORKERS: IntGauge = register_int_gauge!(
144 "greptime_prom_store_pending_workers",
145 "Number of active pending rows batch workers"
146 )
147 .unwrap();
148 pub static ref FLUSH_TOTAL: IntCounter = register_int_counter!(
149 "greptime_prom_store_flush_total",
150 "Total number of batch flushes"
151 )
152 .unwrap();
153 pub static ref FLUSH_ROWS: Histogram = register_histogram!(
154 "greptime_prom_store_flush_rows",
155 "Number of rows per flush",
156 vec![100.0, 1000.0, 10000.0, 50000.0, 100000.0, 500000.0]
157 )
158 .unwrap();
159 pub static ref FLUSH_ELAPSED: Histogram = register_histogram!(
160 "greptime_prom_store_flush_elapsed",
161 "Elapsed time of pending rows batch flush in seconds",
162 vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
163 )
164 .unwrap();
165 pub static ref FLUSH_DROPPED_ROWS: IntCounter = register_int_counter!(
166 "greptime_pending_rows_flush_dropped_rows",
167 "Total rows dropped due to pending rows flush failures"
168 )
169 .unwrap();
170 pub static ref FLUSH_FAILURES: IntCounter = register_int_counter!(
171 "greptime_pending_rows_flush_failures",
172 "Total pending rows flush failures"
173 )
174 .unwrap();
175 pub static ref FLOW_NOTIFICATION_DROPPED: IntCounterVec = register_int_counter_vec!(
176 "greptime_prom_store_flow_notification_dropped_total",
177 "Total flow notifications dropped by the pending rows batcher",
178 &["reason"]
179 )
180 .unwrap();
181 pub static ref PENDING_ROWS_BATCH_INGEST_STAGE_ELAPSED: HistogramVec = register_histogram_vec!(
182 "greptime_prom_store_pending_rows_batch_ingest_stage_elapsed",
183 "Elapsed time of pending rows batch ingestion stages in seconds",
184 &["stage"],
185 vec![0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0]
186 )
187 .unwrap();
188 pub static ref PENDING_ROWS_BATCH_FLUSH_STAGE_ELAPSED: HistogramVec = register_histogram_vec!(
189 "greptime_prom_store_pending_rows_batch_flush_stage_elapsed",
190 "Elapsed time of pending rows batch flush stages in seconds",
191 &["stage"],
192 vec![0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0]
193 )
194 .unwrap();
195 pub static ref METRIC_HTTP_PROM_STORE_READ_ELAPSED: HistogramVec = register_histogram_vec!(
197 "greptime_servers_http_prometheus_read_elapsed",
198 "servers http prometheus read elapsed",
199 &[METRIC_DB_LABEL]
200 )
201 .unwrap();
202 pub static ref METRIC_HTTP_PROMETHEUS_PROMQL_ELAPSED: HistogramVec = register_histogram_vec!(
204 "greptime_servers_http_prometheus_promql_elapsed",
205 "servers http prometheus promql elapsed",
206 &[METRIC_DB_LABEL, METRIC_METHOD_LABEL]
207 )
208 .unwrap();
209 pub static ref METRIC_HTTP_OPENTELEMETRY_METRICS_ELAPSED: HistogramVec =
210 register_histogram_vec!(
211 "greptime_servers_http_otlp_metrics_elapsed",
212 "servers_http_otlp_metrics_elapsed",
213 &[METRIC_DB_LABEL]
214 )
215 .unwrap();
216 pub static ref METRIC_HTTP_OPENTELEMETRY_TRACES_ELAPSED: HistogramVec =
217 register_histogram_vec!(
218 "greptime_servers_http_otlp_traces_elapsed",
219 "servers http otlp traces elapsed",
220 &[METRIC_DB_LABEL]
221 )
222 .unwrap();
223 pub static ref METRIC_HTTP_OPENTELEMETRY_LOGS_ELAPSED: HistogramVec =
224 register_histogram_vec!(
225 "greptime_servers_http_otlp_logs_elapsed",
226 "servers http otlp logs elapsed",
227 &[METRIC_DB_LABEL]
228 )
229 .unwrap();
230 pub static ref METRIC_HTTP_LOGS_INGESTION_COUNTER: IntCounterVec = register_int_counter_vec!(
231 "greptime_servers_http_logs_ingestion_counter",
232 "servers http logs ingestion counter",
233 &[METRIC_DB_LABEL]
234 )
235 .unwrap();
236 pub static ref METRIC_HTTP_LOGS_INGESTION_ELAPSED: HistogramVec =
237 register_histogram_vec!(
238 "greptime_servers_http_logs_ingestion_elapsed",
239 "servers http logs ingestion elapsed",
240 &[METRIC_DB_LABEL, METRIC_RESULT_LABEL]
241 )
242 .unwrap();
243
244 pub static ref METRIC_LOKI_LOGS_INGESTION_COUNTER: IntCounterVec = register_int_counter_vec!(
246 "greptime_servers_loki_logs_ingestion_counter",
247 "servers loki logs ingestion counter",
248 &[METRIC_DB_LABEL]
249 )
250 .unwrap();
251 pub static ref METRIC_LOKI_LOGS_INGESTION_ELAPSED: HistogramVec =
252 register_histogram_vec!(
253 "greptime_servers_loki_logs_ingestion_elapsed",
254 "servers loki logs ingestion elapsed",
255 &[METRIC_DB_LABEL, METRIC_RESULT_LABEL]
256 )
257 .unwrap();
258 pub static ref METRIC_ELASTICSEARCH_LOGS_INGESTION_ELAPSED: HistogramVec =
259 register_histogram_vec!(
260 "greptime_servers_elasticsearch_logs_ingestion_elapsed",
261 "servers elasticsearch logs ingestion elapsed",
262 &[METRIC_DB_LABEL]
263 )
264 .unwrap();
265
266 pub static ref METRIC_ELASTICSEARCH_LOGS_DOCS_COUNT: IntCounterVec = register_int_counter_vec!(
268 "greptime_servers_elasticsearch_logs_docs_count",
269 "servers elasticsearch ingest logs docs count",
270 &[METRIC_DB_LABEL]
271 )
272 .unwrap();
273
274 pub static ref METRIC_HTTP_LOGS_TRANSFORM_ELAPSED: HistogramVec =
275 register_histogram_vec!(
276 "greptime_servers_http_logs_transform_elapsed",
277 "servers http logs transform elapsed",
278 &[METRIC_DB_LABEL, METRIC_RESULT_LABEL]
279 )
280 .unwrap();
281 pub static ref METRIC_MYSQL_CONNECTIONS: IntGauge = register_int_gauge!(
282 "greptime_servers_mysql_connection_count",
283 "servers mysql connection count"
284 )
285 .unwrap();
286 pub static ref METRIC_MYSQL_QUERY_TIMER: HistogramVec = register_histogram_vec!(
287 "greptime_servers_mysql_query_elapsed",
288 "servers mysql query elapsed",
289 &[METRIC_MYSQL_SUBPROTOCOL_LABEL, METRIC_DB_LABEL],
290 vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
291 )
292 .unwrap();
293 pub static ref METRIC_MYSQL_PREPARED_COUNT: IntCounterVec = register_int_counter_vec!(
294 "greptime_servers_mysql_prepared_count",
295 "servers mysql prepared count",
296 &[METRIC_DB_LABEL]
297 )
298 .unwrap();
299 pub static ref METRIC_POSTGRES_CONNECTIONS: IntGauge = register_int_gauge!(
300 "greptime_servers_postgres_connection_count",
301 "servers postgres connection count"
302 )
303 .unwrap();
304 pub static ref METRIC_POSTGRES_QUERY_TIMER: HistogramVec = register_histogram_vec!(
305 "greptime_servers_postgres_query_elapsed",
306 "servers postgres query elapsed",
307 &[METRIC_POSTGRES_SUBPROTOCOL_LABEL, METRIC_DB_LABEL],
308 vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
309 )
310 .unwrap();
311 pub static ref METRIC_POSTGRES_PREPARED_COUNT: IntCounter = register_int_counter!(
312 "greptime_servers_postgres_prepared_count",
313 "servers postgres prepared count"
314 )
315 .unwrap();
316 pub static ref METRIC_SERVER_GRPC_DB_REQUEST_TIMER: HistogramVec = register_histogram_vec!(
317 "greptime_servers_grpc_db_request_elapsed",
318 "servers grpc db request elapsed",
319 &[METRIC_DB_LABEL, METRIC_TYPE_LABEL, METRIC_CODE_LABEL]
320 )
321 .unwrap();
322 pub static ref METRIC_SERVER_GRPC_PROM_REQUEST_TIMER: HistogramVec = register_histogram_vec!(
323 "greptime_servers_grpc_prom_request_elapsed",
324 "servers grpc prom request elapsed",
325 &[METRIC_DB_LABEL],
326 vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
327 )
328 .unwrap();
329 pub static ref METRIC_HTTP_REQUESTS_TOTAL: IntCounterVec = register_int_counter_vec!(
330 "greptime_servers_http_requests_total",
331 "servers http requests total",
332 &[METRIC_METHOD_LABEL, METRIC_PATH_LABEL, METRIC_CODE_LABEL, METRIC_DB_LABEL]
333 )
334 .unwrap();
335 pub static ref METRIC_HTTP_REQUESTS_ELAPSED: HistogramVec = register_histogram_vec!(
336 "greptime_servers_http_requests_elapsed",
337 "servers http requests elapsed",
338 &[METRIC_METHOD_LABEL, METRIC_PATH_LABEL, METRIC_CODE_LABEL, METRIC_DB_LABEL],
339 vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
340 )
341 .unwrap();
342 pub static ref METRIC_GRPC_REQUESTS_TOTAL: IntCounterVec = register_int_counter_vec!(
343 "greptime_servers_grpc_requests_total",
344 "servers grpc requests total",
345 &[METRIC_PATH_LABEL, METRIC_CODE_LABEL]
346 )
347 .unwrap();
348 pub static ref METRIC_GRPC_REQUESTS_ELAPSED: HistogramVec = register_histogram_vec!(
349 "greptime_servers_grpc_requests_elapsed",
350 "servers grpc requests elapsed",
351 &[METRIC_PATH_LABEL, METRIC_CODE_LABEL],
352 vec![0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 60.0, 300.0]
353 )
354 .unwrap();
355 pub static ref METRIC_JAEGER_QUERY_ELAPSED: HistogramVec = register_histogram_vec!(
356 "greptime_servers_jaeger_query_elapsed",
357 "servers jaeger query elapsed",
358 &[METRIC_DB_LABEL, METRIC_PATH_LABEL]
359 ).unwrap();
360
361 pub static ref GRPC_BULK_INSERT_ELAPSED: Histogram = register_histogram!(
362 "greptime_servers_bulk_insert_elapsed",
363 "servers handle bulk insert elapsed",
364 ).unwrap();
365
366 pub static ref REQUEST_MEMORY_IN_USE: IntGauge = register_int_gauge!(
369 "greptime_servers_request_memory_in_use_bytes",
370 "bytes currently reserved for all concurrent request bodies and messages"
371 ).unwrap();
372
373 pub static ref REQUEST_MEMORY_LIMIT: IntGauge = register_int_gauge!(
375 "greptime_servers_request_memory_limit_bytes",
376 "maximum bytes allowed for all concurrent request bodies and messages"
377 ).unwrap();
378
379 pub static ref REQUEST_MEMORY_REJECTED: IntCounterVec = register_int_counter_vec!(
381 "greptime_servers_request_memory_rejected_total",
382 "number of requests rejected due to memory limit",
383 &["reason"]
384 ).unwrap();
385}
386
387#[derive(Debug, Clone, Default)]
391pub(crate) struct MetricsMiddlewareLayer;
392
393impl<S> Layer<S> for MetricsMiddlewareLayer {
394 type Service = MetricsMiddleware<S>;
395
396 fn layer(&self, service: S) -> Self::Service {
397 MetricsMiddleware { inner: service }
398 }
399}
400
401#[derive(Debug, Clone)]
402pub(crate) struct MetricsMiddleware<S> {
403 inner: S,
404}
405
406impl<S> Service<http::Request<Body>> for MetricsMiddleware<S>
407where
408 S: Service<http::Request<Body>, Response = http::Response<Body>> + Clone + Send + 'static,
409 S::Future: Send + 'static,
410{
411 type Response = S::Response;
412 type Error = S::Error;
413 type Future = futures::future::BoxFuture<'static, Result<Self::Response, Self::Error>>;
414
415 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
416 self.inner.poll_ready(cx)
417 }
418
419 fn call(&mut self, req: http::Request<Body>) -> Self::Future {
420 let clone = self.inner.clone();
424 let mut inner = std::mem::replace(&mut self.inner, clone);
425
426 Box::pin(async move {
427 let start = Instant::now();
428 let path = req.uri().path().to_string();
429
430 let response = inner.call(req).await?;
432
433 let latency = start.elapsed().as_secs_f64();
434 let status = response.status().as_u16().to_string();
435
436 let labels = [path.as_str(), status.as_str()];
437 METRIC_GRPC_REQUESTS_TOTAL.with_label_values(&labels).inc();
438 METRIC_GRPC_REQUESTS_ELAPSED
439 .with_label_values(&labels)
440 .observe(latency);
441
442 Ok(response)
443 })
444 }
445}
446
447pub(crate) async fn http_metrics_layer(req: Request, next: Next) -> impl IntoResponse {
450 let start = Instant::now();
451 let path = if let Some(matched_path) = req.extensions().get::<MatchedPath>() {
452 matched_path.as_str().to_string()
453 } else {
454 req.uri().path().to_string()
455 };
456 let method = req.method().clone();
457
458 let db = req
459 .extensions()
460 .get::<QueryContext>()
461 .map(|ctx| ctx.get_db_string())
462 .unwrap_or_else(|| "unknown".to_string());
463
464 let response = next.run(req).await;
465
466 let latency = start.elapsed().as_secs_f64();
467 let status = response.status();
468 let status = status.as_str();
469 let method_str = method.as_str();
470
471 let labels = [method_str, &path, status, db.as_str()];
472 METRIC_HTTP_REQUESTS_TOTAL.with_label_values(&labels).inc();
473 METRIC_HTTP_REQUESTS_ELAPSED
474 .with_label_values(&labels)
475 .observe(latency);
476
477 response
478}