-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcheck_pgactivity
executable file
·9287 lines (7605 loc) · 327 KB
/
check_pgactivity
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
#!/usr/bin/perl
# This program is open source, licensed under the PostgreSQL License.
# For license terms, see the LICENSE file.
#
# Copyright (C) 2012-2022: Open PostgreSQL Monitoring Development Group
=head1 NAME
check_pgactivity - PostgreSQL plugin for Nagios
=head1 SYNOPSIS
check_pgactivity {-w|--warning THRESHOLD} {-c|--critical THRESHOLD} [-s|--service SERVICE ] [-h|--host HOST] [-U|--username ROLE] [-p|--port PORT] [-d|--dbname DATABASE] [-S|--dbservice SERVICE_NAME] [-P|--psql PATH] [--debug] [--status-file FILE] [--path PATH] [-t|--timemout TIMEOUT]
check_pgactivity [-l|--list]
check_pgactivity [--help]
=head1 DESCRIPTION
check_pgactivity is designed to monitor PostgreSQL clusters from Nagios. It
offers many options to measure and monitor useful performance metrics.
=head1 COMPATIBILITY
Each service is available from a different PostgreSQL version,
from 7.4, as documented below.
The psql client must be 8.3 at least. It can be used with an older server.
Please report any undocumented incompatibility.
=cut
use vars qw($VERSION $PROGRAM);
use strict;
use warnings;
use 5.008;
use POSIX;
use Data::Dumper;
use File::Basename;
use File::Spec;
use File::Temp ();
use Getopt::Long qw(:config bundling no_ignore_case_always);
use List::Util qw(max);
use Pod::Usage;
use Scalar::Util qw(looks_like_number);
use Fcntl qw(:flock);
use Storable qw(retrieve store);
use Config;
use FindBin;
# messing with PATH so pod2usage always finds this script
my @path = split /$Config{'path_sep'}/ => $ENV{'PATH'};
push @path => $FindBin::Bin;
$ENV{'PATH'} = join $Config{'path_sep'} => @path;
undef @path;
# force the env in English
delete $ENV{'LC_ALL'};
$ENV{'LC_ALL'} = 'C';
setlocale( LC_ALL, 'C' );
delete $ENV{'LANG'};
delete $ENV{'LANGUAGE'};
$| = 1;
$VERSION = '2.6';
$PROGRAM = 'check_pgactivity';
my $PG_VERSION_MIN = 70400;
my $PG_VERSION_74 = 70400;
my $PG_VERSION_80 = 80000;
my $PG_VERSION_81 = 80100;
my $PG_VERSION_82 = 80200;
my $PG_VERSION_83 = 80300;
my $PG_VERSION_84 = 80400;
my $PG_VERSION_90 = 90000;
my $PG_VERSION_91 = 90100;
my $PG_VERSION_92 = 90200;
my $PG_VERSION_93 = 90300;
my $PG_VERSION_94 = 90400;
my $PG_VERSION_95 = 90500;
my $PG_VERSION_96 = 90600;
my $PG_VERSION_100 = 100000;
my $PG_VERSION_110 = 110000;
my $PG_VERSION_120 = 120000;
my $PG_VERSION_130 = 130000;
my $PG_VERSION_140 = 140000;
# reference to the output sub
my $output_fmt;
# Available services and descriptions.
#
# The referenced sub called to exec each service takes one parameter: a
# reference to the arguments hash (%args)
#
# Note that we cannot use Perl prototype for these subroutine as they are
# called indirectly (thus the args given by references).
my %services = (
# 'service_name' => {
# 'sub' => sub reference to call to run this service
# 'desc' => 'a description of the service'
# }
'autovacuum' => {
'sub' => \&check_autovacuum,
'desc' => 'Check the autovacuum activity.'
},
'backends' => {
'sub' => \&check_backends,
'desc' => 'Number of connections, compared to max_connections.'
},
'backends_status' => {
'sub' => \&check_backends_status,
'desc' => 'Number of connections in relation to their status.'
},
'checksum_errors' => {
'sub' => \&check_checksum_errors,
'desc' => 'Check data checksums errors.'
},
'session_stats' => {
'sub' => \&check_session_stats,
'desc' => 'Miscellaneous session statistics, including session rate.'
},
'commit_ratio' => {
'sub' => \&check_commit_ratio,
'desc' => 'Commit and rollback rate per second and commit ratio since last execution.'
},
'database_size' => {
'sub' => \&check_database_size,
'desc' => 'Variation of database sizes.',
},
'extensions_versions' => {
'sub' => \&check_extensions_versions,
'desc' => 'Check that installed extensions are up-to-date.'
},
'table_unlogged' => {
'sub' => \&check_table_unlogged,
'desc' => 'Check unlogged tables'
},
'wal_files' => {
'sub' => \&check_wal_files,
'desc' => 'Total number of WAL files.',
},
'archiver' => {
'sub' => \&check_archiver,
'desc' => 'Check the archiver status and number of wal files ready to archive.',
},
'last_vacuum' => {
'sub' => \&check_last_vacuum,
'desc' =>
'Check the oldest vacuum (from autovacuum or not) on the database.',
},
'last_analyze' => {
'sub' => \&check_last_analyze,
'desc' =>
'Check the oldest analyze (from autovacuum or not) on the database.',
},
'locks' => {
'sub' => \&check_locks,
'desc' => 'Check the number of locks on the hosts.'
},
'oldest_2pc' => {
'sub' => \&check_oldest_2pc,
'desc' => 'Check the oldest two-phase commit transaction.'
},
'oldest_idlexact' => {
'sub' => \&check_oldest_idlexact,
'desc' => 'Check the oldest idle transaction.'
},
'oldest_xmin' => {
'sub' => \&check_oldest_xmin,
'desc' => 'Check the xmin horizon from distinct sources of xmin retention.'
},
'longest_query' => {
'sub' => \&check_longest_query,
'desc' => 'Check the longest running query.'
},
'bgwriter' => {
'sub' => \&check_bgwriter,
'desc' => 'Check the bgwriter activity.',
},
'archive_folder' => {
'sub' => \&check_archive_folder,
'desc' => 'Check archives in given folder.',
},
'minor_version' => {
'sub' => \&check_minor_version,
'desc' => 'Check if the PostgreSQL minor version is the latest one.',
},
'hot_standby_delta' => {
'sub' => \&check_hot_standby_delta,
'desc' => 'Check delta in bytes between a master and its hot standbys.',
},
'streaming_delta' => {
'sub' => \&check_streaming_delta,
'desc' => 'Check delta in bytes between a master and its standbys in streaming replication.',
},
'settings' => {
'sub' => \&check_settings,
'desc' => 'Check if the configuration file changed.',
},
'hit_ratio' => {
'sub' => \&check_hit_ratio,
'desc' => 'Check hit ratio on databases.'
},
'backup_label_age' => {
'sub' => \&check_backup_label_age,
'desc' => 'Check age of backup_label file.',
},
'connection' => {
'sub' => \&check_connection,
'desc' => 'Perform a simple connection test.'
},
'custom_query' => {
'sub' => \&check_custom_query,
'desc' => 'Perform the given user query.'
},
'configuration' => {
'sub' => \&check_configuration,
'desc' => 'Check the most important settings.',
},
'btree_bloat' => {
'sub' => \&check_btree_bloat,
'desc' => 'Check B-tree index bloat.'
},
'max_freeze_age' => {
'sub' => \&check_max_freeze_age,
'desc' => 'Check oldest database in transaction age.'
},
'invalid_indexes' => {
'sub' => \&check_invalid_indexes,
'desc' => 'Check for invalid indexes.'
},
'is_master' => {
'sub' => \&check_is_master,
'desc' => 'Check if cluster is in production.'
},
'is_hot_standby' => {
'sub' => \&check_is_hot_standby,
'desc' => 'Check if cluster is a hot standby.'
},
'pga_version' => {
'sub' => \&check_pga_version,
'desc' => 'Check the version of this check_pgactivity script.'
},
'is_replay_paused' => {
'sub' => \&check_is_replay_paused,
'desc' => 'Check if the replication is paused.'
},
'table_bloat' => {
'sub' => \&check_table_bloat,
'desc' => 'Check tables bloat.'
},
'temp_files' => {
'sub' => \&check_temp_files,
'desc' => 'Check temp files generation.'
},
'replication_slots' => {
'sub' => \&check_replication_slots,
'desc' => 'Check delta in bytes of the replication slots.'
},
'pg_dump_backup' => {
'sub' => \&check_pg_dump_backup,
'desc' => 'Check pg_dump backups age and retention policy.'
},
'stat_snapshot_age' => {
'sub' => \&check_stat_snapshot_age,
'desc' => 'Check stats collector\'s stats age.'
},
'sequences_exhausted' => {
'sub' => \&check_sequences_exhausted,
'desc' => 'Check that auto-incremented colums aren\'t reaching their upper limit.'
},
'pgdata_permission' => {
'sub' => \&check_pgdata_permission,
'desc' => 'Check that the permission on PGDATA is 700.'
},
'uptime' => {
'sub' => \&check_uptime,
'desc' => 'Time since postmaster start or configurtion reload.'
},
);
=over
=item B<-s>, B<--service> SERVICE
The Nagios service to run. See section SERVICES for a description of
available services or use C<--list> for a short service and description
list.
=item B<-h>, B<--host> HOST
Database server host or socket directory (default: $PGHOST or "localhost")
See section C<CONNECTIONS> for more informations.
=item B<-U>, B<--username> ROLE
Database user name (default: $PGUSER or "postgres").
See section C<CONNECTIONS> for more informations.
=item B<-p>, B<--port> PORT
Database server port (default: $PGPORT or "5432").
See section C<CONNECTIONS> for more informations.
=item B<-d>, B<--dbname> DATABASE
Database name to connect to (default: $PGDATABASE or "template1").
B<WARNING>! This is not necessarily one of the database that will be
checked. See C<--dbinclude> and C<--dbexclude> .
See section C<CONNECTIONS> for more informations.
=item B<-S>, B<--dbservice> SERVICE_NAME
The connection service name from pg_service.conf to use.
See section C<CONNECTIONS> for more informations.
=item B<--dbexclude> REGEXP
Some services automatically check all the databases of your
cluster (note: that does not mean they always need to connect on all
of them to check them though). C<--dbexclude> excludes any
database whose name matches the given Perl regular expression.
Repeat this option as many time as needed.
See C<--dbinclude> as well. If a database match both dbexclude and
dbinclude arguments, it is excluded.
=item B<--dbinclude> REGEXP
Some services automatically check all the databases of your
cluster (note: that does not imply that they always need to connect to all
of them though). Some always exclude the 'postgres'
database and templates. C<--dbinclude> checks B<ONLY>
databases whose names match the given Perl regular expression.
Repeat this option as many time as needed.
See C<--dbexclude> as well. If a database match both dbexclude and
dbinclude arguments, it is excluded.
=item B<-w>, B<--warning> THRESHOLD
The Warning threshold.
=item B<-c>, B<--critical> THRESHOLD
The Critical threshold.
=item B<-F>, B<--format> OUTPUT_FORMAT
The output format. Supported output are: C<binary>, C<debug>, C<human>,
C<nagios>, C<nagios_strict>, C<json> and C<json_strict>.
Using the C<binary> format, the results are written in a binary file (using
perl module C<Storable>) given in argument C<--output>. If no output is given,
defaults to file C<check_pgactivity.out> in the same directory as the script.
The C<nagios_strict> and C<json_strict> formats are equivalent to the C<nagios>
and C<json> formats respectively. The only difference is that they enforce the
units to follow the strict Nagios specs: B, c, s or %. Any unit absent from
this list is dropped (Bps, Tps, etc).
=item B<--tmpdir> DIRECTORY
Path to a directory where the script can create temporary files. The
script relies on the system default temporary directory if possible.
=item B<-P>, B<--psql> FILE
Path to the C<psql> executable (default: "psql").
It should be version 8.3 at least, but the server can be older.
=item B<--status-file> PATH
Path to the file where service status information is kept between successive
calls. Default is to save a file called C<check_pgactivity.data> in the same
directory as the script.
Note that this file is protected from concurrent writes using a lock file
located in the same directory, having the same name than the status file, but
with the extension C<.lock>.
On some plateform, network filesystems may not be supported correctly by the
locking mechanism. See C<perldoc -f flock> for more information.
=item B<--dump-status-file>
Dump the content of the status file and exit. This is useful for debugging
purpose.
=item B<--dump-bin-file> [PATH]
Dump the content of the given binary file previously created using
C<--format binary>. If no path is given, defaults to file
C<check_pgactivity.out> in the same directory as the script.
=item B<-t>, B<--timeout> TIMEOUT
Timeout (default: "30s"), as raw (in seconds) or as
an interval. This timeout will be used as C<statement_timeout> for psql and URL
timeout for C<minor_version> service.
=item B<-l>, B<--list>
List available services.
=item B<-V>, B<--version>
Print version and exit.
=item B<--debug>
Print some debug messages.
=item B<-?>, B<--help>
Show this help page.
=back
=cut
my %args = (
'service' => undef,
'host' => undef,
'username' => undef,
'port' => undef,
'dbname' => undef,
'dbservice' => undef,
'detailed' => 0,
'warning' => undef,
'critical' => undef,
'exclude' => [],
'dbexclude' => [],
'dbinclude' => [],
'tmpdir' => File::Spec->tmpdir(),
'psql' => undef,
'path' => undef,
'status-file' => dirname(__FILE__) . '/check_pgactivity.data',
'output' => dirname(__FILE__) . '/check_pgactivity.out',
'query' => undef,
'type' => undef,
'reverse' => 0,
'work_mem' => undef,
'maintenance_work_mem' => undef,
'shared_buffers' => undef,
'wal_buffers' => undef,
'checkpoint_segments' => undef,
'effective_cache_size' => undef,
'no_check_autovacuum' => 0,
'no_check_fsync' => 0,
'no_check_enable' => 0,
'no_check_track_counts' => 0,
'ignore-wal-size' => 0,
'unarchiver' => '',
'save' => 0,
'suffix' => '',
'slave' => [],
'list' => 0,
'help' => 0,
'debug' => 0,
'timeout' => '30s',
'dump-status-file' => 0,
'dump-bin-file' => undef,
'format' => 'nagios',
'uid' => undef
);
# Set name of the program without path*
my $orig_name = $0;
$0 = $PROGRAM;
# Die on kill -1, -2, -3 or -15
$SIG{'HUP'} = $SIG{'INT'} = $SIG{'QUIT'} = $SIG{'TERM'} = \&terminate;
# Handle SIG
sub terminate() {
my ($signal) = @_;
die ("SIG $signal caught");
}
# Print the version and exit
sub version() {
printf "check_pgactivity version %s, Perl %vd\n",
$VERSION, $^V;
exit 0;
}
# List services that can be performed
sub list_services() {
print "List of available services:\n\n";
foreach my $service ( sort keys %services ) {
printf "\t%-17s\t%s\n", $service, $services{$service}{'desc'};
}
exit 0;
}
# Check wrapper around Storable::file_magic to fallback on
# Storable::read_magic under perl 5.8 and below
# WARNINGS:
# * you must hold a lock on the lockfile **BEFORE** calling this sub
# * the given arg must be an existing and readable file
sub is_storable($) {
my $storage = shift;
my $head;
return defined Storable::file_magic( $storage )
if defined *Storable::file_magic{CODE};
open my $fh, '<', $storage;
read $fh, $head, 64;
close $fh;
return defined Storable::read_magic($head);
}
# Find a unique string for the database instance connection.
# Used by save and load.
#
# Parameter: host structure ref that holds the "host" and "port" parameters
sub find_hostkey($) {
my $host = shift;
return "$host->{'host'}$host->{'port'}" if defined $host->{'host'}
and defined $host->{'port'};
return $host->{'dbservice'} if defined $host->{'dbservice'};
return "binary defaults";
}
# Record the given ref content for the given host in a file on disk.
# The file is defined by argument "--status-file" on command line. By default:
#
# dirname(__FILE__) . '/check_pgactivity.data'
#
# The status file is a data structure saving for each host ($host) the status
# of each service ($name). Format of data in this file is:
# {
# "${host}${port}" => {
# "$name" => $ref
# }
# }
#
# Each call of save($host, $name, $ref, $storage) only overwrite the data for
# given $host for the given $name service. To avoid data loss, the sub first
# require an exclusive lock on the lock file, then load the existing data,
# write its values, then close the file and release the lock.
#
# Data can be retrieved later using the "load" sub.
#
# Parameters are :
# * the $host structure ref that holds the "host" and "port" parameters
# * the $name of the structure to save
# * the $ref of the structure to save
# * the $path to the file storage
sub save($$$$) {
my $host = shift;
my $name = shift;
my $ref = shift;
my $storage = shift;
my $all = {};
my $lockfile = "${storage}.lock";
my $hostkey = find_hostkey($host);
open my $fh, '>', $lockfile or die "can't open «${lockfile}»: $!";
flock($fh, LOCK_EX) or die "can't get exclusive lock on «${lockfile}»: $!";
if ( -e $storage ) {
die "can not write to status file «${storage}»" unless -w ${storage};
exit 1 unless is_storable $storage;
eval { $all = retrieve($storage) };
die "could not retrieve data from «${storage}»:\n $@" if $@;
}
$all->{$hostkey}{$name} = $ref;
eval { store( $all, $storage ); };
die "could not update data in «${storage}»:\n $@" if $@;
# closing the fh removes the lock
close $fh or die "could not release «${lockfile}»: $!";
}
# Load the given ref content for the given host from the file on disk.
#
# See "save" sub comments for more info.
# Parameters are :
# * the host structure ref that holds the "host" and "port" parameters
# * the name of the structure to load
# * the path to the file storage
sub load($$$) {
my $host = shift;
my $name = shift;
my $storage = shift;
my $hostkey = find_hostkey($host);
my $lockfile = "${storage}.lock";
my $all;
return undef unless -e $storage;
die "can not read status file «${storage}»" unless -r $storage;
# Make sure that the lockfile exist. It could have been removed, or just
# not have been created if upgrading from older versions.
if (not -f $lockfile) {
open my $fh, '>', $lockfile or die "can't open «${lockfile}»: $!";
close $fh or die "could not release «${lockfile}»: $!";
}
open my $fh, '<', $lockfile or die "can't open «${lockfile}»: $!";
flock($fh, LOCK_SH) or die "can't get shared lock on «${lockfile}»: $!";
exit 1 unless is_storable $storage;
eval { $all = retrieve($storage) };
die "could not read status file «${storage}»:\n $@" if $@;
# closing the fh removes the lock
close $fh or die "could not release «${lockfile}»: $!";
return $all->{$hostkey}{$name};
}
sub dump_status_file {
my $f = shift;
my $all;
$f = $args{'status-file'} unless defined $f;
$f = $args{'output'} unless $f ;
$all = lock_retrieve($f);
print Data::Dumper->new( [ $all ] )->Terse(1)->Dump;
exit 0;
}
# Return formatted size string with units.
# Parameter: size in bytes
sub to_size($) {
my $val = shift;
my @units = qw{B kB MB GB TB PB EB};
my $size = '';
my $mod = 0;
my $i;
return $val if $val =~ /^(-?inf)|(NaN$)/i;
$val = int($val);
for ( $i=0; $i < 6 and abs($val) > 1024; $i++ ) {
$mod = $val%1024;
$val = int( $val/1024 );
}
$val = "$val.$mod" unless $mod == 0;
return "${val}$units[$i]";
}
# Return formatted time string with units.
# Parameter: duration in seconds
sub to_interval($) {
my $val = shift;
my $interval = '';
return $val if $val =~ /^-?inf/i;
$val = int($val);
if ( $val > 604800 ) {
$interval = int( $val / 604800 ) . "w ";
$val %= 604800;
}
if ( $val > 86400 ) {
$interval .= int( $val / 86400 ) . "d ";
$val %= 86400;
}
if ( $val > 3600 ) {
$interval .= int( $val / 3600 ) . "h";
$val %= 3600;
}
if ( $val > 60 ) {
$interval .= int( $val / 60 ) . "m";
$val %= 60;
}
$interval .= "${val}s" if $val > 0;
return "${val}s" unless $interval; # return a value if $val <= 0
return $interval;
}
=head2 THRESHOLDS
THRESHOLDS provided as warning and critical values can be raw numbers,
percentages, intervals or sizes. Each available service supports one or more
formats (eg. a size and a percentage).
=over
=item B<Percentage>
If THRESHOLD is a percentage, the value should end with a '%' (no space).
For instance: 95%.
=item B<Interval>
If THRESHOLD is an interval, the following units are accepted (not case
sensitive): s (second), m (minute), h (hour), d (day). You can use more than
one unit per given value. If not set, the last unit is in seconds.
For instance: "1h 55m 6" = "1h55m6s".
=cut
sub is_size($){
my $str_size = lc( shift() );
return 1 if $str_size =~ /^\s*[0-9]+([kmgtpez]?[bo]?)?\s*$/ ;
return 0;
}
sub is_time($){
my $str_time = lc( shift() );
return 1 if ( $str_time
=~ /^(\s*([0-9]\s*[smhd]?\s*))+$/
);
return 0;
}
# Return a duration in seconds from an interval (with units).
sub get_time($) {
my $str_time = lc( shift() );
my $ts = 0;
my @date;
die( "Malformed interval: «$str_time»!\n"
. "Authorized unit are: dD, hH, mM, sS\n" )
unless is_time($str_time);
# no bad units should exist after this line!
@date = split( /([smhd])/, $str_time );
LOOP_TS: while ( my $val = shift @date ) {
$val = int($val);
die("Wrong value for an interval: «$val»!") unless defined $val;
my $unit = shift(@date) || '';
if ( $unit eq 'm' ) {
$ts += $val * 60;
next LOOP_TS;
}
if ( $unit eq 'h' ) {
$ts += $val * 3600;
next LOOP_TS;
}
if ( $unit eq 'd' ) {
$ts += $val * 86400;
next LOOP_TS;
}
$ts += $val;
}
return $ts;
}
=pod
=item B<Size>
If THRESHOLD is a size, the following units are accepted (not case sensitive):
b (Byte), k (KB), m (MB), g (GB), t (TB), p (PB), e (EB) or Z (ZB). Only
integers are accepted. Eg. C<1.5MB> will be refused, use C<1500kB>.
The factor between units is 1024 bytes. Eg. C<1g = 1G = 1024*1024*1024.>
=back
=cut
# Return a size in bytes from a size with unit.
# If unit is '%', use the second parameter to compute the size in bytes.
sub get_size($;$) {
my $str_size = shift;
my $size = 0;
my $unit = '';
die "Only integers are accepted as size. Adjust the unit to your need."
if $str_size =~ /[.,]/;
$str_size =~ /^([0-9]+)(.*)$/;
$size = int($1);
$unit = lc($2);
return $size unless $unit ne '';
if ( $unit eq '%' ) {
my $ratio = shift;
die("Can not compute a ratio without the factor!")
unless defined $unit;
return int( $size * $ratio / 100 );
}
return $size if $unit eq 'b';
return $size * 1024 if $unit =~ '^k[bo]?$';
return $size * 1024**2 if $unit =~ '^m[bo]?$';
return $size * 1024**3 if $unit =~ '^g[bo]?$';
return $size * 1024**4 if $unit =~ '^t[bo]?$';
return $size * 1024**5 if $unit =~ '^p[bo]?$';
return $size * 1024**6 if $unit =~ '^e[bo]?$';
return $size * 1024**7 if $unit =~ '^z[bo]?$';
die("Unknown size unit: $unit");
}
=head2 CONNECTIONS
check_pgactivity allows two different connection specifications: by service or
by specifying values for host, user, port, and database.
Some services can run on multiple hosts, or needs to connect to multiple hosts.
You might specify one of the parameters below to connect to your PostgreSQL
instance. If you don't, no connection parameters are given to psql: connection
relies on binary defaults and environment.
The format for connection parameters is:
=over
=item B<Parameter> C<--dbservice SERVICE_NAME>
Define a new host using the given service. Multiple hosts can be defined by
listing multiple services separated by a comma. Eg.
--dbservice service1,service2
For more information about service definition, see:
L<https://www.postgresql.org/docs/current/libpq-pgservice.html>
=item B<Parameters> C<--host HOST>, C<--port PORT>, C<--user ROLE> or C<--dbname DATABASE>
One parameter is enough to define a new host. Usual environment variables
(PGHOST, PGPORT, PGDATABASE, PGUSER, PGSERVICE, PGPASSWORD) or default values
are used for missing parameters.
As for usual PostgreSQL tools, there is no command line argument to set the
password, to avoid exposing it. Use PGPASSWORD, .pgpass or a service file
(recommended).
If multiple values are given, define as many host as maximum given values.
Values are associated by position. Eg.:
--host h1,h2 --port 5432,5433
Means "host=h1 port=5432" and "host=h2 port=5433".
If the number of values is different between parameters, any host missing a
parameter will use the first given value for this parameter. Eg.:
--host h1,h2 --port 5433
Means: "host=h1 port=5433" and "host=h2 port=5433".
=item B<Services are defined first>
For instance:
--dbservice s1 --host h1 --port 5433
means: use "service=s1" and "host=h1 port=5433" in this order. If the service
supports only one host, the second host is ignored.
=item B<Mutual exclusion between both methods>
You can not overwrite services connections variables with parameters C<--host HOST>,
C<--port PORT>, C<--user ROLE> or C<--dbname DATABASE>
=back
=cut
sub parse_hosts(\%) {
my %args = %{ shift() };
my @hosts = ();
if (defined $args{'dbservice'}) {
push
@hosts,
{ 'dbservice' => $_,
'name' => "service:$_",
'pgversion' => undef
}
foreach split /,/, $args{'dbservice'};
}
# Add as many hosts than necessary depending on given parameters
# host/port/db/user.
# Any missing parameter will be set to its default value.
if (defined $args{'host'}
or defined $args{'username'}
or defined $args{'port'}
or defined $args{'dbname'}
) {
$args{'host'} = $ENV{'PGHOST'} || 'localhost'
unless defined $args{'host'};
$args{'username'} = $ENV{'PGUSER'} || 'postgres'
unless defined $args{'username'};
$args{'port'} = $ENV{'PGPORT'} || '5432'
unless defined $args{'port'};
$args{'dbname'} = $ENV{'PGDATABASE'} || 'template1'
unless defined $args{'dbname'};
my @dbhosts = split( /,/, $args{'host'} );
my @dbnames = split( /,/, $args{'dbname'} );
my @dbusers = split( /,/, $args{'username'} );
my @dbports = split( /,/, $args{'port'} );
my $nbhosts = max $#dbhosts, $#dbnames, $#dbusers, $#dbports;
# Take the first value for each connection property as default.
# eg. "-h localhost -p 5432,5433" gives two hosts:
# * localhost:5432
# * localhost:5433
for ( my $i = 0; $i <= $nbhosts; $i++ ) {
push(
@hosts,
{ 'host' => $dbhosts[$i] || $dbhosts[0],
'port' => $dbports[$i] || $dbports[0],
'db' => $dbnames[$i] || $dbnames[0],
'user' => $dbusers[$i] || $dbusers[0],
'pgversion' => undef
}
);
$hosts[-1]{'name'} = sprintf('host:%s port:%d db:%s',
$hosts[-1]{'host'}, $hosts[-1]{'port'}, $hosts[-1]{'db'}
);
}
}
if ( not @hosts ) {
# No connection parameters given.
# The psql execution relies on binary defaults and env variables.
# We look for libpq environment variables to save them and preserve
# default psql behaviour as query() always resets them.
my $name = 'binary defaults';
push @hosts, {
'name' => 'binary defaults',
'pgversion' => undef
};
$hosts[0]{'host'} = $ENV{'PGHOST'} if defined $ENV{'PGHOST'};
$hosts[0]{'port'} = $ENV{'PGPORT'} if defined $ENV{'PGPORT'};
$hosts[0]{'db'} = $ENV{'PGDATABASE'} if defined $ENV{'PGDATABASE'};
$hosts[0]{'user'} = $ENV{'PGUSER'} if defined $ENV{'PGUSER'};
$hosts[0]{'dbservice'} = $ENV{'PGSERVICE'} if defined $ENV{'PGSERVICE'};
if (defined $ENV{'PGHOST'} ) {
$hosts[0]{'host'} = $ENV{'PGHOST'};
$name .= " host:$ENV{'PGHOST'}";
}
if (defined $ENV{'PGPORT'} ) {
$hosts[0]{'port'} = $ENV{'PGPORT'};
$name .= " port:$ENV{'PGPORT'}";
}