hyperlight_host/metrics/
mod.rs

1
2
3
4
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
66
67
68
69
70
71
72
73
74
75
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
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
220
221
222
223
224
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
Copyright 2024 The Hyperlight Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

use std::collections::HashMap;
use std::sync::Once;

use log::error;
use once_cell::sync::OnceCell;
use prometheus::{default_registry, histogram_opts, opts, HistogramOpts, Opts, Registry};
use strum::{IntoEnumIterator, VariantNames};

use crate::error::HyperlightError::{Error, MetricNotFound};
use crate::{log_then_return, new_error, Result};
mod int_gauge_vec;
/// An Integer Gauge Metric for Hyperlight
///
pub use int_gauge_vec::IntGaugeVec;
mod int_gauge;
/// An Integer Gauge Metric for Hyperlight
pub use int_gauge::IntGauge;
mod int_counter_vec;
/// An Integer Counter Vec for Hyperlight
pub use int_counter_vec::IntCounterVec;
mod int_counter;
/// An Integer Counter for Hyperlight
pub use int_counter::IntCounter;
mod histogram_vec;
/// A Histogram Vec for Hyperlight
pub use histogram_vec::HistogramVec;
mod histogram;
/// AHistogram for Hyperlight
pub use histogram::Histogram;
/// A trait that should be implemented by all enums that represent hyperlight metrics
pub trait HyperlightMetricEnum<T>:
    IntoEnumIterator + VariantNames + From<T> + Into<&'static str>
where
    &'static str: From<Self>,
    &'static str: for<'a> From<&'a Self>,
{
    /// A function that should return a static reference to a Once that is used to guard the initialization of the metrics hashmap.
    fn get_init_metrics() -> &'static Once;
    /// A function that should return a static reference to a OnceCell that is used to store the metrics hashmap.
    fn get_metrics() -> &'static OnceCell<HashMap<&'static str, HyperlightMetric>>;
    /// A function that should return a static reference to a slice of HyperlightMetricDefinitions that are used to initialize the metrics hashmap.
    fn get_metric_definitions() -> &'static [HyperlightMetricDefinition];

    /// Gets a HyperlightMetric from the hashmap using the enum variant name as the key
    #[inline]
    fn get_hyperlight_metric(&self) -> Result<&HyperlightMetric> {
        Self::get_init_metrics().call_once(|| {
            let result = init_metrics(Self::get_metric_definitions(), Self::get_metrics());
            if let Err(e) = result {
                error!("Error initializing metrics : {0:?}", e);
            }
        });
        let key: &'static str = <&Self as Into<&'static str>>::into(self);
        HyperlightMetric::get_metric_using_key(key, Self::get_hash_map()?)
    }
    /// Gets the hashmap using the containing the metrics
    #[inline]
    fn get_hash_map() -> Result<&'static HashMap<&'static str, HyperlightMetric>> {
        Self::get_metrics()
            .get()
            .ok_or_else(|| Error("metrics hashmap not initialized".to_string()))
    }
}
/// A trait that should be implemented by all enums that represent hyperlight metrics to
/// convert the enum into a HyperlightMetric
pub trait HyperlightMetricOps {
    /// Converts the enum into a HyperlightMetric
    fn get_metric(&self) -> Result<&HyperlightMetric>;
}

/// A trait that should be implemented by all hyperlight metric definitions to convert the metric into a HyperlightMetric
pub trait GetHyperlightMetric<T> {
    /// Converts the metric into a HyperlightMetric
    fn metric(&self) -> Result<&T>;
}

impl<T: HyperlightMetricEnum<T>> HyperlightMetricOps for T
where
    &'static str: From<T>,
    for<'a> &'static str: From<&'a T>,
{
    fn get_metric(&self) -> Result<&HyperlightMetric> {
        self.get_hyperlight_metric()
    }
}

