"tests/fault_tolerance/etcd_ha/utils.py" did not exist on "9c5bdf83550ed2d1b6d36fb8ab6395541b24e222"
metrics_kvbm.rs 6.35 KB
Newer Older
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

4
5
6
7
8
9
10
11
12
13
14
15
16
use axum::Router;
use dynamo_runtime::metrics::prometheus_names::{
    kvbm::{
        MATCHED_TOKENS, OFFLOAD_BLOCKS_D2H, OFFLOAD_REQUESTS, ONBOARD_BLOCKS_D2D,
        ONBOARD_BLOCKS_H2D, ONBOARD_REQUESTS,
    },
    sanitize_prometheus_name,
};
use prometheus::{IntCounter, Opts, Registry};
use std::{collections::HashMap, net::SocketAddr, sync::Arc, thread};
use tokio::{net::TcpListener, sync::Notify};

use crate::http::service::{RouteDoc, metrics::router};
17
18
19

#[derive(Clone, Debug)]
pub struct KvbmMetrics {
20
    // number of offload requests
21
    pub offload_requests: IntCounter,
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

    // number of blocks offloaded from device to host
    pub offload_blocks_d2h: IntCounter,

    // number of onboard requests
    pub onboard_requests: IntCounter,

    // 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,

    // number of matched tokens from KVBM
    pub matched_tokens: IntCounter,
37
38

    shutdown_notify: Option<Arc<Notify>>,
39
40
41
}

impl KvbmMetrics {
42
43
44
45
    /// 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
46
        let offload_requests = mr
47
            .create_intcounter(OFFLOAD_REQUESTS, "The number of offload requests", &[])
48
            .unwrap();
49
50
        let offload_blocks_d2h = mr
            .create_intcounter(
51
                OFFLOAD_BLOCKS_D2H,
52
53
54
55
56
                "The number of offload blocks from device to host",
                &[],
            )
            .unwrap();
        let onboard_requests = mr
57
            .create_intcounter(ONBOARD_REQUESTS, "The number of onboard requests", &[])
58
59
60
            .unwrap();
        let onboard_blocks_h2d = mr
            .create_intcounter(
61
                ONBOARD_BLOCKS_H2D,
62
63
64
65
66
67
                "The number of onboard blocks from host to device",
                &[],
            )
            .unwrap();
        let onboard_blocks_d2d = mr
            .create_intcounter(
68
                ONBOARD_BLOCKS_D2D,
69
70
71
72
73
                "The number of onboard blocks from disk to device",
                &[],
            )
            .unwrap();
        let matched_tokens = mr
74
            .create_intcounter(MATCHED_TOKENS, "The number of matched tokens", &[])
75
            .unwrap();
76
77
78
79
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
130
131
132

        // early return if no endpoint is needed
        if !create_endpoint {
            return Self {
                offload_requests,
                offload_blocks_d2h,
                onboard_requests,
                onboard_blocks_h2d,
                onboard_blocks_d2d,
                matched_tokens,
                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);
            });
        }

133
134
        Self {
            offload_requests,
135
136
137
138
139
            offload_blocks_d2h,
            onboard_requests,
            onboard_blocks_h2d,
            onboard_blocks_d2d,
            matched_tokens,
140
141
142
143
144
145
146
147
148
149
150
151
152
            shutdown_notify: Some(notify),
        }
    }
}

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();
            }
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198

/// 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)
    }

    pub fn inner(&self) -> Arc<Registry> {
        Arc::clone(&self.registry)
    }
}

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