"docs/vscode:/vscode.git/clone" did not exist on "13a5d61b549919bb6b766f7bc60eecdad282a11a"
lib.rs 19.6 KB
Newer Older
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

4
//! Library functions for the metrics application.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//!
//! This library provides functionality to expose Prometheus metrics either through a local HTTP server
//! or by pushing to a Prometheus PushGateway.
//!
//! # Examples
//!
//! ## Using the metrics pull mode
//! ```no_run
//! use metrics::{PrometheusMetricsCollector, MetricsMode};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let mut collector = PrometheusMetricsCollector::new()?;
//!
//!     // Start a metrics server with default values
//!     collector.start(MetricsMode::default())?;
//!
//!     // Or explicitly specify values
//!     collector.start(MetricsMode::Pull {
//!         host: "127.0.0.1".to_string(),
//!         port: 9090,
//!     })?;
//!
//!     // Or use the convenience constructor
//!     collector.start(MetricsMode::new_pull())?;
//!
//!     // Your application code here
//!     tokio::signal::ctrl_c().await?;
//!
//!     // Stop the metrics server gracefully
//!     collector.stop();
//!     Ok(())
//! }
//! ```
//!
//! ## Using the Push mode
//! ```no_run
//! use metrics::{PrometheusMetricsCollector, MetricsMode};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let mut collector = PrometheusMetricsCollector::new()?;
//!
//!     // Start pushing metrics to a Prometheus PushGateway with default values
//!     collector.start(MetricsMode::new_push())?;
//!
//!     // Or explicitly specify values
//!     collector.start(MetricsMode::Push {
//!         host: "127.0.0.1".to_string(),
//!         port: 9091,
//!         job: "custom_job".to_string(),
//!         interval: 5, // Push every 5 seconds
//!     })?;
//!
//!     // Your application code here
//!     tokio::signal::ctrl_c().await?;
//!
//!     // Stop pushing metrics gracefully
//!     collector.stop();
//!     Ok(())
//! }
66

67
68
use axum::{Router, routing::get};
use prometheus::{Encoder, TextEncoder, register_counter_vec, register_gauge_vec};
69
use reqwest::Client;
70
71
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
72
use std::time::Duration as StdDuration;
73

74
use dynamo_llm::kv_router::protocols::{ForwardPassMetrics, LoadMetrics};
75
use dynamo_llm::kv_router::scoring::Endpoint;
Neelay Shah's avatar
Neelay Shah committed
76
use dynamo_llm::kv_router::scoring::ProcessedEndpoints;
77

78
use dynamo_runtime::{
79
    Result, distributed::Component, error, service::EndpointInfo, utils::Duration,
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
};

/// Configuration for metrics collection mode
#[derive(Debug, Clone)]
pub enum MetricsMode {
    /// Host a Prometheus metrics server for pull-based collection
    Pull {
        /// Host to listen on (e.g. "0.0.0.0")
        host: String,
        /// Port to listen on (e.g. 9091)
        port: u16,
    },
    /// Push to a Prometheus PushGateway
    Push {
        /// PushGateway host (e.g. "http://localhost")
        host: String,
        /// PushGateway port (e.g. 9091)
        port: u16,
        /// Job name for the metrics
        job: String,
        /// Push interval in seconds
        interval: u64,
    },
}

impl Default for MetricsMode {
    fn default() -> Self {
        Self::new_pull()
    }
}

impl MetricsMode {
    /// Create a new Pull mode with default values
    pub fn new_pull() -> Self {
        Self::Pull {
            host: "0.0.0.0".to_string(),
            port: 9091,
        }
    }

    /// Create a new Push mode with default values
    pub fn new_push() -> Self {
        Self::Push {
            host: "127.0.0.1".to_string(),
            port: 9091,
            job: "dynamo_metrics".to_string(),
            interval: 2,
        }
    }
}
130
131
132
133
134
135

