metrics_kvbm.rs 10.9 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
// SPDX-License-Identifier: Apache-2.0

4
5
6
use axum::Router;
use dynamo_runtime::metrics::prometheus_names::{
    kvbm::{
7
8
9
10
        DISK_CACHE_HIT_RATE, HOST_CACHE_HIT_RATE, MATCHED_TOKENS, OBJECT_CACHE_HIT_RATE,
        OBJECT_READ_FAILURES, OBJECT_WRITE_FAILURES, OFFLOAD_BLOCKS_D2D, OFFLOAD_BLOCKS_D2H,
        OFFLOAD_BLOCKS_D2O, OFFLOAD_BLOCKS_H2D, ONBOARD_BLOCKS_D2D, ONBOARD_BLOCKS_H2D,
        ONBOARD_BLOCKS_O2D,
11
12
13
    },
    sanitize_prometheus_name,
};
14
use prometheus::{Gauge, IntCounter, Opts, Registry};
15
16
17
18
use std::{collections::HashMap, net::SocketAddr, sync::Arc, thread};
use tokio::{net::TcpListener, sync::Notify};

use crate::http::service::{RouteDoc, metrics::router};
19
20
21

#[derive(Clone, Debug)]
pub struct KvbmMetrics {
22
23
24
    // number of blocks offloaded from device to host
    pub offload_blocks_d2h: IntCounter,

25
26
    // number of blocks offloaded from host to disk
    pub offload_blocks_h2d: IntCounter,
27

28
29
30
    // number of blocks offloaded from device to disk (bypassing host memory)
    pub offload_blocks_d2d: IntCounter,

31
32
33
    // number of blocks offloaded from device to object storage
    pub offload_blocks_d2o: IntCounter,

34
35
36
37
38
39
    // number of blocks onboarded from host to device
    pub onboard_blocks_h2d: IntCounter,

    // number of blocks onboarded from disk to device
    pub onboard_blocks_d2d: IntCounter,

40
41
42
    // number of blocks onboarded from object storage to device
    pub onboard_blocks_o2d: IntCounter,

43
44
    // number of matched tokens from KVBM
    pub matched_tokens: IntCounter,
45

46
47
48
49
50
51
    // host cache hit rate (0.0-1.0) from the sliding window
    pub host_cache_hit_rate: Gauge,

    // disk cache hit rate (0.0-1.0) from the sliding window
    pub disk_cache_hit_rate: Gauge,

52
53
54
55
56
57
58
59
60
    // object cache hit rate (0.0-1.0) from the sliding window
    pub object_cache_hit_rate: Gauge,

    // number of failed object storage read operations (blocks)
    pub object_read_failures: IntCounter,

    // number of failed object storage write operations (blocks)
    pub object_write_failures: IntCounter,

61
    shutdown_notify: Option<Arc<Notify>>,
62
63
64
}

