Skip to main content

hyperlight_host/metrics/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025 The Hyperlight Authors.
3
4// Counter metric that counter number of times a guest error occurred
5pub(crate) static METRIC_GUEST_ERROR: &str = "guest_errors_total";
6pub(crate) static METRIC_GUEST_ERROR_LABEL_CODE: &str = "code";
7
8// Counter metric that counts the number of times a guest function was called due to timing out
9pub(crate) static METRIC_GUEST_CANCELLATION: &str = "guest_cancellations_total";
10
11// Counter metric that counts the number of times a vCPU was erroneously kicked by a stale cancellation
12// This can happen in two scenarios:
13// 1. Linux: A signal from a previous guest call arrives late and interrupts a new call
14// 2. Windows: WHvCancelRunVirtualProcessor is called right after vCPU exits but RUNNING_BIT is still true
15pub(crate) static METRIC_ERRONEOUS_VCPU_KICKS: &str = "erroneous_vcpu_kicks_total";
16
17// Histogram metric that measures the duration of guest function calls
18#[cfg(feature = "function_call_metrics")]
19pub(crate) static METRIC_GUEST_FUNC_DURATION: &str = "guest_call_duration_seconds";
20
21// Histogram metric that measures the duration of host function calls
22#[cfg(feature = "function_call_metrics")]
23pub(crate) static METRIC_HOST_FUNC_DURATION: &str = "host_call_duration_seconds";
24
25/// If the the `function_call_metrics` feature is enabled, this function measures
26/// the time it takes to execute the given closure, and will then emit a guest call metric
27/// with the given function name.
28///
29/// If the feature is not enabled, the given closure is executed without any additional metrics being emitted,
30/// and the result of the closure is returned directly.
31pub(crate) fn maybe_time_and_emit_guest_call<T, F: FnOnce() -> T>(
32    #[allow(unused_variables)] name: &str,
33    f: F,
34) -> T {
35    cfg_if::cfg_if! {
36        if #[cfg(feature = "function_call_metrics")] {
37            use std::time::Instant;
38
39            let start = Instant::now();
40            let result = f();
41            let duration = start.elapsed();
42
43            static LABEL_GUEST_FUNC_NAME: &str = "function_name";
44            metrics::histogram!(METRIC_GUEST_FUNC_DURATION, LABEL_GUEST_FUNC_NAME => name.to_string()).record(duration);
45            result
46        } else {
47            f()
48        }
49    }
50}
51
52/// If the the `function_call_metrics` feature is enabled, this function measures
53/// the time it takes to execute the given closure, and will then emit a host call metric
54/// with the given function name.
55///
56/// If the feature is not enabled, the given closure is executed without any additional metrics being emitted,
57/// and the result of the closure is returned directly.
58pub(crate) fn maybe_time_and_emit_host_call<T, F: FnOnce() -> T>(
59    #[allow(unused_variables)] name: &str,
60    f: F,
61) -> T {
62    cfg_if::cfg_if! {
63        if #[cfg(feature = "function_call_metrics")] {
64            use std::time::Instant;
65
66            let start = Instant::now();
67            let result = f();
68            let duration = start.elapsed();
69
70            static LABEL_HOST_FUNC_NAME: &str = "function_name";
71            metrics::histogram!(METRIC_HOST_FUNC_DURATION, LABEL_HOST_FUNC_NAME => name.to_string()).record(duration);
72            result
73        } else {
74            f()
75        }
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use hyperlight_testing::simple_guest_as_pathbuf;
82    use metrics::{Key, with_local_recorder};
83    use metrics_util::CompositeKey;
84
85    use super::*;
86    use crate::func::Registerable;
87    use crate::{HyperlightError, SandboxBuilder};
88
89    #[test]
90    fn test_metrics_are_emitted() {
91        let recorder = metrics_util::debugging::DebuggingRecorder::new();
92        let snapshotter = recorder.snapshotter();
93        let snapshot = with_local_recorder(&recorder, || {
94            let mut multi = SandboxBuilder::from_file(simple_guest_as_pathbuf())
95                .build()
96                .unwrap();
97
98            multi
99                .call::<i32>("PrintOutput", "Hello".to_string())
100                .unwrap();
101
102            let interrupt_handle = multi.interrupt_handle();
103            multi
104                .register_host_function("CancelGuest", move || {
105                    // The VM observes this cancellation before re-entering the guest.
106                    interrupt_handle.kill();
107                    Ok(())
108                })
109                .unwrap();
110
111            let result = multi.call::<()>("CallHostThenSpin", "CancelGuest".to_string());
112            assert!(
113                matches!(result, Err(HyperlightError::ExecutionCanceledByHost())),
114                "Expected guest cancellation, got {result:?}"
115            );
116
117            snapshotter.snapshot()
118        });
119
120        // Convert snapshot into a hashmap for easier lookup
121        let snapshot = snapshot.into_hashmap();
122
123        cfg_if::cfg_if! {
124            if #[cfg(feature = "function_call_metrics")] {
125                use metrics::Label;
126
127                let expected_num_metrics = 5;
128
129                // Verify that the histogram metrics are recorded correctly
130                assert_eq!(snapshot.len(), expected_num_metrics);
131
132                // 1. Guest call duration
133                let histogram_key = CompositeKey::new(
134                    metrics_util::MetricKind::Histogram,
135                    Key::from_parts(
136                        METRIC_GUEST_FUNC_DURATION,
137                        vec![Label::new("function_name", "PrintOutput")],
138                    ),
139                );
140                let histogram_value = &snapshot.get(&histogram_key).unwrap().2;
141                assert!(
142                    matches!(
143                        histogram_value,
144                        metrics_util::debugging::DebugValue::Histogram(histogram) if histogram.len() == 1
145                    ),
146                    "Histogram metric does not match expected value"
147                );
148
149                // 2. Guest cancellation
150                let counter_key = CompositeKey::new(
151                    metrics_util::MetricKind::Counter,
152                    Key::from_name(METRIC_GUEST_CANCELLATION),
153                );
154                assert_eq!(
155                    snapshot.get(&counter_key).unwrap().2,
156                    metrics_util::debugging::DebugValue::Counter(1)
157                );
158
159                // 3. Guest call duration
160                let histogram_key = CompositeKey::new(
161                    metrics_util::MetricKind::Histogram,
162                    Key::from_parts(
163                        METRIC_GUEST_FUNC_DURATION,
164                        vec![Label::new("function_name", "CallHostThenSpin")],
165                    ),
166                );
167                let histogram_value = &snapshot.get(&histogram_key).unwrap().2;
168                assert!(
169                    matches!(
170                        histogram_value,
171                        metrics_util::debugging::DebugValue::Histogram(histogram) if histogram.len() == 1
172                    ),
173                    "Histogram metric does not match expected value"
174                );
175
176                for function_name in ["HostPrint", "CancelGuest"] {
177                    let histogram_key = CompositeKey::new(
178                        metrics_util::MetricKind::Histogram,
179                        Key::from_parts(
180                            METRIC_HOST_FUNC_DURATION,
181                            vec![Label::new("function_name", function_name)],
182                        ),
183                    );
184                    let histogram_value = &snapshot.get(&histogram_key).unwrap().2;
185                    assert!(
186                        matches!(
187                            histogram_value,
188                            metrics_util::debugging::DebugValue::Histogram(histogram) if histogram.len() == 1
189                        ),
190                        "Histogram metric does not match expected value for {function_name}"
191                    );
192                }
193            } else {
194                // Verify that the counter metrics are recorded correctly
195                assert_eq!(snapshot.len(), 1);
196
197                let counter_key = CompositeKey::new(
198                    metrics_util::MetricKind::Counter,
199                    Key::from_name(METRIC_GUEST_CANCELLATION),
200                );
201                assert_eq!(
202                    snapshot.get(&counter_key).unwrap().2,
203                    metrics_util::debugging::DebugValue::Counter(1)
204                );
205            }
206        }
207    }
208}