/// Configuration for LLM worker load capacity metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LLMWorkerLoadCapacityConfig {
    pub component_name: String,
    pub endpoint_name: String,
136
    pub model_name: Option<String>,
137
138
}

139
140
/// Metrics collector for exposing metrics to prometheus/grafana
pub struct PrometheusMetricsCollector {
141
    metrics: PrometheusMetrics,
142
143
    mode: Option<MetricsMode>,
    shutdown_tx: Option<tokio::sync::oneshot::Sender<()>>,
144
145
}

146
impl PrometheusMetricsCollector {
147
148
149
    pub fn new() -> Result<Self> {
        Ok(Self {
            metrics: PrometheusMetrics::new()?,
150
151
            mode: None,
            shutdown_tx: None,
152
153
154
        })
    }

155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    /// Start metrics collection with the specified mode
    pub fn start(&mut self, mode: MetricsMode) -> Result<()> {
        // Store the mode
        self.mode = Some(mode.clone());

        match mode {
            MetricsMode::Pull { host, port } => self.start_pull_mode(host, port),
            MetricsMode::Push {
                host,
                port,
                job,
                interval,
            } => self.start_push_mode(host, port, job, interval),
        }
    }

    /// Stop metrics collection
    pub fn stop(&mut self) {
        if let Some(tx) = self.shutdown_tx.take() {
            let _ = tx.send(());
        }
    }

    /// Start a metrics server for pull-based collection on the specified port
    fn start_pull_mode(&mut self, host: String, port: u16) -> Result<()> {
180
181
182
183
184
        // Create an axum router with a metrics endpoint
        let app = Router::new().route(
            "/metrics",
            get(|| async {
                // Gather and encode metrics
185
                let encoder = TextEncoder::new();
186
187
188
189
190
191
192
                let mut buffer = Vec::new();
                encoder.encode(&prometheus::gather(), &mut buffer).unwrap();
                String::from_utf8(buffer).unwrap()
            }),
        );

        // Create a socket address to listen on
193
194
195
196
197
198
199
200
201
        let ip_addr = host.parse().map_err(|e| {
            error!("Failed to parse host '{}' as IP address: {}. Use a valid IPv4 or IPv6 address (e.g. '0.0.0.0' or '127.0.0.1')", host, e)
        })?;
        let addr = SocketAddr::new(ip_addr, port);

        // Create shutdown channel
        let (tx, rx) = tokio::sync::oneshot::channel();
        self.shutdown_tx = Some(tx);

202
203
        // Spawn the server in a background task
        tokio::spawn(async move {
204
205
206
207
            let listener = tokio::net::TcpListener::bind(addr)
                .await
                .unwrap_or_else(|_| panic!("could not bind to address: {addr}"));
            let server = axum::serve(listener, app);
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224

            // Create a future that completes when shutdown signal is received
            let shutdown_future = async {
                rx.await.ok();
            };

            // Run the server with graceful shutdown
            tokio::select! {
                result = server => {
                    if let Err(e) = result {
                        tracing::error!("Metrics server error: {}", e);
                    }
                },
                _ = shutdown_future => {
                    tracing::info!("Metrics server shutting down gracefully");
                },
            }
225
226
        });

227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
        tracing::info!("Prometheus metrics server started at {addr}/metrics");
        Ok(())
    }

