-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathmetrics.yaml
More file actions
4542 lines (4470 loc) · 228 KB
/
metrics.yaml
File metadata and controls
4542 lines (4470 loc) · 228 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# The following structure is expected for metrics and preset definitions:
# metrics:
# metric_name:
# init_sql: |-
# CREATE EXTENSION IF NOT EXISTS some_extension;
# CREATE OR REPLACE FUNCTION get_some_stat(OUT some_stat int)
# ...
# sqls:
# 11: |
# select /* pgwatch_generated */
# (extract(epoch from now()) * 1e9)::int8 as epoch_ns,
# ...
# 14: |
# select /* pgwatch_generated */
# (extract(epoch from now()) * 1e9)::int8 as epoch_ns,
# ...
# gauges:
# - '*'
# is_instance_level: true
# node_status: primary
# statement_timeout_seconds: 300
# storage_name: db_stats
metrics:
archiver:
description: >
This metric retrieves key statistics from the PostgreSQL `pg_stat_archiver` view providing insights into the status of WAL file archiving.
It returns the total number of successfully archived files and failed archiving attempts. Additionally, it identifies if the most recent
attempt resulted in a failure and calculates how many seconds have passed since the last failure. The metric only considers data if WAL
archiving is enabled in the system, helping administrators monitor and diagnose issues related to the archiving process.
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
archived_count,
failed_count,
case when coalesce(last_failed_time, '1970-01-01'::timestamptz) > coalesce(last_archived_time, '1970-01-01'::timestamptz) then 1 else 0 end as is_failing_int,
extract(epoch from now() - last_failed_time)::int8 as seconds_since_last_failure
from
pg_stat_archiver
where
current_setting('archive_mode') in ('on', 'always')
gauges:
- is_failing_int
- seconds_since_last_failure
is_instance_level: true
backends:
description: >
This metric gathers detailed information from the PostgreSQL pg_stat_activity view, providing an overview of the database's current session
and activity state. It tracks the total number of client backends, active sessions, idle sessions, sessions waiting on locks, and background workers.
The metric also calculates statistics on blocked sessions, most extended waiting times, average and longest session durations, transaction times,
and query durations. Additionally, it monitors autovacuum worker activity and provides the age of the oldest transaction (measured by xmin).
This metric helps administrators monitor session states, detect bottlenecks, and ensure the system is within its connection limits,
providing visibility into database performance and contention.
sqls:
14: |
with sa_snapshot as (
select * from pg_stat_activity
where pid != pg_backend_pid()
and datname = current_database()
)
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
(select count(*) from sa_snapshot where backend_type = 'client backend') as total,
(select count(*) from pg_stat_activity where pid != pg_backend_pid()) as instance_total,
current_setting('max_connections')::int as max_connections,
(select count(*) from sa_snapshot where backend_type = 'background worker') as background_workers,
(select count(*) from sa_snapshot where state = 'active' and backend_type = 'client backend') as active,
(select count(*) from sa_snapshot where state = 'idle' and backend_type = 'client backend') as idle,
(select count(*) from sa_snapshot where state = 'idle in transaction' and backend_type = 'client backend') as idleintransaction,
(select count(*) from sa_snapshot where wait_event_type in ('LWLock', 'Lock', 'BufferPin') and backend_type = 'client backend') as waiting,
(select coalesce(sum(case when coalesce(array_length(pg_blocking_pids(pid), 1), 0) >= 1 then 1 else 0 end), 0) from sa_snapshot where backend_type = 'client backend' and state = 'active') as blocked,
(select ceil(extract(epoch from max(now() - query_start)))::int from sa_snapshot where wait_event_type in ('LWLock', 'Lock', 'BufferPin') and backend_type = 'client backend') as longest_waiting_seconds,
(select round(avg(abs(extract(epoch from now() - query_start)))::numeric, 3)::float from sa_snapshot where wait_event_type in ('LWLock', 'Lock', 'BufferPin') and backend_type = 'client backend') as avg_waiting_seconds,
(select ceil(extract(epoch from (now() - backend_start)))::int from sa_snapshot where backend_type = 'client backend' order by backend_start limit 1) as longest_session_seconds,
(select round(avg(abs(extract(epoch from now() - backend_start)))::numeric, 3)::float from sa_snapshot where backend_type = 'client backend') as avg_session_seconds,
(select ceil(extract(epoch from (now() - xact_start)))::int from sa_snapshot where xact_start is not null and backend_type = 'client backend' order by xact_start limit 1) as longest_tx_seconds,
(select round(avg(abs(extract(epoch from now() - xact_start)))::numeric, 3)::float from sa_snapshot where xact_start is not null and backend_type = 'client backend') as avg_tx_seconds,
(select ceil(extract(epoch from (now() - xact_start)))::int from sa_snapshot where backend_type = 'autovacuum worker' order by xact_start limit 1) as longest_autovacuum_seconds,
(select ceil(extract(epoch from max(now() - query_start)))::int from sa_snapshot where state = 'active' and backend_type = 'client backend') as longest_query_seconds,
(select round(avg(abs(extract(epoch from now() - query_start)))::numeric, 3)::float from sa_snapshot where state = 'active' and backend_type = 'client backend') as avg_query_seconds,
(select max(age(backend_xmin))::int8 from sa_snapshot) as max_xmin_age_tx,
(select count(*) from sa_snapshot where state = 'active' and backend_type = 'autovacuum worker') as av_workers
gauges:
- '*'
backup_age_pgbackrest:
description: >
This metric retrieves the age of the last successful pgBackRest backup in seconds. It uses the `pgbackrest --output=json info` command to fetch
the backup information and calculates the age based on the current time and the timestamp of the last backup. The metric returns a retcode of 0
on success, along with the age in seconds and a message indicating the status.
Expects pgBackRest is correctly configured on monitored DB and "jq" tool is installed on the DB server.
sqls:
14: |
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
retcode,
backup_age_seconds,
message
from
get_backup_age_pgbackrest()
init_sql: |-
CREATE EXTENSION IF NOT EXISTS plpython3u;
CREATE OR REPLACE FUNCTION get_backup_age_pgbackrest(OUT retcode int, OUT backup_age_seconds int, OUT message text) AS
$$
import time
import json
import subprocess
PGBACKREST_TIMEOUT = 30
def error(message, returncode=1):
return returncode, 1000000, 'Not OK. '+message
pgbackrest_cmd=["pgbackrest", "--output=json", "info"]
try:
p = subprocess.Popen(pgbackrest_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
stdout, stderr = p.communicate(timeout=PGBACKREST_TIMEOUT)
except OSError as e:
return error('Failed to execute pgbackrest: {}'.format(e))
except subprocess.TimeoutExpired:
p.terminate()
try:
p.wait(0.5)
except subprocess.TimeoutExpired:
p.kill()
return error('pgbackrest failed to respond in {} seconds'.format(PGBACKREST_TIMEOUT))
if p.returncode != 0:
return error('Failed on "pgbackrest info" call', returncode=p.returncode)
try:
data = json.loads(stdout)
backup_age_seconds = int(time.time()) - data[0]['backup'][-1]['timestamp']['stop']
return 0, backup_age_seconds, 'OK. Last backup age in seconds: {}'.format(backup_age_seconds)
except (json.JSONDecodeError, KeyError) :
return error('Failed to parse pgbackrest output')
$$ LANGUAGE plpython3u VOLATILE;
ALTER FUNCTION get_backup_age_pgbackrest() SET statement_timeout TO '30s';
GRANT EXECUTE ON FUNCTION get_backup_age_pgbackrest() TO pgwatch;
COMMENT ON FUNCTION get_backup_age_pgbackrest() is 'created for pgwatch';
is_instance_level: true
backup_age_walg:
description: >
Retrieves the age of the last successful WAL-G backup in seconds. It uses the `wal-g backup-list --json` command to fetch
the backup information and calculates the age based on the current time and the timestamp of the last backup.
The metric returns a retcode of 0 on success, along with the age in seconds and a message indicating the status.
Expects .wal-g.json is correctly configured with all necessary credentials and "jq" tool is installed on the DB server.
sqls:
14: |
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
retcode,
backup_age_seconds,
message
from
get_backup_age_walg()
init_sql: |-
CREATE EXTENSION IF NOT EXISTS plpython3u;
CREATE OR REPLACE FUNCTION get_backup_age_walg(OUT retcode int, OUT backup_age_seconds int, OUT message text) AS
$$
import subprocess
retcode=1
backup_age_seconds=1000000
message=''
# get latest wal-g backup timestamp
walg_last_backup_cmd="""wal-g backup-list --json | jq -r '.[0].time'"""
p = subprocess.run(walg_last_backup_cmd, stdout=subprocess.PIPE, encoding='utf-8', shell=True)
if p.returncode != 0:
# plpy.notice("p.stdout: " + str(p.stderr) + str(p.stderr))
return p.returncode, backup_age_seconds, 'Not OK. Failed on wal-g backup-list call'
# plpy.notice("last_tz: " + last_tz)
last_tz=p.stdout.rstrip('\n\r')
# get seconds since last backup from WAL-G timestamp in format '2020-01-22T17:50:51Z'
try:
plan = plpy.prepare("SELECT extract(epoch from now() - $1::timestamptz)::int AS backup_age_seconds;", ["text"])
rv = plpy.execute(plan, [last_tz])
except Exception as e:
return retcode, backup_age_seconds, 'Not OK. Failed to convert WAL-G backup timestamp to seconds'
else:
backup_age_seconds = rv[0]["backup_age_seconds"]
return 0, backup_age_seconds, 'OK. Last backup age in seconds: %s' % backup_age_seconds
$$ LANGUAGE plpython3u VOLATILE;
/* contacting S3 could be laggy depending on location */
ALTER FUNCTION get_backup_age_walg() SET statement_timeout TO '30s';
GRANT EXECUTE ON FUNCTION get_backup_age_walg() TO pgwatch;
COMMENT ON FUNCTION get_backup_age_walg() is 'created for pgwatch';
is_instance_level: true
bgwriter:
description: >
Retrieves key statistics from the PostgreSQL `pg_stat_bgwriter` view, providing insights into the background writer's performance.
It returns the number of timed and requested checkpoints, checkpoint write and sync times, buffer statistics, and the last reset time.
This metric helps administrators monitor the background writer's activity and its impact on database performance.
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
checkpoints_timed,
checkpoints_req,
checkpoint_write_time,
checkpoint_sync_time,
buffers_checkpoint,
buffers_clean,
maxwritten_clean,
buffers_backend,
buffers_backend_fsync,
buffers_alloc
from
pg_stat_bgwriter
17: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
buffers_clean,
maxwritten_clean,
buffers_alloc,
(extract(epoch from now() - stats_reset))::int as last_reset_s
from
pg_stat_bgwriter
node_status: primary
is_instance_level: true
blocking_locks:
description: >
Identifies blocking locks in the PostgreSQL database by analyzing the `pg_locks` and `pg_stat_activity` views.
It retrieves information about waiting locks, including the lock type, user, mode, and the table involved,
as well as details about the blocking lock. The metric helps administrators identify contention issues and
understand which queries are causing blocks in the system.
sqls:
14: |-
WITH sa_snapshot AS (
select * from pg_stat_activity
where datname = current_database()
and not query like 'autovacuum:%'
and pid != pg_backend_pid()
)
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 AS epoch_ns,
waiting.locktype AS tag_waiting_locktype,
waiting_stm.usename::text AS tag_waiting_user,
coalesce(waiting.mode, 'null'::text) AS tag_waiting_mode,
coalesce(waiting.relation::regclass::text, 'null') AS tag_waiting_table,
waiting_stm.query AS waiting_query,
waiting.pid AS waiting_pid,
other.locktype AS other_locktype,
other.relation::regclass::text AS other_table,
other_stm.query AS other_query,
other.mode AS other_mode,
other.pid AS other_pid,
other_stm.usename::text AS other_user
FROM
pg_catalog.pg_locks AS waiting
JOIN
sa_snapshot AS waiting_stm
ON (
waiting_stm.pid = waiting.pid
)
JOIN
pg_catalog.pg_locks AS other
ON (
(
waiting."database" = other."database"
AND waiting.relation = other.relation
)
OR waiting.transactionid = other.transactionid
)
JOIN
sa_snapshot AS other_stm
ON (
other_stm.pid = other.pid
)
WHERE
NOT waiting.GRANTED
AND
waiting.pid <> other.pid
AND
other.GRANTED
AND
waiting_stm.datname = current_database()
gauges:
- '*'
buffercache_by_db:
description: >
Retrieves buffer cache statistics grouped by database, providing insights into the size of buffers used by each database.
It calculates the total size of buffers in bytes for each database.
This metric helps administrators monitor buffer usage across different databases in the PostgreSQL instance.
init_sql: |-
create extension if not exists pg_buffercache;
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
datname as tag_database,
count(*) * (current_setting('block_size')::int8) as size_b
FROM
pg_buffercache AS b,
pg_database AS d
WHERE
d.oid = b.reldatabase
GROUP BY
datname
gauges:
- '*'
is_instance_level: true
buffercache_by_type:
description: >
Retrieves buffer cache statistics grouped by relation type, providing insights into the size of buffers used
by different relation kinds. It calculates the total size of buffers in bytes for each relation kind
(e.g., Table, Index, Toast, Materialized view). This metric helps administrators monitor buffer usage across
different relation types in the PostgreSQL instance.
init_sql: |-
create extension if not exists pg_buffercache;
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
CASE
WHEN relkind = 'r' THEN 'Table' -- TODO all relkinds covered?
WHEN relkind = 'i' THEN 'Index'
WHEN relkind = 't' THEN 'Toast'
WHEN relkind = 'm' THEN 'Materialized view'
ELSE 'Other'
END as tag_relkind,
count(*) * (current_setting('block_size')::int8) size_b
FROM
pg_buffercache AS b,
pg_class AS d
WHERE
d.oid = b.relfilenode
GROUP BY
relkind
gauges:
- '*'
is_instance_level: true
change_events:
description: >
The "change_events" built-in metric tracks DDL & config changes. Internally, it uses some other *
_hashes metrics that are not meant to be used independently. Such metrics should not be removed.
sqls:
14: ""
checkpointer:
description: >
Retrieves key statistics from the PostgreSQL `pg_stat_checkpointer` view, providing insights into the checkpointer's performance.
It returns the number of timed and requested checkpoints, restart points, write and sync times, and buffer statistics.
This metric helps administrators monitor the checkpointer's activity and its impact on database performance.
sqls:
14: "; -- covered by bgwriter"
17: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
num_timed,
num_requested,
restartpoints_timed,
restartpoints_req,
restartpoints_done,
write_time,
sync_time,
buffers_written,
(extract(epoch from now() - stats_reset))::int as last_reset_s
from
pg_stat_checkpointer
18: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
num_timed,
num_requested,
num_done,
restartpoints_timed,
restartpoints_req,
restartpoints_done,
write_time,
sync_time,
buffers_written,
slru_written,
(extract(epoch from now() - stats_reset))::int as last_reset_s
from
pg_stat_checkpointer
configuration_hashes:
description: >
Retrieves configuration settings from the PostgreSQL `pg_settings` view, providing insights into the current configuration of the database.
This metric helps administrators monitor changes applied to the database configuration.
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
name as tag_setting,
coalesce(reset_val, '') as value
from
pg_settings
where
name <> 'connection_ID'
cpu_load:
description: >
Retrieves the system load average for the last 1, 5, and 15 minutes using a custom PL/Python function.
This metric provides insights into the CPU load on the PostgreSQL server, helping administrators monitor system performance.
The function uses the `os.getloadavg()` method to fetch the load averages.
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
round(load_1min::numeric, 2)::float as load_1min,
round(load_5min::numeric, 2)::float as load_5min,
round(load_15min::numeric, 2)::float as load_15min
from
get_load_average();
init_sql: |-
CREATE EXTENSION IF NOT EXISTS plpython3u;
CREATE OR REPLACE FUNCTION get_load_average(OUT load_1min float, OUT load_5min float, OUT load_15min float) AS
$$
from os import getloadavg
la = getloadavg()
return [la[0], la[1], la[2]]
$$ LANGUAGE plpython3u VOLATILE;
GRANT EXECUTE ON FUNCTION get_load_average() TO pgwatch;
COMMENT ON FUNCTION get_load_average() is 'created for pgwatch';
gauges:
- '*'
is_instance_level: true
database_conflicts:
description: >
Retrieves conflict statistics from the PostgreSQL `pg_stat_database_conflicts` view, providing insights into conflicts that have occurred
in the current database. It returns the number of conflicts related to tablespace, lock, snapshot, buffer pin, and deadlock.
This metric helps administrators monitor and diagnose issues related to database conflicts.
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
confl_tablespace,
confl_lock,
confl_snapshot,
confl_bufferpin,
confl_deadlock
FROM
pg_stat_database_conflicts
WHERE
datname = current_database()
node_status: standby
db_size:
description: >
Retrieves the size of the current database, the size of the `pg_catalog` schema, and total indexes size
providing insights into the storage usage of the database.
It returns the size in bytes for both the current database and the catalog schema.
This metric helps administrators monitor database size and storage consumption.
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
pg_database_size(current_database()) as size_b,
(select sum(pg_total_relation_size(c.oid))::int8
from pg_class c join pg_namespace n on n.oid = c.relnamespace
where nspname = 'pg_catalog' and relkind = 'r'
) as catalog_size_b,
(select sum(pg_relation_size(indexrelid))::int8
from pg_stat_user_indexes) as indexes_size_b
gauges:
- '*'
statement_timeout_seconds: 300
db_size_approx:
description: >
Retrieves an approximate size of the current database and the size of the `pg_catalog` schema, providing insights into the storage usage of the database.
It returns the size in bytes for both the current database and the catalog schema.
This metric helps administrators monitor database size and storage consumption.
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
current_setting('block_size')::int8 * (
select sum(relpages) from pg_class c
join pg_namespace n on n.oid = c.relnamespace
where c.relpersistence != 't'
) as size_b,
current_setting('block_size')::int8 * (
select sum(c.relpages + coalesce(ct.relpages, 0) + coalesce(cti.relpages, 0))
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
left join pg_class ct on ct.oid = c.reltoastrelid
left join pg_index ti on ti.indrelid = ct.oid
left join pg_class cti on cti.oid = ti.indexrelid
where nspname = 'pg_catalog'
and (c.relkind = 'r'
or c.relkind = 'i' and not c.relname ~ '^pg_toast')
) as catalog_size_b
gauges:
- '*'
storage_name: db_size
db_stats:
description: >
Retrieves key statistics from the PostgreSQL `pg_stat_database` view, providing insights into the current database's performance.
It returns the number of backends, transaction commits and rollbacks, buffer reads and hits, tuple statistics, conflicts, temporary files and bytes,
deadlocks, block read and write times, postmaster uptime, backup duration, recovery status, system identifier, and invalid indexes.
This metric helps administrators monitor database activity and performance.
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
numbackends,
xact_commit,
xact_rollback,
blks_read,
blks_hit,
tup_returned,
tup_fetched,
tup_inserted,
tup_updated,
tup_deleted,
conflicts,
temp_files,
temp_bytes,
deadlocks,
blk_read_time,
blk_write_time,
extract(epoch from (now() - pg_postmaster_start_time()))::int8 as postmaster_uptime_s,
extract(epoch from (now() - pg_backup_start_time()))::int8 as backup_duration_s,
checksum_failures,
extract(epoch from (now() - checksum_last_failure))::int8 as checksum_last_failure_s,
case when pg_is_in_recovery() then 1 else 0 end as in_recovery_int,
system_identifier::text as tag_sys_id,
session_time::int8,
active_time::int8,
idle_in_transaction_time::int8,
sessions,
sessions_abandoned,
sessions_fatal,
sessions_killed,
(select count(*) from pg_index i
where not indisvalid
and not exists ( /* leave out ones that are being actively rebuilt */
select * from pg_locks l
join pg_stat_activity a using (pid)
where l.relation = i.indexrelid
and a.state = 'active'
and a.query ~* 'concurrently'
)) as invalid_indexes
from
pg_stat_database, pg_control_system()
where
datname = current_database()
15: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
numbackends,
xact_commit,
xact_rollback,
blks_read,
blks_hit,
tup_returned,
tup_fetched,
tup_inserted,
tup_updated,
tup_deleted,
conflicts,
temp_files,
temp_bytes,
deadlocks,
blk_read_time,
blk_write_time,
extract(epoch from (now() - pg_postmaster_start_time()))::int8 as postmaster_uptime_s,
checksum_failures,
extract(epoch from (now() - checksum_last_failure))::int8 as checksum_last_failure_s,
case when pg_is_in_recovery() then 1 else 0 end as in_recovery_int,
system_identifier::text as tag_sys_id,
session_time::int8,
active_time::int8,
idle_in_transaction_time::int8,
sessions,
sessions_abandoned,
sessions_fatal,
sessions_killed,
(select count(*) from pg_index i
where not indisvalid
and not exists ( /* leave out ones that are being actively rebuilt */
select * from pg_locks l
join pg_stat_activity a using (pid)
where l.relation = i.indexrelid
and a.state = 'active'
and a.query ~* 'concurrently'
)) as invalid_indexes
from
pg_stat_database, pg_control_system()
where
datname = current_database()
18: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
numbackends,
xact_commit,
xact_rollback,
blks_read,
blks_hit,
tup_returned,
tup_fetched,
tup_inserted,
tup_updated,
tup_deleted,
conflicts,
temp_files,
temp_bytes,
deadlocks,
blk_read_time,
blk_write_time,
extract(epoch from (now() - pg_postmaster_start_time()))::int8 as postmaster_uptime_s,
checksum_failures,
extract(epoch from (now() - checksum_last_failure))::int8 as checksum_last_failure_s,
case when pg_is_in_recovery() then 1 else 0 end as in_recovery_int,
system_identifier::text as tag_sys_id,
session_time::int8,
active_time::int8,
idle_in_transaction_time::int8,
sessions,
sessions_abandoned,
sessions_fatal,
sessions_killed,
(select count(*) from pg_index i
where not indisvalid
and not exists ( /* leave out ones that are being actively rebuilt */
select * from pg_locks l
join pg_stat_activity a using (pid)
where l.relation = i.indexrelid
and a.state = 'active'
and a.query ~* 'concurrently'
)) as invalid_indexes,
parallel_workers_to_launch,
parallel_workers_launched
from
pg_stat_database, pg_control_system()
where
datname = current_database()
gauges:
- numbackends
- postmaster_uptime_s
- backup_duration_s
- backup_duration_s
- checksum_last_failure_s
- parallel_workers_to_launch
- parallel_workers_launched
index_hashes:
description: >
Retrieves the hash of index definitions in the PostgreSQL database, providing a way to track changes in index definitions over time.
This metric helps administrators monitor index changes and ensure consistency in index definitions.
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
quote_ident(nspname)||'.'||quote_ident(c.relname) as tag_index,
quote_ident(nspname)||'.'||quote_ident(r.relname) as "table",
i.indisvalid::text as is_valid,
coalesce(md5(pg_get_indexdef(i.indexrelid)), random()::text) as md5
from
pg_index i
join
pg_class c on c.oid = i.indexrelid
join
pg_class r on r.oid = i.indrelid
join
pg_namespace n on n.oid = c.relnamespace
where
c.relnamespace not in (select oid from pg_namespace where nspname like any(array[E'pg\\_%', 'information_schema']))
index_stats:
description: >
Retrieves detailed statistics about indexes in the PostgreSQL database, including index size, scan counts, tuple read and fetch counts,
block read and hit counts, and index validity. It also identifies the largest, most scanned, and unused indexes.
This metric helps administrators monitor index performance and identify potential issues with unused or invalid indexes.
sqls:
14: |-
/* does not return all index stats but biggest, top scanned and biggest unused ones */
WITH q_locked_rels AS (
select relation from pg_locks where mode = 'AccessExclusiveLock'
),
q_index_details AS (
select
sui.schemaname,
sui.indexrelname,
sui.relname,
sui.indexrelid,
coalesce(pg_relation_size(sui.indexrelid), 0) as index_size_b,
sui.idx_scan,
sui.idx_tup_read,
sui.idx_tup_fetch,
io.idx_blks_read,
io.idx_blks_hit,
i.indisvalid,
i.indisprimary,
i.indisunique,
i.indisexclusion
from
pg_stat_user_indexes sui
join pg_statio_user_indexes io on io.indexrelid = sui.indexrelid
join pg_index i on i.indexrelid = sui.indexrelid
where not sui.schemaname like any (array [E'pg\\_temp%', E'\\_timescaledb%'])
and not exists (select * from q_locked_rels where relation = sui.relid or relation = sui.indexrelid)
),
q_top_indexes AS (
/* biggest */
select *
from (
select indexrelid
from q_index_details
where idx_scan > 1
order by index_size_b desc
limit 100
) x
union
/* most block traffic */
select *
from (
select indexrelid
from q_index_details
order by coalesce(idx_blks_read, 0) + coalesce(idx_blks_hit, 0) desc
limit 100
) y
union
/* most scans */
select *
from (
select indexrelid
from q_index_details
order by idx_scan desc nulls last
limit 100
) z
)
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
schemaname::text as tag_schema,
indexrelname::text as tag_index_name,
quote_ident(schemaname)||'.'||quote_ident(indexrelname) as tag_index_full_name,
relname::text as tag_table_name,
quote_ident(schemaname)||'.'||quote_ident(relname) as tag_table_full_name,
coalesce(idx_scan, 0) as idx_scan,
coalesce(idx_tup_read, 0) as idx_tup_read,
coalesce(idx_tup_fetch, 0) as idx_tup_fetch,
coalesce(idx_blks_read, 0) as idx_blks_read,
coalesce(idx_blks_hit, 0) as idx_blks_hit,
coalesce(index_size_b, 0) as index_size_b,
quote_ident(schemaname)||'.'||quote_ident(indexrelname) as index_full_name_val,
md5(regexp_replace(regexp_replace(pg_get_indexdef(indexrelid),indexrelname,'X'), '^CREATE UNIQUE','CREATE')) as tag_index_def_hash,
regexp_replace(regexp_replace(pg_get_indexdef(indexrelid),indexrelname,'X'), '^CREATE UNIQUE','CREATE') as index_def,
case when not indisvalid then 1 else 0 end as is_invalid_int,
case when indisprimary then 1 else 0 end as is_pk_int,
case when indisunique or indisexclusion then 1 else 0 end as is_uq_or_exc,
system_identifier::text as tag_sys_id
FROM
q_index_details id
JOIN
pg_control_system() ON true
WHERE
indexrelid IN (select indexrelid from q_top_indexes)
ORDER BY
id.schemaname, id.relname, id.indexrelname
16: |-
/* NB! does not return all index stats but biggest, top scanned and biggest unused ones */
WITH q_locked_rels AS ( /* pgwatch_generated */
select relation from pg_locks where mode = 'AccessExclusiveLock'
),
q_index_details AS (
select
sui.schemaname,
sui.indexrelname,
sui.relname,
sui.indexrelid,
coalesce(pg_relation_size(sui.indexrelid), 0) as index_size_b,
sui.idx_scan,
sui.idx_tup_read,
sui.idx_tup_fetch,
io.idx_blks_read,
io.idx_blks_hit,
i.indisvalid,
i.indisprimary,
i.indisunique,
i.indisexclusion,
extract(epoch from now() - last_idx_scan)::int as last_idx_scan_s
from
pg_stat_user_indexes sui
join pg_statio_user_indexes io on io.indexrelid = sui.indexrelid
join pg_index i on i.indexrelid = sui.indexrelid
where not sui.schemaname like any (array [E'pg\\_temp%', E'\\_timescaledb%'])
and not exists (select * from q_locked_rels where relation = sui.relid or relation = sui.indexrelid)
),
q_top_indexes AS (
/* biggest */
select *
from (
select indexrelid
from q_index_details
where idx_scan > 1
order by index_size_b desc
limit 100
) x
union
/* most block traffic */
select *
from (
select indexrelid
from q_index_details
order by coalesce(idx_blks_read, 0) + coalesce(idx_blks_hit, 0) desc
limit 100
) y
union
/* most scans */
select *
from (
select indexrelid
from q_index_details
order by idx_scan desc nulls last
limit 100
) z
)
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
schemaname::text as tag_schema,
indexrelname::text as tag_index_name,
quote_ident(schemaname)||'.'||quote_ident(indexrelname) as tag_index_full_name,
relname::text as tag_table_name,
quote_ident(schemaname)||'.'||quote_ident(relname) as tag_table_full_name,
coalesce(idx_scan, 0) as idx_scan,
coalesce(idx_tup_read, 0) as idx_tup_read,
coalesce(idx_tup_fetch, 0) as idx_tup_fetch,
coalesce(idx_blks_read, 0) as idx_blks_read,
coalesce(idx_blks_hit, 0) as idx_blks_hit,
coalesce(index_size_b, 0) as index_size_b,
quote_ident(schemaname)||'.'||quote_ident(indexrelname) as index_full_name_val,
md5(regexp_replace(regexp_replace(pg_get_indexdef(indexrelid),indexrelname,'X'), '^CREATE UNIQUE','CREATE')) as tag_index_def_hash,
regexp_replace(regexp_replace(pg_get_indexdef(indexrelid),indexrelname,'X'), '^CREATE UNIQUE','CREATE') as index_def,
case when not indisvalid then 1 else 0 end as is_invalid_int,
case when indisprimary then 1 else 0 end as is_pk_int,
case when indisunique or indisexclusion then 1 else 0 end as is_uq_or_exc,
system_identifier::text as tag_sys_id,
last_idx_scan_s
FROM
q_index_details id
JOIN
pg_control_system() ON true
WHERE
indexrelid IN (select indexrelid from q_top_indexes)
ORDER BY
id.schemaname, id.relname, id.indexrelname
instance_up:
description: >
This metric has some special handling attached to it - it will store a 0 value if the database is not accessible.
Thus it can be used to for example calculate some percentual "uptime" indicator.
For standard metrics there will be no data rows stored when the DB is not reachable, but for this one,
there will be a zero stored for the "is_up" column that, under normal operations, would always be 1.
sqls:
14: |
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
1::int as is_up
invalid_indexes:
description: >
Retrieves a list of invalid indexes in the PostgreSQL database, providing insights into indexes that are not valid.
It returns the index name, schema, and whether the index is valid or not. This metric helps administrators identify and address issues with invalid indexes.
sqls:
14: |-
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
format('%I.%I', n.nspname , ci.relname) as tag_index_full_name,
coalesce(pg_relation_size(indexrelid), 0) as index_size_b
from
pg_index i
join pg_class ci on ci.oid = i.indexrelid
join pg_class cr on cr.oid = i.indrelid
join pg_namespace n on n.oid = ci.relnamespace
where not n.nspname like E'pg\\_temp%'
and not indisvalid
and not exists ( /* leave out ones that are being actively rebuilt */
select * from pg_locks l
join pg_stat_activity a using (pid)
where l.relation = i.indexrelid
and a.state = 'active'
and a.query ~* 'concurrently'
)
and not exists (select * from pg_locks where relation = indexrelid and mode = 'AccessExclusiveLock') /* can't get size then */
order by index_size_b desc
limit 100
kpi:
description: >
Retrieves key performance indicators (KPIs) from the PostgreSQL `pg_stat_database` view, providing insights into the current database's performance.
It returns the number of backends, active and blocked backends, oldest transaction age, transactions per second (TPS), commit and rollback counts,
buffer read and hit counts, temporary bytes, sequence scans on tables larger than 10MB, tuple statistics, stored procedure calls,
block read and write times, deadlocks, recovery status, and postmaster uptime.
This metric helps administrators monitor database activity and performance.
sqls:
14: |
WITH q_stat_tables AS (
SELECT * FROM pg_stat_user_tables t
JOIN pg_class c ON c.oid = t.relid
WHERE NOT schemaname LIKE E'pg\\_temp%'
AND c.relpages > (1e7 / 8) -- >10MB
),
q_stat_activity AS (
SELECT * FROM pg_stat_activity
WHERE datname = current_database() AND pid != pg_backend_pid()
)
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
case
when pg_is_in_recovery() = false then
pg_wal_lsn_diff(pg_current_wal_lsn(), '0/0')::int8
else
pg_wal_lsn_diff(pg_last_wal_replay_lsn(), '0/0')::int8
end as wal_location_b,
numbackends - 1 as numbackends,
(select count(*) from q_stat_activity where state in ('active', 'idle in transaction')) AS active_backends,
(select count(*) from q_stat_activity where wait_event_type in ('LWLock', 'Lock', 'BufferPin')) AS blocked_backends,
(select round(extract(epoch from now()) - extract(epoch from (select xact_start from q_stat_activity
where datid = d.datid and not query like 'autovacuum:%' order by xact_start limit 1))))::int AS kpi_oldest_tx_s,
xact_commit + xact_rollback AS tps,
xact_commit,
xact_rollback,
blks_read,
blks_hit,
temp_bytes,
(select sum(seq_scan) from q_stat_tables)::int8 AS seq_scans_on_tbls_gt_10mb,
tup_inserted,
tup_updated,
tup_deleted,
(select sum(calls) from pg_stat_user_functions where not schemaname like any(array[E'pg\\_%', 'information_schema']))::int8 AS sproc_calls,
blk_read_time,
blk_write_time,
deadlocks,
case when pg_is_in_recovery() then 1 else 0 end as in_recovery_int,
extract(epoch from (now() - pg_postmaster_start_time()))::int8 as postmaster_uptime_s
FROM
pg_stat_database d
WHERE
datname = current_database()
gauges:
- numbackends
- active_backends
- blocked_backends
- kpi_oldest_tx_s
locks:
description: >
Retrieves lock statistics from the PostgreSQL `pg_locks` view, providing insights into the types and modes of locks currently held in the database.
It returns the lock type, lock mode, and the count of locks for each type and mode. This metric helps administrators monitor lock contention and performance.
sqls:
14: |-
WITH q_locks AS (
select
*
from
pg_locks
where
pid != pg_backend_pid()
and database = (select oid from pg_database where datname = current_database())
)
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
locktypes AS tag_locktype,
coalesce((select count(*) FROM q_locks WHERE locktype = locktypes), 0) AS count
FROM
unnest('{relation, extend, page, tuple, transactionid, virtualxid, object, userlock, advisory}'::text[]) locktypes
gauges:
- '*'
locks_mode:
description: >
Retrieves lock mode statistics from the PostgreSQL `pg_locks` view, providing insights into the different lock modes currently held in the database.
It returns the lock mode and the count of locks for each mode. This metric helps administrators monitor lock contention and performance.
sqls:
14: |-
WITH q_locks AS (
select
*
from
pg_locks
where
pid != pg_backend_pid()
and database = (select oid from pg_database where datname = current_database())
)
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
lockmodes AS tag_lockmode,
coalesce((select count(*) FROM q_locks WHERE mode = lockmodes), 0) AS count
FROM
unnest('{AccessShareLock, ExclusiveLock, RowShareLock, RowExclusiveLock, ShareLock, ShareRowExclusiveLock, AccessExclusiveLock, ShareUpdateExclusiveLock}'::text[]) lockmodes
gauges:
- '*'
logical_subscriptions:
description: >
Retrieves information about logical subscriptions in the PostgreSQL database, including their names, enabled status, and the number of relations in each subscription.
It also provides counts of relations in different states (inserted, deleted, synchronized, and replicated).
This metric helps administrators monitor logical replication subscriptions and their statuses.
sqls:
14: |
with q_sr as (
select * from pg_subscription_rel
)
select /* pgwatch_generated */
(extract(epoch from now()) * 1e9)::int8 as epoch_ns,
subname::text as tag_subname,
subenabled,