forked from darold/pgcluu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgcluu_collectd
executable file
·3504 lines (3060 loc) · 100 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-2024 Gilles Darold - All rights reserved.
#------------------------------------------------------------------------------
use vars qw($VERSION $PROGRAM);
use strict qw(vars subs);
use File::Basename;
use IO::File;
use POSIX;
use Getopt::Long qw(:config bundling no_ignore_case_always);
use POSIX qw(locale_h sys_wait_h);
setlocale(LC_ALL, 'C');
# Change MASK to 0027 if you want to secure the data directory
# Note that in CGI mode the www-data user or group need read
# access to all files in the statistics directory.
use constant UMASK => 0022;
$| = 1;
$VERSION = '4.0';
$PROGRAM = 'pgcluu_collectd';
$SIG{'CHLD'} = 'DEFAULT';
# Default path to the external programs
# They can be specified into command line options
my $SAR_PROG = 'sar';
my $PSQL_PROG = 'psql';
my $CAT_PROG = 'cat ';
my $PIDSTAT_PROG = 'pidstat';
# Global variables
my $CONFIG_FILE = "/usr/local/etc/pgcluu.conf";
my $SAR_FILE = 'sar_stats.dat';
my $PIDSTAT_FILE = 'pidstat_stats.dat';
my $PIDFILE = "/var/run/postgresql/pgcluu_collectd.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 = ();
my $USE_BUFFERCACHE = 0;
my $NO_STATEMENTS = 0;
my $NO_WAITEVENT = 0;
my $NO_PGSTATS_DUMP = 0;
my $NO_SYSINFO = 0;
my $SHOW_VER = 0;
my $END_AFTER = 0;
my $MAX_SIZE = 0;
my $END_AFTER_COUNTER = 0;
my $NO_DATABASE = 0;
my $D_ROTATE = 0;
my $H_ROTATE = 0;
my $RETENTION = 0;
my $OUT_DIR = '.';
my $COMPRESS = 0;
my $OLD_OUT_DIR = '';
my $COLLECT_PID = 0;
my $COMPRESS_PID = 0;
my $GZIP_PROG = '/bin/gzip';
my $INCREMENTAL = 0;
my $CAPTURE = 0;
my $TAR_PROG = 'tar -czf';
my $CAPTURE_DIR = '/tmp';
my $DIFF_PROG = 'diff -U 0';
my $CRONUSER = '';
my $PKG_LIST_PROG = '';
my $DF_COMMAND = 'LANG=C df --output="source,size,used,avail,itotal,iused,iavail,fstype,target" -x squashfs -x tmpfs -x devtmpfs';
my $SAR_PID = 0;
my $PIDSTAT_PID = 0;
my $LOCK_TIMEOUT = 3;
my $DISABLE_PIDSTAT = 0;
# Global storage of extensions installed in each database
my @extensions = ();
# Set the default mask for file and directory creation
umask(UMASK);
# Stores starting time
my $START_TIME = time();
# Variables related to remote ssh connection
my $USE_SSH = '';
my $SSH_COMMAND = '';
my $SSH_BIN = 'ssh';
my $SSH_IDENTITY = '';
my $SSH_USER = '';
my $SSH_TIMEOUT = 10;
my $SSH_OPTIONS = "-o ConnectTimeout=$SSH_TIMEOUT -o PreferredAuthentications=hostbased,publickey";
my $ALWAYS_SECURE_SEARCH_PATH_SQL = "SELECT pg_catalog.set_config('search_path', '', false);";
# Variable to store previous settings
my %ORIGINAL_PG_SETTINGS = ();
my %ORIGINAL_DBROLE_SETTINGS = ();
my %ORIGINAL_SYSTEM_SETTINGS = ();
# Register a termination signal
my $fini = 0;
my $done = 0;
my $initial_run = 1;
# 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'
},
'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,
'start-end' => 1,
},
'user_tables_stats' => {
'output' => 'pg_stat_user_tables.csv',
'command' => 'dump_pgstattables_user',
'repeat' => 1,
'start-end' => 1,
},
'all_tables_io_stats' => {
'output' => 'pg_statio_all_tables.csv',
'command' => 'dump_pgstatiotables',
'repeat' => 1,
'start-end' => 1,
},
'user_tables_io_stats' => {
'output' => 'pg_statio_user_tables.csv',
'command' => 'dump_pgstatiotables_user',
'repeat' => 1,
'start-end' => 1,
},
'all_indexes_stats' => {
'output' => 'pg_stat_all_indexes.csv',
'command' => 'dump_pgstatindexes',
'repeat' => 1,
'start-end' => 1,
},
'user_indexes_stats' => {
'output' => 'pg_stat_user_indexes.csv',
'command' => 'dump_pgstatindexes_user',
'repeat' => 1,
'start-end' => 1,
},
'all_indexes_io_stats' => {
'output' => 'pg_statio_all_indexes.csv',
'command' => 'dump_pgstatioindexes',
'repeat' => 1,
'start-end' => 1,
},
'user_indexes_io_stats' => {
'output' => 'pg_statio_user_indexes.csv',
'command' => 'dump_pgstatioindexes_user',
'repeat' => 1,
'start-end' => 1,
},
'all_sequences_io_stats' => {
'output' => 'pg_statio_all_sequences.csv',
'command' => 'dump_pgstatiosequences',
'repeat' => 1,
'start-end' => 1,
},
'user_sequences_io_stats' => {
'output' => 'pg_statio_user_sequences.csv',
'command' => 'dump_pgstatiosequences_user',
'repeat' => 1,
'start-end' => 1,
},
'functions_stats' => {
'output' => 'pg_stat_user_functions.csv',
'command' => 'dump_pgstatuserfunctions',
'repeat' => 1,
'start-end' => 1,
},
'xact_functions_stats' => {
'output' => 'pg_stat_xact_user_functions.csv',
'command' => 'dump_pgstatxactuserfunctions',
'repeat' => 1,
'start-end' => 1,
},
'all_xact_tables_stats' => {
'output' => 'pg_stat_xact_all_tables.csv',
'command' => 'dump_pgstatxacttables',
'repeat' => 1,
'start-end' => 1,
},
'user_xact_tables_stats' => {
'output' => 'pg_stat_xact_user_tables.csv',
'command' => 'dump_pgstatxacttables_user',
'repeat' => 1,
'start-end' => 1,
},
'class_size_stats' => {
'output' => 'pg_class_size.csv',
'command' => 'dump_pgclass_size',
'repeat' => 1,
'override' => 1,
},
'lock_types_stats' => {
'output' => 'pg_stat_locks.csv',
'command' => 'dump_pgstatlocktypes',
'repeat' => 1,
},
'lock_modes_stats' => {
'output' => 'pg_stat_locks.csv',
'command' => 'dump_pgstatlockmodes',
'repeat' => 1,
},
'lock_granted_stats' => {
'output' => 'pg_stat_locks.csv',
'command' => 'dump_pgstatlockgranted',
'repeat' => 1,
},
'statements_stats' => {
'output' => 'pg_stat_statements.csv',
'command' => 'dump_pgstatstatements',
'override' => 1,
},
'waitevent_stats' => {
'output' => 'pg_stat_waitevent.csv',
'command' => 'dump_pgwaitsampling',
'repeat' => 1,
},
'subxact_stats' => {
'output' => 'pg_subxact_counters.csv',
'command' => 'dump_pgsubxactcounters',
},
'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,
},
'invalid_indexes_stats' => {
'output' => 'pg_stat_invalid_indexes.csv',
'command' => 'dump_invalidindexes',
'repeat' => 1,
'override' => 1,
},
'hash_indexes_stats' => {
'output' => 'pg_stat_hash_indexes.csv',
'command' => 'dump_hashindexes',
'repeat' => 1,
'override' => 1,
},
'missing_fkindexes_stats' => {
'output' => 'pg_stat_missing_fkindexes.csv',
'command' => 'dump_missingfkindexes',
'repeat' => 1,
'override' => 1,
},
'count_indexes_stats' => {
'output' => 'pg_stat_count_indexes.csv',
'command' => 'dump_count_indexes',
'repeat' => 1,
'override' => 1,
},
'unused_trigfunc_stats' => {
'output' => 'pg_stat_unused_trigfunc.csv',
'command' => 'dump_unusedtrigfunc',
'repeat' => 1,
'override' => 1,
},
'pg_settings_stats' => {
'output' => 'pg_settings.csv',
'command' => 'dump_pgsettings',
'repeat' => 1,
'override' => 1,
},
'pg_nondefault_settings_stats' => {
'output' => 'pg_nondefault_settings.csv',
'command' => 'dump_nondefault_pgsettings',
'repeat' => 1,
'override' => 1,
},
'pg_db_role_setting_stats' => {
'output' => 'pg_db_role_setting.csv',
'command' => 'dump_pgdbrolesetting',
'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',
},
'archiver_stats' => {
'output' => 'pg_stat_archiver.csv',
'command' => 'dump_pgstatarchiver',
},
'configuration_stats' => {
'output' => '',
'command' => 'get_configuration_files',
},
'unlogged_stats' => {
'output' => 'pg_stat_unlogged.csv',
'command' => 'dump_unlogged',
'repeat' => 1,
'override' => 1,
},
'prepared_stats' => {
'output' => 'pg_prepared_xact.csv',
'command' => 'dump_preparedxactstats'
},
'statistics_stats' => {
'output' => 'pg_stat_ext.csv',
'command' => 'dump_statisticsext',
'repeat' => 1,
'override' => 1,
},
'stats_stats' => {
'output' => 'pg_stats.csv',
'command' => 'dump_pg_stats_view',
'repeat' => 1,
'start-end' => 1,
},
);
# Read configuration file before reading command line parameters
&read_conf();
# Process command line options and look for an action keyword. There
# are no mandatory options.
my $result = GetOptions(
"B|enable-buffercache!" => \$USE_BUFFERCACHE,
"c|capture!" => \$CAPTURE,
"C|end-counter=s"=> \$END_AFTER_COUNTER,
"d|dbname=s" => \$DBNAME,
"D|daemonize!" => \$DAEMONIZE,
"E|end-after=s" => \$END_AFTER,
"f|pid-file=s" => \$PIDFILE,
"h|host=s" => \$DBHOST,
"i|interval=i" => \$INTERVAL,
"I|incremental!" => \$INCREMENTAL,
"k|kill!" => \$KILL,
"m|metric=s" => \@METRICS,
"M|max-size=s" => \$MAX_SIZE,
"p|port=i" => \$DBPORT,
"P|psql=s" => \$PSQL_PROG,
"Q|no-statement!"=> \$NO_STATEMENTS,
"r|rotate-daily!"=> \$D_ROTATE,
"R|rotate-hourly!"=> \$H_ROTATE,
"s|sar=s" => \$SAR_PROG,
"S|disable-sar!" => \$DISABLE_SAR,
"t|lock-timeout=i" => \$LOCK_TIMEOUT,
"T|no-tablespace!"=> \$NOTABLESPACE,
"U|dbuser=s" => \$DBUSER,
"v|verbose!" => \$DEBUG,
"V|version!" => \$SHOW_VER,
"w|no-waitevent!"=> \$NO_WAITEVENT,
"n|no-pg_stats-dump!"=> \$NO_PGSTATS_DUMP,
"W|password=s" => \$DBPASS,
"z|compress!" => \$COMPRESS,
"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,
"sysinfo!" => \$OS_INFO,
"no-sysinfo!" => \$NO_SYSINFO,
"no-database!" => \$NO_DATABASE,
"included-db=s" => \$INCLUDED_DB,
"exclude-time=s" => \$SKIP_HOURS,
'enable-ssh!' => \$USE_SSH,
'ssh-command=s' => \$SSH_COMMAND,
'ssh-program=s' => \$SSH_BIN,
'ssh-identity=s' => \$SSH_IDENTITY,
'ssh-option=s' => \$SSH_OPTIONS,
'ssh-user=s' => \$SSH_USER,
'ssh-timeout=i' => \$SSH_TIMEOUT,
'cron-user=s' => \$CRONUSER,
'package-list=s' => \$PKG_LIST_PROG,
'retention=i' => \$RETENTION,
"pidstat=s" => \$PIDSTAT_PROG,
"pidstat-file=s" => \$PIDSTAT_FILE,
"disable-pidstat!" => \$DISABLE_PIDSTAT,
) or die &usage();
# Clean retention value
if ($RETENTION) {
$RETENTION =~ s/[+\-]//g;
}
# Set current username for cron listing
if (!$CRONUSER) {
$CRONUSER = $ENV{USERNAME} || 'postgres';
}
# Print version number to stdout
if ($SHOW_VER) {
print "Version: $VERSION\n";
exit 0;
}
END {
kill '-TERM', $SAR_PID if ($SAR_PID);
kill '-TERM', $PIDSTAT_PID if ($PIDSTAT_PID);
}
# The daemon should be stopped
if ($KILL)
{
my $proc = '';
if (-e "$PIDFILE") {
$proc = `cat $PIDFILE`;
} else {
$proc = `ps h -opid -Cpgcluu_collectd | head -1`;
}
chomp($proc);
$proc =~ s/ //g;
if (!$proc) {
die "ERROR: can't find a pid to kill, is $PROGRAM running?\n";
}
kill '-HUP', $proc;
if ($? == -1) {
print "FATAL: failed to execute: $!\n";
} elsif ($? & 127) {
printf "ERROR: child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without';
} else {
printf "OK: pgcluu_collectd exited with value %d\n", $? >> 8;
}
exit 0;
}
# Display usage if help is asked
&usage if $HELP;
if ($CAPTURE && $DAEMONIZE) {
die "ERROR: option -D (--daemonize) can not be used with option -c (--capture).\n";
} elsif ($CAPTURE) {
$DISABLE_SAR = 1;
}
# Set PGOPTIONS environment variable
$ENV{PGOPTIONS} = "$ENV{PGOPTIONS} -c lock_timeout=${LOCK_TIMEOUT}s";
# 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] || '';
if ($OUTPUT_DIR =~ / +/) { die "FATAL: $OUTPUT_DIR contains 1 or more spaces - this is not yet supported. \n" }
# Overwrite the output directory in capture mode
if ($CAPTURE)
{
$OUTPUT_DIR = 'pgcluu_capture';
unless(mkdir("$CAPTURE_DIR/$OUTPUT_DIR")) {
die "FATAL: can not create capture temporary directory $CAPTURE_DIR/$OUTPUT_DIR: $!.\n";
} else {
print "INFO: creating temporary output directory: $CAPTURE_DIR/$OUTPUT_DIR\n";
}
}
if ($USE_SSH && !$DBHOST) {
die "FATAL: you must give an ipaddress for the remote host with -h | --host option to use sar remotely\n";
}
# List metrics and associated SQL commands, then exit
if ($LIST_METRIC)
{
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 @timerange = split(/\s+/, $SKIP_HOURS);
foreach my $t (@timerange)
{
next if (!$t);
if ($t =~ 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: $t. Format of exclusion time must be: HH:MM-HH:MM\n");
}
}
}
# Normalize number of seconds before terminating
if ($END_AFTER)
{
$END_AFTER =~ s/(\D+)//g;
$END_AFTER ||= 0;
if ($1 =~ /^M/i) {
$END_AFTER *= 60;
} elsif ($1 =~ /^H/i) {
$END_AFTER *= 3600;
} elsif ($1 =~ /^D/i) {
$END_AFTER *= 86400;
}
}
# Set max size of the output dir before terminating
$MAX_SIZE = &parse_pretty_size($MAX_SIZE);
# Validate action(s) to execute
if ($#METRICS >= 0)
{
my @list_metric = ();
push(@list_metric, split(/[,]+/, join(',', @METRICS)));
@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");
}
}
}
else
{
# Perform all metrics actions per default
push(@METRICS, sort {$a cmp $b} keys %METRICS_COMMANDS);
}
# Check if output directory exists
if (!$OUTPUT_DIR)
{
&dprint("FATAL: no output directory\n");
exit 1;
}
elsif (!$CAPTURE)
{
# 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;
}
}
# Go to that directory if we are not in capture mode otherwise go to /tmp
if (!$CAPTURE)
{
unless (chdir($OUTPUT_DIR))
{
&dprint("FATAL: can not change directory to $OUTPUT_DIR: $!\n");
exit 1;
}
else
{
# Check if we can write in this directory
my $fh = IO::File->new("wtest", 'w');
if (not defined $fh)
{
&dprint("FATAL: can not write into output directory $OUTPUT_DIR\n");
exit 1;
}
close($fh);
unlink("wtest");
}
}
else
{
unless(chdir("$CAPTURE_DIR"))
{
&dprint("FATAL: can not change directory to $CAPTURE_DIR: $!\n");
exit 1;
}
$OUT_DIR = $OUTPUT_DIR;
}
# Generate the sar command
my $def_sar_command = "LC_ALL=C $SAR_PROG -t -p -A 1 1 | grep -vE 'Average|Summary'";
my $def_pidstat_command = "LC_ALL=C $PIDSTAT_PROG -T ALL -u -w -r -d -U postgres 1 1 | grep -v 'Average'";
my $sshcmd = '';
# Set command to execute sar remotely using ssh if necessary
if ($USE_SSH)
{
# Force using the user defined ssh command
if ($SSH_COMMAND)
{
$sshcmd = $SSH_COMMAND;
}
# else compute command following the configuration parameters
else
{
$sshcmd = $SSH_BIN || 'ssh';
$sshcmd .= " -i $SSH_IDENTITY" if ($SSH_IDENTITY);
$sshcmd .= " $SSH_OPTIONS" if ($SSH_OPTIONS);
if ($SSH_USER) {
$sshcmd .= " $SSH_USER\@$DBHOST";
} else {
$sshcmd .= " $DBHOST";
}
}
# With remote database connection and no ssh acces, disable system and sar information
}
elsif ($DBHOST && !grep(/^$DBHOST$/, 'localhost', '127.0.0.1', '::1'))
{
$NO_SYSINFO = 1;
$DISABLE_SAR = 1;
}
# Get Os information and exit
if ($OS_INFO && !$NO_SYSINFO)
{
&grab_os_information();
exit 0;
}
# Die cleanly on signal
sub terminate
{
my $sig = shift;
$fini = 1;
&dprint("LOG: Received terminating signal $sig.\n");
$SIG{QUIT} = \&terminate;
$SIG{TERM} = \&terminate;
if (-f $PIDFILE) {
unlink("$PIDFILE");
}
# Wait for all child processes to die except for the logger
&wait_all_childs();
exit 0;
}
# Die gracefully at end of all collects
sub end_gracefully
{
my $sig = shift;
$done = 1;
&dprint("LOG: Received terminating signal $sig.\n");
$SIG{INT} = \&end_gracefully;
$SIG{HUP} = \&end_gracefully;
}
# Die on kill -2, -3 or -15
$SIG{'QUIT'} = $SIG{'TERM'} = \&terminate;
$SIG{'HUP'} = $SIG{'INT'} = \&end_gracefully;
# Run in interactive mode if required
if (!$DAEMONIZE)
{
# Start in interactive mode
print "\n*** $PROGRAM v$VERSION (pid:$$) started at " . localtime(time) . "\n";
if ($CAPTURE) {
print "Capture mode enabled, $PROGRAM will ended after one single loop.\n\n";
} else {
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
my $fhp = IO::File->new($PIDFILE, 'w');
if (not defined $fhp) {
die "FATAL: can't create pid file $PIDFILE, $!\n";
}
print $fhp $$;
close($fhp);
# Generate the psql commands
$PSQL_PROG .= " -XAtq -F';' ";
my $PGBOUNCER_PROG = $PSQL_PROG . ' ' . $PGBOUNCER_ARGS . ' pgbouncer';
$PSQL_PROG .= " -f - ";
if ($NO_DATABASE) {
$PSQL_PROG = '';
} else {
$PSQL_PROG .= " -h $DBHOST" if ($DBHOST);
$PSQL_PROG .= " -p $DBPORT" if ($DBPORT);
$PSQL_PROG .= " -U $DBUSER" if ($DBUSER);
if ($#dbnames >= 0) {
if ($dbnames[0] !~ /^[a-z0-9\_\-]+$/i) {
$PSQL_PROG .= " -d '$dbnames[0]'";
} else {
$PSQL_PROG .= " -d $dbnames[0]";
}
}
if ($DBPASS) {
$ENV{PGPASSWORD} = $DBPASS;
}
}
# Try to grab the sysstat version
my $sysstat_version = '';
if (!$CAPTURE) {
$sysstat_version = &sysstat_version() || '';
}
# Remove action that can't be run with the PostgreSQL version
my $PG_RET = '';
$PG_RET = &verify_action() if (!$NO_DATABASE);
# Look if we should limit statistic collect to some DB
my @included_dbs = ();
@included_dbs = split(/,/, $INCLUDED_DB) if ($INCLUDED_DB);
# end counter
my $tcounter = 0;
# Force rotation in incremental mode
if ($INCREMENTAL) {
$D_ROTATE = 1;
$H_ROTATE = 1;
}
my $previous_time = 0;
while (1)
{
# Stores loop start time
my $t0 = time;
# Do not collect metrics if previous time is upper than current time.
# This is to prevent collecting statistics twice when the hour change
# for daylight saving.
if ($previous_time && ($t0 < $previous_time)) {
# Wait next run following the interval value
sleep($INTERVAL);
next;
}
$previous_time = $t0;
# Search if the monitoring need to stop here
if ($END_AFTER && ($t0 > ($START_TIME + $END_AFTER))) {
unlink_pid_and_exit("LOG: ending time reach, terminating.", 0);
}
# If counter reached then exit
$tcounter++;
if (($END_AFTER_COUNTER > 0) && ($tcounter > $END_AFTER_COUNTER)) {
unlink_pid_and_exit("LOG: counter reached, terminating.", 0);
}
# Some time range may not collect data
my ($sec , $min, $hour, $mday, $mon, $year, @other) = localtime(time);
$min = "0$min" if ($min < 10);
$hour = "0$hour" if ($hour < 10);
$mday = "0$mday" if ($mday < 10);
$mon++;
$mon = "0$mon" if ($mon < 10);
$year += 1900;
if (!$CAPTURE)
{
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;
}
}
}
}
####
# Output dir is now relative to $OUTPUT_DIR because we have chdir to that directory.
####
# Compress previous daily directory if required
if ($COMPRESS && $OLD_OUT_DIR && ($OLD_OUT_DIR ne "$year/$mon/$mday") && $D_ROTATE && !$H_ROTATE)
{
# Fork a process to compress old data files in parallel
&spawn_compress(sub {
&compress_files($OLD_OUT_DIR);
});
}
# Set daily rotation subdirectories
if ($D_ROTATE && !$H_ROTATE && !-d "$year/$mon/$mday")
{
mkdir("$year") if (!-d "$year");
mkdir("$year/$mon") if (!-d "$year/$mon");
mkdir("$year/$mon/$mday");
# Set the new output directory
$OUT_DIR = "$year/$mon/$mday";
dprint ("Created OUT_DIR: $OUT_DIR \n") ;
}
elsif ($D_ROTATE)
{
# Set the new output directory
$OUT_DIR = "$year/$mon/$mday";
dprint ("OUT_DIR is: $OUT_DIR \n") if ($initial_run);
}
# Compress previous hourly directory if required
if ($COMPRESS && $OLD_OUT_DIR && ($OLD_OUT_DIR ne "$year/$mon/$mday/$hour") && $H_ROTATE)
{
# Fork a process to compress old data files in parallel
&spawn_compress(sub {
&compress_files($OLD_OUT_DIR);
});
}
# Set hourly rotation/incremental subdirectories
if ($H_ROTATE && !-d "$year/$mon/$mday/$hour")
{
mkdir("$year") if (!-d "$year");
mkdir("$year/$mon") if (!-d "$year/$mon");
mkdir("$year/$mon/$mday") if (!-d "$year/$mon/$mday");
mkdir("$year/$mon/$mday/$hour");
# Set the new output directory
$OUT_DIR = "$year/$mon/$mday/$hour";
dprint ("Created OUT_DIR: $OUT_DIR \n") ;
}
elsif ($H_ROTATE)
{
# Set the new output directory
$OUT_DIR = "$year/$mon/$mday/$hour";
dprint ("OUT_DIR is: $OUT_DIR \n") if ($initial_run);
}
elsif (!$D_ROTATE)
{
$OUT_DIR = $OUTPUT_DIR;
dprint ("OUT_DIR is: $OUT_DIR \n") if ($initial_run);
}
# If we have a retention limit remove everything older
if ($RETENTION > 0 && $OUTPUT_DIR && $year)
{
# We don't use the output directory as root dir but the year
# subdirectory. Rewind to previous year first in case we have
# year overlap.
$year--;
if (-d "$OUTPUT_DIR/$year") {
`find '$OUTPUT_DIR/$year/' -name '*' -mtime +$RETENTION -delete`;
}
$year++;
if (-d "$OUTPUT_DIR/$year") {
`find '$OUTPUT_DIR/$year/' -name '*' -mtime +$RETENTION -delete`;
}
}
# Set the sar and pidstat command
my $sar_command = '';
my $pidstat_command = '';
if (!$DISABLE_SAR && $sysstat_version)
{
$sar_command = ($sshcmd) ? $sshcmd . ' "' . $def_sar_command . ' "' : $def_sar_command;
$sar_command .= " >>'$OUT_DIR/$SAR_FILE'";
if (!$DISABLE_PIDSTAT)
{
$pidstat_command = ($sshcmd) ? $sshcmd . ' "' . $def_pidstat_command . ' "' : $def_pidstat_command;
$pidstat_command .= " >>'$OUT_DIR/$PIDSTAT_FILE'";
}
# Start processes to collect system statistics permanently
&spawn_sar(sub {
&collect_sysstat($sar_command);