/// Initializes the metrics hashmap using the metric definitions
#[inline]
fn init_metrics(
    metric_definitions: &[HyperlightMetricDefinition],
    metrics: &OnceCell<HashMap<&'static str, HyperlightMetric>>,
) -> Result<()> {
    let mut hash_map: HashMap<&'static str, HyperlightMetric> = HashMap::new();
    register_metrics(metric_definitions, &mut hash_map)?;
    // the only failure case is if the metrics hashmap is already set which should not be possible
    // but if it were to happen we dont care.
    if let Err(e) = metrics.set(hash_map) {
        error!("metrics hashmap already set : {0:?}", e);
    }
    Ok(())
}
//TODO: Remove this when we have uses of all metric types
#[allow(dead_code)]
#[derive(Debug)]
/// The types of Hyperlight metrics that can be created
pub enum HyperlightMetricType {
    /// A counter that can only be incremented
    IntCounter,
    /// A counter that can only be incremented and has labels
    IntCounterVec,
    /// A gauge that can be incremented, decremented, set, added to, and subtracted from
    IntGauge,
    /// A gauge that can be incremented, decremented, set, added to, and subtracted from and has labels
    IntGaugeVec,
    /// A histogram that can observe values for activities   
    Histogram,
    /// A histogram that can observe values for activities and has labels
    HistogramVec,
}

/// The definition of a Hyperlight metric
pub struct HyperlightMetricDefinition {
    /// The name of the metric
    pub name: &'static str,
    /// The help text for the metric
    pub help: &'static str,
    /// The type of the metric
    pub metric_type: HyperlightMetricType,
    /// The labels for the metric
    pub labels: &'static [&'static str],
    /// The buckets for the metric
    pub buckets: &'static [f64],
}

fn register_metrics(
    metric_definitions: &[HyperlightMetricDefinition],
    hash_map: &mut HashMap<&'static str, HyperlightMetric>,
) -> Result<()> {
    for metric_definition in metric_definitions {
        let metric: HyperlightMetric = match &metric_definition.metric_type {
            HyperlightMetricType::IntGauge => {
                IntGauge::new(metric_definition.name, metric_definition.help)?.into()
            }

            HyperlightMetricType::IntCounterVec => IntCounterVec::new(
                metric_definition.name,
                metric_definition.help,
                metric_definition.labels,
            )?
            .into(),

            HyperlightMetricType::IntCounter => {
                IntCounter::new(metric_definition.name, metric_definition.help)?.into()
            }
            HyperlightMetricType::HistogramVec => HistogramVec::new(
                metric_definition.name,
                metric_definition.help,
                metric_definition.labels,
                metric_definition.buckets.to_vec(),
            )?
            .into(),
            HyperlightMetricType::Histogram => Histogram::new(
                metric_definition.name,
                metric_definition.help,
                metric_definition.buckets.to_vec(),
            )?
            .into(),
            HyperlightMetricType::IntGaugeVec => IntGaugeVec::new(
                metric_definition.name,
                metric_definition.help,
                metric_definition.labels,
            )?
            .into(),
        };

        hash_map.insert(metric_definition.name, metric);
    }
    Ok(())
}

#[derive(Debug)]
/// An instance of a Hyperlight metric
pub enum HyperlightMetric {
    /// A counter that can only be incremented
    IntCounter(IntCounter),
    /// A counter that can only be incremented and has labels
    IntCounterVec(IntCounterVec),
    /// A gauge that can be incremented, decremented, set, added to, and subtracted from
    IntGauge(IntGauge),
    /// A gauge that can be incremented, decremented, set, added to, and subtracted from and has labels
    IntGaugeVec(IntGaugeVec),
    /// A histogram that can observe values for activities
    Histogram(Histogram),
    /// A histogram that can observe values for activities and has labels
    HistogramVec(HistogramVec),
}

impl HyperlightMetric {
    #[inline]
    fn get_metric_using_key<'a>(
        key: &'static str,
        hash_map: &'a HashMap<&'static str, HyperlightMetric>,
    ) -> Result<&'a HyperlightMetric> {
        hash_map.get(key).ok_or_else(|| MetricNotFound(key))
    }
}

// The registry used for all metrics, this can be set by the user of the library, if its not set then the default will be used.

static REGISTRY: OnceCell<&Registry> = OnceCell::new();

