mithril_aggregator/metrics/
service.rs

1use std::collections::HashMap;
2
3use mithril_metric::{MetricCounterWithLabels, MetricsServiceExporter, build_metrics_service};
4
5use mithril_metric::metric::{MetricCollector, MetricCounter};
6use prometheus::proto::{LabelPair, Metric, MetricFamily};
7
8// Those are three differents dimensions, they use the same value to simplify usage in Grafana
9static CLIENT_ORIGIN_TAG_LABEL: &str = "origin_tag";
10static SIGNER_REGISTRATION_ORIGIN_TAG_LABEL: &str = "origin_tag";
11static SIGNER_SIGNATURE_ORIGIN_TAG_LABEL: &str = "origin_tag";
12static CLIENT_TYPE_LABEL: &str = "client_type";
13
14build_metrics_service!(
15    MetricsService,
16
17    certificate_detail_total_served_since_startup:MetricCounterWithLabels(
18        "certificate_detail_total_served_since_startup",
19        "Number of certificate details served since startup on a Mithril aggregator node",
20        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
21    ),
22    artifact_detail_cardano_immutable_files_full_total_served_since_startup:MetricCounterWithLabels(
23        "mithril_aggregator_artifact_detail_cardano_db_total_served_since_startup",
24        "Number of Cardano immutable files full artifact details served since startup on a Mithril aggregator node",
25        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
26    ),
27    cardano_immutable_files_full_total_restoration_since_startup:MetricCounterWithLabels(
28        "mithril_aggregator_cardano_db_total_restoration_since_startup",
29        "Number of Cardano immutable files full restorations since startup on a Mithril aggregator node",
30        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
31    ),
32    cardano_database_immutable_files_restored_since_startup:MetricCounterWithLabels(
33        "mithril_aggregator_cardano_db_immutable_files_restored_since_startup",
34        "Number of Cardano immutable files restored since startup on a Mithril aggregator node",
35        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
36    ),
37    cardano_database_ancillary_files_restored_since_startup:MetricCounterWithLabels(
38        "mithril_aggregator_cardano_db_ancillary_files_restored_since_startup",
39        "Number of Cardano ancillary files restored since startup on a Mithril aggregator node",
40        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
41    ),
42    cardano_database_complete_restoration_since_startup:MetricCounterWithLabels(
43        "mithril_aggregator_cardano_db_complete_restoration_since_startup",
44        "Number of complete Cardano database restoration since startup on a Mithril aggregator node",
45        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
46    ),
47    cardano_database_partial_restoration_since_startup:MetricCounterWithLabels(
48        "mithril_aggregator_cardano_db_partial_restoration_since_startup",
49        "Number of partial Cardano database restoration since startup on a Mithril aggregator node",
50        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
51    ),
52    artifact_detail_cardano_database_total_served_since_startup:MetricCounterWithLabels(
53        "mithril_aggregator_artifact_detail_cardano_database_total_served_since_startup",
54        "Number of Cardano database artifact details served since startup on a Mithril aggregator node",
55        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
56    ),
57    artifact_detail_mithril_stake_distribution_total_served_since_startup:MetricCounterWithLabels(
58        "mithril_aggregator_artifact_detail_mithril_stake_distribution_total_served_since_startup",
59        "Number of Mithril stake distribution artifact details served since startup on a Mithril aggregator node",
60        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
61    ),
62    artifact_detail_cardano_stake_distribution_total_served_since_startup:MetricCounterWithLabels(
63        "mithril_aggregator_artifact_detail_cardano_stake_distribution_total_served_since_startup",
64        "Number of Cardano stake distribution artifact details served since startup on a Mithril aggregator node",
65        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
66    ),
67    artifact_detail_cardano_transaction_total_served_since_startup:MetricCounterWithLabels(
68        "mithril_aggregator_artifact_detail_cardano_transaction_total_served_since_startup",
69        "Number of Cardano transaction artifact details served since startup on a Mithril aggregator node",
70        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
71    ),
72    proof_cardano_transaction_total_proofs_served_since_startup:MetricCounterWithLabels(
73        "mithril_aggregator_proof_cardano_transaction_total_proofs_served_since_startup",
74        "Number of Cardano transaction proofs served since startup on a Mithril aggregator node",
75        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
76    ),
77    proof_cardano_transaction_total_transactions_served_since_startup:MetricCounterWithLabels(
78        "mithril_aggregator_proof_cardano_transaction_total_transactions_served_since_startup",
79        "Number of Cardano transaction hashes requested for proof since startup on a Mithril aggregator node",
80        &[CLIENT_ORIGIN_TAG_LABEL, CLIENT_TYPE_LABEL]
81    ),
82    signer_registration_total_received_since_startup:MetricCounterWithLabels(
83        "mithril_aggregator_signer_registration_total_received_since_startup",
84        "Number of signer registrations received since startup on a Mithril aggregator node",
85        &[SIGNER_REGISTRATION_ORIGIN_TAG_LABEL]
86    ),
87    signer_registration_total_successful_since_startup:MetricCounterWithLabels(
88        "mithril_aggregator_signer_registration_total_successful_since_startup",
89        "Number of successful signer registrations received since startup on a Mithril aggregator node",
90        &[SIGNER_REGISTRATION_ORIGIN_TAG_LABEL]
91    ),
92    signature_registration_total_received_since_startup:MetricCounterWithLabels(
93        "mithril_aggregator_signature_registration_total_received_since_startup",
94        "Number of signature registrations received since startup on a Mithril aggregator node",
95        &[SIGNER_SIGNATURE_ORIGIN_TAG_LABEL]
96    ),
97    signature_registration_total_successful_since_startup:MetricCounterWithLabels(
98        "mithril_aggregator_signature_registration_total_successful_since_startup",
99        "Number of successful signature registrations received since startup on a Mithril aggregator node",
100        &[SIGNER_SIGNATURE_ORIGIN_TAG_LABEL]
101    ),
102    certificate_total_produced_since_startup:MetricCounter(
103        "mithril_aggregator_certificate_total_produced_since_startup",
104        "Number of certificates produced since startup on a Mithril aggregator node"
105    ),
106    artifact_cardano_immutable_files_full_total_produced_since_startup:MetricCounter(
107        "mithril_aggregator_artifact_cardano_db_total_produced_since_startup",
108        "Number of Cardano immutable files full artifacts produced since startup on a Mithril aggregator node"
109    ),
110    artifact_cardano_database_total_produced_since_startup:MetricCounter(
111        "mithril_aggregator_artifact_cardano_database_total_produced_since_startup",
112        "Number of Cardano database artifacts produced since startup on a Mithril aggregator node"
113    ),
114    artifact_mithril_stake_distribution_total_produced_since_startup:MetricCounter(
115        "mithril_aggregator_artifact_mithril_stake_distribution_total_produced_since_startup",
116        "Number of Mithril stake distribution artifacts produced since startup on a Mithril aggregator node"
117    ),
118    artifact_cardano_stake_distribution_total_produced_since_startup:MetricCounter(
119        "mithril_aggregator_artifact_cardano_stake_distribution_total_produced_since_startup",
120        "Number of Cardano stake distribution artifacts produced since startup on a Mithril aggregator node"
121    ),
122    artifact_cardano_transaction_total_produced_since_startup:MetricCounter(
123        "mithril_aggregator_artifact_cardano_transaction_total_produced_since_startup",
124        "Number of Cardano transaction artifacts produced since startup on a Mithril aggregator node"
125    ),
126    artifact_cardano_blocks_transactions_total_produced_since_startup:MetricCounter(
127        "mithril_aggregator_artifact_cardano_blocks_transactions_total_produced_since_startup",
128        "Number of Cardano blocks transactions artifacts produced since startup on a Mithril aggregator node"
129    ),
130    runtime_cycle_success_since_startup:MetricCounter(
131        "mithril_aggregator_runtime_cycle_success_since_startup",
132        "Number of successful runtime cycles since startup on a Mithril aggregator"
133    ),
134    runtime_cycle_total_since_startup:MetricCounter(
135        "mithril_aggregator_runtime_cycle_total_since_startup",
136        "Number of runtime cycles since startup on a Mithril aggregator"
137    )
138
139);
140
141impl MetricsService {
142    /// Export metrics in map.
143    pub fn export_metrics_map(&self) -> HashMap<String, HashMap<String, MetricLabelValueMap>> {
144        self.registry
145            .gather()
146            .iter()
147            .map(|metric_family| {
148                (
149                    metric_family.name().to_string(),
150                    self.build_metric_map(metric_family),
151                )
152            })
153            .collect()
154    }
155
156    fn build_label_key(&self, labels: &[LabelPair]) -> String {
157        labels.iter().map(|p| p.value()).collect::<Vec<_>>().join(",")
158    }
159
160    fn build_metric_map(
161        &self,
162        metric_family: &MetricFamily,
163    ) -> HashMap<String, MetricLabelValueMap> {
164        metric_family
165            .get_metric()
166            .iter()
167            .map(|m| {
168                (
169                    self.build_label_key(m.get_label()),
170                    MetricLabelValueMap::new(m.clone()),
171                )
172            })
173            .collect()
174    }
175}
176
177type LabelName = String;
178type LabelValue = String;
179
180#[derive(Debug, Clone, PartialEq, Eq)]
181/// [MetricLabelValueMap] represent a metric with a label_value_map and a counter.
182pub struct MetricLabelValueMap {
183    /// HashMap of label names and their corresponding values (eg. `{"origin_tag": "HTTP", "client_type": "CLI"}`).
184    pub label_value_map: HashMap<LabelName, LabelValue>,
185    /// Counter value of the metric
186    pub counter: i32,
187}
188
189impl MetricLabelValueMap {
190    /// Create a new MetricMap from a Metric Promotheus Metric.
191    pub fn new(metric: Metric) -> Self {
192        Self {
193            label_value_map: metric
194                .get_label()
195                .iter()
196                .map(|label| (label.name().to_string(), label.value().to_string()))
197                .collect(),
198            counter: metric.get_counter().as_ref().unwrap_or_default().value() as i32,
199        }
200    }
201}
202
203impl Default for MetricLabelValueMap {
204    /// Create a new MetricMap with an empty key_value map and a counter set to 0.
205    fn default() -> Self {
206        Self {
207            label_value_map: HashMap::new(),
208            counter: 0,
209        }
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use crate::test::TestLogger;
216
217    use super::*;
218
219    #[test]
220    fn should_export_counter_metrics_in_a_map() {
221        let metrics_service = MetricsService::new(TestLogger::stdout()).unwrap();
222        let metric_a = metrics_service.get_runtime_cycle_total_since_startup();
223        let metric_b = metrics_service.get_certificate_total_produced_since_startup();
224        metric_a.increment_by(5);
225        metric_b.increment_by(12);
226
227        let export = metrics_service.export_metrics_map();
228        assert_eq!(5, export[&metric_a.name()][""].counter);
229        assert_eq!(12, export[&metric_b.name()][""].counter);
230    }
231
232    #[test]
233    fn should_export_counter_metrics_with_label_in_a_map() {
234        let metrics_service = MetricsService::new(TestLogger::stdout()).unwrap();
235        let metric_a = metrics_service.get_certificate_detail_total_served_since_startup();
236        metric_a.increment_by(&["A", "B"], 5);
237        metric_a.increment_by(&["1", "2"], 12);
238
239        let export = metrics_service.export_metrics_map();
240
241        let metric_a_token_a_b = export[&metric_a.name()]["B,A"].clone();
242        let metric_a_token_1_2 = export[&metric_a.name()]["2,1"].clone();
243
244        assert_eq!(5, metric_a_token_a_b.to_owned().counter);
245        assert_eq!(
246            "A",
247            metric_a_token_a_b.to_owned().label_value_map["origin_tag"]
248        );
249        assert_eq!(
250            "B",
251            metric_a_token_a_b.to_owned().label_value_map["client_type"]
252        );
253
254        assert_eq!(12, metric_a_token_1_2.to_owned().counter);
255        assert_eq!(
256            "1",
257            metric_a_token_1_2.to_owned().label_value_map["origin_tag"]
258        );
259        assert_eq!(
260            "2",
261            metric_a_token_1_2.to_owned().label_value_map["client_type"]
262        );
263    }
264
265    #[test]
266    fn should_export_several_times_and_counter_return_values_since_start() {
267        let metrics_service = MetricsService::new(TestLogger::stdout()).unwrap();
268        let metric_a = metrics_service.get_runtime_cycle_total_since_startup();
269        metric_a.increment_by(5);
270
271        let export = metrics_service.export_metrics_map();
272        assert_eq!(5, export[&metric_a.name()][""].counter);
273
274        metric_a.increment();
275        let export = metrics_service.export_metrics_map();
276        assert_eq!(6, export[&metric_a.name()][""].counter);
277    }
278
279    #[test]
280    fn should_export_counter_even_the_value_is_0() {
281        let metrics_service = MetricsService::new(TestLogger::stdout()).unwrap();
282        let metric_a = metrics_service.get_runtime_cycle_total_since_startup();
283
284        let export = metrics_service.export_metrics_map();
285        assert_eq!(0, export[&metric_a.name()][""].counter);
286    }
287
288    #[test]
289    fn metric_service_should_only_contain_counters_as_export_metrics_map_does_not_yet_support_other_types()
290     {
291        let metrics_service = MetricsService::new(TestLogger::stdout()).unwrap();
292
293        for metric_family in metrics_service.registry.gather() {
294            for metric in metric_family.get_metric() {
295                assert!(metric.get_counter().is_some());
296            }
297        }
298    }
299}