Line data Source code
1 : //! Global safekeeper mertics and per-timeline safekeeper metrics.
2 :
3 : use std::{
4 : sync::{Arc, RwLock},
5 : time::{Instant, SystemTime},
6 : };
7 :
8 : use ::metrics::{register_histogram, GaugeVec, Histogram, IntGauge, DISK_FSYNC_SECONDS_BUCKETS};
9 : use anyhow::Result;
10 : use futures::Future;
11 : use metrics::{
12 : core::{AtomicU64, Collector, Desc, GenericCounter, GenericGaugeVec, Opts},
13 : proto::MetricFamily,
14 : register_histogram_vec, register_int_counter, register_int_counter_pair,
15 : register_int_counter_pair_vec, register_int_counter_vec, register_int_gauge, Gauge,
16 : HistogramVec, IntCounter, IntCounterPair, IntCounterPairVec, IntCounterVec, IntGaugeVec,
17 : };
18 : use once_cell::sync::Lazy;
19 :
20 : use postgres_ffi::XLogSegNo;
21 : use utils::pageserver_feedback::PageserverFeedback;
22 : use utils::{id::TenantTimelineId, lsn::Lsn};
23 :
24 : use crate::{
25 : state::{TimelineMemState, TimelinePersistentState},
26 : GlobalTimelines,
27 : };
28 :
29 : // Global metrics across all timelines.
30 0 : pub static WRITE_WAL_BYTES: Lazy<Histogram> = Lazy::new(|| {
31 0 : register_histogram!(
32 0 : "safekeeper_write_wal_bytes",
33 0 : "Bytes written to WAL in a single request",
34 0 : vec![
35 0 : 1.0,
36 0 : 10.0,
37 0 : 100.0,
38 0 : 1024.0,
39 0 : 8192.0,
40 0 : 128.0 * 1024.0,
41 0 : 1024.0 * 1024.0,
42 0 : 10.0 * 1024.0 * 1024.0
43 0 : ]
44 0 : )
45 0 : .expect("Failed to register safekeeper_write_wal_bytes histogram")
46 0 : });
47 0 : pub static WRITE_WAL_SECONDS: Lazy<Histogram> = Lazy::new(|| {
48 0 : register_histogram!(
49 0 : "safekeeper_write_wal_seconds",
50 0 : "Seconds spent writing and syncing WAL to a disk in a single request",
51 0 : DISK_FSYNC_SECONDS_BUCKETS.to_vec()
52 0 : )
53 0 : .expect("Failed to register safekeeper_write_wal_seconds histogram")
54 0 : });
55 0 : pub static FLUSH_WAL_SECONDS: Lazy<Histogram> = Lazy::new(|| {
56 0 : register_histogram!(
57 0 : "safekeeper_flush_wal_seconds",
58 0 : "Seconds spent syncing WAL to a disk",
59 0 : DISK_FSYNC_SECONDS_BUCKETS.to_vec()
60 0 : )
61 0 : .expect("Failed to register safekeeper_flush_wal_seconds histogram")
62 0 : });
63 2 : pub static PERSIST_CONTROL_FILE_SECONDS: Lazy<Histogram> = Lazy::new(|| {
64 2 : register_histogram!(
65 2 : "safekeeper_persist_control_file_seconds",
66 2 : "Seconds to persist and sync control file",
67 2 : DISK_FSYNC_SECONDS_BUCKETS.to_vec()
68 2 : )
69 2 : .expect("Failed to register safekeeper_persist_control_file_seconds histogram vec")
70 2 : });
71 0 : pub static WAL_STORAGE_OPERATION_SECONDS: Lazy<HistogramVec> = Lazy::new(|| {
72 0 : register_histogram_vec!(
73 0 : "safekeeper_wal_storage_operation_seconds",
74 0 : "Seconds spent on WAL storage operations",
75 0 : &["operation"],
76 0 : DISK_FSYNC_SECONDS_BUCKETS.to_vec()
77 0 : )
78 0 : .expect("Failed to register safekeeper_wal_storage_operation_seconds histogram vec")
79 0 : });
80 10 : pub static MISC_OPERATION_SECONDS: Lazy<HistogramVec> = Lazy::new(|| {
81 10 : register_histogram_vec!(
82 10 : "safekeeper_misc_operation_seconds",
83 10 : "Seconds spent on miscellaneous operations",
84 10 : &["operation"],
85 10 : DISK_FSYNC_SECONDS_BUCKETS.to_vec()
86 10 : )
87 10 : .expect("Failed to register safekeeper_misc_operation_seconds histogram vec")
88 10 : });
89 0 : pub static PG_IO_BYTES: Lazy<IntCounterVec> = Lazy::new(|| {
90 0 : register_int_counter_vec!(
91 0 : "safekeeper_pg_io_bytes_total",
92 0 : "Bytes read from or written to any PostgreSQL connection",
93 0 : &["client_az", "sk_az", "app_name", "dir", "same_az"]
94 0 : )
95 0 : .expect("Failed to register safekeeper_pg_io_bytes gauge")
96 0 : });
97 0 : pub static BROKER_PUSHED_UPDATES: Lazy<IntCounter> = Lazy::new(|| {
98 0 : register_int_counter!(
99 0 : "safekeeper_broker_pushed_updates_total",
100 0 : "Number of timeline updates pushed to the broker"
101 0 : )
102 0 : .expect("Failed to register safekeeper_broker_pushed_updates_total counter")
103 0 : });
104 0 : pub static BROKER_PULLED_UPDATES: Lazy<IntCounterVec> = Lazy::new(|| {
105 0 : register_int_counter_vec!(
106 0 : "safekeeper_broker_pulled_updates_total",
107 0 : "Number of timeline updates pulled and processed from the broker",
108 0 : &["result"]
109 0 : )
110 0 : .expect("Failed to register safekeeper_broker_pulled_updates_total counter")
111 0 : });
112 0 : pub static PG_QUERIES_GAUGE: Lazy<IntCounterPairVec> = Lazy::new(|| {
113 0 : register_int_counter_pair_vec!(
114 0 : "safekeeper_pg_queries_received_total",
115 0 : "Number of queries received through pg protocol",
116 0 : "safekeeper_pg_queries_finished_total",
117 0 : "Number of queries finished through pg protocol",
118 0 : &["query"]
119 0 : )
120 0 : .expect("Failed to register safekeeper_pg_queries_finished_total counter")
121 0 : });
122 0 : pub static REMOVED_WAL_SEGMENTS: Lazy<IntCounter> = Lazy::new(|| {
123 0 : register_int_counter!(
124 0 : "safekeeper_removed_wal_segments_total",
125 0 : "Number of WAL segments removed from the disk"
126 0 : )
127 0 : .expect("Failed to register safekeeper_removed_wal_segments_total counter")
128 0 : });
129 0 : pub static BACKED_UP_SEGMENTS: Lazy<IntCounter> = Lazy::new(|| {
130 0 : register_int_counter!(
131 0 : "safekeeper_backed_up_segments_total",
132 0 : "Number of WAL segments backed up to the S3"
133 0 : )
134 0 : .expect("Failed to register safekeeper_backed_up_segments_total counter")
135 0 : });
136 0 : pub static BACKUP_ERRORS: Lazy<IntCounter> = Lazy::new(|| {
137 0 : register_int_counter!(
138 0 : "safekeeper_backup_errors_total",
139 0 : "Number of errors during backup"
140 0 : )
141 0 : .expect("Failed to register safekeeper_backup_errors_total counter")
142 0 : });
143 0 : pub static BROKER_PUSH_ALL_UPDATES_SECONDS: Lazy<Histogram> = Lazy::new(|| {
144 0 : register_histogram!(
145 0 : "safekeeper_broker_push_update_seconds",
146 0 : "Seconds to push all timeline updates to the broker",
147 0 : DISK_FSYNC_SECONDS_BUCKETS.to_vec()
148 0 : )
149 0 : .expect("Failed to register safekeeper_broker_push_update_seconds histogram vec")
150 0 : });
151 : pub const TIMELINES_COUNT_BUCKETS: &[f64] = &[
152 : 1.0, 10.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0, 20000.0, 50000.0,
153 : ];
154 0 : pub static BROKER_ITERATION_TIMELINES: Lazy<Histogram> = Lazy::new(|| {
155 0 : register_histogram!(
156 0 : "safekeeper_broker_iteration_timelines",
157 0 : "Count of timelines pushed to the broker in a single iteration",
158 0 : TIMELINES_COUNT_BUCKETS.to_vec()
159 0 : )
160 0 : .expect("Failed to register safekeeper_broker_iteration_timelines histogram vec")
161 0 : });
162 0 : pub static RECEIVED_PS_FEEDBACKS: Lazy<IntCounter> = Lazy::new(|| {
163 0 : register_int_counter!(
164 0 : "safekeeper_received_ps_feedbacks_total",
165 0 : "Number of pageserver feedbacks received"
166 0 : )
167 0 : .expect("Failed to register safekeeper_received_ps_feedbacks_total counter")
168 0 : });
169 0 : pub static PARTIAL_BACKUP_UPLOADS: Lazy<IntCounterVec> = Lazy::new(|| {
170 0 : register_int_counter_vec!(
171 0 : "safekeeper_partial_backup_uploads_total",
172 0 : "Number of partial backup uploads to the S3",
173 0 : &["result"]
174 0 : )
175 0 : .expect("Failed to register safekeeper_partial_backup_uploads_total counter")
176 0 : });
177 0 : pub static PARTIAL_BACKUP_UPLOADED_BYTES: Lazy<IntCounter> = Lazy::new(|| {
178 0 : register_int_counter!(
179 0 : "safekeeper_partial_backup_uploaded_bytes_total",
180 0 : "Number of bytes uploaded to the S3 during partial backup"
181 0 : )
182 0 : .expect("Failed to register safekeeper_partial_backup_uploaded_bytes_total counter")
183 0 : });
184 0 : pub static MANAGER_ITERATIONS_TOTAL: Lazy<IntCounter> = Lazy::new(|| {
185 0 : register_int_counter!(
186 0 : "safekeeper_manager_iterations_total",
187 0 : "Number of iterations of the timeline manager task"
188 0 : )
189 0 : .expect("Failed to register safekeeper_manager_iterations_total counter")
190 0 : });
191 0 : pub static MANAGER_ACTIVE_CHANGES: Lazy<IntCounter> = Lazy::new(|| {
192 0 : register_int_counter!(
193 0 : "safekeeper_manager_active_changes_total",
194 0 : "Number of timeline active status changes in the timeline manager task"
195 0 : )
196 0 : .expect("Failed to register safekeeper_manager_active_changes_total counter")
197 0 : });
198 0 : pub static WAL_BACKUP_TASKS: Lazy<IntCounterPair> = Lazy::new(|| {
199 0 : register_int_counter_pair!(
200 0 : "safekeeper_wal_backup_tasks_started_total",
201 0 : "Number of active WAL backup tasks",
202 0 : "safekeeper_wal_backup_tasks_finished_total",
203 0 : "Number of finished WAL backup tasks",
204 0 : )
205 0 : .expect("Failed to register safekeeper_wal_backup_tasks_finished_total counter")
206 0 : });
207 :
208 : // Metrics collected on operations on the storage repository.
209 0 : #[derive(strum_macros::EnumString, strum_macros::Display, strum_macros::IntoStaticStr)]
210 : #[strum(serialize_all = "kebab_case")]
211 : pub(crate) enum EvictionEvent {
212 : Evict,
213 : Restore,
214 : }
215 :
216 0 : pub(crate) static EVICTION_EVENTS_STARTED: Lazy<IntCounterVec> = Lazy::new(|| {
217 0 : register_int_counter_vec!(
218 0 : "safekeeper_eviction_events_started_total",
219 0 : "Number of eviction state changes, incremented when they start",
220 0 : &["kind"]
221 0 : )
222 0 : .expect("Failed to register metric")
223 0 : });
224 :
225 0 : pub(crate) static EVICTION_EVENTS_COMPLETED: Lazy<IntCounterVec> = Lazy::new(|| {
226 0 : register_int_counter_vec!(
227 0 : "safekeeper_eviction_events_completed_total",
228 0 : "Number of eviction state changes, incremented when they complete",
229 0 : &["kind"]
230 0 : )
231 0 : .expect("Failed to register metric")
232 0 : });
233 :
234 0 : pub static NUM_EVICTED_TIMELINES: Lazy<IntGauge> = Lazy::new(|| {
235 0 : register_int_gauge!(
236 0 : "safekeeper_evicted_timelines",
237 0 : "Number of currently evicted timelines"
238 0 : )
239 0 : .expect("Failed to register metric")
240 0 : });
241 :
242 : pub const LABEL_UNKNOWN: &str = "unknown";
243 :
244 : /// Labels for traffic metrics.
245 : #[derive(Clone)]
246 : struct ConnectionLabels {
247 : /// Availability zone of the connection origin.
248 : client_az: String,
249 : /// Availability zone of the current safekeeper.
250 : sk_az: String,
251 : /// Client application name.
252 : app_name: String,
253 : }
254 :
255 : impl ConnectionLabels {
256 0 : fn new() -> Self {
257 0 : Self {
258 0 : client_az: LABEL_UNKNOWN.to_string(),
259 0 : sk_az: LABEL_UNKNOWN.to_string(),
260 0 : app_name: LABEL_UNKNOWN.to_string(),
261 0 : }
262 0 : }
263 :
264 0 : fn build_metrics(
265 0 : &self,
266 0 : ) -> (
267 0 : GenericCounter<metrics::core::AtomicU64>,
268 0 : GenericCounter<metrics::core::AtomicU64>,
269 0 : ) {
270 0 : let same_az = match (self.client_az.as_str(), self.sk_az.as_str()) {
271 0 : (LABEL_UNKNOWN, _) | (_, LABEL_UNKNOWN) => LABEL_UNKNOWN,
272 0 : (client_az, sk_az) => {
273 0 : if client_az == sk_az {
274 0 : "true"
275 : } else {
276 0 : "false"
277 : }
278 : }
279 : };
280 :
281 0 : let read = PG_IO_BYTES.with_label_values(&[
282 0 : &self.client_az,
283 0 : &self.sk_az,
284 0 : &self.app_name,
285 0 : "read",
286 0 : same_az,
287 0 : ]);
288 0 : let write = PG_IO_BYTES.with_label_values(&[
289 0 : &self.client_az,
290 0 : &self.sk_az,
291 0 : &self.app_name,
292 0 : "write",
293 0 : same_az,
294 0 : ]);
295 0 : (read, write)
296 0 : }
297 : }
298 :
299 : struct TrafficMetricsState {
300 : /// Labels for traffic metrics.
301 : labels: ConnectionLabels,
302 : /// Total bytes read from this connection.
303 : read: GenericCounter<metrics::core::AtomicU64>,
304 : /// Total bytes written to this connection.
305 : write: GenericCounter<metrics::core::AtomicU64>,
306 : }
307 :
308 : /// Metrics for measuring traffic (r/w bytes) in a single PostgreSQL connection.
309 : #[derive(Clone)]
310 : pub struct TrafficMetrics {
311 : state: Arc<RwLock<TrafficMetricsState>>,
312 : }
313 :
314 : impl Default for TrafficMetrics {
315 0 : fn default() -> Self {
316 0 : Self::new()
317 0 : }
318 : }
319 :
320 : impl TrafficMetrics {
321 0 : pub fn new() -> Self {
322 0 : let labels = ConnectionLabels::new();
323 0 : let (read, write) = labels.build_metrics();
324 0 : let state = TrafficMetricsState {
325 0 : labels,
326 0 : read,
327 0 : write,
328 0 : };
329 0 : Self {
330 0 : state: Arc::new(RwLock::new(state)),
331 0 : }
332 0 : }
333 :
334 0 : pub fn set_client_az(&self, value: &str) {
335 0 : let mut state = self.state.write().unwrap();
336 0 : state.labels.client_az = value.to_string();
337 0 : (state.read, state.write) = state.labels.build_metrics();
338 0 : }
339 :
340 0 : pub fn set_sk_az(&self, value: &str) {
341 0 : let mut state = self.state.write().unwrap();
342 0 : state.labels.sk_az = value.to_string();
343 0 : (state.read, state.write) = state.labels.build_metrics();
344 0 : }
345 :
346 0 : pub fn set_app_name(&self, value: &str) {
347 0 : let mut state = self.state.write().unwrap();
348 0 : state.labels.app_name = value.to_string();
349 0 : (state.read, state.write) = state.labels.build_metrics();
350 0 : }
351 :
352 0 : pub fn observe_read(&self, cnt: usize) {
353 0 : self.state.read().unwrap().read.inc_by(cnt as u64)
354 0 : }
355 :
356 0 : pub fn observe_write(&self, cnt: usize) {
357 0 : self.state.read().unwrap().write.inc_by(cnt as u64)
358 0 : }
359 : }
360 :
361 : /// Metrics for WalStorage in a single timeline.
362 : #[derive(Clone, Default)]
363 : pub struct WalStorageMetrics {
364 : /// How much bytes were written in total.
365 : write_wal_bytes: u64,
366 : /// How much time spent writing WAL to disk, waiting for write(2).
367 : write_wal_seconds: f64,
368 : /// How much time spent syncing WAL to disk, waiting for fsync(2).
369 : flush_wal_seconds: f64,
370 : }
371 :
372 : impl WalStorageMetrics {
373 0 : pub fn observe_write_bytes(&mut self, bytes: usize) {
374 0 : self.write_wal_bytes += bytes as u64;
375 0 : WRITE_WAL_BYTES.observe(bytes as f64);
376 0 : }
377 :
378 0 : pub fn observe_write_seconds(&mut self, seconds: f64) {
379 0 : self.write_wal_seconds += seconds;
380 0 : WRITE_WAL_SECONDS.observe(seconds);
381 0 : }
382 :
383 0 : pub fn observe_flush_seconds(&mut self, seconds: f64) {
384 0 : self.flush_wal_seconds += seconds;
385 0 : FLUSH_WAL_SECONDS.observe(seconds);
386 0 : }
387 : }
388 :
389 : /// Accepts async function that returns empty anyhow result, and returns the duration of its execution.
390 0 : pub async fn time_io_closure<E: Into<anyhow::Error>>(
391 0 : closure: impl Future<Output = Result<(), E>>,
392 0 : ) -> Result<f64> {
393 0 : let start = std::time::Instant::now();
394 0 : closure.await.map_err(|e| e.into())?;
395 0 : Ok(start.elapsed().as_secs_f64())
396 0 : }
397 :
398 : /// Metrics for a single timeline.
399 : #[derive(Clone)]
400 : pub struct FullTimelineInfo {
401 : pub ttid: TenantTimelineId,
402 : pub ps_feedback_count: u64,
403 : pub last_ps_feedback: PageserverFeedback,
404 : pub wal_backup_active: bool,
405 : pub timeline_is_active: bool,
406 : pub num_computes: u32,
407 : pub last_removed_segno: XLogSegNo,
408 :
409 : pub epoch_start_lsn: Lsn,
410 : pub mem_state: TimelineMemState,
411 : pub persisted_state: TimelinePersistentState,
412 :
413 : pub flush_lsn: Lsn,
414 :
415 : pub wal_storage: WalStorageMetrics,
416 : }
417 :
418 : /// Collects metrics for all active timelines.
419 : pub struct TimelineCollector {
420 : descs: Vec<Desc>,
421 : commit_lsn: GenericGaugeVec<AtomicU64>,
422 : backup_lsn: GenericGaugeVec<AtomicU64>,
423 : flush_lsn: GenericGaugeVec<AtomicU64>,
424 : epoch_start_lsn: GenericGaugeVec<AtomicU64>,
425 : peer_horizon_lsn: GenericGaugeVec<AtomicU64>,
426 : remote_consistent_lsn: GenericGaugeVec<AtomicU64>,
427 : ps_last_received_lsn: GenericGaugeVec<AtomicU64>,
428 : feedback_last_time_seconds: GenericGaugeVec<AtomicU64>,
429 : ps_feedback_count: GenericGaugeVec<AtomicU64>,
430 : timeline_active: GenericGaugeVec<AtomicU64>,
431 : wal_backup_active: GenericGaugeVec<AtomicU64>,
432 : connected_computes: IntGaugeVec,
433 : disk_usage: GenericGaugeVec<AtomicU64>,
434 : acceptor_term: GenericGaugeVec<AtomicU64>,
435 : written_wal_bytes: GenericGaugeVec<AtomicU64>,
436 : written_wal_seconds: GaugeVec,
437 : flushed_wal_seconds: GaugeVec,
438 : collect_timeline_metrics: Gauge,
439 : timelines_count: IntGauge,
440 : active_timelines_count: IntGauge,
441 : }
442 :
443 : impl Default for TimelineCollector {
444 0 : fn default() -> Self {
445 0 : Self::new()
446 0 : }
447 : }
448 :
449 : impl TimelineCollector {
450 0 : pub fn new() -> TimelineCollector {
451 0 : let mut descs = Vec::new();
452 0 :
453 0 : let commit_lsn = GenericGaugeVec::new(
454 0 : Opts::new(
455 0 : "safekeeper_commit_lsn",
456 0 : "Current commit_lsn (not necessarily persisted to disk), grouped by timeline",
457 0 : ),
458 0 : &["tenant_id", "timeline_id"],
459 0 : )
460 0 : .unwrap();
461 0 : descs.extend(commit_lsn.desc().into_iter().cloned());
462 0 :
463 0 : let backup_lsn = GenericGaugeVec::new(
464 0 : Opts::new(
465 0 : "safekeeper_backup_lsn",
466 0 : "Current backup_lsn, up to which WAL is backed up, grouped by timeline",
467 0 : ),
468 0 : &["tenant_id", "timeline_id"],
469 0 : )
470 0 : .unwrap();
471 0 : descs.extend(backup_lsn.desc().into_iter().cloned());
472 0 :
473 0 : let flush_lsn = GenericGaugeVec::new(
474 0 : Opts::new(
475 0 : "safekeeper_flush_lsn",
476 0 : "Current flush_lsn, grouped by timeline",
477 0 : ),
478 0 : &["tenant_id", "timeline_id"],
479 0 : )
480 0 : .unwrap();
481 0 : descs.extend(flush_lsn.desc().into_iter().cloned());
482 0 :
483 0 : let epoch_start_lsn = GenericGaugeVec::new(
484 0 : Opts::new(
485 0 : "safekeeper_epoch_start_lsn",
486 0 : "Point since which compute generates new WAL in the current consensus term",
487 0 : ),
488 0 : &["tenant_id", "timeline_id"],
489 0 : )
490 0 : .unwrap();
491 0 : descs.extend(epoch_start_lsn.desc().into_iter().cloned());
492 0 :
493 0 : let peer_horizon_lsn = GenericGaugeVec::new(
494 0 : Opts::new(
495 0 : "safekeeper_peer_horizon_lsn",
496 0 : "LSN of the most lagging safekeeper",
497 0 : ),
498 0 : &["tenant_id", "timeline_id"],
499 0 : )
500 0 : .unwrap();
501 0 : descs.extend(peer_horizon_lsn.desc().into_iter().cloned());
502 0 :
503 0 : let remote_consistent_lsn = GenericGaugeVec::new(
504 0 : Opts::new(
505 0 : "safekeeper_remote_consistent_lsn",
506 0 : "LSN which is persisted to the remote storage in pageserver",
507 0 : ),
508 0 : &["tenant_id", "timeline_id"],
509 0 : )
510 0 : .unwrap();
511 0 : descs.extend(remote_consistent_lsn.desc().into_iter().cloned());
512 0 :
513 0 : let ps_last_received_lsn = GenericGaugeVec::new(
514 0 : Opts::new(
515 0 : "safekeeper_ps_last_received_lsn",
516 0 : "Last LSN received by the pageserver, acknowledged in the feedback",
517 0 : ),
518 0 : &["tenant_id", "timeline_id"],
519 0 : )
520 0 : .unwrap();
521 0 : descs.extend(ps_last_received_lsn.desc().into_iter().cloned());
522 0 :
523 0 : let feedback_last_time_seconds = GenericGaugeVec::new(
524 0 : Opts::new(
525 0 : "safekeeper_feedback_last_time_seconds",
526 0 : "Timestamp of the last feedback from the pageserver",
527 0 : ),
528 0 : &["tenant_id", "timeline_id"],
529 0 : )
530 0 : .unwrap();
531 0 : descs.extend(feedback_last_time_seconds.desc().into_iter().cloned());
532 0 :
533 0 : let ps_feedback_count = GenericGaugeVec::new(
534 0 : Opts::new(
535 0 : "safekeeper_ps_feedback_count_total",
536 0 : "Number of feedbacks received from the pageserver",
537 0 : ),
538 0 : &["tenant_id", "timeline_id"],
539 0 : )
540 0 : .unwrap();
541 0 :
542 0 : let timeline_active = GenericGaugeVec::new(
543 0 : Opts::new(
544 0 : "safekeeper_timeline_active",
545 0 : "Reports 1 for active timelines, 0 for inactive",
546 0 : ),
547 0 : &["tenant_id", "timeline_id"],
548 0 : )
549 0 : .unwrap();
550 0 : descs.extend(timeline_active.desc().into_iter().cloned());
551 0 :
552 0 : let wal_backup_active = GenericGaugeVec::new(
553 0 : Opts::new(
554 0 : "safekeeper_wal_backup_active",
555 0 : "Reports 1 for timelines with active WAL backup, 0 otherwise",
556 0 : ),
557 0 : &["tenant_id", "timeline_id"],
558 0 : )
559 0 : .unwrap();
560 0 : descs.extend(wal_backup_active.desc().into_iter().cloned());
561 0 :
562 0 : let connected_computes = IntGaugeVec::new(
563 0 : Opts::new(
564 0 : "safekeeper_connected_computes",
565 0 : "Number of active compute connections",
566 0 : ),
567 0 : &["tenant_id", "timeline_id"],
568 0 : )
569 0 : .unwrap();
570 0 : descs.extend(connected_computes.desc().into_iter().cloned());
571 0 :
572 0 : let disk_usage = GenericGaugeVec::new(
573 0 : Opts::new(
574 0 : "safekeeper_disk_usage_bytes",
575 0 : "Estimated disk space used to store WAL segments",
576 0 : ),
577 0 : &["tenant_id", "timeline_id"],
578 0 : )
579 0 : .unwrap();
580 0 : descs.extend(disk_usage.desc().into_iter().cloned());
581 0 :
582 0 : let acceptor_term = GenericGaugeVec::new(
583 0 : Opts::new("safekeeper_acceptor_term", "Current consensus term"),
584 0 : &["tenant_id", "timeline_id"],
585 0 : )
586 0 : .unwrap();
587 0 : descs.extend(acceptor_term.desc().into_iter().cloned());
588 0 :
589 0 : let written_wal_bytes = GenericGaugeVec::new(
590 0 : Opts::new(
591 0 : "safekeeper_written_wal_bytes_total",
592 0 : "Number of WAL bytes written to disk, grouped by timeline",
593 0 : ),
594 0 : &["tenant_id", "timeline_id"],
595 0 : )
596 0 : .unwrap();
597 0 : descs.extend(written_wal_bytes.desc().into_iter().cloned());
598 0 :
599 0 : let written_wal_seconds = GaugeVec::new(
600 0 : Opts::new(
601 0 : "safekeeper_written_wal_seconds_total",
602 0 : "Total time spent in write(2) writing WAL to disk, grouped by timeline",
603 0 : ),
604 0 : &["tenant_id", "timeline_id"],
605 0 : )
606 0 : .unwrap();
607 0 : descs.extend(written_wal_seconds.desc().into_iter().cloned());
608 0 :
609 0 : let flushed_wal_seconds = GaugeVec::new(
610 0 : Opts::new(
611 0 : "safekeeper_flushed_wal_seconds_total",
612 0 : "Total time spent in fsync(2) flushing WAL to disk, grouped by timeline",
613 0 : ),
614 0 : &["tenant_id", "timeline_id"],
615 0 : )
616 0 : .unwrap();
617 0 : descs.extend(flushed_wal_seconds.desc().into_iter().cloned());
618 0 :
619 0 : let collect_timeline_metrics = Gauge::new(
620 0 : "safekeeper_collect_timeline_metrics_seconds",
621 0 : "Time spent collecting timeline metrics, including obtaining mutex lock for all timelines",
622 0 : )
623 0 : .unwrap();
624 0 : descs.extend(collect_timeline_metrics.desc().into_iter().cloned());
625 0 :
626 0 : let timelines_count = IntGauge::new(
627 0 : "safekeeper_timelines",
628 0 : "Total number of timelines loaded in-memory",
629 0 : )
630 0 : .unwrap();
631 0 : descs.extend(timelines_count.desc().into_iter().cloned());
632 0 :
633 0 : let active_timelines_count = IntGauge::new(
634 0 : "safekeeper_active_timelines",
635 0 : "Total number of active timelines",
636 0 : )
637 0 : .unwrap();
638 0 : descs.extend(active_timelines_count.desc().into_iter().cloned());
639 0 :
640 0 : TimelineCollector {
641 0 : descs,
642 0 : commit_lsn,
643 0 : backup_lsn,
644 0 : flush_lsn,
645 0 : epoch_start_lsn,
646 0 : peer_horizon_lsn,
647 0 : remote_consistent_lsn,
648 0 : ps_last_received_lsn,
649 0 : feedback_last_time_seconds,
650 0 : ps_feedback_count,
651 0 : timeline_active,
652 0 : wal_backup_active,
653 0 : connected_computes,
654 0 : disk_usage,
655 0 : acceptor_term,
656 0 : written_wal_bytes,
657 0 : written_wal_seconds,
658 0 : flushed_wal_seconds,
659 0 : collect_timeline_metrics,
660 0 : timelines_count,
661 0 : active_timelines_count,
662 0 : }
663 0 : }
664 : }
665 :
666 : impl Collector for TimelineCollector {
667 0 : fn desc(&self) -> Vec<&Desc> {
668 0 : self.descs.iter().collect()
669 0 : }
670 :
671 0 : fn collect(&self) -> Vec<MetricFamily> {
672 0 : let start_collecting = Instant::now();
673 0 :
674 0 : // reset all metrics to clean up inactive timelines
675 0 : self.commit_lsn.reset();
676 0 : self.backup_lsn.reset();
677 0 : self.flush_lsn.reset();
678 0 : self.epoch_start_lsn.reset();
679 0 : self.peer_horizon_lsn.reset();
680 0 : self.remote_consistent_lsn.reset();
681 0 : self.ps_last_received_lsn.reset();
682 0 : self.feedback_last_time_seconds.reset();
683 0 : self.ps_feedback_count.reset();
684 0 : self.timeline_active.reset();
685 0 : self.wal_backup_active.reset();
686 0 : self.connected_computes.reset();
687 0 : self.disk_usage.reset();
688 0 : self.acceptor_term.reset();
689 0 : self.written_wal_bytes.reset();
690 0 : self.written_wal_seconds.reset();
691 0 : self.flushed_wal_seconds.reset();
692 0 :
693 0 : let timelines_count = GlobalTimelines::get_all().len();
694 0 : let mut active_timelines_count = 0;
695 0 :
696 0 : // Prometheus Collector is sync, and data is stored under async lock. To
697 0 : // bridge the gap with a crutch, collect data in spawned thread with
698 0 : // local tokio runtime.
699 0 : let infos = std::thread::spawn(|| {
700 0 : let rt = tokio::runtime::Builder::new_current_thread()
701 0 : .build()
702 0 : .expect("failed to create rt");
703 0 : rt.block_on(collect_timeline_metrics())
704 0 : })
705 0 : .join()
706 0 : .expect("collect_timeline_metrics thread panicked");
707 :
708 0 : for tli in &infos {
709 0 : let tenant_id = tli.ttid.tenant_id.to_string();
710 0 : let timeline_id = tli.ttid.timeline_id.to_string();
711 0 : let labels = &[tenant_id.as_str(), timeline_id.as_str()];
712 0 :
713 0 : if tli.timeline_is_active {
714 0 : active_timelines_count += 1;
715 0 : }
716 :
717 0 : self.commit_lsn
718 0 : .with_label_values(labels)
719 0 : .set(tli.mem_state.commit_lsn.into());
720 0 : self.backup_lsn
721 0 : .with_label_values(labels)
722 0 : .set(tli.mem_state.backup_lsn.into());
723 0 : self.flush_lsn
724 0 : .with_label_values(labels)
725 0 : .set(tli.flush_lsn.into());
726 0 : self.epoch_start_lsn
727 0 : .with_label_values(labels)
728 0 : .set(tli.epoch_start_lsn.into());
729 0 : self.peer_horizon_lsn
730 0 : .with_label_values(labels)
731 0 : .set(tli.mem_state.peer_horizon_lsn.into());
732 0 : self.remote_consistent_lsn
733 0 : .with_label_values(labels)
734 0 : .set(tli.mem_state.remote_consistent_lsn.into());
735 0 : self.timeline_active
736 0 : .with_label_values(labels)
737 0 : .set(tli.timeline_is_active as u64);
738 0 : self.wal_backup_active
739 0 : .with_label_values(labels)
740 0 : .set(tli.wal_backup_active as u64);
741 0 : self.connected_computes
742 0 : .with_label_values(labels)
743 0 : .set(tli.num_computes as i64);
744 0 : self.acceptor_term
745 0 : .with_label_values(labels)
746 0 : .set(tli.persisted_state.acceptor_state.term);
747 0 : self.written_wal_bytes
748 0 : .with_label_values(labels)
749 0 : .set(tli.wal_storage.write_wal_bytes);
750 0 : self.written_wal_seconds
751 0 : .with_label_values(labels)
752 0 : .set(tli.wal_storage.write_wal_seconds);
753 0 : self.flushed_wal_seconds
754 0 : .with_label_values(labels)
755 0 : .set(tli.wal_storage.flush_wal_seconds);
756 0 :
757 0 : self.ps_last_received_lsn
758 0 : .with_label_values(labels)
759 0 : .set(tli.last_ps_feedback.last_received_lsn.0);
760 0 : self.ps_feedback_count
761 0 : .with_label_values(labels)
762 0 : .set(tli.ps_feedback_count);
763 0 : if let Ok(unix_time) = tli
764 0 : .last_ps_feedback
765 0 : .replytime
766 0 : .duration_since(SystemTime::UNIX_EPOCH)
767 0 : {
768 0 : self.feedback_last_time_seconds
769 0 : .with_label_values(labels)
770 0 : .set(unix_time.as_secs());
771 0 : }
772 :
773 0 : if tli.last_removed_segno != 0 {
774 0 : let segno_count = tli
775 0 : .flush_lsn
776 0 : .segment_number(tli.persisted_state.server.wal_seg_size as usize)
777 0 : - tli.last_removed_segno;
778 0 : let disk_usage_bytes = segno_count * tli.persisted_state.server.wal_seg_size as u64;
779 0 : self.disk_usage
780 0 : .with_label_values(labels)
781 0 : .set(disk_usage_bytes);
782 0 : }
783 : }
784 :
785 : // collect MetricFamilys.
786 0 : let mut mfs = Vec::new();
787 0 : mfs.extend(self.commit_lsn.collect());
788 0 : mfs.extend(self.backup_lsn.collect());
789 0 : mfs.extend(self.flush_lsn.collect());
790 0 : mfs.extend(self.epoch_start_lsn.collect());
791 0 : mfs.extend(self.peer_horizon_lsn.collect());
792 0 : mfs.extend(self.remote_consistent_lsn.collect());
793 0 : mfs.extend(self.ps_last_received_lsn.collect());
794 0 : mfs.extend(self.feedback_last_time_seconds.collect());
795 0 : mfs.extend(self.ps_feedback_count.collect());
796 0 : mfs.extend(self.timeline_active.collect());
797 0 : mfs.extend(self.wal_backup_active.collect());
798 0 : mfs.extend(self.connected_computes.collect());
799 0 : mfs.extend(self.disk_usage.collect());
800 0 : mfs.extend(self.acceptor_term.collect());
801 0 : mfs.extend(self.written_wal_bytes.collect());
802 0 : mfs.extend(self.written_wal_seconds.collect());
803 0 : mfs.extend(self.flushed_wal_seconds.collect());
804 0 :
805 0 : // report time it took to collect all info
806 0 : let elapsed = start_collecting.elapsed().as_secs_f64();
807 0 : self.collect_timeline_metrics.set(elapsed);
808 0 : mfs.extend(self.collect_timeline_metrics.collect());
809 0 :
810 0 : // report total number of timelines
811 0 : self.timelines_count.set(timelines_count as i64);
812 0 : mfs.extend(self.timelines_count.collect());
813 0 :
814 0 : self.active_timelines_count
815 0 : .set(active_timelines_count as i64);
816 0 : mfs.extend(self.active_timelines_count.collect());
817 0 :
818 0 : mfs
819 0 : }
820 : }
821 :
822 0 : async fn collect_timeline_metrics() -> Vec<FullTimelineInfo> {
823 0 : let mut res = vec![];
824 0 : let active_timelines = GlobalTimelines::get_global_broker_active_set().get_all();
825 :
826 0 : for tli in active_timelines {
827 0 : if let Some(info) = tli.info_for_metrics().await {
828 0 : res.push(info);
829 0 : }
830 : }
831 0 : res
832 0 : }
|