forked from inuits/monitoring-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_pgactivity
executable file
·5601 lines (4496 loc) · 188 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-2014: Open PostgreSQL Monitoring Development Group
=head1 check_pgactivity
check_pgactivity - PostgreSQL plugin for Nagios
=head2 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]
=head2 DESCRIPTION
check_pgactivity is designed to monitor PostgreSQL clusters from Nagios. It
offers many options to measure and monitor useful performance metrics.
=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 Storable qw(store retrieve);
setlocale( LC_ALL, 'C' );
$| = 1;
$VERSION = '1.25dev';
$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;
# Available services and descriptions.
#
# The referenced sub called to exec each service takes one parameters: a
# reference to the arguments hash (%args)
#
# Note that we can not 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 desctiption 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.'
},
'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.',
},
'wal_files' => {
'sub' => \&check_wal_files,
'desc' => 'Total number of WAL files.',
},
'ready_archives' => {
'sub' => \&check_ready_archives,
'desc' => 'Check the 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.'
},
'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.',
},
'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.'
},
'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.'
}
);
=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: "localhost").
=item B<-U>, B<--username> ROLE
Database user name (default: "postgres").
=item B<-p>, B<--port> PORT
Database server port (default: "5432").
=item B<-d>, B<--dbname> DATABASE
Database name to connect to (default: "postgres").
B<WARNING>! This is not necessarily one of the database that will be
checked. See C<--dbinclude> and C<--dbexclude> .
=item B<-S>, B<--dbservice> SERVICE_NAME
The connection service name from pg_service.conf to use.
=item B<--dbexclude> REGEXP
Some services are automatically checking 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> allows to exclude any
database whose name matches the given perl regular expression. You
can 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 are automatically checking 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<--dbinclude> allows to B<ONLY> check
databases whose names match the given perl regular expression. You
can 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<--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").
=item B<--status-file> PATH
PATH to the file where service status information will be kept between
successive calls. Default is to save check_pgactivity.data in the same
directory as the script.
=item B<-t>, B<--timeout> TIMEOUT
Timeout to use (default: "30s"). It can be specified 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,
'warning' => undef,
'critical' => undef,
'exclude' => [],
'dbexclude' => [],
'dbinclude' => [],
'tmpdir' => File::Spec->tmpdir(),
'psql' => undef,
'path' => undef,
'status-file' => dirname(__FILE__) . '/check_pgactivity.data',
'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,
'suffix' => '',
'slave' => [],
'list' => 0,
'help' => 0,
'debug' => 0,
'timeout' => '30s'
);
# 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
sub is_storable($) {
my $storage = shift;
my $head;
return 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);
}
# 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'
#
# Format of data in this file is:
# {
# "${host}${port}" => {
# "$name" => ref
# }
# }
# 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 $hostkey;
if (defined $host->{'dbservice'}) {
$hostkey = "$host->{'dbservice'}";
}
else {
$hostkey = "$host->{'host'}$host->{'port'}";
}
die "File «${storage}» not recognized as a check_pgactivity status file.\n\n"
."Please, check its path or move away this wrong file"
if -r $storage and not is_storable $storage;
$all = retrieve($storage) if -r $storage;
$all->{$hostkey}{$name} = $ref;
store( $all, $storage )
or die "Can't store data in '$storage'!\n";
}
# 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;
my $all;
if (defined $host->{'dbservice'}) {
$hostkey = "$host->{'dbservice'}";
}
else {
$hostkey = "$host->{'host'}$host->{'port'}";
}
return undef unless -r $storage;
die "File «${storage}» not recognized as a check_pgactivity status file.\n\n"
."Please, check its path or move away this wrong file"
unless is_storable $storage;
$all = retrieve($storage);
return $all->{$hostkey}{$name};
}
# Returns formated size string with units.
# Takes a size in bytes as parameter.
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 $val > 1024; $i++ ) {
$mod = $val%1024;
$val = int( $val/1024 );
}
$val = "$val.$mod" unless $mod == 0;
return "${val}$units[$i]";
}
# Returns formated time string with units.
# Takes a duration in seconds as parameter.
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 $interval;
}
=head2 THRESHOLDS
THRESHOLDS provided as warning and critical values can be a raw numbers,
percentages, intervals or a 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;
}
# Takes an interval (with units) as parameter and returns a duration in second.
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 exists 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
# Takes a size with unit as parameter and returns it in bytes.
# If unit is '%', use the second parameter to compute the size in byte.
sub get_size($;$) {
my $str_size = shift;
my $size = 0;
my $unit = '';
die "Only integers are accepted as size. Ajust the unit for 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 must specify one of the parameters below if the service needs to connect
to your PostgreSQL instance. In other words, check_pgactivity will NOT look for
the C<libpq> environment variables.
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
=item B<Parameters> C<--host HOST>, C<--port PORT>, C<--user ROLE> or C<--dbname DATABASE>
One of these parameters is enough to define a new host. If some
parameters are missing, default values are used.
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 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 parameters 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 properties 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'}
);
}
}
dprint ('Hosts: '. Dumper(\@hosts));
return \@hosts;
}
# Execute a query on a host.
# Params:
# * host
# * query
# * (optional) database
# The result is an array of array:
# [
# [column1, ...] # line1
# ...
# ]
sub query($$;$) {
my $host = shift;
my $query = shift;
my $db = shift;
my @res = ();
my $res = '';
my $RS = chr(30); # ASCII RS (record separator)
my $FS = chr(3); # ASCII ETX (end of text)
my $tmpfile;
my $psqlcmd;
my $rc;
local $/ = undef;
delete $ENV{PGSERVICE};
delete $ENV{PGDATABASE};
delete $ENV{PGHOST};
delete $ENV{PGPORT};
delete $ENV{PGUSER};
delete $ENV{PGOPTIONS};
$ENV{PGDATABASE} = $host->{'db'} if defined $host->{'db'};
$ENV{PGSERVICE} = $host->{'dbservice'} if defined $host->{'dbservice'};
$ENV{PGHOST} = $host->{'host'} if defined $host->{'host'};
$ENV{PGPORT} = $host->{'port'} if defined $host->{'port'};
$ENV{PGUSER} = $host->{'user'} if defined $host->{'user'};
$ENV{PGOPTIONS} = '-c client_min_messages=error -c statement_timeout=' . get_time($args{'timeout'}) * 1000;
dprint ("Query: $query\n");
dprint ("Env. service: $ENV{PGSERVICE} \n") if defined $host->{'dbservice'};
dprint ("Env. host : $ENV{PGHOST} \n") if defined $host->{'host'};
dprint ("Env. port : $ENV{PGPORT} \n") if defined $host->{'port'};
dprint ("Env. user : $ENV{PGUSER} \n") if defined $host->{'user'};
dprint ("Env. db : $ENV{PGDATABASE}\n") if defined $host->{'db'};
$tmpfile = File::Temp->new(
TEMPLATE => 'check_pga-XXXXXXXX',
DIR => $args{'tmpdir'}
) or die "Could not create or write in a temp file!";
print $tmpfile "$query;" or die "Could not create or write in a temp file!";
$psqlcmd = qq{ $args{'psql'} --set "ON_ERROR_STOP=1" }
. qq{ -qXAtf $tmpfile -R $RS -F $FS };
$psqlcmd .= qq{ --dbname='$db' } if defined $db;
$res = qx{ $psqlcmd 2>&1 };
$rc = $?;
dprint("Query rc: $rc\n");
dprint( sprintf( " stderr (%u): «%s»\n", length $res, $res ) )
if $rc;
exit unknown('CHECK_PGACTIVITY',
[ "Query fail !\n" . $res ]
) unless $rc == 0;
if (defined $res) {
chop $res;
push @res, [ split(chr(3) => $_, -1) ]
foreach split (chr(30) => $res, -1);
}
dprint( "Query result: ". Dumper( \@res ) );
return \@res;
}
# Select the query appropriate query amongs an hash of query according to the
# backend version and execute it. Same argument order than in "query" sub.
# Hash of query must be of this form:
# {
# pg_version_num => $query1,
# ...
# }
#
# Where pg_version_num is the minimum PostgreSQL version which can run the
# query. The given versions are in numric version. See "set_pgversion" about
# how to compute a PostgreSQL num version, or globals $PG_VERSION_*.
sub query_ver($\%;$) {
my $host = shift;
my %queries = %{ shift() };
# shift returns undef if he db is not given. The value is then set in
# "query" sub
my $db = shift;
set_pgversion($host);
foreach my $ver ( sort { $b cmp $a } keys %queries ) {
return query( $host, $queries{$ver}, $db )
if ( $ver <= $host->{'version_num'} );
}
return undef;
}
# Returns an array (not sorted) with all databases existing in given host but
# templates and "postgres" one.
sub get_all_dbname($) {
my @dbs;
push @dbs => $_->[0] foreach (
@{ query( shift, q{
SELECT datname
FROM pg_database
WHERE NOT datistemplate
AND datallowconn
AND datname <> 'postgres'
ORDER BY 1
})
}
);
return \@dbs;
}
# Query and set the version for the given host
sub set_pgversion($) {
my $host = shift;
unless ( $host->{'version'} ) {
my $rs = query( $host, q{SELECT current_setting('server_version')} );
if ( $? != 0 ) {
dprint("FATAL: psql error, $!\n");
exit 1;
}
$host->{'version'} = $rs->[0][0];
chomp( $host->{'version'} );
}
if ( $host->{'version'} =~ /^(\d+)\.(\d+)(.(\d+))?/ ) {
$host->{'version_num'} = int($1) * 10000 + int($2) * 100;
# alpha/beta version have no minor version number
$host->{'version_num'} += int($4) if defined $4;
dprint(sprintf ("host %s is version %s/%s\n",
$host->{'name'},
$host->{'version'},
$host->{'version_num'})
);
return;
}
return 1;
}
# Check host compatibility
sub is_compat($$$;$) {
my $host = shift;
my $service = shift;
my $min = shift;
my $max = shift() || 9999999;;
my $ver;
set_pgversion($host);
$ver = 100*int($host->{'version_num'}/100);
unless (
$ver >= $min
and $ver <= $max
) {
warn sprintf "Service %s is not compatible with host '%s' (v%s).\n",
$service, $host->{'name'}, $host->{'version'};
return 0;
}
return 1;
}
sub dprint {
return unless $args{'debug'};
foreach (@_) {
print "DEBUG: $_";
}
}
sub unknown($;$$$) {
return output( 3, $_[0], $_[1], $_[2], $_[3] );
}
sub critical($;$$$) {
return output( 2, $_[0], $_[1], $_[2], $_[3] );
}
sub warning($;$$$) {
return output( 1, $_[0], $_[1], $_[2], $_[3] );
}
sub ok($;$$$) {
return output( 0, $_[0], $_[1], $_[2], $_[3] );
}
sub output ($$;$$$) {
my $rc = shift;