    /// Start pushing metrics to a Prometheus PushGateway
    fn start_push_mode(
        &mut self,
        host: String,
        port: u16,
        job: String,
        interval: u64,
    ) -> Result<()> {
        // Create shutdown channel
        let (tx, mut rx) = tokio::sync::oneshot::channel();
        self.shutdown_tx = Some(tx);

        // Create HTTP client
        let client = Client::new();
        let url = format!("http://{host}:{port}/metrics/job/{job}");
        let url_clone = url.clone();
        let interval_duration = StdDuration::from_secs(interval);

        // Spawn background task to periodically push metrics
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(interval_duration);

            loop {
                tokio::select! {
                    _ = interval.tick() => {
                        // Gather and encode metrics
                        let encoder = TextEncoder::new();
                        let mut buffer = Vec::new();
                        if let Err(e) = encoder.encode(&prometheus::gather(), &mut buffer) {
                            tracing::error!("Failed to encode metrics: {}", e);
                            continue;
                        }

                        // Push metrics to the gateway
                        match client.post(&url)
                            .header("Content-Type", encoder.format_type())
                            .body(buffer)
                            .send()
                            .await
                        {
                            Ok(response) => {
                                if response.status().is_success() {
                                    tracing::debug!("Successfully pushed metrics to PushGateway");
                                } else {
                                    tracing::error!(
                                        "Failed to push metrics to PushGateway. Status: {}, Error: {:?}",
                                        response.status(),
                                        response.text().await
                                    );
                                }
                            }
                            Err(e) => {
                                tracing::error!("Failed to push metrics to PushGateway: {}", e);
                            }
                        }
                    }
                    _ = &mut rx => {
                        tracing::info!("Stopping metrics push task");
                        break;
                    }
                }
            }
        });

        tracing::info!(
            "Started pushing metrics to PushGateway at '{url_clone}' with job name '{job}'"
        );
        Ok(())
299
300
301
302
303
304
    }

    /// Update metrics with current values
    pub fn update(&mut self, config: &LLMWorkerLoadCapacityConfig, processed: &ProcessedEndpoints) {
        self.metrics.update(config, processed);
    }
305
306
307
308
309
310
311
312
313
314
315
316

    /// Update KV hit rate metrics
    pub fn update_kv_hit_rate(
        &mut self,
        config: &LLMWorkerLoadCapacityConfig,
        worker_id: i64,
        isl_blocks: usize,
        overlap_blocks: usize,
    ) {
        self.metrics
            .update_kv_hit_rate(config, worker_id, isl_blocks, overlap_blocks);
    }
317
318
319
320
321
322
323
324
325
326
}

/// Prometheus metrics collection
pub struct PrometheusMetrics {
    kv_blocks_active: prometheus::GaugeVec,
    kv_blocks_total: prometheus::GaugeVec,
    requests_active: prometheus::GaugeVec,
    requests_total: prometheus::GaugeVec,
    load_avg: prometheus::GaugeVec,
    load_std: prometheus::GaugeVec,
327
    // KV hit rate metrics
328
329
    kv_hit_rate_percent: prometheus::GaugeVec,
    // FIXME: These are currently unused outside of mock_worker
330
331
    kv_hit_rate_isl_blocks: prometheus::CounterVec,
    kv_hit_rate_overlap_blocks: prometheus::CounterVec,
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
}

impl PrometheusMetrics {
    /// Initialize all metrics
    fn new() -> Result<Self> {
        Ok(Self {
            kv_blocks_active: register_gauge_vec!(
                "llm_kv_blocks_active",
                "Active KV cache blocks",
                &["component", "endpoint", "worker_id"]
            )?,
            kv_blocks_total: register_gauge_vec!(
                "llm_kv_blocks_total",
                "Total KV cache blocks",
                &["component", "endpoint", "worker_id"]
            )?,
            requests_active: register_gauge_vec!(
                "llm_requests_active_slots",
                "Active request slots",
                &["component", "endpoint", "worker_id"]
            )?,
            requests_total: register_gauge_vec!(
                "llm_requests_total_slots",
                "Total request slots",
                &["component", "endpoint", "worker_id"]
            )?,
            load_avg: register_gauge_vec!(
                "llm_load_avg",
                "Average load across workers",
                &["component", "endpoint"]
            )?,
            load_std: register_gauge_vec!(
                "llm_load_std",
                "Load standard deviation across workers",
                &["component", "endpoint"]
            )?,
368
369
370
371
372
373
374
375
376
            // KV hit rate (ForwardPassMetrics)
            kv_hit_rate_percent: register_gauge_vec!(
                "llm_kv_hit_rate_percent",
                "KV hit rate percentage per worker",
                &["component", "endpoint", "worker_id"]
            )?,
            // FIXME: Cleanup/remove event based metrics after finalizaing
            //        metrics collection approach with vllm/trtllm workers.
            // Event-based KV hit rate metrics (not currently used outside mock worker)
377
378
379
380
381
382
383
384
385
386
            kv_hit_rate_isl_blocks: register_counter_vec!(
                "llm_kv_hit_rate_isl_blocks",
                "Cumulative count of ISL blocks in KV hit rate events",
                &["component", "endpoint", "worker_id"]
            )?,
            kv_hit_rate_overlap_blocks: register_counter_vec!(
                "llm_kv_hit_rate_overlap_blocks",
                "Cumulative count of overlapping blocks in KV hit rate events",
                &["component", "endpoint", "worker_id"]
            )?,
387
388
389
390
391
392
393
394
        })
    }

