1use std::collections::HashSet;
10use std::hash::Hash;
11use std::sync::{Arc, Mutex, PoisonError};
12use std::time::Duration;
13
14use prometheus_client::encoding::EncodeLabelSet;
15use prometheus_client::metrics::counter::Counter;
16use prometheus_client::metrics::family::Family;
17use prometheus_client::metrics::gauge::Gauge;
18use prometheus_client::metrics::histogram::{Histogram, exponential_buckets};
19use prometheus_client::registry::Registry;
20use schedr_db::reads::StateCounts;
21use schedr_model::metric_doc::{MetricDoc, MetricKind};
22
23#[cfg(test)]
24mod tests;
25
26pub const GAUGE_REFRESH: Duration = Duration::from_secs(15);
28
29const TICK_DURATION: MetricDoc = MetricDoc {
30 name: "master_tick_duration_seconds",
31 kind: MetricKind::Histogram,
32 labels: &[],
33 help: "How long each tick of the master's loop took",
34};
35const START_RECORDED: MetricDoc = MetricDoc {
36 name: "master_start_recorded_seconds",
37 kind: MetricKind::Histogram,
38 labels: &[],
39 help: "From a task's start on its worker (in master time, as the worker estimates it) to \
40 the master recording it: the wait for the core's lock and the message's way (M5.1m)",
41};
42const CORE_LOCK_WAIT: MetricDoc = MetricDoc {
43 name: "master_core_lock_wait_seconds",
44 kind: MetricKind::Histogram,
45 labels: &["by"],
46 help: "How long the master's core lock was waited for, by who waited (turn: a worker's \
47 messages; round; register; upload: a parse result; stream: a stream ended or dropped; \
48 restore)",
49};
50const TURN_PART: MetricDoc = MetricDoc {
51 name: "master_turn_part_seconds",
52 kind: MetricKind::Histogram,
53 labels: &["part"],
54 help: "How long each part of a worker's turn held the core lock (started: its `Started`s \
55 stored; finished: its `Finished`s; rest: heartbeats, warnings and the other messages)",
56};
57const ROUND_PART: MetricDoc = MetricDoc {
58 name: "master_round_part_seconds",
59 kind: MetricKind::Histogram,
60 labels: &["part"],
61 help: "How long each part of a round took, the core lock held (commands: commands applied \
62 and their follow-ups; scheduler: the scheduler's pass; triggers: the trigger loop's pass, beside the rounds; prepare: runs prepared \
63 and retries queued; expire: assignments expired and replaced incarnations ended; assign: \
64 cleanups, chained runs and assignments; rest: parse jobs expired, workers lost)",
65};
66const TURN_MESSAGES: MetricDoc = MetricDoc {
67 name: "master_turn_messages",
68 kind: MetricKind::Histogram,
69 labels: &["part"],
70 help: "How many messages each part of a worker's turn handled",
71};
72const RUNS: MetricDoc = MetricDoc {
73 name: "runs",
74 kind: MetricKind::Gauge,
75 labels: &["state", "kind"],
76 help: "Runs by state and kind",
77};
78const RUNS_FINISHED: MetricDoc = MetricDoc {
79 name: "runs_finished",
80 kind: MetricKind::Counter,
81 labels: &["dag_id", "result"],
82 help: "Runs finished, by DAG and result",
83};
84const RUNS_LATE_FAILED: MetricDoc = MetricDoc {
85 name: "runs_late_failed",
86 kind: MetricKind::Counter,
87 labels: &["dag_id", "reason"],
88 help: "Runs that ended `success` and learnt of a failure afterwards (a yellow success, \
89 decision 309), by DAG and reason (`late_cleanup_failed`)",
90};
91const NOTIFICATIONS_SENT: MetricDoc = MetricDoc {
92 name: "notifications_sent",
93 kind: MetricKind::Counter,
94 labels: &["channel"],
95 help: "Notifications delivered, by channel",
96};
97const RETENTION_DELETED: MetricDoc = MetricDoc {
98 name: "retention_deleted",
99 kind: MetricKind::Counter,
100 labels: &["kind"],
101 help: "Rows the retention job deleted: runs, outputs (runs whose outputs went), events, \
102 commands, dags, versions",
103};
104const NOTIFICATIONS_FAILED: MetricDoc = MetricDoc {
105 name: "notifications_failed",
106 kind: MetricKind::Counter,
107 labels: &["channel"],
108 help: "Notifications given up on (`[notifications] give_up_after`), by channel",
109};
110const TASKS: MetricDoc = MetricDoc {
111 name: "tasks",
112 kind: MetricKind::Gauge,
113 labels: &["state"],
114 help: "Task instances of unfinished runs, by state",
115};
116const TASKS_WAITING: MetricDoc = MetricDoc {
117 name: "tasks_waiting",
118 kind: MetricKind::Gauge,
119 labels: &["reason"],
120 help: "Ready tasks not assigned at the last assignment pass, by reason (`next_round`: over \
121 the round's limit of assignments; `max_active_tasks`, `max_active`, \
122 `max_active_per_run`: a concurrency limit reached)",
123};
124const ASSIGNMENTS: MetricDoc = MetricDoc {
125 name: "assignments",
126 kind: MetricKind::Counter,
127 labels: &[],
128 help: "Attempts assigned to workers",
129};
130const REJECTIONS: MetricDoc = MetricDoc {
131 name: "rejections",
132 kind: MetricKind::Counter,
133 labels: &["reason"],
134 help: "Assignments workers rejected, by reason",
135};
136const ATTEMPTS_ENDED: MetricDoc = MetricDoc {
137 name: "attempts_ended",
138 kind: MetricKind::Counter,
139 labels: &["status"],
140 help: "Attempts ended, by status",
141};
142const PARSE_JOBS_STARTED: MetricDoc = MetricDoc {
143 name: "parse_jobs_started",
144 kind: MetricKind::Counter,
145 labels: &[],
146 help: "Parse jobs created",
147};
148const PARSE_JOBS_FINISHED: MetricDoc = MetricDoc {
149 name: "parse_jobs_finished",
150 kind: MetricKind::Counter,
151 labels: &[],
152 help: "Parse jobs finished",
153};
154const PARSE_DURATION: MetricDoc = MetricDoc {
155 name: "parse_duration_seconds",
156 kind: MetricKind::Histogram,
157 labels: &[],
158 help: "How long parse jobs took, from creation to the stored parse",
159};
160const COMMANDS: MetricDoc = MetricDoc {
161 name: "commands",
162 kind: MetricKind::Counter,
163 labels: &["kind", "decision"],
164 help: "Commands decided, by kind and decision",
165};
166const COMMAND_LATENCY: MetricDoc = MetricDoc {
167 name: "command_latency_seconds",
168 kind: MetricKind::Histogram,
169 labels: &[],
170 help: "How long commands waited for the master's decision",
171};
172const LEADING: MetricDoc = MetricDoc {
173 name: "master_leading",
174 kind: MetricKind::Gauge,
175 labels: &[],
176 help: "1 while this master holds the lease and schedules, 0 while it waits or is paused",
177};
178const REPLACED_HELD: MetricDoc = MetricDoc {
179 name: "master_replaced_attempts_held",
180 kind: MetricKind::Gauge,
181 labels: &[],
182 help: "Started attempts of a replaced worker incarnation the master holds for a lease before \
183 ending them lost (decision 443): its old process may still run them",
184};
185const WORKERS: MetricDoc = MetricDoc {
186 name: "workers",
187 kind: MetricKind::Gauge,
188 labels: &["state"],
189 help: "Workers in the registry, by state",
190};
191
192const DAGS: MetricDoc = MetricDoc {
193 name: "master_dags",
194 kind: MetricKind::Gauge,
195 labels: &["state"],
196 help: "DAGs that can run, as of the last scheduler round: busy (it visited them) or quiet \
197 (nothing due); held: those whose file fails to import (no runs until it does)",
198};
199const DAG_WAKES: MetricDoc = MetricDoc {
200 name: "master_dag_wakes",
201 kind: MetricKind::Counter,
202 labels: &["reason"],
203 help: "DAGs a scheduler round visited after its term's first, by reason: timer, unknown (no \
204 next fire time stored), command, run_queued, run_ended, new_version",
205};
206
207const TRIGGERS: MetricDoc = MetricDoc {
208 name: "master_triggers",
209 kind: MetricKind::Gauge,
210 labels: &["state"],
211 help: "Triggers of DAGs that want them running, by state: running, waiting (for a free watcher \
212 slot or to start again), stopped (back-pressure, a generator that returned) or failing \
213 (`[triggers] failing_after` errors in a row)",
214};
215const TRIGGER_EVENTS: MetricDoc = MetricDoc {
216 name: "master_trigger_events",
217 kind: MetricKind::Counter,
218 labels: &["result"],
219 help: "Events received from triggers, by result: new (it started a run) or repeat (its key was \
220 seen before, and it started none)",
221};
222const TRIGGER_BACK_PRESSURE_STOPS: MetricDoc = MetricDoc {
223 name: "master_trigger_back_pressure_stops",
224 kind: MetricKind::Counter,
225 labels: &[],
226 help: "Triggers stopped for having `[triggers] max_queued_events` queued runs",
227};
228const TRIGGER_IDLE_RESTARTS: MetricDoc = MetricDoc {
229 name: "master_trigger_idle_restarts",
230 kind: MetricKind::Counter,
231 labels: &[],
232 help: "Triggers started again for finding nothing for their `restart_if_idle`",
233};
234
235#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
237pub struct TriggerCounts {
238 pub running: usize,
240 pub waiting: usize,
242 pub stopped: usize,
244 pub failing: usize,
246}
247
248#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
250pub struct EventResultLabels {
251 pub result: String,
253}
254
255pub const METRICS: &[MetricDoc] = &[
257 TRIGGERS,
258 TRIGGER_EVENTS,
259 TRIGGER_BACK_PRESSURE_STOPS,
260 TRIGGER_IDLE_RESTARTS,
261 TICK_DURATION,
262 START_RECORDED,
263 CORE_LOCK_WAIT,
264 TURN_PART,
265 TURN_MESSAGES,
266 ROUND_PART,
267 RUNS,
268 RUNS_FINISHED,
269 RUNS_LATE_FAILED,
270 NOTIFICATIONS_SENT,
271 NOTIFICATIONS_FAILED,
272 RETENTION_DELETED,
273 TASKS,
274 TASKS_WAITING,
275 ASSIGNMENTS,
276 REJECTIONS,
277 ATTEMPTS_ENDED,
278 PARSE_JOBS_STARTED,
279 PARSE_JOBS_FINISHED,
280 PARSE_DURATION,
281 COMMANDS,
282 COMMAND_LATENCY,
283 WORKERS,
284 LEADING,
285 REPLACED_HELD,
286 DAGS,
287 DAG_WAKES,
288];
289
290#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
292pub struct StateLabels {
293 pub state: String,
295}
296
297#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
299pub struct RunLabels {
300 pub state: String,
302 pub kind: String,
304}
305
306#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
308pub struct ResultLabels {
309 pub dag_id: String,
311 pub result: String,
313}
314
315#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
317pub struct LateLabels {
318 pub dag_id: String,
320 pub reason: String,
322}
323
324#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
326pub struct KindLabels {
327 pub kind: String,
329}
330
331#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
333pub struct ChannelLabels {
334 pub channel: String,
336}
337
338#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
340pub struct ReasonLabels {
341 pub reason: String,
343}
344
345#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
347pub struct StatusLabels {
348 pub status: String,
350}
351
352#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
354pub struct CommandLabels {
355 pub kind: String,
357 pub decision: String,
359}
360
361#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
363pub struct ByLabels {
364 pub by: String,
366}
367
368#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
370pub struct PartLabels {
371 pub part: String,
373}
374
375type Histograms<L> = Family<L, Histogram, fn() -> Histogram>;
376
377#[derive(Debug, Clone)]
379pub struct MasterMetrics {
380 pub tick_duration: Histogram,
382 pub start_recorded: Histogram,
384 pub core_lock_wait: Histograms<ByLabels>,
386 pub turn_part: Histograms<PartLabels>,
388 pub turn_messages: Histograms<PartLabels>,
390 pub round_part: Histograms<PartLabels>,
392 pub runs: Family<RunLabels, Gauge>,
394 pub runs_finished: Family<ResultLabels, Counter>,
396 pub runs_late_failed: Family<LateLabels, Counter>,
398 pub notifications_sent: Family<ChannelLabels, Counter>,
400 pub notifications_failed: Family<ChannelLabels, Counter>,
402 pub retention_deleted: Family<KindLabels, Counter>,
404 pub tasks: Family<StateLabels, Gauge>,
406 pub tasks_waiting: Family<ReasonLabels, Gauge>,
408 pub assignments: Counter,
410 pub rejections: Family<ReasonLabels, Counter>,
412 pub attempts_ended: Family<StatusLabels, Counter>,
414 pub parse_jobs_started: Counter,
416 pub parse_jobs_finished: Counter,
418 pub parse_duration: Histogram,
420 pub commands: Family<CommandLabels, Counter>,
422 pub command_latency: Histogram,
424 pub workers: Family<StateLabels, Gauge>,
426 pub leading: Gauge,
428 pub replaced_held: Gauge,
430 pub dags: Family<StateLabels, Gauge>,
432 pub dag_wakes: Family<ReasonLabels, Counter>,
434 pub triggers: Family<StateLabels, Gauge>,
436 pub trigger_events: Family<EventResultLabels, Counter>,
438 pub trigger_back_pressure_stops: Counter,
440 pub trigger_idle_restarts: Counter,
442 seen: Arc<Mutex<Seen>>,
444 staged: Arc<Mutex<Option<Vec<Staged>>>>,
446}
447
448#[derive(Debug, Default)]
449struct Seen {
450 runs: HashSet<RunLabels>,
451 tasks: HashSet<StateLabels>,
452 workers: HashSet<StateLabels>,
453 waiting: HashSet<ReasonLabels>,
454}
455
456impl Default for MasterMetrics {
457 fn default() -> Self {
458 Self {
459 tick_duration: Histogram::new(exponential_buckets(0.001, std::f64::consts::SQRT_2, 29)),
462 start_recorded: Histogram::new(exponential_buckets(
464 0.001,
465 std::f64::consts::SQRT_2,
466 29,
467 )),
468 core_lock_wait: Family::new_with_constructor(|| {
470 Histogram::new(exponential_buckets(0.0001, 2.0, 19))
471 }),
472 turn_part: Family::new_with_constructor(|| {
473 Histogram::new(exponential_buckets(0.0001, 2.0, 19))
474 }),
475 round_part: Family::new_with_constructor(|| {
476 Histogram::new(exponential_buckets(0.0001, 2.0, 19))
477 }),
478 turn_messages: Family::new_with_constructor(|| {
480 Histogram::new(exponential_buckets(1.0, 2.0, 8))
481 }),
482 runs: Family::default(),
483 runs_finished: Family::default(),
484 runs_late_failed: Family::default(),
485 notifications_sent: Family::default(),
486 notifications_failed: Family::default(),
487 retention_deleted: Family::default(),
488 tasks: Family::default(),
489 tasks_waiting: Family::default(),
490 assignments: Counter::default(),
491 rejections: Family::default(),
492 attempts_ended: Family::default(),
493 parse_jobs_started: Counter::default(),
494 parse_jobs_finished: Counter::default(),
495 parse_duration: Histogram::new(exponential_buckets(0.5, 2.0, 13)),
497 commands: Family::default(),
498 command_latency: Histogram::new(exponential_buckets(0.01, 2.0, 14)),
500 workers: Family::default(),
501 leading: Gauge::default(),
502 replaced_held: Gauge::default(),
503 dags: Family::default(),
504 dag_wakes: Family::default(),
505 triggers: Family::default(),
506 trigger_events: Family::default(),
507 trigger_back_pressure_stops: Counter::default(),
508 trigger_idle_restarts: Counter::default(),
509 seen: Arc::default(),
510 staged: Arc::default(),
511 }
512 }
513}
514
515impl MasterMetrics {
516 fn register_lock(&self, r: &mut Registry) {
518 r.register(
519 CORE_LOCK_WAIT.name,
520 CORE_LOCK_WAIT.help,
521 self.core_lock_wait.clone(),
522 );
523 r.register(TURN_PART.name, TURN_PART.help, self.turn_part.clone());
524 r.register(
525 TURN_MESSAGES.name,
526 TURN_MESSAGES.help,
527 self.turn_messages.clone(),
528 );
529 r.register(ROUND_PART.name, ROUND_PART.help, self.round_part.clone());
530 }
531
532 pub fn core_lock_waited(&self, by: &str, took: Duration) {
534 self.core_lock_wait
535 .get_or_create(&ByLabels { by: by.to_owned() })
536 .observe(took.as_secs_f64());
537 }
538
539 pub fn round_part_done(&self, part: &str, took: Duration) {
541 self.round_part
542 .get_or_create(&PartLabels {
543 part: part.to_owned(),
544 })
545 .observe(took.as_secs_f64());
546 }
547
548 pub fn turn_part_done(&self, part: &str, messages: usize, took: Duration) {
550 let labels = PartLabels {
551 part: part.to_owned(),
552 };
553 self.turn_part
554 .get_or_create(&labels)
555 .observe(took.as_secs_f64());
556 #[expect(
557 clippy::cast_precision_loss,
558 reason = "a turn's messages, far below 2^52"
559 )]
560 self.turn_messages
561 .get_or_create(&labels)
562 .observe(messages as f64);
563 }
564
565 pub fn register(&self, registry: &mut Registry) {
568 let r = registry;
569 r.register(
570 TICK_DURATION.name,
571 TICK_DURATION.help,
572 self.tick_duration.clone(),
573 );
574 r.register(
575 START_RECORDED.name,
576 START_RECORDED.help,
577 self.start_recorded.clone(),
578 );
579 self.register_lock(r);
580 r.register(RUNS.name, RUNS.help, self.runs.clone());
581 r.register(
582 RUNS_FINISHED.name,
583 RUNS_FINISHED.help,
584 self.runs_finished.clone(),
585 );
586 r.register(
587 RUNS_LATE_FAILED.name,
588 RUNS_LATE_FAILED.help,
589 self.runs_late_failed.clone(),
590 );
591 r.register(
592 NOTIFICATIONS_SENT.name,
593 NOTIFICATIONS_SENT.help,
594 self.notifications_sent.clone(),
595 );
596 r.register(
597 NOTIFICATIONS_FAILED.name,
598 NOTIFICATIONS_FAILED.help,
599 self.notifications_failed.clone(),
600 );
601 r.register(
602 RETENTION_DELETED.name,
603 RETENTION_DELETED.help,
604 self.retention_deleted.clone(),
605 );
606 r.register(TASKS.name, TASKS.help, self.tasks.clone());
607 r.register(
608 TASKS_WAITING.name,
609 TASKS_WAITING.help,
610 self.tasks_waiting.clone(),
611 );
612 r.register(ASSIGNMENTS.name, ASSIGNMENTS.help, self.assignments.clone());
613 r.register(REJECTIONS.name, REJECTIONS.help, self.rejections.clone());
614 r.register(
615 ATTEMPTS_ENDED.name,
616 ATTEMPTS_ENDED.help,
617 self.attempts_ended.clone(),
618 );
619 r.register(
620 PARSE_JOBS_STARTED.name,
621 PARSE_JOBS_STARTED.help,
622 self.parse_jobs_started.clone(),
623 );
624 r.register(
625 PARSE_JOBS_FINISHED.name,
626 PARSE_JOBS_FINISHED.help,
627 self.parse_jobs_finished.clone(),
628 );
629 r.register(
630 PARSE_DURATION.name,
631 PARSE_DURATION.help,
632 self.parse_duration.clone(),
633 );
634 r.register(COMMANDS.name, COMMANDS.help, self.commands.clone());
635 r.register(
636 COMMAND_LATENCY.name,
637 COMMAND_LATENCY.help,
638 self.command_latency.clone(),
639 );
640 r.register(WORKERS.name, WORKERS.help, self.workers.clone());
641 r.register(LEADING.name, LEADING.help, self.leading.clone());
642 r.register(
643 REPLACED_HELD.name,
644 REPLACED_HELD.help,
645 self.replaced_held.clone(),
646 );
647 r.register(DAGS.name, DAGS.help, self.dags.clone());
648 r.register(DAG_WAKES.name, DAG_WAKES.help, self.dag_wakes.clone());
649 r.register(TRIGGERS.name, TRIGGERS.help, self.triggers.clone());
650 r.register(
651 TRIGGER_EVENTS.name,
652 TRIGGER_EVENTS.help,
653 self.trigger_events.clone(),
654 );
655 r.register(
656 TRIGGER_BACK_PRESSURE_STOPS.name,
657 TRIGGER_BACK_PRESSURE_STOPS.help,
658 self.trigger_back_pressure_stops.clone(),
659 );
660 r.register(
661 TRIGGER_IDLE_RESTARTS.name,
662 TRIGGER_IDLE_RESTARTS.help,
663 self.trigger_idle_restarts.clone(),
664 );
665 }
666
667 pub fn set_dags(&self, busy: usize, quiet: usize, held: usize) {
669 for (state, count) in [("busy", busy), ("quiet", quiet), ("held", held)] {
670 self.dags
671 .get_or_create(&StateLabels {
672 state: state.to_owned(),
673 })
674 .set(i64::try_from(count).unwrap_or(i64::MAX));
675 }
676 }
677
678 pub fn set_triggers(&self, counts: TriggerCounts) {
680 for (state, count) in [
681 ("running", counts.running),
682 ("waiting", counts.waiting),
683 ("stopped", counts.stopped),
684 ("failing", counts.failing),
685 ] {
686 self.triggers
687 .get_or_create(&StateLabels {
688 state: state.to_owned(),
689 })
690 .set(i64::try_from(count).unwrap_or(i64::MAX));
691 }
692 }
693
694 pub fn trigger_event(&self, new: bool) {
696 self.trigger_events
697 .get_or_create(&EventResultLabels {
698 result: if new { "new" } else { "repeat" }.to_owned(),
699 })
700 .inc();
701 }
702
703 pub fn dag_woken(&self, reason: &str) {
705 self.dag_wakes
706 .get_or_create(&ReasonLabels {
707 reason: reason.to_owned(),
708 })
709 .inc();
710 }
711
712 pub fn set_counts(&self, counts: &StateCounts) {
714 let mut seen = self.seen.lock().unwrap_or_else(PoisonError::into_inner);
715 let runs = counts.runs.iter().map(|(state, kind, count)| {
716 let labels = RunLabels {
717 state: state.clone(),
718 kind: kind.clone(),
719 };
720 (labels, *count)
721 });
722 set_gauges(&self.runs, &mut seen.runs, runs);
723 set_gauges(&self.tasks, &mut seen.tasks, states(&counts.tasks));
724 set_gauges(&self.workers, &mut seen.workers, states(&counts.workers));
725 }
726
727 pub fn set_waiting(&self, waiting: &[(&'static str, i64)]) {
729 let mut seen = self.seen.lock().unwrap_or_else(PoisonError::into_inner);
730 let waiting = waiting.iter().map(|(reason, count)| {
731 let labels = ReasonLabels {
732 reason: (*reason).to_owned(),
733 };
734 (labels, *count)
735 });
736 set_gauges(&self.tasks_waiting, &mut seen.waiting, waiting);
737 }
738
739 pub fn attempt_ended(&self, status: &impl ToString) {
741 if self.held(|| Staged::AttemptEnded(status.to_string())) {
742 return;
743 }
744 self.attempts_ended
745 .get_or_create(&StatusLabels {
746 status: status.to_string(),
747 })
748 .inc();
749 }
750
751 pub fn run_late_failed(&self, dag_id: &str, reason: &str) {
753 if self.held(|| Staged::RunLateFailed(dag_id.to_owned(), reason.to_owned())) {
754 return;
755 }
756 self.runs_late_failed
757 .get_or_create(&LateLabels {
758 dag_id: dag_id.to_owned(),
759 reason: reason.to_owned(),
760 })
761 .inc();
762 }
763
764 pub fn notification_sent(&self, channel: &str) {
766 self.notifications_sent
767 .get_or_create(&ChannelLabels {
768 channel: channel.to_owned(),
769 })
770 .inc();
771 }
772
773 pub fn notification_failed(&self, channel: &str) {
775 self.notifications_failed
776 .get_or_create(&ChannelLabels {
777 channel: channel.to_owned(),
778 })
779 .inc();
780 }
781
782 pub fn retention_deleted(&self, kind: &str, n: u64) {
784 if n > 0 {
785 self.retention_deleted
786 .get_or_create(&KindLabels {
787 kind: kind.to_owned(),
788 })
789 .inc_by(n);
790 }
791 }
792
793 pub fn run_finished(&self, dag_id: &str, result: &impl ToString) {
795 if self.held(|| Staged::RunFinished(dag_id.to_owned(), result.to_string())) {
796 return;
797 }
798 self.runs_finished
799 .get_or_create(&ResultLabels {
800 dag_id: dag_id.to_owned(),
801 result: result.to_string(),
802 })
803 .inc();
804 }
805}
806
807#[derive(Debug, Clone, PartialEq, Eq)]
809enum Staged {
810 AttemptEnded(String),
811 RunFinished(String, String),
812 RunLateFailed(String, String),
813}
814
815impl MasterMetrics {
816 pub fn stage(&self) {
821 *self
822 .staged
823 .lock()
824 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Vec::new());
825 }
826
827 pub fn count_staged(&self) {
829 let held = self
830 .staged
831 .lock()
832 .unwrap_or_else(std::sync::PoisonError::into_inner)
833 .take();
834 for staged in held.unwrap_or_default() {
835 match staged {
836 Staged::AttemptEnded(status) => self.attempt_ended(&status),
837 Staged::RunFinished(dag_id, result) => self.run_finished(&dag_id, &result),
838 Staged::RunLateFailed(dag_id, reason) => self.run_late_failed(&dag_id, &reason),
839 }
840 }
841 }
842
843 pub fn drop_staged(&self) {
845 self.staged
846 .lock()
847 .unwrap_or_else(std::sync::PoisonError::into_inner)
848 .take();
849 }
850
851 fn held(&self, staged: impl FnOnce() -> Staged) -> bool {
853 let mut held = self
854 .staged
855 .lock()
856 .unwrap_or_else(std::sync::PoisonError::into_inner);
857 held.as_mut().map(|held| held.push(staged())).is_some()
858 }
859}
860
861fn states(counts: &[(String, i64)]) -> impl Iterator<Item = (StateLabels, i64)> + '_ {
862 counts.iter().map(|(state, count)| {
863 let labels = StateLabels {
864 state: state.clone(),
865 };
866 (labels, *count)
867 })
868}
869
870fn set_gauges<L: Clone + Hash + Eq + EncodeLabelSet + std::fmt::Debug + Send + Sync + 'static>(
873 family: &Family<L, Gauge>,
874 seen: &mut HashSet<L>,
875 counts: impl Iterator<Item = (L, i64)>,
876) {
877 let counts: Vec<(L, i64)> = counts.collect();
878 for labels in seen.iter() {
879 if !counts.iter().any(|(counted, _)| counted == labels) {
880 family.get_or_create(labels).set(0);
881 }
882 }
883 for (labels, count) in counts {
884 family.get_or_create(&labels).set(count);
885 seen.insert(labels);
886 }
887}