impl KvbmMetrics {
65
66
67
68
    /// Create raw metrics and (once per process) spawn an axum server exposing `/metrics` at metrics_port.
    /// Non-blocking: the HTTP server runs on a background task.
    pub fn new(mr: &KvbmMetricsRegistry, create_endpoint: bool, metrics_port: u16) -> Self {
        // 1) register kvbm metrics
69
70
        let offload_blocks_d2h = mr
            .create_intcounter(
71
                OFFLOAD_BLOCKS_D2H,
72
73
74
75
                "The number of offload blocks from device to host",
                &[],
            )
            .unwrap();
76
77
78
79
80
81
        let offload_blocks_h2d = mr
            .create_intcounter(
                OFFLOAD_BLOCKS_H2D,
                "The number of offload blocks from host to disk",
                &[],
            )
82
            .unwrap();
83
84
85
86
87
88
89
        let offload_blocks_d2d = mr
            .create_intcounter(
                OFFLOAD_BLOCKS_D2D,
                "The number of offload blocks from device to disk (bypassing host memory)",
                &[],
            )
            .unwrap();
90
91
92
93
94
95
96
        let offload_blocks_d2o = mr
            .create_intcounter(
                OFFLOAD_BLOCKS_D2O,
                "The number of offload blocks from device to object storage",
                &[],
            )
            .unwrap();
97
98
        let onboard_blocks_h2d = mr
            .create_intcounter(
99
                ONBOARD_BLOCKS_H2D,
100
101
102
103
104
105
                "The number of onboard blocks from host to device",
                &[],
            )
            .unwrap();
        let onboard_blocks_d2d = mr
            .create_intcounter(
106
                ONBOARD_BLOCKS_D2D,
107
108
109
110
                "The number of onboard blocks from disk to device",
                &[],
            )
            .unwrap();
111
112
113
114
115
116
117
118
        let onboard_blocks_o2d = mr
            .create_intcounter(
                ONBOARD_BLOCKS_O2D,
                "The number of onboard blocks from object storage to device",
                &[],
            )
            .unwrap();

119
        let matched_tokens = mr
120
            .create_intcounter(MATCHED_TOKENS, "The number of matched tokens", &[])
121
            .unwrap();
122
123
124
125
126
127
128
129
130
131
132
133
134
135
        let host_cache_hit_rate = mr
            .create_gauge(
                HOST_CACHE_HIT_RATE,
                "Host cache hit rate (0.0-1.0) from the sliding window",
                &[],
            )
            .unwrap();
        let disk_cache_hit_rate = mr
            .create_gauge(
                DISK_CACHE_HIT_RATE,
                "Disk cache hit rate (0.0-1.0) from the sliding window",
                &[],
            )
            .unwrap();
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
        let object_cache_hit_rate = mr
            .create_gauge(
                OBJECT_CACHE_HIT_RATE,
                "Object storage cache hit rate (0.0-1.0) from the sliding window",
                &[],
            )
            .unwrap();
        let object_read_failures = mr
            .create_intcounter(
                OBJECT_READ_FAILURES,
                "The number of failed object storage read operations (blocks)",
                &[],
            )
            .unwrap();
        let object_write_failures = mr
            .create_intcounter(
                OBJECT_WRITE_FAILURES,
                "The number of failed object storage write operations (blocks)",
                &[],
            )
            .unwrap();
157
158
159
160
        // early return if no endpoint is needed
        if !create_endpoint {
            return Self {
                offload_blocks_d2h,
161
                offload_blocks_h2d,
162
                offload_blocks_d2d,
163
                offload_blocks_d2o,
164
165
                onboard_blocks_h2d,
                onboard_blocks_d2d,
166
                onboard_blocks_o2d,
167
                matched_tokens,
168
169
                host_cache_hit_rate,
                disk_cache_hit_rate,
170
171
172
                object_cache_hit_rate,
                object_read_failures,
                object_write_failures,
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
                shutdown_notify: None,
            };
        }

        // 2) start HTTP server in background with graceful shutdown via Notify
        let registry = mr.inner(); // Arc<Registry>
        let notify = Arc::new(Notify::new());
        let notify_for_task = notify.clone();

        let addr = SocketAddr::from(([0, 0, 0, 0], metrics_port));
        let (_route_docs, app): (Vec<RouteDoc>, Router) = router(
            (*registry).clone(), // take owned Registry (Clone) for router to wrap in Arc
            None,                // or Some("/metrics".to_string()) to override the path
        );

        let run_server = async move {
            let listener = match TcpListener::bind(addr).await {
                Ok(listener) => listener,
                Err(err) => {
                    panic!("failed to bind metrics server to {addr}: {err}");
                }
            };

            if let Err(err) = axum::serve(listener, app)
                .with_graceful_shutdown(async move {
                    // wait for shutdown signal
                    notify_for_task.notified().await;
                })
                .await
            {
                tracing::error!("[kvbm] metrics server error: {err}");
            }
        };

        // Spawn on existing runtime if present, otherwise start our own.
        if tokio::runtime::Handle::try_current().is_ok() {
            tokio::spawn(run_server);
        } else {
            thread::spawn(move || {
                let rt = tokio::runtime::Builder::new_multi_thread()
                    .enable_all()
                    .build()
                    .expect("build tokio runtime");
                rt.block_on(run_server);
            });
        }

220
        Self {
221
            offload_blocks_d2h,
222
            offload_blocks_h2d,
223
            offload_blocks_d2d,
224
            offload_blocks_d2o,
225
226
            onboard_blocks_h2d,
            onboard_blocks_d2d,
227
            onboard_blocks_o2d,
228
            matched_tokens,
229
230
            host_cache_hit_rate,
            disk_cache_hit_rate,
231
232
233
            object_cache_hit_rate,
            object_read_failures,
            object_write_failures,
234
235
236
            shutdown_notify: Some(notify),
        }
    }
237
238