    /// Helper method to set a gauge with worker-specific labels (3 labels)
    fn set_worker_gauge(
        &self,
        gauge: &prometheus::GaugeVec,
        config: &LLMWorkerLoadCapacityConfig,
395
        worker_id: &String,
396
397
398
399
400
401
402
        value: f64,
    ) {
        gauge
            .with_label_values(&[&config.component_name, &config.endpoint_name, worker_id])
            .set(value);
    }

403
404
405
406
407
    /// Helper method to increment a counter with worker-specific labels (3 labels)
    fn increment_worker_counter(
        &self,
        counter: &prometheus::CounterVec,
        config: &LLMWorkerLoadCapacityConfig,
408
        worker_id: &String,
409
410
411
412
413
414
415
        value: f64,
    ) {
        counter
            .with_label_values(&[&config.component_name, &config.endpoint_name, worker_id])
            .inc_by(value);
    }

416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
    /// Helper method to set a gauge with component/endpoint labels only (2 labels)
    fn set_endpoint_gauge(
        &self,
        gauge: &prometheus::GaugeVec,
        config: &LLMWorkerLoadCapacityConfig,
        value: f64,
    ) {
        gauge
            .with_label_values(&[&config.component_name, &config.endpoint_name])
            .set(value);
    }

    /// Update metrics with current values
    fn update(&self, config: &LLMWorkerLoadCapacityConfig, processed: &ProcessedEndpoints) {
        // Update per-worker metrics
431
432
        for (worker_id, endpoint) in processed.endpoints.iter() {
            let worker_id = worker_id.to_string();
433
434
435
436
            let load_metrics = endpoint.data.clone();
            let LoadMetrics::EngineLoadMetrics(metrics) = load_metrics else {
                panic!("Can only update with ForwardPassMetrics");
            };
437
438
439
440
441

            self.set_worker_gauge(
                &self.kv_blocks_active,
                config,
                &worker_id,
442
                metrics.kv_stats.kv_active_blocks as f64,
443
444
445
446
447
            );
            self.set_worker_gauge(
                &self.kv_blocks_total,
                config,
                &worker_id,
448
                metrics.kv_stats.kv_total_blocks as f64,
449
450
451
452
453
            );
            self.set_worker_gauge(
                &self.requests_active,
                config,
                &worker_id,
454
                metrics.worker_stats.request_active_slots as f64,
455
456
457
458
459
            );
            self.set_worker_gauge(
                &self.requests_total,
                config,
                &worker_id,
460
                metrics.worker_stats.request_total_slots as f64,
461
            );
462
463
464
465
            self.set_worker_gauge(
                &self.kv_hit_rate_percent,
                config,
                &worker_id,
466
                metrics.kv_stats.gpu_prefix_cache_hit_rate as f64,
467
            );
468
469
470
471
472
473
        }

        // Update aggregate metrics
        self.set_endpoint_gauge(&self.load_avg, config, processed.load_avg);
        self.set_endpoint_gauge(&self.load_std, config, processed.load_std);
    }
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523

