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, Gauge, HistogramVec, IntCounter,
16 : 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 : pub const LABEL_UNKNOWN: &str = "unknown";
235 :
236 : /// Labels for traffic metrics.
237 : #[derive(Clone)]
238 : struct ConnectionLabels {
239 : /// Availability zone of the connection origin.
240 : client_az: String,
241 : /// Availability zone of the current safekeeper.
242 : sk_az: String,
243 : /// Client application name.
244 : app_name: String,
245 : }
246 :
247 : impl ConnectionLabels {
248 0 : fn new() -> Self {
249 0 : Self {
250 0 : client_az: LABEL_UNKNOWN.to_string(),
251 0 : sk_az: LABEL_UNKNOWN.to_string(),
252 0 : app_name: LABEL_UNKNOWN.to_string(),
253 0 : }
254 0 : }
255 :
256 0 : fn build_metrics(
257 0 : &self,
258 0 : ) -> (
259 0 : GenericCounter<metrics::core::AtomicU64>,
260 0 : GenericCounter<metrics::core::AtomicU64>,
261 0 : ) {
262 0 : let same_az = match (self.client_az.as_str(), self.sk_az.as_str()) {
263 0 : (LABEL_UNKNOWN, _) | (_, LABEL_UNKNOWN) => LABEL_UNKNOWN,
264 0 : (client_az, sk_az) => {
265 0 : if client_az == sk_az {
266 0 : "true"
267 : } else {
268 0 : "false"
269 : }
270 : }
271 : };
272 :
273 0 : let read = PG_IO_BYTES.with_label_values(&[
274 0 : &self.client_az,
275 0 : &self.sk_az,
276 0 : &self.app_name,
277 0 : "read",
278 0 : same_az,
279 0 : ]);
280 0 : let write = PG_IO_BYTES.with_label_values(&[
281 0 : &self.client_az,
282 0 : &self.sk_az,
283 0 : &self.app_name,
284 0 : "write",
285 0 : same_az,
286 0 : ]);
287 0 : (read, write)
288 0 : }
289 : }
290 :
291 : struct TrafficMetricsState {
292 : /// Labels for traffic metrics.
293 : labels: ConnectionLabels,
294 : /// Total bytes read from this connection.
295 : read: GenericCounter<metrics::core::AtomicU64>,
296 : /// Total bytes written to this connection.
297 : write: GenericCounter<metrics::core::AtomicU64>,
298 : }
299 :
300 : /// Metrics for measuring traffic (r/w bytes) in a single PostgreSQL connection.
301 : #[derive(Clone)]
302 : pub struct TrafficMetrics {
303 : state: Arc<RwLock<TrafficMetricsState>>,
304 : }
305 :
306 : impl Default for TrafficMetrics {
307 0 : fn default() -> Self {
308 0 : Self::new()
309 0 : }
310 : }
311 :
312 : impl TrafficMetrics {
313 0 : pub fn new() -> Self {
314 0 : let labels = ConnectionLabels::new();
315 0 : let (read, write) = labels.build_metrics();
316 0 : let state = TrafficMetricsState {
317 0 : labels,
318 0 : read,
319 0 : write,
320 0 : };
321 0 : Self {
322 0 : state: Arc::new(RwLock::new(state)),
323 0 : }
324 0 : }
325 :
326 0 : pub fn set_client_az(&self, value: &str) {
327 0 : let mut state = self.state.write().unwrap();
328 0 : state.labels.client_az = value.to_string();
329 0 : (state.read, state.write) = state.labels.build_metrics();
330 0 : }
331 :
332 0 : pub fn set_sk_az(&self, value: &str) {
333 0 : let mut state = self.state.write().unwrap();
334 0 : state.labels.sk_az = value.to_string();
335 0 : (state.read, state.write) = state.labels.build_metrics();
336 0 : }
337 :
338 0 : pub fn set_app_name(&self, value: &str) {
339 0 : let mut state = self.state.write().unwrap();
340 0 : state.labels.app_name = value.to_string();
341 0 : (state.read, state.write) = state.labels.build_metrics();
342 0 : }
343 :
344 0 : pub fn observe_read(&self, cnt: usize) {
345 0 : self.state.read().unwrap().read.inc_by(cnt as u64)
346 0 : }
347 :
348 0 : pub fn observe_write(&self, cnt: usize) {
349 0 : self.state.read().unwrap().write.inc_by(cnt as u64)
350 0 : }
351 : }
352 :
353 : /// Metrics for WalStorage in a single timeline.
354 : #[derive(Clone, Default)]
355 : pub struct WalStorageMetrics {
356 : /// How much bytes were written in total.
357 : write_wal_bytes: u64,
358 : /// How much time spent writing WAL to disk, waiting for write(2).
359 : write_wal_seconds: f64,
360 : /// How much time spent syncing WAL to disk, waiting for fsync(2).
361 : flush_wal_seconds: f64,
362 : }
363 :
364 : impl WalStorageMetrics {
365 0 : pub fn observe_write_bytes(&mut self, bytes: usize) {
366 0 : self.write_wal_bytes += bytes as u64;
367 0 : WRITE_WAL_BYTES.observe(bytes as f64);
368 0 : }
369 :
370 0 : pub fn observe_write_seconds(&mut self, seconds: f64) {
371 0 : self.write_wal_seconds += seconds;
372 0 : WRITE_WAL_SECONDS.observe(seconds);
373 0 : }
374 :
375 0 : pub fn observe_flush_seconds(&mut self, seconds: f64) {
376 0 : self.flush_wal_seconds += seconds;
377 0 : FLUSH_WAL_SECONDS.observe(seconds);
378 0 : }
379 : }
380 :
381 : /// Accepts async function that returns empty anyhow result, and returns the duration of its execution.
382 0 : pub async fn time_io_closure<E: Into<anyhow::Error>>(
383 0 : closure: impl Future<Output = Result<(), E>>,
384 0 : ) -> Result<f64> {
385 0 : let start = std::time::Instant::now();
386 0 : closure.await.map_err(|e| e.into())?;
387 0 : Ok(start.elapsed().as_secs_f64())
388 0 : }
389 :
390 : /// Metrics for a single timeline.
391 : #[derive(Clone)]
392 : pub struct FullTimelineInfo {
393 : pub ttid: TenantTimelineId,
394 : pub ps_feedback_count: u64,
395 : pub last_ps_feedback: PageserverFeedback,
396 : pub wal_backup_active: bool,
397 : pub timeline_is_active: bool,
398 : pub num_computes: u32,
399 : pub last_removed_segno: XLogSegNo,
400 :
401 : pub epoch_start_lsn: Lsn,
402 : pub mem_state: TimelineMemState,
403 : pub persisted_state: TimelinePersistentState,
404 :
405 : pub flush_lsn: Lsn,
406 :
407 : pub wal_storage: WalStorageMetrics,
408 : }
409 :
410 : /// Collects metrics for all active timelines.
411 : pub struct TimelineCollector {
412 : descs: Vec<Desc>,
413 : commit_lsn: GenericGaugeVec<AtomicU64>,
414 : backup_lsn: GenericGaugeVec<AtomicU64>,
415 : flush_lsn: GenericGaugeVec<AtomicU64>,
416 : epoch_start_lsn: GenericGaugeVec<AtomicU64>,
417 : peer_horizon_lsn: GenericGaugeVec<AtomicU64>,
418 : remote_consistent_lsn: GenericGaugeVec<AtomicU64>,
419 : ps_last_received_lsn: GenericGaugeVec<AtomicU64>,
420 : feedback_last_time_seconds: GenericGaugeVec<AtomicU64>,
421 : ps_feedback_count: GenericGaugeVec<AtomicU64>,
422 : timeline_active: GenericGaugeVec<AtomicU64>,
423 : wal_backup_active: GenericGaugeVec<AtomicU64>,
424 : connected_computes: IntGaugeVec,
425 : disk_usage: GenericGaugeVec<AtomicU64>,
426 : acceptor_term: GenericGaugeVec<AtomicU64>,
427 : written_wal_bytes: GenericGaugeVec<AtomicU64>,
428 : written_wal_seconds: GaugeVec,
429 : flushed_wal_seconds: GaugeVec,
430 : collect_timeline_metrics: Gauge,
431 : timelines_count: IntGauge,
432 : active_timelines_count: IntGauge,
433 : }
434 :
435 : impl Default for TimelineCollector {
436 0 : fn default() -> Self {
437 0 : Self::new()
438 0 : }
439 : }
440 :
441 : impl TimelineCollector {
442 0 : pub fn new() -> TimelineCollector {
443 0 : let mut descs = Vec::new();
444 0 :
445 0 : let commit_lsn = GenericGaugeVec::new(
446 0 : Opts::new(
447 0 : "safekeeper_commit_lsn",
448 0 : "Current commit_lsn (not necessarily persisted to disk), grouped by timeline",
449 0 : ),
450 0 : &["tenant_id", "timeline_id"],
451 0 : )
452 0 : .unwrap();
453 0 : descs.extend(commit_lsn.desc().into_iter().cloned());
454 0 :
455 0 : let backup_lsn = GenericGaugeVec::new(
456 0 : Opts::new(
457 0 : "safekeeper_backup_lsn",
458 0 : "Current backup_lsn, up to which WAL is backed up, grouped by timeline",
459 0 : ),
460 0 : &["tenant_id", "timeline_id"],
461 0 : )
462 0 : .unwrap();
463 0 : descs.extend(backup_lsn.desc().into_iter().cloned());
464 0 :
465 0 : let flush_lsn = GenericGaugeVec::new(
466 0 : Opts::new(
467 0 : "safekeeper_flush_lsn",
468 0 : "Current flush_lsn, grouped by timeline",
469 0 : ),
470 0 : &["tenant_id", "timeline_id"],
471 0 : )
472 0 : .unwrap();
473 0 : descs.extend(flush_lsn.desc().into_iter().cloned());
474 0 :
475 0 : let epoch_start_lsn = GenericGaugeVec::new(
476 0 : Opts::new(
477 0 : "safekeeper_epoch_start_lsn",
478 0 : "Point since which compute generates new WAL in the current consensus term",
479 0 : ),
480 0 : &["tenant_id", "timeline_id"],
481 0 : )
482 0 : .unwrap();
483 0 : descs.extend(epoch_start_lsn.desc().into_iter().cloned());
484 0 :
485 0 : let peer_horizon_lsn = GenericGaugeVec::new(
486 0 : Opts::new(
487 0 : "safekeeper_peer_horizon_lsn",
488 0 : "LSN of the most lagging safekeeper",
489 0 : ),
490 0 : &["tenant_id", "timeline_id"],
491 0 : )
492 0 : .unwrap();
493 0 : descs.extend(peer_horizon_lsn.desc().into_iter().cloned());
494 0 :
495 0 : let remote_consistent_lsn = GenericGaugeVec::new(
496 0 : Opts::new(
497 0 : "safekeeper_remote_consistent_lsn",
498 0 : "LSN which is persisted to the remote storage in pageserver",
499 0 : ),
500 0 : &["tenant_id", "timeline_id"],
501 0 : )
502 0 : .unwrap();
503 0 : descs.extend(remote_consistent_lsn.desc().into_iter().cloned());
504 0 :
505 0 : let ps_last_received_lsn = GenericGaugeVec::new(
506 0 : Opts::new(
507 0 : "safekeeper_ps_last_received_lsn",
508 0 : "Last LSN received by the pageserver, acknowledged in the feedback",
509 0 : ),
510 0 : &["tenant_id", "timeline_id"],
511 0 : )
512 0 : .unwrap();
513 0 : descs.extend(ps_last_received_lsn.desc().into_iter().cloned());
514 0 :
515 0 : let feedback_last_time_seconds = GenericGaugeVec::new(
516 0 : Opts::new(
517 0 : "safekeeper_feedback_last_time_seconds",
518 0 : "Timestamp of the last feedback from the pageserver",
519 0 : ),
520 0 : &["tenant_id", "timeline_id"],
521 0 : )
522 0 : .unwrap();
523 0 : descs.extend(feedback_last_time_seconds.desc().into_iter().cloned());
524 0 :
525 0 : let ps_feedback_count = GenericGaugeVec::new(
526 0 : Opts::new(
527 0 : "safekeeper_ps_feedback_count_total",
528 0 : "Number of feedbacks received from the pageserver",
529 0 : ),
530 0 : &["tenant_id", "timeline_id"],
531 0 : )
532 0 : .unwrap();
533 0 :
534 0 : let timeline_active = GenericGaugeVec::new(
535 0 : Opts::new(
536 0 : "safekeeper_timeline_active",
537 0 : "Reports 1 for active timelines, 0 for inactive",
538 0 : ),
539 0 : &["tenant_id", "timeline_id"],
540 0 : )
541 0 : .unwrap();
542 0 : descs.extend(timeline_active.desc().into_iter().cloned());
543 0 :
544 0 : let wal_backup_active = GenericGaugeVec::new(
545 0 : Opts::new(
546 0 : "safekeeper_wal_backup_active",
547 0 : "Reports 1 for timelines with active WAL backup, 0 otherwise",
548 0 : ),
549 0 : &["tenant_id", "timeline_id"],
550 0 : )
551 0 : .unwrap();
552 0 : descs.extend(wal_backup_active.desc().into_iter().cloned());
553 0 :
554 0 : let connected_computes = IntGaugeVec::new(
555 0 : Opts::new(
556 0 : "safekeeper_connected_computes",
557 0 : "Number of active compute connections",
558 0 : ),
559 0 : &["tenant_id", "timeline_id"],
560 0 : )
561 0 : .unwrap();
562 0 : descs.extend(connected_computes.desc().into_iter().cloned());
563 0 :
564 0 : let disk_usage = GenericGaugeVec::new(
565 0 : Opts::new(
566 0 : "safekeeper_disk_usage_bytes",
567 0 : "Estimated disk space used to store WAL segments",
568 0 : ),
569 0 : &["tenant_id", "timeline_id"],
570 0 : )
571 0 : .unwrap();
572 0 : descs.extend(disk_usage.desc().into_iter().cloned());
573 0 :
574 0 : let acceptor_term = GenericGaugeVec::new(
575 0 : Opts::new("safekeeper_acceptor_term", "Current consensus term"),
576 0 : &["tenant_id", "timeline_id"],
577 0 : )
578 0 : .unwrap();
579 0 : descs.extend(acceptor_term.desc().into_iter().cloned());
580 0 :
581 0 : let written_wal_bytes = GenericGaugeVec::new(
582 0 : Opts::new(
583 0 : "safekeeper_written_wal_bytes_total",
584 0 : "Number of WAL bytes written to disk, grouped by timeline",
585 0 : ),
586 0 : &["tenant_id", "timeline_id"],
587 0 : )
588 0 : .unwrap();
589 0 : descs.extend(written_wal_bytes.desc().into_iter().cloned());
590 0 :
591 0 : let written_wal_seconds = GaugeVec::new(
592 0 : Opts::new(
593 0 : "safekeeper_written_wal_seconds_total",
594 0 : "Total time spent in write(2) writing WAL to disk, grouped by timeline",
595 0 : ),
596 0 : &["tenant_id", "timeline_id"],
597 0 : )
598 0 : .unwrap();
599 0 : descs.extend(written_wal_seconds.desc().into_iter().cloned());
600 0 :
601 0 : let flushed_wal_seconds = GaugeVec::new(
602 0 : Opts::new(
603 0 : "safekeeper_flushed_wal_seconds_total",
604 0 : "Total time spent in fsync(2) flushing WAL to disk, grouped by timeline",
605 0 : ),
606 0 : &["tenant_id", "timeline_id"],
607 0 : )
608 0 : .unwrap();
609 0 : descs.extend(flushed_wal_seconds.desc().into_iter().cloned());
610 0 :
611 0 : let collect_timeline_metrics = Gauge::new(
612 0 : "safekeeper_collect_timeline_metrics_seconds",
613 0 : "Time spent collecting timeline metrics, including obtaining mutex lock for all timelines",
614 0 : )
615 0 : .unwrap();
616 0 : descs.extend(collect_timeline_metrics.desc().into_iter().cloned());
617 0 :
618 0 : let timelines_count = IntGauge::new(
619 0 : "safekeeper_timelines",
620 0 : "Total number of timelines loaded in-memory",
621 0 : )
622 0 : .unwrap();
623 0 : descs.extend(timelines_count.desc().into_iter().cloned());
624 0 :
625 0 : let active_timelines_count = IntGauge::new(
626 0 : "safekeeper_active_timelines",
627 0 : "Total number of active timelines",
628 0 : )
629 0 : .unwrap();
630 0 : descs.extend(active_timelines_count.desc().into_iter().cloned());
631 0 :
632 0 : TimelineCollector {
633 0 : descs,
634 0 : commit_lsn,
635 0 : backup_lsn,
636 0 : flush_lsn,
637 0 : epoch_start_lsn,
638 0 : peer_horizon_lsn,
639 0 : remote_consistent_lsn,
640 0 : ps_last_received_lsn,
641 0 : feedback_last_time_seconds,
642 0 : ps_feedback_count,
643 0 : timeline_active,
644 0 : wal_backup_active,
645 0 : connected_computes,
646 0 : disk_usage,
647 0 : acceptor_term,
648 0 : written_wal_bytes,
649 0 : written_wal_seconds,
650 0 : flushed_wal_seconds,
651 0 : collect_timeline_metrics,
652 0 : timelines_count,
653 0 : active_timelines_count,
654 0 : }
655 0 : }
656 : }
657 :
658 : impl Collector for TimelineCollector {
659 0 : fn desc(&self) -> Vec<&Desc> {
660 0 : self.descs.iter().collect()
661 0 : }
662 :
663 0 : fn collect(&self) -> Vec<MetricFamily> {
664 0 : let start_collecting = Instant::now();
665 0 :
666 0 : // reset all metrics to clean up inactive timelines
667 0 : self.commit_lsn.reset();
668 0 : self.backup_lsn.reset();
669 0 : self.flush_lsn.reset();
670 0 : self.epoch_start_lsn.reset();
671 0 : self.peer_horizon_lsn.reset();
672 0 : self.remote_consistent_lsn.reset();
673 0 : self.ps_last_received_lsn.reset();
674 0 : self.feedback_last_time_seconds.reset();
675 0 : self.ps_feedback_count.reset();
676 0 : self.timeline_active.reset();
677 0 : self.wal_backup_active.reset();
678 0 : self.connected_computes.reset();
679 0 : self.disk_usage.reset();
680 0 : self.acceptor_term.reset();
681 0 : self.written_wal_bytes.reset();
682 0 : self.written_wal_seconds.reset();
683 0 : self.flushed_wal_seconds.reset();
684 0 :
685 0 : let timelines_count = GlobalTimelines::get_all().len();
686 0 : let mut active_timelines_count = 0;
687 0 :
688 0 : // Prometheus Collector is sync, and data is stored under async lock. To
689 0 : // bridge the gap with a crutch, collect data in spawned thread with
690 0 : // local tokio runtime.
691 0 : let infos = std::thread::spawn(|| {
692 0 : let rt = tokio::runtime::Builder::new_current_thread()
693 0 : .build()
694 0 : .expect("failed to create rt");
695 0 : rt.block_on(collect_timeline_metrics())
696 0 : })
697 0 : .join()
698 0 : .expect("collect_timeline_metrics thread panicked");
699 :
700 0 : for tli in &infos {
701 0 : let tenant_id = tli.ttid.tenant_id.to_string();
702 0 : let timeline_id = tli.ttid.timeline_id.to_string();
703 0 : let labels = &[tenant_id.as_str(), timeline_id.as_str()];
704 0 :
705 0 : if tli.timeline_is_active {
706 0 : active_timelines_count += 1;
707 0 : }
708 :
709 0 : self.commit_lsn
710 0 : .with_label_values(labels)
711 0 : .set(tli.mem_state.commit_lsn.into());
712 0 : self.backup_lsn
713 0 : .with_label_values(labels)
714 0 : .set(tli.mem_state.backup_lsn.into());
715 0 : self.flush_lsn
716 0 : .with_label_values(labels)
717 0 : .set(tli.flush_lsn.into());
718 0 : self.epoch_start_lsn
719 0 : .with_label_values(labels)
720 0 : .set(tli.epoch_start_lsn.into());
721 0 : self.peer_horizon_lsn
722 0 : .with_label_values(labels)
723 0 : .set(tli.mem_state.peer_horizon_lsn.into());
724 0 : self.remote_consistent_lsn
725 0 : .with_label_values(labels)
726 0 : .set(tli.mem_state.remote_consistent_lsn.into());
727 0 : self.timeline_active
728 0 : .with_label_values(labels)
729 0 : .set(tli.timeline_is_active as u64);
730 0 : self.wal_backup_active
731 0 : .with_label_values(labels)
732 0 : .set(tli.wal_backup_active as u64);
733 0 : self.connected_computes
734 0 : .with_label_values(labels)
735 0 : .set(tli.num_computes as i64);
736 0 : self.acceptor_term
737 0 : .with_label_values(labels)
738 0 : .set(tli.persisted_state.acceptor_state.term);
739 0 : self.written_wal_bytes
740 0 : .with_label_values(labels)
741 0 : .set(tli.wal_storage.write_wal_bytes);
742 0 : self.written_wal_seconds
743 0 : .with_label_values(labels)
744 0 : .set(tli.wal_storage.write_wal_seconds);
745 0 : self.flushed_wal_seconds
746 0 : .with_label_values(labels)
747 0 : .set(tli.wal_storage.flush_wal_seconds);
748 0 :
749 0 : self.ps_last_received_lsn
750 0 : .with_label_values(labels)
751 0 : .set(tli.last_ps_feedback.last_received_lsn.0);
752 0 : self.ps_feedback_count
753 0 : .with_label_values(labels)
754 0 : .set(tli.ps_feedback_count);
755 0 : if let Ok(unix_time) = tli
756 0 : .last_ps_feedback
757 0 : .replytime
758 0 : .duration_since(SystemTime::UNIX_EPOCH)
759 0 : {
760 0 : self.feedback_last_time_seconds
761 0 : .with_label_values(labels)
762 0 : .set(unix_time.as_secs());
763 0 : }
764 :
765 0 : if tli.last_removed_segno != 0 {
766 0 : let segno_count = tli
767 0 : .flush_lsn
768 0 : .segment_number(tli.persisted_state.server.wal_seg_size as usize)
769 0 : - tli.last_removed_segno;
770 0 : let disk_usage_bytes = segno_count * tli.persisted_state.server.wal_seg_size as u64;
771 0 : self.disk_usage
772 0 : .with_label_values(labels)
773 0 : .set(disk_usage_bytes);
774 0 : }
775 : }
776 :
777 : // collect MetricFamilys.
778 0 : let mut mfs = Vec::new();
779 0 : mfs.extend(self.commit_lsn.collect());
780 0 : mfs.extend(self.backup_lsn.collect());
781 0 : mfs.extend(self.flush_lsn.collect());
782 0 : mfs.extend(self.epoch_start_lsn.collect());
783 0 : mfs.extend(self.peer_horizon_lsn.collect());
784 0 : mfs.extend(self.remote_consistent_lsn.collect());
785 0 : mfs.extend(self.ps_last_received_lsn.collect());
786 0 : mfs.extend(self.feedback_last_time_seconds.collect());
787 0 : mfs.extend(self.ps_feedback_count.collect());
788 0 : mfs.extend(self.timeline_active.collect());
789 0 : mfs.extend(self.wal_backup_active.collect());
790 0 : mfs.extend(self.connected_computes.collect());
791 0 : mfs.extend(self.disk_usage.collect());
792 0 : mfs.extend(self.acceptor_term.collect());
793 0 : mfs.extend(self.written_wal_bytes.collect());
794 0 : mfs.extend(self.written_wal_seconds.collect());
795 0 : mfs.extend(self.flushed_wal_seconds.collect());
796 0 :
797 0 : // report time it took to collect all info
798 0 : let elapsed = start_collecting.elapsed().as_secs_f64();
799 0 : self.collect_timeline_metrics.set(elapsed);
800 0 : mfs.extend(self.collect_timeline_metrics.collect());
801 0 :
802 0 : // report total number of timelines
803 0 : self.timelines_count.set(timelines_count as i64);
804 0 : mfs.extend(self.timelines_count.collect());
805 0 :
806 0 : self.active_timelines_count
807 0 : .set(active_timelines_count as i64);
808 0 : mfs.extend(self.active_timelines_count.collect());
809 0 :
810 0 : mfs
811 0 : }
812 : }
813 :
814 0 : async fn collect_timeline_metrics() -> Vec<FullTimelineInfo> {
815 0 : let mut res = vec![];
816 0 : let active_timelines = GlobalTimelines::get_global_broker_active_set().get_all();
817 :
818 0 : for tli in active_timelines {
819 0 : if let Some(info) = tli.info_for_metrics().await {
820 0 : res.push(info);
821 0 : }
822 : }
823 0 : res
824 0 : }
|