| •1 |
#!/usr/bin/perl |
| 2 |
#------------------------------------------------------------------------------ |
| 3 |
# |
| 4 |
# PgCluu - PostgreSQL monitoring tool with statistics collector and grapher |
| 5 |
# |
| 6 |
# This program is open source, licensed under the PostgreSQL license. |
| 7 |
# For license terms, see the LICENSE file. |
| 8 |
# |
| 9 |
# Author: Gilles Darold |
| 10 |
# Copyright: (C) 2012-2024 Gilles Darold - All rights reserved. |
| 11 |
#------------------------------------------------------------------------------ |
| 12 |
use vars qw($VERSION $PROGRAM); |
| 13 |
use strict qw(vars subs); |
| 14 |
|
| 15 |
use File::Basename; |
| 16 |
use IO::File; |
| 17 |
use POSIX; |
| 18 |
use Getopt::Long qw(:config bundling no_ignore_case_always); |
| 19 |
use POSIX qw(locale_h sys_wait_h); |
| 20 |
setlocale(LC_ALL, 'C'); |
| 21 |
|
| 22 |
# Change MASK to 0027 if you want to secure the data directory |
| 23 |
# Note that in CGI mode the www-data user or group need read |
| 24 |
# access to all files in the statistics directory. |
| 25 |
use constant UMASK => 0022; |
| 26 |
|
| 27 |
$| = 1; |
| 28 |
|
| 29 |
$VERSION = '4.0'; |
| 30 |
$PROGRAM = 'pgcluu_collectd'; |
| 31 |
|
| 32 |
$SIG{'CHLD'} = 'DEFAULT'; |
| 33 |
|
| 34 |
# Default path to the external programs |
| 35 |
# They can be specified into command line options |
| 36 |
my $SAR_PROG = 'sar'; |
| 37 |
my $PSQL_PROG = 'psql'; |
| 38 |
my $CAT_PROG = 'cat '; |
| 39 |
my $PIDSTAT_PROG = 'pidstat'; |
| 40 |
|
| 41 |
# Global variables |
| 42 |
my $CONFIG_FILE = "/usr/local/etc/pgcluu.conf"; |
| 43 |
my $SAR_FILE = 'sar_stats.dat'; |
| 44 |
my $PIDSTAT_FILE = 'pidstat_stats.dat'; |
| 45 |
my $PIDFILE = "/var/run/postgresql/pgcluu_collectd.pid"; |
| 46 |
my $SQL_PROBE = ''; |
| 47 |
my %DB_INFO = (); |
| 48 |
my $HELP = 0; |
| 49 |
my $DAEMONIZE = 0; |
| 50 |
my $DISABLE_SAR = 0; |
| 51 |
my $INTERVAL = 60; # wait 60 seconds between runs |
| 52 |
my $DEBUG = 0; |
| 53 |
my $DBNAME = ''; |
| 54 |
my $DBUSER = ''; |
| 55 |
my $DBHOST = ''; |
| 56 |
my $DBPORT = ''; |
| 57 |
my $DBPASS = ''; |
| 58 |
my @METRICS = (); |
| 59 |
my $LIST_METRIC = 0; |
| 60 |
my $FILE_REDIR = '>>'; |
| 61 |
my $PG_VERSION = 0; |
| 62 |
my $DBSERVICE = ''; |
| 63 |
my $STAT_TYPE = 'user'; |
| 64 |
my $KILL = 0; |
| 65 |
my $OS_INFO = 0; |
| 66 |
my $NOTABLESPACE= 0; |
| 67 |
my $PGBOUNCER_ARGS = ''; |
| 68 |
my $INCLUDED_DB = (); |
| 69 |
my $SKIP_HOURS = ''; |
| 70 |
my @SKIP_BEGIN = (); |
| 71 |
my @SKIP_END = (); |
| 72 |
my $USE_BUFFERCACHE = 0; |
| 73 |
my $NO_STATEMENTS = 0; |
| 74 |
my $NO_WAITEVENT = 0; |
| 75 |
my $NO_PGSTATS_DUMP = 0; |
| 76 |
my $NO_SYSINFO = 0; |
| 77 |
my $SHOW_VER = 0; |
| 78 |
my $END_AFTER = 0; |
| 79 |
my $MAX_SIZE = 0; |
| 80 |
my $END_AFTER_COUNTER = 0; |
| 81 |
my $NO_DATABASE = 0; |
| 82 |
my $D_ROTATE = 0; |
| 83 |
my $H_ROTATE = 0; |
| 84 |
my $RETENTION = 0; |
| 85 |
my $OUT_DIR = '.'; |
| 86 |
my $COMPRESS = 0; |
| 87 |
my $OLD_OUT_DIR = ''; |
| 88 |
my $COLLECT_PID = 0; |
| 89 |
my $COMPRESS_PID = 0; |
| 90 |
my $GZIP_PROG = '/bin/gzip'; |
| 91 |
my $INCREMENTAL = 0; |
| 92 |
my $CAPTURE = 0; |
| 93 |
my $TAR_PROG = 'tar -czf'; |
| 94 |
my $CAPTURE_DIR = '/tmp'; |
| 95 |
my $DIFF_PROG = 'diff -U 0'; |
| 96 |
my $CRONUSER = ''; |
| 97 |
my $PKG_LIST_PROG = ''; |
| 98 |
my $DF_COMMAND = 'LANG=C df --output="source,size,used,avail,itotal,iused,iavail,fstype,target" -x squashfs -x tmpfs -x devtmpfs'; |
| 99 |
my $SAR_PID = 0; |
| 100 |
my $PIDSTAT_PID = 0; |
| 101 |
my $LOCK_TIMEOUT = 3; |
| 102 |
my $DISABLE_PIDSTAT = 0; |
| 103 |
|
| 104 |
# Global storage of extensions installed in each database |
| 105 |
my @extensions = (); |
| 106 |
|
| 107 |
# Set the default mask for file and directory creation |
| 108 |
umask(UMASK); |
| 109 |
|
| 110 |
# Stores starting time |
| 111 |
my $START_TIME = time(); |
| 112 |
|
| 113 |
# Variables related to remote ssh connection |
| 114 |
my $USE_SSH = ''; |
| 115 |
my $SSH_COMMAND = ''; |
| 116 |
my $SSH_BIN = 'ssh'; |
| 117 |
my $SSH_IDENTITY = ''; |
| 118 |
my $SSH_USER = ''; |
| 119 |
my $SSH_TIMEOUT = 10; |
| 120 |
my $SSH_OPTIONS = "-o ConnectTimeout=$SSH_TIMEOUT -o PreferredAuthentications=hostbased,publickey"; |
| 121 |
|
| 122 |
my $ALWAYS_SECURE_SEARCH_PATH_SQL = "SELECT pg_catalog.set_config('search_path', '', false);"; |
| 123 |
|
| 124 |
# Variable to store previous settings |
| 125 |
my %ORIGINAL_PG_SETTINGS = (); |
| 126 |
my %ORIGINAL_DBROLE_SETTINGS = (); |
| 127 |
my %ORIGINAL_SYSTEM_SETTINGS = (); |
| 128 |
|
| 129 |
# Register a termination signal |
| 130 |
my $fini = 0; |
| 131 |
my $done = 0; |
| 132 |
my $initial_run = 1; |
| 133 |
|
| 134 |
# Definition to collect metrics from the database |
| 135 |
my %METRICS_COMMANDS = ( |
| 136 |
'database_stats' => { |
| 137 |
'output' => 'pg_stat_database.csv', |
| 138 |
'command' => 'dump_pgstatdatabase' |
| 139 |
}, |
| 140 |
'tablespace_size_stats' => { |
| 141 |
'output' => 'pg_tablespace_size.csv', |
| 142 |
'command' => 'dump_pgtablespace_size' |
| 143 |
}, |
| 144 |
'bgwriter_stats' => { |
| 145 |
'output' => 'pg_stat_bgwriter.csv', |
| 146 |
'command' => 'dump_pgstatbgwriter' |
| 147 |
}, |
| 148 |
'conflict_stats' => { |
| 149 |
'output' => 'pg_stat_database_conflicts.csv', |
| 150 |
'command' => 'dump_pgstatdatabaseconflicts' |
| 151 |
}, |
| 152 |
'replication_stats' => { |
| 153 |
'output' => 'pg_stat_replication.csv', |
| 154 |
'command' => 'dump_pgstatreplication' |
| 155 |
}, |
| 156 |
'all_tables_stats' => { |
| 157 |
'output' => 'pg_stat_all_tables.csv', |
| 158 |
'command' => 'dump_pgstattables', |
| 159 |
'repeat' => 1, |
| 160 |
'start-end' => 1, |
| 161 |
}, |
| 162 |
'user_tables_stats' => { |
| 163 |
'output' => 'pg_stat_user_tables.csv', |
| 164 |
'command' => 'dump_pgstattables_user', |
| 165 |
'repeat' => 1, |
| 166 |
'start-end' => 1, |
| 167 |
}, |
| 168 |
'all_tables_io_stats' => { |
| 169 |
'output' => 'pg_statio_all_tables.csv', |
| 170 |
'command' => 'dump_pgstatiotables', |
| 171 |
'repeat' => 1, |
| 172 |
'start-end' => 1, |
| 173 |
}, |
| 174 |
'user_tables_io_stats' => { |
| 175 |
'output' => 'pg_statio_user_tables.csv', |
| 176 |
'command' => 'dump_pgstatiotables_user', |
| 177 |
'repeat' => 1, |
| 178 |
'start-end' => 1, |
| 179 |
}, |
| 180 |
'all_indexes_stats' => { |
| 181 |
'output' => 'pg_stat_all_indexes.csv', |
| 182 |
'command' => 'dump_pgstatindexes', |
| 183 |
'repeat' => 1, |
| 184 |
'start-end' => 1, |
| 185 |
}, |
| 186 |
'user_indexes_stats' => { |
| 187 |
'output' => 'pg_stat_user_indexes.csv', |
| 188 |
'command' => 'dump_pgstatindexes_user', |
| 189 |
'repeat' => 1, |
| 190 |
'start-end' => 1, |
| 191 |
}, |
| 192 |
'all_indexes_io_stats' => { |
| 193 |
'output' => 'pg_statio_all_indexes.csv', |
| 194 |
'command' => 'dump_pgstatioindexes', |
| 195 |
'repeat' => 1, |
| 196 |
'start-end' => 1, |
| 197 |
}, |
| 198 |
'user_indexes_io_stats' => { |
| 199 |
'output' => 'pg_statio_user_indexes.csv', |
| 200 |
'command' => 'dump_pgstatioindexes_user', |
| 201 |
'repeat' => 1, |
| 202 |
'start-end' => 1, |
| 203 |
}, |
| 204 |
'all_sequences_io_stats' => { |
| 205 |
'output' => 'pg_statio_all_sequences.csv', |
| 206 |
'command' => 'dump_pgstatiosequences', |
| 207 |
'repeat' => 1, |
| 208 |
'start-end' => 1, |
| 209 |
}, |
| 210 |
'user_sequences_io_stats' => { |
| 211 |
'output' => 'pg_statio_user_sequences.csv', |
| 212 |
'command' => 'dump_pgstatiosequences_user', |
| 213 |
'repeat' => 1, |
| 214 |
'start-end' => 1, |
| 215 |
}, |
| 216 |
'functions_stats' => { |
| 217 |
'output' => 'pg_stat_user_functions.csv', |
| 218 |
'command' => 'dump_pgstatuserfunctions', |
| 219 |
'repeat' => 1, |
| 220 |
'start-end' => 1, |
| 221 |
}, |
| 222 |
'xact_functions_stats' => { |
| 223 |
'output' => 'pg_stat_xact_user_functions.csv', |
| 224 |
'command' => 'dump_pgstatxactuserfunctions', |
| 225 |
'repeat' => 1, |
| 226 |
'start-end' => 1, |
| 227 |
}, |
| 228 |
'all_xact_tables_stats' => { |
| 229 |
'output' => 'pg_stat_xact_all_tables.csv', |
| 230 |
'command' => 'dump_pgstatxacttables', |
| 231 |
'repeat' => 1, |
| 232 |
'start-end' => 1, |
| 233 |
}, |
| 234 |
'user_xact_tables_stats' => { |
| 235 |
'output' => 'pg_stat_xact_user_tables.csv', |
| 236 |
'command' => 'dump_pgstatxacttables_user', |
| 237 |
'repeat' => 1, |
| 238 |
'start-end' => 1, |
| 239 |
}, |
| 240 |
'class_size_stats' => { |
| 241 |
'output' => 'pg_class_size.csv', |
| 242 |
'command' => 'dump_pgclass_size', |
| 243 |
'repeat' => 1, |
| 244 |
'override' => 1, |
| 245 |
}, |
| 246 |
'lock_types_stats' => { |
| 247 |
'output' => 'pg_stat_locks.csv', |
| 248 |
'command' => 'dump_pgstatlocktypes', |
| 249 |
'repeat' => 1, |
| 250 |
}, |
| 251 |
'lock_modes_stats' => { |
| 252 |
'output' => 'pg_stat_locks.csv', |
| 253 |
'command' => 'dump_pgstatlockmodes', |
| 254 |
'repeat' => 1, |
| 255 |
}, |
| 256 |
'lock_granted_stats' => { |
| 257 |
'output' => 'pg_stat_locks.csv', |
| 258 |
'command' => 'dump_pgstatlockgranted', |
| 259 |
'repeat' => 1, |
| 260 |
}, |
| 261 |
'statements_stats' => { |
| 262 |
'output' => 'pg_stat_statements.csv', |
| 263 |
'command' => 'dump_pgstatstatements', |
| 264 |
'override' => 1, |
| 265 |
}, |
| 266 |
'waitevent_stats' => { |
| 267 |
'output' => 'pg_stat_waitevent.csv', |
| 268 |
'command' => 'dump_pgwaitsampling', |
| 269 |
'repeat' => 1, |
| 270 |
}, |
| 271 |
'subxact_stats' => { |
| 272 |
'output' => 'pg_subxact_counters.csv', |
| 273 |
'command' => 'dump_pgsubxactcounters', |
| 274 |
}, |
| 275 |
'xlog_stats' => { |
| 276 |
'output' => 'pg_xlog_stat.csv', |
| 277 |
'command' => 'dump_xlog_stat' |
| 278 |
}, |
| 279 |
'database_size_stats' => { |
| 280 |
'output' => 'pg_database_size.csv', |
| 281 |
'command' => 'dump_pgdatabase_size' |
| 282 |
}, |
| 283 |
'connections_stats' => { |
| 284 |
'output' => 'pg_stat_connections.csv', |
| 285 |
'command' => 'dump_pgstatconnections' |
| 286 |
}, |
| 287 |
'pgbouncer_stats' => { |
| 288 |
'output' => 'pgbouncer_stats.csv', |
| 289 |
'command' => 'dump_pgbouncerpoolstats' |
| 290 |
}, |
| 291 |
'pgbouncer_req_stats' => { |
| 292 |
'output' => 'pgbouncer_req_stats.csv', |
| 293 |
'command' => 'dump_pgbouncerquerystats' |
| 294 |
}, |
| 295 |
'unused_indexes_stats' => { |
| 296 |
'output' => 'pg_stat_unused_indexes.csv', |
| 297 |
'command' => 'dump_unusedindexes', |
| 298 |
'repeat' => 1, |
| 299 |
'override' => 1, |
| 300 |
}, |
| 301 |
'redundant_indexes_stats' => { |
| 302 |
'output' => 'pg_stat_redundant_indexes.csv', |
| 303 |
'command' => 'dump_redundantindexes', |
| 304 |
'repeat' => 1, |
| 305 |
'override' => 1, |
| 306 |
}, |
| 307 |
'invalid_indexes_stats' => { |
| 308 |
'output' => 'pg_stat_invalid_indexes.csv', |
| 309 |
'command' => 'dump_invalidindexes', |
| 310 |
'repeat' => 1, |
| 311 |
'override' => 1, |
| 312 |
}, |
| 313 |
'hash_indexes_stats' => { |
| 314 |
'output' => 'pg_stat_hash_indexes.csv', |
| 315 |
'command' => 'dump_hashindexes', |
| 316 |
'repeat' => 1, |
| 317 |
'override' => 1, |
| 318 |
}, |
| 319 |
'missing_fkindexes_stats' => { |
| 320 |
'output' => 'pg_stat_missing_fkindexes.csv', |
| 321 |
'command' => 'dump_missingfkindexes', |
| 322 |
'repeat' => 1, |
| 323 |
'override' => 1, |
| 324 |
}, |
| 325 |
'count_indexes_stats' => { |
| 326 |
'output' => 'pg_stat_count_indexes.csv', |
| 327 |
'command' => 'dump_count_indexes', |
| 328 |
'repeat' => 1, |
| 329 |
'override' => 1, |
| 330 |
}, |
| 331 |
'unused_trigfunc_stats' => { |
| 332 |
'output' => 'pg_stat_unused_trigfunc.csv', |
| 333 |
'command' => 'dump_unusedtrigfunc', |
| 334 |
'repeat' => 1, |
| 335 |
'override' => 1, |
| 336 |
}, |
| 337 |
'pg_settings_stats' => { |
| 338 |
'output' => 'pg_settings.csv', |
| 339 |
'command' => 'dump_pgsettings', |
| 340 |
'repeat' => 1, |
| 341 |
'override' => 1, |
| 342 |
}, |
| 343 |
'pg_nondefault_settings_stats' => { |
| 344 |
'output' => 'pg_nondefault_settings.csv', |
| 345 |
'command' => 'dump_nondefault_pgsettings', |
| 346 |
'repeat' => 1, |
| 347 |
'override' => 1, |
| 348 |
}, |
| 349 |
'pg_db_role_setting_stats' => { |
| 350 |
'output' => 'pg_db_role_setting.csv', |
| 351 |
'command' => 'dump_pgdbrolesetting', |
| 352 |
'repeat' => 1, |
| 353 |
'override' => 1, |
| 354 |
}, |
| 355 |
'database_buffercache_stats' => { |
| 356 |
'output' => 'pg_database_buffercache.csv', |
| 357 |
'command' => 'dump_pgdatabase_buffercache' |
| 358 |
}, |
| 359 |
'database_usagecount_stats' => { |
| 360 |
'output' => 'pg_database_usagecount.csv', |
| 361 |
'command' => 'dump_pgdatabase_usercount' |
| 362 |
}, |
| 363 |
'database_isdirty_stats' => { |
| 364 |
'output' => 'pg_database_isdirty.csv', |
| 365 |
'command' => 'dump_pgdatabase_isdirty' |
| 366 |
}, |
| 367 |
'relation_buffercache_stats' => { |
| 368 |
'output' => 'pg_relation_buffercache.csv', |
| 369 |
'command' => 'dump_pgrelation_buffercache', |
| 370 |
}, |
| 371 |
'archiver_stats' => { |
| 372 |
'output' => 'pg_stat_archiver.csv', |
| 373 |
'command' => 'dump_pgstatarchiver', |
| 374 |
}, |
| 375 |
'configuration_stats' => { |
| 376 |
'output' => '', |
| 377 |
'command' => 'get_configuration_files', |
| 378 |
}, |
| 379 |
'unlogged_stats' => { |
| 380 |
'output' => 'pg_stat_unlogged.csv', |
| 381 |
'command' => 'dump_unlogged', |
| 382 |
'repeat' => 1, |
| 383 |
'override' => 1, |
| 384 |
}, |
| 385 |
'prepared_stats' => { |
| 386 |
'output' => 'pg_prepared_xact.csv', |
| 387 |
'command' => 'dump_preparedxactstats' |
| 388 |
}, |
| 389 |
'statistics_stats' => { |
| 390 |
'output' => 'pg_stat_ext.csv', |
| 391 |
'command' => 'dump_statisticsext', |
| 392 |
'repeat' => 1, |
| 393 |
'override' => 1, |
| 394 |
}, |
| 395 |
'stats_stats' => { |
| 396 |
'output' => 'pg_stats.csv', |
| 397 |
'command' => 'dump_pg_stats_view', |
| 398 |
'repeat' => 1, |
| 399 |
'start-end' => 1, |
| 400 |
}, |
| 401 |
); |
| 402 |
|
| 403 |
# Read configuration file before reading command line parameters |
| 404 |
&read_conf(); |
| 405 |
|
| 406 |
# Process command line options and look for an action keyword. There |
| 407 |
# are no mandatory options. |
| 408 |
my $result = GetOptions( |
| 409 |
"B|enable-buffercache!" => \$USE_BUFFERCACHE, |
| 410 |
"c|capture!" => \$CAPTURE, |
| 411 |
"C|end-counter=s"=> \$END_AFTER_COUNTER, |
| 412 |
"d|dbname=s" => \$DBNAME, |
| 413 |
"D|daemonize!" => \$DAEMONIZE, |
| 414 |
"E|end-after=s" => \$END_AFTER, |
| 415 |
"f|pid-file=s" => \$PIDFILE, |
| 416 |
"h|host=s" => \$DBHOST, |
| 417 |
"i|interval=i" => \$INTERVAL, |
| 418 |
"I|incremental!" => \$INCREMENTAL, |
| 419 |
"k|kill!" => \$KILL, |
| 420 |
"m|metric=s" => \@METRICS, |
| 421 |
"M|max-size=s" => \$MAX_SIZE, |
| 422 |
"p|port=i" => \$DBPORT, |
| 423 |
"P|psql=s" => \$PSQL_PROG, |
| 424 |
"Q|no-statement!"=> \$NO_STATEMENTS, |
| 425 |
"r|rotate-daily!"=> \$D_ROTATE, |
| 426 |
"R|rotate-hourly!"=> \$H_ROTATE, |
| 427 |
"s|sar=s" => \$SAR_PROG, |
| 428 |
"S|disable-sar!" => \$DISABLE_SAR, |
| 429 |
"t|lock-timeout=i" => \$LOCK_TIMEOUT, |
| 430 |
"T|no-tablespace!"=> \$NOTABLESPACE, |
| 431 |
"U|dbuser=s" => \$DBUSER, |
| 432 |
"v|verbose!" => \$DEBUG, |
| 433 |
"V|version!" => \$SHOW_VER, |
| 434 |
"w|no-waitevent!"=> \$NO_WAITEVENT, |
| 435 |
"n|no-pg_stats-dump!"=> \$NO_PGSTATS_DUMP, |
| 436 |
"W|password=s" => \$DBPASS, |
| 437 |
"z|compress!" => \$COMPRESS, |
| 438 |
"pgversion=s" => \$PG_VERSION, |
| 439 |
"pgservice=s" => \$DBSERVICE, |
| 440 |
"help!" => \$HELP, |
| 441 |
"stat-type=s" => \$STAT_TYPE, |
| 442 |
"sar-file=s" => \$SAR_FILE, |
| 443 |
"list-metric!" => \$LIST_METRIC, |
| 444 |
"pgbouncer-args=s" => \$PGBOUNCER_ARGS, |
| 445 |
"sysinfo!" => \$OS_INFO, |
| 446 |
"no-sysinfo!" => \$NO_SYSINFO, |
| 447 |
"no-database!" => \$NO_DATABASE, |
| 448 |
"included-db=s" => \$INCLUDED_DB, |
| 449 |
"exclude-time=s" => \$SKIP_HOURS, |
| 450 |
'enable-ssh!' => \$USE_SSH, |
| 451 |
'ssh-command=s' => \$SSH_COMMAND, |
| 452 |
'ssh-program=s' => \$SSH_BIN, |
| 453 |
'ssh-identity=s' => \$SSH_IDENTITY, |
| 454 |
'ssh-option=s' => \$SSH_OPTIONS, |
| 455 |
'ssh-user=s' => \$SSH_USER, |
| 456 |
'ssh-timeout=i' => \$SSH_TIMEOUT, |
| 457 |
'cron-user=s' => \$CRONUSER, |
| 458 |
'package-list=s' => \$PKG_LIST_PROG, |
| 459 |
'retention=i' => \$RETENTION, |
| 460 |
"pidstat=s" => \$PIDSTAT_PROG, |
| 461 |
"pidstat-file=s" => \$PIDSTAT_FILE, |
| 462 |
"disable-pidstat!" => \$DISABLE_PIDSTAT, |
| 463 |
) or die &usage(); |
| 464 |
|
| 465 |
# Clean retention value |
| 466 |
if ($RETENTION) { |
| 467 |
$RETENTION =~ s/[+\-]//g; |
| 468 |
} |
| 469 |
|
| 470 |
# Set current username for cron listing |
| 471 |
if (!$CRONUSER) { |
| 472 |
$CRONUSER = $ENV{USERNAME} || 'postgres'; |
| 473 |
} |
| 474 |
|
| 475 |
# Print version number to stdout |
| 476 |
if ($SHOW_VER) { |
| 477 |
print "Version: $VERSION\n"; |
| 478 |
exit 0; |
| 479 |
} |
| 480 |
|
| 481 |
END { |
| 482 |
kill '-TERM', $SAR_PID if ($SAR_PID); |
| 483 |
kill '-TERM', $PIDSTAT_PID if ($PIDSTAT_PID); |
| 484 |
} |
| 485 |
|
| 486 |
# The daemon should be stopped |
| 487 |
if ($KILL) |
| 488 |
{ |
| 489 |
my $proc = ''; |
| 490 |
if (-e "$PIDFILE") { |
| 491 |
$proc = `cat $PIDFILE`; |
| 492 |
} else { |
| 493 |
$proc = `ps h -opid -Cpgcluu_collectd | head -1`; |
| 494 |
} |
| 495 |
chomp($proc); |
| 496 |
$proc =~ s/ //g; |
| 497 |
|
| 498 |
if (!$proc) { |
| 499 |
die "ERROR: can't find a pid to kill, is $PROGRAM running?\n"; |
| 500 |
} |
| 501 |
|
| 502 |
kill '-HUP', $proc; |
| 503 |
if ($? == -1) { |
| 504 |
print "FATAL: failed to execute: $!\n"; |
| 505 |
} elsif ($? & 127) { |
| 506 |
printf "ERROR: child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without'; |
| 507 |
} else { |
| 508 |
printf "OK: pgcluu_collectd exited with value %d\n", $? >> 8; |
| 509 |
} |
| 510 |
exit 0; |
| 511 |
} |
| 512 |
|
| 513 |
# Display usage if help is asked |
| 514 |
&usage if $HELP; |
| 515 |
|
| 516 |
if ($CAPTURE && $DAEMONIZE) { |
| 517 |
die "ERROR: option -D (--daemonize) can not be used with option -c (--capture).\n"; |
| 518 |
} elsif ($CAPTURE) { |
| 519 |
$DISABLE_SAR = 1; |
| 520 |
} |
| 521 |
|
| 522 |
# Set PGOPTIONS environment variable |
| 523 |
$ENV{PGOPTIONS} = "$ENV{PGOPTIONS} -c lock_timeout=${LOCK_TIMEOUT}s"; |
| 524 |
|
| 525 |
# Set the multi host information |
| 526 |
my @MULTI_HOST_INFO = (); |
| 527 |
my @dbnames = split(/,/, $DBNAME); |
| 528 |
my @dbports = split(/,/, $DBPORT); |
| 529 |
my @dbhosts = split(/,/, $DBHOST); |
| 530 |
my @dbusers = split(/,/, $DBUSER); |
| 531 |
my @dbpass = split(/,/, $DBPASS); |
| 532 |
for (my $i = 0; $i <= $#dbhosts; $i++) |
| 533 |
{ |
| 534 |
push(@MULTI_HOST_INFO, { 'ip' => $dbhosts[$i] || 'localhost', 'port' => $dbports[$i] || 5432, 'db' => $dbnames[$i] || 'postgres', 'user' => $dbusers[$i] || 'postgres', 'password' => $dbpass[$i] || ''}); |
| 535 |
} |
| 536 |
|
| 537 |
# Get the output dir from command line |
| 538 |
my $OUTPUT_DIR = $ARGV[0] || ''; |
| 539 |
# Overwrite the output directory in capture mode |
| 540 |
if ($CAPTURE) |
| 541 |
{ |
| 542 |
$OUTPUT_DIR = 'pgcluu_capture'; |
| 543 |
unless(mkdir("$CAPTURE_DIR/$OUTPUT_DIR")) { |
| 544 |
die "FATAL: can not create capture temporary directory $CAPTURE_DIR/$OUTPUT_DIR: $!.\n"; |
| 545 |
} else { |
| 546 |
print "INFO: creating temporary output directory: $CAPTURE_DIR/$OUTPUT_DIR\n"; |
| 547 |
} |
| 548 |
} |
| 549 |
|
| 550 |
if ($USE_SSH && !$DBHOST) { |
| 551 |
die "FATAL: you must give an ipaddress for the remote host with -h | --host option to use sar remotely\n"; |
| 552 |
} |
| 553 |
|
| 554 |
# List metrics and associated SQL commands, then exit |
| 555 |
if ($LIST_METRIC) |
| 556 |
{ |
| 557 |
print "List of available metrics:\n\n"; |
| 558 |
foreach my $c (sort {$a cmp $b} keys %METRICS_COMMANDS) |
| 559 |
{ |
| 560 |
next if (($c =~ /^(user|all)_/) && ($c !~ /^$STAT_TYPE/)); |
| 561 |
$c =~ s/_stats$//; |
| 562 |
print "\t$c\n"; |
| 563 |
} |
| 564 |
print "\n"; |
| 565 |
exit 0; |
| 566 |
} |
| 567 |
|
| 568 |
# Check if an other process is already running |
| 569 |
if (-f $PIDFILE) |
| 570 |
{ |
| 571 |
&dprint("FATAL: an other process is already started, see pid in $PIDFILE\n"); |
| 572 |
exit 1; |
| 573 |
} |
| 574 |
|
| 575 |
# Check excluded times |
| 576 |
if ($SKIP_HOURS) |
| 577 |
{ |
| 578 |
my @timerange = split(/\s+/, $SKIP_HOURS); |
| 579 |
foreach my $t (@timerange) |
| 580 |
{ |
| 581 |
next if (!$t); |
| 582 |
if ($t =~ m#(\d{2}):(\d{2})-(\d{2}):(\d{2})#) |
| 583 |
{ |
| 584 |
push(@SKIP_BEGIN, "$1$2"); |
| 585 |
push(@SKIP_END, "$3$4"); |
| 586 |
} else { |
| 587 |
&dprint("FATAL: Bad time range: $t. Format of exclusion time must be: HH:MM-HH:MM\n"); |
| 588 |
} |
| 589 |
} |
| 590 |
} |
| 591 |
|
| 592 |
# Normalize number of seconds before terminating |
| 593 |
if ($END_AFTER) |
| 594 |
{ |
| 595 |
$END_AFTER =~ s/(\D+)//g; |
| 596 |
$END_AFTER ||= 0; |
| 597 |
if ($1 =~ /^M/i) { |
| 598 |
$END_AFTER *= 60; |
| 599 |
} elsif ($1 =~ /^H/i) { |
| 600 |
$END_AFTER *= 3600; |
| 601 |
} elsif ($1 =~ /^D/i) { |
| 602 |
$END_AFTER *= 86400; |
| 603 |
} |
| 604 |
} |
| 605 |
|
| 606 |
# Set max size of the output dir before terminating |
| 607 |
$MAX_SIZE = &parse_pretty_size($MAX_SIZE); |
| 608 |
|
| 609 |
# Validate action(s) to execute |
| 610 |
if ($#METRICS >= 0) |
| 611 |
{ |
| 612 |
my @list_metric = (); |
| 613 |
push(@list_metric, split(/[,]+/, join(',', @METRICS))); |
| 614 |
@METRICS = (); |
| 615 |
foreach my $a (@list_metric) |
| 616 |
{ |
| 617 |
if (!grep(/^${a}_stats$/, keys %METRICS_COMMANDS)) |
| 618 |
{ |
| 619 |
&dprint("FATAL: metric $a does not exist. Use --list-metric to show the available metrics.\n"); |
| 620 |
exit 1; |
| 621 |
} else { |
| 622 |
push(@METRICS, "${a}_stats"); |
| 623 |
} |
| 624 |
} |
| 625 |
} |
| 626 |
else |
| 627 |
{ |
| 628 |
# Perform all metrics actions per default |
| 629 |
push(@METRICS, sort {$a cmp $b} keys %METRICS_COMMANDS); |
| 630 |
} |
| 631 |
|
| 632 |
# Check if output directory exists |
| 633 |
if (!$OUTPUT_DIR) |
| 634 |
{ |
| 635 |
&dprint("FATAL: no output directory\n"); |
| 636 |
exit 1; |
| 637 |
} |
| 638 |
elsif (!$CAPTURE) |
| 639 |
{ |
| 640 |
# Ensure this is not a relative path |
| 641 |
if (dirname($OUTPUT_DIR) eq '.') { |
| 642 |
&dprint("FATAL: output directory ($OUTPUT_DIR) is not an absolute path.\n"); |
| 643 |
exit 1; |
| 644 |
} |
| 645 |
} |
| 646 |
|
| 647 |
# Go to that directory if we are not in capture mode otherwise go to /tmp |
| 648 |
if (!$CAPTURE) |
| 649 |
{ |
| 650 |
unless (chdir($OUTPUT_DIR)) |
| 651 |
{ |
| 652 |
&dprint("FATAL: can not change directory to $OUTPUT_DIR: $!\n"); |
| 653 |
exit 1; |
| 654 |
} |
| 655 |
else |
| 656 |
{ |
| 657 |
# Check if we can write in this directory |
| 658 |
my $fh = IO::File->new("wtest", 'w'); |
| 659 |
if (not defined $fh) |
| 660 |
{ |
| 661 |
&dprint("FATAL: can not write into output directory $OUTPUT_DIR\n"); |
| 662 |
exit 1; |
| 663 |
} |
| 664 |
close($fh); |
| 665 |
unlink("wtest"); |
| 666 |
|
| 667 |
} |
| 668 |
} |
| 669 |
else |
| 670 |
{ |
| 671 |
unless(chdir("$CAPTURE_DIR")) |
| 672 |
{ |
| 673 |
&dprint("FATAL: can not change directory to $CAPTURE_DIR: $!\n"); |
| 674 |
exit 1; |
| 675 |
} |
| 676 |
$OUT_DIR = $OUTPUT_DIR; |
| 677 |
} |
| 678 |
|
| 679 |
# Generate the sar command |
| 680 |
my $def_sar_command = "LC_ALL=C $SAR_PROG -t -p -A 1 1 | grep -vE 'Average|Summary'"; |
| 681 |
my $def_pidstat_command = "LC_ALL=C $PIDSTAT_PROG -T ALL -u -w -r -d -U postgres 1 1 | grep -v 'Average'"; |
| 682 |
my $sshcmd = ''; |
| 683 |
# Set command to execute sar remotely using ssh if necessary |
| 684 |
if ($USE_SSH) |
| 685 |
{ |
| 686 |
# Force using the user defined ssh command |
| 687 |
if ($SSH_COMMAND) |
| 688 |
{ |
| 689 |
$sshcmd = $SSH_COMMAND; |
| 690 |
} |
| 691 |
# else compute command following the configuration parameters |
| 692 |
else |
| 693 |
{ |
| 694 |
$sshcmd = $SSH_BIN || 'ssh'; |
| 695 |
$sshcmd .= " -i $SSH_IDENTITY" if ($SSH_IDENTITY); |
| 696 |
$sshcmd .= " $SSH_OPTIONS" if ($SSH_OPTIONS); |
| 697 |
if ($SSH_USER) { |
| 698 |
$sshcmd .= " $SSH_USER\@$DBHOST"; |
| 699 |
} else { |
| 700 |
$sshcmd .= " $DBHOST"; |
| 701 |
} |
| 702 |
} |
| 703 |
|
| 704 |
# With remote database connection and no ssh acces, disable system and sar information |
| 705 |
} |
| 706 |
elsif ($DBHOST && !grep(/^$DBHOST$/, 'localhost', '127.0.0.1', '::1')) |
| 707 |
{ |
| 708 |
$NO_SYSINFO = 1; |
| 709 |
$DISABLE_SAR = 1; |
| 710 |
} |
| 711 |
|
| 712 |
# Get Os information and exit |
| 713 |
if ($OS_INFO && !$NO_SYSINFO) |
| 714 |
{ |
| 715 |
&grab_os_information(); |
| 716 |
exit 0; |
| 717 |
} |
| 718 |
|
| 719 |
|
| 720 |
# Die cleanly on signal |
| 721 |
sub terminate |
| 722 |
{ |
| 723 |
my $sig = shift; |
| 724 |
|
| 725 |
$fini = 1; |
| 726 |
|
| 727 |
&dprint("LOG: Received terminating signal $sig.\n"); |
| 728 |
|
| 729 |
$SIG{QUIT} = \&terminate; |
| 730 |
$SIG{TERM} = \&terminate; |
| 731 |
|
| 732 |
if (-f $PIDFILE) { |
| 733 |
unlink("$PIDFILE"); |
| 734 |
} |
| 735 |
|
| 736 |
# Wait for all child processes to die except for the logger |
| 737 |
&wait_all_childs(); |
| 738 |
exit 0; |
| 739 |
} |
| 740 |
|
| 741 |
# Die gracefully at end of all collects |
| 742 |
sub end_gracefully |
| 743 |
{ |
| 744 |
my $sig = shift; |
| 745 |
|
| 746 |
$done = 1; |
| 747 |
|
| 748 |
&dprint("LOG: Received terminating signal $sig.\n"); |
| 749 |
|
| 750 |
$SIG{INT} = \&end_gracefully; |
| 751 |
$SIG{HUP} = \&end_gracefully; |
| 752 |
} |
| 753 |
|
| 754 |
|
| 755 |
# Die on kill -2, -3 or -15 |
| 756 |
$SIG{'QUIT'} = $SIG{'TERM'} = \&terminate; |
| 757 |
$SIG{'HUP'} = $SIG{'INT'} = \&end_gracefully; |
| 758 |
|
| 759 |
# Run in interactive mode if required |
| 760 |
if (!$DAEMONIZE) |
| 761 |
{ |
| 762 |
# Start in interactive mode |
| 763 |
print "\n*** $PROGRAM v$VERSION (pid:$$) started at " . localtime(time) . "\n"; |
| 764 |
if ($CAPTURE) { |
| 765 |
print "Capture mode enabled, $PROGRAM will ended after one single loop.\n\n"; |
| 766 |
} else { |
| 767 |
print "Type Ctrl+c to quit.\n\n"; |
| 768 |
} |
| 769 |
} |
| 770 |
else |
| 771 |
{ |
| 772 |
# detach from terminal |
| 773 |
my $pid = fork; |
| 774 |
exit 0 if ($pid); |
| 775 |
die "FATAL: Couldn't fork: $!" unless defined($pid); |
| 776 |
POSIX::setsid() or die "Can't detach: \$!"; |
| 777 |
&dprint("LOG: Detach from terminal with pid: $$\n"); |
| 778 |
open(STDIN , '<', "/dev/null"); |
| 779 |
open(STDOUT, '>', "/dev/null"); |
| 780 |
open(STDERR, '>', "/dev/null"); |
| 781 |
} |
| 782 |
|
| 783 |
|
| 784 |
# Set name of the program without path |
| 785 |
my $orig_name = $0; |
| 786 |
$0 = $PROGRAM; |
| 787 |
|
| 788 |
# Create pid file |
| 789 |
my $fhp = IO::File->new($PIDFILE, 'w'); |
| 790 |
if (not defined $fhp) { |
| 791 |
die "FATAL: can't create pid file $PIDFILE, $!\n"; |
| 792 |
} |
| 793 |
print $fhp $$; |
| 794 |
close($fhp); |
| 795 |
|
| 796 |
# Generate the psql commands |
| 797 |
$PSQL_PROG .= " -XAtq -F';' "; |
| 798 |
my $PGBOUNCER_PROG = $PSQL_PROG . ' ' . $PGBOUNCER_ARGS . ' pgbouncer'; |
| 799 |
$PSQL_PROG .= " -f - "; |
| 800 |
|
| 801 |
|
| 802 |
if ($NO_DATABASE) { |
| 803 |
$PSQL_PROG = ''; |
| 804 |
} else { |
| 805 |
$PSQL_PROG .= " -h $DBHOST" if ($DBHOST); |
| 806 |
$PSQL_PROG .= " -p $DBPORT" if ($DBPORT); |
| 807 |
$PSQL_PROG .= " -U $DBUSER" if ($DBUSER); |
| 808 |
if ($#dbnames >= 0) { |
| 809 |
if ($dbnames[0] !~ /^[a-z0-9\_\-]+$/i) { |
| 810 |
$PSQL_PROG .= " -d '$dbnames[0]'"; |
| 811 |
} else { |
| 812 |
$PSQL_PROG .= " -d $dbnames[0]"; |
| 813 |
} |
| 814 |
} |
| 815 |
if ($DBPASS) { |
| 816 |
$ENV{PGPASSWORD} = $DBPASS; |
| 817 |
} |
| 818 |
} |
| 819 |
|
| 820 |
# Try to grab the sysstat version |
| 821 |
my $sysstat_version = ''; |
| 822 |
if (!$CAPTURE) { |
| 823 |
$sysstat_version = &sysstat_version() || ''; |
| 824 |
} |
| 825 |
|
| 826 |
# Remove action that can't be run with the PostgreSQL version |
| 827 |
my $PG_RET = ''; |
| 828 |
$PG_RET = &verify_action() if (!$NO_DATABASE); |
| 829 |
|
| 830 |
# Look if we should limit statistic collect to some DB |
| 831 |
my @included_dbs = (); |
| 832 |
@included_dbs = split(/,/, $INCLUDED_DB) if ($INCLUDED_DB); |
| 833 |
|
| 834 |
# end counter |
| 835 |
my $tcounter = 0; |
| 836 |
|
| 837 |
# Force rotation in incremental mode |
| 838 |
if ($INCREMENTAL) { |
| 839 |
$D_ROTATE = 1; |
| 840 |
$H_ROTATE = 1; |
| 841 |
} |
| 842 |
|
| 843 |
my $previous_time = 0; |
| 844 |
while (1) |
| 845 |
{ |
| 846 |
# Stores loop start time |
| 847 |
my $t0 = time; |
| 848 |
|
| 849 |
# Do not collect metrics if previous time is upper than current time. |
| 850 |
# This is to prevent collecting statistics twice when the hour change |
| 851 |
# for daylight saving. |
| 852 |
if ($previous_time && ($t0 < $previous_time)) { |
| 853 |
# Wait next run following the interval value |
| 854 |
sleep($INTERVAL); |
| 855 |
next; |
| 856 |
} |
| 857 |
$previous_time = $t0; |
| 858 |
|
| 859 |
# Search if the monitoring need to stop here |
| 860 |
if ($END_AFTER && ($t0 > ($START_TIME + $END_AFTER))) { |
| 861 |
unlink_pid_and_exit("LOG: ending time reach, terminating.", 0); |
| 862 |
} |
| 863 |
|
| 864 |
# If counter reached then exit |
| 865 |
$tcounter++; |
| 866 |
|
| 867 |
if (($END_AFTER_COUNTER > 0) && ($tcounter > $END_AFTER_COUNTER)) { |
| 868 |
unlink_pid_and_exit("LOG: counter reached, terminating.", 0); |
| 869 |
} |
| 870 |
|
| 871 |
# Some time range may not collect data |
| 872 |
my ($sec , $min, $hour, $mday, $mon, $year, @other) = localtime(time); |
| 873 |
$min = "0$min" if ($min < 10); |
| 874 |
$hour = "0$hour" if ($hour < 10); |
| 875 |
$mday = "0$mday" if ($mday < 10); |
| 876 |
$mon++; |
| 877 |
$mon = "0$mon" if ($mon < 10); |
| 878 |
$year += 1900; |
| 879 |
if (!$CAPTURE) |
| 880 |
{ |
| 881 |
for (my $i = 0; $i <= $#SKIP_BEGIN; $i++) |
| 882 |
{ |
| 883 |
if ( $SKIP_BEGIN[$i] <= $SKIP_END[$i] ) |
| 884 |
{ |
| 885 |
if ( ("$hour$min" >= $SKIP_BEGIN[$i]) && ("$hour$min" <= $SKIP_END[$i]) ) |
| 886 |
{ |
| 887 |
# Wait next run |
| 888 |
sleep($INTERVAL); |
| 889 |
next; |
| 890 |
} |
| 891 |
} |
| 892 |
elsif ( $SKIP_BEGIN[$i] > $SKIP_END[$i] ) |
| 893 |
{ |
| 894 |
if ( ("$hour$min" >= $SKIP_BEGIN[$i]) && ("$hour$min" < 2400) || |
| 895 |
("$hour$min" <= $SKIP_END[$i]) && ("$hour$min" > 0)) |
| 896 |
{ |
| 897 |
# Wait for next run |
| 898 |
sleep($INTERVAL); |
| 899 |
next; |
| 900 |
} |
| 901 |
} |
| 902 |
} |
| 903 |
} |
| 904 |
|
| 905 |
#### |
| 906 |
# Output dir is now relative to $OUTPUT_DIR because we have chdir to that directory. |
| 907 |
#### |
| 908 |
|
| 909 |
# Compress previous daily directory if required |
| 910 |
if ($COMPRESS && $OLD_OUT_DIR && ($OLD_OUT_DIR ne "$year/$mon/$mday") && $D_ROTATE && !$H_ROTATE) |
| 911 |
{ |
| 912 |
# Fork a process to compress old data files in parallel |
| 913 |
&spawn_compress(sub { |
| 914 |
&compress_files($OLD_OUT_DIR); |
| 915 |
}); |
| 916 |
} |
| 917 |
|
| 918 |
# Set daily rotation subdirectories |
| 919 |
if ($D_ROTATE && !$H_ROTATE && !-d "$year/$mon/$mday") |
| 920 |
{ |
| 921 |
mkdir("$year") if (!-d "$year"); |
| 922 |
mkdir("$year/$mon") if (!-d "$year/$mon"); |
| 923 |
mkdir("$year/$mon/$mday"); |
| 924 |
# Set the new output directory |
| 925 |
$OUT_DIR = "$year/$mon/$mday"; |
| 926 |
dprint ("Created OUT_DIR: $OUT_DIR \n") ; |
| 927 |
} |
| 928 |
elsif ($D_ROTATE) |
| 929 |
{ |
| 930 |
# Set the new output directory |
| 931 |
$OUT_DIR = "$year/$mon/$mday"; |
| 932 |
dprint ("OUT_DIR is: $OUT_DIR \n") if ($initial_run); |
| 933 |
} |
| 934 |
|
| 935 |
# Compress previous hourly directory if required |
| 936 |
if ($COMPRESS && $OLD_OUT_DIR && ($OLD_OUT_DIR ne "$year/$mon/$mday/$hour") && $H_ROTATE) |
| 937 |
{ |
| 938 |
# Fork a process to compress old data files in parallel |
| 939 |
&spawn_compress(sub { |
| 940 |
&compress_files($OLD_OUT_DIR); |
| 941 |
}); |
| 942 |
} |
| 943 |
|
| 944 |
# Set hourly rotation/incremental subdirectories |
| 945 |
if ($H_ROTATE && !-d "$year/$mon/$mday/$hour") |
| 946 |
{ |
| 947 |
mkdir("$year") if (!-d "$year"); |
| 948 |
mkdir("$year/$mon") if (!-d "$year/$mon"); |
| 949 |
mkdir("$year/$mon/$mday") if (!-d "$year/$mon/$mday"); |
| 950 |
mkdir("$year/$mon/$mday/$hour"); |
| 951 |
# Set the new output directory |
| 952 |
$OUT_DIR = "$year/$mon/$mday/$hour"; |
| 953 |
dprint ("Created OUT_DIR: $OUT_DIR \n") ; |
| 954 |
} |
| 955 |
elsif ($H_ROTATE) |
| 956 |
{ |
| 957 |
# Set the new output directory |
| 958 |
$OUT_DIR = "$year/$mon/$mday/$hour"; |
| 959 |
dprint ("OUT_DIR is: $OUT_DIR \n") if ($initial_run); |
| 960 |
} |
| 961 |
elsif (!$D_ROTATE) |
| 962 |
{ |
| 963 |
$OUT_DIR = $OUTPUT_DIR; |
| 964 |
dprint ("OUT_DIR is: $OUT_DIR \n") if ($initial_run); |
| 965 |
} |
| 966 |
|
| 967 |
# If we have a retention limit remove everything older |
| 968 |
if ($RETENTION > 0 && $OUTPUT_DIR && $year) |
| 969 |
{ |
| 970 |
# We don't use the output directory as root dir but the year |
| 971 |
# subdirectory. Rewind to previous year first in case we have |
| 972 |
# year overlap. |
| 973 |
$year--; |
| 974 |
if (-d "$OUTPUT_DIR/$year") { |
| 975 |
`find '$OUTPUT_DIR/$year/' -name '*' -mtime +$RETENTION -delete`; |
| 976 |
} |
| 977 |
$year++; |
| 978 |
if (-d "$OUTPUT_DIR/$year") { |
| 979 |
`find '$OUTPUT_DIR/$year/' -name '*' -mtime +$RETENTION -delete`; |
| 980 |
} |
| 981 |
} |
| 982 |
|
| 983 |
# Set the sar and pidstat command |
| 984 |
my $sar_command = ''; |
| 985 |
my $pidstat_command = ''; |
| 986 |
if (!$DISABLE_SAR && $sysstat_version) |
| 987 |
{ |
| 988 |
$sar_command = ($sshcmd) ? $sshcmd . ' "' . $def_sar_command . ' "' : $def_sar_command; |
| 989 |
$sar_command .= " >>'$OUT_DIR/$SAR_FILE'"; |
| 990 |
if (!$DISABLE_PIDSTAT) |
| 991 |
{ |
| 992 |
$pidstat_command = ($sshcmd) ? $sshcmd . ' "' . $def_pidstat_command . ' "' : $def_pidstat_command; |
| 993 |
$pidstat_command .= " >>'$OUT_DIR/$PIDSTAT_FILE'"; |
| 994 |
} |
| 995 |
|
| 996 |
# Start processes to collect system statistics permanently |
| 997 |
&spawn_sar(sub { |
| 998 |
&collect_sysstat($sar_command); |
| 999 |
}); |
| 1000 |
if (!$DISABLE_PIDSTAT) |
| 1001 |
{ |
| 1002 |
&spawn_pidstat(sub { |
| 1003 |
&collect_sysstat($pidstat_command); |
| 1004 |
}); |
| 1005 |
} |
| 1006 |
} |
| 1007 |
|
| 1008 |
# Collect all metrics about the cluster |
| 1009 |
&collect_metrics(); |
| 1010 |
$initial_run = 0; |
| 1011 |
|
| 1012 |
# stores previous directory to check when rotated files must compressed |
| 1013 |
$OLD_OUT_DIR = $OUT_DIR; |
| 1014 |
|
| 1015 |
# Wait for metric + compress child process to terminate |
| 1016 |
&wait_all_childs(); |
| 1017 |
|
| 1018 |
# We received a signal while waiting |
| 1019 |
last if ($done || $fini); |
| 1020 |
|
| 1021 |
if (!$CAPTURE) |
| 1022 |
{ |
| 1023 |
# Lookup if output dir size is upper than limit |
| 1024 |
if ($MAX_SIZE) |
| 1025 |
{ |
| 1026 |
my $lsize = `du -s '$OUTPUT_DIR'`; |
| 1027 |
chomp($lsize); |
| 1028 |
if ($lsize > $MAX_SIZE) { |
| 1029 |
unlink_pid_and_exit("LOG: max size limit reach, terminating.", 0); |
| 1030 |
} |
| 1031 |
} |
| 1032 |
|
| 1033 |
# Wait next run following the interval value |
| 1034 |
my $t1 = time - $t0; |
| 1035 |
if ($t1 >= $INTERVAL) |
| 1036 |
{ |
| 1037 |
print "WARNING: loop took: $t1 seconds, you may consider increase the interval ($INTERVAL sec) using -i option.\n"; |
| 1038 |
# Wait next run following the interval value |
| 1039 |
sleep($INTERVAL); |
| 1040 |
} |
| 1041 |
else |
| 1042 |
{ |
| 1043 |
# Wait next run following the interval value minus the loop time |
| 1044 |
sleep($INTERVAL - $t1); |
| 1045 |
} |
| 1046 |
} |
| 1047 |
else |
| 1048 |
{ |
| 1049 |
# get out of the main loop |
| 1050 |
last; |
| 1051 |
} |
| 1052 |
|
| 1053 |
# We received a HUP signal or a TERM/INT signal |
| 1054 |
last if ($done || $fini); |
| 1055 |
} |
| 1056 |
|
| 1057 |
# Wait for last child stop |
| 1058 |
&wait_all_childs(); |
| 1059 |
|
| 1060 |
# In capture mode we have to create a tarball |
| 1061 |
if ($CAPTURE) { |
| 1062 |
# be sure to be in the parent directory |
| 1063 |
chdir($CAPTURE_DIR); |
| 1064 |
# Then create a tarball before removing the output directory |
| 1065 |
print "INFO: creating archive $CAPTURE_DIR/pgcluu_capture.tar.gz of the capture directory $CAPTURE_DIR/$OUTPUT_DIR.\n"; |
| 1066 |
`$TAR_PROG pgcluu_capture.tar.gz '$OUTPUT_DIR'`; |
| 1067 |
# Removing temporary directory and ensure that we are not removing anything else |
| 1068 |
print "INFO: removing capture temporary directory: $CAPTURE_DIR/$OUTPUT_DIR\n"; |
| 1069 |
if ($OUTPUT_DIR eq 'pgcluu_capture') { |
| 1070 |
`rm -rf '$OUTPUT_DIR'`; |
| 1071 |
} |
| 1072 |
} |
| 1073 |
|
| 1074 |
if (-f $PIDFILE) { |
| 1075 |
unlink("$PIDFILE") or &dprint("ERROR: Unable to remove pid file $PIDFILE, $!\n"); |
| 1076 |
} |
| 1077 |
|
| 1078 |
exit 0; |
| 1079 |
|
| 1080 |
#### |
| 1081 |
# Collect system information using the given command |
| 1082 |
#### |
| 1083 |
sub collect_sysstat |
| 1084 |
{ |
| 1085 |
local $SIG{USR1} = sub { |
| 1086 |
print STDERR "Received terminate signal, exiting.\n"; |
| 1087 |
exit 1; |
| 1088 |
}; |
| 1089 |
$0 = "pgcluu_collectd: $_[0]"; |
| 1090 |
|
| 1091 |
`$_[0]`; |
| 1092 |
} |
| 1093 |
|
| 1094 |
#### |
| 1095 |
# Collect system information about the cluster |
| 1096 |
#### |
| 1097 |
sub collect_metrics |
| 1098 |
{ |
| 1099 |
# Use a temporary file, final file sysinfo.txt is overridden at end of the function |
| 1100 |
if (-e "$OUT_DIR/sysinfo.txt.tmp") { |
| 1101 |
# Remove old system information file |
| 1102 |
unlink("$OUT_DIR/sysinfo.txt.tmp"); |
| 1103 |
} |
| 1104 |
|
| 1105 |
# Store current pgcluu configuration |
| 1106 |
my $fhl = IO::File->new("$OUT_DIR/sysinfo.txt.tmp", 'a'); |
| 1107 |
if (not defined $fhl) { |
| 1108 |
&dprint("FATAL: can not write into file $OUT_DIR/sysinfo.txt\n"); |
| 1109 |
unlink_pid_and_exit("FATAL: can not write into file $OUT_DIR/sysinfo.txt.tmp, $!", 1); |
| 1110 |
} |
| 1111 |
print $fhl "[CONFIGURATION]\n"; |
| 1112 |
print $fhl "capture=$CAPTURE\n"; |
| 1113 |
print $fhl "sysstat=$sysstat_version\n" if ($sysstat_version); |
| 1114 |
close($fhl); |
| 1115 |
|
| 1116 |
# Collect PostgreSQL global cluster information and save all into $OUT_DIR/sysinfo.txt |
| 1117 |
# Diff with old collected information will be saved to sysinfo.txt.diff |
| 1118 |
if (!$NO_DATABASE && ($PG_RET >= 0)) { |
| 1119 |
&get_initial_info(); |
| 1120 |
} |
| 1121 |
|
| 1122 |
# Get System information and save all into $OUT_DIR/sysinfo.txt |
| 1123 |
# Diff with old collected information will be saved to sysinfo.txt.diff |
| 1124 |
if (!$NO_SYSINFO) { |
| 1125 |
&grab_os_information($OUT_DIR); |
| 1126 |
} |
| 1127 |
|
| 1128 |
#### |
| 1129 |
# Stores settings and detect change |
| 1130 |
#### |
| 1131 |
if (!$NO_DATABASE) { |
| 1132 |
# Collect previous PostgreSQL settings to track changes |
| 1133 |
&load_settings($OUT_DIR, \%ORIGINAL_PG_SETTINGS,\%ORIGINAL_DBROLE_SETTINGS); |
| 1134 |
} |
| 1135 |
|
| 1136 |
# Copy configuration files into output directory and keep track of change |
| 1137 |
if (!$NO_DATABASE && ($#METRICS >= 0) && grep(/^configuration_stats$/, @METRICS)) |
| 1138 |
{ |
| 1139 |
my @conf_files = $METRICS_COMMANDS{'configuration_stats'}->{command}->(); |
| 1140 |
@conf_files = () if ($PG_RET < 0); |
| 1141 |
my $outdir = $OUT_DIR; |
| 1142 |
$outdir = "$CAPTURE_DIR/$OUT_DIR" if ($CAPTURE); |
| 1143 |
foreach my $f (@conf_files, '/etc/pgbouncer/pgbouncer.ini') |
| 1144 |
{ |
| 1145 |
my $filename = basename($f); |
| 1146 |
# Rename old file to be able to perform a diff |
| 1147 |
if (-e "$OUT_DIR/$filename") { |
| 1148 |
# Unlink any temporary renaming of file (can only appears with a crash/interrupt) |
| 1149 |
unlink("$OUT_DIR/$filename.tmpold"); |
| 1150 |
rename ("$OUT_DIR/$filename","$OUT_DIR/$filename.tmpold"); |
| 1151 |
} |
| 1152 |
if ($sshcmd) { |
| 1153 |
`$sshcmd "$CAT_PROG $f" >"$outdir/$filename" 2>/dev/null`; |
| 1154 |
} else { |
| 1155 |
`$CAT_PROG $f >"$outdir/$filename" 2>/dev/null`; |
| 1156 |
} |
| 1157 |
if (-z "$OUT_DIR/$filename") { |
| 1158 |
# remove file when empty |
| 1159 |
unlink("$OUT_DIR/$filename" ); |
| 1160 |
} elsif (-e "$OUT_DIR/$filename.tmpold") { |
| 1161 |
# Perform a diff to keep track of configuration change |
| 1162 |
`$DIFF_PROG "$OUT_DIR/$filename.tmpold" "$OUT_DIR/$filename" >> "$OUT_DIR/$filename.diff"`; |
| 1163 |
unlink("$OUT_DIR/$filename.tmpold"); |
| 1164 |
# When there's no change do not keep the file |
| 1165 |
if (-z "$OUT_DIR/$filename.diff") { |
| 1166 |
unlink("$OUT_DIR/$filename.diff"); |
| 1167 |
} |
| 1168 |
} |
| 1169 |
} |
| 1170 |
} |
| 1171 |
|
| 1172 |
# Remove files that must be overriden |
| 1173 |
foreach my $type (sort {$a cmp $b} keys %METRICS_COMMANDS) |
| 1174 |
{ |
| 1175 |
if ($METRICS_COMMANDS{$type}->{override} && -e "$OUT_DIR/$METRICS_COMMANDS{$type}->{output}") |
| 1176 |
{ |
| 1177 |
unlink("$OUT_DIR/$METRICS_COMMANDS{$type}->{output}"); |
| 1178 |
} |
| 1179 |
if ($METRICS_COMMANDS{$type}->{'start-end'} && -e "$OUT_DIR/end-$METRICS_COMMANDS{$type}->{output}") |
| 1180 |
{ |
| 1181 |
# Keep the file but remove its content |
| 1182 |
if ( open(my $outf, '>', "$OUT_DIR/end-$METRICS_COMMANDS{$type}->{output}") ) { |
| 1183 |
close($outf); |
| 1184 |
} |
| 1185 |
} |
| 1186 |
} |
| 1187 |
|
| 1188 |
# Generating global statistics collector SQL script |
| 1189 |
my $script_sql = &create_sql_script(); |
| 1190 |
|
| 1191 |
if (!$script_sql && ($#METRICS < 0)) |
| 1192 |
{ |
| 1193 |
# No action can be perform with this PostgreSQL version |
| 1194 |
unlink_pid_and_exit("FATAL: no action will be run on this PostgreSQL version $DB_INFO{major}.$DB_INFO{minor}, $!", 1); |
| 1195 |
} |
| 1196 |
if (!$NO_DATABASE) |
| 1197 |
{ |
| 1198 |
# Collecting database statistics if there other than pgbouncer metrics to collect |
| 1199 |
if ($PG_RET >= 0) |
| 1200 |
{ |
| 1201 |
if (open(my $fhl, '|-', $PSQL_PROG)) { |
| 1202 |
print $fhl $script_sql, "\n"; |
| 1203 |
close($fhl); |
| 1204 |
} else { |
| 1205 |
&dprint("FATAL: failure when calling psql command: $PSQL_PROG, $!\n"); |
| 1206 |
unlink_pid_and_exit("FATAL: failure when calling psql command: $PSQL_PROG, $!", 1); |
| 1207 |
} |
| 1208 |
|
| 1209 |
# Get database list |
| 1210 |
my @dblist = &get_databases(); |
| 1211 |
push(@dblist, $DBNAME) if (($#dblist == -1) && $DBNAME); |
| 1212 |
|
| 1213 |
# Generating per database statistics collector SQL script |
| 1214 |
foreach my $db (@dblist) |
| 1215 |
{ |
| 1216 |
|
| 1217 |
next if (($#included_dbs >= 0) && !grep(/^$db$/i, @included_dbs)); |
| 1218 |
my $script_repeat_sql = &create_sql_script($db); |
| 1219 |
if (!$script_repeat_sql) { |
| 1220 |
last; |
| 1221 |
} |
| 1222 |
my $LOCAL_PSQL_PROG = &set_local_psql_command($db); |
| 1223 |
|
| 1224 |
# Collecting database statistics |
| 1225 |
if (open(my $fhl, '|-', $LOCAL_PSQL_PROG)) { |
| 1226 |
print $fhl $script_repeat_sql, "\n"; |
| 1227 |
close($fhl); |
| 1228 |
} else { |
| 1229 |
&dprint("FATAL: failure when calling psql command: $LOCAL_PSQL_PROG, $!\n"); |
| 1230 |
unlink_pid_and_exit("FATAL: failure when calling psql command: $LOCAL_PSQL_PROG, $!", 1); |
| 1231 |
} |
| 1232 |
} |
| 1233 |
} |
| 1234 |
|
| 1235 |
# Keep track of settings change |
| 1236 |
if (scalar keys %ORIGINAL_PG_SETTINGS > 0) |
| 1237 |
{ |
| 1238 |
my %current_pg_settings = (); |
| 1239 |
my %current_dbrole_settings = (); |
| 1240 |
# Collect current PostgreSQL settings to look compare values |
| 1241 |
&load_settings($OUT_DIR, \%current_pg_settings,\%current_dbrole_settings); |
| 1242 |
# Save pg_settings into a temporary files |
| 1243 |
my ($file1, $file2) = &save_pg_settings($OUT_DIR, \%ORIGINAL_PG_SETTINGS,\%current_pg_settings); |
| 1244 |
# Perform a diff to keep track of configuration change |
| 1245 |
`$DIFF_PROG "$file1" "$file2" >> "$OUT_DIR/pg_settings.diff"`; |
| 1246 |
unlink($file2, $file1); |
| 1247 |
# When there's no change do not keep the file |
| 1248 |
if (-z "$OUT_DIR/pg_settings.diff") { |
| 1249 |
unlink("$OUT_DIR/pg_settings.diff"); |
| 1250 |
} |
| 1251 |
# Save settings into temporaries files |
| 1252 |
($file1, $file2) = &save_dbrole_settings($OUT_DIR, \%ORIGINAL_DBROLE_SETTINGS,\%current_dbrole_settings); |
| 1253 |
# Perform a diff to keep track of configuration change |
| 1254 |
`$DIFF_PROG "$file1" "$file2" >> "$OUT_DIR/pg_db_role_setting.diff"`; |
| 1255 |
# When there's no change do not keep the file |
| 1256 |
if (-z "$OUT_DIR/pg_db_role_setting.diff") { |
| 1257 |
unlink("$OUT_DIR/pg_db_role_setting.diff"); |
| 1258 |
} |
| 1259 |
unlink($file2, $file1); |
| 1260 |
} |
| 1261 |
} |
| 1262 |
|
| 1263 |
# Collecting pgbouncer statistics |
| 1264 |
if ($PGBOUNCER_ARGS) |
| 1265 |
{ |
| 1266 |
foreach my $c (@METRICS) |
| 1267 |
{ |
| 1268 |
next if ($c !~ /^pgbouncer_/); |
| 1269 |
# create a timestamp to registrer pgbouncer statistics |
| 1270 |
my $timestamp = &get_current_timestamp(); |
| 1271 |
|
| 1272 |
my $sql = ''; |
| 1273 |
eval { $sql = &{$METRICS_COMMANDS{$c}->{command}}; }; |
| 1274 |
if (!$sql || $@) { |
| 1275 |
if (-f $PIDFILE) { |
| 1276 |
unlink("$PIDFILE") or &dprint("ERROR: Unable to remove pid file $PIDFILE, $!\n"); |
| 1277 |
} |
| 1278 |
die "FATAL: no SQL with metric command pgbouncer_stats ($sql).\n" if (!$sql || $@); |
| 1279 |
} |
| 1280 |
|
| 1281 |
# Remove lock_timeout from PGOPTIONS environment variable |
| 1282 |
# when querying pgbouncer, it is restored after the command |
| 1283 |
my $tmp_pgopt = $ENV{PGOPTIONS}; |
| 1284 |
$tmp_pgopt =~ s/ -c lock_timeout=\d+s//; |
| 1285 |
$ENV{PGOPTIONS} = $tmp_pgopt; |
| 1286 |
# Get statistics from pgbouncer |
| 1287 |
`$PGBOUNCER_PROG -c "$sql" | sed 's/^/$timestamp;/' $FILE_REDIR '$OUT_DIR/$METRICS_COMMANDS{$c}->{output}'`; |
| 1288 |
# Restore PGOPTIONS environment variable |
| 1289 |
$ENV{PGOPTIONS} = "$ENV{PGOPTIONS} -c lock_timeout=${LOCK_TIMEOUT}s"; |
| 1290 |
if ($? != 0) { |
| 1291 |
&dprint("LOG: $PGBOUNCER_PROG -c \"$sql\" | sed 's/^/$timestamp;/' $FILE_REDIR '$OUT_DIR/$METRICS_COMMANDS{$c}->{output}'\n"); |
| 1292 |
&dprint("ERROR: pgbouncer pool query failure, $!\n"); |
| 1293 |
} |
| 1294 |
} |
| 1295 |
} |
| 1296 |
|
| 1297 |
if (!$NO_SYSINFO && $sysstat_version lt "11.7.4") |
| 1298 |
{ |
| 1299 |
# Store filesystem use information |
| 1300 |
my @fsuse = `$DF_COMMAND 2>/dev/null`; |
| 1301 |
if ($#fsuse > 0) { |
| 1302 |
shift(@fsuse); # remove header |
| 1303 |
chomp(@fsuse); |
| 1304 |
my $ntime = &get_current_timestamp(); |
| 1305 |
map { s/\s+/;/g; s/^/$ntime;/; } @fsuse; # format output to csv |
| 1306 |
# Filesystem;1K-blocks;Used;Avail;Inodes;IUsed;IFree;Typer;Mounted on |
| 1307 |
$fhl = IO::File->new("$OUT_DIR/fs_stat_use.csv", 'a'); |
| 1308 |
if (not defined $fhl) { |
| 1309 |
&dprint("FATAL: can not write into file $OUT_DIR/fs_stat_use.csv\n"); |
| 1310 |
unlink_pid_and_exit("FATAL: can not write into file $OUT_DIR/fs_stat_use.csv, $!", 1); |
| 1311 |
} |
| 1312 |
print $fhl join("\n", @fsuse), "\n"; |
| 1313 |
close($fhl); |
| 1314 |
} |
| 1315 |
} |
| 1316 |
|
| 1317 |
# Override sysinfo.txt to be atomic |
| 1318 |
if (-e "$OUT_DIR/sysinfo.txt.tmp") { |
| 1319 |
`mv -f '$OUT_DIR/sysinfo.txt.tmp' '$OUT_DIR/sysinfo.txt'`; |
| 1320 |
} |
| 1321 |
} |
| 1322 |
|
| 1323 |
sub get_initial_info |
| 1324 |
{ |
| 1325 |
return if ($NO_DATABASE); |
| 1326 |
|
| 1327 |
# Get list of database in the PostgreSQL cluster |
| 1328 |
my @alldbs = (); |
| 1329 |
if ($#dbnames >= 0) { |
| 1330 |
# from command line |
| 1331 |
push(@alldbs, @dbnames); |
| 1332 |
} else { |
| 1333 |
# or by querying the database list |
| 1334 |
@alldbs = &get_databases(); |
| 1335 |
} |
| 1336 |
|
| 1337 |
# Store PG version into sysinfo file |
| 1338 |
&fetch_version(1); |
| 1339 |
|
| 1340 |
# Store PG uptime into sysinfo file |
| 1341 |
&get_uptime(1); |
| 1342 |
|
| 1343 |
# Collect general information about each database |
| 1344 |
if ($#alldbs > -1) |
| 1345 |
{ |
| 1346 |
@extensions = (); |
| 1347 |
my @schemas = (); |
| 1348 |
my @json = (); |
| 1349 |
my @procs = (); |
| 1350 |
my @trigs = (); |
| 1351 |
my %parts = (); |
| 1352 |
my $fhl = IO::File->new("$OUT_DIR/sysinfo.txt.tmp", 'a'); |
| 1353 |
if (not defined $fhl) { |
| 1354 |
&dprint("FATAL: can not write into file $OUT_DIR/sysinfo.txt.tmp\n"); |
| 1355 |
unlink_pid_and_exit("FATAL: can not write into file $OUT_DIR/sysinfo.txt.tmp, $!", 1); |
| 1356 |
} |
| 1357 |
if (&backend_minimum_version(9, 1)) { |
| 1358 |
# Look for all installed extensions |
| 1359 |
print $fhl "[EXTENSION]\n"; |
| 1360 |
foreach my $db (sort @alldbs) |
| 1361 |
{ |
| 1362 |
my @ext = &get_extensions($db); |
| 1363 |
push(@extensions, "$db=" . join(',', sort @ext)) if ($#ext >= 0); |
| 1364 |
} |
| 1365 |
foreach my $e (@extensions) { |
| 1366 |
print $fhl "$e\n"; |
| 1367 |
} |
| 1368 |
} |
| 1369 |
# Look for all schema in a database |
| 1370 |
print $fhl "[SCHEMA]\n"; |
| 1371 |
foreach my $db (sort @alldbs) { |
| 1372 |
my @sch = &get_schemas($db); |
| 1373 |
push(@schemas, "$db=" . join(',', sort @sch)) if ($#sch >= 0); |
| 1374 |
} |
| 1375 |
foreach my $s (@schemas) { |
| 1376 |
print $fhl "$s\n"; |
| 1377 |
} |
| 1378 |
# Look for all JSON vs JSONB columns in a database |
| 1379 |
print $fhl "[JSON]\n"; |
| 1380 |
foreach my $db (sort @alldbs) { |
| 1381 |
my @col = &get_json_cols($db); |
| 1382 |
push(@json, "$db=" . join(',', sort @col)) if ($#col >= 0); |
| 1383 |
} |
| 1384 |
foreach my $s (@json) { |
| 1385 |
print $fhl "$s\n"; |
| 1386 |
} |
| 1387 |
# Look for all procedure in a database |
| 1388 |
print $fhl "[PROCEDURE]\n"; |
| 1389 |
foreach my $db (sort @alldbs) { |
| 1390 |
my $pro = &get_proc_count($db); |
| 1391 |
push(@procs, "$db=" . $pro); |
| 1392 |
} |
| 1393 |
foreach my $p (@procs) { |
| 1394 |
print $fhl "$p\n"; |
| 1395 |
} |
| 1396 |
# Look for all schema in a database |
| 1397 |
print $fhl "[TRIGGER]\n"; |
| 1398 |
foreach my $db (sort @alldbs) { |
| 1399 |
my $tgs = &get_triggers($db); |
| 1400 |
push(@trigs, "$db=$tgs"); |
| 1401 |
} |
| 1402 |
foreach my $t (@trigs) { |
| 1403 |
print $fhl "$t\n"; |
| 1404 |
} |
| 1405 |
# Look for partitionned tables in a database |
| 1406 |
print $fhl "[PARTITIONNED_TABLE]\n"; |
| 1407 |
foreach my $db (sort @alldbs) { |
| 1408 |
my @p = &get_partitionned_tables($db); |
| 1409 |
|
| 1410 |
# Get general partition information |
| 1411 |
foreach my $line (@p) { |
| 1412 |
my ($oid, $content) = split(/[;]/, $line, 2); |
| 1413 |
|
| 1414 |
$parts{$oid} = $db; |
| 1415 |
print $fhl "$db=$oid;$content\n"; |
| 1416 |
} |
| 1417 |
} |
| 1418 |
# get trigger or rule definition of each partitionned table |
| 1419 |
foreach my $oid (sort keys %parts) { |
| 1420 |
my $db = $parts{$oid}; |
| 1421 |
my @implementation = &get_partitionned_implementation($db, $oid); |
| 1422 |
|
| 1423 |
print $fhl "[PARTITION_IMPL $db $oid]\n"; |
| 1424 |
foreach my $line (@implementation) { |
| 1425 |
print $fhl "$line\n"; |
| 1426 |
} |
| 1427 |
} |
| 1428 |
close($fhl); |
| 1429 |
} |
| 1430 |
} |
| 1431 |
|
| 1432 |
sub verify_action |
| 1433 |
{ |
| 1434 |
# Detect PostgreSQL version |
| 1435 |
my $ret = &fetch_version(); |
| 1436 |
|
| 1437 |
# Only pgbouncer metrics and configuration |
| 1438 |
if ($ret < 0) { |
| 1439 |
foreach my $m (keys %METRICS_COMMANDS) |
| 1440 |
{ |
| 1441 |
delete $METRICS_COMMANDS{$m} if (($m ne 'configuration_stats') && ($m !~ /pgbouncer/)); |
| 1442 |
} |
| 1443 |
return $ret; |
| 1444 |
} |
| 1445 |
# Remove some metric collection following the PostgreSQL version. |
| 1446 |
if (!&backend_minimum_version(10, 0)) { |
| 1447 |
delete $METRICS_COMMANDS{'statistics_stats'}; |
| 1448 |
} |
| 1449 |
if (!&backend_minimum_version(9, 4)) { |
| 1450 |
delete $METRICS_COMMANDS{'archiver_stats'}; |
| 1451 |
} |
| 1452 |
if (!&backend_minimum_version(8, 3)) { |
| 1453 |
delete $METRICS_COMMANDS{'bgwriter_stats'}; |
| 1454 |
delete $METRICS_COMMANDS{'pg_buffercache_stats'}; |
| 1455 |
} |
| 1456 |
if (!&backend_minimum_version(9, 1)) { |
| 1457 |
delete $METRICS_COMMANDS{'conflict_stats'}; |
| 1458 |
delete $METRICS_COMMANDS{'replication_stats'}; |
| 1459 |
delete $METRICS_COMMANDS{'unlogged_stats'}; |
| 1460 |
} |
| 1461 |
if (!&backend_minimum_version(9, 0)) { |
| 1462 |
delete $METRICS_COMMANDS{'hot_standby_delay'}; |
| 1463 |
delete $METRICS_COMMANDS{'user_xact_tables_stats'}; |
| 1464 |
delete $METRICS_COMMANDS{'all_xact_tables_stats'}; |
| 1465 |
delete $METRICS_COMMANDS{'xact_functions_stats'}; |
| 1466 |
delete $METRICS_COMMANDS{'pg_db_role_setting_stats'}; |
| 1467 |
} |
| 1468 |
if (!&backend_minimum_version(8, 4)) { |
| 1469 |
delete $METRICS_COMMANDS{'functions_stats'}; |
| 1470 |
delete $METRICS_COMMANDS{'redundant_indexes_stats'}; |
| 1471 |
delete $METRICS_COMMANDS{'invalid_indexes_stats'}; |
| 1472 |
delete $METRICS_COMMANDS{'hash_indexes_stats'}; |
| 1473 |
delete $METRICS_COMMANDS{'missing_fkindexes_stats'}; |
| 1474 |
} |
| 1475 |
if (!&backend_minimum_version(8, 1)) { |
| 1476 |
delete $METRICS_COMMANDS{'xlog_stats'}; |
| 1477 |
delete $METRICS_COMMANDS{'prepared_stats'}; |
| 1478 |
} |
| 1479 |
$DB_INFO{pg_stat_statement} = &has_pgstatstatements(); |
| 1480 |
if ($NO_STATEMENTS || !$DB_INFO{pg_stat_statement}) { |
| 1481 |
delete $METRICS_COMMANDS{'statements_stats'}; |
| 1482 |
} |
| 1483 |
$DB_INFO{pg_subxact_counters} = &has_pgsubxactcounters(); |
| 1484 |
if (!$DB_INFO{pg_subxact_counters}) { |
| 1485 |
delete $METRICS_COMMANDS{'subxact_stats'}; |
| 1486 |
} |
| 1487 |
if (!&is_superuser($DBUSER)) { |
| 1488 |
delete $METRICS_COMMANDS{'xlog_stats'}; |
| 1489 |
} |
| 1490 |
if ($NOTABLESPACE) { |
| 1491 |
delete $METRICS_COMMANDS{'tablespace_size_stats'}; |
| 1492 |
} |
| 1493 |
|
| 1494 |
# Check if the connection database has pg_buffercache installed |
| 1495 |
if (!$USE_BUFFERCACHE || !&has_pg_buffercache()) { |
| 1496 |
delete $METRICS_COMMANDS{'database_buffercache_stats'}; |
| 1497 |
delete $METRICS_COMMANDS{'database_usagecount_stats'}; |
| 1498 |
delete $METRICS_COMMANDS{'relation_buffercache_stats'}; |
| 1499 |
delete $METRICS_COMMANDS{'database_isdirty_stats'}; |
| 1500 |
} |
| 1501 |
|
| 1502 |
return $ret; |
| 1503 |
} |
| 1504 |
|
| 1505 |
sub create_sql_script |
| 1506 |
{ |
| 1507 |
my $db = shift; |
| 1508 |
|
| 1509 |
# Prepare the SQL script |
| 1510 |
my $sql_queries = ''; |
| 1511 |
foreach my $type (sort {$a cmp $b} keys %METRICS_COMMANDS) |
| 1512 |
{ |
| 1513 |
next if (!$db && $METRICS_COMMANDS{$type}->{repeat}); |
| 1514 |
next if ($db && !$METRICS_COMMANDS{$type}->{repeat}); |
| 1515 |
next if ($type =~ /^pgbouncer_|configuration_/); |
| 1516 |
next if (($type =~ /^(user|all)_/) && ($type !~ /^$STAT_TYPE/)); |
| 1517 |
next if (($#METRICS >= 0) && !grep(/^$type$/, @METRICS)); |
| 1518 |
|
| 1519 |
# For these extensions a database to connect is required as they use |
| 1520 |
# shared memory and must always be run only one time. They must all |
| 1521 |
# be installed is the same database. |
| 1522 |
if ($db) |
| 1523 |
{ |
| 1524 |
# Look if there is the pg_stat_statements extension in this database |
| 1525 |
if ($type eq 'statements_stats') |
| 1526 |
{ |
| 1527 |
next if ($NO_STATEMENTS); |
| 1528 |
next if (!grep(/^$db=.*pg_stat_statements/, @extensions)); |
| 1529 |
} |
| 1530 |
# Look if there is the pg_wait_sampling extension in this database |
| 1531 |
if ($type eq 'waitevent_stats') |
| 1532 |
{ |
| 1533 |
next if ($NO_WAITEVENT); |
| 1534 |
next if (!grep(/^$db=.*pg_wait_sampling/, @extensions)); |
| 1535 |
} |
| 1536 |
# Look if there is the pg_subxact_counters extension in this database |
| 1537 |
if ($type eq 'subxact_stats') |
| 1538 |
{ |
| 1539 |
next if (!grep(/^$db=.*pg_subxact_counters/, @extensions)); |
| 1540 |
} |
| 1541 |
} |
| 1542 |
|
| 1543 |
if ($type eq 'stats_stats') |
| 1544 |
{ |
| 1545 |
next if ($NO_PGSTATS_DUMP); |
| 1546 |
} |
| 1547 |
|
| 1548 |
# Get the SQL command to execute for this metric |
| 1549 |
my $sql = $METRICS_COMMANDS{$type}->{command}->(); |
| 1550 |
if (!$sql) { |
| 1551 |
return; |
| 1552 |
} |
| 1553 |
my $file_output = $METRICS_COMMANDS{$type}->{output}; |
| 1554 |
# Metrics that must be saved at start and end only |
| 1555 |
if ($METRICS_COMMANDS{$type}->{'start-end'} && !$initial_run |
| 1556 |
&& -e "$OUT_DIR/$METRICS_COMMANDS{$type}->{output}") |
| 1557 |
{ |
| 1558 |
# Add a prefix to end file so that the first file will be preserved |
| 1559 |
$file_output = 'end-' . $METRICS_COMMANDS{$type}->{output}; |
| 1560 |
} |
| 1561 |
|
| 1562 |
if (&backend_minimum_version(8, 2)) { |
| 1563 |
$sql_queries .= <<EOF |
| 1564 |
\\o | cat > /dev/null |
| 1565 |
$ALWAYS_SECURE_SEARCH_PATH_SQL |
| 1566 |
-- $type |
| 1567 |
\\o | cat $FILE_REDIR '$OUT_DIR/$file_output' |
| 1568 |
COPY ($sql) TO STDOUT CSV DELIMITER ';'; |
| 1569 |
|
| 1570 |
EOF |
| 1571 |
} else { |
| 1572 |
# 8.1 and lower doesn't support select statement into COPY |
| 1573 |
# we use a temporary table instead |
| 1574 |
$sql_queries .= <<EOF |
| 1575 |
\\o | cat > /dev/null |
| 1576 |
$ALWAYS_SECURE_SEARCH_PATH_SQL |
| 1577 |
-- $type |
| 1578 |
\\o | cat $FILE_REDIR '$OUT_DIR/$file_output' |
| 1579 |
BEGIN; |
| 1580 |
CREATE TEMPORARY TABLE __pgcluu as $sql; |
| 1581 |
COPY __pgcluu TO STDOUT CSV DELIMITER ';'; |
| 1582 |
ROLLBACK; |
| 1583 |
|
| 1584 |
EOF |
| 1585 |
} |
| 1586 |
} |
| 1587 |
|
| 1588 |
if ($sql_queries && &backend_minimum_version(9, 0)) { |
| 1589 |
$sql_queries = "SET application_name TO pgcluu;\n" . $sql_queries; |
| 1590 |
} |
| 1591 |
|
| 1592 |
return $sql_queries |
| 1593 |
} |
| 1594 |
|
| 1595 |
sub fetch_version |
| 1596 |
{ |
| 1597 |
my $save = shift; |
| 1598 |
|
| 1599 |
if ($PG_VERSION =~ /^(\d+)/) { |
| 1600 |
$DB_INFO{major} = $1; |
| 1601 |
if ($DB_INFO{major} >= 10) { |
| 1602 |
$DB_INFO{minor} = 0; |
| 1603 |
return "$DB_INFO{major}.0"; |
| 1604 |
} elsif ($PG_VERSION =~ /^(\d+)\.(\d+)/) { |
| 1605 |
$DB_INFO{major} = $1; |
| 1606 |
$DB_INFO{minor} = $2; |
| 1607 |
return "$1.$2"; |
| 1608 |
} |
| 1609 |
} |
| 1610 |
|
| 1611 |
return -1 if ($NO_DATABASE); |
| 1612 |
|
| 1613 |
my $pg_ver = `echo "SELECT version();" | $PSQL_PROG 2>&1`; |
| 1614 |
if ($? != 0) { |
| 1615 |
# Only stop here if there's no pgbouncer querying |
| 1616 |
if (!$PGBOUNCER_ARGS) { |
| 1617 |
unlink_pid_and_exit("FATAL: psql error. $pg_ver", 0); |
| 1618 |
} else { |
| 1619 |
return -1; |
| 1620 |
} |
| 1621 |
} |
| 1622 |
chomp($pg_ver); |
| 1623 |
|
| 1624 |
if ($pg_ver =~ /^(?:PostgreSQL|EnterpriseDB) (\d+)/) { |
| 1625 |
$DB_INFO{major} = $1; |
| 1626 |
if ($DB_INFO{major} >= 10) { |
| 1627 |
$DB_INFO{minor} = 0; |
| 1628 |
} elsif ($pg_ver =~ /^(?:PostgreSQL|EnterpriseDB) (\d+)\.(\d+)/) { |
| 1629 |
$DB_INFO{major} = $1; |
| 1630 |
$DB_INFO{minor} = $2; |
| 1631 |
} |
| 1632 |
} elsif ($pg_ver =~ /(\d+)\.(\d+)(\.\d+)?/) { |
| 1633 |
$DB_INFO{major} = $1; |
| 1634 |
$DB_INFO{minor} = $2; |
| 1635 |
if ($DB_INFO{major} >= 10) { |
| 1636 |
$DB_INFO{minor} = 0; |
| 1637 |
} else { |
| 1638 |
$DB_INFO{minor} = $2; |
| 1639 |
} |
| 1640 |
} |
| 1641 |
|
| 1642 |
if ($save) { |
| 1643 |
my $fhl = IO::File->new("$OUT_DIR/sysinfo.txt", 'a'); |
| 1644 |
if (not defined $fhl) { |
| 1645 |
&dprint("FATAL: can not write into file $OUT_DIR/sysinfo.txt\n"); |
| 1646 |
unlink_pid_and_exit("FATAL: can not write into file $OUT_DIR/sysinfo.txt, $!", 1); |
| 1647 |
} |
| 1648 |
print $fhl "[PGVERSION]\n"; |
| 1649 |
print $fhl "$pg_ver\n"; |
| 1650 |
close($fhl); |
| 1651 |
} |
| 1652 |
|
| 1653 |
return "$DB_INFO{major}.$DB_INFO{minor}"; |
| 1654 |
} |
| 1655 |
|
| 1656 |
#### |
| 1657 |
# Retrieve installed extension for a given database. |
| 1658 |
#### |
| 1659 |
sub get_extensions |
| 1660 |
{ |
| 1661 |
my $database = shift; |
| 1662 |
|
| 1663 |
my $LOCAL_PSQL_PROG = &set_local_psql_command($database); |
| 1664 |
|
| 1665 |
my @db_extension = `echo "SELECT extname||'-'||extversion FROM pg_extension;" | $LOCAL_PSQL_PROG`; |
| 1666 |
if ($? != 0) { |
| 1667 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 1668 |
} |
| 1669 |
chomp(@db_extension); |
| 1670 |
|
| 1671 |
return sort @db_extension; |
| 1672 |
} |
| 1673 |
|
| 1674 |
#### |
| 1675 |
# Get the list of database that are not template and that allow connction |
| 1676 |
#### |
| 1677 |
sub get_databases |
| 1678 |
{ |
| 1679 |
|
| 1680 |
my @dbs = `echo "SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn;" | $PSQL_PROG`; |
| 1681 |
if ($? != 0) { |
| 1682 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 1683 |
} |
| 1684 |
chomp(@dbs); |
| 1685 |
|
| 1686 |
return @dbs; |
| 1687 |
} |
| 1688 |
|
| 1689 |
#### |
| 1690 |
# Get postmater uptime |
| 1691 |
#### |
| 1692 |
sub get_uptime |
| 1693 |
{ |
| 1694 |
my $save = shift; |
| 1695 |
|
| 1696 |
my $uptime = `echo "SELECT pg_postmaster_start_time();" | $PSQL_PROG`; |
| 1697 |
if ($? != 0) { |
| 1698 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 1699 |
} |
| 1700 |
chomp($uptime); |
| 1701 |
|
| 1702 |
if ($save) { |
| 1703 |
my $fhl = IO::File->new("$OUT_DIR/sysinfo.txt", 'a'); |
| 1704 |
if (not defined $fhl) { |
| 1705 |
&dprint("FATAL: can not write into file $OUT_DIR/sysinfo.txt\n"); |
| 1706 |
unlink_pid_and_exit("FATAL: can not write into file $OUT_DIR/sysinfo.txt, $!", 1); |
| 1707 |
} |
| 1708 |
print $fhl "[PGUPTIME]\n"; |
| 1709 |
print $fhl "$uptime\n"; |
| 1710 |
close($fhl); |
| 1711 |
} |
| 1712 |
return $uptime; |
| 1713 |
} |
| 1714 |
|
| 1715 |
#### |
| 1716 |
# Get PGDATA path |
| 1717 |
#### |
| 1718 |
sub get_pgdata_path |
| 1719 |
{ |
| 1720 |
my $path = `echo "SELECT setting FROM pg_settings WHERE name='data_directory';" | $PSQL_PROG`; |
| 1721 |
if ($? != 0) { |
| 1722 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 1723 |
} |
| 1724 |
chomp($path); |
| 1725 |
|
| 1726 |
return $path; |
| 1727 |
} |
| 1728 |
|
| 1729 |
|
| 1730 |
#### |
| 1731 |
# Retrieve schemas for a given database. |
| 1732 |
#### |
| 1733 |
sub get_schemas |
| 1734 |
{ |
| 1735 |
my $database = shift; |
| 1736 |
|
| 1737 |
my $LOCAL_PSQL_PROG = &set_local_psql_command($database); |
| 1738 |
|
| 1739 |
my @db_schema = `echo "SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_' AND nspname <> 'information_schema'" | $LOCAL_PSQL_PROG`; |
| 1740 |
if ($? != 0) { |
| 1741 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 1742 |
} |
| 1743 |
chomp(@db_schema); |
| 1744 |
|
| 1745 |
return sort @db_schema; |
| 1746 |
} |
| 1747 |
|
| 1748 |
#### |
| 1749 |
# Retrieve JSON vs JSONB columns for a given database. |
| 1750 |
#### |
| 1751 |
sub get_json_cols |
| 1752 |
{ |
| 1753 |
my $database = shift; |
| 1754 |
|
| 1755 |
my $LOCAL_PSQL_PROG = &set_local_psql_command($database); |
| 1756 |
|
| 1757 |
my @db_json = `echo "SELECT c.relname||'.'||a.attname FROM pg_attribute a JOIN pg_class c ON (a.attrelid=c.relfilenode) WHERE a.atttypid = 114" | $LOCAL_PSQL_PROG`; |
| 1758 |
if ($? != 0) { |
| 1759 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 1760 |
} |
| 1761 |
chomp(@db_json); |
| 1762 |
|
| 1763 |
return sort @db_json; |
| 1764 |
} |
| 1765 |
|
| 1766 |
|
| 1767 |
#### |
| 1768 |
## Retrieve partitionned tables from a given database. |
| 1769 |
#### |
| 1770 |
sub get_partitionned_tables |
| 1771 |
{ |
| 1772 |
my $database = shift; |
| 1773 |
|
| 1774 |
my $LOCAL_PSQL_PROG = &set_local_psql_command($database); |
| 1775 |
|
| 1776 |
# Assume that inherited tables having check constraints are partitions |
| 1777 |
my $sql = sprintf( |
| 1778 |
"SELECT p.oid, quote_ident(pn.nspname) || '.' || quote_ident(p.relname)," |
| 1779 |
. " quote_ident(cn.nspname) || '.' || quote_ident(c.relname), %s," |
| 1780 |
. " CASE WHEN t.oid IS NOT NULL THEN 'Trigger' WHEN r.oid IS NOT NULL THEN 'Rule' ELSE 'Unknown' END," |
| 1781 |
. " count(*) OVER (PARTITION BY p.oid)" |
| 1782 |
. " FROM pg_inherits i" |
| 1783 |
. " JOIN pg_class p ON p.oid = i.inhparent" |
| 1784 |
. " JOIN pg_namespace pn ON pn.oid = p.relnamespace" |
| 1785 |
. " JOIN pg_class c ON c.oid = i.inhrelid" |
| 1786 |
. " JOIN pg_namespace cn ON cn.oid = p.relnamespace" |
| 1787 |
. " JOIN pg_constraint con ON con.conrelid= c.oid AND con.contype = 'c'" |
| 1788 |
. " LEFT JOIN pg_trigger t ON t.tgrelid = p.oid" |
| 1789 |
. " LEFT JOIN pg_rewrite r ON r.ev_class = p.oid", |
| 1790 |
&backend_minimum_version(12, 0) ? "pg_get_constraintdef(con.oid)" : "con.consrc" |
| 1791 |
); |
| 1792 |
|
| 1793 |
my @db_parttables = `echo "$ALWAYS_SECURE_SEARCH_PATH_SQL $sql" | $LOCAL_PSQL_PROG`; |
| 1794 |
if ($? != 0) { |
| 1795 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 1796 |
} |
| 1797 |
chomp(@db_parttables); |
| 1798 |
|
| 1799 |
# Return non empty lines |
| 1800 |
return grep(!/^\s*$/s, @db_parttables); |
| 1801 |
} |
| 1802 |
|
| 1803 |
### |
| 1804 |
# Retrieve trigger or rules of a specific partitionned table from a given database. |
| 1805 |
### |
| 1806 |
sub get_partitionned_implementation |
| 1807 |
{ |
| 1808 |
my $database = shift; |
| 1809 |
my $oid = shift; |
| 1810 |
|
| 1811 |
my $LOCAL_PSQL_PROG = &set_local_psql_command($database); |
| 1812 |
|
| 1813 |
my $sql = "SELECT DISTINCT CASE WHEN pro.oid IS NOT NULL THEN pro.prosrc" |
| 1814 |
. " WHEN r.oid IS NOT NULL THEN pg_get_ruledef(r.oid)" |
| 1815 |
. " ELSE 'Unknown' END" |
| 1816 |
. " FROM pg_inherits i" |
| 1817 |
. " JOIN pg_class p ON p.oid = i.inhparent" |
| 1818 |
. " JOIN pg_namespace pn ON pn.oid = p.relnamespace" |
| 1819 |
. " LEFT JOIN pg_trigger t ON t.tgrelid = p.oid" |
| 1820 |
. " LEFT JOIN pg_proc pro ON pro.oid = t.tgfoid" |
| 1821 |
. " LEFT JOIN pg_rewrite r ON r.ev_class = p.oid" |
| 1822 |
. " WHERE p.oid = $oid"; |
| 1823 |
|
| 1824 |
my @db_parttables = `echo "$sql" | $LOCAL_PSQL_PROG`; |
| 1825 |
if ($? != 0) { |
| 1826 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 1827 |
} |
| 1828 |
chomp(@db_parttables); |
| 1829 |
|
| 1830 |
# Return non empty lines |
| 1831 |
return grep(!/^\s*$/s, @db_parttables); |
| 1832 |
} |
| 1833 |
|
| 1834 |
#### |
| 1835 |
# Check if the database have the pg_buffercache extension |
| 1836 |
#### |
| 1837 |
sub has_pg_buffercache |
| 1838 |
{ |
| 1839 |
|
| 1840 |
my $hasit = `echo "SELECT proname FROM pg_proc WHERE proname = 'pg_buffercache_pages';" | $PSQL_PROG`; |
| 1841 |
if ($? != 0) { |
| 1842 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 1843 |
} |
| 1844 |
chomp($hasit); |
| 1845 |
if (!$hasit) { |
| 1846 |
&dprint("WARNING: you ask for pg_buffercache reports but pg_buffercache extention is not installed in the connection database. See -d option to set the startup connection database.\n"); |
| 1847 |
} |
| 1848 |
|
| 1849 |
return $hasit; |
| 1850 |
} |
| 1851 |
|
| 1852 |
|
| 1853 |
#### |
| 1854 |
# Check if the database have the pg_stat_statements extension |
| 1855 |
#### |
| 1856 |
sub has_pgstatstatements |
| 1857 |
{ |
| 1858 |
|
| 1859 |
my $hasit = `echo "SELECT n.nspname||'.'||p.proname FROM pg_proc p, pg_namespace n, pg_settings s WHERE p.proname='pg_stat_statements' AND p.pronamespace=n.oid AND s.name='shared_preload_libraries' AND s.setting LIKE '%pg_stat_statements%';" | $PSQL_PROG`; |
| 1860 |
if ($? != 0) { |
| 1861 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 1862 |
} |
| 1863 |
chomp($hasit); |
| 1864 |
|
| 1865 |
return $hasit; |
| 1866 |
} |
| 1867 |
|
| 1868 |
#### |
| 1869 |
# Check if the database have the pg_subxact_counters extension |
| 1870 |
#### |
| 1871 |
sub has_pgsubxactcounters |
| 1872 |
{ |
| 1873 |
|
| 1874 |
my $hasit = `echo "SELECT n.nspname||'.'||p.proname FROM pg_proc p, pg_namespace n, pg_settings s WHERE p.proname='pg_subxact_counters' AND p.pronamespace=n.oid AND s.name='shared_preload_libraries' AND s.setting LIKE '%pg_subxact_counters%';" | $PSQL_PROG`; |
| 1875 |
if ($? != 0) { |
| 1876 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 1877 |
} |
| 1878 |
chomp($hasit); |
| 1879 |
|
| 1880 |
return $hasit; |
| 1881 |
} |
| 1882 |
|
| 1883 |
|
| 1884 |
sub is_superuser |
| 1885 |
{ |
| 1886 |
my $usr = shift; |
| 1887 |
|
| 1888 |
# Assume it is superuser per default. In any case this will raise a psql error. |
| 1889 |
return 1 if (!$usr); |
| 1890 |
|
| 1891 |
$DB_INFO{is_superuser} = `echo "SELECT 1 FROM pg_user WHERE usename='$usr' AND usesuper" | $PSQL_PROG`; |
| 1892 |
chomp($DB_INFO{is_superuser}); |
| 1893 |
# If not super user look if the user has pg_monitor role |
| 1894 |
if (!$DB_INFO{is_superuser} && &backend_minimum_version(10, 0)) |
| 1895 |
{ |
| 1896 |
$DB_INFO{is_superuser} = `echo "SELECT 1 from pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles r ON (m.member = r.oid) WHERE m.member='$usr'::regrole AND m.roleid = 'pg_monitor'::regrole" | $PSQL_PROG`; |
| 1897 |
chomp($DB_INFO{is_superuser}); |
| 1898 |
} |
| 1899 |
|
| 1900 |
return $DB_INFO{is_superuser}; |
| 1901 |
|
| 1902 |
} |
| 1903 |
|
| 1904 |
sub sysstat_version |
| 1905 |
{ |
| 1906 |
my $ver = 0; |
| 1907 |
if (!$DISABLE_SAR) { |
| 1908 |
my $ver_command = "LC_ALL=C $SAR_PROG -V 2>&1"; |
| 1909 |
$ver_command = $sshcmd . ' "' . $ver_command . '"' if ($sshcmd) ; |
| 1910 |
$ver = `$ver_command | grep "sysstat version"`; |
| 1911 |
if ($?) { |
| 1912 |
&dprint("ERROR: $SAR_PROG execution failure: $!\n"); |
| 1913 |
$ver = 0; |
| 1914 |
} elsif ($ver =~ m!^sysstat version ([\.\d]+)!) { |
| 1915 |
$ver = $1; |
| 1916 |
} |
| 1917 |
} |
| 1918 |
return $ver; |
| 1919 |
} |
| 1920 |
|
| 1921 |
sub grab_os_information |
| 1922 |
{ |
| 1923 |
my $out_dir = shift(); |
| 1924 |
|
| 1925 |
# Look at CPU informations |
| 1926 |
my $cmd = 'cat /proc/cpuinfo 2>/dev/null'; |
| 1927 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1928 |
my @cpuinfo = `$cmd | grep -E "model name|cpu MHz|cache size|cpu cores|processor"`; |
| 1929 |
# Look at kernel informations |
| 1930 |
$cmd = 'uname -a 2>/dev/null'; |
| 1931 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1932 |
my $kernel_info = `$cmd`; |
| 1933 |
# Look at memory informations |
| 1934 |
$cmd = 'cat /proc/meminfo 2>/dev/null'; |
| 1935 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1936 |
my @meminfo = `$cmd`; |
| 1937 |
if ($out_dir) { |
| 1938 |
my ($commit_limit) = grep(/^CommitLimit:/, @meminfo); |
| 1939 |
my ($commit_as) = grep(/^Committed_AS:/, @meminfo); |
| 1940 |
if ($commit_limit and $commit_as ne '' and open(my $outf, '>>', "$out_dir/commit_memory.csv")) { |
| 1941 |
my $cdate = time(); |
| 1942 |
$commit_limit =~ s/[^\d]+(\d+)[^\d]+/$1/; |
| 1943 |
$commit_as =~ s/[^\d]+(\d+)[^\d]+/$1/; |
| 1944 |
print $outf "$cdate;$commit_limit;$commit_as\n"; |
| 1945 |
close($outf); |
| 1946 |
} |
| 1947 |
} |
| 1948 |
# Look at filesystem informations |
| 1949 |
$cmd = 'df -h | grep -v "/dev/loop" 2>/dev/null'; |
| 1950 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1951 |
my @dfinfo = `$cmd`; |
| 1952 |
# Mount informations |
| 1953 |
$cmd = 'mount -l | grep -v "squashfs" 2>/dev/null'; |
| 1954 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1955 |
my @mountinfo = `$cmd`; |
| 1956 |
# Fstab informations |
| 1957 |
$cmd = 'cat /etc/fstab 2>/dev/null'; |
| 1958 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1959 |
my @fstabinfo = `$cmd | grep -v "^#"`; |
| 1960 |
# PCI information |
| 1961 |
$cmd = 'lspci 2>/dev/null'; |
| 1962 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1963 |
my @pciinfo = `$cmd`; |
| 1964 |
# Release informations |
| 1965 |
$cmd = 'cat /etc/*release 2>/dev/null'; |
| 1966 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1967 |
my @releaseinfo = `$cmd`; |
| 1968 |
# Process list |
| 1969 |
$cmd = 'ps -faux 2>/dev/null'; |
| 1970 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1971 |
my @pslist = `$cmd`; |
| 1972 |
# System kernel tuning parameters |
| 1973 |
$cmd = '/sbin/sysctl -a 2>/dev/null'; |
| 1974 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1975 |
my @system = `$cmd | grep -E "vm.nr_hugepages |vm.nr_overcommit_hugepages|vm.overcommit|vm.dirty_.*(ratio|bytes|kbytes)|swappiness|zone_reclaim_mode|shmmax|shmall|sched_autogroup_enabled|sched_migration_cost|keepalive"`; |
| 1976 |
|
| 1977 |
my $fhl = IO::File->new("$OUT_DIR/sysinfo.txt.tmp", 'a'); |
| 1978 |
if (not defined $fhl) { |
| 1979 |
&dprint("FATAL: can not write into file $OUT_DIR/sysinfo.txt\n"); |
| 1980 |
unlink_pid_and_exit("FATAL: can not write into file $OUT_DIR/sysinfo.txt, $!", 1); |
| 1981 |
} |
| 1982 |
$cmd = 'cat /sys/kernel/mm/*transparent_hugepage/enabled 2>/dev/null'; |
| 1983 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1984 |
my $ret = `$cmd`; |
| 1985 |
if ($ret ne '') |
| 1986 |
{ |
| 1987 |
push(@system, "/sys/kernel/mm/transparent_hugepage/enabled: " . $ret); |
| 1988 |
$cmd = 'cat /sys/kernel/mm/*transparent_hugepage/defrag 2>/dev/null'; |
| 1989 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1990 |
$ret = `$cmd`; |
| 1991 |
push(@system, "/sys/kernel/mm/transparent_hugepage/defrag: " . $ret); |
| 1992 |
$cmd = 'cat /sys/kernel/mm/*transparent_hugepage/khugepaged/defrag 2>/dev/null'; |
| 1993 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1994 |
$ret = `$cmd`; |
| 1995 |
push(@system, "/sys/kernel/mm/transparent_hugepage/khugepaged/defrag: " . $ret); |
| 1996 |
} |
| 1997 |
$cmd = "cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null | grep -E 'performance|powersave|userspace|ondemand|conservative|schedutil'"; |
| 1998 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 1999 |
$ret = `$cmd`; |
| 2000 |
if ($ret ne '') { |
| 2001 |
push(@system, "scaling_governor: " . $ret); |
| 2002 |
} |
| 2003 |
# Since kernel 5.19, the migration cost is define in a file, /sys/kernel/debug |
| 2004 |
# must be readable by the user running pgcluu_collectd |
| 2005 |
if (!grep(/sched_migration_cost/, @system)) { |
| 2006 |
$cmd = 'cat /sys/kernel/debug/sched/migration_cost_ns 2>/dev/null'; |
| 2007 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 2008 |
$ret = `$cmd`; |
| 2009 |
chomp($ret); |
| 2010 |
push(@system, "/sys/kernel/debug/sched/migration_cost_ns: " . $ret) if ($ret ne ''); |
| 2011 |
} |
| 2012 |
|
| 2013 |
# Look at block devices informations |
| 2014 |
my @devices; |
| 2015 |
$cmd = 'ls /sys/block/ | grep -v "^loop"'; |
| 2016 |
foreach my $device ( `$cmd` ) |
| 2017 |
{ |
| 2018 |
my @row; |
| 2019 |
chomp($device); |
| 2020 |
push(@row , 'Device : ' . $device . "\n"); |
| 2021 |
# Fetch scheduler setting |
| 2022 |
$cmd = 'cat /sys/block/' . $device . '/queue/scheduler 2>/dev/null'; |
| 2023 |
my $ret = `$cmd`; |
| 2024 |
push(@row , '/queue/scheduler : ' . $ret) if ($ret); |
| 2025 |
# Fetch add_random setting |
| 2026 |
$cmd = 'cat /sys/block/' . $device . '/queue/add_random 2>/dev/null'; |
| 2027 |
$ret = `$cmd`; |
| 2028 |
push(@row , '/queue/add_random : ' . $ret) if ($ret); |
| 2029 |
# Fetch rq_affinity setting |
| 2030 |
$cmd = 'cat /sys/block/' . $device . '/queue/rq_affinity 2>/dev/null'; |
| 2031 |
$ret = `$cmd`; |
| 2032 |
push(@row , '/queue/rq_affinity : ' . $ret) if ($ret); |
| 2033 |
# Fetch rotational setting |
| 2034 |
$cmd = 'cat /sys/block/' . $device . '/queue/rotational 2>/dev/null'; |
| 2035 |
$ret = `$cmd`; |
| 2036 |
push(@row , '/queue/rotational : ' . $ret) if ($ret); |
| 2037 |
push(@devices, @row); |
| 2038 |
} |
| 2039 |
print $fhl "[DEVICES]\n"; |
| 2040 |
print $fhl @devices; |
| 2041 |
# Look at uptime informations |
| 2042 |
$cmd = 'uptime 2>/dev/null'; |
| 2043 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 2044 |
my $uptime = `$cmd`; |
| 2045 |
# Get crontab information |
| 2046 |
$cmd = "crontab -u $CRONUSER -l 2>/dev/null"; |
| 2047 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 2048 |
my @crontab = `$cmd`; |
| 2049 |
# Get package installation information |
| 2050 |
my @installation = (); |
| 2051 |
|
| 2052 |
# Autodetect package listing command to use |
| 2053 |
if (!$PKG_LIST_PROG) { |
| 2054 |
my @ret = `which rpm dpkg 2>/dev/null`; |
| 2055 |
chomp(@ret); |
| 2056 |
foreach my $c (@ret) { |
| 2057 |
$PKG_LIST_PROG = "$c -qa " if ($c =~ /\/rpm/); |
| 2058 |
$PKG_LIST_PROG = "$c -l " if ($c =~ /\/dpkg/); |
| 2059 |
} |
| 2060 |
} |
| 2061 |
$cmd = "$PKG_LIST_PROG 2>/dev/null | grep postgres"; |
| 2062 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 2063 |
@installation = `$cmd`; |
| 2064 |
|
| 2065 |
# Get all file status from PGDATA directory |
| 2066 |
my $pgdata = &get_pgdata_path(); |
| 2067 |
$cmd = "ls -la $pgdata/ 2>/dev/null"; |
| 2068 |
$cmd = $sshcmd . ' "' . $cmd . "\"" if ($sshcmd); |
| 2069 |
my @list_pgdatafiles = `$cmd`; |
| 2070 |
|
| 2071 |
print $fhl "[CPU]\n"; |
| 2072 |
print $fhl @cpuinfo; |
| 2073 |
print $fhl "[KERNEL]\n"; |
| 2074 |
print $fhl $kernel_info; |
| 2075 |
print $fhl "[UPTIME]\n"; |
| 2076 |
print $fhl $uptime; |
| 2077 |
print $fhl "[MEMORY]\n"; |
| 2078 |
print $fhl @meminfo; |
| 2079 |
print $fhl "[DF]\n"; |
| 2080 |
print $fhl @dfinfo; |
| 2081 |
print $fhl "[MOUNT]\n"; |
| 2082 |
print $fhl @mountinfo; |
| 2083 |
print $fhl "[FSTAB]\n"; |
| 2084 |
print $fhl @fstabinfo; |
| 2085 |
print $fhl "[PCI]\n"; |
| 2086 |
print $fhl @pciinfo; |
| 2087 |
print $fhl "[RELEASE]\n"; |
| 2088 |
print $fhl @releaseinfo; |
| 2089 |
print $fhl "[SYSTEM]\n"; |
| 2090 |
print $fhl @system; |
| 2091 |
print $fhl "[PROCESS]\n"; |
| 2092 |
print $fhl @pslist; |
| 2093 |
print $fhl "[CRONTAB]\n"; |
| 2094 |
print $fhl @crontab; |
| 2095 |
print $fhl "[INSTALLATION]\n"; |
| 2096 |
print $fhl @installation; |
| 2097 |
print $fhl "[PGDATA]\n"; |
| 2098 |
print $fhl @list_pgdatafiles; |
| 2099 |
|
| 2100 |
close($fhl); |
| 2101 |
} |
| 2102 |
|
| 2103 |
sub usage |
| 2104 |
{ |
| 2105 |
print qq{ |
| 2106 |
usage: $PROGRAM [options] output_dir |
| 2107 |
|
| 2108 |
output_dir: full path to directory where pgcluu_collectd will |
| 2109 |
store statistics. |
| 2110 |
|
| 2111 |
options: |
| 2112 |
|
| 2113 |
-B, --enable-buffercache enable buffercache statistics if pg_buffercache |
| 2114 |
extension is installed. |
| 2115 |
-c, --capture create a snapshot of the PostgreSQL installation |
| 2116 |
into tmp/pgcluu_capture.tar.gz. |
| 2117 |
-C, --end-counter=NUM terminate program after NUM reports. |
| 2118 |
-d, --dbname=DATABASE database name to connect to. Default to current user. |
| 2119 |
-D, --daemonize detach from console and enter in daemon mode. |
| 2120 |
-E, --end-after=NUM self terminate the program after a given number of |
| 2121 |
seconds. Can be written: 7200 or 120M or 2H, for |
| 2122 |
days use 7D for example to stop collecting data |
| 2123 |
after seven days. |
| 2124 |
-f, --pid-file=FILE path to pid file. Default: $PIDFILE. |
| 2125 |
-h, --host=HOSTNAME database server host or socket directory |
| 2126 |
-i, --interval=NUM time to wait between runs |
| 2127 |
-k, --kill stop current $PROGRAM running daemon. |
| 2128 |
-m, --metric=METRIC set a coma separated list of metrics to perform. |
| 2129 |
-M, --max-size=SIZE self terminate program when the size of the output |
| 2130 |
directory exceed a given size. Can be written: 2GB |
| 2131 |
or 2000MB. |
| 2132 |
-n, --no-pg_stats-dump don't collect statistics from the pg_stats view. |
| 2133 |
-p, --port=PORT database port(s) to connect to. Defaults to 5432. |
| 2134 |
-P, --psql=BIN path to the psql command. Default: $PSQL_PROG. |
| 2135 |
-Q, --no-statement do not collect statistics from pg_stat_statements. |
| 2136 |
-r, --rotate-daily force daily rotation of data files. |
| 2137 |
-R, --rotate-hourly force hourly rotation of data files. |
| 2138 |
-s, --sar=BIN path to sar sysstat command. Default: $SAR_PROG. |
| 2139 |
-S, --disable-sar disable collect of system statistics with sar. |
| 2140 |
-t, --lock-timeout=NUM terminate metric SQL query after N second in case it |
| 2141 |
wait too much time because of a lock. Default: 3 |
| 2142 |
-T, --no-tablespace disable lookup at tablespace when the connect user |
| 2143 |
is not superuser to avoid printing an error message. |
| 2144 |
-U, --dbuser=USERNAME database user to connect as. Default to current user. |
| 2145 |
-v, --verbose Print out debug informations. |
| 2146 |
-V, --version Show pgcluu_collectd version and exit. |
| 2147 |
-w, --no-waitevent don't collect wait event stats from pg_wait_sampling. |
| 2148 |
-W, --password=pass database password. |
| 2149 |
-z, --compress force compression of rotated data files. |
| 2150 |
--included-db=DATABASE collect statistics only for those databases present |
| 2151 |
in a comma separated list of database names. |
| 2152 |
--list-metric list available metrics actions that can be performed. |
| 2153 |
--sysinfo get operating system infos and exit (sysinfo.txt). |
| 2154 |
--no-sysinfo do not collect operating system information at all. |
| 2155 |
--no-database do not collect database statistics at all. |
| 2156 |
--pgbouncer-args=OPTIONS Option to used to connect to the pgbouncer system |
| 2157 |
database. Ex: -p 6432 -U postgres -h 192.168.1.100 |
| 2158 |
You must at least give one parameter to enable |
| 2159 |
pgbouncer monitoring. |
| 2160 |
--sar-file=FILE path to sar output data file for sysstat stats |
| 2161 |
Default to output_dir/sar_stats.dat. |
| 2162 |
--stat-type all|user Set stats tables to read. Values: 'all' or 'user' to |
| 2163 |
look at pg_stat_(all|user) tables. Default: user. |
| 2164 |
--pgversion X.Y force the PostgreSQL version to the given value. |
| 2165 |
--pgservice NAME Name of service inside of the pg_service.conf file. |
| 2166 |
--exclude-time RANGE exclude a laps of time by giving the start and end |
| 2167 |
hours. |
| 2168 |
--cron-user=USERNAME collect crontab settings for the given username (in |
| 2169 |
this case pgcluu_collectd need to be run as root). |
| 2170 |
Default is to use USERNAME environment variable or |
| 2171 |
postgres when it is not defined. |
| 2172 |
--package-list=CMD command to list PostgreSQL packages. Default is to |
| 2173 |
autodetect package type and using command 'rpm -qa' |
| 2174 |
or 'dpkg -l'. If you have an other system you can |
| 2175 |
set a custom command. A filter on keyword 'postgres' |
| 2176 |
is appended to the command: ' | grep postgres'. |
| 2177 |
--retention NDAYS number of rolling days to keep in data directory in |
| 2178 |
incremental mode. Default is to store indefinitely. |
| 2179 |
--disable-pidstat do not collect metrics from pidstat command. |
| 2180 |
--help print usage |
| 2181 |
|
| 2182 |
Use those options to execute sar on the remote host defined by the -h option, |
| 2183 |
otherwise it will be executed locally: |
| 2184 |
|
| 2185 |
--enable-ssh activate the use of ssh to run sysstat remotely. |
| 2186 |
--ssh-program ssh path to the ssh program to use. Default: ssh. |
| 2187 |
--ssh-user username connection login name. Default to running user. |
| 2188 |
--ssh-identity file path to the identity file to use. |
| 2189 |
--ssh-timeout second timeout to ssh connection failure. Default 10. |
| 2190 |
--ssh-options options list of -o options to use for the ssh connection. |
| 2191 |
Options always used: |
| 2192 |
-o ConnectTimeout=\$ssh_timeout |
| 2193 |
-o PreferredAuthentications=hostbased,publickey |
| 2194 |
|
| 2195 |
For example, as postgres user to monitor locally a full PostgreSQL cluster: |
| 2196 |
|
| 2197 |
mkdir /tmp/stat_db1/ |
| 2198 |
pgcluu_collectd -D -i 60 /tmp/stat_db1/ |
| 2199 |
|
| 2200 |
to collect statistics from pgbouncer too, and limit database statistics to a |
| 2201 |
single database: |
| 2202 |
|
| 2203 |
pgcluu_collectd -D -i 60 /tmp/stat_db1/ -h 10.10.1.1 -U postgres -d mydb \ |
| 2204 |
--pgbouncer-args='-p 5342' |
| 2205 |
|
| 2206 |
to disable statistics collect between 22:30 and 06:30 the next day: |
| 2207 |
|
| 2208 |
pgcluu_collectd -D -i 60 /tmp/stat_db1/ --exclude-time "22:30-06:30" |
| 2209 |
|
| 2210 |
to collect statistics from a remote server: |
| 2211 |
|
| 2212 |
pgcluu_collectd -D -i 60 /tmp/statdb1/ -h 10.0.0.1 -U postgres --disable-sar |
| 2213 |
|
| 2214 |
the same but with collecting system statistics using remote sar calls: |
| 2215 |
|
| 2216 |
pgcluu_collectd -D -i 60 /tmp/statdb1/ -h 10.0.0.1 -U postgres --enable-ssh \ |
| 2217 |
--ssh-user postgres --ssh-identity /var/lib/postgresql/.ssh/id_rsa.pub |
| 2218 |
|
| 2219 |
You may need a .pgpass and be able to establish passwordless ssh connections to |
| 2220 |
be able to collect statistics from remote hosts. |
| 2221 |
|
| 2222 |
Then after some time and activities on the database, stop the daemon as follow: |
| 2223 |
|
| 2224 |
pgcluu_collectd -k |
| 2225 |
|
| 2226 |
or by sending sigterm to the pgcluu_collectd's pid. |
| 2227 |
|
| 2228 |
You can run the collector in incremental mode using a daily or a hourly |
| 2229 |
statistics rotation: |
| 2230 |
|
| 2231 |
pgcluu_collectd -D -i 60 /tmp/stat_db1/ --rotate-daily |
| 2232 |
|
| 2233 |
On a server with huge activity you may want to use --rotate-hourly and |
| 2234 |
compression mode with --compress option. If you have limited disk space you |
| 2235 |
can restrict the retention time of statistics files using option --retention |
| 2236 |
with the storage day limit. |
| 2237 |
|
| 2238 |
}; |
| 2239 |
exit 1; |
| 2240 |
} |
| 2241 |
|
| 2242 |
sub dprint |
| 2243 |
{ |
| 2244 |
foreach (@_) { |
| 2245 |
next if (/^DEBUG:/s && !$DEBUG); |
| 2246 |
print "$_" |
| 2247 |
} |
| 2248 |
} |
| 2249 |
|
| 2250 |
# Compare given major and minor numbers to the one of the connected server |
| 2251 |
sub backend_minimum_version |
| 2252 |
{ |
| 2253 |
my ($major, $minor) = @_; |
| 2254 |
|
| 2255 |
return if ($major eq ''); |
| 2256 |
return if ($minor eq ''); |
| 2257 |
|
| 2258 |
return ($DB_INFO{major} > $major) || (($DB_INFO{major} == $major) && ($DB_INFO{minor} >= $minor)); |
| 2259 |
} |
| 2260 |
|
| 2261 |
sub dump_pgstatactivity |
| 2262 |
{ |
| 2263 |
|
| 2264 |
my $sql = sprintf( |
| 2265 |
"SELECT date_trunc('seconds', now()), datid, datname, %s, " . |
| 2266 |
"usesysid, usename, %s%s%s%s%s" . |
| 2267 |
"date_trunc('seconds', query_start) AS query_start, " . |
| 2268 |
"%s%s%s " . |
| 2269 |
"FROM pg_stat_activity %s", |
| 2270 |
&backend_minimum_version(9, 2) ? "pid" : "procpid", |
| 2271 |
&backend_minimum_version(9, 0) ? "application_name, " : "", |
| 2272 |
&backend_minimum_version(8, 1) ? "client_addr, " : "", |
| 2273 |
&backend_minimum_version(9, 1) ? "client_hostname, " : "", |
| 2274 |
&backend_minimum_version(8, 1) ? "client_port, date_trunc('seconds', backend_start) AS backend_start, " : "", |
| 2275 |
&backend_minimum_version(8, 3) ? "date_trunc('seconds', xact_start) AS xact_start, " : "", |
| 2276 |
&backend_minimum_version(9, 2) ? "state_change, " : "", |
| 2277 |
&backend_minimum_version(8, 2) ? "waiting, " : "", |
| 2278 |
&backend_minimum_version(9, 2) ? "query" : "current_query", |
| 2279 |
&backend_minimum_version(9, 0) ? "WHERE application_name != 'pgcluu' " : "", |
| 2280 |
&backend_minimum_version(9, 2) ? "pid" : "procpid" |
| 2281 |
); |
| 2282 |
|
| 2283 |
return $sql; |
| 2284 |
} |
| 2285 |
|
| 2286 |
sub dump_pgstatbgwriter |
| 2287 |
{ |
| 2288 |
|
| 2289 |
my $sql = sprintf( |
| 2290 |
"SELECT date_trunc('seconds', now()), checkpoints_timed, " . |
| 2291 |
"checkpoints_req, %sbuffers_checkpoint, buffers_clean, " . |
| 2292 |
"maxwritten_clean, buffers_backend, %sbuffers_alloc%s " . |
| 2293 |
"FROM pg_stat_bgwriter ", |
| 2294 |
&backend_minimum_version(9, 2) ? "checkpoint_write_time, checkpoint_sync_time, " : "", |
| 2295 |
&backend_minimum_version(9, 1) ? "buffers_backend_fsync, " : "", |
| 2296 |
&backend_minimum_version(9, 1) ? ", date_trunc('seconds', stats_reset) AS stats_reset " : "" |
| 2297 |
); |
| 2298 |
|
| 2299 |
return $sql; |
| 2300 |
} |
| 2301 |
|
| 2302 |
sub dump_pgstatdatabase |
| 2303 |
{ |
| 2304 |
|
| 2305 |
my $sql = sprintf( |
| 2306 |
"SELECT date_trunc('seconds', now()), datid, datname, " . |
| 2307 |
"numbackends, xact_commit, xact_rollback, blks_read, blks_hit" . |
| 2308 |
"%s%s%s%s " . |
| 2309 |
"FROM pg_stat_database ", |
| 2310 |
&backend_minimum_version(8, 3) ? ", tup_returned, tup_fetched, tup_inserted, tup_updated, tup_deleted" : "", |
| 2311 |
&backend_minimum_version(9, 1) ? ", conflicts, date_trunc('seconds', stats_reset) AS stats_reset" : "", |
| 2312 |
&backend_minimum_version(9, 2) ? ", temp_files, temp_bytes, deadlocks" : "", |
| 2313 |
&backend_minimum_version(17, 0) ? ", shared_blk_read_time, shared_blk_write_time" : ", blk_read_time, blk_write_time" |
| 2314 |
); |
| 2315 |
|
| 2316 |
return $sql; |
| 2317 |
} |
| 2318 |
|
| 2319 |
sub dump_pgtablespace_size |
| 2320 |
{ |
| 2321 |
|
| 2322 |
my $sql = sprintf( |
| 2323 |
"SELECT date_trunc('seconds', now()), spcname, " . |
| 2324 |
"pg_tablespace_size(spcname), " . |
| 2325 |
"CASE WHEN %s = '' THEN CASE WHEN spcname = 'pg_default' THEN (select setting from pg_settings where name='data_directory')||'/base' ELSE (select setting from pg_settings where name='data_directory')||'/global' END ELSE %s END as tablespace_location " . |
| 2326 |
"FROM pg_tablespace ", |
| 2327 |
&backend_minimum_version(9, 2) ? "pg_tablespace_location(oid)" : "spclocation", |
| 2328 |
&backend_minimum_version(9, 2) ? "pg_tablespace_location(oid)" : "spclocation" |
| 2329 |
); |
| 2330 |
|
| 2331 |
return $sql; |
| 2332 |
} |
| 2333 |
|
| 2334 |
sub dump_pgstatdatabaseconflicts |
| 2335 |
{ |
| 2336 |
|
| 2337 |
my $sql = sprintf( |
| 2338 |
"SELECT date_trunc('seconds', now()), * " . |
| 2339 |
"FROM pg_stat_database_conflicts " |
| 2340 |
); |
| 2341 |
|
| 2342 |
return $sql; |
| 2343 |
} |
| 2344 |
|
| 2345 |
sub dump_pgstatreplication |
| 2346 |
{ |
| 2347 |
|
| 2348 |
my $sql = sprintf( |
| 2349 |
"SELECT date_trunc('seconds', now()), %s, usesysid, usename, " . |
| 2350 |
"application_name, client_addr, client_hostname, client_port, " . |
| 2351 |
"date_trunc('seconds', backend_start) AS backend_start, state, " . |
| 2352 |
"(CASE WHEN pg_is_in_recovery() THEN NULL ELSE %s END) AS master_location, " . |
| 2353 |
"%s, %s, %s, %s, " . |
| 2354 |
"sync_priority, " . |
| 2355 |
"sync_state " . |
| 2356 |
"FROM pg_stat_replication ", |
| 2357 |
&backend_minimum_version(9, 2) ? "pid" : "procpid", |
| 2358 |
&backend_minimum_version(10, 0) ? "pg_current_wal_lsn()" : "pg_current_xlog_location()", |
| 2359 |
&backend_minimum_version(10, 0) ? "sent_lsn" : "sent_location", |
| 2360 |
&backend_minimum_version(10, 0) ? "write_lsn" : "write_location", |
| 2361 |
&backend_minimum_version(10, 0) ? "flush_lsn" : "flush_location", |
| 2362 |
&backend_minimum_version(10, 0) ? "replay_lsn" : "replay_location" |
| 2363 |
); |
| 2364 |
|
| 2365 |
return $sql; |
| 2366 |
} |
| 2367 |
|
| 2368 |
sub dump_pgstattables_user { return dump_pgstattables('user'); }; |
| 2369 |
|
| 2370 |
sub dump_pgstattables |
| 2371 |
{ |
| 2372 |
my $type = shift; |
| 2373 |
|
| 2374 |
$type ||= 'all'; |
| 2375 |
|
| 2376 |
my $sql = sprintf( |
| 2377 |
"SELECT date_trunc('seconds', now()), current_database(), relid, schemaname, relname, " . |
| 2378 |
"seq_scan, seq_tup_read, idx_scan, idx_tup_fetch, n_tup_ins, " . |
| 2379 |
"n_tup_upd, n_tup_del" . |
| 2380 |
"%s" . |
| 2381 |
"%s" . |
| 2382 |
"%s" . |
| 2383 |
" FROM pg_stat_${type}_tables " . |
| 2384 |
"WHERE schemaname <> 'information_schema' ", |
| 2385 |
&backend_minimum_version(8, 3) ? ", n_tup_hot_upd, n_live_tup, n_dead_tup" : "", |
| 2386 |
&backend_minimum_version(8, 2) ? ", date_trunc('seconds', last_vacuum) AS last_vacuum, date_trunc('seconds', last_autovacuum) AS last_autovacuum, date_trunc('seconds',last_analyze) AS last_analyze, date_trunc('seconds',last_autoanalyze) AS last_autoanalyze" : "", |
| 2387 |
&backend_minimum_version(9, 1) ? ", vacuum_count, autovacuum_count, analyze_count, autoanalyze_count" : "" |
| 2388 |
); |
| 2389 |
|
| 2390 |
return $sql; |
| 2391 |
} |
| 2392 |
|
| 2393 |
sub dump_pg_stats_view |
| 2394 |
{ |
| 2395 |
my $sql = sprintf( |
| 2396 |
"SELECT date_trunc('seconds', now()), current_database(), schemaname, tablename, attname, " . |
| 2397 |
"%s" . |
| 2398 |
"null_frac, avg_width, n_distinct, " . |
| 2399 |
"most_common_vals, most_common_freqs, " . |
| 2400 |
"histogram_bounds, correlation" . |
| 2401 |
" FROM pg_stats " . |
| 2402 |
"WHERE schemaname NOT IN ('pg_catalog', 'information_schema')", |
| 2403 |
&backend_minimum_version(9, 0) ? "inherited, " : "", |
| 2404 |
); |
| 2405 |
|
| 2406 |
return $sql; |
| 2407 |
} |
| 2408 |
|
| 2409 |
sub dump_pgstatindexes_user { return dump_pgstatindexes('user'); }; |
| 2410 |
|
| 2411 |
sub dump_pgstatindexes |
| 2412 |
{ |
| 2413 |
my $type = shift; |
| 2414 |
|
| 2415 |
$type ||= 'all'; |
| 2416 |
|
| 2417 |
my $sql = sprintf( |
| 2418 |
"SELECT date_trunc('seconds', now()), current_database(), * " . |
| 2419 |
"FROM pg_stat_${type}_indexes " . |
| 2420 |
"WHERE schemaname <> 'information_schema' ", |
| 2421 |
); |
| 2422 |
|
| 2423 |
return $sql; |
| 2424 |
} |
| 2425 |
|
| 2426 |
sub dump_pgstatiotables_user { return dump_pgstatiotables('user'); }; |
| 2427 |
|
| 2428 |
sub dump_pgstatiotables |
| 2429 |
{ |
| 2430 |
my $type = shift; |
| 2431 |
|
| 2432 |
$type ||= 'all'; |
| 2433 |
|
| 2434 |
my $sql = sprintf( |
| 2435 |
"SELECT date_trunc('seconds', now()), current_database(), * " . |
| 2436 |
"FROM pg_statio_${type}_tables " . |
| 2437 |
"WHERE schemaname <> 'information_schema' " |
| 2438 |
); |
| 2439 |
|
| 2440 |
return $sql; |
| 2441 |
} |
| 2442 |
|
| 2443 |
sub dump_pgstatioindexes_user { return dump_pgstatioindexes('user'); }; |
| 2444 |
|
| 2445 |
sub dump_pgstatioindexes |
| 2446 |
{ |
| 2447 |
my $type = shift; |
| 2448 |
|
| 2449 |
$type ||= 'all'; |
| 2450 |
|
| 2451 |
my $sql = sprintf( |
| 2452 |
"SELECT date_trunc('seconds', now()), current_database(), * " . |
| 2453 |
"FROM pg_statio_${type}_indexes " . |
| 2454 |
"WHERE schemaname <> 'information_schema' " |
| 2455 |
); |
| 2456 |
|
| 2457 |
return $sql; |
| 2458 |
} |
| 2459 |
|
| 2460 |
sub dump_pgstatiosequences_user { return dump_pgstatiosequences('user'); }; |
| 2461 |
|
| 2462 |
sub dump_pgstatiosequences |
| 2463 |
{ |
| 2464 |
my $type = shift; |
| 2465 |
|
| 2466 |
$type ||= 'all'; |
| 2467 |
|
| 2468 |
my $sql = sprintf( |
| 2469 |
"SELECT date_trunc('seconds', now()), current_database(), * " . |
| 2470 |
"FROM pg_statio_${type}_sequences " . |
| 2471 |
"WHERE schemaname <> 'information_schema' " |
| 2472 |
); |
| 2473 |
|
| 2474 |
return $sql; |
| 2475 |
} |
| 2476 |
|
| 2477 |
sub dump_pgstatuserfunctions |
| 2478 |
{ |
| 2479 |
|
| 2480 |
my $sql = sprintf( |
| 2481 |
"SELECT date_trunc('seconds', now()), current_database(), * " . |
| 2482 |
"FROM pg_stat_user_functions " . |
| 2483 |
"WHERE schemaname <> 'information_schema' " |
| 2484 |
); |
| 2485 |
|
| 2486 |
return $sql; |
| 2487 |
} |
| 2488 |
|
| 2489 |
sub dump_pgclass_size |
| 2490 |
{ |
| 2491 |
|
| 2492 |
my $sql = sprintf( |
| 2493 |
"SELECT date_trunc('seconds', now()), current_database(), n.nspname, c.relname, c.relkind, c.reltuples, c.relpages%s " . |
| 2494 |
"FROM pg_class c, pg_namespace n " . |
| 2495 |
"WHERE n.oid=c.relnamespace AND n.nspname <> 'information_schema' AND n.nspname <> 'pg_catalog' ", |
| 2496 |
($CAPTURE && &backend_minimum_version(8, 1)) ? ", pg_relation_size(c.oid)" : "" |
| 2497 |
); |
| 2498 |
|
| 2499 |
return $sql; |
| 2500 |
} |
| 2501 |
|
| 2502 |
sub dump_pgstatstatements |
| 2503 |
{ |
| 2504 |
|
| 2505 |
my $sql = sprintf( |
| 2506 |
"SELECT date_trunc('seconds', now()), r.rolname, d.datname, " . |
| 2507 |
"regexp_replace(regexp_replace(query, E'[ \\n]+', ' ', 'g'), E';', '#SMCLN#', 'g'), calls, %s, rows, " . |
| 2508 |
"shared_blks_hit, shared_blks_read, shared_blks_written, " . |
| 2509 |
"local_blks_hit, local_blks_read, local_blks_written, " . |
| 2510 |
"temp_blks_read, temp_blks_written " . |
| 2511 |
"FROM $DB_INFO{pg_stat_statement} q, pg_database d, pg_roles r " . |
| 2512 |
"WHERE q.userid=r.oid and q.dbid=d.oid ", |
| 2513 |
&backend_minimum_version(13, 0) ? "(total_plan_time + total_exec_time) as total_time " : "total_time" |
| 2514 |
); |
| 2515 |
|
| 2516 |
return $sql; |
| 2517 |
} |
| 2518 |
|
| 2519 |
sub dump_pgwaitsampling |
| 2520 |
{ |
| 2521 |
|
| 2522 |
my $sql = "SELECT date_trunc('seconds', now()), current_database(), " . |
| 2523 |
"event_type, event, SUM(count) " . |
| 2524 |
"FROM public.pg_wait_sampling_profile " . |
| 2525 |
"WHERE event IS NOT NULL " . |
| 2526 |
"GROUP BY event_type, event"; |
| 2527 |
|
| 2528 |
return $sql; |
| 2529 |
} |
| 2530 |
|
| 2531 |
sub dump_pgsubxactcounters |
| 2532 |
{ |
| 2533 |
|
| 2534 |
my $sql = "SELECT date_trunc('seconds', now()), current_database(), " . |
| 2535 |
"subxact_start, subxact_commit, subxact_abort, subxact_overflow " . |
| 2536 |
"FROM public.pg_subxact_counters "; |
| 2537 |
|
| 2538 |
return $sql; |
| 2539 |
} |
| 2540 |
|
| 2541 |
sub dump_xlog_stat |
| 2542 |
{ |
| 2543 |
|
| 2544 |
my $sql = ''; |
| 2545 |
|
| 2546 |
if (&backend_minimum_version(8, 4)) { |
| 2547 |
$sql = sprintf( |
| 2548 |
"SELECT date_trunc('seconds', now()), count(*) AS num_file, " . |
| 2549 |
"(CASE WHEN pg_is_in_recovery() THEN '-'::text ELSE %s END) AS current, " . |
| 2550 |
"sum(is_recycled::int) AS is_recycled, " . |
| 2551 |
"sum((NOT is_recycled)::int) AS written, " . |
| 2552 |
"%s " . |
| 2553 |
"FROM ( " . |
| 2554 |
"SELECT file > first_value(file) OVER w AS is_recycled " . |
| 2555 |
"%s " . |
| 2556 |
"FROM %s as file " . |
| 2557 |
"WHERE %s ~ '^[0-9A-F]{24}\$' " . |
| 2558 |
"WINDOW w AS ( " . |
| 2559 |
"ORDER BY %s.modification " . |
| 2560 |
"DESC " . |
| 2561 |
") " . |
| 2562 |
") AS t " . |
| 2563 |
"GROUP BY 6 ", |
| 2564 |
&backend_minimum_version(10, 0) ? "pg_walfile_name(pg_current_wal_lsn())" : "pg_xlogfile_name(pg_current_xlog_location())", |
| 2565 |
&backend_minimum_version(9, 5) ? "max_wal" : &backend_minimum_version(9, 0) ? "CASE WHEN max_wal1 > max_wal2 THEN max_wal1 ELSE max_wal2 END AS max_wal" : "1 + ( current_setting('checkpoint_segments')::float4 * ( 2 + current_setting('checkpoint_completion_target')::float4 )) AS max_wal", |
| 2566 |
&backend_minimum_version(9, 5) ? ",(select setting from pg_settings where name = 'max_wal_size')::float4 AS max_wal" : &backend_minimum_version(9, 0) ? ",1 + ( current_setting('checkpoint_segments')::float4 * ( 2 + current_setting('checkpoint_completion_target')::float4 )) AS max_wal1, 1 + current_setting('wal_keep_segments')::float4 + current_setting('checkpoint_segments')::float4 AS max_wal2" : "", |
| 2567 |
&backend_minimum_version(10, 0) ? "pg_ls_waldir()" : "pg_ls_dir('pg_xlog')", |
| 2568 |
&backend_minimum_version(10, 0) ? "file.name" : "file", |
| 2569 |
&backend_minimum_version(10, 0) ? "file" : "(pg_stat_file('pg_xlog/'||file))" |
| 2570 |
); |
| 2571 |
} else { |
| 2572 |
$sql = sprintf( |
| 2573 |
"SELECT date_trunc('seconds', now()), count(*) AS num_file, " . |
| 2574 |
"(CASE WHEN pg_is_in_recovery() THEN '-'::text ELSE %s END) AS current, " . |
| 2575 |
"sum(recycled::int) AS is_recycled, " . |
| 2576 |
"sum((NOT recycled)::int) AS written, " . |
| 2577 |
"%s " . |
| 2578 |
"FROM ( " . |
| 2579 |
"SELECT file, file > ( " . |
| 2580 |
"SELECT s.f " . |
| 2581 |
"FROM %s AS s(f) " . |
| 2582 |
"ORDER BY %s.modification DESC " . |
| 2583 |
"LIMIT 1 " . |
| 2584 |
") AS recycled " . |
| 2585 |
"FROM %s AS file " . |
| 2586 |
"WHERE %s ~ '^[0-9A-F]{24}\$' " . |
| 2587 |
") AS t ", |
| 2588 |
&backend_minimum_version(10, 0) ? "pg_walfile_name(pg_current_wal_lsn())" : &backend_minimum_version(8, 2) ? "pg_xlogfile_name(pg_current_xlog_location())" : "'-'::text", |
| 2589 |
&backend_minimum_version(8, 3) ? "1 + ( current_setting('checkpoint_segments')::float4 * ( 2 + current_setting('checkpoint_completion_target')::float4 ))" : "1 + (current_setting('checkpoint_segments')::integer * 2)", |
| 2590 |
&backend_minimum_version(10, 0) ? "pg_ls_waldir()" : "pg_ls_dir('pg_xlog')", |
| 2591 |
&backend_minimum_version(10, 0) ? "file" : "(pg_stat_file('pg_xlog/'||file))" , |
| 2592 |
&backend_minimum_version(10, 0) ? "pg_ls_waldir()" : "pg_ls_dir('pg_xlog')", |
| 2593 |
&backend_minimum_version(10, 0) ? "file.name" : "file" |
| 2594 |
); |
| 2595 |
} |
| 2596 |
|
| 2597 |
return $sql; |
| 2598 |
} |
| 2599 |
|
| 2600 |
sub dump_pgdatabase_size |
| 2601 |
{ |
| 2602 |
|
| 2603 |
my $sql = sprintf( |
| 2604 |
"SELECT date_trunc('seconds', now()), datid, datname, pg_database_size(datid) AS size " . |
| 2605 |
"FROM pg_stat_database WHERE datid > 0" |
| 2606 |
); |
| 2607 |
|
| 2608 |
return $sql; |
| 2609 |
} |
| 2610 |
|
| 2611 |
sub dump_pgstatconnections |
| 2612 |
{ |
| 2613 |
|
| 2614 |
my $waiting = ''; |
| 2615 |
if (&backend_minimum_version(9, 6)) { |
| 2616 |
#$waiting = "coalesce(SUM((wait_event_type IS NOT NULL)::integer), 0)"; |
| 2617 |
$waiting = "coalesce(SUM((wait_event_type='Lock' AND wait_event='tuple')::integer), 0)"; |
| 2618 |
} else { |
| 2619 |
&backend_minimum_version(8, 2) ? $waiting = "coalesce(SUM(waiting::integer), 0)" : $waiting = "0::integer"; |
| 2620 |
} |
| 2621 |
my $sql = sprintf( |
| 2622 |
"SELECT date_trunc('seconds', now()), COUNT(*) AS total, coalesce(SUM((%s)::integer), 0) AS active, " . |
| 2623 |
"%s AS waiting, " . |
| 2624 |
"coalesce(SUM((%s)::integer), 0) AS idle_in_xact, pg_database.datname AS datname " . |
| 2625 |
"FROM pg_stat_activity JOIN pg_database ON (pg_database.oid=pg_stat_activity.datid) " . |
| 2626 |
"WHERE %s <> pg_backend_pid() GROUP BY pg_database.datname" , |
| 2627 |
&backend_minimum_version(9, 2) ? "state NOT LIKE 'idle%'" : "current_query NOT IN ('<IDLE>','<IDLE> in transaction')", |
| 2628 |
$waiting, |
| 2629 |
&backend_minimum_version(9, 2) ? "state = 'idle in transaction'" : "current_query = '<IDLE> in transaction'", |
| 2630 |
&backend_minimum_version(9, 2) ? "pid" : "procpid" , |
| 2631 |
); |
| 2632 |
|
| 2633 |
return $sql; |
| 2634 |
} |
| 2635 |
|
| 2636 |
sub dump_pgstatlocktypes |
| 2637 |
{ |
| 2638 |
|
| 2639 |
my $sql = sprintf( |
| 2640 |
"SELECT date_trunc('seconds', now()), current_database(), 'lock_type'::text as label, " . |
| 2641 |
"locktype, count(locktype) as count " . |
| 2642 |
"FROM pg_locks GROUP BY locktype" |
| 2643 |
); |
| 2644 |
|
| 2645 |
return $sql; |
| 2646 |
} |
| 2647 |
|
| 2648 |
sub dump_pgstatlockmodes |
| 2649 |
{ |
| 2650 |
|
| 2651 |
my $sql = sprintf( |
| 2652 |
"SELECT date_trunc('seconds', now()), current_database(), 'lock_mode'::text as label, " . |
| 2653 |
"mode, count(mode) as count " . |
| 2654 |
"FROM pg_locks GROUP BY mode" |
| 2655 |
); |
| 2656 |
|
| 2657 |
return $sql; |
| 2658 |
} |
| 2659 |
|
| 2660 |
sub dump_pgstatlockgranted |
| 2661 |
{ |
| 2662 |
|
| 2663 |
my $sql = sprintf( |
| 2664 |
"SELECT date_trunc('seconds', now()), current_database(), 'lock_granted'::text as label, " . |
| 2665 |
"granted, count(granted) as count " . |
| 2666 |
"FROM pg_locks GROUP BY granted" |
| 2667 |
); |
| 2668 |
|
| 2669 |
return $sql; |
| 2670 |
} |
| 2671 |
|
| 2672 |
sub dump_pgbouncerpoolstats |
| 2673 |
{ |
| 2674 |
|
| 2675 |
my $sql = sprintf( |
| 2676 |
"SHOW POOLS" |
| 2677 |
); |
| 2678 |
|
| 2679 |
return $sql; |
| 2680 |
} |
| 2681 |
|
| 2682 |
sub dump_pgbouncerquerystats |
| 2683 |
{ |
| 2684 |
|
| 2685 |
my $sql = sprintf( |
| 2686 |
"SHOW STATS" |
| 2687 |
); |
| 2688 |
|
| 2689 |
return $sql; |
| 2690 |
} |
| 2691 |
|
| 2692 |
|
| 2693 |
|
| 2694 |
sub get_current_timestamp |
| 2695 |
{ |
| 2696 |
|
| 2697 |
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); |
| 2698 |
|
| 2699 |
$year += 1900; |
| 2700 |
$mon++; |
| 2701 |
|
| 2702 |
return $year . '-' . sprintf("%02d", $mon) . '-' . sprintf("%02d", $mday) . ' ' . |
| 2703 |
sprintf("%02d", $hour) . ':' . sprintf("%02d", $min) . ':' . sprintf("%02d", $sec); |
| 2704 |
} |
| 2705 |
|
| 2706 |
sub dump_pgstatxactuserfunctions |
| 2707 |
{ |
| 2708 |
|
| 2709 |
my $sql = sprintf( |
| 2710 |
"SELECT date_trunc('seconds', now()), * " . |
| 2711 |
"FROM pg_stat_xact_user_functions " . |
| 2712 |
"WHERE schemaname <> 'information_schema' " |
| 2713 |
); |
| 2714 |
|
| 2715 |
return $sql; |
| 2716 |
} |
| 2717 |
|
| 2718 |
sub dump_pgstatxacttables_user { return dump_pgstatxacttables('user'); }; |
| 2719 |
|
| 2720 |
sub dump_pgstatxacttables |
| 2721 |
{ |
| 2722 |
my $type = shift; |
| 2723 |
|
| 2724 |
$type ||= 'all'; |
| 2725 |
|
| 2726 |
my $sql = sprintf( |
| 2727 |
"SELECT date_trunc('seconds', now()), * " . |
| 2728 |
"FROM pg_stat_xact_${type}_tables " . |
| 2729 |
"WHERE schemaname <> 'information_schema' " |
| 2730 |
); |
| 2731 |
|
| 2732 |
return $sql; |
| 2733 |
} |
| 2734 |
|
| 2735 |
sub get_proc_name |
| 2736 |
{ |
| 2737 |
my $database = shift; |
| 2738 |
|
| 2739 |
my $LOCAL_PSQL_PROG = &set_local_psql_command($database); |
| 2740 |
|
| 2741 |
my @db_proc = `echo "SELECT n.nspname||'.'||p.proname FROM pg_proc p, pg_namespace n WHERE p.pronamespace=n.oid AND n.nspname NOT IN ('pg_catalog', 'information_schema');" | $LOCAL_PSQL_PROG`; |
| 2742 |
if ($? != 0) { |
| 2743 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 2744 |
} |
| 2745 |
chomp(@db_proc); |
| 2746 |
|
| 2747 |
return @db_proc; |
| 2748 |
|
| 2749 |
} |
| 2750 |
|
| 2751 |
sub set_local_psql_command |
| 2752 |
{ |
| 2753 |
my $database = shift; |
| 2754 |
|
| 2755 |
my $local_psql_prog = $PSQL_PROG; |
| 2756 |
|
| 2757 |
$local_psql_prog =~ s/-d\s*[^\s]+//; |
| 2758 |
if ($database !~ /^[a-z0-9\_\-]+$/i) { |
| 2759 |
$local_psql_prog .= " -d '$database'"; |
| 2760 |
} else { |
| 2761 |
$local_psql_prog .= " -d $database"; |
| 2762 |
} |
| 2763 |
|
| 2764 |
return $local_psql_prog; |
| 2765 |
} |
| 2766 |
|
| 2767 |
sub get_proc_count |
| 2768 |
{ |
| 2769 |
my $database = shift; |
| 2770 |
|
| 2771 |
my $LOCAL_PSQL_PROG = &set_local_psql_command($database); |
| 2772 |
|
| 2773 |
my $db_proc = `echo "SELECT count(p.proname) FROM pg_proc p, pg_namespace n WHERE p.pronamespace=n.oid AND n.nspname NOT IN ('pg_catalog', 'information_schema');" | $LOCAL_PSQL_PROG`; |
| 2774 |
if ($? != 0) { |
| 2775 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 2776 |
} |
| 2777 |
chomp($db_proc); |
| 2778 |
|
| 2779 |
return $db_proc; |
| 2780 |
} |
| 2781 |
|
| 2782 |
|
| 2783 |
#### |
| 2784 |
# Retrieve user triggers count for a given database. |
| 2785 |
#### |
| 2786 |
sub get_triggers |
| 2787 |
{ |
| 2788 |
my $database = shift; |
| 2789 |
|
| 2790 |
# we can only detect internal triggers since pg 9.0 |
| 2791 |
return 0 if (! &backend_minimum_version(9,0)); |
| 2792 |
|
| 2793 |
my $LOCAL_PSQL_PROG = &set_local_psql_command($database); |
| 2794 |
|
| 2795 |
my $db_trigger = `echo "SELECT count(tgname) FROM pg_trigger WHERE NOT tgisinternal;" | $LOCAL_PSQL_PROG`; |
| 2796 |
if ($? != 0) { |
| 2797 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 2798 |
} |
| 2799 |
chomp($db_trigger); |
| 2800 |
|
| 2801 |
return $db_trigger; |
| 2802 |
} |
| 2803 |
|
| 2804 |
#### |
| 2805 |
# Get unused indexes in a database |
| 2806 |
#### |
| 2807 |
sub dump_unusedindexes |
| 2808 |
{ |
| 2809 |
|
| 2810 |
my $sql = sprintf( |
| 2811 |
"SELECT date_trunc('seconds', now()), current_database(), " . |
| 2812 |
"schemaname, relname, indexrelname, regexp_replace(pg_get_indexdef(pg_stat_user_indexes.indexrelid), E'[\\\\n\\\\r]+', ' ', 'g') " . |
| 2813 |
"FROM pg_stat_user_indexes " . |
| 2814 |
"INNER JOIN pg_index ON pg_index.indexrelid = pg_stat_user_indexes.indexrelid " . |
| 2815 |
"WHERE NOT indexrelname ILIKE 'fki%%' " . |
| 2816 |
"AND NOT indisprimary " . |
| 2817 |
"AND NOT indisunique AND idx_scan = 0 " . |
| 2818 |
(&backend_minimum_version(9,1) ? "AND NOT indisexclusion " : "") |
| 2819 |
); |
| 2820 |
|
| 2821 |
return $sql; |
| 2822 |
} |
| 2823 |
|
| 2824 |
#### |
| 2825 |
# Get redundant indexes in a database |
| 2826 |
#### |
| 2827 |
sub dump_redundantindexes |
| 2828 |
{ |
| 2829 |
|
| 2830 |
my $sql = sprintf( |
| 2831 |
"SELECT date_trunc('seconds', now()), current_database(), " . |
| 2832 |
"regexp_replace(pg_get_indexdef(indexrelid), E'[\\\\n\\\\r]+', ' ', 'g') AS contained, " . |
| 2833 |
"regexp_replace(pg_get_indexdef(index_backward), E'[\\\\n\\\\r]+', ' ', 'g') AS container " . |
| 2834 |
"FROM " . |
| 2835 |
"( " . |
| 2836 |
" SELECT indexrelid, " . |
| 2837 |
" indrelid, " . |
| 2838 |
" array_to_string(indkey,'+') AS colindex, " . |
| 2839 |
" indisunique AS is_unique, " . |
| 2840 |
" lag(array_to_string(indkey,'+')) OVER search_window AS colindexbackward, " . |
| 2841 |
" lag(indexrelid) OVER search_window AS index_backward, " . |
| 2842 |
" lag(indisunique) OVER search_window AS is_unique_backward " . |
| 2843 |
" FROM pg_index " . |
| 2844 |
" WINDOW search_window AS (PARTITION BY indrelid " . |
| 2845 |
" ORDER BY array_to_string(indkey,'+') DESC, length(regexp_replace(pg_get_indexdef(indexrelid), E'[\\n\\r]+', ' ', 'g')))" . |
| 2846 |
") AS tmp " . |
| 2847 |
"WHERE (colindexbackward LIKE (colindex || '+%') OR colindexbackward = colindex) " . |
| 2848 |
" AND (is_unique_backward <> is_unique OR (not is_unique_backward AND NOT is_unique)) " . |
| 2849 |
" AND NOT is_unique AND %s", |
| 2850 |
&backend_minimum_version(10,0) ? |
| 2851 |
" coalesce(regexp_match(pg_get_indexdef(indexrelid), ' (WHERE .*)')::text, 'A') = coalesce(regexp_match(pg_get_indexdef(index_backward), ' (WHERE .*)')::text, 'A')" : |
| 2852 |
" coalesce((SELECT (regexp_matches(pg_get_indexdef(indexrelid), ' (WHERE .*)'))[1])::text, 'A') = coalesce((SELECT (regexp_matches(pg_get_indexdef(index_backward), ' (WHERE .*)'))[1])::text, 'A')" |
| 2853 |
); |
| 2854 |
|
| 2855 |
return $sql; |
| 2856 |
} |
| 2857 |
|
| 2858 |
#### |
| 2859 |
# Get invalid indexes in a database |
| 2860 |
#### |
| 2861 |
sub dump_invalidindexes |
| 2862 |
{ |
| 2863 |
|
| 2864 |
my $sql = sprintf( |
| 2865 |
"SELECT date_trunc('seconds', now()), current_database(), " . |
| 2866 |
"schemaname, relname, indexrelname, regexp_replace(pg_get_indexdef(pg_stat_user_indexes.indexrelid), E'[\\\\n\\\\r]+', ' ', 'g') " . |
| 2867 |
"FROM pg_stat_user_indexes " . |
| 2868 |
"INNER JOIN pg_index ON pg_index.indexrelid = pg_stat_user_indexes.indexrelid " . |
| 2869 |
"WHERE NOT pg_index.indisvalid " |
| 2870 |
); |
| 2871 |
|
| 2872 |
return $sql; |
| 2873 |
} |
| 2874 |
|
| 2875 |
#### |
| 2876 |
# Get hash indexes in a database |
| 2877 |
#### |
| 2878 |
sub dump_hashindexes |
| 2879 |
{ |
| 2880 |
|
| 2881 |
my $sql = |
| 2882 |
"WITH indexes AS ( " . |
| 2883 |
"SELECT date_trunc('seconds', now()), current_database(), " . |
| 2884 |
"schemaname,relname, indexrelname, " . |
| 2885 |
"regexp_replace(pg_get_indexdef(pg_stat_user_indexes.indexrelid), E'[\\\\n\\\\r]+', ' ', 'g') as indexdef " . |
| 2886 |
"FROM pg_stat_user_indexes " . |
| 2887 |
"INNER JOIN pg_index ON pg_index.indexrelid = pg_stat_user_indexes.indexrelid)" . |
| 2888 |
"SELECT * from indexes where indexdef like '%%USING hash (%' "; |
| 2889 |
return $sql; |
| 2890 |
} |
| 2891 |
|
| 2892 |
#### |
| 2893 |
# Get table without indexes |
| 2894 |
#### |
| 2895 |
sub dump_count_indexes |
| 2896 |
{ |
| 2897 |
|
| 2898 |
my $sql = sprintf( |
| 2899 |
"SELECT date_trunc('seconds', now()), current_database(), " . |
| 2900 |
"pg_stat_user_tables.schemaname, pg_stat_user_tables.relname, " . |
| 2901 |
"count(pg_stat_user_indexes.indexrelid) as number_of_indexes " . |
| 2902 |
"FROM pg_stat_user_tables " . |
| 2903 |
"lEFT JOIN pg_stat_user_indexes ON pg_stat_user_indexes.schemaname = pg_stat_user_tables.schemaname " . |
| 2904 |
"AND pg_stat_user_indexes.relname = pg_stat_user_tables.relname " . |
| 2905 |
"GROUP BY pg_stat_user_tables.schemaname, pg_stat_user_tables.relname " |
| 2906 |
); |
| 2907 |
|
| 2908 |
return $sql; |
| 2909 |
} |
| 2910 |
|
| 2911 |
#### |
| 2912 |
# Get unused trigger function in a database |
| 2913 |
#### |
| 2914 |
sub dump_unusedtrigfunc |
| 2915 |
{ |
| 2916 |
|
| 2917 |
my $sql = sprintf( |
| 2918 |
"SELECT date_trunc('seconds', now()), current_database(), " . |
| 2919 |
"c.nspname, a.proname " . |
| 2920 |
"FROM pg_proc a JOIN pg_type b ON a.prorettype = b.oid " . |
| 2921 |
"JOIN pg_namespace c ON a.pronamespace = c.oid " . |
| 2922 |
"WHERE %s " . |
| 2923 |
"AND b.typname = 'trigger' AND c.nspname NOT IN ('pg_catalog', 'information_schema') " . |
| 2924 |
"AND a.proname NOT IN (SELECT funcname FROM pg_stat_user_functions) ", |
| 2925 |
(&backend_minimum_version(11, 0) ? "a.prokind = 'f'" : " NOT a.proiswindow AND NOT a.proisagg") |
| 2926 |
); |
| 2927 |
|
| 2928 |
return $sql; |
| 2929 |
} |
| 2930 |
|
| 2931 |
#### |
| 2932 |
# Get PostgreSQL settings |
| 2933 |
#### |
| 2934 |
sub dump_pgsettings |
| 2935 |
{ |
| 2936 |
|
| 2937 |
my $lto = $LOCK_TIMEOUT*1000; |
| 2938 |
my $sql = sprintf( |
| 2939 |
"SELECT date_trunc('seconds', now()), category, name, " . |
| 2940 |
" (CASE WHEN name = 'lock_timeout' THEN (setting::bigint-$lto)::text ELSE setting END) as setting," . |
| 2941 |
" %s, context, source, %s, %s, %s " . |
| 2942 |
"FROM pg_settings ", |
| 2943 |
&backend_minimum_version(8, 2) ? "unit" : "''::text as unit", |
| 2944 |
&backend_minimum_version(8, 4) ? "boot_val" : "''::text as boot_val", |
| 2945 |
&backend_minimum_version(8, 4) ? "(CASE WHEN name = 'lock_timeout' THEN (reset_val::bigint-$lto)::text ELSE reset_val END) as reset_val" : "''::text as reset_val", |
| 2946 |
&backend_minimum_version(9, 5) ? "pending_restart" : "''::text as pending_restart" |
| 2947 |
); |
| 2948 |
|
| 2949 |
return $sql; |
| 2950 |
} |
| 2951 |
|
| 2952 |
#### |
| 2953 |
# Get PostgreSQL non default settings |
| 2954 |
#### |
| 2955 |
sub dump_nondefault_pgsettings |
| 2956 |
{ |
| 2957 |
|
| 2958 |
my $sql = sprintf( |
| 2959 |
"SELECT date_trunc('seconds', now()), category, name, " . |
| 2960 |
" setting, %s, context, source, %s, %s " . |
| 2961 |
"FROM pg_settings " . |
| 2962 |
"WHERE source != 'default' AND source != 'override' %s", |
| 2963 |
&backend_minimum_version(8, 2) ? "unit" : "''::text as unit", |
| 2964 |
&backend_minimum_version(8, 4) ? "boot_val" : "''::text as boot_val", |
| 2965 |
&backend_minimum_version(8, 4) ? "reset_val" : "''::text as reset_val", |
| 2966 |
&backend_minimum_version(8, 4) ? "AND setting != boot_val " : "" |
| 2967 |
); |
| 2968 |
|
| 2969 |
return $sql; |
| 2970 |
} |
| 2971 |
|
| 2972 |
#### |
| 2973 |
# Get PostgreSQL database and role settings |
| 2974 |
#### |
| 2975 |
sub dump_pgdbrolesetting |
| 2976 |
{ |
| 2977 |
|
| 2978 |
my $sql = sprintf( |
| 2979 |
"SELECT date_trunc('seconds', now()), b.datname, c.rolname, a.setconfig " . |
| 2980 |
"FROM pg_db_role_setting a LEFT JOIN pg_database b ON (a.setdatabase=b.oid) " . |
| 2981 |
"LEFT JOIN pg_roles c ON (a.setrole=c.oid) " |
| 2982 |
); |
| 2983 |
|
| 2984 |
return $sql; |
| 2985 |
} |
| 2986 |
|
| 2987 |
#### |
| 2988 |
# Get unlogged tables in a database |
| 2989 |
#### |
| 2990 |
sub dump_unlogged |
| 2991 |
{ |
| 2992 |
my $sql = sprintf( |
| 2993 |
"SELECT date_trunc('seconds', now()), current_database(), n.nspname, c.relname, c.relkind " . |
| 2994 |
"FROM pg_class c, pg_namespace n " . |
| 2995 |
"WHERE n.oid=c.relnamespace AND c.relpersistence='u' and n.nspname != 'pg_toast' and c.relkind = 'r'" |
| 2996 |
); |
| 2997 |
|
| 2998 |
return $sql; |
| 2999 |
} |
| 3000 |
|
| 3001 |
|
| 3002 |
|
| 3003 |
#### |
| 3004 |
# Get path the PostgreSQL configuration files |
| 3005 |
#### |
| 3006 |
sub get_configuration_files |
| 3007 |
{ |
| 3008 |
my @cfiles = `echo "SELECT setting FROM pg_settings WHERE name IN ('config_file','hba_file','ident_file','data_directory');" | $PSQL_PROG`; |
| 3009 |
if ($? != 0) { |
| 3010 |
unlink_pid_and_exit("FATAL: psql error.", 0); |
| 3011 |
} |
| 3012 |
chomp(@cfiles); |
| 3013 |
|
| 3014 |
# Add recovery.conf and postgresql.auto.conf to the file list |
| 3015 |
my $alter_system_conf = ''; |
| 3016 |
for (my $i = 0; $i <= $#cfiles; $i++) { |
| 3017 |
if ($cfiles[$i] !~ /\.conf$/) { |
| 3018 |
$alter_system_conf = $cfiles[$i] . '/postgresql.auto.conf'; |
| 3019 |
$cfiles[$i] .= '/recovery.conf'; |
| 3020 |
} |
| 3021 |
} |
| 3022 |
push(@cfiles, $alter_system_conf); |
| 3023 |
|
| 3024 |
return sort @cfiles; |
| 3025 |
} |
| 3026 |
|
| 3027 |
#### |
| 3028 |
# Get list of DDL to create indexes missing on foreign keys |
| 3029 |
#### |
| 3030 |
sub dump_missingfkindexes |
| 3031 |
{ |
| 3032 |
|
| 3033 |
my $sql = sprintf( |
| 3034 |
"SELECT date_trunc('seconds', now()), current_database(), relname, " . |
| 3035 |
"'CREATE INDEX CONCURRENTLY idx_' || relname || '_' || |
| 3036 |
array_to_string(column_name_list, '_') || ' ON ' || conrelid || |
| 3037 |
' (' || array_to_string(column_name_list, ',') || ')' |
| 3038 |
|| CASE WHEN COUNT(DISTINCT redi.indexrelid) >0 THEN ' /* maybe redundant with: '|| string_agg (redi.indexrelid::regclass::text,', ') || ' */' ELSE '' END |
| 3039 |
AS ddl |
| 3040 |
FROM (SELECT DISTINCT conrelid, |
| 3041 |
array_agg(attname) AS column_name_list, |
| 3042 |
array_agg(attnum) AS column_list |
| 3043 |
FROM pg_attribute |
| 3044 |
JOIN (-- existing constraints |
| 3045 |
SELECT conrelid::regclass, conname, |
| 3046 |
unnest(conkey) AS column_index |
| 3047 |
FROM (SELECT DISTINCT conrelid, conname, conkey |
| 3048 |
FROM pg_constraint |
| 3049 |
JOIN pg_class ON pg_class.oid = pg_constraint.conrelid |
| 3050 |
JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace |
| 3051 |
WHERE %s AND nspname !~ '^pg_' |
| 3052 |
AND nspname <> 'information_schema' AND pg_constraint.contype = 'f' |
| 3053 |
) fkey |
| 3054 |
) fkey |
| 3055 |
ON fkey.conrelid = pg_attribute.attrelid |
| 3056 |
AND fkey.column_index = pg_attribute.attnum |
| 3057 |
GROUP BY conrelid, conname |
| 3058 |
) candidate_index |
| 3059 |
JOIN pg_class ON pg_class.oid = candidate_index.conrelid |
| 3060 |
LEFT JOIN pg_index i ON i.indrelid = conrelid |
| 3061 |
AND i.indkey::text = array_to_string(column_list, ' ') |
| 3062 |
-- potentially redundant existing indexes |
| 3063 |
LEFT JOIN pg_index redi ON redi.indrelid = conrelid |
| 3064 |
AND column_list <@ redi.indkey::smallint[] -- contains |
| 3065 |
AND redi.indkey::text != array_to_string(column_list, ' ') |
| 3066 |
WHERE i.indrelid IS NULL |
| 3067 |
GROUP BY relname, conrelid, column_name_list |
| 3068 |
ORDER BY ddl", |
| 3069 |
&backend_minimum_version(10, 0) ? "NOT pg_class.relispartition" : "true" |
| 3070 |
); |
| 3071 |
|
| 3072 |
return $sql; |
| 3073 |
} |
| 3074 |
|
| 3075 |
#### |
| 3076 |
# Get per database shared buffers statistics with pg_buffercache |
| 3077 |
#### |
| 3078 |
sub dump_pgdatabase_buffercache |
| 3079 |
{ |
| 3080 |
|
| 3081 |
# date_trunc | datname | buffers | buffered | buffers % | database % |
| 3082 |
my $sql = sprintf( |
| 3083 |
"SELECT date_trunc('seconds', now()), d.datname, " . |
| 3084 |
"count(*) AS buffers, count(*)*8192 as buffered, " . |
| 3085 |
"round(100.0 * count(*) / (SELECT setting FROM pg_settings " . |
| 3086 |
" WHERE name='shared_buffers')::integer,1) AS \"buffers %\", " . |
| 3087 |
"round(100.0 * count(*) * 8192 / pg_database_size(d.datname),1) AS \"database %\" " . |
| 3088 |
"FROM pg_database d INNER JOIN public.pg_buffercache b ON b.reldatabase=d.oid " . |
| 3089 |
"GROUP BY d.datname " |
| 3090 |
); |
| 3091 |
|
| 3092 |
return $sql; |
| 3093 |
} |
| 3094 |
|
| 3095 |
#### |
| 3096 |
# Get per relation shared buffers statistics with pg_buffercache |
| 3097 |
#### |
| 3098 |
sub dump_pgrelation_buffercache |
| 3099 |
{ |
| 3100 |
|
| 3101 |
# date_trunc | datname | relname | buffers | relpages | buffered | buffers % | relation % |
| 3102 |
my $sql = sprintf( |
| 3103 |
"SELECT date_trunc('seconds', now()), d.datname, c.relname, " . |
| 3104 |
"count(*) AS buffers, c.relpages, count(*)*8192 as buffered, " . |
| 3105 |
"round(100.0 * count(*) / (SELECT setting FROM pg_settings " . |
| 3106 |
" WHERE name='shared_buffers')::integer,1) AS \"buffers %\", " . |
| 3107 |
"round(100.0 * count(*) * 8192 / pg_relation_size(c.oid),1) AS \"relation %\" " . |
| 3108 |
"FROM pg_class c INNER JOIN public.pg_buffercache b ON b.relfilenode=c.relfilenode " . |
| 3109 |
"INNER JOIN pg_database d ON ( b.reldatabase=d.oid ) " . |
| 3110 |
"WHERE pg_relation_size(c.oid) > 0 " . |
| 3111 |
# "AND c.relname !~ '^pg_' " . |
| 3112 |
"GROUP BY d.datname, c.relname, c.relpages, c.oid " |
| 3113 |
); |
| 3114 |
|
| 3115 |
return $sql; |
| 3116 |
} |
| 3117 |
|
| 3118 |
#### |
| 3119 |
# Get usagecount distribution in shared buffers statistics with pg_buffercache |
| 3120 |
#### |
| 3121 |
sub dump_pgdatabase_usercount |
| 3122 |
{ |
| 3123 |
|
| 3124 |
# date_trunc | datname | usagecount | buffer | buffers % |
| 3125 |
my $sql = sprintf( |
| 3126 |
"SELECT date_trunc('seconds', now()), d.datname, usagecount, " . |
| 3127 |
"count(*) AS buffers, round(100.0 * count(*) / (SELECT setting FROM pg_settings " . |
| 3128 |
" WHERE name='shared_buffers')::integer,1) AS \"buffers %\" " . |
| 3129 |
"FROM pg_database d INNER JOIN public.pg_buffercache b ON b.reldatabase=d.oid " . |
| 3130 |
"GROUP BY d.datname, usagecount" |
| 3131 |
); |
| 3132 |
return $sql; |
| 3133 |
} |
| 3134 |
|
| 3135 |
#### |
| 3136 |
# Get dirty usagecount distribution in shared buffers statistics with pg_buffercache |
| 3137 |
#### |
| 3138 |
sub dump_pgdatabase_isdirty |
| 3139 |
{ |
| 3140 |
|
| 3141 |
# date_trunc | datname | usagecount | isdirty | buffer | buffers % |
| 3142 |
my $sql = sprintf( |
| 3143 |
"SELECT date_trunc('seconds', now()), d.datname, usagecount, isdirty, " . |
| 3144 |
"count(*) AS buffers, round(100.0 * count(*) / (SELECT setting FROM pg_settings " . |
| 3145 |
" WHERE name='shared_buffers')::integer,1) AS \"buffers %\" " . |
| 3146 |
"FROM pg_database d INNER JOIN public.pg_buffercache b ON b.reldatabase=d.oid " . |
| 3147 |
"GROUP BY d.datname, usagecount, isdirty " |
| 3148 |
); |
| 3149 |
return $sql; |
| 3150 |
} |
| 3151 |
|
| 3152 |
#### |
| 3153 |
# Get information about archive |
| 3154 |
#### |
| 3155 |
sub dump_pgstatarchiver |
| 3156 |
{ |
| 3157 |
|
| 3158 |
my $sql = sprintf( |
| 3159 |
"SELECT date_trunc('seconds', now()), archived_count, last_archived_wal, " . |
| 3160 |
"last_archived_time, failed_count, last_failed_wal, last_failed_time, stats_reset " . |
| 3161 |
"FROM pg_stat_archiver" |
| 3162 |
); |
| 3163 |
|
| 3164 |
return $sql; |
| 3165 |
} |
| 3166 |
|
| 3167 |
#### |
| 3168 |
# Get information about prepared transactions |
| 3169 |
#### |
| 3170 |
sub dump_preparedxactstats |
| 3171 |
{ |
| 3172 |
|
| 3173 |
my $sql = sprintf( |
| 3174 |
"SELECT date_trunc('seconds', now()), database, count(*) AS num_prepared, " . |
| 3175 |
"max(coalesce(extract('epoch' FROM date_trunc('second', current_timestamp-prepared)), 0)) oldest " . |
| 3176 |
"FROM pg_prepared_xacts GROUP BY database" |
| 3177 |
); |
| 3178 |
|
| 3179 |
return $sql; |
| 3180 |
} |
| 3181 |
|
| 3182 |
#### |
| 3183 |
# Get extended statisctics defined in a database |
| 3184 |
#### |
| 3185 |
sub dump_statisticsext |
| 3186 |
{ |
| 3187 |
|
| 3188 |
my $sql = sprintf( |
| 3189 |
"SELECT date_trunc('seconds', now()), current_database(), " . |
| 3190 |
"cn.nspname AS schemaname, c.relname AS tablename, sn.nspname AS stat_schemaname, " . |
| 3191 |
"s.stxname AS stat_name, pg_get_userbyid(s.stxowner) AS stat_owner, " . |
| 3192 |
"(SELECT array_agg(a.attname ORDER BY a.attnum) AS array_agg FROM unnest(s.stxkeys) k(k) JOIN pg_attribute a ON a.attrelid = s.stxrelid AND a.attnum = k.k) AS attnames, " . |
| 3193 |
"s.stxkind AS kinds " . |
| 3194 |
"FROM pg_statistic_ext s JOIN pg_class c ON c.oid = s.stxrelid " . |
| 3195 |
"LEFT JOIN pg_namespace cn ON cn.oid = c.relnamespace " . |
| 3196 |
"LEFT JOIN pg_namespace sn ON sn.oid = s.stxnamespace " . |
| 3197 |
"WHERE NOT (EXISTS (SELECT 1 FROM unnest(s.stxkeys) k(k) JOIN pg_attribute a ON a.attrelid = s.stxrelid AND a.attnum = k.k WHERE NOT has_column_privilege(c.oid, a.attnum, 'select'::text))) " . |
| 3198 |
"AND (c.relrowsecurity = false OR NOT row_security_active(c.oid))" |
| 3199 |
); |
| 3200 |
|
| 3201 |
return $sql; |
| 3202 |
} |
| 3203 |
|
| 3204 |
|
| 3205 |
|
| 3206 |
sub parse_pretty_size |
| 3207 |
{ |
| 3208 |
my $val = shift; |
| 3209 |
return 0 if (!$val); |
| 3210 |
|
| 3211 |
$val =~ s/\s+//g; |
| 3212 |
|
| 3213 |
if ($val =~ /^(\d+)PB/i) { |
| 3214 |
$val = $1 * 1024 * 1024 * 1024 * 1024 * 1024; |
| 3215 |
} elsif ($val =~ /^(\d+)TB/i) { |
| 3216 |
$val = $1 * 1024 * 1024 * 1024 * 1024; |
| 3217 |
} elsif ($val =~ /^(\d+)GB/i) { |
| 3218 |
$val = $1 * 1024 * 1024 * 1024; |
| 3219 |
} elsif ($val =~ /^(\d+)MB/i) { |
| 3220 |
$val = $1 * 1024 * 1024; |
| 3221 |
} elsif ($val =~ /^(\d+)KB/i) { |
| 3222 |
$val = $1 * 1024; |
| 3223 |
} |
| 3224 |
|
| 3225 |
# du -s command returns kb so do the same here |
| 3226 |
return int($val/1024); |
| 3227 |
} |
| 3228 |
|
| 3229 |
|
| 3230 |
#### |
| 3231 |
# Method used to fork compress process |
| 3232 |
## |
| 3233 |
sub spawn_compress |
| 3234 |
{ |
| 3235 |
my $coderef = shift; |
| 3236 |
|
| 3237 |
unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') { |
| 3238 |
print "usage: spawn_comrpess CODEREF"; |
| 3239 |
exit 0; |
| 3240 |
} |
| 3241 |
|
| 3242 |
if (!defined($COMPRESS_PID = fork)) { |
| 3243 |
print STDERR "Error: cannot fork: $!\n"; |
| 3244 |
return; |
| 3245 |
} elsif ($COMPRESS_PID) { |
| 3246 |
return; # the parent |
| 3247 |
} |
| 3248 |
# the child -- go spawn |
| 3249 |
$< = $>; |
| 3250 |
$( = $); # suid progs only |
| 3251 |
|
| 3252 |
exit &$coderef(); |
| 3253 |
} |
| 3254 |
|
| 3255 |
#### |
| 3256 |
# Method used to fork metrics collect |
| 3257 |
## |
| 3258 |
sub spawn_collect |
| 3259 |
{ |
| 3260 |
my $coderef = shift; |
| 3261 |
|
| 3262 |
unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') { |
| 3263 |
print "usage: spawn_collect CODEREF"; |
| 3264 |
exit 0; |
| 3265 |
} |
| 3266 |
|
| 3267 |
if (!defined($COLLECT_PID = fork)) { |
| 3268 |
print STDERR "Error: cannot fork: $!\n"; |
| 3269 |
return; |
| 3270 |
} elsif ($COLLECT_PID) { |
| 3271 |
return; # the parent |
| 3272 |
} |
| 3273 |
# the child -- go spawn |
| 3274 |
$< = $>; |
| 3275 |
$( = $); # suid progs only |
| 3276 |
|
| 3277 |
exit &$coderef(); |
| 3278 |
} |
| 3279 |
|
| 3280 |
#### |
| 3281 |
# Methods used to fork sar and pidstat |
| 3282 |
## |
| 3283 |
sub spawn_sar |
| 3284 |
{ |
| 3285 |
my $coderef = shift; |
| 3286 |
|
| 3287 |
unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') { |
| 3288 |
print "usage: spawn_sar CODEREF"; |
| 3289 |
exit 0; |
| 3290 |
} |
| 3291 |
|
| 3292 |
if (!defined($SAR_PID = fork)) { |
| 3293 |
print STDERR "Error: cannot fork: $!\n"; |
| 3294 |
return; |
| 3295 |
} elsif ($SAR_PID) { |
| 3296 |
return; # the parent |
| 3297 |
} |
| 3298 |
# the child -- go spawn |
| 3299 |
$< = $>; |
| 3300 |
$( = $); # suid progs only |
| 3301 |
|
| 3302 |
exit &$coderef(); |
| 3303 |
} |
| 3304 |
|
| 3305 |
sub spawn_pidstat |
| 3306 |
{ |
| 3307 |
my $coderef = shift; |
| 3308 |
|
| 3309 |
unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') { |
| 3310 |
print "usage: spawn_pidstat CODEREF"; |
| 3311 |
exit 0; |
| 3312 |
} |
| 3313 |
|
| 3314 |
if (!defined($PIDSTAT_PID = fork)) { |
| 3315 |
print STDERR "Error: cannot fork: $!\n"; |
| 3316 |
return; |
| 3317 |
} elsif ($PIDSTAT_PID) { |
| 3318 |
return; # the parent |
| 3319 |
} |
| 3320 |
# the child -- go spawn |
| 3321 |
$< = $>; |
| 3322 |
$( = $); # suid progs only |
| 3323 |
|
| 3324 |
exit &$coderef(); |
| 3325 |
} |
| 3326 |
|
| 3327 |
sub wait_all_childs |
| 3328 |
{ |
| 3329 |
while ($COMPRESS_PID || $COLLECT_PID || $SAR_PID || $PIDSTAT_PID) |
| 3330 |
{ |
| 3331 |
my $kid = waitpid(-1, WNOHANG); |
| 3332 |
if ($kid > 0) |
| 3333 |
{ |
| 3334 |
if ($COLLECT_PID == $kid) { |
| 3335 |
$COLLECT_PID = 0; |
| 3336 |
} elsif ($COMPRESS_PID == $kid) { |
| 3337 |
$COMPRESS_PID = 0; |
| 3338 |
} elsif ($SAR_PID == $kid) { |
| 3339 |
$SAR_PID = 0; |
| 3340 |
} elsif ($PIDSTAT_PID == $kid) { |
| 3341 |
$PIDSTAT_PID = 0; |
| 3342 |
} |
| 3343 |
} |
| 3344 |
sleep(1); |
| 3345 |
} |
| 3346 |
} |
| 3347 |
|
| 3348 |
sub compress_files |
| 3349 |
{ |
| 3350 |
my ($dir) = shift; |
| 3351 |
|
| 3352 |
&dprint("LOG: compressing directory $dir using $GZIP_PROG.\n"); |
| 3353 |
|
| 3354 |
`$GZIP_PROG $dir/*`; |
| 3355 |
|
| 3356 |
} |
| 3357 |
|
| 3358 |
sub unlink_pid_and_exit |
| 3359 |
{ |
| 3360 |
my ($msg, $rc) = shift; |
| 3361 |
|
| 3362 |
&dprint("$msg\n"); |
| 3363 |
# remove the pidfile |
| 3364 |
if (-f $PIDFILE) { |
| 3365 |
unlink $PIDFILE or &dprint("ERROR: Unable to remove pidfile: $!\n"); |
| 3366 |
} |
| 3367 |
exit $rc; |
| 3368 |
} |
| 3369 |
|
| 3370 |
# Load setting from file pg_settings.csv and pg_db_role_setting.csv into hashrefs |
| 3371 |
sub load_settings |
| 3372 |
{ |
| 3373 |
my ($in_dir, $pg_settings, $dbrole_settings) = @_; |
| 3374 |
|
| 3375 |
if (-e "$in_dir/pg_settings.csv") { |
| 3376 |
# Load data from pg_settings.csv file |
| 3377 |
my $curfh = IO::File->new("$in_dir/pg_settings.csv", 'r'); |
| 3378 |
while (<$curfh>) { |
| 3379 |
chomp(); |
| 3380 |
my @data = split(/;/); |
| 3381 |
# timestamp | label | setting | value | unit | context | source | boot_val | reset_val | pending_restart |
| 3382 |
$pg_settings->{$data[2]}{value} = $data[3]; |
| 3383 |
$pg_settings->{$data[2]}{unit} = ''; |
| 3384 |
$pg_settings->{$data[2]}{bootval} = ''; |
| 3385 |
$pg_settings->{$data[2]}{resetval} = ''; |
| 3386 |
if ($#data >= 6) { |
| 3387 |
$pg_settings->{$data[2]}{unit} = $data[4]; |
| 3388 |
$pg_settings->{$data[2]}{bootval} = $data[7]; |
| 3389 |
$pg_settings->{$data[2]}{resetval} = $data[8]; |
| 3390 |
if ($#data >= 9) { |
| 3391 |
$pg_settings->{$data[2]}{pending_restart} = $data[9]; |
| 3392 |
} |
| 3393 |
} |
| 3394 |
} |
| 3395 |
$curfh->close(); |
| 3396 |
} |
| 3397 |
if (-e "$in_dir/pg_db_role_setting.csv") { |
| 3398 |
# Load data from pg_db_role_setting.csv file |
| 3399 |
my $curfh = IO::File->new("$in_dir/pg_db_role_setting.csv", 'r'); |
| 3400 |
while (<$curfh>) { |
| 3401 |
chomp(); |
| 3402 |
my @data = split(/;/); |
| 3403 |
# timestamp | database | role | settings |
| 3404 |
$data[1] ||= 'All'; |
| 3405 |
$data[2] ||= 'All'; |
| 3406 |
$dbrole_settings->{$data[1]}{$data[2]} = $data[3]; |
| 3407 |
} |
| 3408 |
$curfh->close(); |
| 3409 |
|
| 3410 |
} |
| 3411 |
} |
| 3412 |
|
| 3413 |
# Save pg_settings into temporaries files and return the path to the files |
| 3414 |
sub save_pg_settings |
| 3415 |
{ |
| 3416 |
my ($out_dir, $pg_settings_orig, $pg_settings_curr) = @_; |
| 3417 |
|
| 3418 |
my $f1 = "$out_dir/pg_settings_orig.tmp"; |
| 3419 |
my $curfh = IO::File->new($f1, 'w'); |
| 3420 |
if (defined $curfh) { |
| 3421 |
foreach my $k (sort keys %$pg_settings_orig) { |
| 3422 |
print $curfh "$k : "; |
| 3423 |
foreach my $c (sort keys %{$pg_settings_orig->{$k}}) { |
| 3424 |
next if ($pg_settings_orig->{$k}{$c} eq ''); |
| 3425 |
print $curfh "$c => $pg_settings_orig->{$k}{$c}, "; |
| 3426 |
} |
| 3427 |
print $curfh "\n"; |
| 3428 |
} |
| 3429 |
$curfh->close(); |
| 3430 |
} |
| 3431 |
|
| 3432 |
my $f2 = "$out_dir/pg_settings_curr.tmp"; |
| 3433 |
$curfh = IO::File->new($f2, 'w'); |
| 3434 |
if (defined $curfh) { |
| 3435 |
foreach my $k (sort keys %$pg_settings_curr) { |
| 3436 |
print $curfh "$k : "; |
| 3437 |
foreach my $c (sort keys %{$pg_settings_curr->{$k}}) { |
| 3438 |
next if ($pg_settings_curr->{$k}{$c} eq ''); |
| 3439 |
print $curfh "$c => $pg_settings_curr->{$k}{$c}, "; |
| 3440 |
} |
| 3441 |
print $curfh "\n"; |
| 3442 |
} |
| 3443 |
$curfh->close(); |
| 3444 |
} |
| 3445 |
|
| 3446 |
return ($f1,$f2); |
| 3447 |
} |
| 3448 |
|
| 3449 |
# Save db / roles settings into temporaries files and return the path to the files |
| 3450 |
sub save_dbrole_settings |
| 3451 |
{ |
| 3452 |
my ($out_dir, $pg_dbrole_settings_orig, $pg_dbrole_settings_curr) = @_; |
| 3453 |
|
| 3454 |
my $f1 = "$out_dir/pg_dbrole_settings_orig.tmp"; |
| 3455 |
my $curfh = IO::File->new($f1, 'w'); |
| 3456 |
if (defined $curfh) { |
| 3457 |
foreach my $k (sort keys %$pg_dbrole_settings_orig) { |
| 3458 |
foreach my $c (sort keys %{$pg_dbrole_settings_orig->{$k}}) { |
| 3459 |
print $curfh "Database: $k, Role: $c, Settings: $pg_dbrole_settings_orig->{$k}{$c}\n"; |
| 3460 |
} |
| 3461 |
} |
| 3462 |
$curfh->close(); |
| 3463 |
} |
| 3464 |
|
| 3465 |
my $f2 = "$out_dir/pg_dbrole_settings_curr.tmp"; |
| 3466 |
$curfh = IO::File->new($f2, 'w'); |
| 3467 |
if (defined $curfh) { |
| 3468 |
foreach my $k (sort keys %$pg_dbrole_settings_curr) { |
| 3469 |
foreach my $c (sort keys %{$pg_dbrole_settings_curr->{$k}}) { |
| 3470 |
print $curfh "Database: $k, Role: $c, Settings: $pg_dbrole_settings_curr->{$k}{$c}\n"; |
| 3471 |
} |
| 3472 |
} |
| 3473 |
$curfh->close(); |
| 3474 |
} |
| 3475 |
|
| 3476 |
return ($f1,$f2); |
| 3477 |
} |
| 3478 |
|
| 3479 |
sub read_conf |
| 3480 |
{ |
| 3481 |
# We don't need a configuration file but if any check the |
| 3482 |
# configuration directives related to pgcluu_collectd. |
| 3483 |
my $curfh = IO::File->new($CONFIG_FILE, 'r'); |
| 3484 |
if (defined $curfh) { |
| 3485 |
print STDERR "DEBUG: Reading configuration file $CONFIG_FILE\n" if ($DEBUG); |
| 3486 |
while (my $l = <$curfh>) |
| 3487 |
{ |
| 3488 |
chomp($l); |
| 3489 |
$l =~ s/\r//gs; |
| 3490 |
next if (!$l); |
| 3491 |
|
| 3492 |
my ($var, @vals) = split(/[\s]+/, $l); |
| 3493 |
if ($var eq 'STATS_COLLECTD_RETENTION') { |
| 3494 |
$vals[0] = int($vals[0]); |
| 3495 |
if ($RETENTION != $vals[0]) { |
| 3496 |
$RETENTION = $vals[0]; |
| 3497 |
print STDERR "LOG: Setting retention from configuration file to $RETENTION\n"; |
| 3498 |
} |
| 3499 |
} |
| 3500 |
} |
| 3501 |
} |
| 3502 |
} |