Line data Source code
1 : use std::{
2 : sync::{Arc, RwLock},
3 : time::{Duration, Instant},
4 : };
5 :
6 : use metrics::{IntGauge, proto::MetricFamily, register_int_gauge};
7 : use once_cell::sync::Lazy;
8 :
9 0 : pub static METRICS_STALE_MILLIS: Lazy<IntGauge> = Lazy::new(|| {
10 0 : register_int_gauge!(
11 : "metrics_metrics_stale_milliseconds",
12 : "The current metrics stale time in milliseconds"
13 : )
14 0 : .expect("failed to define a metric")
15 0 : });
16 :
17 : #[derive(Debug)]
18 : pub struct CollectedMetrics {
19 : pub metrics: Vec<MetricFamily>,
20 : pub collected_at: Instant,
21 : }
22 :
23 : impl CollectedMetrics {
24 0 : fn new(metrics: Vec<MetricFamily>) -> Self {
25 0 : Self {
26 0 : metrics,
27 0 : collected_at: Instant::now(),
28 0 : }
29 0 : }
30 : }
31 :
32 : #[derive(Debug)]
33 : pub struct MetricsCollector {
34 : last_collected: RwLock<Arc<CollectedMetrics>>,
35 : }
36 :
37 : impl MetricsCollector {
38 0 : pub fn new() -> Self {
39 0 : Self {
40 0 : last_collected: RwLock::new(Arc::new(CollectedMetrics::new(vec![]))),
41 0 : }
42 0 : }
43 :
44 : #[tracing::instrument(name = "metrics_collector", skip_all)]
45 : pub fn run_once(&self, cache_metrics: bool) -> Arc<CollectedMetrics> {
46 : let started = Instant::now();
47 : let metrics = metrics::gather();
48 : let collected = Arc::new(CollectedMetrics::new(metrics));
49 : if cache_metrics {
50 : let mut guard = self.last_collected.write().unwrap();
51 : *guard = collected.clone();
52 : }
53 : tracing::info!(
54 : "Collected {} metric families in {} ms",
55 : collected.metrics.len(),
56 : started.elapsed().as_millis()
57 : );
58 : collected
59 : }
60 :
61 0 : pub fn last_collected(&self) -> Arc<CollectedMetrics> {
62 0 : self.last_collected.read().unwrap().clone()
63 0 : }
64 : }
65 :
66 : impl Default for MetricsCollector {
67 0 : fn default() -> Self {
68 0 : Self::new()
69 0 : }
70 : }
71 :
72 : // Interval for metrics collection. Currently hard-coded to be the same as the metrics scape interval from the obs agent
73 : pub static METRICS_COLLECTION_INTERVAL: Duration = Duration::from_secs(30);
74 :
75 : pub static METRICS_COLLECTOR: Lazy<MetricsCollector> = Lazy::new(MetricsCollector::default);
|