-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrds_psql_patch.sh
1006 lines (796 loc) · 41.2 KB
/
rds_psql_patch.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: To upgrade RDS databases (RDS-PostgreSQL only)
#
# Usage: ./rds_psql_patch.sh [db-instance-id] [next-engine-version] [run-pre-check]
# ./rds_psql_patch.sh [rds-psql-patch-test-1] [15.6] [PREUPGRADE|UPGRADE]
#
# PREUPGRADE = Run pre-requisite tasks, and do NOT run upgrade tasks
# UPGRADE = Do not run pre-requisite tasks, but run upgrade tasks
#
# Note: Review this document [https://docs.aws.amazon.com/AmazonRDS/latest/PostgreSQLReleaseNotes/postgresql-versions.html]
# for appropriate minor or major supported verion (a.k.a appropirate upgrade path)
#
# Example Usage:
# nohup ./rds_psql_patch.sh rds-psql-patch-test-1 15.6 PREUPGRADE >logs/pre-upgrade-rds-psql-patch-test-1-`date +'%Y%m%d-%H-%M-%S'`.out 2>&1 &
# nohup ./rds_psql_patch.sh rds-psql-patch-test-1 15.6 UPGRADE >logs/upgrade-rds-psql-patch-test-1-`date +'%Y%m%d-%H-%M-%S'`.out 2>&1 &
#
# Prerequisites:
# 1. AWS Resources Required:
# - EC2 instance for running this script
# - IAM profile attached to EC2 instance with necessary permissions
# * create_rds_psql_patch_iam_policy_role_cfn.yaml can be used to create a policy and role.
# ** Modify resource names appropriately
# * Attach this IAM role to ec2 instance.
# - RDS instance(s) with:
# * VPC configuration
# * Subnet group(s)
# * Security group(s)
# * Parameter group
# * Secrets Manager secret
# * "create_rds_psql_instance_cfn.yaml" can be used (this creates DB Parameter group and RDS instance)
# ** Modify resource names appropriately
# - AWS Secrets Manager secret attached to each RDS instance
# - S3 bucket for upgrade logs
# - SNS topic for notifications
#
# 2. Network Configuration:
# - Database security group must allow inbound traffic from EC2 instance
#
# 3. Required Tools:
# - AWS CLI
# - PostgreSQL client utilities
# - jq for JSON processing
#
# 4. Update environment variables "manual" section if/as needed (optional)
#
# Functions:
# wait_till_available - funtion to check DBInstance status
# create_param_group - function to create parameter group
# db_upgrade - function to upgrade DBInstance
# db_modify_logs - function to add DB logs to CloudWatch
# db_pending_maint - function to check pending maintenance status
# get_rds_creds - function to retrieve DB creds from secret manager
# copy_logs_to_s3 - copy upgrade files to s3 bucket for future reference
# db_snapshot - function to take DB snapshot/backup if required
# run_psql_command - run analyze/vacuum freeze commands
# run_psql_drop_repl_slot - check and drop replication slot in PSQL if exists (applies to MAJOR version upgrade only)
# check_upgrade_type - function to determine if upgrade/patching path is MINOR or MAJOR
# update_extensions - function to update PostgreSQL extensions
# send_email - send email
# get_db_info - get database related info into local variables
# check_rds_upgrade_version - check if the next-engine-version is valid for the current rds-postgresql instance version
#
##-------------------------------------------------------------------------------------
# Environment Variables - Input parameters #
current_db_instance_id=${1}
next_engine_version=$(echo "${2}" | bc)
run_pre_upg_tasks=${3}
run_pre_upg_tasks="${run_pre_upg_tasks^^}" # convert to upper case #
LOGS_DIR="./logs"
##-------------------------------------------------------------------------------------
# Environment Variables - Software binaries - Manual #
AWS_CLI=$(which aws)
PSQL_BIN=$(which psql)
# Environment Variables - Misc. - Manual #
db_snapshot_required="Y" # set this to Y if manual snapshot is required #
db_parameter_modify="N" # set this to Y if security and replication related parameters needs to be enabled; if not set it to N. Used in create_param_group function #
DATE_TIME=$(date +'%Y%m%d-%H-%M-%S')
##-------------------------------------------------------------------------------------
# check number of input arguments #
if [ ! $# -eq 3 ]; then
echo -e "\nERROR: Incorrect syntax; Three (3) parameters expected."
echo -e "\nUsage: ./rds_psql_patch.sh [db-instance-id] [next-engine-version] [PREUPGRADE|UPGRADE]"
echo -e "Example:"
echo -e " ./rds_psql_patch.sh rds-psql-patch-test-1 15.6 PREUPGRADE"
echo -e " ./rds_psql_patch.sh rds-psql-patch-test-1 15.6 UPGRADE\n"
exit 1
fi
# validate 3rd argument/parameter #
if [ ! "${run_pre_upg_tasks}" = "PREUPGRADE" ] && [ ! "${run_pre_upg_tasks}" = "UPGRADE" ]; then
echo -e "\nERROR: Invalid 3rd parameter. Expected value PREUPGRADE|UPGRADE."
echo -e "\nUsage: ./rds_psql_patch.sh [db-instance-id] [next-engine-version] [PREUPGRADE|UPGRADE]"
echo -e "Example:"
echo -e " ./rds_psql_patch.sh rds-psql-patch-test-1 15.6 PREUPGRADE"
echo -e " ./rds_psql_patch.sh rds-psql-patch-test-1 15.6 UPGRADE\n"
exit 1
fi
# Display input parameters for verification
echo ""
echo "INFO: Input parameter 1: $current_db_instance_id"
echo "INFO: Input parameter 2: $next_engine_version"
echo "INFO: Input parameter 3: $run_pre_upg_tasks"
echo ""
if [ "${run_pre_upg_tasks}" = "PREUPGRADE" ]; then
EMAIL_SUBJECT="RDS PostgreSQL DB Pre-Upgrade Tasks"
else
EMAIL_SUBJECT="RDS PostgreSQL DB Upgrade"
fi
echo -e "\nBEGIN - ${EMAIL_SUBJECT} - $(date)"
##-------------------------------------------------------------------------------------
# functions #
##-------------------------------------------------------------------------------------
# funtion to check DBInstance status #
function wait_till_available() {
echo ""
# wait for modification to start
sleep 90s
current_db_status=$( ${AWS_CLI} rds describe-db-instances --db-instance-identifier ${current_db_instance_id} --query 'DBInstances[0].[DBInstanceStatus]' --output text )
while [ "${current_db_status}" != "available" ]
do
# alternative is to synchronously wait for instance to become available
# echo "Waiting for ${current_db_instance_id} to enter 'available' state..."
# aws rds wait db-instance-available --profile $profile --db-instance-identifier $current_db_instance_id
# exit_status="$?"
current_db_status=$( ${AWS_CLI} rds describe-db-instances --db-instance-identifier ${current_db_instance_id} --query 'DBInstances[0].[DBInstanceStatus]' --output text )
#echo ".%s"
echo "INFO: Wait-DBUpgrade Status = ${current_db_status} - $(date)"
sleep 60s
done
echo ""
}
##-------------------------------------------------------------------------------------
# function to create parameter group #
function create_param_group() {
echo -e "\nINFO: Execute create_param_group function...\n"
return_value=""
# generate new parameter group name #
db_param_group_name="rds-param-group-${current_engine_type}${next_engine_version_family}-${current_db_instance_id}"
echo -e "\ndb_param_group_name = $db_param_group_name\n"
#echo "${AWS_CLI} rds describe-db-parameter-groups --db-parameter-group-name ${db_param_group_name} 2>/dev/null"
${AWS_CLI} rds describe-db-parameter-groups --db-parameter-group-name ${db_param_group_name} 2>/dev/null
return_value="$?"
echo ""
echo "DBParamGroupCheck ReturnValue = ${return_value}"
# get current db parameter group name #
current_db_param_group=$( ${AWS_CLI} rds describe-db-instances --db-instance-identifier ${current_db_instance_id} --query 'DBInstances[*].DBParameterGroups[*].DBParameterGroupName' --output text )
echo "current_db_param_group = $current_db_param_group"
# if parameter group does NOT exists, then create a new one #
if [ "${return_value}" = "0" ]; then
echo "INFO: DB Parameter Group Exists already. No need to create a new DB parameter group."
else
echo "INFO: Creating new parameter group..."
# create new db parameter group #
${AWS_CLI} rds create-db-parameter-group \
--db-parameter-group-name "${db_param_group_name}" \
--db-parameter-group-family "${current_engine_type}${next_engine_version_family}" \
--description "${current_engine_type}${next_engine_version_family} DB parameter group for ${current_db_instance_id} database" \
--tags '[{"Key": "Name","Value": "'"$db_param_group_name"'"}]'
return_value="$?"
echo ""
echo "CreateDBParamGroup ReturnValue = ${return_value}"
if [ "${return_value}" != "0" ]; then
exit 1
fi
if [ "${db_parameter_modify}" = "Y" ]; then
echo -e "\nINFO: Modify DB parameter group...\n"
# Define parameters to modify #
# only 20 parameters can be modified at a time; hence splitting into two groups #
# These are security best practices related; also include enabling logical replication parameters as well #
# These parameters can be removed or updated as needed #
local params=(
"ParameterName=authentication_timeout,ParameterValue=300,ApplyMethod=immediate"
"ParameterName=backslash_quote,ParameterValue=safe_encoding,ApplyMethod=immediate"
"ParameterName=client_min_messages,ParameterValue=notice,ApplyMethod=immediate"
"ParameterName=escape_string_warning,ParameterValue=1,ApplyMethod=immediate"
"ParameterName=log_connections,ParameterValue=1,ApplyMethod=immediate"
"ParameterName=log_disconnections,ParameterValue=1,ApplyMethod=immediate"
"ParameterName=log_duration,ParameterValue=1,ApplyMethod=immediate"
"ParameterName=log_min_duration_statement,ParameterValue=1000,ApplyMethod=immediate"
"ParameterName=log_min_error_statement,ParameterValue=info,ApplyMethod=immediate"
"ParameterName=log_min_messages,ParameterValue=info,ApplyMethod=immediate"
"ParameterName=log_statement,ParameterValue=all,ApplyMethod=immediate"
"ParameterName=rds.logical_replication,ParameterValue=1,ApplyMethod=pending-reboot"
"ParameterName=shared_preload_libraries,ParameterValue=pg_stat_statements,ApplyMethod=pending-reboot"
"ParameterName=standard_conforming_strings,ParameterValue=1,ApplyMethod=immediate"
"ParameterName=tcp_keepalives_count,ParameterValue=0,ApplyMethod=immediate"
)
local params2=(
"ParameterName=tcp_keepalives_idle,ParameterValue=0,ApplyMethod=immediate"
"ParameterName=tcp_keepalives_interval,ParameterValue=0,ApplyMethod=immediate"
"ParameterName=rds.force_ssl,ParameterValue=0,ApplyMethod=immediate"
"ParameterName=rds.log_retention_period,ParameterValue=4320,ApplyMethod=immediate"
"ParameterName=wal_receiver_timeout,ParameterValue=0,ApplyMethod=immediate"
"ParameterName=wal_sender_timeout,ParameterValue=0,ApplyMethod=immediate"
"ParameterName=idle_in_transaction_session_timeout,ParameterValue=0,ApplyMethod=immediate"
"ParameterName=checkpoint_warning,ParameterValue=0,ApplyMethod=immediate"
"ParameterName=statement_timeout,ParameterValue=0,ApplyMethod=immediate"
)
# modify 1st set of parameters #
#echo -e "\nParmGroup statement = ${AWS_CLI} rds modify-db-parameter-group --db-parameter-group-name "${db_param_group_name}" --parameters "${params[@]}" \n"
${AWS_CLI} rds modify-db-parameter-group --db-parameter-group-name "${db_param_group_name}" --parameters "${params[@]}"
return_value="$?"
echo ""
echo "DBParamGroupUpdate1 ReturnValue = ${return_value}"
if [ "${return_value}" != "0" ]; then
exit 1
fi
# modify 2nd set of parameters #
#echo -e "\nParmGroup statement2 = ${AWS_CLI} rds modify-db-parameter-group --db-parameter-group-name "${db_param_group_name}" --parameters "${params2[@]}" \n"
${AWS_CLI} rds modify-db-parameter-group --db-parameter-group-name "${db_param_group_name}" --parameters "${params2[@]}"
return_value="$?"
echo ""
echo "DBParamGroupUpdate2 ReturnValue = ${return_value}"
if [ "${return_value}" != "0" ]; then
exit 1
fi
fi
fi
echo ""
}
##-------------------------------------------------------------------------------------
# function to upgrade DBInstance #
function db_upgrade() {
echo -e "\nINFO: Execute db_upgrade function...\n"
return_value=""
# backup current DB config #
${AWS_CLI} rds describe-db-instances --db-instance-identifier ${current_db_instance_id} >${LOGS_DIR}/${current_db_instance_id}/db_current_config_backup_${current_engine_type}${current_engine_version_family}-${DATE_TIME}.txt
echo -e "\n${AWS_CLI} rds modify-db-instance \
--db-instance-identifier ${current_db_instance_id} \
--db-parameter-group-name ${db_param_group_name} \
--engine-version ${next_engine_version} \
--allow-major-version-upgrade \
--apply-immediately\n"
${AWS_CLI} rds modify-db-instance \
--db-instance-identifier ${current_db_instance_id} \
--db-parameter-group-name ${db_param_group_name} \
--engine-version ${next_engine_version} \
--allow-major-version-upgrade \
--apply-immediately
return_value="$?"
echo "DBUpgrade ReturnValue = ${return_value}"
if [ "${return_value}" != "0" ]; then
exit 1
fi
# wait until DB instance status is available #
wait_till_available
echo ""
}
##-------------------------------------------------------------------------------------
# function to add DB logs to CloudWatch #
function db_modify_logs() {
echo -e "\nINFO: Execute db_modify_logs function...\n"
return_value=""
${AWS_CLI} rds modify-db-instance \
--db-instance-identifier ${current_db_instance_id} \
--cloudwatch-logs-export-configuration '{"EnableLogTypes":["postgresql","upgrade"]}' \
--apply-immediately
return_value="$?"
echo "DBModifyLogs ReturnValue = ${return_value}"
if [ "${return_value}" != "0" ]; then
exit 1
fi
echo ""
}
##-------------------------------------------------------------------------------------
# function to check pending maintenance status #
function db_pending_maint() {
echo -e "\nINFO: Execute db_pending_maint function...\n"
local return_value=""
# Get DB instance ARN
db_instance_arn=$( ${AWS_CLI} rds describe-db-instances --db-instance-identifier ${current_db_instance_id} --query 'DBInstances[].{DBInstanceArn:DBInstanceArn}' --output text )
echo "db_instance_arn = $db_instance_arn"
# Check pending maintenance tasks
pending_maintenance_tasks=$( ${AWS_CLI} rds describe-pending-maintenance-actions --resource-identifier ${db_instance_arn} --output text )
echo "PendingMaintTasks = ${pending_maintenance_tasks}"
if [ "${pending_maintenance_tasks}" != "" ]; then
# Perform OS related maintenance only - system-update
echo -e "\nINFO: PendingMaintApply - BEGIN - $(date)"
# Capture both stdout and stderr
maintenance_output=$( ${AWS_CLI} rds apply-pending-maintenance-action \
--resource-identifier ${db_instance_arn} \
--apply-action system-update \
--opt-in-type immediate 2>&1 )
return_value=$?
# Check if the error message contains the expected error
if echo "${maintenance_output}" | grep -q "There is no pending system-update action"; then
echo "INFO: No pending system updates available - this is expected"
return_value="0"
else
echo "${maintenance_output}"
fi
echo "PendingMaintApply ReturnValue = ${return_value}"
if [ "${return_value}" = "0" ] || [ "${return_value}" = "254" ]; then
echo -e "\nINFO: No pending maintenance."
else
exit 1
fi
# wait until DB instance status is available
wait_till_available
echo "INFO: PendingMaintApply - END - $(date)"
echo ""
fi
}
##-------------------------------------------------------------------------------------
# function to retrieve DB creds from secret manager #
function get_rds_creds() {
echo -e "\nINFO: Execute get_rds_creds function...\n"
SECRET_VALUE=$(${AWS_CLI} secretsmanager get-secret-value --secret-id ${current_db_secret_arn} --query SecretString --output text)
db_user2=$(echo $SECRET_VALUE | jq -r '.password')
#echo "db_user2 = ${db_user2}"
export PGPASSWORD="${db_user2}"
}
##-------------------------------------------------------------------------------------
# run analyze in PSQL database #
function run_psql_command() {
echo -e "\nINFO: Execute run_psql_command function...\n"
# Create log file path
local log_file="${LOGS_DIR}/${current_db_instance_id}/run_db_task_${1,,}-${DATE_TIME}.log"
# ${LOGS_DIR}/${current_db_instance_id}/${current_db_instance_id}-[analyze|freeze|unfreeze]-${DATE_TIME}.log
# Ensure log directory exists
mkdir -p "${LOGS_DIR}/${current_db_instance_id}"
# Initialize command status
local cmd_status=0
local cmd=""
{
echo "================================================================"
echo "PostgreSQL Command Execution Log - Started at $(date)"
echo "================================================================"
echo "Command Type: ${1}"
echo "Database Instance: ${current_db_instance_id}"
echo "Database Name: ${db_name}"
echo "Log File: ${log_file}"
echo "----------------------------------------------------------------"
# Get DB credentials
echo "INFO: Retrieving database credentials..."
get_rds_creds
# Validate DB credentials
if [[ -z "${db_user1}" || -z "${db_user2}" ]]; then
echo "WARNING: Database credentials NOT found. Command ${1} will NOT run."
echo "----------------------------------------------------------------"
return 1
fi
echo "INFO: Database credentials retrieved successfully."
# Test database connection
echo "INFO: Testing database connection..."
if ! "${PSQL_BIN}" -U "${db_user1}" -h "${db_endpoint}" -p "${db_port}" \
-d "${db_name}" -c '\q' >/dev/null 2>&1
then
echo "ERROR: Failed to connect to database"
echo "----------------------------------------------------------------"
return 1
fi
echo "INFO: Database connection successful"
# Execute command based on input parameter
case "${1}" in
"ANALYZE")
echo -e "\nINFO: Executing ANALYZE VERBOSE command..."
cmd="ANALYZE VERBOSE"
;;
"FREEZE")
echo -e "\nINFO: Executing VACUUM FREEZE VERBOSE command..."
cmd="VACUUM FREEZE VERBOSE"
;;
"UNFREEZE")
echo -e "\nINFO: Executing VACUUM VERBOSE command..."
cmd="VACUUM VERBOSE"
;;
*)
echo "ERROR: Invalid command type: ${1}"
echo "Valid options are: ANALYZE, FREEZE, UNFREEZE"
echo "----------------------------------------------------------------"
return 1
;;
esac
# Log and execute the command
echo "Executing command: ${PSQL_BIN} -h ${db_endpoint} -p ${db_port} -d ${db_name} -a -c '${cmd}'"
echo "----------------------------------------"
echo "Command execution started at: $(date)"
# Execute PostgreSQL command
if ! "${PSQL_BIN}" -U "${db_user1}" -h "${db_endpoint}" -p "${db_port}" \
-d "${db_name}" -a -c "\timing on" -c "${cmd}" 2>&1
then
cmd_status=$?
echo "Command failed with status: ${cmd_status}"
fi
echo "Command execution completed at: $(date)"
echo "----------------------------------------"
# Check command execution status
if [ ${cmd_status} -eq 0 ]; then
echo "SUCCESS: ${1} command completed successfully"
else
echo "ERROR: ${1} command failed with exit status ${cmd_status}"
fi
echo "----------------------------------------------------------------"
echo "Operation completed at: $(date)"
echo "================================================================"
echo ""
} 2>&1 | tee "${log_file}"
return ${cmd_status}
}
##-------------------------------------------------------------------------------------
# drop replication slot in PSQL if exists (applies to MAJOR version upgrade only) #
function run_psql_drop_repl_slot() {
echo -e "\nINFO: Execute run_psql_drop_repl_slot function...\n"
# Create log file path
local log_file="${LOGS_DIR}/${current_db_instance_id}/drop_replication_slot_${DATE_TIME}.log"
# Ensure log directory exists
mkdir -p "${LOGS_DIR}/${current_db_instance_id}"
{
echo "================================================================"
echo "Replication Slot Drop Operation Log - Started at $(date)"
echo "================================================================"
echo "Database Instance: ${current_db_instance_id}"
echo "Log File: ${log_file}"
echo "----------------------------------------------------------------"
# Get DB credentials from secret manager
echo "INFO: Retrieving database credentials..."
get_rds_creds
# Validate DB credentials
if [[ -z "${db_user1}" || -z "${db_user2}" ]]; then
echo "ERROR: Database credentials NOT found."
echo "ERROR: MAJOR version upgrade will NOT run if there are one or more replication slots."
echo "----------------------------------------------------------------"
return 1
fi
echo "INFO: Database credentials retrieved successfully."
# Check for existing replication slots
echo "INFO: Checking for existing replication slots..."
repl_slot_count=$(${PSQL_BIN} -U "${db_user1}" -h "${db_endpoint}" -d "${db_name}" -AXqtc "SELECT COUNT(*) cnt FROM pg_replication_slots" 2>&1)
if [ $? -ne 0 ]; then
echo "ERROR: Failed to query replication slots:"
echo "${repl_slot_count}"
return 1
fi
echo "INFO: Current replication slot count = ${repl_slot_count}"
# Process replication slots if they exist
if [ "${repl_slot_count}" -gt 0 ]; then
echo "INFO: Found ${repl_slot_count} replication slot(s). Processing..."
# Log current replication slots
echo "INFO: Capturing current replication slot details..."
echo "Current replication slots:"
echo "----------------------------------------"
${PSQL_BIN} -U "${db_user1}" -h "${db_endpoint}" -d "${db_name}" \
-c "SELECT slot_name, plugin, slot_type, database, active, xmin FROM pg_replication_slots"
echo "----------------------------------------"
# Drop replication slots
echo "INFO: Dropping replication slots..."
drop_result=$(${PSQL_BIN} -U "${db_user1}" -h "${db_endpoint}" -d "${db_name}" \
-c "SELECT pg_drop_replication_slot(slot_name) FROM pg_replication_slots WHERE slot_name IN (SELECT slot_name FROM pg_replication_slots)" 2>&1)
if [ $? -ne 0 ]; then
echo "ERROR: Failed to drop replication slots:"
echo "${drop_result}"
return 1
fi
echo "Drop operation result:"
echo "----------------------------------------"
echo "${drop_result}"
echo "----------------------------------------"
# Verify slots were dropped
echo "INFO: Verifying replication slots after drop operation..."
echo "Remaining replication slots:"
echo "----------------------------------------"
${PSQL_BIN} -U "${db_user1}" -h "${db_endpoint}" -d "${db_name}" \
-c "SELECT slot_name, plugin, slot_type, database, active, xmin FROM pg_replication_slots"
echo "----------------------------------------"
# Final count verification
final_count=$(${PSQL_BIN} -U "${db_user1}" -h "${db_endpoint}" -d "${db_name}" -AXqtc "SELECT COUNT(*) cnt FROM pg_replication_slots")
if [ $? -ne 0 ]; then
echo "ERROR: Failed to get final replication slot count"
return 1
fi
echo "INFO: Final replication slot count = ${final_count}"
if [ "${final_count}" -eq 0 ]; then
echo "SUCCESS: All replication slots were successfully dropped."
else
echo "WARNING: ${final_count} replication slots still remain."
fi
else
echo "INFO: No replication slots found. No action needed."
fi
echo "----------------------------------------------------------------"
echo "Operation completed at: $(date)"
echo "================================================================"
echo ""
} 2>&1 | tee "${log_file}"
return 0
}
##-------------------------------------------------------------------------------------
# copy upgrade files to s3 bucket for future reference #
function copy_logs_to_s3() {
if [ -n "${S3_BUCKET_PATCH_LOGS}" ]; then
echo -e "\nINFO: Execute copy_logs_to_s3 function...\n"
# LOGS_DIR='rds/rds_upgrade'
# s3_url_complete="s3://${s3_bucket_name}/${s3_folder_prefix}-postgresql/
# aws s3 sync rds_upgrade/ s3://rds-patch-test-s3/rds_upgrade/
echo -e "\nINFO: Copy log files to S3"
${AWS_CLI} s3 sync "${LOGS_DIR}/" "s3://${S3_BUCKET_PATCH_LOGS}/"
echo ""
# S3 logs directory #
S3_LOGS_DIR="s3://${S3_BUCKET_PATCH_LOGS}/${current_db_instance_id}/"
echo -e "\nS3_LOGS_DIR = ${S3_LOGS_DIR} \n"
fi
}
##-------------------------------------------------------------------------------------
# function to take DB snapshot/backup if required #
function db_snapshot() {
echo -e "\nINFO: Execute db_snapshot function...\n"
if [ "${db_snapshot_required}" = "Y" ]; then
db_snapshot_name="${current_db_instance_id}-backup-pre-${UPGRADE_SCOPE}-upgrade-${next_engine_version}-${DATE_TIME}"
#db_snapshot_name=$( echo ${db_snapshot_name:1} | tr '.' '-' )
db_snapshot_name=$( echo "${db_snapshot_name//./-}" )
echo ""
echo "INFO: DBSnapshot [ ${db_snapshot_name} ] - $(date)"
${AWS_CLI} rds create-db-snapshot \
--db-instance-identifier ${current_db_instance_id} \
--db-snapshot-identifier ${db_snapshot_name}
return_value=$?
if [ "${return_value}" = "254" ]; then
echo -e "\nERROR: DB Backup Failed.\n"
exit 1
fi
# wait until DB instance status is available #
wait_till_available
#sleep 90
else
echo ""
echo "INFO: Manual DBSnapshot NOT required for Major version upgrade - $(date)"
fi
}
##-------------------------------------------------------------------------------------
# function to send email #
function send_email() {
if [ -n "${SNS_TOPIC_ARN_EMAIL}" ]; then
echo -e "\nINFO: Execute send_email function...\n"
${AWS_CLI} sns publish \
--topic-arn ${SNS_TOPIC_ARN_EMAIL} \
--message "Please check logfile(s) in S3 bucket: ${S3_LOGS_DIR}" \
--subject "${EMAIL_SUBJECT} [${current_db_instance_id}] - Completed"
fi
}
##-------------------------------------------------------------------------------------
# function to check if the next-engine-version is valid for the current rds-postgresql instance version #
# Usage example: check_rds_upgrade_version "rds-psql-patch-instance-1" "16.6"
check_rds_upgrade_version() {
local instance_id="$1"
local target_version="$2"
echo -e "\nINFO: Checking if version ${target_version} is a valid upgrade target for ${instance_id}..."
is_valid=$(aws rds describe-db-engine-versions \
--engine postgres \
--engine-version $(aws rds describe-db-instances \
--db-instance-identifier "$instance_id" \
--query 'DBInstances[0].EngineVersion' \
--output text) \
--query 'DBEngineVersions[0].ValidUpgradeTarget[*].EngineVersion' \
--output text | grep -q "$target_version" && echo "true" || echo "false")
if [ "$is_valid" = "false" ]; then
echo "INFO: Please check the available upgrade versions and try again"
echo -e "\nERROR: Version ${target_version} is not a valid upgrade target for instance ${instance_id} \n"
return 1
fi
echo -e "\nINFO: Version ${target_version} is a valid upgrade target \n"
return 0
}
##-------------------------------------------------------------------------------------
# function to determine if upgrade/patching path is MINOR or MAJOR #
function check_upgrade_type() {
echo -e "\nINFO: Checking upgrade type..."
# Extract major version numbers (family)
current_engine_version_family=$(echo "$current_engine_version" | cut -d. -f1)
next_engine_version_family=$(echo "$next_engine_version" | cut -d. -f1)
echo "Current version: $current_engine_version (family: $current_engine_version_family)"
echo "Target version: $next_engine_version (family: $next_engine_version_family)"
# Compare versions directly without version_to_number function
if [ "$next_engine_version_family" -gt "$current_engine_version_family" ]; then
UPGRADE_SCOPE="major"
echo -e "\nINFO: Major version upgrade required (family $current_engine_version_family -> $next_engine_version_family)"
return 0
fi
# Compare full versions for minor upgrade check
current_engine_version=$(echo "$current_engine_version" | tr -d '.')
next_engine_version=$(echo "$next_engine_version" | tr -d '.')
if [ "$current_engine_version" -eq "$next_engine_version" ]; then
echo -e "\nINFO: Current and target versions are identical. No upgrade required."
exit 0
elif [ "$current_engine_version" -gt "$next_engine_version" ]; then
echo -e "\nINFO: Current version is newer than target. No upgrade required."
exit 0
else
UPGRADE_SCOPE="minor"
echo -e "\nINFO: Minor version upgrade required"
echo "INFO: DB Parameter Group remains unchanged"
db_param_group_name=${current_db_param_group}
return 0
fi
}
##-------------------------------------------------------------------------------------
# function to update PostgreSQL extensions
function update_extensions() {
echo -e "\nINFO: Execute update_extensions function...\n"
# Create log file path
local log_file="${LOGS_DIR}/${current_db_instance_id}/update_db_extensions_${DATE_TIME}.log"
# Ensure log directory exists
mkdir -p "${LOGS_DIR}/${current_db_instance_id}"
# Start logging
{
echo "================================================================"
echo "Execute update DB extensions Log - Started at $(date)"
echo "================================================================"
echo "Database Instance: ${current_db_instance_id}"
echo "Log File: ${log_file}"
echo "----------------------------------------------------------------"
echo -e "\nINFO: Execute update_extensions function..."
echo -e "INFO: Started at $(date)"
# get DB creds from secret manager #
get_rds_creds
# Check if DB credentials exist
if [[ -z "${db_user1}" || -z "${db_user2}" ]]; then
echo "ERROR: Database credentials not found in secret manager"
return 1
fi
# Connect to the PostgreSQL database
echo "INFO: Testing database connection..."
if ! ${PSQL_BIN} -U "${db_user1}" -h "${db_endpoint}" -p "${db_port}" -d "${db_name}" -c '\q' >/dev/null 2>&1; then
echo "ERROR: Failed to connect to the PostgreSQL database."
return 1
fi
echo "INFO: Database connection successful"
# Update extensions using a PL/pgSQL anonymous code block
echo -e "\nINFO: Starting extension updates..."
${PSQL_BIN} -U "${db_user1}" -h "${db_endpoint}" -p "${db_port}" -d "${db_name}" <<EOF
\timing on
SELECT current_timestamp AS "Start Time";
DO \$\$
DECLARE
rec RECORD;
newest_version TEXT;
extensions_updated BOOLEAN := FALSE;
BEGIN
FOR rec IN
SELECT extname, extversion, (
SELECT version newest_version
FROM pg_available_extension_versions
WHERE name = extname
ORDER BY newest_version DESC
LIMIT 1
) AS newest_version
FROM pg_extension
LOOP
IF rec.newest_version IS NOT NULL THEN
EXECUTE 'ALTER EXTENSION ' || quote_ident(rec.extname) || ' UPDATE TO ' || quote_literal(rec.newest_version);
RAISE NOTICE 'Updated extension % to version %', rec.extname, rec.newest_version;
extensions_updated := TRUE;
END IF;
END LOOP;
IF NOT extensions_updated THEN
RAISE NOTICE 'No extensions were updated.';
END IF;
END\$\$;
SELECT current_timestamp AS "End Time";
EOF
if [ $? -ne 0 ]; then
echo "ERROR: Failed to update extensions"
return 1
fi
echo -e "\nINFO: Extension update process completed at $(date)"
echo "INFO: Log file location: ${log_file}"
echo "----------------------------------------------------------------"
echo "Operation completed at: $(date)"
echo "================================================================"
echo ""
} 2>&1 | tee "${log_file}"
return 0
}
##-------------------------------------------------------------------------------------
## get database info #
## get current engine type and engine versison #
function get_db_info() {
## Run the AWS CLI command and store the output
instance_info=$( ${AWS_CLI} rds describe-db-instances --db-instance-identifier ${current_db_instance_id} --output json )
# Parse the output and extract the required properties
db_name=$(echo $instance_info | jq -r '.DBInstances[0].DBName')
db_endpoint=$(echo $instance_info | jq -r '.DBInstances[0].Endpoint.Address')
db_port=$(echo $instance_info | jq -r '.DBInstances[0].Endpoint.Port')
db_user1=$(echo $instance_info | jq -r '.DBInstances[0].MasterUsername') # master account #
current_db_status=$(echo $instance_info | jq -r '.DBInstances[0].DBInstanceStatus')
current_engine_type=$(echo $instance_info | jq -r '.DBInstances[0].Engine')
current_engine_version=$(echo $instance_info | jq -r '.DBInstances[0].EngineVersion')
current_engine_version_family=$(echo $instance_info | jq -r '.DBInstances[0].EngineVersion | split(".")[0:2] | join(".")')
current_engine_version_family=$(echo "${current_engine_version_family}" | cut -d. -f1)
current_db_param_group=$(echo $instance_info | jq -r '.DBInstances[0].DBParameterGroups[0].DBParameterGroupName')
current_db_secret_arn=$(echo $instance_info | jq -r '.DBInstances[0].MasterUserSecret.SecretArn')
echo -e "\nINFO: Upgrade/Patching steps begin...\n"
echo "current_db_instance_id = $current_db_instance_id"
echo "current_engine_type = $current_engine_type"
echo "current_engine_version = $current_engine_version"
echo "current_engine_version_family = $current_engine_version_family"
echo "current_db_status = $current_db_status"
echo "current_db_param_group = $current_db_param_group"
echo "db_snapshot_required = $db_snapshot_required"
echo "db_parameter_modify = $db_parameter_modify"
echo "run_pre_upg_tasks = $run_pre_upg_tasks"
echo "db_user1 = ${db_user1}"
echo "db_name = ${db_name}"
echo "db_endpoint = ${db_endpoint}"
echo "db_port = ${db_port}"
echo "current_db_secret_arn = ${current_db_secret_arn}"
echo "S3_BUCKET_PATCH_LOGS = ${S3_BUCKET_PATCH_LOGS}"
echo "SNS_TOPIC_ARN_EMAIL = ${SNS_TOPIC_ARN_EMAIL}"
}
##-------------------------------------------------------------------------------------
echo ""
##-------------------------------------------------------------------------------------
##------------------------EXECUTE RDS-PostgreSQL UPGRADE/PATCHING TASKS----------------
##-------------------------------------------------------------------------------------
# run upgrade only when db status is available and there are no pending maintenace tasks #
current_db_status=$( ${AWS_CLI} rds describe-db-instances --db-instance-identifier ${current_db_instance_id} --query 'DBInstances[0].[DBInstanceStatus]' --output text )
echo "InitialDBStatus = ${current_db_status}"
if [ "${current_db_status}" != "available" ]; then
echo -e "\nERROR: Invalid DB-Instance-ID or DBInstance status is NOT AVAILABLE. Upgrade can not proceed.\n"
exit 1
fi
##-------------------------------------------------------------------------------------
# mkdir for logs #
mkdir -p ${LOGS_DIR}/${current_db_instance_id}
##-------------------------------------------------------------------------------------
## Call function to get database info #
get_db_info
##-------------------------------------------------------------------------------------
# Check db engine type and version to create a new db paramerer group #
# DBEngine = postgres #
if [ "${current_engine_type}" = "postgres" ]; then
# call function to check if the next-engine-version is valid for the current rds-postgresql instance version #
check_rds_upgrade_version "${current_db_instance_id}" "${next_engine_version}"
if [ $? -ne 0 ]; then
#echo -e "\nERROR: Invalid next engine version provided. Upgrade can not proceed.\n"
exit 1
fi
# call function to check if upgrade/patching path is MINOR or MAJOR #
check_upgrade_type
### Run PreReq tasks one or few hours prior to the DB patching/upgrade #
## Take DB snapshot
## Run Freeze
## Create DB parameter group if major version upgrade
if [ "${run_pre_upg_tasks}" = "PREUPGRADE" ]; then
if [ "${UPGRADE_SCOPE}" = "major" ]; then
echo -e "\nUPGRADE_SCOPE = ${UPGRADE_SCOPE}\n"
create_param_group
fi
# call function to take DB snapshot/backup #
db_snapshot
#call function to run UnFreeze in database #
run_psql_command "FREEZE"
else # run_pre_upg_tasks = UPG; perform upgrade/patching tasks
echo "INFO: DB Parameter Group Exists already. No need to create a new DB parameter group."
#UPGRADE_SCOPE="minor"
db_param_group_name=${current_db_param_group}
# take DB snapshot for MINOR version upgrade only; for MAJOR version, snapshot is taken automatically/default #
if [ "${UPGRADE_SCOPE}" = "minor" ]; then
echo -e "\nUPGRADE_SCOPE = ${UPGRADE_SCOPE}\n"
db_snapshot
fi
# call function to check/drop replication slots - only for MAJOR version upgrade #
if [ "${UPGRADE_SCOPE}" = "major" ]; then
# call function to create parameter group
# it is ok if this was run during PRE-REQUISITE stage (1 or few hours head of actuals upgradde)
create_param_group
echo -e "\nUPGRADE_SCOPE = ${UPGRADE_SCOPE}\n"
run_psql_drop_repl_slot
fi
## below are common tasks that apply to major/minor version upgrade ##
# call function to add DB logs to CloudWatch if not already #
db_modify_logs
# run pending-maintenance task and also DB upgrade #
db_pending_maint
# call function to run DB upgrade #
db_upgrade
# call function to update PostgreSQL extensions
update_extensions
# call function to run ANALYZE in database #
run_psql_command "ANALYZE"
# call function to run UnFreeze (vacuum) in database #
run_psql_command "UNFREEZE"
fi
else # current_engine_type != postgres
echo -e "\nERROR: Invalid DBInstance-ID or DBEngine is NOT PostgreSQL. Please check DBInstance-ID.\n"
fi
##-------------------------------------------------------------------------------------
# copy logs to s3 #
# PSQSL database upgrade log file is available in CloudWatch and also will be avaibale in Splunk.
copy_logs_to_s3