This repository has been archived by the owner on Jul 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
checkup
executable file
·1489 lines (1329 loc) · 45.7 KB
/
checkup
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
#
# Copyright © Postgres.ai (https://postgres.ai), Nikolay Samokhvalov
#
# Automated health-checks of PostgreSQL clusters
#
# Usage: ./checkup --help
#
# GLOBALS (user-assigned variables)
FULL_REPORT_FNAME="0_Full_report.md"
# GLOBALS (autoload, do not change)
: ${DEBUG:=false} # print debug output
SCRIPT_NAME=$(basename $0)
SCRIPT_DIR=$(dirname $0)
PGHREP_BIN="${SCRIPT_DIR}/pghrep/bin/pghrep"
SAFE_IFS="$IFS"
ALL_ARGS="$@"
OPTIONS_ERROR_EXIT="false"
DEFAULT_LIST_LIMIT=50
DEFAULT_CONNECTION_TIMEOUT=10
DEFAULT_PG_PORT=5432
DEFAULT_SSH_PORT=22
LARGE_DB_ITEMS_COUNT=100000
AVAILABLE_MODES=("collect" "process" "upload" "help" "run")
# Output styles (only BOLD is supported by default GNU screen)
BOLD=`tput md 2>/dev/null` || :
RESET=`tput me 2>/dev/null` || :
#######################################
# Print a message to STDOUT with timestamp
# Globals:
# None
# Arguments:
# None
# Returns:
# (text) STDOUT
#######################################
function msg() {
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')] $@"
}
#######################################
# Print a debug-level message to STDOUT with timestamp
# Globals:
# DEBUG
# Arguments:
# (text) Message
# Returns:
# None
#######################################
function dbg() {
if [[ $DEBUG == "true" ]] ; then
msg "DEBUG: ${FUNCNAME[1]}: $@"
fi
}
#######################################
# Print an error/warning/notice to STDERR with timestamp and error location
# Please use 'exit' with code after usage
# of this function (if needed)
# Globals:
# None
# Arguments:
# (text) Error message
# Returns:
# (text) STDERR
#######################################
function err() {
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')] ERROR: ${FUNCNAME[1]}: $@" >&2
}
#######################################
# Print an error/warning/notice to STDERR with timestamp only
# Please use 'exit' with code after usage
# of this function (if needed)
# Globals:
# None
# Arguments:
# (text) Error message
# Returns:
# (text) STDERR
#######################################
function errmsg() {
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')] $@" >&2
}
#######################################
# Error trapping function, prints line number
# Globals:
# SCRIPT_NAME, BASH_LINENO[0]
# Arguments:
# (text) Message
# Returns:
# (lines with text) STDOUT
#######################################
error_handler() {
err "^^^ ERROR at [file: '${SCRIPT_NAME}', line: '${BASH_LINENO[0]}']" >&2
echo >&2
}
#######################################
# Cleanup function: close ssh sockets, etc.
# Globals:
# HOST
# Arguments:
# None
# Returns:
# (lines with text) STDOUT/STDERR
#######################################
cleanup_and_exit() {
local exit_code="$?" # we can detect exit code here
if [[ ! -z ${HOST+x} ]]; then
dbg "closing ssh conenction to host '$HOST' (if exists)"
(ssh -O exit ${HOST} 2>/dev/null) || true
fi
dbg "exit code is: '${exit_code}'"
exit "${exit_code}"
}
#######################################
# Read non-comment and non-empty lines from cli.conf
# Globals:
# SCRIPT_DIR
# Arguments:
# None
# Returns:
# (lines with text) STDOUT
#######################################
load_cli_res() {
local setting
if [[ ! -f "${SCRIPT_DIR}/resources/cli.conf" ]]; then
err "Cannot load '${SCRIPT_DIR}/resources/cli.conf'"
exit 2
fi
while read -r setting; do
# skip comments and empty lines
local re='^(#|$|[:blank:])'
[[ "$setting" =~ $re ]] && continue
echo "${setting}'"
done < "${SCRIPT_DIR}"/resources/cli.conf
}
#######################################
# Fill structures with possible CLI arguments from file
# Globals:
# CLI_ARGS_POSSIBLE, SECTION[], SHORT_NAME[],
# FULL_NAME[], ARG_TYPE[], MANDATARY[], DESCRIPTION[],
# Arguments:
# None
# Returns:
# None
#######################################
read_possible_args() {
local iter_num=0
local section short_name full_name arg_type mandatary description
if [[ ! -f "${SCRIPT_DIR}/resources/cli.conf" ]]; then
err "Can't load '${SCRIPT_DIR}/resources/cli.conf'"
exit 2
fi
while IFS="|" read -r section short_name full_name internal_name arg_type mandatary arg_mode description; do
# cut last garbage symbol
# TODO(vyagofarov): understand this 'cutting' behavior
description=${description%?}
SECTION[$iter_num]="$section"
SHORT_NAME[$iter_num]="$short_name"
FULL_NAME[$iter_num]="$full_name"
INTERNAL_NAME[$iter_num]="$internal_name"
ARG_TYPE[$iter_num]="$arg_type"
MANDATARY[$iter_num]="$mandatary"
ARG_MODE[$iter_num]="$arg_mode"
DESCRIPTION[$iter_num]="$description"
dbg "iteration number: $iter_num"
dbg "1: section '${SECTION[$iter_num]}'"
dbg "2: short_name '${SHORT_NAME[$iter_num]}'"
dbg "3: full_name '${FULL_NAME[$iter_num]}'"
dbg "4: internal_name '${INTERNAL_NAME[$iter_num]}'"
dbg "5: arg_type '${ARG_TYPE[$iter_num]}'"
dbg "6: mandatary '${MANDATARY[$iter_num]}'"
dbg "6: mode '${ARG_MODE[$iter_num]}'"
dbg "7: description '${DESCRIPTION[$iter_num]}'"
iter_num=$(( iter_num + 1 ))
done < <(load_cli_res)
# $CLI_ARGS_POSSIBLE is a global index
# for all CLI input values and their properties,
# starting from zero (convenient for arrays)
CLI_ARGS_POSSIBLE=$(( iter_num - 1 ))
dbg "possible args are read"
}
#######################################
# Load configuration from a file and save parameters in an indexed array
# Globals:
# $1, CLI_ARGS_POSSIBLE, ARG_VALUE[],
# CLI_ARGS_CNT, ARG_IS_GIVEN[]
# Arguments:
# (text) config file path
# Returns:
# None
#######################################
load_config_params () {
dbg "Load params from config file"
config_filename=${1}
if [[ ! -f "$config_filename" ]]; then
err "Config filename ${config_filename} not found."
exit 1
fi
eval $(${PGHREP_BIN} --mode loadcfg --path $config_filename 2>/dev/null)
for i in $(seq 0 ${CLI_ARGS_POSSIBLE}); do
var_name="CONFIG__"${FULL_NAME[$i]}
var_name=${var_name//-/_}
if [[ ! -z ${!var_name+x} ]]; then
value=$(eval echo "\$$var_name")
dbg "$var_name = $value"
if [[ "${ARG_TYPE[$i]}" = "None" ]]; then
ARG_VALUE[$i]="true"
ARG_IS_GIVEN[$i]="true"
else
if [[ -z "${value+x}" ]] || [[ "${value}" =~ $re ]]; then
err "Empty value is not allowed for variable '--${FULL_NAME[$i]}' in config file '${config_filename}'."
exit 1
fi
ARG_VALUE[$i]=$value
ARG_IS_GIVEN[$i]="true"
fi
fi
CLI_ARGS_CNT=$(( CLI_ARGS_CNT + 1 ))
done
return
}
#######################################
# Parse CLI arguments and save as an indexed array
# Globals:
# $1, CLI_ARGS_POSSIBLE, SHORT_NAME[], FULL_NAME[], ARG_VALUE[],
# CLI_ARGS_CNT, ARG_IS_GIVEN[]
# Arguments:
# $@
# Returns:
# None
#######################################
process_cli_args() {
local cli_arg_cur_value i
local re='^-'
local while_loops_cnt=0
local argvalue
dbg "Valid CLI args possible count: ${CLI_ARGS_POSSIBLE}+1"
CLI_ARGS_CNT=0
while [[ ! -z "${1+x}" ]]; do
# print help if first argument matches regular expression
local help_re="(-+(help|usage|\?))|(help|usage|\?)"
if [[ "${1}" =~ $help_re ]]; then
usage "Help" "0"
exit 0
fi
if [[ "${AVAILABLE_MODES[@]}" =~ "${1}" ]]; then
ARG_VALUE[0]="${1}"
ARG_IS_GIVEN[0]="true"
shift 1
continue
fi
# avoid infinite loop if argument is unknown
while_loops_cnt=$(( while_loops_cnt + 1 ))
[[ $while_loops_cnt -gt $(( CLI_ARGS_POSSIBLE * 2 )) ]] && break
# first, error if argument is unknown:
local arg_is_valid="false"
for i in $(seq 0 ${CLI_ARGS_POSSIBLE}); do
if [[ "${1}" = "-${SHORT_NAME[$i]}" ]] || [[ "${1}" = "--${FULL_NAME[$i]}" ]]; then
arg_is_valid="true"
break
fi
done
if [[ "${arg_is_valid}" == "false" ]]; then
err "invalid argument '${1}'"
exit 1
fi
# compare given argument to all possible arguments from cli.conf
for i in $(seq 0 ${CLI_ARGS_POSSIBLE}); do
if [[ ! -z "${1+x}" ]]; then
case $1 in
"-${SHORT_NAME[$i]}" | "--${FULL_NAME[$i]}" )
# argument without value (like '--force', ARG_TYPE is 'None')
if [[ "${1}" = "-c" ]] || [[ "${1}" = "--config" ]]; then
# parse yaml config file and load params
load_config_params ${2}
shift 2
continue
fi
if [[ "${ARG_TYPE[$i]}" = "None" ]]; then
ARG_VALUE[$i]="true"
ARG_IS_GIVEN[$i]="true"
shift 1
# argument with value
else
if [[ -z "${2+x}" ]]; then
err "empty value for variable '--${FULL_NAME[$i]}'"
exit 1
fi
if [[ "${2}" =~ $re ]]; then
err "empty value for variable '--${FULL_NAME[$i]}'"
exit 1
fi
ARG_VALUE[$i]="${2}"
ARG_IS_GIVEN[$i]="true"
dbg "${SHORT_NAME[$i]} 45 ${ARG_VALUE[$i]}"
shift 2
fi
CLI_ARGS_CNT=$(( CLI_ARGS_CNT + 1 ))
esac
fi
done
done
dbg "given arguments count: '$CLI_ARGS_CNT'"
}
#######################################
# Validate single argument type
# Globals:
# None
# Arguments:
# $1, $2, $3
# Returns:
# None
#######################################
validate_arg_type() {
local name="$1"
local type="$2"
local value="$3"
local re
if [ -z "$name" -o -z "$type" -o -z "$value" ]; then
err "name: '$name', type: '$type', value: '$value'"
fi
if [[ "$type" = "number" ]]; then
re='^[0-9]+$'
if ! [[ $value =~ $re ]] ; then
err "'$name' = '$value' => is not a '$type' (${re})"
exit 1
fi
elif [ $type = "word" ]; then
re='^[a-zA-Z0-9_-]+$'
if ! [[ $value =~ $re ]]; then
err "'$name' = '$value' => is not a '$type' (${re})"
exit 1
fi
elif [ $type = "alnum" ]; then
re='^[a-zA-Z0-9\.]+$'
if ! [[ $value =~ $re ]]; then
err "'$name' = '$value' => is not a '$type' (${re})"
exit 1
fi
elif [[ $type = "uri" ]]; then
re='^[a-zA-Z\;\:\\\/]+.*'
if ! [[ $value =~ $re ]]; then
err "'$name' = '$value' => is not a '$type' (${re})"
exit 1
fi
elif [[ $type = "filepath" ]]; then
re='.*'
if ! [[ $value =~ $re ]]; then
err "'$name' = '$value' => is not a '$type' (${re})"
exit 1
fi
elif [[ $type = "text" ]]; then
re='^[a-zA-Z0-9\;\.\s\\\/]+.*'
if ! [[ $value =~ $re ]]; then
err "'$name' = '$value' => is not a '$type' (${re})"
exit 1
fi
elif [[ $type = "None" ]]; then
true
else
err "'$name' = '$value' => unknown argument type, validation error"
exit 1
fi
}
#######################################
# Generate psql command
# Globals:
# PSQL_CONN_OPTIONS, HOST, OPTIONS_ERROR_EXIT
# USERNAME, PGPASSWORD, DBNAME, STIMEOUT
# Arguments:
# None
# Returns:
# None
#######################################
generate_psql_cmd() {
local pg_port=$DEFAULT_PG_PORT
if [[ "$PGPORT" != "None" ]]; then
pg_port=$PGPORT
fi
# custom UNIX domain socket directory for PostgreSQL
local psql_unix_socket_option=""
if [[ "${PGSOCKET}" != "None" ]]; then
psql_unix_socket_option=" --host '${PGSOCKET}' "
fi
# custom psql binary path support
local psql_bin="psql"
if [[ "${PSQLBINARY}" != "None" ]]; then
psql_bin="${PSQLBINARY}"
fi
# generate or not PGPASSWORD string (for substitution)
if [[ ! -z ${PGPASSWORD+x} ]]; then
local pgpas_subst="PGPASSWORD=\"${PGPASSWORD}\" " # whitespace in the end of the string
else
local pgpas_subst=""
fi
# use default Postgres username or not
local user_substr=""
if [[ ! -z ${USERNAME+x} ]]; then
user_substr=" -U \"${USERNAME}\" "
fi
# Construct _PSQL macro for usage inside the check scripts
export PSQL_CONN_OPTIONS="--port=${pg_port} --dbname=${DBNAME} ${user_substr} ${psql_unix_socket_option}"
psql_command="${pgpas_subst}${psql_bin} -1 -X -At -q -v ON_ERROR_STOP=1 -P pager=off ${PSQL_CONN_OPTIONS}"
export _PSQL_NO_TIMEOUT="PGAPPNAME=checkup ${psql_command}"
export _PSQL="PGAPPNAME=checkup PGOPTIONS=\"-c statement_timeout=${STIMEOUT}s\" ${psql_command}"
dbg ""
dbg "PSQL_CONN_OPTIONS: $PSQL_CONN_OPTIONS"
dbg ""
}
#######################################
# Validate arguments and and save input variables
# Globals:
# CLI_ARGS_POSSIBLE, SECTION[], SHORT_NAME[],
# FULL_NAME[], ARG_TYPE[], MANDATARY[], DESCRIPTION[],
# ARG_VALUE[], ARG_IS_GIVEN[], INTERNAL_*, CLI_ARGS_CNT,
# MANDATORY[], PSQL_CONN_OPTIONS, HOST, OPTIONS_ERROR_EXIT
# Arguments:
# None
# Returns:
# None
#######################################
validate_args() {
local i
local x=0
local need_fail_exit="false"
if [[ "${CLI_ARGS_CNT}" -lt 1 ]]; then
usage "No arguments are provided, at least one is needed." "1"
fi
for i in $(seq 0 ${CLI_ARGS_POSSIBLE}); do
if [[ ! -z "${ARG_IS_GIVEN[$i]+x}" ]]; then
# generate dynamic variables like "$HOST" or "$PSQLBINARY"
# from './resources/cli.conf' (INTERNAL_NAME)
eval "export ${INTERNAL_NAME[$i]}=\"${ARG_VALUE[$i]}\""
validate_arg_type "${FULL_NAME[$i]}" "${ARG_TYPE[$i]}" "${ARG_VALUE[$i]}"
else
export "${INTERNAL_NAME[$i]}=None"
fi
done
# fill default (not given) psql connection related variables
[[ "${DBNAME}" = "None" ]] && export DBNAME=postgres
[[ "${STIMEOUT}" = "None" ]] && export STIMEOUT=30 # statement timeout
[[ "${USERNAME}" = "None" ]] && export USERNAME=""
[[ "${LISTLIMIT}" = "None" ]] && export LISTLIMIT=${DEFAULT_LIST_LIMIT}
[[ "${CONNTIMEOUT}" = "None" ]] && export CONNTIMEOUT=${DEFAULT_CONNECTION_TIMEOUT} # connection timeout
if [[ "${MODE}" = "None" ]]; then
export MODE="run"
ARG_VALUE[0]="run"
ARG_IS_GIVEN[0]="true"
fi
generate_psql_cmd
if ([[ "$HTML" == "true" ]] || [[ "$PDF" == "true" ]]); then
PANDOC=$(which pandoc || echo -n "0");
if [[ "$PANDOC" == "0" ]]; then
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')] ERROR: 'pandoc' not found. Cannot generate PDF/HTML." >&2
exit 1
fi
fi
if [[ "$PDF" == "true" ]]; then
WKHTMLTOPDF=$(which wkhtmltopdf || echo -n "0");
if [[ "$WKHTMLTOPDF" == "0" ]]; then
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')] ERROR: 'wkhtmltopdf' not found. Cannot generate PDF." >&2
exit 1
fi
wkhtmltopdf_ver_resp=$(wkhtmltopdf -V)
wkhtmltopdf_ver_resp_lines=${wkhtmltopdf_ver_resp// /\\n}
wkhtmltopdf_current_ver=$(echo -e $wkhtmltopdf_ver_resp_lines | awk '/([0-9.]+)/')
wkhtmltopdf_required_ver="0.12.4"
if [ "$(printf '%s\n' "$wkhtmltopdf_required_ver" "$wkhtmltopdf_current_ver" | sort -V | head -n1)" != "$wkhtmltopdf_required_ver" ]; then
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')] ERROR: 'wkhtmltopdf' version is outdated. Update to $wkhtmltopdf_required_ver or newer. See README. Cannot generate PDF." >&2
exit 1
fi
fi
# error if mandatory options are not set (print as a stack)
local buf=""
for i in $(seq 0 ${CLI_ARGS_POSSIBLE}); do
if [[ "${MANDATARY[$i]}" == "mandatory" ]] && [[ -z "${ARG_IS_GIVEN[$i]+x}" ]] ; then
if ([[ "${ARG_MODE[$i]}" == "all" ]] || ( [[ "${ARG_MODE[$i]}" != "all" ]] && [[ "${ARG_MODE[$i]}" =~ "${MODE}" ]])); then
# please do not change align for 'buf' variable text
buf="$buf
mandatory option '--${FULL_NAME[$i]}' is not set"
need_fail_exit=true
OPTIONS_ERROR_EXIT=true
fi
fi
done
if [[ "$HOST" == "None" ]] && [[ "$SSHHOST" == "None" ]] &&
[[ "$PGHOST" == "None" ]] && ([[ "$MODE" == "collect" ]] || [[ "$MODE" == "run" ]]) ; then
buf="$buf
at least one of options '--hostname', '--ssh-hostname' or '--pg-hostname' must be set"
# mandatory option '--hostname' is not set"
need_fail_exit=true
OPTIONS_ERROR_EXIT=true
fi
local hosts=0
[[ "$SSHHOST" != "None" ]] && hosts=$((hosts + 1))
[[ "$PGHOST" != "None" ]] && hosts=$((hosts + 1))
[[ "$HOST" != "None" ]] && hosts=$((hosts + 1))
if [[ $hosts -gt 1 ]]; then
buf="$buf
only one of options '--hostname', '--ssh-hostname' or '--pg-hostname' may be used"
need_fail_exit=true
OPTIONS_ERROR_EXIT=true
fi
if [[ "$SSHPORT" != "None" ]] && ([[ "$PGHOST" != "None" ]] || [[ "$HOST" != "None" ]]) ; then
buf="$buf
'--ssh-port' may be used only with '--ssh-hostname'"
need_fail_exit=true
OPTIONS_ERROR_EXIT=true
fi
if [[ "$need_fail_exit" = "true" ]]; then
usage "$buf" "1"
fi
}
#######################################
# Generate usage/help
# Globals:
# CLI_ARGS_POSSIBLE, FULL_NAME[], SECTION[]
# SCRIPT_NAME, SHORT_NAME[], DESCRIPTION[]
# Arguments:
# description exit_code code
# Returns:
# (text) stdout/stderr
#######################################
usage() {
local i
local description="$1"
local exit_code="$2"
local exit_code=${exit_code:=0}
local out_descriptor
local re="[a-zA-Z]"
if [[ ! "$description" =~ $re ]]; then
err "First argument of 'usage' must be a text description"
exit 1
fi
# if error: print reason before 'Usage:'
if [[ "$exit_code" -ne "0" ]]; then
out_descriptor="2" # STDERR
echo "ERROR: " >&${out_descriptor}
echo " $description" >&${out_descriptor}
echo >&${out_descriptor}
else
out_descriptor="1" # STDOUT
# help part starts here
echo >&${out_descriptor}
echo "POSTGRES-CHECKUP collects deep diagnostics of a Postgres database's health." >&${out_descriptor}
echo "Project home: https://gitlab.com/postgres-ai-team/postgres-checkup." >&${out_descriptor}
echo >&${out_descriptor}
fi
echo "Usage:" >&${out_descriptor}
echo " ${SCRIPT_NAME} OPTION [OPTION] ..." >&${out_descriptor}
echo " ${SCRIPT_NAME} help" >&${out_descriptor}
if [[ "$exit_code" -ne "0" ]]; then
exit "$exit_code"
fi
echo >&${out_descriptor}
echo "postgres-checkup can separately collect, process and upload data to server. " >&${out_descriptor}
echo "You can set the working mode with --mode option." >&${out_descriptor}
echo "Available values for mode: 'collect', 'process', 'upload', 'run'." >&${out_descriptor}
echo "Mode 'run' executes collecting and processing at once, it is a default mode." >&${out_descriptor}
# Printing CLI options starts here
# calc max size of FULL_NAME[] for text alignment
local max_name_len=0
for i in $(seq 0 ${CLI_ARGS_POSSIBLE}); do
bytlen=${#FULL_NAME[$i]}
if [[ "$bytlen" -ge "$max_name_len" ]]; then
max_name_len=$bytlen
fi
done
local space
local prev_section="Misc"
for i in $(seq 0 ${CLI_ARGS_POSSIBLE}); do
if [[ "${SECTION[$i]}" != "$prev_section" ]] || [[ -z ${SECTION[0]} ]] ; then
echo >&${out_descriptor}
echo "${SECTION[$i]}:" >&${out_descriptor}
fi
[[ "${SHORT_NAME[$i]}" = "None" ]] && SHORT_NAME[$i]=" "
if [[ "${SHORT_NAME[$i]}" = " " ]]; then
echo -n " "${SHORT_NAME[$i]} >&${out_descriptor}
else
echo -n " -"${SHORT_NAME[$i]}"," >&${out_descriptor}
fi
curr_byte_len=${#FULL_NAME[$i]}
# print space padding
for f in $(seq 0 $(( max_name_len - curr_byte_len + 2 )) ); do
echo -n " " >&${out_descriptor}
done
echo -n " --"${FULL_NAME[$i]} >&${out_descriptor}
echo " "${DESCRIPTION[$i]} >&${out_descriptor}
# print options about this usage/help and additional info in the last iteration
curr_byte_len="help"
curr_byte_len=${#curr_byte_len}
if [[ "$i" -eq "$CLI_ARGS_POSSIBLE" ]]; then
echo -n " -?," >&${out_descriptor}
for f in $(seq 0 $(( max_name_len - curr_byte_len + 2 )) ); do
echo -n " " >&${out_descriptor}
done
echo -n " --help" >&${out_descriptor}
echo " this help" >&${out_descriptor}
fi
prev_section=${SECTION[$i]}
done
# Print example
echo >&${out_descriptor}
echo "Example:" >&${out_descriptor}
echo " PGPASSWORD=mypasswd ./${SCRIPT_NAME} collect -h [ssh_user]@host_to_connect_via_ssh \\"
echo " --username ${USER} --dbname postgres \\"
echo " --project dummy ${BOLD}-e %EPOCH_NUMBER%${RESET}" >&${out_descriptor}
echo >&${out_descriptor}
echo "Comments, ideas, bug reports? https://gitlab.com/postgres-ai/postgres-checkup" >&${out_descriptor}
exit $exit_code
}
#######################################
# Generate json report
# Globals:
# CURRENT_CHECK_FNAME, SCRIPT_DIR, PROJECT,
# HOST, JSON_REPORTS_DIR, TIMESTAMP_DIR,
# TIMESTAMPTZ, MD_REPORTS_DIR
# Arguments:
# input, check_id
# Returns:
# (text) stdout/stderr
#######################################
generate_report_json() {
local input_json="$1"
local check_id="$2"
local check_name="$3"
local epoch="null"
[[ -z ${3+x} ]] && err "function needs 3 arguments"
# insert json object data into template
local template_fname="${SCRIPT_DIR}/resources/templates/report.json"
local tmp_input_json_fname=$(mktemp "${SCRIPT_DIR}"/artifacts/${check_id}_tmp_XXXXXX)
# save function's input as a temporary file
echo "$input_json" > "$tmp_input_json_fname"
# final report file name
local json_output_fname="${JSON_REPORTS_DIR}/${check_id}_${check_name}.json"
# use template or existing file
if [[ -f "$json_output_fname" ]]; then
local json_input_fname="${json_output_fname}"
else
local json_input_fname="${template_fname}"
fi
local tmp_output_json_fname=$(mktemp "${JSON_REPORTS_DIR}"/${check_id}_${check_name}_tmp_XXXXXX)
jq -r \
--argfile Results "${tmp_input_json_fname}" \
--arg CheckId "${check_id}" \
--arg CheckName "${check_name}" \
--arg TimestampTz "${TIMESTAMPTZ}" \
--arg Host "${HOST}" \
--arg Project "${PROJECT}" \
--arg Database "${DBNAME}" \
'.checkId = $CheckId | .name = $CheckName | ."timestamptz" = $TimestampTz | ."project" = $Project | ."database" = $Database | .results += { ($Host): { data: $Results } }' \
"${json_input_fname}" \
> "${tmp_output_json_fname}"
mv "${tmp_output_json_fname}" "${json_output_fname}"
rm "$tmp_input_json_fname"
# extend check for current host with actual 'nodes.json' inside a json report
tmp_output_json_fname=$(mktemp "${JSON_REPORTS_DIR}"/${check_id}_${check_name}_tmp_ex_XXXXXX)
jq --argfile nodes_json "${PROJECT_DIR}/nodes.json" \
'.results.'\"${HOST}\"'."nodes.json" = $nodes_json' \
"${json_output_fname}" \
> "$tmp_output_json_fname"
mv "$tmp_output_json_fname" "${json_output_fname}"
# update json report by attaching 'nodes.json' into top of the report
tmp_output_json_fname=$(mktemp "${JSON_REPORTS_DIR}"/${check_id}_${check_name}_tmp_ex_XXXXXX)
jq --argfile nodes_json "${PROJECT_DIR}/nodes.json" \
'.last_nodes_json = $nodes_json' \
"${json_output_fname}" \
> "$tmp_output_json_fname"
mv "$tmp_output_json_fname" "${json_output_fname}"
msg "JSON report saved at: '${json_output_fname}'"
}
#######################################
# Check is host in recovery mode or not
#
# Do not use this function before 'host_pre_start_checks()'
#
# Globals:
# HOST
# Arguments:
# None
# Returns:
# Integer
#######################################
is_in_recovery() {
local res="$(${CHECK_HOST_CMD} "${_PSQL} -c \"select * from pg_is_in_recovery()\"")"
if [[ "$res" = "f" ]]; then
dbg "host $HOST is 'master'"
return 12
elif [[ "$res" = "t" ]]; then
dbg "host $HOST is 'standby'"
return 0
else
msg "ERROR: Cannot connect to the host: ${HOST}"
exit 1
fi
return 13
}
#######################################
# Check the number of objects in the database:
# return 0 if the database has more than LARGE_DB_ITEMS_COUNT
# (100000) objects, 1 otherwise.
#
# Do not use this function before 'host_pre_start_checks()'
#
# Globals:
# _PSQL, LARGE_DB_ITEMS_COUNT
# Arguments:
# None
# Returns:
# Integer
#######################################
is_large_database() {
local res="$(${CHECK_HOST_CMD} "${_PSQL} -c \"select count(*) from pg_class\"")"
if [[ "$res" -gt $LARGE_DB_ITEMS_COUNT ]]; then
return 0
else
return 1
fi
}
#######################################
# Check binary dependencies
# Globals:
# KERNEL_NAME, OS_NAME, timeout()
# Arguments:
# None
# Returns:
# (text) stdout/stderr
#######################################
check_bin_deps() {
# detect OS
export KERNEL_NAME=$(uname)
if [[ "${KERNEL_NAME}" =~ "Darwin" ]]; then
export OS_NAME="macOS"
dbg "This is macOS"
elif [[ "${KERNEL_NAME}" =~ "Linux" ]]; then
export OS_NAME="Linux"
dbg "This is Linux"
else
export OS_NAME="Unknown"
dbg "Can't detect OS name"
fi
###### Checking the existence of commands #####
# timeout
if ! $(which gtimeout >/dev/null 2>&1) && ! $(which timeout >/dev/null 2>&1); then
err "Can't find the 'timeout' executable. Please install it:"
if [[ "${KERNEL_NAME}" = "Darwin" ]]; then
err "${OS_NAME}: 'brew install coreutils'"
elif [[ "${KERNEL_NAME}" = "Linux" ]]; then
err "Debian/Ubuntu GNU/${OS_NAME}: 'sudo apt-get install coreutils'"
err "RHEL/CentOS GNU/${OS_NAME}: 'sudo yum install coreutils'"
fi
return 1
else
# redefine command (alias won't work inside the script)
if [[ "${KERNEL_NAME}" = "Darwin" ]]; then
timeout() {
gtimeout "$@"
}
fi
fi
# awk
if ! $(which awk >/dev/null 2>&1); then
err "Can't find the 'awk' executable. Please install it:"
if [[ "${KERNEL_NAME}" = "Darwin" ]]; then
err "${OS_NAME}: 'brew install gawk'"
elif [[ "${KERNEL_NAME}" = "Linux" ]]; then
err "Debian/Ubuntu GNU/${OS_NAME}: 'sudo apt-get install gawk'"
err "RHEL/CentOS GNU/${OS_NAME}: 'sudo yum install gawk'"
fi
return 1
fi
# jq
if ! $(which jq >/dev/null 2>&1); then
err "Can't find the 'jq' executable. Please install it:"
if [[ "${KERNEL_NAME}" = "Darwin" ]]; then
err "${OS_NAME}: 'brew install jq'"
elif [[ "${KERNEL_NAME}" = "Linux" ]]; then
err "Debian/Ubuntu GNU/${OS_NAME}: 'sudo apt-get install jq'"
err "RHEL/CentOS GNU/${OS_NAME}: 'sudo yum install jq'"
fi
return 1
fi
# jq version
re="jq([0-9]+.[0-9]+).+"
local jq_version_full=$(jq --version)
local version="" # short form (e.g. '1.11')
local jq_version_num="" # get only first two numbers devided by '.'
if [[ "${jq_version_full}" =~ $re ]]; then
version="${BASH_REMATCH[1]}"
local major=${version%.*}
local minor=${version#*.}
jq_version_num="${major}${minor}"
if [[ $(( go_version_num % 1000 )) -lt "15" ]]; then
err "Unsupported jq version '${jq_version_full}'"
err "Please install jq version >= '1.5'"
return 1
fi
fi
}
#######################################
# Glue all .md file together
# (makes final report)
# Globals:
# PROJECT_DIR, FULL_REPORT_FNAME, EPOCH,
# DBNAME, HOST, MD_REPORTS_DIR
# Arguments:
# None
# Returns:
# Integer
#######################################
glue_md_reports() {
# final report path and name
local out_fname="${MD_REPORTS_DIR}/${FULL_REPORT_FNAME}"
local epoch=$(jq -r '.last_check.epoch' ${PROJECT_DIR}/nodes.json)
local database=$(jq -r '.last_check.database' ${PROJECT_DIR}/nodes.json)
# do not re-generate full report if '--file' is given
[[ "${FILE}" != "None" ]] && return 0
# make header
echo "# PostgreSQL Checkup. Project: '${PROJECT}'. Database: '${database}'" > "${out_fname}"
echo "## Epoch number: '${epoch}'" >> "${out_fname}"
echo "NOTICE: while most reports describe the “current database”, some of them may contain cluster-wide information describing all databases in the cluster." >> "${out_fname}"
echo >> "${out_fname}"
echo "Last modified at: " $(date +'%Y-%m-%d %H:%M:%S %z') >> "${out_fname}"
echo >> "${out_fname}"
tableOfContents=""
content=""
summaryTable="\n---\n### Issues found ###\n\nThe empty lines represent reports for which Conclusions and Recommendations are not yet implemented.\n\n|Report|P1|P2|P3|\n|-----|---|---|---|"
echo "" >> "${out_fname}"
echo "<a name=\"postgres-checkup_top\"> </a>" >> "${out_fname}"
echo "### Table of contents ###" >> "${out_fname}"
#generate table of contents and glue reports together
for cur_report in "${MD_REPORTS_DIR}"/*.md; do
[[ -e "${cur_report}" ]] || continue
[[ "${cur_report}" != "${MD_REPORTS_DIR}/${FULL_REPORT_FNAME}" ]] || continue
title=$(head -n 1 ${cur_report})
title="${title/\#/}"
title="${title/\#/}"
title="${title#"${title%%[![:space:]]*}"}"
title="${title%"${title##*[![:space:]]}"}"
checkId=$(echo $title | cut -c 1-4)
tableOfContents="$tableOfContents\n[$title](#postgres-checkup_$checkId) "
content="$content\n\n\n---\n<a name=\"postgres-checkup_$checkId\"> </a>\n[Table of contents](#postgres-checkup_top)"
report=$(cat "${cur_report}")
content="$content\n$report"
fileCheckId=$checkId
if [[ "$fileCheckId" =~ "K" ]]; then
if [[ "$fileCheckId" != "K003" ]]; then
summaryTable="${summaryTable}\n|[$title](#postgres-checkup_$checkId)||||"
continue
fi
fileCheckId="K000";
fi
jsonFile=$(ls ${JSON_REPORTS_DIR}/${fileCheckId}*.json)
p1=$(jq '.recommendations | [.[]|.Message|startswith("[P1]")] | map(select(. == true)) | length' ${jsonFile} 2>/dev/null \
|| jq 'if .p1 == false then 0 elif .p1 == true then "!" else "" end' ${jsonFile} 2>/dev/null || echo "")
p2=$(jq '.recommendations | [.[]|.Message|startswith("[P2]")] | map(select(. == true)) | length' ${jsonFile} 2>/dev/null \
|| jq 'if .p2 == false then 0 elif .p2 == true then "!" else "" end' ${jsonFile} 2>/dev/null || echo "")
p3=$(jq '.recommendations | [.[]|.Message|startswith("[P3]")] | map(select(. == true)) | length' ${jsonFile} 2>/dev/null \
|| jq 'if .p3 == false then 0 elif .p3 == true then "!" else "" end' ${jsonFile} 2>/dev/null || echo "")
summaryTable="${summaryTable}\n|[$title](#postgres-checkup_$checkId)|${p1//\"/}|${p2//\"/}|${p3//\"/}|"
done
echo -e "$tableOfContents" >> "${out_fname}"
echo -e "$summaryTable\n\n" >> "${out_fname}"
echo -e "$content" >> "${out_fname}"
}
#######################################
# Configure SSH connection
# Globals:
# CHECK_HOST_CMD, SSH_SUPPORT, SSHPORT, PORT
# Arguments:
# (text) host name
# Returns:
# Integer
#######################################
configure_ssh_connection() {
hostname=$1
if [[ "$SSHPORT" == "None" ]]; then
if [[ "$PORT" != "None" ]]; then
SSHPORT=$PORT
else
SSHPORT=$DEFAULT_SSH_PORT
fi
fi
if native_hostname=$(ssh -p ${SSHPORT} -o ConnectTimeout=10 ${hostname} "hostname" 2>/dev/null); then
# ssh to remote host and use local psql (default)
export CHECK_HOST_CMD="ssh ${hostname}"
export SSH_SUPPORT="true"
return 0
else
return 1
fi
}
#######################################
# Configure psql connection
# Globals:
# CHECK_HOST_CMD, SSH_SUPPORT, PGPORT, PORT
# Arguments:
# (text) host name
# Returns:
# Integer
#######################################
configure_psql_connection() {
hostname=$1
if [[ "$PGPORT" == "None" ]]; then
if [[ "$PORT" != "None" ]]; then
PGPORT=$PORT
else
PGPORT=$DEFAULT_PG_PORT
fi
generate_psql_cmd