/// Get the registry to be used for all metrics, this can be set by the user of the library, if its not set then the default registry will be used.
#[inline]
pub fn get_metrics_registry() -> &'static Registry {
    REGISTRY.get_or_init(default_registry)
}
/// Set the registry to be used for all metrics, this can be set by the user of the library, if its not set then the default registry will be used.
/// This function should be called before any other function in this module is called.
///
/// The user of can then use the registry to gather metrics from the library.
pub fn set_metrics_registry(registry: &'static Registry) -> Result<()> {
    match REGISTRY.get() {
        Some(_) => {
            log_then_return!("Registry was already set");
        }
        None => {
            REGISTRY
                .set(registry)
                // This should be impossible
                .map_err(|e| new_error!("Registry alread set : {0:?}", e))
        }
    }
}

fn get_metric_opts(name: &str, help: &str) -> Opts {
    let opts = opts!(name, help);
    opts.namespace("hyperlight")
}

fn get_histogram_opts(name: &str, help: &str, buckets: Vec<f64>) -> HistogramOpts {
    let mut opts = histogram_opts!(name, help);
    opts = opts.namespace("hyperlight");
    opts.buckets(buckets)
}

/// Provides functionaility to help with testing Hyperlight Metrics
pub mod tests {
    use std::collections::HashSet;

    use super::*;

    /// A trait that provides test helper functions for Hyperlight Metrics
    pub trait HyperlightMetricEnumTest<T>:
        HyperlightMetricEnum<T> + From<T> + Into<&'static str>
    where
        &'static str: From<Self>,
        &'static str: for<'a> From<&'a Self>,
    {
        /// Defines a function that should return the names of all the metric enum variants
        fn get_enum_variant_names() -> &'static [&'static str];

        /// Provides a function to test that all hyperlight metric definitions in a module have a corresponding enum variant
        /// Should be called in tests in modules that define hyperlight metrics.
        #[track_caller]
        fn enum_has_variant_for_all_metrics() {
            let metric_definitions = Self::get_metric_definitions().iter();
            for metric_definition in metric_definitions {
                let metric_defintion_name = metric_definition.name;
                assert!(
                    Self::get_enum_variant_names().contains(&metric_defintion_name),
                    "Metric Definition Name {} not found",
                    metric_defintion_name,
                );
            }
        }

        /// Provides a function to test that all hyperlight metric definitions have a unique help text
        /// and that there are the same number of enum variants as metric definitions
        /// Should be called in tests in modules that define hyperlight metrics.
        #[track_caller]
        fn check_metric_definitions() {
            let sandbox_metric_definitions = Self::get_metric_definitions();
            let metric_definitions = sandbox_metric_definitions.iter();
            let mut help_text = HashSet::new();
            for metric_definition in metric_definitions {
                assert!(
                    help_text.insert(metric_definition.help),
                    "duplicate metric help definition for {}",
                    metric_definition.name
                );
            }
            assert_eq!(
                Self::get_enum_variant_names().len(),
                sandbox_metric_definitions.len()
            );
        }

        /// Gets a named int gauge metric
        fn get_intguage_metric(name: &str) -> Result<&IntGauge> {
            Self::get_metrics()
                .get()
                .ok_or_else(|| new_error!("metrics hashmap not initialized"))?
                .get(name)
                .ok_or_else(|| new_error!("metric not found : {0:?}", name))?
                .try_into()
        }

        /// Gets a named int counter vec metric
        fn get_intcountervec_metric(name: &str) -> Result<&IntCounterVec> {
            Self::get_metrics()
                .get()
                .ok_or_else(|| new_error!("metrics hashmap not initialized"))?
                .get(name)
                .ok_or_else(|| new_error!("metric not found : {0:?}", name))?
                .try_into()
        }

        /// Gets a named int counter metric
        fn get_intcounter_metric(name: &str) -> Result<&IntCounter> {
            Self::get_metrics()
                .get()
                .ok_or_else(|| new_error!("metrics hashmap not initialized"))?
                .get(name)
                .ok_or_else(|| new_error!("metric not found : {0:?}", name))?
                .try_into()
        }

        /// Gets a named histogram vec metric
        fn get_histogramvec_metric(name: &str) -> Result<&HistogramVec> {
            Self::get_metrics()
                .get()
                .ok_or_else(|| new_error!("metrics hashmap not initialized"))?
                .get(name)
                .ok_or_else(|| new_error!("metric not found : {0:?}", name))?
                .try_into()
        }
    }
}