1use prometheus_client::encoding::EncodeLabelSet;
6use prometheus_client::metrics::counter::Counter;
7use prometheus_client::metrics::family::Family;
8use prometheus_client::metrics::gauge::Gauge;
9use prometheus_client::metrics::histogram::{Histogram, exponential_buckets};
10use prometheus_client::registry::Registry;
11use schedr_model::metric_doc::{MetricDoc, MetricKind};
12
13use crate::attempt::StartTimes;
14
15#[cfg(test)]
16mod tests;
17
18const SLOTS: MetricDoc = MetricDoc {
19 name: "worker_slots",
20 kind: MetricKind::Gauge,
21 labels: &[],
22 help: "Task slots",
23};
24const SLOTS_USED: MetricDoc = MetricDoc {
25 name: "worker_slots_used",
26 kind: MetricKind::Gauge,
27 labels: &[],
28 help: "Task slots in use",
29};
30const ATTEMPTS: MetricDoc = MetricDoc {
31 name: "worker_attempts",
32 kind: MetricKind::Counter,
33 labels: &["status"],
34 help: "Attempts ended on this worker, by status",
35};
36const TASK_START: MetricDoc = MetricDoc {
37 name: "worker_task_start_seconds",
38 kind: MetricKind::Histogram,
39 labels: &["method", "phase"],
40 help: "How long Python tasks took to start, by start method (spawn, fork) and phase \
41 (runner: from starting the process to the runner's hello; import: from sending the \
42 task to the DAG file imported, not counted when that fails)",
43};
44const ASSIGN_TO_STARTED: MetricDoc = MetricDoc {
45 name: "worker_assign_to_started_seconds",
46 kind: MetricKind::Histogram,
47 labels: &[],
48 help: "How long an assignment took from its `AssignTask` taken by the agent's loop to its \
49 `Started` sent (its plan, inputs and journal record): not counted when rejected",
50};
51const JOURNAL_WRITE: MetricDoc = MetricDoc {
52 name: "worker_journal_write_seconds",
53 kind: MetricKind::Histogram,
54 labels: &["record"],
55 help: "How long the journal took to keep records on disk, by record (start: a group of \
56 attempts before their `Started`s; process: a group of their processes' identities; \
57 results: a group of results)",
58};
59const MASTER_SAMPLE_AGE: MetricDoc = MetricDoc {
60 name: "worker_master_sample_age_seconds",
61 kind: MetricKind::Gauge,
62 labels: &[],
63 help: "How old the heartbeat is that the worker reads master time from (decision 447: the \
64 tightest of its window; growing past a few heartbeats means the master isn't answering)",
65};
66const MASTER_ROUND_TRIP: MetricDoc = MetricDoc {
67 name: "worker_master_round_trip_seconds",
68 kind: MetricKind::Gauge,
69 labels: &[],
70 help: "That message's round trip, from its send to the master's answer naming it: how much \
71 the worker's master-time deadlines lose to the link",
72};
73const OLDER_EPOCH: MetricDoc = MetricDoc {
74 name: "worker_older_epoch_refusals",
75 kind: MetricKind::Counter,
76 labels: &[],
77 help: "Streams ended because their master leads with a lower lease epoch than one seen \
78 (decision 444: a deposed master still answering)",
79};
80const WATCHDOG_KILLS: MetricDoc = MetricDoc {
81 name: "worker_watchdog_kills",
82 kind: MetricKind::Counter,
83 labels: &[],
84 help: "Tasks and parse runners killed over their memory budget",
85};
86const JOURNAL_RECORDS: MetricDoc = MetricDoc {
87 name: "worker_journal_records",
88 kind: MetricKind::Gauge,
89 labels: &[],
90 help: "Attempts in the journal (running, or results not acknowledged)",
91};
92const LOG_BYTES: MetricDoc = MetricDoc {
93 name: "worker_log_bytes",
94 kind: MetricKind::Gauge,
95 labels: &[],
96 help: "Bytes of logs kept, as of the last retention sweep",
97};
98const FORK_SERVERS: MetricDoc = MetricDoc {
99 name: "worker_fork_servers",
100 kind: MetricKind::Gauge,
101 labels: &["interpreter", "kind", "state"],
102 help: "Fork servers by interpreter, kind (preloaded, bare) and state (up, down, disabled): \
103 1 for each server's current state",
104};
105const FORK_FALLBACKS: MetricDoc = MetricDoc {
106 name: "worker_fork_fallbacks",
107 kind: MetricKind::Counter,
108 labels: &["interpreter", "reason"],
109 help: "Python tasks a fork server didn't fork, by interpreter and reason (disabled, down, \
110 fork_failed, shim_died); the next fork server, or spawn, starts them",
111};
112const LOG_SWEPT_BYTES: MetricDoc = MetricDoc {
113 name: "worker_log_swept_bytes",
114 kind: MetricKind::Counter,
115 labels: &[],
116 help: "Bytes of logs deleted by retention",
117};
118const WATCHER_SLOTS: MetricDoc = MetricDoc {
119 name: "worker_watcher_slots",
120 kind: MetricKind::Gauge,
121 labels: &[],
122 help: "Slots for wait steps",
123};
124const WATCHER_SLOTS_USED: MetricDoc = MetricDoc {
125 name: "worker_watcher_slots_used",
126 kind: MetricKind::Gauge,
127 labels: &[],
128 help: "Wait steps running",
129};
130const WATCHER_HOSTS: MetricDoc = MetricDoc {
131 name: "worker_watcher_hosts",
132 kind: MetricKind::Gauge,
133 labels: &[],
134 help: "Processes running wait steps, one per code set",
135};
136const WATCHER_THREADS: MetricDoc = MetricDoc {
137 name: "worker_watcher_threads",
138 kind: MetricKind::Gauge,
139 labels: &["kind"],
140 help: "Threads of the hosts, by kind (tied: running a wait step's `to_thread` calls or \
141 started by it; untied: the rest of the process, a library's pools among them)",
142};
143const WATCHER_MEMORY: MetricDoc = MetricDoc {
144 name: "worker_watcher_memory_bytes",
145 kind: MetricKind::Gauge,
146 labels: &[],
147 help: "Memory the hosts use together, against `[watchers] memory_budget`",
148};
149const WATCHER_LOOP_LAG: MetricDoc = MetricDoc {
150 name: "worker_watcher_loop_lag_seconds",
151 kind: MetricKind::Histogram,
152 labels: &[],
153 help: "How long a host's event loop took to get to a call: long ones are wait steps \
154 holding it up, short of `[watchers] block_limit`",
155};
156const WATCHER_BLOCKED_KILLS: MetricDoc = MetricDoc {
157 name: "worker_watcher_blocked_kills",
158 kind: MetricKind::Counter,
159 labels: &[],
160 help: "Hosts killed for one wait step: it held the event loop, a thread of it stayed stuck, \
161 or it ignored its cancel",
162};
163const WATCHER_RESTARTS: MetricDoc = MetricDoc {
164 name: "worker_watcher_restarts",
165 kind: MetricKind::Counter,
166 labels: &[],
167 help: "Wait steps started again on a new host, as another one got theirs killed",
168};
169const WATCHER_HOSTS_LOST: MetricDoc = MetricDoc {
170 name: "worker_watcher_hosts_lost",
171 kind: MetricKind::Counter,
172 labels: &["code"],
173 help: "Hosts ended with no wait step to blame (a crash, a memory kill, silence), by the code \
174 they ran: their wait steps use a retry",
175};
176const WATCHER_THREAD_STOPS: MetricDoc = MetricDoc {
177 name: "worker_watcher_thread_stops",
178 kind: MetricKind::Counter,
179 labels: &[],
180 help: "`to_thread` calls stopped at their wait step's end, each of which may have left \
181 shared state half updated",
182};
183
184pub const METRICS: &[MetricDoc] = &[
186 SLOTS,
187 SLOTS_USED,
188 ATTEMPTS,
189 TASK_START,
190 ASSIGN_TO_STARTED,
191 JOURNAL_WRITE,
192 MASTER_SAMPLE_AGE,
193 MASTER_ROUND_TRIP,
194 OLDER_EPOCH,
195 WATCHDOG_KILLS,
196 JOURNAL_RECORDS,
197 LOG_BYTES,
198 LOG_SWEPT_BYTES,
199 FORK_SERVERS,
200 FORK_FALLBACKS,
201 WATCHER_SLOTS,
202 WATCHER_SLOTS_USED,
203 WATCHER_HOSTS,
204 WATCHER_THREADS,
205 WATCHER_MEMORY,
206 WATCHER_LOOP_LAG,
207 WATCHER_BLOCKED_KILLS,
208 WATCHER_RESTARTS,
209 WATCHER_HOSTS_LOST,
210 WATCHER_THREAD_STOPS,
211];
212
213#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
215pub struct StatusLabels {
216 pub status: String,
218}
219
220#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
222pub struct StartLabels {
223 pub method: String,
225 pub phase: String,
227}
228
229#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
231pub struct RecordLabels {
232 pub record: String,
234}
235
236#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
238pub struct ForkServerLabels {
239 pub interpreter: String,
241 pub kind: String,
243 pub state: String,
245}
246
247#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
249pub struct ForkFallbackLabels {
250 pub interpreter: String,
252 pub reason: String,
254}
255
256#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
258pub struct ThreadLabels {
259 pub kind: String,
261}
262
263#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
265pub struct CodeLabels {
266 pub code: String,
268}
269
270#[derive(Debug, Clone)]
272pub struct WatcherMetrics {
273 pub slots: Gauge,
275 pub slots_used: Gauge,
277 pub hosts: Gauge,
279 pub threads: Family<ThreadLabels, Gauge>,
281 pub memory: Gauge,
283 pub loop_lag: Histogram,
285 pub blocked_kills: Counter,
287 pub restarts: Counter,
289 pub hosts_lost: Family<CodeLabels, Counter>,
291 pub thread_stops: Counter,
293}
294
295impl Default for WatcherMetrics {
296 fn default() -> Self {
297 Self {
298 slots: Gauge::default(),
299 slots_used: Gauge::default(),
300 hosts: Gauge::default(),
301 threads: Family::default(),
302 memory: Gauge::default(),
303 loop_lag: Histogram::new(exponential_buckets(0.001, 2.0, 16)),
305 blocked_kills: Counter::default(),
306 restarts: Counter::default(),
307 hosts_lost: Family::default(),
308 thread_stops: Counter::default(),
309 }
310 }
311}
312
313impl WatcherMetrics {
314 fn register(&self, r: &mut Registry) {
315 r.register(WATCHER_SLOTS.name, WATCHER_SLOTS.help, self.slots.clone());
316 r.register(
317 WATCHER_SLOTS_USED.name,
318 WATCHER_SLOTS_USED.help,
319 self.slots_used.clone(),
320 );
321 r.register(WATCHER_HOSTS.name, WATCHER_HOSTS.help, self.hosts.clone());
322 r.register(
323 WATCHER_THREADS.name,
324 WATCHER_THREADS.help,
325 self.threads.clone(),
326 );
327 r.register(
328 WATCHER_MEMORY.name,
329 WATCHER_MEMORY.help,
330 self.memory.clone(),
331 );
332 r.register(
333 WATCHER_LOOP_LAG.name,
334 WATCHER_LOOP_LAG.help,
335 self.loop_lag.clone(),
336 );
337 r.register(
338 WATCHER_BLOCKED_KILLS.name,
339 WATCHER_BLOCKED_KILLS.help,
340 self.blocked_kills.clone(),
341 );
342 r.register(
343 WATCHER_RESTARTS.name,
344 WATCHER_RESTARTS.help,
345 self.restarts.clone(),
346 );
347 r.register(
348 WATCHER_HOSTS_LOST.name,
349 WATCHER_HOSTS_LOST.help,
350 self.hosts_lost.clone(),
351 );
352 r.register(
353 WATCHER_THREAD_STOPS.name,
354 WATCHER_THREAD_STOPS.help,
355 self.thread_stops.clone(),
356 );
357 }
358
359 pub fn set_threads(&self, tied: u64, untied: u64) {
361 for (kind, count) in [("tied", tied), ("untied", untied)] {
362 self.threads
363 .get_or_create(&ThreadLabels {
364 kind: kind.to_owned(),
365 })
366 .set(i64::try_from(count).unwrap_or(i64::MAX));
367 }
368 }
369}
370
371type StartHistograms = Family<StartLabels, Histogram, fn() -> Histogram>;
372
373#[derive(Debug, Clone)]
375pub struct AgentMetrics {
376 pub slots: Gauge,
378 pub slots_used: Gauge,
380 pub attempts: Family<StatusLabels, Counter>,
382 pub task_start: StartHistograms,
384 pub assign_to_started: Histogram,
386 pub journal_write: Family<RecordLabels, Histogram, fn() -> Histogram>,
388 pub master_sample_age: Gauge<f64, std::sync::atomic::AtomicU64>,
390 pub master_round_trip: Gauge<f64, std::sync::atomic::AtomicU64>,
392 pub older_epoch: Counter,
394 pub watchdog_kills: Counter,
396 pub journal_records: Gauge,
398 pub log_bytes: Gauge,
400 pub log_swept_bytes: Counter,
402 pub fork: crate::fork::ForkMetrics,
404 pub watchers: WatcherMetrics,
406}
407
408impl Default for AgentMetrics {
409 fn default() -> Self {
410 Self {
411 slots: Gauge::default(),
412 slots_used: Gauge::default(),
413 attempts: Family::default(),
414 task_start: Family::new_with_constructor(|| {
416 Histogram::new(exponential_buckets(0.01, 2.0, 13))
417 }),
418 assign_to_started: Histogram::new(exponential_buckets(0.0001, 2.0, 19)),
420 journal_write: Family::new_with_constructor(|| {
421 Histogram::new(exponential_buckets(0.0001, 2.0, 19))
422 }),
423 master_sample_age: Gauge::default(),
424 master_round_trip: Gauge::default(),
425 older_epoch: Counter::default(),
427 watchdog_kills: Counter::default(),
428 journal_records: Gauge::default(),
429 log_bytes: Gauge::default(),
430 log_swept_bytes: Counter::default(),
431 fork: crate::fork::ForkMetrics::default(),
432 watchers: WatcherMetrics::default(),
433 }
434 }
435}
436
437impl AgentMetrics {
438 pub fn register(&self, registry: &mut Registry) {
441 let r = registry;
442 r.register(SLOTS.name, SLOTS.help, self.slots.clone());
443 r.register(SLOTS_USED.name, SLOTS_USED.help, self.slots_used.clone());
444 r.register(ATTEMPTS.name, ATTEMPTS.help, self.attempts.clone());
445 r.register(TASK_START.name, TASK_START.help, self.task_start.clone());
446 r.register(
447 ASSIGN_TO_STARTED.name,
448 ASSIGN_TO_STARTED.help,
449 self.assign_to_started.clone(),
450 );
451 r.register(
452 JOURNAL_WRITE.name,
453 JOURNAL_WRITE.help,
454 self.journal_write.clone(),
455 );
456 r.register(
457 MASTER_SAMPLE_AGE.name,
458 MASTER_SAMPLE_AGE.help,
459 self.master_sample_age.clone(),
460 );
461 r.register(
462 MASTER_ROUND_TRIP.name,
463 MASTER_ROUND_TRIP.help,
464 self.master_round_trip.clone(),
465 );
466 r.register(OLDER_EPOCH.name, OLDER_EPOCH.help, self.older_epoch.clone());
467 r.register(
468 WATCHDOG_KILLS.name,
469 WATCHDOG_KILLS.help,
470 self.watchdog_kills.clone(),
471 );
472 r.register(
473 JOURNAL_RECORDS.name,
474 JOURNAL_RECORDS.help,
475 self.journal_records.clone(),
476 );
477 r.register(LOG_BYTES.name, LOG_BYTES.help, self.log_bytes.clone());
478 r.register(
479 LOG_SWEPT_BYTES.name,
480 LOG_SWEPT_BYTES.help,
481 self.log_swept_bytes.clone(),
482 );
483 r.register(
484 FORK_SERVERS.name,
485 FORK_SERVERS.help,
486 self.fork.servers.clone(),
487 );
488 r.register(
489 FORK_FALLBACKS.name,
490 FORK_FALLBACKS.help,
491 self.fork.fallbacks.clone(),
492 );
493 self.watchers.register(r);
494 }
495
496 pub fn task_started(&self, method: &str, start: &StartTimes) {
498 let phases = [("runner", Some(start.runner)), ("import", start.import)];
499 for (phase, took) in phases {
500 if let Some(took) = took {
501 self.task_start
502 .get_or_create(&StartLabels {
503 method: method.to_owned(),
504 phase: phase.to_owned(),
505 })
506 .observe(took.as_secs_f64());
507 }
508 }
509 }
510
511 pub fn journal_written(&self, record: &str, took: std::time::Duration) {
513 self.journal_write
514 .get_or_create(&RecordLabels {
515 record: record.to_owned(),
516 })
517 .observe(took.as_secs_f64());
518 }
519
520 pub fn attempt_ended(&self, status: &impl ToString) {
522 self.attempts
523 .get_or_create(&StatusLabels {
524 status: status.to_string(),
525 })
526 .inc();
527 }
528}