-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathfunctions
More file actions
1742 lines (1464 loc) · 55.3 KB
/
functions
File metadata and controls
1742 lines (1464 loc) · 55.3 KB
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
# set root repo relatively to a test dir
ROOT_REPO=${ROOT_REPO:-$(realpath ../../..)}
CERT_MANAGER_VER="1.20.0"
CHAOS_MESH_VER="2.5.1"
BUSYBOX_VER="1.36"
test_name=$(basename "$(pwd)")
source "${ROOT_REPO}/e2e-tests/vars.sh"
if oc get projects 2>/dev/null; then
OPENSHIFT=4
fi
init_temp_dir() {
rm -rf "$TEMP_DIR"
mkdir -p "$TEMP_DIR"
}
create_namespace() {
local namespace=$1
if [[ $OPENSHIFT ]]; then
set -o pipefail
if [[ $OPERATOR_NS ]] && (oc get project "$OPERATOR_NS" -o json >/dev/null 2>&1 | jq -r '.metadata.name' >/dev/null 2>&1); then
oc delete --grace-period=0 --force=true project "$namespace" && sleep 120 || :
else
oc delete project "$namespace" && sleep 40 || :
fi
wait_for_delete "project/$namespace"
oc new-project "$namespace"
oc project "$namespace"
oc adm policy add-scc-to-user hostaccess -z default || :
else
kubectl delete namespace $namespace --ignore-not-found || :
kubectl wait --for=delete namespace "$namespace" || :
kubectl create namespace $namespace
fi
}
check_operator_panic() {
local operator_pod=$(get_operator_pod)
local panic_log
panic_log=$(kubectl logs -n "${OPERATOR_NS:-$NAMESPACE}" "$operator_pod" -c operator | grep -A 100 "Observed a panic" || true)
if [ -n "$panic_log" ]; then
echo "Detected panic in operator:"
echo "$panic_log"
exit 1
fi
}
deploy_operator() {
local cw_prefix=""
destroy_operator
if [[ $OPERATOR_NS ]]; then
create_namespace $OPERATOR_NS
cw_prefix="cw-"
fi
kubectl -n "${OPERATOR_NS:-$NAMESPACE}" apply --server-side --force-conflicts -f "${DEPLOY_DIR}/crd.yaml"
kubectl -n "${OPERATOR_NS:-$NAMESPACE}" apply --server-side --force-conflicts -f "${DEPLOY_DIR}/${cw_prefix}rbac.yaml"
local disable_telemetry=true
if [ "${test_name}" == "telemetry-transfer" ]; then
disable_telemetry=false
fi
yq eval '.spec.template.spec.containers[0].image = "'${IMAGE}'"' "${DEPLOY_DIR}/${cw_prefix}operator.yaml" \
| yq eval '(.spec.template.spec.containers[] | select(.name=="operator") | .env[] | select(.name=="DISABLE_TELEMETRY") | .value) = "'${disable_telemetry}'"' - \
| yq eval '(.spec.template.spec.containers[] | select(.name=="operator") | .env[] | select(.name=="LOG_LEVEL") | .value) = "DEBUG"' - \
| yq eval '(.spec.template.spec.containers[] | select(.name=="operator") | .env[] | select(.name=="PGO_FEATURE_GATES") | .value) = "'${PGO_FEATURE_GATES}'"' - \
| kubectl -n "${OPERATOR_NS:-$NAMESPACE}" apply -f -
}
update_operator() {
local cw_prefix=""
if [[ $OPERATOR_NS ]]; then
cw_prefix="cw-"
fi
kubectl -n "${OPERATOR_NS:-$NAMESPACE}" apply --server-side --force-conflicts -f "${DEPLOY_DIR}/crd.yaml"
kubectl -n "${OPERATOR_NS:-$NAMESPACE}" apply --server-side --force-conflicts -f "${DEPLOY_DIR}/${cw_prefix}rbac.yaml"
local disable_telemetry=true
if [ "${test_name}" == "telemetry-transfer" ]; then
disable_telemetry=false
fi
kubectl -n "${OPERATOR_NS:-$NAMESPACE}" patch deployment percona-postgresql-operator -p \
'{"spec":{"template":{"spec":{"containers":[{"name":"operator","image":"'${IMAGE}'"}]}}}}'
}
deploy_operator_gh() {
local git_tag="$1"
local cw_prefix=""
destroy_operator
if [[ $OPERATOR_NS ]]; then
create_namespace $OPERATOR_NS
cw_prefix="cw-"
fi
kubectl -n "${OPERATOR_NS:-$NAMESPACE}" apply --server-side --force-conflicts -f "https://raw.githubusercontent.com/percona/percona-postgresql-operator/${git_tag}/deploy/crd.yaml"
kubectl -n "${OPERATOR_NS:-$NAMESPACE}" apply --server-side --force-conflicts -f "https://raw.githubusercontent.com/percona/percona-postgresql-operator/${git_tag}/deploy/${cw_prefix}rbac.yaml"
curl -s "https://raw.githubusercontent.com/percona/percona-postgresql-operator/${git_tag}/deploy/${cw_prefix}operator.yaml" >"${TEMP_DIR}/${cw_prefix}operator_${git_tag}.yaml"
local docker_hub_org=$(echo "$IMAGE" | $sed -E 's|(.*/)?([^/]+)/[^/]+(:.*)?|\2|')
yq eval '.spec.template.spec.containers[0].image = "'${REGISTRY_NAME_FULL}''$docker_hub_org'/percona-postgresql-operator:'${git_tag#v}'"' \
"${TEMP_DIR}/${cw_prefix}operator_${git_tag}.yaml" \
| kubectl -n "${OPERATOR_NS:-$NAMESPACE}" apply -f -
}
remove_all_finalizers() {
resource_types=("pg-restore" "pg-backup" "pg")
for resource in "${resource_types[@]}"; do
echo "removing all finalizers for $resource resources"
kubectl -n "${NAMESPACE}" get "$resource" -o json | jq '.items[] | .metadata.name' -r | while IFS= read -r name; do
kubectl -n "${NAMESPACE}" delete "$resource" "$name" --wait=0
if [[ $(kubectl -n "${NAMESPACE}" get "$resource" "$name" -o yaml | yq '.metadata.finalizers | length') == "0" ]]; then
continue
fi
kubectl -n "${NAMESPACE}" patch "$resource" "$name" --type=json -p='[{"op": "remove", "path": "/metadata/finalizers"}]'
done
done
}
wait_for_ready_containers() {
local pod_prefix="$1"
local target_count="$2"
local namespace="${NAMESPACE}"
local max_wait_seconds=300
local check_interval=5
local elapsed_time=0
if [[ -z $pod_prefix || -z $target_count || -z $namespace ]]; then
echo "Error: Missing arguments." >&2
echo "Usage: wait_for_ready_containers <pod_name_prefix> <target_ready_count> <namespace>" >&2
return 1
fi
echo "Waiting for pods starting with '$pod_prefix' in namespace '$namespace' to have $target_count ready containers (Max ${max_wait_seconds}s)..."
while [[ $elapsed_time -lt $max_wait_seconds ]]; do
local target_pods
# Get pods that match the prefix AND are running
target_pods=$(kubectl get pods -n "$namespace" --field-selector=status.phase=Running --output=json \
| jq -r ".items[] | select(.metadata.name | startswith(\"$pod_prefix\")) | .metadata.name")
# If no running pods match the prefix, something might be wrong, but we'll keep waiting.
if [[ -z $target_pods ]]; then
echo "No running pods found with prefix '$pod_prefix'. Waiting..."
sleep "$check_interval"
elapsed_time=$((elapsed_time + check_interval))
continue
fi
local ready_count=0
local total_matches=0
# Check each pod individually
for pod_name in $target_pods; do
total_matches=$((total_matches + 1))
current_ready=$(kubectl get pod "$pod_name" -n "$namespace" -o json 2>/dev/null \
| jq '.status.containerStatuses | map(select(.ready == true)) | length')
if [[ $current_ready -eq $target_count ]]; then
ready_count=$((ready_count + 1))
fi
done
if [[ $ready_count -eq $total_matches ]]; then
echo "Success: All $total_matches pods now have $target_count ready containers."
return 0
fi
echo "Current status: $ready_count of $total_matches pods have $target_count ready containers. Waiting ${check_interval}s..."
sleep "$check_interval"
elapsed_time=$((elapsed_time + check_interval))
done
echo "Error: Timeout reached! After ${max_wait_seconds} seconds, not all pods reached $target_count ready containers." >&2
return 1
}
destroy_operator() {
kubectl -n "${OPERATOR_NS:-$NAMESPACE}" delete deployment percona-postgresql-operator --force --grace-period=0 || true
if [[ $OPERATOR_NS ]]; then
kubectl delete namespace $OPERATOR_NS --force --grace-period=0 || true
fi
}
get_operator_pod() {
echo $(kubectl get pods -n "${OPERATOR_NS:-$NAMESPACE}" --selector=app.kubernetes.io/name=percona-postgresql-operator -o jsonpath='{.items[].metadata.name}')
}
retry() {
local max=$1
local delay=$2
shift 2 # cut delay and max args
local n=1
until "$@"; do
if [[ $n -ge $max ]]; then
echo "The command ${*} has failed after $n attempts."
exit 1
fi
((n++))
sleep $delay
done
}
deploy_minio() {
local access_key
local secret_key
access_key="$(kubectl -n "${NAMESPACE}" get secret minio-secret -o jsonpath='{.data.AWS_ACCESS_KEY_ID}' | base64 -d)"
secret_key="$(kubectl -n "${NAMESPACE}" get secret minio-secret -o jsonpath='{.data.AWS_SECRET_ACCESS_KEY}' | base64 -d)"
helm uninstall -n "${NAMESPACE}" minio-service || :
helm repo remove minio || :
helm repo add minio https://charts.min.io/
retry 10 60 helm install minio-service \
-n "${NAMESPACE}" \
--version "${MINIO_VER}" \
--set replicas=1 \
--set mode=standalone \
--set resources.requests.memory=256Mi \
--set rootUser=rootuser \
--set rootPassword=rootpass123 \
--set "users[0].accessKey"="$(printf '%q' "$(printf '%q' "$access_key")")" \
--set "users[0].secretKey"="$(printf '%q' "$(printf '%q' "$secret_key")")" \
--set "users[0].policy"=consoleAdmin \
--set service.type=ClusterIP \
--set configPathmc=/tmp/.minio/ \
--set persistence.size=2G \
--set securityContext.enabled=false \
minio/minio
MINIO_POD=$(kubectl -n "${NAMESPACE}" get pods --selector=release=minio-service -o 'jsonpath={.items[].metadata.name}')
wait_pod $MINIO_POD
# create bucket
kubectl -n "${NAMESPACE}" run -i --rm aws-cli --image=perconalab/awscli --restart=Never -- \
bash -c "AWS_ACCESS_KEY_ID='$access_key' AWS_SECRET_ACCESS_KEY='$secret_key' AWS_DEFAULT_REGION=us-east-1 \
/usr/bin/aws --endpoint-url http://minio-service:9000 s3 mb s3://operator-testing"
}
get_repo_auth() {
local repo=$1
local type=$2
local key=$3
local secret=$4
auth="${repo}-${type}-key=${key}\n${repo}-${type}-key-secret=${secret}"
if [[ "$type" == "azure" ]]; then
auth="${repo}-${type}-account=${key}\n${repo}-${type}-key=${secret}"
elif [[ "$type" == "gcs" ]]; then
auth="${repo}-${type}-key=${key}"
fi
echo "\n$auth"
}
deploy_s3_secrets() {
set +o xtrace
local platform=${1:-$(detect_k8s_platform)}
local repo_auth=""
local secret_args=()
if [[ $platform == "digitalocean" ]]; then
key=$(yq eval 'select(.metadata.name=="*spaces*").data.ACCESS_KEY_ID' "$TESTS_CONFIG_DIR/cloud-secret.yml" | base64 -d)
secret=$(yq eval 'select(.metadata.name=="*spaces*").data.SECRET_ACCESS_KEY' "$TESTS_CONFIG_DIR/cloud-secret.yml" | base64 -d)
repo_auth+=$(get_repo_auth repo1 s3 $key $secret)
case $test_name in
"demand-backup")
repo_auth+=$(get_repo_auth repo3 s3 $key $secret)
;;
"scheduled-backup")
repo_auth+=$(get_repo_auth repo2 s3 $key $secret)
repo_auth+=$(get_repo_auth repo3 s3 $key $secret)
;;
esac
else
key=$(yq eval 'select(.metadata.name=="*s3*").data.AWS_ACCESS_KEY_ID' "$TESTS_CONFIG_DIR/cloud-secret.yml" | base64 -d)
secret=$(yq eval 'select(.metadata.name=="*s3*").data.AWS_SECRET_ACCESS_KEY' "$TESTS_CONFIG_DIR/cloud-secret.yml" | base64 -d)
azure_key=$(yq eval 'select(.metadata.name=="azure*").data.AZURE_STORAGE_ACCOUNT_NAME' "$TESTS_CONFIG_DIR/cloud-secret.yml" | base64 -d)
azure_secret=$(yq eval 'select(.metadata.name=="azure*").data.AZURE_STORAGE_ACCOUNT_KEY' "$TESTS_CONFIG_DIR/cloud-secret.yml" | base64 -d)
repo_auth+=$(get_repo_auth repo1 s3 $key $secret)
case $test_name in
"demand-backup")
repo_auth+=$(get_repo_auth repo3 azure $azure_key $azure_secret)
;;
"scheduled-backup")
repo_auth+=$(get_repo_auth repo2 gcs "/etc/pgbackrest/conf.d/gcs-key.json")
repo_auth+=$(get_repo_auth repo3 azure $azure_key $azure_secret)
yq eval '.stringData["credentials.json"]' "$TESTS_CONFIG_DIR/cloud-secret-minio-gw.yml" > "$TEMP_DIR/gcs-key.json"
secret_args+=(--from-file=gcs-key.json="$TEMP_DIR/gcs-key.json")
;;
esac
fi
printf "[global]%b" "$repo_auth" > "$TEMP_DIR/pgbackrest-secret.ini"
secret_args+=(--from-file=cloud.conf="$TEMP_DIR/pgbackrest-secret.ini")
kubectl -n "$NAMESPACE" create secret generic "${test_name}-pgbackrest-secrets" "${secret_args[@]}"
case $test_name in
"custom-extensions" | "builtin-extensions" | major-upgrade* )
kubectl -n "$NAMESPACE" apply -f "$TESTS_CONFIG_DIR/cloud-secret.yml"
kubectl -n "$NAMESPACE" apply -f "$TESTS_CONFIG_DIR/minio-secret.yml"
;;
esac
set -o xtrace
}
deploy_client() {
kubectl -n "${NAMESPACE}" apply -f "${TESTS_CONFIG_DIR}/client.yaml"
}
deploy_cmctl() {
envsubst < "${TESTS_CONFIG_DIR}/cmctl.yml" | kubectl -n "${NAMESPACE}" apply -f -
kubectl -n "${NAMESPACE}" wait deployment cmctl --for=condition=available --timeout=60s
}
get_client_pod() {
kubectl -n ${NAMESPACE} get pods --selector=name=pg-client -o 'jsonpath={.items[].metadata.name}'
}
get_cr() {
local cr_name=$1
local repo_path=$2
local source_path=$3
if [ -z "$cr_name" ]; then
cr_name=${test_name}
fi
local platform="$(detect_k8s_platform)"
local cr_file="$TEST_CONFIG_DIR/${cr_name}.yaml"
local spaces_cr_file="$TEST_CONFIG_DIR/${cr_name}-spaces.yaml"
local aks_cr_file="$TEST_CONFIG_DIR/${cr_name}-aks.yaml"
if [[ $platform == "digitalocean" && -f "$spaces_cr_file" ]]; then
cr_file=$spaces_cr_file
elif [[ $platform == "aks" && -f "$aks_cr_file" ]]; then
cr_file=$aks_cr_file
fi
local crs=("$DEPLOY_DIR/cr.yaml")
if [[ -f "$cr_file" ]]; then
crs+=($cr_file)
fi
yq eval-all '
select(fileIndex == 0) * (select(fileIndex == 1) // {}) |
.metadata.name = "'${cr_name}'" |
.metadata.labels = {"e2e":"'${cr_name}'"} |
.spec.postgresVersion = '$PG_VER' |
.spec.users += [{"name":"postgres","password":{"type":"AlphaNumeric"}}] |
.spec.users += [{"name":"'${cr_name}'","password":{"type":"AlphaNumeric"}}] |
.spec.image = "'$IMAGE_POSTGRESQL'" |
.spec.initContainer.image = "'$IMAGE'" |
.spec.backups.pgbackrest.image = "'$IMAGE_BACKREST'" |
.spec.proxy.pgBouncer.image = "'$IMAGE_PGBOUNCER'" |
.spec.pmm.image = "'$IMAGE_PMM_CLIENT'" |
.spec.pmm.secret = "'${cr_name}'-pmm-secret" |
.spec.pmm.customClusterName = "'${cr_name}'-pmm-custom-name" |
.spec.pmm.postgresParams = "--environment=dev-postgres"
' "${crs[@]}" > "$TEMP_DIR/cr.yaml"
$sed -i "s|<repo-path>|$repo_path|g" "$TEMP_DIR/cr.yaml"
$sed -i "s|<source-path>|$source_path|g" "$TEMP_DIR/cr.yaml"
$sed -i "s|<bucket>|$BUCKET|g" "$TEMP_DIR/cr.yaml"
$sed -i "s|<image>|$IMAGE|g" "$TEMP_DIR/cr.yaml"
if [[ $OPENSHIFT ]]; then
yq eval -i '.spec.openshift = true' "$TEMP_DIR/cr.yaml"
fi
cat "$TEMP_DIR/cr.yaml"
}
run_comand_on_pod() {
local command=${1}
kubectl -n ${NAMESPACE} exec $(get_client_pod) -- \
bash -c "$command"
}
run_psql_local() {
local command=${1}
local uri=${2}
local driver=${3:-postgres}
kubectl -n ${NAMESPACE} exec $(get_client_pod) -- \
bash -c "printf '$command\n' | psql -v ON_ERROR_STOP=1 -t -q $driver://'$uri'"
}
run_psql() {
local command=${1}
local uri=${2}
local password=${3}
kubectl -n ${NAMESPACE} exec $(get_client_pod) -- \
bash -c "printf '$command\n' | PGPASSWORD="\'$password\'" psql -v ON_ERROR_STOP=1 -t -q $uri"
}
get_psql_user_pass() {
local secret_name=${1}
kubectl -n ${NAMESPACE} get "secret/${secret_name}" --template='{{.data.password | base64decode}}'
}
get_pgbouncer_host() {
local secret_name=${1}
kubectl -n ${NAMESPACE} get "secret/${secret_name}" -o jsonpath={.data.pgbouncer-host} | base64 -d
}
get_psql_user_host() {
local secret_name=${1}
kubectl -n ${NAMESPACE} get "secret/${secret_name}" --template='{{.data.host | base64decode }}'
}
get_aws_access_key() {
local secret_name=${1}
kubectl -n ${NAMESPACE} get "secret/${secret_name}" --template='{{.data.AWS_SECRET_ACCESS_KEY | base64decode }}'
}
get_aws_access_key_id() {
local secret_name=${1}
kubectl -n ${NAMESPACE} get "secret/${secret_name}" --template='{{.data.AWS_ACCESS_KEY_ID | base64decode }}'
}
get_psql_user_host() {
local secret_name=${1}
kubectl -n ${NAMESPACE} get "secret/${secret_name}" --template='{{.data.host | base64decode }}'
}
get_instance_set_pods() {
local instance=${1:-instance1}
kubectl get pods -n ${NAMESPACE} --selector postgres-operator.crunchydata.com/instance-set=${instance} -o custom-columns='NAME:.metadata.name' --no-headers
}
copy_custom_extensions_form_aws() {
set +o xtrace
access_key="$(kubectl -n "${NAMESPACE}" get secret minio-secret -o jsonpath='{.data.AWS_ACCESS_KEY_ID}' | base64 -d)"
secret_key="$(kubectl -n "${NAMESPACE}" get secret minio-secret -o jsonpath='{.data.AWS_SECRET_ACCESS_KEY}' | base64 -d)"
kubectl -n "${NAMESPACE}" run -i --rm aws-cli \
--image=perconalab/awscli \
--restart=Never -- \
bash -c "
AWS_ACCESS_KEY_ID=$(get_aws_access_key_id aws-s3-secret) \
AWS_SECRET_ACCESS_KEY=$(get_aws_access_key aws-s3-secret) \
AWS_DEFAULT_REGION=eu-central-1 \
/usr/bin/aws --endpoint-url https://s3.amazonaws.com s3 cp s3://pg-extensions/ /tmp/ --recursive &&
AWS_ACCESS_KEY_ID='${access_key}' \
AWS_SECRET_ACCESS_KEY='${secret_key}' \
AWS_DEFAULT_REGION=us-east-1 \
/usr/bin/aws --endpoint-url http://minio-service:9000 s3 cp /tmp/ s3://operator-testing/ --recursive
"
set -o xtrace
}
get_psql_pod_host() {
local pod=${1}
echo "${pod}.${test_name}-pods.${NAMESPACE}.svc"
}
wait_pod() {
local pod=$1
set +o xtrace
retry=0
echo -n $pod
until kubectl get pod/$pod -n "${NAMESPACE}" -o jsonpath='{.status.containerStatuses[0].ready}' 2>/dev/null | grep 'true'; do
sleep 1
echo -n .
let retry+=1
if [ $retry -ge 360 ]; then
kubectl describe pod/$pod -n "${NAMESPACE}"
kubectl logs $pod -n "${NAMESPACE}"
kubectl logs $(get_operator_pod) ${OPERATOR_NS:+-n $OPERATOR_NS} \
| grep -v 'level=info' \
| grep -v 'level=debug' \
| grep -v 'Getting tasks for pod' \
| grep -v 'Getting pods from source' \
| tail -100
echo max retry count $retry reached. something went wrong with operator or kubernetes cluster
exit 1
fi
done
set -o xtrace
}
get_service_ip() {
local service=$1
while (kubectl get service/$service -n "${NAMESPACE}" -o 'jsonpath={.spec.type}' 2>&1 || :) | grep -q NotFound; do
sleep 1
done
if [ "$(kubectl get service/$service -n "${NAMESPACE}" -o 'jsonpath={.spec.type}')" = "ClusterIP" ]; then
kubectl get service/$service -n "${NAMESPACE}" -o 'jsonpath={.spec.clusterIP}'
return
fi
until kubectl get service/$service -n "${NAMESPACE}" -o 'jsonpath={.status.loadBalancer.ingress[]}' 2>&1 | egrep -q "hostname|ip"; do
sleep 1
done
kubectl get service/$service -n "${NAMESPACE}" -o 'jsonpath={.status.loadBalancer.ingress[].ip}'
kubectl get service/$service -n "${NAMESPACE}" -o 'jsonpath={.status.loadBalancer.ingress[].hostname}'
}
get_version_images() {
local cr_version="$1"
local component="$2"
local release_versions_file="${TEMP_DIR}/release_version_${cr_version}"
if [[ ! -f $release_versions_file ]]; then
curl -s "https://raw.githubusercontent.com/percona/percona-postgresql-operator/refs/tags/v${cr_version}/e2e-tests/release_versions" >$release_versions_file
fi
grep -i ${component} $release_versions_file | cut -d'=' -f2
}
get_release_image() {
local key="$1"
local release_versions_file="${ROOT_REPO}/e2e-tests/release_versions"
grep -E "^${key}=" "$release_versions_file" | cut -d'=' -f2
}
wait_for_delete() {
local res="$1"
echo -n "$res - "
retry=0
until (kubectl get $res -n "${NAMESPACE}" || :) 2>&1 | grep NotFound; do
sleep 1
echo -n .
let retry+=1
if [ $retry -ge 120 ]; then
echo max retry count $retry reached. something went wrong with operator or kubernetes cluster
exit 1
fi
done
}
deploy_pmm_server() {
helm uninstall -n "${NAMESPACE}" pmm || :
if [[ $OPENSHIFT ]]; then
platform=openshift
oc create sa pmm-server -n "$NAMESPACE"
oc adm policy add-scc-to-user privileged -z pmm-server -n "$NAMESPACE"
if [[ $OPERATOR_NS ]]; then
timeout 30 oc delete clusterrolebinding $(kubectl get clusterrolebinding | grep 'pmm-pg-operator-' | awk '{print $1}') || :
oc create clusterrolebinding pmm-pg-operator-cluster-wide --clusterrole=percona-postgresql-operator --serviceaccount=$NAMESPACE:pmm-server -n "$NAMESPACE"
oc patch clusterrole/percona-postgresql-operator --type json -p='[{"op":"add","path": "/rules/-","value":{"apiGroups":["security.openshift.io"],"resources":["securitycontextconstraints"],"verbs":["use"],"resourceNames":["privileged"]}}]' ${OPERATOR_NS:+-n $OPERATOR_NS}
else
oc create rolebinding pmm-pg-operator-namespace-only --role percona-postgresql-operator --serviceaccount=$NAMESPACE:pmm-server -n "${NAMESPACE}"
oc patch role/percona-postgresql-operator --type json -p='[{"op":"add","path": "/rules/-","value":{"apiGroups":["security.openshift.io"],"resources":["securitycontextconstraints"],"verbs":["use"],"resourceNames":["privileged"]}}]' -n "$NAMESPACE"
fi
helm install monitoring --set imageTag=${IMAGE_PMM_SERVER#*:} --set imageRepo=${IMAGE_PMM_SERVER%:*} --set platform=$platform --set sa=pmm-server --set supresshttp2=false https://percona-charts.storage.googleapis.com/pmm-server-${PMM_SERVER_VERSION}.tgz -n "$NAMESPACE"
else
platform=kubernetes
helm install monitoring -n "$NAMESPACE" --set imageTag=${IMAGE_PMM_SERVER#*:} --set service.type="LoadBalancer" \
--set imageRepo=${IMAGE_PMM_SERVER%:*} --set platform="$platform" "https://percona-charts.storage.googleapis.com/pmm-server-${PMM_SERVER_VERSION}.tgz"
fi
}
deploy_pmm3_server() {
helm uninstall -n "${NAMESPACE}" monitoring || :
helm repo remove percona || :
kubectl delete clusterrole monitoring --ignore-not-found
kubectl delete clusterrolebinding monitoring --ignore-not-found
helm repo add percona https://percona.github.io/percona-helm-charts/
helm repo update
if [[ $OPENSHIFT ]]; then
oc create sa pmm-server -n "$NAMESPACE"
oc adm policy add-scc-to-user privileged -z pmm-server -n "$NAMESPACE"
if [[ $OPERATOR_NS ]]; then
timeout 30 oc delete clusterrolebinding $(kubectl get clusterrolebinding | grep 'pmm-pg-operator-' | awk '{print $1}') || :
oc create clusterrolebinding pmm-pg-operator-cluster-wide --clusterrole=percona-postgresql-operator --serviceaccount=$NAMESPACE:pmm-server -n "$NAMESPACE"
oc patch clusterrole/percona-postgresql-operator --type json -p='[{"op":"add","path": "/rules/-","value":{"apiGroups":["security.openshift.io"],"resources":["securitycontextconstraints"],"verbs":["use"],"resourceNames":["privileged"]}}]' ${OPERATOR_NS:+-n $OPERATOR_NS}
else
oc create rolebinding pmm-pg-operator-namespace-only --role percona-postgresql-operator --serviceaccount=$NAMESPACE:pmm-server -n "${NAMESPACE}"
oc patch role/percona-postgresql-operator --type json -p='[{"op":"add","path": "/rules/-","value":{"apiGroups":["security.openshift.io"],"resources":["securitycontextconstraints"],"verbs":["use"],"resourceNames":["privileged"]}}]' -n "$NAMESPACE"
fi
local additional_params="--set platform=openshift --set supresshttp2=false --set serviceAccount.create=false --set serviceAccount.name=pmm-server"
fi
retry 10 60 helm install monitoring percona/pmm -n "${NAMESPACE}" \
--set fullnameOverride=monitoring \
--set image.tag=${IMAGE_PMM3_SERVER#*:} \
--set image.repository=${IMAGE_PMM3_SERVER%:*} \
--set service.type=LoadBalancer \
$additional_params \
--force
}
retry() {
local max=$1
local delay=$2
shift 2 # cut delay and max args
local n=1
until "$@"; do
if [[ $n -ge $max ]]; then
echo "The command '$@' has failed after $n attempts."
exit 1
fi
((n++))
sleep $delay
done
}
generate_pmm_api_key() {
local ADMIN_PASSWORD=$(kubectl -n "${NAMESPACE}" exec monitoring-0 -- bash -c "printenv | grep ADMIN_PASSWORD | cut -d '=' -f2")
local PMM_SERVICE_IP=$(get_service_ip monitoring-service)
curl \
--insecure \
-X POST \
-H "Content-Type: application/json" \
-d '{"name":"'${RANDOM}'", "role": "Admin"}' \
--user "admin:${ADMIN_PASSWORD}" \
"https://${PMM_SERVICE_IP}/graph/api/auth/keys" \
| jq -r .key
}
generate_pmm3_server_token() {
local key_name=$RANDOM
local ADMIN_PASSWORD
ADMIN_PASSWORD=$(kubectl -n "${NAMESPACE}" get secret pmm-secret -o jsonpath="{.data.PMM_ADMIN_PASSWORD}" | base64 --decode)
if [[ -z $ADMIN_PASSWORD ]]; then
echo "Error: ADMIN_PASSWORD is empty or not found!" >&2
return 1
fi
local create_response create_status_code create_json_response
create_response=$(curl --insecure -s -X POST -H 'Content-Type: application/json' -H 'Accept: application/json' \
-d "{\"name\":\"${key_name}\", \"role\":\"Admin\", \"isDisabled\":false}" \
--user "admin:${ADMIN_PASSWORD}" \
"https://$(get_service_ip monitoring-service)/graph/api/serviceaccounts" \
-w "\n%{http_code}")
create_status_code=$(echo "$create_response" | tail -n1)
create_json_response=$(echo "$create_response" | $sed '$ d')
if [[ $create_status_code -ne 201 ]]; then
echo "Error: Failed to create PMM service account. HTTP Status: $create_status_code" >&2
echo "Response: $create_json_response" >&2
return 1
fi
local service_account_id
service_account_id=$(echo "$create_json_response" | jq -r '.id')
if [[ -z $service_account_id || $service_account_id == "null" ]]; then
echo "Error: Failed to extract service account ID!" >&2
return 1
fi
local token_response token_status_code token_json_response
token_response=$(curl --insecure -s -X POST -H 'Content-Type: application/json' \
-d "{\"name\":\"${key_name}\"}" \
--user "admin:${ADMIN_PASSWORD}" \
"https://$(get_service_ip monitoring-service)/graph/api/serviceaccounts/${service_account_id}/tokens" \
-w "\n%{http_code}")
token_status_code=$(echo "$token_response" | tail -n1)
token_json_response=$(echo "$token_response" | $sed '$ d')
if [[ $token_status_code -ne 200 ]]; then
echo "Error: Failed to create token. HTTP Status: $token_status_code" >&2
echo "Response: $token_json_response" >&2
return 1
fi
echo "$token_json_response" | jq -r '.key'
}
get_metric_values() {
local metric=$1
local instance=$2
local token=$3
local start=$($date -u "+%s" -d "-5 minute")
local end=$($date -u "+%s")
local endpoint=$(get_service_ip monitoring-service)
local wait_count=20
local retry=0
until [[ $(curl -s -k -H "Authorization: Bearer ${token}" "https://$endpoint/graph/api/datasources/proxy/1/api/v1/query_range?query=min%28$metric%7Bnode_name%3D%7E%22$instance%22%7d%20or%20$metric%7Bnode_name%3D%7E%22$instance%22%7D%29&start=$start&end=$end&step=60" \
| jq '.data.result[0].values[][1]' \
| grep '^"[0-9]') ]]; do
sleep 2
local start=$($date -u "+%s" -d "-5 minute")
local end=$($date -u "+%s")
let retry+=1
if [[ $retry -ge $wait_count ]]; then
exit 1
fi
done
}
get_qan20_values() {
local instance=$1
local api_key=$2
local start=$($date -u "+%Y-%m-%dT%H:%M:%S" -d "-30 minute")
local end=$($date -u "+%Y-%m-%dT%H:%M:%S")
local endpoint=$(get_service_ip monitoring-service)
cat >payload.json <<EOF
{
"columns":[
"load",
"num_queries",
"query_time"
],
"first_seen": false,
"group_by": "queryid",
"include_only_fields": [],
"keyword": "",
"labels": [
{
"key": "cluster",
"value": ["postgresql"]
}],
"limit": 10,
"offset": 0,
"order_by": "-load",
"main_metric": "load",
"period_start_from": "$($date -u -d '-12 hour' '+%Y-%m-%dT%H:%M:%S%:z')",
"period_start_to": "$($date -u '+%Y-%m-%dT%H:%M:%S%:z')"
}
EOF
curl -s -k -H "Authorization: Bearer ${api_key}" -XPOST -d @payload.json "https://$endpoint/v0/qan/GetReport" \
| jq '.rows[].sparkline'
rm -f payload.json
}
get_qan20_values_pmm3() {
local instance=$1
local token=$2
local start=$($date -u "+%Y-%m-%dT%H:%M:%S" -d "-30 minute")
local end=$($date -u "+%Y-%m-%dT%H:%M:%S")
local endpoint=$(get_service_ip monitoring-service)
cat >payload.json <<EOF
{
"columns":[
"load",
"num_queries",
"query_time"
],
"first_seen": false,
"group_by": "queryid",
"include_only_fields": [],
"keyword": "",
"labels": [
{
"key": "cluster",
"value": ["postgresql"]
}],
"limit": 10,
"offset": 0,
"order_by": "-load",
"main_metric": "load",
"period_start_from": "$($date -u -d '-12 hour' '+%Y-%m-%dT%H:%M:%S%:z')",
"period_start_to": "$($date -u '+%Y-%m-%dT%H:%M:%S%:z')"
}
EOF
curl -s -k -H "Authorization: Bearer ${token}" -XPOST -d @payload.json "https://$endpoint/v1/qan/metrics:getReport" \
| jq '.rows[].sparkline'
rm -f payload.json
}
deploy_chaos_mesh() {
destroy_chaos_mesh
helm repo add chaos-mesh https://charts.chaos-mesh.org
helm install chaos-mesh chaos-mesh/chaos-mesh --namespace=${NAMESPACE} --set chaosDaemon.runtime=containerd --set chaosDaemon.socketPath=/run/containerd/containerd.sock --set dashboard.create=false --version ${CHAOS_MESH_VER}
if [[ $OPENSHIFT ]]; then
oc adm policy add-scc-to-user privileged -z chaos-daemon --namespace=${NAMESPACE}
fi
sleep 10
}
destroy_chaos_mesh() {
local chaos_mesh_ns=$(helm list --all-namespaces --filter chaos-mesh | tail -n1 | awk -F' ' '{print $2}' | $sed 's/NAMESPACE//')
if [ -n "${chaos_mesh_ns}" ]; then
helm uninstall --wait --timeout 60s chaos-mesh --namespace ${chaos_mesh_ns} || :
fi
timeout 30 kubectl delete MutatingWebhookConfiguration $(kubectl get MutatingWebhookConfiguration | grep 'chaos-mesh' | awk '{print $1}') || :
timeout 30 kubectl delete ValidatingWebhookConfiguration $(kubectl get ValidatingWebhookConfiguration | grep 'chaos-mesh' | awk '{print $1}') || :
timeout 30 kubectl delete ValidatingWebhookConfiguration $(kubectl get ValidatingWebhookConfiguration | grep 'validate-auth' | awk '{print $1}') || :
for i in $(kubectl api-resources | grep chaos-mesh | awk '{print $1}'); do
kubectl get ${i} --all-namespaces --no-headers -o custom-columns=Kind:.kind,Name:.metadata.name,NAMESPACE:.metadata.namespace \
| while read -r line; do
local kind=$(echo "$line" | awk '{print $1}')
local name=$(echo "$line" | awk '{print $2}')
local namespace=$(echo "$line" | awk '{print $3}')
kubectl patch $kind $name -n $namespace --type=merge -p '{"metadata":{"finalizers":[]}}' || :
done
timeout 30 kubectl delete ${i} --all --all-namespaces || :
done
timeout 30 kubectl delete crd $(kubectl get crd | grep 'chaos-mesh.org' | awk '{print $1}') || :
timeout 30 kubectl delete clusterrolebinding $(kubectl get clusterrolebinding | grep 'chaos-mesh' | awk '{print $1}') || :
timeout 30 kubectl delete clusterrole $(kubectl get clusterrole | grep 'chaos-mesh' | awk '{print $1}') || :
}
kill_pods() {
local ns=$1
local selector=$2
local pod_label=$3
local label_value=$4
if [ "${selector}" == "pod" ]; then
yq eval '
.metadata.name = "chaos-pod-kill-'${RANDOM}'" |
del(.spec.selector.pods.test-namespace) |
.spec.selector.pods.'${ns}'[0] = "'${pod_label}'"' ${TESTS_CONFIG_DIR}/chaos-pod-kill.yml \
| kubectl apply --namespace ${ns} -f -
elif [ "${selector}" == "label" ]; then
yq eval '
.metadata.name = "chaos-kill-label-'${RANDOM}'" |
.spec.mode = "all" |
del(.spec.selector.pods) |
.spec.selector.labelSelectors."'${pod_label}'" = "'${label_value}'"' ${TESTS_CONFIG_DIR}/chaos-pod-kill.yml \
| kubectl apply --namespace ${ns} -f -
fi
sleep 5
}
failure_pod() {
local ns=$1
local pod=$2
yq eval '
.metadata.name = "chaos-pod-failure-'${RANDOM}'" |
del(.spec.selector.pods.test-namespace) |
.spec.selector.pods.'${ns}'[0] = "'${pod}'"' ${TESTS_CONFIG_DIR}/chaos-pod-failure.yml \
| kubectl apply --namespace ${ns} -f -
sleep 5
}
network_loss() {
local ns=$1
local pod=$2
yq eval '
.metadata.name = "chaos-pod-network-loss-'${RANDOM}'" |
del(.spec.selector.pods.test-namespace) |
.spec.selector.pods.'${ns}'[0] = "'${pod}'"' ${TESTS_CONFIG_DIR}/chaos-network-loss.yml \
| kubectl apply --namespace ${ns} -f -
sleep 5
}
wait_deployment() {
local name=$1
local target_namespace=${2:-"$namespace"}
sleep 10
set +o xtrace
retry=0
echo -n $name
until [ -n "$(kubectl -n ${target_namespace} get deployment $name -o jsonpath='{.status.replicas}')" \
-a "$(kubectl -n ${target_namespace} get deployment $name -o jsonpath='{.status.replicas}')" \
== "$(kubectl -n ${target_namespace} get deployment $name -o jsonpath='{.status.readyReplicas}')" ]; do
sleep 1
echo -n .
let retry+=1
if [ $retry -ge 360 ]; then
kubectl logs $(get_operator_pod) -c operator \
| grep -v 'level=info' \
| grep -v 'level=debug' \
| tail -100
echo max retry count $retry reached. something went wrong with operator or kubernetes cluster
exit 1
fi
done
echo
set -o xtrace
}
get_pod_by_role() {
local cluster=${1}
local role=${2}
local parameter=${3}
case ${parameter} in
'name')
local jsonpath="{.items[].metadata.name}"
;;
'IP')
local jsonpath="{.items[].status.podIP}"
;;
esac
echo "$(kubectl get pods --namespace ${NAMESPACE} --selector=postgres-operator.crunchydata.com/role=${role},postgres-operator.crunchydata.com/cluster=${cluster} -o 'jsonpath='${jsonpath}'')"
}
check_passwords_leak() {
local secrets
local passwords
local pods
secrets=$(
kubectl -n "${NAMESPACE}" get secrets -o json | jq -r '.items[] | select(.data."password"? != null) | .data."password"'
kubectl -n "${NAMESPACE}" get secrets -o json | jq -r '.items[] | select(.data."pgbouncer-password"? != null) | .data."pgbouncer-password"'
)
passwords="$(for i in $secrets; do
base64 -d <<<$i
echo
done) $secrets"
pods=$(kubectl -n "${NAMESPACE}" get pods -o name | awk -F "/" '{print $2}')
collect_logs() {
local containers
local count
NS=$1
for p in $pods; do
containers=$(kubectl -n "$NS" get pod $p -o jsonpath='{.spec.containers[*].name}')
for c in $containers; do
# temporary, because of: https://jira.percona.com/browse/PMM-8357
if [[ $c =~ "pmm" ]]; then
continue
fi
kubectl -n "$NS" logs $p -c $c >${TEMP_DIR}/logs_output-$p-$c.txt
echo logs saved in: ${TEMP_DIR}/logs_output-$p-$c.txt
for pass in $passwords; do
count=$(grep -c --fixed-strings -- "$pass" ${TEMP_DIR}/logs_output-$p-$c.txt || :)
if [[ $count != 0 ]]; then
echo leaked passwords are found in log ${TEMP_DIR}/logs_output-$p-$c.txt
false
fi
done
done
echo
done
}
collect_logs $NAMESPACE
if [ -n "$OPERATOR_NS" ]; then
pods=$(kubectl -n "${OPERATOR_NS}" get pods -o name | awk -F "/" '{print $2}')
collect_logs $OPERATOR_NS
fi
}
get_backup_destination() {
local cluster=$1
local backup_name=$2
local repo
local storage_type
repo=$(kubectl get pg-backup -n "$NAMESPACE" "$backup_name" -o yaml \
| yq ".spec.repoName")
if [[ $(kubectl get pg -n "$NAMESPACE" "$cluster" -o yaml \
| yq ".spec.backups.pgbackrest.repos[] | select(.name==\"$repo\") | has(\"s3\")") == "true" ]]; then
storage_type="s3"
elif [[ $(kubectl get pg -n "$NAMESPACE" "$cluster" -o yaml \
| yq ".spec.backups.pgbackrest.repos[] | select(.name==\"$repo\") | has(\"gcs\")") == "true" ]]; then
storage_type="gcs"
elif [[ $(kubectl get pg -n "$NAMESPACE" "$cluster" -o yaml \
| yq ".spec.backups.pgbackrest.repos[] | select(.name==\"$repo\") | has(\"azure\")") == "true" ]]; then
storage_type="azure"
else
echo "ERROR: unknown storage type"
exit 1
fi
local repo_path
local bucket
repo_path=$(kubectl get pg -n "$NAMESPACE" "$cluster" -o yaml \
| yq ".spec.backups.pgbackrest.global.$repo-path")
bucket=$(kubectl get pg -n "$NAMESPACE" "$cluster" -o yaml \
| yq ".spec.backups.pgbackrest.repos[] | select(.name==\"$repo\").$storage_type.bucket")