Skip to main content

mz_orchestratord/
metrics.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::BTreeMap;
11use std::sync::{Arc, Mutex};
12use std::time::Duration;
13
14use axum::{Extension, Router, body::Body, routing::get};
15use http::{HeaderMap, Method, Request, Response, StatusCode};
16use k8s_controller::PrometheusMetrics;
17use prometheus::core::AtomicU64;
18use prometheus::{Encoder, TextEncoder};
19use tower_http::{classify::ServerErrorsFailureClass, trace::TraceLayer};
20use tracing::{Level, Span};
21use uuid::Uuid;
22
23use mz_ore::metric;
24use mz_ore::metrics::{
25    DeleteOnDropGauge, MetricTag, MetricVisibility, MetricsRegistry, UIntGauge, UIntGaugeVec,
26};
27
28type EnvironmentGauge = DeleteOnDropGauge<AtomicU64, Vec<String>>;
29
30#[derive(Debug)]
31pub struct Metrics {
32    pub is_leader: UIntGauge,
33    pub environmentd_needs_update: UIntGauge,
34    environment_info: UIntGaugeVec,
35    environment_active_generation: UIntGaugeVec,
36    /// The series published for each `Materialize` resource, keyed by its
37    /// namespace and name, or `None` while this replica doesn't hold the
38    /// leadership lease. Dropping an entry removes its series.
39    environments: Mutex<Option<BTreeMap<(String, String), EnvironmentSeries>>>,
40    /// The reconciliation metrics of every controller, as defined by
41    /// `k8s_controller`: counts and durations of reconciliation passes, and
42    /// of the steps within them.
43    pub reconcile: Arc<PrometheusMetrics>,
44}
45
46/// The series describing one `Materialize` resource.
47#[derive(Debug)]
48struct EnvironmentSeries {
49    /// The label values of `info`, which `active_generation` extends with the
50    /// generation.
51    labels: Vec<String>,
52    /// Held so that dropping it removes the series; its value is always 1.
53    #[allow(dead_code)]
54    info: EnvironmentGauge,
55    active_generation: Option<(u64, EnvironmentGauge)>,
56}
57
58impl Metrics {
59    pub fn register_into(registry: &MetricsRegistry) -> Self {
60        Self {
61            is_leader: registry.register(
62                metric! {
63                    name: "orchestratord_is_leader",
64                    help: "Whether this operator replica holds the controller leadership lease, and is therefore the replica reconciling. Summed across the replicas this should be 1. A sustained 0 means no replica can take the lease, for instance because the service account lacks permission on leases, and the operator is reconciling nothing.",
65                }),
66            environmentd_needs_update: registry.register(
67                metric! {
68                    name: "environmentd_needs_update",
69                    help: "Count of organizations in this cluster which are running outdated pod templates. Only the operator replica holding the leadership lease reconciles, so the others report zero.",
70                }),
71            environment_info: registry.register(metric!(
72                name: "mz_environment_info",
73                help: "Maps Materialize environment IDs to the environment's name and the namespace of its Materialize resource. Constant 1. Only the operator replica holding the leadership lease reports it.",
74                var_labels: ["environment_id", "environment_name", "environment_namespace"],
75                visibility: MetricVisibility::Public,
76                tags: [MetricTag::Environment],
77            )),
78            environment_active_generation: registry.register(metric!(
79                name: "mz_environment_active_generation",
80                help: "The deployment generation each Materialize environment serves: the one the operator last promoted, from the resource's status.activeGeneration. During a rollout it is the older generation until the new one is promoted. The generation label carries the same number, so it joins to the generation in a pod's name. Only the operator replica holding the leadership lease reports it.",
81                var_labels: ["environment_id", "environment_name", "environment_namespace", "generation"],
82                visibility: MetricVisibility::Public,
83                tags: [MetricTag::Environment],
84            )),
85            environments: Mutex::new(None),
86            reconcile: {
87                let reconcile = PrometheusMetrics::new("orchestratord")
88                    .expect("valid reconciliation metric definitions");
89                registry.register_collector(reconcile.clone());
90                Arc::new(reconcile)
91            },
92        }
93    }
94
95    /// Records that this replica has taken the leadership lease.
96    pub fn leadership_acquired(&self) {
97        self.is_leader.set(1);
98        *self.environments.lock().expect("lock poisoned") = Some(BTreeMap::new());
99    }
100
101    /// Records that this replica no longer holds the leadership lease, and
102    /// resets the metrics that only mean anything while it is reconciling.
103    ///
104    /// Those are derived from what reconciliation observed, and the process
105    /// outlives its own leadership: it keeps serving the conversion webhook
106    /// after losing the lease. Without this, a former leader would go on
107    /// publishing its last observation forever, so summing across the
108    /// replicas would count the same organizations once per past leader, and
109    /// each environment would have a series per past leader.
110    ///
111    /// Reconciliations still running when the lease is lost can observe an
112    /// environment after this, since aborting their tasks only takes effect at
113    /// their next await point. Those observations publish nothing until this
114    /// replica acquires the lease again.
115    pub fn leadership_lost(&self) {
116        self.is_leader.set(0);
117        self.environmentd_needs_update.set(0);
118        *self.environments.lock().expect("lock poisoned") = None;
119    }
120
121    /// Publishes the series describing the environment of the `Materialize`
122    /// resource `name` in `namespace`, replacing those published for it
123    /// before. Does nothing while this replica doesn't hold the leadership
124    /// lease.
125    ///
126    /// `mz_environment_info` needs the environment's ID, which the operator
127    /// assigns on its first reconciliation of a resource that has none, so
128    /// nothing is published while `environment_id` is nil.
129    /// `mz_environment_active_generation` is published only while the
130    /// resource has a status, which `active_generation` comes from.
131    pub fn observe_environment(
132        &self,
133        namespace: &str,
134        name: &str,
135        environment_id: Uuid,
136        active_generation: Option<u64>,
137    ) {
138        let key = (namespace.to_owned(), name.to_owned());
139        let mut environments = self.environments.lock().expect("lock poisoned");
140        let Some(environments) = environments.as_mut() else {
141            return;
142        };
143        if environment_id.is_nil() {
144            environments.remove(&key);
145            return;
146        }
147
148        let labels = vec![
149            environment_id.to_string(),
150            name.to_owned(),
151            namespace.to_owned(),
152        ];
153        let new_series = || {
154            let info = self
155                .environment_info
156                .get_delete_on_drop_metric(labels.clone());
157            info.set(1);
158            EnvironmentSeries {
159                labels: labels.clone(),
160                info,
161                active_generation: None,
162            }
163        };
164        let series = environments.entry(key).or_insert_with(new_series);
165        // A new handle on the labels a series already has would share it, and
166        // dropping the old handle would then remove it, so a series is only
167        // replaced when its labels change.
168        if series.labels != labels {
169            *series = new_series();
170        }
171
172        match active_generation {
173            None => series.active_generation = None,
174            Some(generation)
175                if series
176                    .active_generation
177                    .as_ref()
178                    .is_some_and(|(current, _)| *current == generation) => {}
179            Some(generation) => {
180                let mut labels = labels;
181                labels.push(generation.to_string());
182                let gauge = self
183                    .environment_active_generation
184                    .get_delete_on_drop_metric(labels);
185                gauge.set(generation);
186                series.active_generation = Some((generation, gauge));
187            }
188        }
189    }
190
191    /// Removes the series describing the environment of the `Materialize`
192    /// resource `name` in `namespace`.
193    pub fn forget_environment(&self, namespace: &str, name: &str) {
194        if let Some(environments) = self.environments.lock().expect("lock poisoned").as_mut() {
195            environments.remove(&(namespace.to_owned(), name.to_owned()));
196        }
197    }
198}
199
200pub fn router(registry: MetricsRegistry) -> Router {
201    add_tracing_layer(
202        Router::new()
203            .route("/metrics", get(metrics))
204            .layer(Extension(registry)),
205    )
206}
207
208#[allow(clippy::unused_async)]
209async fn metrics(Extension(registry): Extension<MetricsRegistry>) -> (StatusCode, Vec<u8>) {
210    let mut buf = vec![];
211    let encoder = TextEncoder::new();
212    let metric_families = registry.gather();
213    encoder.encode(&metric_families, &mut buf).unwrap();
214    (StatusCode::OK, buf)
215}
216
217///   Adds a tracing layer that reports an `INFO` level span per
218///   request and reports a `WARN` event when a handler returns a
219///   server error to the given Axum Router
220///
221///   This accepts a router instead of returning a layer itself
222///   to avoid dealing with defining generics over a bunch of closures
223///   (see <https://users.rust-lang.org/t/how-to-encapsulate-a-builder-that-depends-on-a-closure/71139/6>)
224///
225///   And this also can't be returned as a Router::new()::layer(TraceLayer)...
226///   because the TraceLayer needs to be added to a Router after
227///   all routes are defined, as it won't trace any routes defined
228///   on the router after it's attached.
229fn add_tracing_layer<S>(router: Router<S>) -> Router<S>
230where
231    S: Clone + Send + Sync + 'static,
232{
233    router.layer(
234        TraceLayer::new_for_http()
235            .make_span_with(|request: &Request<Body>| {
236                // This ugly macro is needed, unfortunately (and
237                // copied from tower-http), because
238                // `tracing::span!` required the level argument to
239                // be static. Meaning we can't just pass
240                // `self.level`.
241                macro_rules! make_span {
242                        ($level:expr) => {
243                            tracing::span!(
244                                $level,
245                                "HTTP request",
246                                "request.uri" = %request.uri(),
247                                "request.version" = ?request.version(),
248                                "request.method" = %request.method(),
249                                "request.headers" = tracing::field::Empty,
250                                "response.status" = tracing::field::Empty,
251                                "response.status_code" = tracing::field::Empty,
252                                "response.headers" = tracing::field::Empty,
253                            )
254                        }
255                    }
256                let span = if ["/api/health", "/metrics"].contains(&request.uri().path())
257                    || request.method() == Method::OPTIONS
258                {
259                    make_span!(Level::DEBUG)
260                } else {
261                    make_span!(Level::INFO)
262                };
263
264                if let Ok(s) = serde_json::to_string(&display_headers(request.headers().clone())) {
265                    span.record("request.headers", s);
266                }
267
268                span
269            })
270            .on_response(|response: &Response<Body>, _latency, span: &Span| {
271                span.record(
272                    "response.status",
273                    &tracing::field::display(response.status()),
274                );
275                span.record("response.status_code", response.status().as_u16());
276                if let Ok(s) = serde_json::to_string(&display_headers(response.headers().clone())) {
277                    span.record("response.headers", s);
278                }
279
280                // Emit an event at the same level as the span. For the same reason as noted in the comment
281                // above we can't use `tracing::event!(dynamic_level, ...)` since the level argument
282                // needs to be static
283                if span
284                    .metadata()
285                    .and_then(|m| Some(m.level()))
286                    .unwrap_or(&Level::DEBUG)
287                    == &Level::DEBUG
288                {
289                    tracing::debug!("HTTP response generated");
290                } else {
291                    tracing::info!("HTTP response generated");
292                }
293            })
294            .on_failure(
295                |error: ServerErrorsFailureClass, _latency: Duration, _span: &Span| {
296                    tracing::warn!(error = ?error, "HTTP request handling error");
297                },
298            ),
299    )
300}
301
302fn display_headers(mut headers: HeaderMap) -> BTreeMap<String, String> {
303    // Don't log Authorization headers
304    _ = headers.remove(http::header::AUTHORIZATION);
305
306    headers
307        .into_iter()
308        .filter_map(|(k, v)| {
309            k.map(|k| {
310                (
311                    k.to_string(),
312                    String::from_utf8_lossy(v.as_bytes()).to_string(),
313                )
314            })
315        })
316        .collect()
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322
323    const NAMESPACE: &str = "materialize-environment";
324    const NAME: &str = "production";
325    const ENVIRONMENT_ID: &str = "4b1a2f6e-0c3d-4e5f-8a9b-0c1d2e3f4a5b";
326    const OTHER_ENVIRONMENT_ID: &str = "9f8e7d6c-5b4a-4321-9876-543210fedcba";
327
328    /// The environment series in `registry`, one line each, in the text
329    /// exposition format.
330    fn environment_series(registry: &MetricsRegistry) -> Vec<String> {
331        let mut series: Vec<String> = registry
332            .gather()
333            .iter()
334            .filter(|family| family.name().starts_with("mz_environment_"))
335            .flat_map(|family| {
336                family.get_metric().iter().map(|metric| {
337                    let labels: Vec<String> = metric
338                        .get_label()
339                        .iter()
340                        .map(|label| format!("{}=\"{}\"", label.name(), label.value()))
341                        .collect();
342                    format!(
343                        "{}{{{}}} {}",
344                        family.name(),
345                        labels.join(","),
346                        metric.get_gauge().value()
347                    )
348                })
349            })
350            .collect();
351        series.sort();
352        series
353    }
354
355    fn info(environment_id: &str, namespace: &str) -> String {
356        format!(
357            "mz_environment_info{{environment_id=\"{environment_id}\",\
358             environment_name=\"{NAME}\",environment_namespace=\"{namespace}\"}} 1"
359        )
360    }
361
362    fn active_generation(environment_id: &str, namespace: &str, generation: u64) -> String {
363        format!(
364            "mz_environment_active_generation{{environment_id=\"{environment_id}\",\
365             environment_name=\"{NAME}\",environment_namespace=\"{namespace}\",\
366             generation=\"{generation}\"}} {generation}"
367        )
368    }
369
370    #[mz_ore::test]
371    fn environment_series_follow_the_resource() {
372        let registry = MetricsRegistry::new();
373        let metrics = Metrics::register_into(&registry);
374        metrics.leadership_acquired();
375        let id = Uuid::parse_str(ENVIRONMENT_ID).unwrap();
376
377        metrics.observe_environment(NAMESPACE, NAME, Uuid::nil(), None);
378        assert_eq!(environment_series(&registry), Vec::<String>::new());
379
380        metrics.observe_environment(NAMESPACE, NAME, id, None);
381        assert_eq!(
382            environment_series(&registry),
383            vec![info(ENVIRONMENT_ID, NAMESPACE)]
384        );
385
386        metrics.observe_environment(NAMESPACE, NAME, id, Some(3));
387        let at_generation_3 = vec![
388            active_generation(ENVIRONMENT_ID, NAMESPACE, 3),
389            info(ENVIRONMENT_ID, NAMESPACE),
390        ];
391        assert_eq!(environment_series(&registry), at_generation_3);
392
393        // Observing the same resource again keeps its series.
394        metrics.observe_environment(NAMESPACE, NAME, id, Some(3));
395        assert_eq!(environment_series(&registry), at_generation_3);
396
397        metrics.observe_environment(NAMESPACE, NAME, id, Some(4));
398        assert_eq!(
399            environment_series(&registry),
400            vec![
401                active_generation(ENVIRONMENT_ID, NAMESPACE, 4),
402                info(ENVIRONMENT_ID, NAMESPACE),
403            ]
404        );
405
406        // A resource of the same name in another namespace is another
407        // environment.
408        let other = Uuid::parse_str(OTHER_ENVIRONMENT_ID).unwrap();
409        metrics.observe_environment("other", NAME, other, Some(1));
410        metrics.forget_environment(NAMESPACE, NAME);
411        assert_eq!(
412            environment_series(&registry),
413            vec![
414                active_generation(OTHER_ENVIRONMENT_ID, "other", 1),
415                info(OTHER_ENVIRONMENT_ID, "other"),
416            ]
417        );
418    }
419
420    #[mz_ore::test]
421    fn environment_id_change_replaces_series() {
422        let registry = MetricsRegistry::new();
423        let metrics = Metrics::register_into(&registry);
424        metrics.leadership_acquired();
425
426        let id = Uuid::parse_str(ENVIRONMENT_ID).unwrap();
427        metrics.observe_environment(NAMESPACE, NAME, id, Some(2));
428        let other = Uuid::parse_str(OTHER_ENVIRONMENT_ID).unwrap();
429        metrics.observe_environment(NAMESPACE, NAME, other, Some(2));
430        assert_eq!(
431            environment_series(&registry),
432            vec![
433                active_generation(OTHER_ENVIRONMENT_ID, NAMESPACE, 2),
434                info(OTHER_ENVIRONMENT_ID, NAMESPACE),
435            ]
436        );
437    }
438
439    #[mz_ore::test]
440    fn environment_series_only_while_leading() {
441        let registry = MetricsRegistry::new();
442        let metrics = Metrics::register_into(&registry);
443        let id = Uuid::parse_str(ENVIRONMENT_ID).unwrap();
444
445        metrics.observe_environment(NAMESPACE, NAME, id, Some(1));
446        assert_eq!(environment_series(&registry), Vec::<String>::new());
447
448        metrics.leadership_acquired();
449        metrics.observe_environment(NAMESPACE, NAME, id, Some(1));
450        let at_generation_1 = vec![
451            active_generation(ENVIRONMENT_ID, NAMESPACE, 1),
452            info(ENVIRONMENT_ID, NAMESPACE),
453        ];
454        assert_eq!(environment_series(&registry), at_generation_1);
455
456        metrics.leadership_lost();
457        assert_eq!(environment_series(&registry), Vec::<String>::new());
458
459        // A reconciliation that was still running when the lease was lost.
460        metrics.observe_environment(NAMESPACE, NAME, id, Some(2));
461        metrics.forget_environment(NAMESPACE, NAME);
462        assert_eq!(environment_series(&registry), Vec::<String>::new());
463
464        metrics.leadership_acquired();
465        metrics.observe_environment(NAMESPACE, NAME, id, Some(1));
466        assert_eq!(environment_series(&registry), at_generation_1);
467    }
468}