hyperlight_host/metrics/
int_gauge.rs

1/*
2Copyright 2024 The Hyperlight Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17use prometheus::core::{AtomicI64, GenericGauge};
18use prometheus::register_int_gauge_with_registry;
19use tracing::{instrument, Span};
20
21use super::{
22    get_metric_opts, get_metrics_registry, GetHyperlightMetric, HyperlightMetric,
23    HyperlightMetricOps,
24};
25use crate::{new_error, HyperlightError, Result};
26
27/// A gauge backed by an `AtomicI64`
28#[derive(Debug)]
29pub struct IntGauge {
30    gauge: GenericGauge<AtomicI64>,
31    /// The name of the gauge
32    pub name: &'static str,
33}
34
35impl IntGauge {
36    /// Creates a new gauge and registers it with the metric registry
37    #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")]
38    pub fn new(name: &'static str, help: &str) -> Result<Self> {
39        let registry = get_metrics_registry();
40        let opts = get_metric_opts(name, help);
41        let gauge = register_int_gauge_with_registry!(opts, registry)?;
42        Ok(Self { gauge, name })
43    }
44    /// Increments a gauge by 1
45    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
46    pub fn inc(&self) {
47        self.gauge.inc();
48    }
49    /// Decrements a gauge by 1
50    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
51    pub fn dec(&self) {
52        self.gauge.dec();
53    }
54    /// Gets the value of a gauge
55    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
56    pub fn set(&self, val: i64) {
57        self.gauge.set(val);
58    }
59    /// Resets a gauge
60    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
61    pub fn get(&self) -> i64 {
62        self.gauge.get()
63    }
64    /// Adds a value to a gauge
65    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
66    pub fn add(&self, val: i64) {
67        self.gauge.add(val);
68    }
69    /// Subtracts a value from a gauge
70    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
71    pub fn sub(&self, val: i64) {
72        self.gauge.sub(val)
73    }
74}
75
76impl<S: HyperlightMetricOps> GetHyperlightMetric<IntGauge> for S {
77    #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")]
78    fn metric(&self) -> Result<&IntGauge> {
79        let metric = self.get_metric()?;
80        <&HyperlightMetric as TryInto<&IntGauge>>::try_into(metric)
81    }
82}
83
84impl<'a> TryFrom<&'a HyperlightMetric> for &'a IntGauge {
85    type Error = HyperlightError;
86    #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")]
87    fn try_from(metric: &'a HyperlightMetric) -> Result<Self> {
88        match metric {
89            HyperlightMetric::IntGauge(gauge) => Ok(gauge),
90            _ => Err(new_error!("metric is not a IntGauge")),
91        }
92    }
93}
94
95impl From<IntGauge> for HyperlightMetric {
96    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
97    fn from(gauge: IntGauge) -> Self {
98        HyperlightMetric::IntGauge(gauge)
99    }
100}
101
102/// Increments an IntGauge by 1 or logs an error if the metric is not found
103#[macro_export]
104macro_rules! int_gauge_inc {
105    ($metric:expr) => {{
106        match $crate::metrics::GetHyperlightMetric::<$crate::metrics::IntGauge>::metric($metric) {
107            Ok(val) => val.inc(),
108            Err(e) => log::error!("error getting metric: {}", e),
109        };
110    }};
111}
112
113/// Decrements an IntGauge by 1 or logs an error if the metric is not found
114#[macro_export]
115macro_rules! int_gauge_dec {
116    ($metric:expr) => {{
117        match $crate::metrics::GetHyperlightMetric::<$crate::metrics::IntGauge>::metric($metric) {
118            Ok(val) => val.dec(),
119            Err(e) => log::error!("error getting metric: {}", e),
120        };
121    }};
122}
123
124/// Sets an IntGauge to value or logs an error if the metric is not found
125#[macro_export]
126macro_rules! int_gauge_set {
127    ($metric:expr, $val:expr) => {{
128        match $crate::metrics::GetHyperlightMetric::<$crate::metrics::IntGauge>::metric($metric) {
129            Ok(val) => val.set($val),
130            Err(e) => log::error!("error getting metric: {}", e),
131        };
132    }};
133}
134
135/// Gets the value of an IntGauge logs an error
136/// and returns 0 if the metric is not found
137#[macro_export]
138macro_rules! int_gauge_get {
139    ($metric:expr) => {{
140        match $crate::metrics::GetHyperlightMetric::<$crate::metrics::IntGauge>::metric($metric) {
141            Ok(val) => val.get(),
142            Err(e) => {
143                log::error!("error getting metric: {}", e);
144                0
145            }
146        }
147    }};
148}
149
150/// Adds a value to an IntGauge or logs an error if the metric is not found
151#[macro_export]
152macro_rules! int_gauge_add {
153    ($metric:expr, $val:expr) => {{
154        match $crate::metrics::GetHyperlightMetric::<$crate::metrics::IntGauge>::metric($metric) {
155            Ok(val) => val.add($val),
156            Err(e) => log::error!("error getting metric: {}", e),
157        };
158    }};
159}
160
161/// Subtracts a value from an IntGauge or logs an error if the metric is not found
162#[macro_export]
163macro_rules! int_gauge_sub {
164    ($metric:expr, $val:expr) => {{
165        match $crate::metrics::GetHyperlightMetric::<$crate::metrics::IntGauge>::metric($metric) {
166            Ok(val) => val.sub($val),
167            Err(e) => log::error!("error getting metric: {}", e),
168        };
169    }};
170}