    /// Update KV hit rate metrics
    pub fn update_kv_hit_rate(
        &self,
        config: &LLMWorkerLoadCapacityConfig,
        worker_id: i64,
        isl_blocks: usize,
        overlap_blocks: usize,
    ) {
        let worker_id_str = worker_id.to_string();

        // Increment the ISL blocks and overlap blocks counters
        self.increment_worker_counter(
            &self.kv_hit_rate_isl_blocks,
            config,
            &worker_id_str,
            isl_blocks as f64,
        );

        self.increment_worker_counter(
            &self.kv_hit_rate_overlap_blocks,
            config,
            &worker_id_str,
            overlap_blocks as f64,
        );

        // TODO: The cumulative hit rate percentage can probably be computed by consumers
        // of Prometheus metrics like Grafana instead, but we'll compute it here for now
        // for convenient debugging/logging.
        // Calculate and set the cumulative hit rate percentage
        let cumulative_isl = self
            .kv_hit_rate_isl_blocks
            .with_label_values(&[
                &config.component_name,
                &config.endpoint_name,
                &worker_id_str,
            ])
            .get();

        let cumulative_overlap = self
            .kv_hit_rate_overlap_blocks
            .with_label_values(&[
                &config.component_name,
                &config.endpoint_name,
                &worker_id_str,
            ])
            .get();

        if cumulative_isl > 0.0 {
            let cumulative_hit_rate = (cumulative_overlap / cumulative_isl) * 100.0;
524
            tracing::debug!(
525
526
527
528
                "Estimated Cumulative KV hit rate: {cumulative_hit_rate:.2}% (Overlap: {cumulative_overlap} / ISL: {cumulative_isl})"
            );
        }
    }
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
}

/// Collect endpoints from a component
pub async fn collect_endpoints(
    component: &Component,
    subject: &str,
    timeout: Duration,
) -> Result<Vec<EndpointInfo>> {
    // Collect stats from each backend
    let stream = component.scrape_stats(timeout).await?;

    // Filter the stats by the service subject
    let endpoints = stream
        .into_endpoints()
        .filter(|e| e.subject.starts_with(subject))
        .collect::<Vec<_>>();
    tracing::debug!("Endpoints: {endpoints:?}");
    Ok(endpoints)
}

/// Extract metrics from endpoints
pub fn extract_metrics(endpoints: &[EndpointInfo]) -> Vec<ForwardPassMetrics> {
    let endpoint_data = endpoints.iter().map(|e| e.data.clone()).collect::<Vec<_>>();

553
554
    // Extract ForwardPassMetrics objects from endpoint services
    let metrics: Vec<ForwardPassMetrics> = endpoint_data
555
556
557
558
        .iter()
        .filter_map(|e| {
            let metrics_data = e.as_ref()?;

559
560
            match metrics_data.clone().decode::<ForwardPassMetrics>() {
                Ok(stats) => Some(stats),
561
                Err(err) => {
562
563
564
565
566
                    tracing::error!(
                        "Failed to decode ForwardPassMetrics data: {}. Raw data: {:?}",
                        err,
                        metrics_data
                    );
567
568
                    None
                }
569
570
            }
        })
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
        .collect();
    tracing::debug!("Metrics: {metrics:?}");

    metrics
}

/// Create ProcessedEndpoints from metrics and endpoints
pub fn postprocess_metrics(
    metrics: &[ForwardPassMetrics],
    endpoints: &[EndpointInfo],
) -> ProcessedEndpoints {
    let processed_endpoints: Vec<Endpoint> = metrics
        .iter()
        .zip(endpoints.iter())
        .filter_map(|(m, e)| {
            e.id().ok().map(|id| Endpoint {
                name: format!("worker-{id}"),
                subject: e.subject.clone(),
589
                data: LoadMetrics::EngineLoadMetrics(m.clone()),
590
591
592
593
594
595
            })
        })
        .collect();

    ProcessedEndpoints::new(processed_endpoints)
}