forked from darold/pgcluu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgcluu_collectd
executable file
·1648 lines (1409 loc) · 43.8 KB
/
pgcluu_collectd
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/env perl
#------------------------------------------------------------------------------
#
# PgCluu - PostgreSQL monitoring tool with statistics collector and grapher
#
# This program is open source, licensed under the PostgreSQL license.
# For license terms, see the LICENSE file.
#
# Author: Gilles Darold
# Copyright: (C) 2012-2014 Gilles Darold - All rights reserved.
#------------------------------------------------------------------------------
use vars qw($VERSION $PROGRAM);
use strict qw(vars subs);
use File::Basename;
use POSIX;
use Getopt::Long qw(:config bundling no_ignore_case_always);
use POSIX qw(locale_h sys_wait_h);
setlocale(LC_ALL, 'C');
$| = 1;
$VERSION = '2.0pre';
$PROGRAM = 'pgcluu_collectd';
# Default path to the external programs
# They can be specified into command line options
my $SAR_PROG = 'sar';
my $PSQL_PROG = 'psql';
my $CP_PROG = 'cp -f ';
my $SAR_FILE = 'sar_stats.dat';
my $PIDFILE = "/tmp/$PROGRAM.pid";
my $SQL_PROBE = '';
my %DB_INFO = ();
my $HELP = 0;
my $DAEMONIZE = 0;
my $DISABLE_SAR = 0;
my $INTERVAL = 60; # wait 60 seconds between runs
my $DEBUG = 0;
my $DBNAME = '';
my $DBUSER = '';
my $DBHOST = '';
my $DBPORT = '';
my $DBPASS = '';
my @METRICS = ();
my $LIST_METRIC = 0;
my $FILE_REDIR = '>>';
my $PG_VERSION = 0;
my $DBSERVICE = '';
my $STAT_TYPE = 'user';
my $KILL = 0;
my $OS_INFO = 0;
my $NOTABLESPACE= 0;
my $PGBOUNCER_ARGS = '';
my $INCLUDED_DB = ();
my $SKIP_HOURS = '';
my @SKIP_BEGIN = ();
my @SKIP_END = ();
# Definition to collect metrics from the database
my %METRICS_COMMANDS = (
'database_stats' => {
'output' => 'pg_stat_database.csv',
'command' => 'dump_pgstatdatabase'
},
'tablespace_size_stats' => {
'output' => 'pg_tablespace_size.csv',
'command' => 'dump_pgtablespace_size'
},
'bgwriter_stats' => {
'output' => 'pg_stat_bgwriter.csv',
'command' => 'dump_pgstatbgwriter'
},
# Too much data, may be repalced by pg_stat_statement information
# 'activity_stats' => {
# 'output' => 'pg_stat_activity.csv',
# 'command' => 'dump_pgstatactivity'
# },
'conflict_stats' => {
'output' => 'pg_stat_database_conflicts.csv',
'command' => 'dump_pgstatdatabaseconflicts'
},
'replication_stats' => {
'output' => 'pg_stat_replication.csv',
'command' => 'dump_pgstatreplication'
},
'all_tables_stats' => {
'output' => 'pg_stat_all_tables.csv',
'command' => 'dump_pgstattables',
'repeat' => 1,
},
'user_tables_stats' => {
'output' => 'pg_stat_user_tables.csv',
'command' => 'dump_pgstattables_user',
'repeat' => 1,
},
'all_tables_io_stats' => {
'output' => 'pg_statio_all_tables.csv',
'command' => 'dump_pgstatiotables',
'repeat' => 1,
},
'user_tables_io_stats' => {
'output' => 'pg_statio_user_tables.csv',
'command' => 'dump_pgstatiotables_user',
'repeat' => 1,
},
'all_indexes_stats' => {
'output' => 'pg_stat_all_indexes.csv',
'command' => 'dump_pgstatindexes',
'repeat' => 1,
},
'user_indexes_stats' => {
'output' => 'pg_stat_user_indexes.csv',
'command' => 'dump_pgstatindexes_user',
'repeat' => 1,
},
'all_indexes_io_stats' => {
'output' => 'pg_statio_all_indexes.csv',
'command' => 'dump_pgstatioindexes',
'repeat' => 1,
},
'user_indexes_io_stats' => {
'output' => 'pg_statio_user_indexes.csv',
'command' => 'dump_pgstatioindexes_user',
'repeat' => 1,
},
'all_sequences_io_stats' => {
'output' => 'pg_statio_all_sequences.csv',
'command' => 'dump_pgstatiosequences',
'repeat' => 1,
},
'user_sequences_io_stats' => {
'output' => 'pg_statio_user_sequences.csv',
'command' => 'dump_pgstatiosequences_user',
'repeat' => 1,
},
'functions_stats' => {
'output' => 'pg_stat_user_functions.csv',
'command' => 'dump_pgstatuserfunctions',
'repeat' => 1,
},
'xact_functions_stats' => {
'output' => 'pg_stat_xact_user_functions.csv',
'command' => 'dump_pgstatxactuserfunctions',
'repeat' => 1,
},
'all_xact_tables_stats' => {
'output' => 'pg_stat_xact_all_tables.csv',
'command' => 'dump_pgstatxacttables',
'repeat' => 1,
},
'user_xact_tables_stats' => {
'output' => 'pg_stat_xact_user_tables.csv',
'command' => 'dump_pgstatxacttables_user',
'repeat' => 1,
},
'class_size_stats' => {
'output' => 'pg_class_size.csv',
'command' => 'dump_pgclass_size',
'repeat' => 1,
'override' => 1,
},
'lock_types' => {
'output' => 'pg_stat_locks.csv',
'command' => 'dump_pgstatlocktypes',
'repeat' => 1,
},
'lock_modes' => {
'output' => 'pg_stat_locks.csv',
'command' => 'dump_pgstatlockmodes',
'repeat' => 1,
},
'lock_granted' => {
'output' => 'pg_stat_locks.csv',
'command' => 'dump_pgstatlockgranted',
'repeat' => 1,
},
'statements_stats' => {
'output' => 'pg_stat_statements.csv',
'command' => 'dump_pgstatstatements'
},
'xlog_stats' => {
'output' => 'pg_xlog_stat.csv',
'command' => 'dump_xlog_stat'
},
'database_size_stats' => {
'output' => 'pg_database_size.csv',
'command' => 'dump_pgdatabase_size'
},
'connections_stats' => {
'output' => 'pg_stat_connections.csv',
'command' => 'dump_pgstatconnections'
},
'pgbouncer_stats' => {
'output' => 'pgbouncer_stats.csv',
'command' => 'dump_pgbouncerpoolstats'
},
'pgbouncer_req_stats' => {
'output' => 'pgbouncer_req_stats.csv',
'command' => 'dump_pgbouncerquerystats'
},
'unused_indexes_stats' => {
'output' => 'pg_stat_unused_indexes.csv',
'command' => 'dump_unusedindexes',
'repeat' => 1,
'override' => 1,
},
'redundant_indexes_stats' => {
'output' => 'pg_stat_redundant_indexes.csv',
'command' => 'dump_redundantindexes',
'repeat' => 1,
'override' => 1,
},
'missing_fkindexes_stats' => {
'output' => 'pg_stat_missing_fkindexes.csv',
'command' => 'dump_missingfkindexes',
'repeat' => 1,
'override' => 1,
},
'pg_settings' => {
'output' => 'pg_settings.csv',
'command' => 'dump_pgsettings',
'repeat' => 1,
'override' => 1,
},
'database_buffercache_stats' => {
'output' => 'pg_database_buffercache.csv',
'command' => 'dump_pgdatabase_buffercache'
},
'database_usagecount_stats' => {
'output' => 'pg_database_usagecount.csv',
'command' => 'dump_pgdatabase_usercount'
},
'database_isdirty_stats' => {
'output' => 'pg_database_isdirty.csv',
'command' => 'dump_pgdatabase_isdirty'
},
# 'relation_buffercache_stats' => {
# 'output' => 'pg_relation_buffercache.csv',
# 'command' => 'dump_pgrelation_buffercache',
# },
);
# Process command line options and look for an action keyword. There
# are no mandatory options.
my $result = GetOptions(
"d|dbname=s" => \$DBNAME,
"D|daemonize!" => \$DAEMONIZE,
"f|pid-file=s" => \$PIDFILE,
"h|host=s" => \$DBHOST,
"i|interval=i" => \$INTERVAL,
"k|kill!" => \$KILL,
"m|metric=s" => \@METRICS,
"p|port=i" => \$DBPORT,
"P|psql=s" => \$PSQL_PROG,
"s|sar=s" => \$SAR_PROG,
"S|disable-sar!" => \$DISABLE_SAR,
"T|notablespace!"=> \$NOTABLESPACE,
"U|dbuser=s" => \$DBUSER,
"W|password=s" => \$DBPASS,
"pgversion=s" => \$PG_VERSION,
"pgservice=s" => \$DBSERVICE,
"help!" => \$HELP,
"stat-type=s" => \$STAT_TYPE,
"sar-file=s" => \$SAR_FILE,
"list-metric!" => \$LIST_METRIC,
"pgbouncer-args=s" => \$PGBOUNCER_ARGS,
"os-info!" => \$OS_INFO,
"included-db=s" => \$INCLUDED_DB,
"exclude-time=s" => \$SKIP_HOURS,
) or die &usage();
# The daemon should be stopped
if ($KILL) {
if (-e "$PIDFILE") {
system("kill -15 `cat $PIDFILE`");
exit 0;
} else {
die "ERROR: can't find $PIDFILE, is $PROGRAM running?\n";
}
}
# Display usage if help is asked
&usage if $HELP;
# Set the multi host information
my @MULTI_HOST_INFO = ();
my @dbnames = split(/,/, $DBNAME);
my @dbports = split(/,/, $DBPORT);
my @dbhosts = split(/,/, $DBHOST);
my @dbusers = split(/,/, $DBUSER);
my @dbpass = split(/,/, $DBPASS);
for (my $i = 0; $i <= $#dbhosts; $i++) {
push(@MULTI_HOST_INFO, { 'ip' => $dbhosts[$i] || 'localhost', 'port' => $dbports[$i] || 5432, 'db' => $dbnames[$i] || 'postgres', 'user' => $dbusers[$i] || 'postgres', 'password' => $dbpass[$i] || ''});
}
# Get the output dir from command line
my $OUTPUT_DIR = $ARGV[0] || '';
# List metrics and associated SQL commands
if ($LIST_METRIC) {
# Detect PostgreSQL version
&fetch_version() if ($PG_VERSION);
print "List of available metrics:\n\n";
foreach my $c (sort {$a cmp $b} keys %METRICS_COMMANDS) {
next if (($c =~ /^(user|all)_/) && ($c !~ /^$STAT_TYPE/));
$c =~ s/_stats$//;
print "\t$c\n";
}
print "\n";
exit 0;
}
# Check if an other process is already running
if (-f $PIDFILE) {
&dprint("FATAL: an other process is already started, see pid in $PIDFILE\n");
exit 1;
}
# Check excluded times
if ($SKIP_HOURS) {
my $tmp = $SKIP_HOURS;
my @timerange = split(/[\s\t]+/, $tmp);
foreach $tmp (@timerange) {
next if (!$tmp);
if ($tmp =~ m#(\d{2}):(\d{2})-(\d{2}):(\d{2})#) {
push(@SKIP_BEGIN, "$1$2");
push(@SKIP_END, "$3$4");
} else {
&dprint("FATAL: Bad time range: $tmp. Format of exclusion time must be: HH:MM-HH:MM\n");
}
}
}
# Validate action(s) to execute
if ($#METRICS >= 0) {
my @list_metric = ();
push(@list_metric, $METRICS[0]);
@METRICS = ();
foreach my $a (@list_metric) {
if (!grep(/^${a}_stats$/, keys %METRICS_COMMANDS)) {
&dprint("FATAL: metric $a does not exist. Use --list-metric to show the available metrics.\n");
exit 1;
} else {
push(@METRICS, "${a}_stats");
}
}
}
# Set the default actions outside Nagios mode
# Perform all metrics actions per default
push(@METRICS, sort {$a cmp $b} keys %METRICS_COMMANDS);
# Create output directory if not exists
if (!$OUTPUT_DIR) {
&dprint("FATAL: no output directory\n");
&usage();
} else {
# Ensure this is not a relative path
if (dirname($OUTPUT_DIR) eq '.') {
&dprint("FATAL: output directory ($OUTPUT_DIR) is not an absolute path.\n");
exit 1;
}
}
if (!-d $OUTPUT_DIR) {
&dprint("FATAL: output directory $OUTPUT_DIR doesn't exists\n");
exit 1;
} else {
# Check if we can write in this directory
unless(open(OUT, ">$OUTPUT_DIR/wtest")) {
&dprint("FATAL: can't write into output directory $OUTPUT_DIR\n");
exit 1;
}
unlink("$OUTPUT_DIR/wtest");
}
# Go to that directory
chdir($OUTPUT_DIR);
# Get Os information and exit
if ($OS_INFO) {
&grab_os_information();
exit 0;
}
# Die cleanly on signal
sub terminate
{
# block signal
local $SIG{TERM} = 'IGNORE';
local $SIG{INT} = 'IGNORE';
local $SIG{QUIT} = 'IGNORE';
&dprint("LOG: Received terminating signal.\n");
if (-f $PIDFILE) {
unlink("$PIDFILE") or &dprint("ERROR: Unable to remove pid file $PIDFILE, $!\n");
}
exit 0;
}
# Die on kill -2, -3 or -15
$SIG{'INT'} = $SIG{'QUIT'} = $SIG{'TERM'} = 'terminate';
# Run in interactive mode if required
if (!$DAEMONIZE) {
# Start in interactive mode
print "\n*** $PROGRAM v$VERSION (pid:$$) started at " . localtime(time) . "\n";
print "Type Ctrl+c to quit.\n\n";
} else {
# detach from terminal
my $pid = fork;
exit 0 if ($pid);
die "FATAL: Couldn't fork: $!" unless defined($pid);
POSIX::setsid() or die "Can't detach: \$!";
&dprint("LOG: Detach from terminal with pid: $$\n");
open(STDIN, "/dev/null");
open(STDOUT, ">/dev/null");
open(STDERR, ">/dev/null");
}
# Set name of the program without path
my $orig_name = $0;
$0 = $PROGRAM;
# Create pid file
unless(open(OUT, ">$PIDFILE")) {
&dprint("FATAL: can't create pid file $PIDFILE, $!\n");
exit 1;
}
print OUT $$;
close(OUT);
# Get Os information
&grab_os_information();
my $sysstat_version = &sysstat_version() || '';
# Generate the psql command
$PSQL_PROG .= " -At -F';' -f - ";
my $PGBOUNCER_PROG = $PSQL_PROG . ' ' . $PGBOUNCER_ARGS . ' pgbouncer';
$PSQL_PROG .= " -h $DBHOST" if ($DBHOST);
$PSQL_PROG .= " -p $DBPORT" if ($DBPORT);
$PSQL_PROG .= " -U $DBUSER" if ($DBUSER);
$PSQL_PROG .= " -d $dbnames[0]" if ($#dbnames >= 0);
if ($DBPASS) {
$ENV{PGPASSWORD} = $DBPASS;
}
# Generate the sar command
my $sar_command = "LC_ALL=C $SAR_PROG -t -p -A 1 1 >>$SAR_FILE";
# Remove action that can't be run with the PostgreSQL version
&verify_action();
# Check if the connection database has pg_buffercache installed
if (!&has_pg_buffercache()) {
delete $METRICS_COMMANDS{'database_buffercache_stats'};
delete $METRICS_COMMANDS{'database_usagecount_stats'};
delete $METRICS_COMMANDS{'relation_buffercache_stats'};
delete $METRICS_COMMANDS{'database_isdirty_stats'};
}
# Generating global statistics collector SQL script
my $script_sql = &create_sql_script();
if (!$script_sql) {
# No action can be perform with this PostgreSQL version
&dprint("FATAL: no action will be run on this PostgreSQL version $DB_INFO{major}.$DB_INFO{minor}, $!\n");
exit 1;
}
# Get list of database in the PostgreSQL cluster
my @alldbs = ();
if ($#dbnames >= 0) {
# from command line
push(@alldbs, @dbnames);
} else {
# or by querying the database list
@alldbs = &get_databases();
}
# Collect general information about each database
if (&backend_minimum_version(9, 1) && ($#alldbs > -1)) {
my @extensions = ();
my @schemas = ();
my @procs = ();
my @trigs = ();
unless(open(OUT, ">>$OUTPUT_DIR/sysinfo.txt")) {
&dprint("FATAL: can't write into output directory $OUTPUT_DIR\n");
exit 1;
}
# Look for all installed extensions
print OUT "[EXTENSION]\n";
foreach my $db (@alldbs) {
my @ext = &get_extensions($db);
push(@extensions, "$db=" . join(',', @ext)) if ($#ext >= 0);
}
foreach my $e (@extensions) {
print OUT "$e\n";
}
# Look for all schema in a database
print OUT "[SCHEMA]\n";
foreach my $db (@alldbs) {
my @sch = &get_schemas($db);
push(@schemas, "$db=" . join(',', @sch)) if ($#sch >= 0);
}
foreach my $s (@schemas) {
print OUT "$s\n";
}
# Look for all schema in a database
print OUT "[PROCEDURE]\n";
foreach my $db (@alldbs) {
my @pro = &get_proc_name($db);
push(@procs, "$db=" . join(',', @pro)) if ($#pro >= 0);
}
foreach my $p (@procs) {
print OUT "$p\n";
}
# Look for all schema in a database
print OUT "[TRIGGER]\n";
foreach my $db (@alldbs) {
my $tgs = &get_triggers($db);
push(@trigs, "$db=$tgs");
}
foreach my $t (@trigs) {
print OUT "$t\n";
}
close(OUT);
}
# Copy configuration files into output directory
my @conf_files = &get_configuration_files();
foreach my $f (@conf_files, '/etc/pgbouncer/pgbouncer.ini') {
`$CP_PROG $f $OUTPUT_DIR/ >/dev/null 2>&1`;
}
# Look if we should limit statistic collect to some DB
my @included_dbs = split(/,/, $INCLUDED_DB);
while (1) {
# Some time range may not collect data
my ($sec , $min, $hour, @other) = localtime(time);
$min = "0$min" if ($min < 10);
$hour = "0$hour" if ($hour < 10);
for (my $i = 0; $i <= $#SKIP_BEGIN; $i++) {
if ( $SKIP_BEGIN[$i] <= $SKIP_END[$i] ) {
if ( ("$hour$min" >= $SKIP_BEGIN[$i]) && ("$hour$min" <= $SKIP_END[$i]) ) {
# Wait next run
sleep($INTERVAL);
next;
}
} elsif ( $SKIP_BEGIN[$i] > $SKIP_END[$i] ) {
if ( ("$hour$min" >= $SKIP_BEGIN[$i]) && ("$hour$min" < 2400) ||
("$hour$min" <= $SKIP_END[$i]) && ("$hour$min" > 0)) {
# Wait for next run
sleep($INTERVAL);
next;
}
}
}
# Collecting database statistics
open(PSQL, "| $PSQL_PROG");
print PSQL $script_sql, "\n";
close(PSQL);
# Get database list
my @dblist = &get_databases();
push(@dblist, $DBNAME) if (($#dblist == -1) && $DBNAME);
# Remove files that must be overriden
foreach my $type (sort {$a cmp $b} keys %METRICS_COMMANDS) {
if (($METRICS_COMMANDS{$type}->{override}) && -e "$OUTPUT_DIR/$METRICS_COMMANDS{$type}->{output}") {
unlink("$OUTPUT_DIR/$METRICS_COMMANDS{$type}->{output}");
}
}
# Generating per database statistics collector SQL script
foreach my $db (@dblist) {
next if (($#included_dbs >= 0) && !grep(/^$db$/i, @included_dbs));
my $script_repeat_sql = &create_sql_script($db);
if (!$script_repeat_sql) {
# No action can be perform with this PostgreSQL version
&dprint("FATAL: no action will be run on this PostgreSQL version $DB_INFO{major}.$DB_INFO{minor}, $!\n");
last;
}
my $LOCAL_PSQL_PROG = $PSQL_PROG;
if ($db && ($LOCAL_PSQL_PROG !~ s/-d $dbnames[0]/-d $db/i)) {
$LOCAL_PSQL_PROG .= " -d $db";
}
# Collecting database statistics
open(PSQL, "| $LOCAL_PSQL_PROG");
print PSQL $script_repeat_sql, "\n";
close(PSQL);
}
# Collecting pgbouncer statistics
if ($PGBOUNCER_ARGS) {
foreach my $c (@METRICS) {
next if ($c !~ /^pgbouncer_/);
# create a timestamp to registrer pgbouncer statistics
my $timestamp = &get_current_timestamp();
my $sql = '';
eval { $sql = &{$METRICS_COMMANDS{$c}->{command}}; };
if (!$sql || $@) {
if (-f $PIDFILE) {
unlink("$PIDFILE") or &dprint("ERROR: Unable to remove pid file $PIDFILE, $!\n");
}
die "FATAL: no SQL with metric command pgbouncer_stats ($sql).\n" if (!$sql || $@);
}
`$PGBOUNCER_PROG -c "$sql" | sed 's/^/$timestamp;/' $FILE_REDIR $OUTPUT_DIR/$METRICS_COMMANDS{$c}->{output}`;
if ($? != 0) {
&dprint("LOG: $PGBOUNCER_PROG -c \"$sql\" | sed 's/^/$timestamp;/' $FILE_REDIR $OUTPUT_DIR/$METRICS_COMMANDS{$c}->{output}\n");
&dprint("ERROR: pgbouncer pool query failure, $!\n");
}
}
}
# Collecting system statistics
if (!$DISABLE_SAR && ($sysstat_version > -1)) {
&dprint(`$sar_command`);
}
# Wait next run and allow signal
sleep($INTERVAL);
}
exit 0;
sub verify_action
{
# Detect PostgreSQL version
&fetch_version();
# Has pg_stat_statements ?
&backend_has_pgstatstatements();
if (!&backend_minimum_version(8, 3)) {
delete $METRICS_COMMANDS{'bgwriter_stats'};
delete $METRICS_COMMANDS{'pg_buffercache_stats'};
}
if (!&backend_minimum_version(9, 1)) {
delete $METRICS_COMMANDS{'conflict_stats'};
delete $METRICS_COMMANDS{'replication_stats'};
}
if (!&backend_minimum_version(9, 0)) {
delete $METRICS_COMMANDS{'hot_standby_delay'};
delete $METRICS_COMMANDS{'user_xact_tables_stats'};
delete $METRICS_COMMANDS{'all_xact_tables_stats'};
delete $METRICS_COMMANDS{'xact_functions_stats'};
}
if (!&backend_minimum_version(8, 4)) {
delete $METRICS_COMMANDS{'functions_stats'};
delete $METRICS_COMMANDS{'redundant_indexes_stats'};
}
if (!&backend_minimum_version(8, 2)) {
delete $METRICS_COMMANDS{'xlog_stats'};
}
if (!$DB_INFO{has_stat_statement}) {
delete $METRICS_COMMANDS{'statements_stats'};
}
if (!&is_superuser($DBUSER)) {
delete $METRICS_COMMANDS{'xlog_stats'};
}
if ($NOTABLESPACE) {
delete $METRICS_COMMANDS{'tablespace_size_stats'};
}
}
sub create_sql_script
{
my $db = shift;
# Prepare the SQL script
my $sql_queries = '';
foreach my $type (sort {$a cmp $b} keys %METRICS_COMMANDS) {
next if (!$db && $METRICS_COMMANDS{$type}->{repeat});
next if ($db && !$METRICS_COMMANDS{$type}->{repeat});
next if ($type =~ /^pgbouncer_/);
next if (($type =~ /^(user|all)_/) && ($type !~ /^$STAT_TYPE/));
next if (($#METRICS >= 0) && !grep(/^$type$/, @METRICS));
my $sql = $METRICS_COMMANDS{$type}->{command}->();
if (!$sql) {
if (-f $PIDFILE) {
unlink("$PIDFILE") or &dprint("ERROR: Unable to remove pid file $PIDFILE, $!\n");
}
die "FATAL: no SQL with metric command $type ($sql).\n";
}
$sql_queries .= <<EOF
-- $type
\\o | cat $FILE_REDIR $OUTPUT_DIR/$METRICS_COMMANDS{$type}->{output}
CREATE TEMP TABLE __pgcluu as $sql;
COPY __pgcluu TO STDOUT CSV DELIMITER ';';
DROP TABLE __pgcluu;
EOF
}
return $sql_queries
}
sub fetch_version
{
if ($PG_VERSION) {
if ($PG_VERSION =~ /^(\d+)\.(\d+)/) {
$DB_INFO{major} = $1;
$DB_INFO{minor} = $2;
return "$1.$2";
}
}
my $pg_ver = `$PSQL_PROG -c "SELECT version();"`;
if ($? != 0) {
&dprint("FATAL: psql error.\n");
# remove the pidfile
if (-f $PIDFILE) {
unlink $PIDFILE or &dprint("ERROR: Unable to remove pidfile: $!\n");
}
exit 0;
}
chomp($pg_ver);
if ($pg_ver =~ /^PostgreSQL (\d+)\.(\d+)/) {
$DB_INFO{major} = $1;
$DB_INFO{minor} = $2;
}
unless(open(OUT, ">>$OUTPUT_DIR/sysinfo.txt")) {
&dprint("FATAL: can't write into output directory $OUTPUT_DIR\n");
exit 1;
}
print OUT "[PGVERSION]\n";
print OUT "$pg_ver\n";
close(OUT);
return "$1.$2";
}
####
# Retrieve installed extension for a given database.
####
sub get_extensions
{
my $database = shift;
my $LOCAL_PSQL_PROG = $PSQL_PROG;
if ($database && ($LOCAL_PSQL_PROG !~ s/-d $dbnames[0]/-d $database/i)) {
$LOCAL_PSQL_PROG .= " -d $database";
}
my @db_extension = `$LOCAL_PSQL_PROG -c "SELECT extname FROM pg_extension;"`;
if ($? != 0) {
&dprint("FATAL: psql error.\n");
# remove the pidfile
if (-f $PIDFILE) {
unlink $PIDFILE or &dprint("ERROR: Unable to remove pidfile: $!\n");
}
exit 0;
}
chomp(@db_extension);
return @db_extension;
}
####
# Get the list of database that are not template and that allow connction
####
sub get_databases
{
my @dbs = `$PSQL_PROG -c "SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn;"`;
if ($? != 0) {
&dprint("FATAL: psql error.\n");
# remove the pidfile
if (-f $PIDFILE) {
unlink $PIDFILE or &dprint("ERROR: Unable to remove pidfile: $!\n");
}
exit 0;
}
chomp(@dbs);
return @dbs;
}
####
# Retrieve schemas for a given database.
####
sub get_schemas
{
my $database = shift;
my $LOCAL_PSQL_PROG = $PSQL_PROG;
if ($database && ($LOCAL_PSQL_PROG !~ s/-d $dbnames[0]/-d $database/i)) {
$LOCAL_PSQL_PROG .= " -d $database";
}
my @db_schema = `$LOCAL_PSQL_PROG -c "SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_' AND nspname <> 'information_schema' ORDER BY 1"`;
if ($? != 0) {
&dprint("FATAL: psql error.\n");
# remove the pidfile
if (-f $PIDFILE) {
unlink $PIDFILE or &dprint("ERROR: Unable to remove pidfile: $!\n");
}
exit 0;
}
chomp(@db_schema);
return @db_schema;
}
####
# Check if the database have the pg_buffercache extension
####
sub has_pg_buffercache
{
my $hasit = `$PSQL_PROG -c "SELECT proname FROM pg_proc WHERE proname = 'pg_buffercache_pages';"`;
if ($? != 0) {
&dprint("FATAL: psql error.\n");
# remove the pidfile
if (-f $PIDFILE) {
unlink $PIDFILE or &dprint("ERROR: Unable to remove pidfile: $!\n");
}
exit 0;
}
chomp($hasit);
return $hasit;
}
sub backend_has_pgstatstatements
{
$DB_INFO{has_stat_statement} = `$PSQL_PROG -c "SELECT 1 FROM pg_proc p, pg_namespace n WHERE p.proname='pg_stat_statements' AND p.pronamespace=n.oid"`;
}
sub is_superuser
{
my $usr = shift;
# Assume it is superuser per default. In any case this will raise a psql error.
return 1 if (!$usr);
$DB_INFO{is_superuser} = `$PSQL_PROG -c "SELECT 1 FROM pg_user WHERE usename='$usr' AND usesuper"`;
}
sub sysstat_version
{
if (!$DISABLE_SAR) {
my $ver = 0;
$ver = `LC_ALL=C $SAR_PROG -V 2>&1 | grep "sysstat version"`;
if ($?) {
&dprint("ERROR: $SAR_PROG execution failure: $!\n");
return -1;
}
if ($ver =~ m!^sysstat version (\d+)\.!) {
return $1;
}
}
return -1;
}
sub grab_os_information
{
# Look at CPU informations
my @cpuinfo = `cat /proc/cpuinfo | grep -E "model name|cpu MHz|cache size|cpu cores|processor" 2>/dev/null`;
# Look at kernel informations
my $kernel_info = `uname -a 2>/dev/null`;
# Look at memory informations
my @meminfo = `cat /proc/meminfo 2>/dev/null`;
# Look at filesystem informations
my @dfinfo = `df -h 2>/dev/null`;
# Mount informations
my @mountinfo = `mount -l 2>/dev/null`;
# Fstab informations
my @fstabinfo = `cat /etc/fstab | grep -v "^#" 2>/dev/null`;
# PCI information
my @pciinfo = `lspci 2>/dev/null`;
# Release informations
my @releaseinfo = `cat /etc/*release 2>/dev/null`;
# System kernel tuning parameters
my @system = `/sbin/sysctl -a 2>/dev/null| grep -E "vm.overcommit|vm.dirty_.*ratio|swappiness|zone_reclaim_mode|shmmax|shmall"`;
unless(open(OUT, ">$OUTPUT_DIR/sysinfo.txt")) {
&dprint("FATAL: can't write into output directory $OUTPUT_DIR\n");
exit 1;
}
print OUT "[CPU]\n";
print OUT @cpuinfo;
print OUT "[KERNEL]\n";
print OUT $kernel_info;
print OUT "[MEMORY]\n";
print OUT @meminfo;
print OUT "[DF]\n";
print OUT @dfinfo;
print OUT "[MOUNT]\n";
print OUT @mountinfo;
print OUT "[FSTAB]\n";
print OUT @fstabinfo;
print OUT "[PCI]\n";
print OUT @pciinfo;
print OUT "[RELEASE]\n";
print OUT @releaseinfo;
print OUT "[SYSTEM]\n";
print OUT @system;
close(OUT);
}
sub usage
{
print qq{
usage: $PROGRAM [options] output_dir
output_dir: full path to directory where pgcluu_collectd will
store statistics.
options:
-d, --dbname=DATABASE database name to connect to. Default to current user.
-D, --daemonize detach from console and enter in daemon mode.
-f, --pid-file=FILE path to pid file. Default: $PIDFILE.
-h, --host=HOSTNAME database server host or socket directory
-i, --interval=NUM time to wait between runs
-k, --kill stop current $PROGRAM running daemon.
-m, --metric=METRIC set a coma separated list of metrics to perform.
-p, --port=PORT database port(s) to connect to. Defaults to 5432.
-P, --psql=BIN path to the psql command. Default: $PSQL_PROG.
-s, --sar=BIN path to sar sysstat command. Default: $SAR_PROG.
-S, --disable-sar disable collect of system statistics with sar.
-T, --notablespace disable lookup at tablespace when the connect user
is not superuser to avoid printing an error message.
-U, --dbuser=USERNAME database user to connect as. Default to current user.
--included-db=DATABASE do not collect statistics for the comma separated list
of database name.
--list-metric list available metrics actions that can be performed.
--os-info grab operating system information and exit.
--pgbouncer-args=OPTIONS Option to used to connect to the pgbouncer system
database. Ex: -p 6432 -U postgres -h 192.168.1.100
You must at least give one parameter to enable
pgbouncer monitoring.
--sar-file=FILE path to sar output data file for sysstat stats
Default to output_dir/sar_stats.dat.
--stat-type all|user Set stats tables to read. Values: 'all' or 'user' to
look at pg_stat_(all|user) tables. Default: user.
--pgversion X.Y force the PostgreSQL version to the given value.
--pgservice NAME Name of service inside of the pg_service.conf file.
--exclude-time RANGE exclude a laps of time by giving the start and end
hours.
--help print usage
For example, as postgres user:
mkdir /tmp/stat_db1/
pgcluu_collectd -D -i 60 /tmp/stat_db1/ -h 10.10.1.1 -U postgres -d mydb
to collect statistics from pgbouncer too:
pgcluu_collectd -D -i 60 /tmp/stat_db1/ -h 10.10.1.1 -U postgres -d mydb \
--pgbouncer-args='-p 5342'
to disable statistics collect between 22:30 and 06:30 the next day:
pgcluu_collectd -D -i 60 /tmp/stat_db1/ --exclude-time "22:30-06:30"
then after some time and activities on the database, stop the daemon:
pgcluu_collectd -k
};
exit 1
}
sub dprint
{
foreach (@_) {
next if (/^DEBUG:/s && !$DEBUG);
print "$_"
}
}
# Compare given major and minor numbers to the one of the connected server
sub backend_minimum_version
{
my ($major, $minor) = @_;
return if (!$major);