Skip to main content

mz_metrics/
lib.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Internal metrics libraries for Materialize.
17
18#![warn(missing_docs, missing_debug_implementations)]
19
20use std::time::Duration;
21
22use mz_dyncfg::{ConfigSet, ConfigUpdates};
23use mz_ore::metrics::MetricsRegistry;
24use tokio::time::Interval;
25
26pub use dyncfgs::all_dyncfgs;
27
28mod dyncfgs;
29pub mod lgalloc;
30pub mod rusage;
31
32/// Handle to metrics defined in this crate.
33#[derive(Debug)]
34pub struct Metrics {
35    config_set: ConfigSet,
36    lgalloc: MetricsTask,
37    lgalloc_map: MetricsTask,
38    rusage: MetricsTask,
39}
40
41static METRICS: std::sync::Mutex<Option<Metrics>> = std::sync::Mutex::new(None);
42
43/// Register all metrics into the provided registry.
44///
45/// We do not recommend calling this function multiple times. It is safe to call this function,
46/// but it might delete previous metrics. If we ever want to change this, we should
47/// remove the shared static mutex and make this function return a handle to the metrics.
48///
49/// This function is async, because it needs to be called from a tokio runtime context.
50#[allow(clippy::unused_async)]
51pub async fn register_metrics_into(metrics_registry: &MetricsRegistry, config_set: ConfigSet) {
52    let update_duration_metric = metrics_registry.register(mz_ore::metric!(
53        name: "mz_metrics_update_duration",
54        help: "The time it took to update lgalloc stats",
55        var_labels: ["name"],
56        buckets: mz_ore::stats::histogram_seconds_buckets(0.000_500, 32.),
57    ));
58
59    let lgalloc = Metrics::new_metrics_task(
60        metrics_registry,
61        lgalloc::register_metrics_into,
62        dyncfgs::MZ_METRICS_LGALLOC_REFRESH_INTERVAL,
63        &update_duration_metric,
64    );
65    let lgalloc_map = Metrics::new_metrics_task(
66        metrics_registry,
67        lgalloc::register_map_metrics_into,
68        dyncfgs::MZ_METRICS_LGALLOC_MAP_REFRESH_INTERVAL,
69        &update_duration_metric,
70    );
71    let rusage = Metrics::new_metrics_task(
72        metrics_registry,
73        rusage::register_metrics_into,
74        dyncfgs::MZ_METRICS_RUSAGE_REFRESH_INTERVAL,
75        &update_duration_metric,
76    );
77
78    *METRICS.lock().expect("lock poisoned") = Some(Metrics {
79        lgalloc,
80        lgalloc_map,
81        rusage,
82        config_set,
83    });
84}
85
86/// Returns the `(name, help, source)` of every metric this crate registers
87/// through a `metric!`-wrapping macro (lgalloc and rusage).
88///
89/// The metrics catalog (`mz-metrics-catalog`) builds the user-facing metrics
90/// docs by scraping `metric!` invocations out of the source with `syn`. These
91/// metrics are invisible to that scraper because their names are assembled at
92/// macro-expansion time, so the catalog
93/// imports them from here instead: it registers them into a throwaway registry
94/// and reads their descriptors back out.
95pub fn describe_metrics() -> Vec<(String, String, &'static str)> {
96    let registry = MetricsRegistry::new();
97
98    let tag = |descs: Vec<(String, String)>, src: &'static str| {
99        descs.into_iter().map(move |(name, help)| (name, help, src))
100    };
101
102    let mut out = Vec::new();
103    out.extend(tag(
104        lgalloc::register_metrics_into(&registry).descs(),
105        lgalloc::SOURCE,
106    ));
107    out.extend(tag(
108        lgalloc::register_map_metrics_into(&registry).descs(),
109        lgalloc::SOURCE,
110    ));
111    out.extend(tag(
112        rusage::register_metrics_into(&registry).descs(),
113        rusage::SOURCE,
114    ));
115    out
116}
117
118/// Update the configuration of the metrics.
119pub fn update_dyncfg(config_updates: &ConfigUpdates) {
120    if let Some(metrics) = METRICS.lock().expect("lock poisoned").as_mut() {
121        metrics.apply_dyncfg_updates(config_updates);
122    }
123}
124
125impl Metrics {
126    /// Update the dynamic configuration.
127    pub fn apply_dyncfg_updates(&mut self, config_updates: &ConfigUpdates) {
128        // Update the config set.
129        config_updates.apply(&self.config_set);
130        // Notify tasks about updated configuration.
131        self.lgalloc.update_dyncfg(&self.config_set);
132        self.lgalloc_map.update_dyncfg(&self.config_set);
133        self.rusage.update_dyncfg(&self.config_set);
134    }
135
136    fn new_metrics_task<T: MetricsUpdate>(
137        metrics_registry: &MetricsRegistry,
138        constructor: impl FnOnce(&MetricsRegistry) -> T,
139        interval_config: mz_dyncfg::Config<Duration>,
140        update_duration_metric: &mz_ore::metrics::HistogramVec,
141    ) -> MetricsTask {
142        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
143
144        // Start disabled.
145        let mut interval: Option<Interval> = None;
146
147        let update_duration_metric =
148            update_duration_metric.get_delete_on_drop_metric(&[T::NAME][..]);
149
150        let mut metrics = constructor(metrics_registry);
151
152        let mut update_metrics = move || {
153            tracing::debug!(metrics = T::NAME, "updating metrics");
154            let start = std::time::Instant::now();
155            if let Err(err) = metrics.update() {
156                tracing::error!(metrics = T::NAME, ?err, "metrics update failed");
157            }
158            let elapsed = start.elapsed();
159            update_duration_metric.observe(elapsed.as_secs_f64());
160        };
161
162        let update_interval = |new_interval, interval: &mut Option<Interval>| {
163            // Zero duration disables ticking.
164            if new_interval == Duration::ZERO {
165                *interval = None;
166                return;
167            }
168            // Prevent no-op changes.
169            if Some(new_interval) == interval.as_ref().map(Interval::period) {
170                return;
171            }
172            tracing::debug!(metrics = T::NAME, ?new_interval, "updating interval");
173            let mut new_interval = tokio::time::interval(new_interval);
174            new_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
175            *interval = Some(new_interval);
176        };
177
178        mz_ore::task::spawn(|| format!("mz_metrics_update({})", T::NAME), async move {
179            loop {
180                tokio::select! {
181                    _ = async {
182                        interval.as_mut().unwrap().tick().await
183                    }, if interval.is_some() => {
184                        update_metrics()
185                    }
186                    new_interval = rx.recv() => match new_interval {
187                        Some(new_interval) => update_interval(new_interval, &mut interval),
188                        None => break,
189                    }
190                }
191            }
192        });
193
194        MetricsTask {
195            tx,
196            interval_config,
197        }
198    }
199}
200
201/// Behavior to update metrics.
202pub trait MetricsUpdate: Send + Sync + 'static {
203    /// Error type to indicate updating failed.
204    type Error: std::fmt::Debug;
205    /// A human-readable name.
206    const NAME: &'static str;
207    /// Update the metrics.
208    fn update(&mut self) -> Result<(), Self::Error>;
209}
210
211#[derive(Debug)]
212struct MetricsTask {
213    interval_config: mz_dyncfg::Config<Duration>,
214    tx: tokio::sync::mpsc::UnboundedSender<Duration>,
215}
216
217impl MetricsTask {
218    pub(crate) fn update_dyncfg(&self, config_set: &ConfigSet) {
219        self.tx
220            .send(self.interval_config.get(config_set))
221            .expect("Receiver exists");
222    }
223}