    /// Update cache hit rate metrics from a CacheStatsTracker
239
    pub fn update_cache_hit_rates(&self, host_rate: f32, disk_rate: f32, object_rate: f32) {
240
241
        self.host_cache_hit_rate.set(host_rate as f64);
        self.disk_cache_hit_rate.set(disk_rate as f64);
242
243
244
245
246
247
248
249
250
251
        self.object_cache_hit_rate.set(object_rate as f64);
    }
    /// Record failed object storage read operations
    pub fn record_object_read_failure(&self, num_blocks: u64) {
        self.object_read_failures.inc_by(num_blocks);
    }

    /// Record failed object storage write operations
    pub fn record_object_write_failure(&self, num_blocks: u64) {
        self.object_write_failures.inc_by(num_blocks);
252
    }
253
254
255
256
257
258
259
260
261
262
}

impl Drop for KvbmMetrics {
    fn drop(&mut self) {
        if let Some(n) = &self.shutdown_notify {
            // (all KvbmMetrics clones) + 1 (held by server task)
            // strong_count == 2 means this is the last metrics instance
            if Arc::strong_count(n) == 2 {
                n.notify_waiters();
            }
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

/// A raw, standalone Prometheus metrics registry implementation using the fixed prefix: `kvbm_`
#[derive(Debug, Clone)]
pub struct KvbmMetricsRegistry {
    registry: Arc<Registry>,
    prefix: String,
}

impl KvbmMetricsRegistry {
    pub fn new() -> Self {
        Self {
            registry: Arc::new(Registry::new()),
            prefix: "kvbm".to_string(),
        }
    }

    pub fn create_intcounter(
        &self,
        name: &str,
        description: &str,
        labels: &[(&str, &str)],
    ) -> anyhow::Result<IntCounter> {
        let metrics_name = sanitize_prometheus_name(&format!("{}_{}", self.prefix, name))?;
        let const_labels: HashMap<String, String> = labels
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        let opts = Opts::new(metrics_name, description).const_labels(const_labels);
        let c = IntCounter::with_opts(opts)?;
        self.registry.register(Box::new(c.clone()))?;
        Ok(c)
    }

299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    pub fn create_gauge(
        &self,
        name: &str,
        description: &str,
        labels: &[(&str, &str)],
    ) -> anyhow::Result<Gauge> {
        let metrics_name = sanitize_prometheus_name(&format!("{}_{}", self.prefix, name))?;
        let const_labels: HashMap<String, String> = labels
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        let opts = Opts::new(metrics_name, description).const_labels(const_labels);
        let g = Gauge::with_opts(opts)?;
        self.registry.register(Box::new(g.clone()))?;
        Ok(g)
    }

316
317
318
319
320
321
322
323
324
325
    pub fn inner(&self) -> Arc<Registry> {
        Arc::clone(&self.registry)
    }
}

impl Default for KvbmMetricsRegistry {
    fn default() -> Self {
        Self::new()
    }
}