-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathgenerate_postmortem.sh
executable file
·2805 lines (2381 loc) · 119 KB
/
generate_postmortem.sh
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
#
# Purpose: Collects API Connect logs and packages into an archive.
#
# Authors: Charles Johnson, [email protected]
# Franck Delporte, [email protected]
# Nagarjun Nama Balaji, [email protected]
# Kenny Nguyen, [email protected]
#
#parse passed arguments
NUMERICALVERSION=44
PMCOMMITDATE='Thu Apr 11 04:31:36 UTC 2024'
PMCOMMIT='51fdde0f23c6e63270dedc6d7aa721cb27a8412f'
PMCOMMITURL="https://github.com/ibm-apiconnect/v10-postmortem/blob/$PMCOMMIT/generate_postmortem.sh"
print_postmortem_version(){
echo "Postmortem Version: $NUMERICALVERSION, Date: $PMCOMMITDATE, URL: $PMCOMMITURL"
}
# We want customers to use the latest postmortem scripts wherever possible
warn_if_script_is_not_latest() {
if [[ ${NO_SCRIPT_CHECK:-0} -eq 1 ]]; then
return
fi
local script_name=$1
local script_remote_url=$2
local_script_hash=$(sha256sum "$script_name" | cut -d ' ' -f1)
response=$(curl -s --connect-timeout 5 "$script_remote_url") && rc=$? || rc=$?
# Only give the warning if we know this was a good returned hash
if [[ "$rc" -eq 0 ]]; then
remote_script_hash=$(echo "$response" | sha256sum | cut -d ' ' -f1) || true
if [[ -n "$remote_script_hash" && ${#remote_script_hash} -eq 64 && "$remote_script_hash" != "$local_script_hash" ]]; then
echo "---------------------------------------------------------"
echo "NOTE: There is a newer version of $script_name available. Please download the latest postmortem script from https://github.com/ibm-apiconnect/v10-postmortem so that up-to-date information is gathered."
echo "WARNING: If you don't use the latest $script_name script, IBM support may ask you to download the latest $script_name script and run it again."
echo "---------------------------------------------------------"
fi
fi
}
#Confirm whether oc or kubectl exists and choose which command tool to use based on that
which oc &> /dev/null
if [[ $? -eq 0 ]]; then
KUBECTL="oc"
$KUBECTL whoami
if [[ $? -ne 0 ]]; then
echo "Error: oc whoami failed. This script requires you to be logged in to the server. EXITING..."
exit 1
fi
else
which kubectl &> /dev/null
if [[ $? -ne 0 ]]; then
echo "Unable to locate the command [kubectl] nor [oc] in the path. Either install or add it to the path. EXITING..."
exit 1
fi
KUBECTL="kubectl"
fi
# Check if kubectl-cnp plugin is installed
function is_kubectl_cnp_plugin {
if which kubectl-cnp >/dev/null; then
echo kubectl-cnp plugin found
else
echo -e "kubectl-cnp plugin not found"
read -p "Download and Install kubectl-cnp plugin (y/n)? " yn
case $yn in
[Yy]* )
echo -e "Proceeding..."
echo -e "Executing: curl -sSfL https://github.com/EnterpriseDB/kubectl-cnp/raw/main/install.sh | sudo sh -s -- -b /usr/local/bin"
curl -sSfL \
https://github.com/EnterpriseDB/kubectl-cnp/raw/main/install.sh | \
sudo sh -s -- -b /usr/local/bin
if [[ $? -ne 0 ]]; then
echo "Error installing kubectl-cnp plugin. Exiting..."
exit 1
fi
;;
[Nn]* )
echo -e "Exiting... please install kubectl-cnp plugin and add it to your PATH, see https://www.enterprisedb.com/docs/postgres_for_kubernetes/latest/kubectl-plugin."
exit 1
;;
esac
fi
}
#Check to see if this is an OCP cluster
IS_OCP=false
if $KUBECTL api-resources | grep -q "route.openshift.io"; then
IS_OCP=true
fi
for switch in $@; do
case $switch in
*"-h"*|*"--help"*)
echo -e 'Usage: generate_postmortem.sh {optional: LOG LIMIT}'
echo -e ""
echo -e "Available switches:"
echo -e ""
echo -e "--specific-namespaces: Target only the listed namespaces for the data collection. Example: --specific-namespaces=dev1,dev2,dev3"
echo -e "--extra-namespaces: Extra namespaces separated with commas. Example: --extra-namespaces=dev1,dev2,dev3"
echo -e "--log-limit: Set the number of lines to collect from each pod logs."
echo -e "--no-prompt: Do not prompt to report auto-detected namespaces."
echo -e "--performance-check: Set to run performance checks."
echo -e "--no-history: Do not collect user history."
echo -e ""
echo -e "--ova: Only set if running inside an OVA deployment."
echo -e ""
echo -e "--collect-private-keys: Include "tls.key" members in TLS secrets from targeted namespaces. Due to sensitivity of data, do not use unless requested by support."
echo -e "--collect-crunchy: Collect Crunchy mustgather."
echo -e "--collect-edb: Collect EDB mustgather."
echo -e ""
echo -e "--no-diagnostic: Set to disable all diagnostic data."
echo -e "--no-manager-diagnostic: Set to disable additional manager specific data."
echo -e "--no-gateway-diagnostic: Set to disable additional gateway specific data."
echo -e "--no-portal-diagnostic: Set to disable additional portal specific data."
echo -e "--no-analytics-diagnostic: Set to disable additional analytics specific data."
echo -e ""
echo -e "--debug: Set to enable verbose logging."
echo -e "--no-script-check: Set to disable checking if the postmortem scripts are up to date."
echo -e ""
echo -e "--version: Show postmortem version"
exit 0
;;
*"--debug"*)
set -x
DEBUG_SET=1
;;
*"--ova"*)
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root."
exit 1
fi
IS_OVA=1
NO_PROMPT=1
NAMESPACE_LIST="kube-system"
;;
*"--no-diagnostic"*)
NOT_DIAG_MANAGER=1
NOT_DIAG_GATEWAY=1
NOT_DIAG_PORTAL=1
NOT_DIAG_ANALYTICS=1
;;
*"--no-manager-diagnostic"*)
NOT_DIAG_MANAGER=1
;;
*"--no-gateway-diagnostic"*)
NOT_DIAG_GATEWAY=1
;;
*"--no-portal-diagnostic"*)
NOT_DIAG_PORTAL=1
;;
*"--no-analytics-diagnostic"*)
NOT_DIAG_ANALYTICS=1
;;
*"--log-limit"*)
limit=`echo "${switch}" | cut -d'=' -f2`
if [[ "$limit" =~ ^[0-9]+$ ]]; then
LOG_LIMIT="--tail=${limit}"
fi
;;
*"--specific-namespaces"*)
NO_PROMPT=1
SPECIFIC_NAMESPACES=1
specific_namespaces=`echo "${switch}" | cut -d'=' -f2 | tr ',' ' '`
NAMESPACE_LIST="${specific_namespaces}"
AUTO_DETECT=0
;;
*"--extra-namespaces"*)
NO_PROMPT=1
extra_namespaces=`echo "${switch}" | cut -d'=' -f2 | tr ',' ' '`
NAMESPACE_LIST="kube-system ${extra_namespaces}"
;;
*"--performance-check"*)
PERFORMANCE_CHECK=1
;;
*"--no-history"*)
NO_HISTORY=1
;;
*"--no-prompt"*)
NO_PROMPT=1
;;
*"--no-script-check"*)
NO_SCRIPT_CHECK=1
;;
*"--collect-private-keys"*)
COLLECT_PRIVATE_KEYS=1
;;
*"--collect-crunchy"*)
COLLECT_CRUNCHY=1
;;
*"--collect-edb"*)
COLLECT_EDB=1
is_kubectl_cnp_plugin
;;
*"--version"*)
print_postmortem_version
exit 0
;;
*)
if [[ -z "$DEBUG_SET" ]]; then
set +e
fi
;;
esac
done
echo -e "#\n# WARNING: this script is being deprecated in favor of the apic-mustgather tool."
echo -e "# Please see: https://github.com/ibm-apiconnect/v10-postmortem"
echo -e "#"
#Printing Postmortem Version
print_postmortem_version
echo "using [$KUBECTL] command for cluster cli"
warn_if_script_is_not_latest ${0##*/} "https://raw.githubusercontent.com/ibm-apiconnect/v10-postmortem/master/generate_postmortem.sh"
if [[ -z "$LOG_LIMIT" ]]; then
LOG_LIMIT=""
fi
if [[ -z "$NO_PROMPT" ]]; then
NO_PROMPT=0
fi
if [[ -z "$SPECIFIC_NAMESPACES" ]]; then
SPECIFIC_NAMESPACES=0
fi
#====================================== Confirm pre-reqs and init variables ======================================
#------------------------------- Make sure all necessary commands exists ------------------------------
ARCHIVE_UTILITY=`which zip 2>/dev/null`
if [[ $? -ne 0 ]]; then
ARCHIVE_UTILITY=`which tar 2>/dev/null`
if [[ $? -ne 0 ]]; then
echo "Unable to locate either command [tar] / [zip] in the path. Either install or add it to the path. EXITING..."
exit 1
fi
fi
if [[ $NOT_DIAG_MANAGER -eq 0 ]]; then
EDB_CLUSTER_NAME=$($KUBECTL get cluster --all-namespaces -o=jsonpath='{.items[0].metadata.name}' 2>/dev/null)
if [[ -z "$EDB_CLUSTER_NAME" ]]; then
COLLECT_CRUNCHY=1
else
COLLECT_EDB=1
is_kubectl_cnp_plugin
fi
fi
which apicops &> /dev/null
if [[ $? -eq 0 ]]; then
APICOPS="apicops"
else
if [[ ! -e /tmp/apicops-v10-linux ]]; then
if [[ $NO_PROMPT -eq 0 ]]; then
echo -e "apicops cli not found!"
read -p "Download and Install apicops cli (y/n)? " yn
case $yn in
[Yy]* )
echo -e "Downloading apicops......"
curl -L -o /tmp/apicops-v10-linux https://github.com/ibm-apiconnect/apicops/releases/latest/download/apicops-v10-linux
if [[ ! -e /tmp/apicops-v10-linux ]]; then
echo -e "Warning: Failed to download the apicops cli. Skipping to collect apicops mustgather. Please download the latest release of apicops manually before running the postmortem script. commands: curl -LO https://github.com/ibm-apiconnect/apicops/releases/latest/download/apicops-v10-linux"
else
chmod +x /tmp/apicops-v10-linux
APICOPS="/tmp/apicops-v10-linux"
fi
;;
[Nn]* )
echo -e "Skipping to collect apicops mustgather"
;;
esac
else
echo -e "Skipping to collect apicops mustgather"
fi
else
APICOPS="/tmp/apicops-v10-linux"
fi
fi
#------------------------------------------------------------------------------------------------------
#------------------------------------------ custom functions ------------------------------------------
#compare versions
function version_gte() { test "$1" == "$2" || test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; }
#XML to generate error report
function generateXmlForErrorReport()
{
cat << EOF > $1
<?xml version="1.0" encoding="UTF-8"?>
<!-- ErrorReport Request -->
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Body>
<dp:request xmlns:dp="http://www.datapower.com/schemas/management" domain="default">
<dp:do-action>
<ErrorReport/>
</dp:do-action>
</dp:request>
</env:Body>
</env:Envelope>
EOF
}
function gatherEdbOperatorData() {
$KUBECTL cnp report operator --logs -n ${EDB_OP_NAMESPACE} -f ${SPECIFIC_NS_EDB_OP}/operator-report.zip
for pod in $PG_OP
do
mkdir ${OPERATOR_PODS}/${pod}
$KUBECTL get po ${pod} -o yaml -n ${EDB_OP_NAMESPACE} > ${OPERATOR_PODS}/${pod}/pod.yaml
$KUBECTL describe pod ${pod} -n ${EDB_OP_NAMESPACE} > ${OPERATOR_PODS}/${pod}/describe.txt
$KUBECTL logs ${pod} -n ${EDB_OP_NAMESPACE} > ${OPERATOR_PODS}/${pod}/logs.txt
$KUBECTL logs ${pod} -n ${EDB_OP_NAMESPACE} --previous 2>/dev/null > ${OPERATOR_PODS}/${pod}/previous-logs.txt
done
}
function gatherClusterData() {
$KUBECTL cnp status ${EDB_CLUSTER_NAME} -n ${EDB_CLUSTER_NAMESPACE} > ${CLUSTER}/${EDB_CLUSTER_NAME}/status.txt
$KUBECTL cnp status ${EDB_CLUSTER_NAME} --verbose -n ${EDB_CLUSTER_NAMESPACE} > ${CLUSTER}/${EDB_CLUSTER_NAME}/status-verbose.txt
$KUBECTL get cluster ${EDB_CLUSTER_NAME} -n ${EDB_CLUSTER_NAMESPACE} > ${CLUSTER}/${EDB_CLUSTER_NAME}/info.txt
$KUBECTL get cluster ${EDB_CLUSTER_NAME} -o yaml -n ${EDB_CLUSTER_NAMESPACE} > ${CLUSTER}/${EDB_CLUSTER_NAME}/cluster.yaml
$KUBECTL describe cluster ${EDB_CLUSTER_NAME} -n ${EDB_CLUSTER_NAMESPACE} > ${CLUSTER}/${EDB_CLUSTER_NAME}/describe.txt
}
function gatherEDBPodData() {
$KUBECTL cnp report cluster ${EDB_CLUSTER_NAME} --logs -n ${EDB_CLUSTER_NAMESPACE} -f ${SPECIFIC_NS_CLUSTER}/cluster-report.zip
$KUBECTL get pod -l k8s.enterprisedb.io/cluster=${EDB_CLUSTER_NAME} -L role -n ${EDB_CLUSTER_NAMESPACE} > ${CLUSTER_PODS}/pods.txt
for pod in ${EDB_POD_NAMES}; do
mkdir ${CLUSTER_PODS}/${pod}
$KUBECTL get po ${pod} -o yaml -n ${EDB_CLUSTER_NAMESPACE} > ${CLUSTER_PODS}/${pod}/pod.yaml
$KUBECTL describe pod ${pod} -n ${EDB_CLUSTER_NAMESPACE} > ${CLUSTER_PODS}/${pod}/describe.txt
$KUBECTL logs ${pod} -n ${EDB_CLUSTER_NAMESPACE} > ${CLUSTER_PODS}/${pod}/logs.txt
$KUBECTL logs ${pod} -n ${EDB_CLUSTER_NAMESPACE} --previous 2>/dev/null > ${CLUSTER_PODS}/${pod}/previous-logs.txt
$KUBECTL logs ${pod} -n ${EDB_CLUSTER_NAMESPACE} | jq -r '.record | select(.error_severity == "FATAL")' > ${CLUSTER_PODS}/${pod}/logs-fatal.txt
done
}
function gatherEDBBackupData() {
$KUBECTL get backups -n ${EDB_CLUSTER_NAMESPACE} -o=jsonpath='{.items[?(@.spec.cluster.name=="'${EDB_CLUSTER_NAME}'")]}' -o wide > ${CLUSTER_BACKUPS}/${EDB_CLUSTER_NAME}/backups.txt
for backup in ${EDB_BACKUP_NAMES}; do
mkdir ${CLUSTER_BACKUPS}/${EDB_CLUSTER_NAME}/${backup}
$KUBECTL get backups ${backup} -o yaml -n ${EDB_CLUSTER_NAMESPACE} > ${CLUSTER_BACKUPS}/${EDB_CLUSTER_NAME}/${backup}/backup.yaml
$KUBECTL describe backups ${backup} -n ${EDB_CLUSTER_NAMESPACE} > ${CLUSTER_BACKUPS}/${EDB_CLUSTER_NAME}/${backup}/describe.txt
done
}
function gatherEDBScheduledBackupData() {
$KUBECTL -n ${EDB_CLUSTER_NAMESPACE} get scheduledbackups -o=jsonpath='{.items[?(@.spec.cluster.name=="'${EDB_CLUSTER_NAME}'")]}' -o wide > ${CLUSTER_SCHEDULED_BACKUPS}/${EDB_CLUSTER_NAME}/scheduledbackups.txt
for scheduledbackup in ${EDB_SCHEDULED_BACKUP_NAMES}; do
mkdir ${CLUSTER_SCHEDULED_BACKUPS}/${EDB_CLUSTER_NAME}/${scheduledbackup}
$KUBECTL -n ${EDB_CLUSTER_NAMESPACE} get scheduledbackups ${scheduledbackup} -o yaml > ${CLUSTER_SCHEDULED_BACKUPS}/${EDB_CLUSTER_NAME}/${scheduledbackup}/backup.yaml
$KUBECTL -n ${EDB_CLUSTER_NAMESPACE} describe scheduledbackups ${scheduledbackup} > ${CLUSTER_SCHEDULED_BACKUPS}/${EDB_CLUSTER_NAME}/${scheduledbackup}/describe.txt
done
}
function collectEDB {
EDB_OP_NAMESPACE=''
PG_OP=''
ARCHITECTURE=$($KUBECTL get nodes -o jsonpath='{.items[0].status.nodeInfo.architecture}')
if [ "$ARCHITECTURE" = 's390x' ]; then
EDB_OP_NAMESPACE='ibm-common-services'
PG_OP=$($KUBECTL get po -n ${EDB_OP_NAMESPACE} -o=custom-columns=NAME:.metadata.name | grep postgresql-operator-controller-manager)
else
EDB_OP_NAMESPACE=$EDB_CLUSTER_NAMESPACE
PG_OP=$($KUBECTL get po -n ${EDB_OP_NAMESPACE} -o=custom-columns=NAME:.metadata.name | grep -e edb-operator -e postgresql-operator-controller-manager)
fi
MGMT_CR_NAME=$($KUBECTL get mgmt -n ${EDB_CLUSTER_NAMESPACE} -o=jsonpath='{.items[0].metadata.name}' 2>/dev/null)
EDB_CLUSTER_NAME=$($KUBECTL get cluster -n ${EDB_CLUSTER_NAMESPACE} -o=jsonpath='{.items[?(@.metadata.ownerReferences[0].name=="'${MGMT_CR_NAME}'")].metadata.name}' 2>/dev/null)
EDB_POD_NAMES=$($KUBECTL get pod -l k8s.enterprisedb.io/cluster=${EDB_CLUSTER_NAME} -L role -n ${EDB_CLUSTER_NAMESPACE} -o=custom-columns=NAME:.metadata.name --no-headers)
EDB_BACKUP_NAMES=$($KUBECTL get backups -o=jsonpath='{.items[?(@.spec.cluster.name=="'${EDB_CLUSTER_NAME}'")]}' -L role -n ${EDB_CLUSTER_NAMESPACE} -o=custom-columns=NAME:.metadata.name --no-headers)
EDB_SCHEDULED_BACKUP_NAMES=$($KUBECTL get scheduledBackups -o=jsonpath='{.items[?(@.spec.cluster.name=="'${EDB_CLUSTER_NAME}'")]}' -n ${EDB_CLUSTER_NAMESPACE} -o=custom-columns=NAME:.metadata.name --no-headers)
K8S_DATA="${TEMP_PATH}/kubernetes"
K8S_NAMESPACES="${K8S_DATA}/namespaces"
K8S_NAMESPACES_SPECIFIC="${K8S_NAMESPACES}/${EDB_OP_NAMESPACE}"
K8S_NAMESPACES_EDB_DATA="${K8S_NAMESPACES_SPECIFIC}/edb"
K8S_NAMESPACES_POD_DATA="${K8S_NAMESPACES_SPECIFIC}/pods"
K8S_NAMESPACES_POD_DESCRIBE_DATA="${K8S_NAMESPACES_POD_DATA}/describe"
K8S_NAMESPACES_POD_LOG_DATA="${K8S_NAMESPACES_POD_DATA}/logs"
NS=${LOG_PATH}/namespaces
SPECIFIC_NS_EDB_OP=${NS}/${EDB_OP_NAMESPACE}
SPECIFIC_NS_CLUSTER=${NS}/${EDB_CLUSTER_NAMESPACE}
OPERATOR_PODS=${SPECIFIC_NS_EDB_OP}/pods
CLUSTER=${SPECIFIC_NS_CLUSTER}/cluster
CLUSTER_PODS=${SPECIFIC_NS_CLUSTER}/pods
CLUSTER_BACKUPS=${SPECIFIC_NS_CLUSTER}/backups
CLUSTER_SCHEDULED_BACKUPS=${SPECIFIC_NS_CLUSTER}/scheduledbackups
mkdir ${NS}
mkdir ${SPECIFIC_NS_EDB_OP}
mkdir -p ${SPECIFIC_NS_CLUSTER}
mkdir ${OPERATOR_PODS}
mkdir ${CLUSTER}
mkdir -p ${CLUSTER}/${EDB_CLUSTER_NAME}
mkdir -p ${CLUSTER_PODS}
mkdir ${CLUSTER_BACKUPS}
mkdir -p ${CLUSTER_BACKUPS}/${EDB_CLUSTER_NAME}
mkdir ${CLUSTER_SCHEDULED_BACKUPS}
mkdir -p ${CLUSTER_SCHEDULED_BACKUPS}/${EDB_CLUSTER_NAME}
if [[ -n "$PG_OP" ]]; then
echo "Found EDB operator pod $PG_OP"
gatherEdbOperatorData
fi
if [[ -n "$EDB_CLUSTER_NAME" ]]; then
echo "Found EDB Cluster $EDB_CLUSTER_NAME"
gatherClusterData
fi
if [[ -n "$EDB_POD_NAMES" ]]; then
gatherEDBPodData
fi
if [[ -n "$EDB_BACKUP_NAMES" ]]; then
gatherEDBBackupData
fi
if [[ -n "$EDB_SCHEDULED_BACKUP_NAMES" ]]; then
gatherEDBScheduledBackupData
fi
}
function collectCrunchy {
python3 - << EOF -n $NAMESPACE -l 7 -c $KUBECTL -o $K8S_NAMESPACES_CRUNCHY_DATA &> "${K8S_NAMESPACES_CRUNCHY_DATA}/crunchy-collect.log"
"""
Copyright 2017 - 2021 Crunchy Data
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Crunchy kubernetes support dump script
Original Author: Pramodh Mereddy <[email protected]>
Description:
This script collects kubernetes objects, logs and other metadata from
the objects corresponding to Crunchydata container solution
NOTE: secrets are data are NOT collected
Pre-requisites:
1. Valid login session to your kubernetes cluster
2. kubectl or oc CLI in your PATH
Example:
./crunchy_gather_k8s_support_dump.py -n pgdb -o $HOME/dumps/crunchy/pgdb
Arguments:
-n: namespace or project name
-o: directory to create the support dump in
-l: number of pg_log files to save
"""
import argparse
import logging
import os
import subprocess
import sys
import tarfile
import posixpath
import time
from collections import OrderedDict
if sys.version_info[0] < 3:
print("Python 3 or a more recent version is required.")
sys.exit()
# Local Script Version
# Update for each release
__version__ = "v1.0.2"
class Options(): # pylint: disable=too-few-public-methods
"""
class for globals
"""
def __init__(self, dest_dir, namespace, kube_cli, pg_logs_count):
self.dest_dir = dest_dir
self.namespace = namespace
self.kube_cli = kube_cli
self.pg_logs_count = pg_logs_count
self.delete_dir = False
self.output_dir = ""
self.dir_name = (f"crunchy_{time.strftime('%Y-%m-%d-%H%M%S')}")
OPT = Options("", "", "kubectl", 2)
MAX_ARCHIVE_EMAIL_SIZE = 25*1024*1024 # 25 MB filesize limit
logger = logging.getLogger("crunchy_support") # pylint: disable=locally-disabled, invalid-name
API_RESOURCES = [
"pods",
"ReplicaSet",
"StatefulSet",
"Deployment",
"Services",
"Routes",
"Ingress",
"pvc",
"configmap",
"networkpolicies",
"postgresclusters",
"pgreplicas",
"pgclusters",
"pgpolicies",
"pgtasks"
]
CONTAINER_COMMANDS = {
'collect': [],
'exporter': [],
'database': ["patronictl list", "patronictl history"],
'pgbadger': [],
'pgbackrest': [],
'replication-cert-copy': [],
'all': ["ps aux --width 500"]
}
def run():
"""
Main function to collect support dump
"""
logger.info("Saving support dump files in %s", OPT.output_dir)
collect_current_time()
collect_script_version()
collect_kube_version()
collect_node_info()
collect_namespace_info()
collect_events()
collect_pvc_list()
collect_configmap_list()
collect_pods_describe()
collect_api_resources()
collect_pg_logs()
collect_pods_logs()
collect_pg_pod_details()
archive_files()
def collect_current_time():
"""
function to collect the time which the Support Dump was
captured, so that Events and other relative-time items could
be easily correlated
"""
cmd = "date"
logger.debug("collecting current timestamp info: %s", cmd)
collect_helper(cmd, file_name="timestamp.info", resource_name="timestamp info")
def collect_kube_version():
"""
function to gather kubernetes version information
"""
cmd = OPT.kube_cli + " version "
logger.debug("collecting kube version info: %s", cmd)
collect_helper(cmd, file_name="k8s-version.info", resource_name="Platform Version info")
def collect_script_version():
"""
function to gather script version, allow us to determine
if the tool is out of date
"""
cmd = "echo Support Dump Tool: " + __version__
logger.debug("collecting support dump tool version info: %s", cmd)
collect_helper(cmd, file_name="dumptool-version.info", resource_name="Support Dump Tool version info")
def collect_node_info():
"""
function to gather kubernetes node information
"""
cmd = OPT.kube_cli + " get nodes -o wide "
logger.debug("collecting node info: %s", cmd)
collect_helper(cmd, file_name="nodes.info", resource_name="Node info")
def collect_namespace_info():
"""
function to gather kubernetes namespace information
"""
if OPT.kube_cli == "oc":
cmd = OPT.kube_cli + " describe project " + OPT.namespace
else:
cmd = OPT.kube_cli + " get namespace -o yaml " + OPT.namespace
logger.debug("collecting namespace info: %s", cmd)
collect_helper(cmd, file_name="namespace.yml",
resource_name="namespace-info")
def collect_pvc_list():
"""
function to gather kubernetes PVC information
"""
cmd = OPT.kube_cli + " get pvc {}".format(get_namespace_argument())
collect_helper(cmd, file_name="pvc.list", resource_name="pvc-list")
def collect_pvc_details():
"""
function to gather kubernetes PVC details
"""
cmd = OPT.kube_cli + " get pvc -o yaml {}".format(get_namespace_argument())
collect_helper(cmd, file_name="pvc.details", resource_name="pvc-details")
def collect_configmap_list():
"""
function to gather configmap list
"""
cmd = OPT.kube_cli + " get configmap {}".format(get_namespace_argument())
collect_helper(cmd, file_name="configmap.list",
resource_name="configmap-list")
def collect_configmap_details():
"""
function to gather configmap details
"""
cmd = (OPT.kube_cli +
" get configmap -o yaml {}".format(get_namespace_argument()))
collect_helper(cmd, file_name="configmap.details",
resource_name="configmap-details")
def collect_events():
"""
function to gather k8s events
"""
cmd = OPT.kube_cli + " get events {}".format(get_namespace_argument())
collect_helper(cmd=cmd, file_name="events", resource_name="k8s events")
def collect_api_resources():
"""
function to gather details on different k8s resources
"""
logger.info("Collecting API resources:")
resources_out = OrderedDict()
for resource in API_RESOURCES:
if OPT.kube_cli == "kubectl" and resource == "Routes":
continue
output = run_kube_get(resource)
if output:
resources_out[resource] = run_kube_get(resource)
logger.info(" + %s", resource)
for entry, out in resources_out.items():
with open(posixpath.join(OPT.output_dir, f"{entry}.yml"), "wb") as file_pointer:
file_pointer.write(out)
def collect_pods_describe():
"""
function to gather k8s describe on the namespace pods
"""
cmd = OPT.kube_cli + " describe pods {}".format(get_namespace_argument())
collect_helper(cmd=cmd, file_name="describe-pods", resource_name="pod describe")
def collect_pods_logs():
"""
Collects all the pods logs from a given namespace
"""
logger.info("Collecting pod logs:")
logs_dir = posixpath.join(OPT.output_dir, "pod_logs")
os.makedirs(logs_dir)
pods = get_pods_v4() + get_op_pod()
if not pods:
logger.debug("No Pods found, trying PGO V5 methods...")
pods = get_pods_v5() + get_op_pod()
if not pods:
logger.warning("Could not get pods list - skipping automatic pod logs collection")
logger.error("########")
logger.error("#### You will need to collect these pod logs manually ####")
logger.error("########")
logger.warning("»HINT: Was the correct namespace used?")
logger.debug("This error sometimes happens when labels have been modified")
return
logger.info("Found and processing the following containers:")
for pod in pods:
containers = get_containers(pod)
if not containers:
logger.warning("Could not get pods list")
logger.warning("»HINT: Were the labels modified?")
logger.warning("»HINT: Was the correct namespace used?")
logger.error("########")
logger.error("#### You will need to collect these pod logs manually ####")
logger.error("########")
logger.debug("This error sometimes happens when labels have been modified")
return
for cont in containers:
container = cont.rstrip()
cmd = (OPT.kube_cli + " logs {} {} -c {}".
format(get_namespace_argument(), pod, container))
with open("{}/{}_{}.log".format(logs_dir, pod,
container), "wb") as file_pointer:
handle = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
while True:
line = handle.stdout.readline()
if line:
file_pointer.write(line)
else:
break
logger.info(" + pod:%s, container:%s", pod, container)
def collect_pg_pod_details():
"""
Collects PG pods details
"""
logger.info("Collecting PG pod details:")
logs_dir = posixpath.join(OPT.output_dir, "pg_pod_details")
os.makedirs(logs_dir)
pods = get_pg_pods_v4()
if not pods:
logger.debug("No Pods found, trying PGO V5 methods...")
pods = get_pg_pods_v5()
if not pods:
logger.warning("Could not get pods list - skipping PG pod details collection")
logger.error("########")
logger.error("#### You will need to collect Postgres pod logs manually ####")
logger.error("########")
logger.warning("»HINT: Was the correct namespace used?")
logger.debug("This error sometimes happens when labels have been modified")
return
logger.info("Found and processing the following containers:")
for pod in pods:
containers = get_containers(pod)
for cont in containers:
container = cont.rstrip()
with open("{}/{}_{}.log".format(logs_dir, pod,
container), "ab+") as file_pointer:
for command in (CONTAINER_COMMANDS['all'] +
CONTAINER_COMMANDS[container]):
cmd = (OPT.kube_cli + " exec -it {} -c {} {} -- "
"/bin/bash -c '{}'"
.format(get_namespace_argument(),
container, pod, command))
handle = subprocess.Popen(cmd, shell=True,
stdout=file_pointer.fileno(),
stderr=file_pointer.fileno())
try:
out=handle.communicate(timeout=60)
except subprocess.TimeoutExpired:
logger.warning("The output for " + cmd + " was not captured due to timeout")
handle.kill()
logger.info(" + pod:%s, container:%s", pod, container)
def collect_pg_logs():
"""
Collects PG database server logs
"""
logger.info("Collecting last %s PG logs "
"(may take a while)", OPT.pg_logs_count)
logs_dir = posixpath.join(OPT.output_dir, "pg_logs")
os.makedirs(logs_dir)
pods = get_pg_pods_v4()
if not pods:
logger.debug("No Pods found, trying PGO V5 methods...")
pods = get_pg_pods_v5()
if not pods:
logger.warning("Could not get pods list - skipping pods logs collection")
logger.error("########")
logger.error("#### You will need to collect these Postgres logs manually ####")
logger.error("########")
logger.warning("»HINT: Was the correct namespace used?")
logger.debug("This error sometimes happens when labels have been modified")
return
logger.info("Found and processing the following containers:")
for pod in pods:
tgt_file = "{}/{}".format(logs_dir, pod)
os.makedirs(tgt_file)
# print("OPT.pg_logs_count: ", OPT.pg_logs_count)
cmd = (OPT.kube_cli +
" exec -it {} -c database {} -- /bin/bash -c"
" 'ls -1dt /pgdata/*/pglogs/* | head -{}'"
.format(get_namespace_argument(), pod, OPT.pg_logs_count))
# print(cmd)
handle = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
while True:
line = handle.stdout.readline()
if line:
cmd = (OPT.kube_cli +
" cp -c database {} {}:{} {}"
.format(get_namespace_argument(),
pod, line.rstrip().decode('UTF-8'),
tgt_file + line.rstrip().decode('UTF-8')))
handle2 = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
handle2.wait()
else:
break
logger.info(" + pod:%s", pod)
def sizeof_fmt(num, suffix="B"):
"""
Formats the file size in a human-readable format
Probably overkill to go to Zi range, but reusable
"""
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1024.0
return f"{num:.1f}Yi{suffix}"
def archive_files():
"""
Create an archive and compress it
"""
archive_file_size = 0
file_name = OPT.output_dir + ".tar.gz"
with tarfile.open(file_name, "w|gz") as tar:
tar.add(OPT.output_dir, arcname=OPT.dir_name)
logger.info("")
# Let user choose to delete the files manually
if OPT.delete_dir:
rtn, out = run_shell_command(f"rm -rf {OPT.output_dir}")
if rtn:
logger.warning('Failed to delete directory after archiving: %s',
out)
logger.info("support dump files saved at %s", OPT.output_dir)
try:
archive_file_size = os.stat(file_name).st_size
logger.info("┌──────────────────────────────────────────────────────────────────-")
logger.info("│ Archive file saved to: %s ", file_name)
if archive_file_size > MAX_ARCHIVE_EMAIL_SIZE:
logger.info("│ Archive file (%d) may be too big to email.",
sizeof_fmt(archive_file_size))
logger.info("│ Please request file share link by"
" emailing [email protected]")
else:
logger.info("│ Archive file size: %s ", sizeof_fmt(archive_file_size))
logger.info("│ Email the support dump to [email protected]")
logger.info("│ or attach as a email reply to your existing Support Ticket")
logger.info("└──────────────────────────────────────────────────────────────────-")
except (OSError, ValueError) as e: # pylint: disable=invalid-name
logger.warning("Archive file size: NA --- %s", e)
def get_pods_v4():
"""
Returns list of pods names, all pods
"""
cmd = (OPT.kube_cli + " get pod {} -lvendor=crunchydata "
"-o=custom-columns=NAME:.metadata.name "
"--no-headers".format(get_namespace_argument()))
return_code, out = run_shell_command(cmd)
if return_code == 0:
return out.decode("utf-8").split("\n")[:-1]
logger.warning("Failed to get pods: %s", out)
return None
def get_pods_v5():
"""
Returns list of pods names, all pods
"""
cmd = (OPT.kube_cli + " get pod {} "
"-lpostgres-operator.crunchydata.com/cluster "
"-o=custom-columns=NAME:.metadata.name "
"--no-headers".format(get_namespace_argument()))
return_code, out = run_shell_command(cmd)
if return_code == 0:
return out.decode("utf-8").split("\n")[:-1]
logger.warning("Failed to get pods: %s", out)
return None
def get_op_pod():
"""
Returns just the operator pod
"""
cmd = (OPT.kube_cli + " get pod {} "
"-lapp.kubernetes.io/name=postgres-operator "
"-o=custom-columns=NAME:.metadata.name "
"--no-headers".format(get_namespace_argument()))
return_code, out = run_shell_command(cmd)
if return_code == 0:
return out.decode("utf-8").split("\n")[:-1]
logger.warning("Failed to get pods: %s", out)
return None
def get_pg_pods_v4():
"""
Returns list of pods names, only DB pods
"""
cmd = (OPT.kube_cli + " get pod {} "
"-lpgo-pg-database=true,vendor=crunchydata "
"-o=custom-columns=NAME:.metadata.name "
"--no-headers".format(get_namespace_argument()))
return_code, out = run_shell_command(cmd)
if return_code == 0:
return out.decode("utf-8").split("\n")[:-1]
logger.warning("Failed to get pods: %s", out)
return None
def get_pg_pods_v5():
"""
Returns list of pods names, only DB pods
"""
cmd = (OPT.kube_cli + " get pod {} "
"-lpostgres-operator.crunchydata.com/cluster "
"-o=custom-columns=NAME:.metadata.name "
"--no-headers".format(get_namespace_argument()))
return_code, out = run_shell_command(cmd)
if return_code == 0:
return out.decode("utf-8").split("\n")[:-1]
logger.warning("Failed to get pods: %s", out)
return None
def get_containers(pod_name):
"""
Returns list of containers in a pod
"""
cmd = (OPT.kube_cli + " get pods {} {} --no-headers "
"-o=custom-columns=CONTAINERS:.spec.containers[*].name"
.format(get_namespace_argument(), pod_name))
return_code, out = run_shell_command(cmd)
if return_code == 0:
return out.decode("utf-8").split(",")
logger.warning("Failed to get pods: %s", out)
return None
def get_namespace_argument():
"""
Returns namespace option for kube cli
"""
if OPT.namespace:
return "-n {}".format(OPT.namespace)
return ""
def collect_helper(cmd, file_name, resource_name):
"""
helper function to gather data
"""
return_code, out = run_shell_command(cmd)
if return_code:
logger.warning("Error when running %s: %s", cmd, out.decode('utf-8').rstrip())
return
path = posixpath.join(OPT.output_dir, file_name)
with open(path, "wb") as file_pointer:
file_pointer.write(out)
logger.info("Collected %s", resource_name)
def run_shell_command(cmd, log_error=True):
"""
Returns a tuple of the shell exit code, output
"""
try:
output = subprocess.check_output(
cmd,
shell=True,
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as ex: