Skip to main content

mz_environmentd/http/
prometheus.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 Apach
9
10use mz_catalog::memory::objects::{Cluster, ClusterReplica};
11use mz_ore::sql;
12use mz_ore::sql::Sql;
13
14use super::sql::SqlRequest;
15
16#[derive(Debug)]
17pub(crate) struct PrometheusSqlQuery<'a> {
18    pub(crate) metric_name: &'a str,
19    pub(crate) help: &'a str,
20    pub(crate) query: &'static str,
21    pub(crate) value_column_name: &'a str,
22    pub(crate) per_replica: bool,
23}
24
25impl<'a> PrometheusSqlQuery<'a> {
26    pub(crate) fn to_sql_request(
27        &self,
28        cluster: Option<(&Cluster, &ClusterReplica)>,
29    ) -> SqlRequest {
30        let query = Sql::new(self.query);
31        let query = if let Some((cluster, replica)) = cluster {
32            sql!(
33                "SET auto_route_catalog_queries = false; SET CLUSTER = {}; SET CLUSTER_REPLICA = {}; {}",
34                Sql::literal(&cluster.name),
35                Sql::literal(&replica.name),
36                query
37            )
38        } else {
39            sql!(
40                "SET auto_route_catalog_queries = true; RESET CLUSTER; RESET CLUSTER_REPLICA; {}",
41                query
42            )
43        };
44        SqlRequest::Simple { query }
45    }
46}
47
48pub(crate) static FRONTIER_METRIC_QUERIES: &[PrometheusSqlQuery] = &[
49    PrometheusSqlQuery {
50        metric_name: "mz_write_frontier",
51        help: "The global write frontiers of compute and storage collections.",
52        query: "SELECT
53                    object_id AS collection_id,
54                    coalesce(write_frontier::text::uint8, 18446744073709551615::uint8) AS write_frontier
55                FROM mz_internal.mz_frontiers
56                WHERE object_id NOT LIKE 't%';",
57        value_column_name: "write_frontier",
58        per_replica: false,
59    },
60    PrometheusSqlQuery {
61        metric_name: "mz_read_frontier",
62        help: "The global read frontiers of compute and storage collections.",
63        query: "SELECT
64                    object_id AS collection_id,
65                    coalesce(read_frontier::text::uint8, 18446744073709551615::uint8) AS read_frontier
66                FROM mz_internal.mz_frontiers
67                WHERE object_id NOT LIKE 't%';",
68        value_column_name: "read_frontier",
69        per_replica: false,
70    },
71    PrometheusSqlQuery {
72        metric_name: "mz_replica_write_frontiers",
73        help: "The per-replica write frontiers of compute and storage collections.",
74        query: "SELECT
75                    object_id AS collection_id,
76                    coalesce(write_frontier::text::uint8, 18446744073709551615::uint8) AS write_frontier,
77                    cluster_id AS instance_id,
78                    replica_id AS replica_id
79                FROM mz_catalog.mz_cluster_replica_frontiers
80                JOIN mz_cluster_replicas ON (id = replica_id)
81                WHERE object_id NOT LIKE 't%';",
82        value_column_name: "write_frontier",
83        per_replica: false,
84    },
85];
86
87pub(crate) static USAGE_METRIC_QUERIES: &[PrometheusSqlQuery] = &[
88    PrometheusSqlQuery {
89        metric_name: "mz_compute_cluster_status",
90        help: "Reports the name, ID, size, and availability zone of each cluster replica. Value is always 1.",
91        query: "SELECT
92                1 AS status,
93                cr.cluster_id AS compute_cluster_id,
94                cr.id AS compute_replica_id,
95                c.name AS compute_cluster_name,
96                cr.name AS compute_replica_name,
97                COALESCE(cr.size, '') AS size,
98                COALESCE(cr.availability_zone, '') AS availability_zone,
99                mz_version() AS mz_version
100          FROM
101            mz_cluster_replicas AS cr
102            JOIN mz_clusters AS c
103              ON cr.cluster_id = c.id",
104        value_column_name: "status",
105        per_replica: false,
106    },
107    PrometheusSqlQuery {
108        metric_name: "mz_workload_clusters",
109        help: "Reports the workload_class of each user cluster. Value is always 1.",
110        query: "select
111                    c.id as cluster_id,
112                    c.name as cluster_name,
113                    coalesce(wc.workload_class,'false') as workload_class,
114                    1 as value
115                from mz_clusters c
116                join mz_internal.mz_cluster_workload_classes wc
117                    on c.id = wc.id",
118        value_column_name: "value",
119        per_replica: false,
120    },
121    PrometheusSqlQuery {
122        metric_name: "mz_indexes_count",
123        help: "Number of active indexes in the instance, by the type of relation on which the index is built.",
124        query: "select
125                o.type as relation_type
126                , count(i.id) as indexes
127            from mz_catalog.mz_indexes i
128            join mz_catalog.mz_objects o
129                on i.on_id = o.id
130            where i.id like 'u%'
131            group by relation_type",
132        value_column_name: "indexes",
133        per_replica: false,
134    },
135    PrometheusSqlQuery {
136        metric_name: "mz_sources_count",
137        help: "Number of active sources in the instance, by type, envelope type, and size of source.",
138        query: "SELECT
139                type,
140                COALESCE(envelope_type, '<none>') AS envelope_type,
141                COALESCE(mz_cluster_replicas.size, '') AS size,
142                count(mz_sources.id) AS sources
143            FROM
144                mz_sources, mz_cluster_replicas
145            WHERE mz_sources.id LIKE 'u%'
146            AND mz_sources.type != 'subsource'
147            AND mz_sources.cluster_id = mz_cluster_replicas.cluster_id
148            GROUP BY
149            type, envelope_type, mz_cluster_replicas.size",
150        value_column_name: "sources",
151        per_replica: false,
152    },
153    PrometheusSqlQuery {
154        metric_name: "mz_sinks_count",
155        help: "Number of active sinks in the instance, by type, envelope type, and size.",
156        query: "SELECT
157                type,
158                COALESCE(envelope_type, '<none>') AS envelope_type,
159                COALESCE(mz_cluster_replicas.size, '') AS size,
160                count(mz_sinks.id) AS sinks
161            FROM
162                mz_sinks, mz_cluster_replicas
163            WHERE mz_sinks.id LIKE 'u%'
164            AND mz_sinks.cluster_id = mz_cluster_replicas.cluster_id
165            GROUP BY type, envelope_type, mz_cluster_replicas.size",
166        value_column_name: "sinks",
167        per_replica: false,
168    },
169    PrometheusSqlQuery {
170        metric_name: "mz_connections_count",
171        help: "Number of active connections in the instance, by type.",
172        query: "select
173                type
174                , count(id) as connections
175            from mz_connections
176            where id like 'u%'
177            group by type",
178        value_column_name: "connections",
179        per_replica: false,
180    },
181];
182
183pub(crate) static COMPUTE_METRIC_QUERIES: &[PrometheusSqlQuery] = &[
184    PrometheusSqlQuery {
185        metric_name: "mz_arrangement_count",
186        help: "The number of arrangements in a dataflow.",
187        query: "WITH
188            arrangements AS (
189                SELECT DISTINCT operator_id AS id
190                FROM mz_internal.mz_arrangement_records_raw
191            ),
192            collections AS (
193                SELECT
194                    id,
195                    CASE
196                        WHEN starts_with(export_id, 't') THEN 'transient'
197                        ELSE export_id
198                    END AS export_id
199                FROM
200                    mz_internal.mz_dataflow_addresses,
201                    mz_internal.mz_compute_exports
202                WHERE address[1] = dataflow_id
203            )
204        SELECT
205            COALESCE(export_id, 'none') AS collection_id,
206            count(*) as count
207        FROM arrangements
208        LEFT JOIN collections USING (id)
209        GROUP BY export_id",
210        value_column_name: "count",
211        per_replica: true,
212    },
213    PrometheusSqlQuery {
214        metric_name: "mz_arrangement_record_count",
215        help: "The number of records in all arrangements in a dataflow.",
216        query: "WITH
217            collections AS (
218                SELECT
219                    id,
220                    CASE
221                        WHEN starts_with(export_id, 't') THEN 'transient'
222                        ELSE export_id
223                    END AS export_id
224                FROM
225                    mz_internal.mz_dataflow_addresses,
226                    mz_internal.mz_compute_exports
227                WHERE address[1] = dataflow_id
228            )
229        SELECT
230            worker_id,
231            COALESCE(export_id, 'none') AS collection_id,
232            count(*) as count
233        FROM mz_internal.mz_arrangement_records_raw
234        LEFT JOIN collections ON (operator_id = id)
235        GROUP BY worker_id, export_id",
236        value_column_name: "count",
237        per_replica: true,
238    },
239    PrometheusSqlQuery {
240        metric_name: "mz_arrangement_batch_count",
241        help: "The number of batches in all arrangements in a dataflow.",
242        query: "WITH
243            collections AS (
244                SELECT
245                    id,
246                    CASE
247                        WHEN starts_with(export_id, 't') THEN 'transient'
248                        ELSE export_id
249                    END AS export_id
250                FROM
251                    mz_internal.mz_dataflow_addresses,
252                    mz_internal.mz_compute_exports
253                WHERE address[1] = dataflow_id
254            )
255        SELECT
256            worker_id,
257            COALESCE(export_id, 'none') AS collection_id,
258            count(*) as count
259        FROM mz_internal.mz_arrangement_batches_raw
260        LEFT JOIN collections ON (operator_id = id)
261        GROUP BY worker_id, export_id",
262        value_column_name: "count",
263        per_replica: true,
264    },
265    PrometheusSqlQuery {
266        metric_name: "mz_arrangement_size_bytes",
267        help: "The size of all arrangements in a dataflow.",
268        query: "WITH
269            collections AS (
270                SELECT
271                    id,
272                    CASE
273                        WHEN starts_with(export_id, 't') THEN 'transient'
274                        ELSE export_id
275                    END AS export_id
276                FROM
277                    mz_internal.mz_dataflow_addresses,
278                    mz_internal.mz_compute_exports
279                WHERE address[1] = dataflow_id
280            )
281        SELECT
282            worker_id,
283            COALESCE(export_id, 'none') AS collection_id,
284            count(*) as count
285        FROM mz_internal.mz_arrangement_heap_size_raw
286        LEFT JOIN collections ON (operator_id = id)
287        GROUP BY worker_id, export_id",
288        value_column_name: "count",
289        per_replica: true,
290    },
291    PrometheusSqlQuery {
292        metric_name: "mz_arrangement_capacity_bytes",
293        help: "The capacity of all arrangements in all dataflows.",
294        query: "SELECT
295            worker_id,
296            count(*) as count
297        FROM mz_internal.mz_arrangement_heap_capacity_raw
298        GROUP BY worker_id",
299        value_column_name: "count",
300        per_replica: true,
301    },
302    PrometheusSqlQuery {
303        metric_name: "mz_arrangement_allocation_count",
304        help: "The number of allocations in all arrangements in all dataflows.",
305        query: "SELECT
306            worker_id,
307            count(*) as count
308        FROM mz_internal.mz_arrangement_heap_allocations_raw
309        GROUP BY worker_id",
310        value_column_name: "count",
311        per_replica: true,
312    },
313    PrometheusSqlQuery {
314        metric_name: "mz_compute_replica_park_duration_seconds_total",
315        help: "The total time workers were parked since restart.",
316        query: "SELECT
317            worker_id,
318            sum(slept_for_ns * count)::float8 / 1000000000 AS duration_s
319        FROM mz_internal.mz_scheduling_parks_histogram_per_worker
320        GROUP BY worker_id",
321        value_column_name: "duration_s",
322        per_replica: true,
323    },
324    PrometheusSqlQuery {
325        metric_name: "mz_compute_replica_peek_count",
326        help: "The number of pending peeks.",
327        query: "SELECT worker_id, count(*) as count
328        FROM mz_internal.mz_active_peeks_per_worker
329        GROUP BY worker_id",
330        value_column_name: "count",
331        per_replica: true,
332    },
333    PrometheusSqlQuery {
334        metric_name: "mz_dataflow_elapsed_seconds_total",
335        help: "The total time spent computing a dataflow.",
336        query: "SELECT
337            worker_id,
338            CASE
339                WHEN starts_with(export_id, 't') THEN 'transient'
340                ELSE export_id
341            END AS collection_id,
342            sum(elapsed_ns)::float8 / 1000000000 AS elapsed_s
343        FROM
344            mz_internal.mz_scheduling_elapsed_per_worker AS s,
345            mz_internal.mz_dataflow_operators AS o,
346            mz_internal.mz_dataflow_addresses AS a,
347            mz_internal.mz_compute_exports AS e
348        WHERE
349            o.id = s.id AND
350            o.id = a.id AND
351            list_length(a.address) = 1 AND
352            e.dataflow_id = a.address[1]
353        GROUP BY worker_id, collection_id",
354        value_column_name: "elapsed_s",
355        per_replica: true,
356    },
357    PrometheusSqlQuery {
358        metric_name: "mz_dataflow_error_count",
359        help: "The number of errors in a dataflow",
360        query: "SELECT
361            CASE
362                WHEN starts_with(export_id, 't') THEN 'transient'
363                ELSE export_id
364            END AS collection_id,
365            count::uint8 as count
366        FROM mz_internal.mz_compute_error_counts",
367        value_column_name: "count",
368        per_replica: true,
369    },
370];
371
372pub(crate) static STORAGE_METRIC_QUERIES: &[PrometheusSqlQuery] = &[
373    PrometheusSqlQuery {
374        metric_name: "mz_storage_objects",
375        help: "Nicely labeled information about existing sources and sinks.",
376        value_column_name: "value",
377        per_replica: false,
378        query: "
379        WITH
380            -- All user, non- progress or subsource sources.
381            top_level_sources AS (
382                SELECT id, connection_id, type, envelope_type, cluster_id
383                FROM mz_sources
384                WHERE id LIKE 'u%' AND type NOT IN ('progress', 'subsource')
385            ),
386            -- Sources enriched with the type of the core connection.
387            source_and_conns AS (
388                SELECT top_level_sources.*, mc.type AS connection_type
389                FROM top_level_sources
390                LEFT OUTER JOIN mz_connections mc ON mc.id = top_level_sources.connection_id
391            ),
392
393            -- All user sinks.
394            top_level_sinks AS (
395                SELECT id, connection_id, type, envelope_type, cluster_id
396                FROM mz_sinks
397                WHERE id LIKE 'u%'
398            ),
399            -- Sinks enriched with the type of the core connection.
400            sink_and_conns AS (
401                SELECT top_level_sinks.*, mc.type AS connection_type
402                FROM top_level_sinks
403                LEFT OUTER JOIN mz_connections mc ON mc.id = top_level_sinks.connection_id
404            ),
405
406            -- All objects we care about
407            object_and_conns AS (
408                SELECT * FROM source_and_conns
409                UNION ALL
410                SELECT * FROM sink_and_conns
411            ),
412
413            -- The networking the object connection uses, if any.
414            networking AS (
415                SELECT object_and_conns.id, mc.id AS networking_id, mc.type AS networking_type
416                FROM object_and_conns
417                JOIN mz_internal.mz_object_dependencies mod ON object_and_conns.connection_id = mod.object_id
418                JOIN mz_connections mc ON mc.id = mod.referenced_object_id
419                -- Not required but made explicit
420                WHERE object_and_conns.connection_id IS NOT NULL
421            ),
422            -- The connection the format of the object uses, if any. This uses `mz_object_dependencies`
423            -- and a filter to find non-core objects the object depends on.
424            format_conns AS (
425                SELECT object_and_conns.id, mc.id AS format_connection_id, mc.type AS format_connection
426                FROM mz_internal.mz_object_dependencies mod
427                JOIN object_and_conns ON mod.object_id = object_and_conns.id
428                JOIN mz_connections mc ON mc.id = mod.referenced_object_id
429                WHERE mc.id NOT IN (SELECT connection_id FROM top_level_sources UNION ALL SELECT connection_id FROM top_level_sinks)
430                -- Not required but made explicit
431                AND object_and_conns.connection_id IS NOT NULL
432            ),
433            -- The networking used by `format_conns`, if any.
434            format_conn_deps AS (
435                SELECT format_conns.id, mc.id AS format_connection_networking_id, mc.type AS format_connection_networking
436                FROM format_conns
437                JOIN mz_internal.mz_object_dependencies mod ON mod.object_id = format_conns.format_connection_id
438                JOIN mz_connections mc
439                ON mc.id = mod.referenced_object_id
440            ),
441
442            -- When aggregating values that are known to be the same, we just use `MAX` for simplicity.
443
444            -- source_and_conns LEFT JOINed with the networking and format connection information.
445            -- Missing networking/format connections are coalesced to `none`, and aggregated with a comma.
446            -- This is because sources can have multiple type of networking (i.e. different kafka brokers with
447            -- different configuration), and multiple connections for formats (for key and value formats).
448            --
449            -- The actual format type is not yet included, as it depends on https://github.com/MaterializeInc/materialize/pull/23880
450            sources AS (
451                SELECT
452                -- Whether its a source or sink
453                'source' AS type,
454                1 AS value,
455                source_and_conns.id AS id,
456                -- What type of source/sink it is
457                MAX(type) AS object_type,
458                COALESCE(MAX(connection_type), 'none') AS connection_type,
459                COALESCE(MAX(envelope_type), 'none') AS envelope_type,
460                STRING_AGG(
461                    DISTINCT COALESCE(networking_type, 'none'),
462                    ','
463                    ORDER BY COALESCE(networking_type, 'none') ASC
464                ) AS networking_type,
465                STRING_AGG(
466                    DISTINCT COALESCE(format_connection, 'none'),
467                    ','
468                    ORDER BY COALESCE(format_connection, 'none') ASC
469                ) AS format_connection,
470                STRING_AGG(
471                    DISTINCT COALESCE(format_connection_networking, 'none'),
472                    ','
473                    ORDER BY COALESCE(format_connection_networking, 'none') ASC
474                ) AS format_connection_networking,
475                MAX(cluster_id) AS cluster_id
476                FROM source_and_conns
477                LEFT OUTER JOIN networking ON networking.id = source_and_conns.id
478                LEFT OUTER JOIN format_conns ON format_conns.id = source_and_conns.id
479                LEFT OUTER JOIN format_conn_deps ON format_conn_deps.id = source_and_conns.id
480                GROUP BY source_and_conns.id
481            ),
482
483            sinks AS (
484                SELECT
485                'sink' AS type,
486                1 AS value,
487                sink_and_conns.id AS id,
488                MAX(type) AS object_type,
489                COALESCE(MAX(connection_type), 'none') AS connection_type,
490                COALESCE(MAX(envelope_type), 'none') AS envelope_type,
491                STRING_AGG(
492                    DISTINCT COALESCE(networking_type, 'none'),
493                    ','
494                    ORDER BY COALESCE(networking_type, 'none') ASC
495                ) AS networking_type,
496                -- Sinks can only have 1 format connection but we aggregate
497                -- for consistency.
498                STRING_AGG(
499                    DISTINCT COALESCE(format_connection, 'none'),
500                    ','
501                    ORDER BY COALESCE(format_connection, 'none') ASC
502                ) AS format_connection,
503                STRING_AGG(
504                    DISTINCT COALESCE(format_connection_networking, 'none'),
505                    ','
506                    ORDER BY COALESCE(format_connection_networking, 'none') ASC
507                ) AS format_connection_networking,
508                MAX(cluster_id) AS cluster_id
509                FROM sink_and_conns
510                LEFT OUTER JOIN networking ON networking.id = sink_and_conns.id
511                LEFT OUTER JOIN format_conns ON format_conns.id = sink_and_conns.id
512                LEFT OUTER JOIN format_conn_deps ON format_conn_deps.id = sink_and_conns.id
513                GROUP BY sink_and_conns.id
514            ),
515
516            -- everything without replicas
517            together AS (
518                SELECT * FROM sources
519                UNION ALL
520                SELECT * from sinks
521            ),
522
523            with_cluster_replicas AS (
524                SELECT
525                -- `together.*` doesn't work because we need to aggregate the columns :(
526                MAX(together.id) AS id,
527                MAX(together.type) AS type,
528                MAX(together.object_type) AS object_type,
529                -- We just report 1 to the gauge. The `replica_id` labels aggregates the 0-many replicas associated
530                -- with this object.
531                MAX(together.value) AS value,
532                MAX(together.connection_type) AS connection_type,
533                MAX(together.envelope_type) AS envelope_type,
534                MAX(together.networking_type) AS networking_type,
535                MAX(together.format_connection) AS format_connection,
536                MAX(together.format_connection_networking) AS format_connection_networking,
537                MAX(together.cluster_id) AS cluster_id,
538                mcr.id AS replica_id,
539                -- Coalesce to 0 when there is no replica. This ensures `with_pod` below will generate
540                -- 1 row for the object. Also, -1 because `generate_series` is inclusive.
541                COALESCE((mcrs.processes - 1)::int, 0) AS processes
542                FROM together
543                LEFT OUTER JOIN mz_cluster_replicas mcr ON together.cluster_id = mcr.cluster_id
544                LEFT OUTER JOIN mz_catalog.mz_cluster_replica_sizes mcrs ON mcr.size = mcrs.size
545                GROUP BY together.id, mcr.id, mcrs.processes
546            ),
547
548            with_pod AS (
549                SELECT
550                id,
551                type,
552                object_type,
553                value,
554                connection_type,
555                envelope_type,
556                networking_type,
557                format_connection,
558                format_connection_networking,
559                cluster_id,
560                COALESCE(replica_id, 'none') AS replica_id,
561                -- When `replica_id` is NULL`, this coalesces to `none`.
562                COALESCE('cluster-' || cluster_id || '-replica-' || replica_id || '-' || generated, 'none') AS synthesized_pod
563                FROM with_cluster_replicas, generate_series(0, processes) generated
564            )
565
566        SELECT * FROM with_pod;
567        ",
568    },
569];