-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathfunctions
executable file
·1705 lines (1463 loc) · 54 KB
/
functions
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
GIT_COMMIT=$(git rev-parse HEAD)
GIT_BRANCH=${VERSION:-$(git rev-parse --abbrev-ref HEAD | sed -e 's^/^-^g; s^[.]^-^g;' | sed -e 's/_/-/g' | tr '[:upper:]' '[:lower:]')}
API="psmdb.percona.com/v1"
OPERATOR_VERSION="$(grep 'crVersion' $(realpath $(dirname ${BASH_SOURCE[0]})/../deploy/cr.yaml) | awk '{print $2}')"
IMAGE=${IMAGE:-"perconalab/percona-server-mongodb-operator:${GIT_BRANCH}"}
IMAGE_MONGOD=${IMAGE_MONGOD:-"perconalab/percona-server-mongodb-operator:main-mongod8.0"}
IMAGE_MONGOD_CHAIN=${IMAGE_MONGOD_CHAIN:-$'
perconalab/percona-server-mongodb-operator:main-mongod6.0
perconalab/percona-server-mongodb-operator:main-mongod7.0
perconalab/percona-server-mongodb-operator:main-mongod8.0'}
IMAGE_BACKUP=${IMAGE_BACKUP:-"perconalab/percona-server-mongodb-operator:pbm-290"}
SKIP_BACKUPS_TO_AWS_GCP_AZURE=${SKIP_BACKUPS_TO_AWS_GCP_AZURE:-1}
PMM_SERVER_VER=${PMM_SERVER_VER:-"9.9.9"}
IMAGE_PMM_CLIENT=${IMAGE_PMM_CLIENT:-"perconalab/pmm-client:dev-latest"}
IMAGE_PMM_SERVER=${IMAGE_PMM_SERVER:-"perconalab/pmm-server:dev-latest"}
CERT_MANAGER_VER="1.16.3"
tmp_dir=$(mktemp -d)
sed=$(which gsed || which sed)
date=$(which gdate || which date)
test_name=$(basename $test_dir)
namespace="${test_name}-${RANDOM}"
replica_namespace="${test_name}-replica-${RANDOM}"
conf_dir=$(realpath $test_dir/../conf || :)
src_dir=$(realpath $test_dir/../..)
logs_dir=$(realpath $test_dir/../logs || :)
if [[ ${ENABLE_LOGGING} == "true" ]]; then
if [ ! -d "${logs_dir}" ]; then
mkdir "${logs_dir}"
fi
exec &> >(tee ${logs_dir}/${test_name}.log)
echo "Log: ${logs_dir}/${test_name}.log"
fi
if [ -f "$conf_dir/cloud-secret.yml" ]; then
SKIP_BACKUPS_TO_AWS_GCP_AZURE=''
fi
if oc get projects 2>/dev/null; then
OPENSHIFT=4
fi
if kubectl get nodes | grep "^minikube" >/dev/null; then
export MINIKUBE=1
fi
minikube_sleep() {
sleep_time=${1:-10}
if [[ $MINIKUBE == 1 ]]; then
sleep $sleep_time
fi
}
if [ $(kubectl version -o json | jq -r '.serverVersion.gitVersion' | grep "\-eks\-") ]; then
EKS=1
else
EKS=0
fi
if [ $(kubectl version -o json | jq -r '.serverVersion.gitVersion' | grep "gke") ]; then
GKE=1
else
GKE=0
fi
KUBE_VERSION=$(kubectl version -o json | jq -r '.serverVersion.major + "." + .serverVersion.minor' | $sed -r 's/[^0-9.]+//g')
log() {
echo "[$(date +%Y-%m-%dT%H:%M:%S%z)]" $*
}
set_debug() {
if [[ ${DEBUG_TESTS} == 1 ]]; then
set -o xtrace
else
set +o xtrace
fi
}
version_gt() {
# return true if kubernetes version equal or greater than desired
if [ $(echo "${KUBE_VERSION} >= $1" | bc -l) -eq 1 ]; then
return 0
else
return 1
fi
}
apply_s3_storage_secrets() {
desc 'create secrets for cloud storages'
if [ -z "$SKIP_BACKUPS_TO_AWS_GCP_AZURE" ]; then
kubectl_bin apply \
-f $conf_dir/minio-secret.yml \
-f $conf_dir/cloud-secret.yml
else
kubectl_bin apply \
-f $conf_dir/minio-secret.yml
fi
}
create_namespace() {
local namespace="$1"
local skip_clean_namespace="$2"
if [[ ${CLEAN_NAMESPACE} == 1 ]] && [[ -z ${skip_clean_namespace} ]]; then
destroy_chaos_mesh
desc 'cleaned up all old namespaces'
kubectl_bin get ns \
| egrep -v "^kube-|^default|Terminating|psmdb-operator|openshift|gke-mcs|^NAME" \
| awk '{print$1}' \
| xargs kubectl delete ns &
fi
if [ -n "${OPENSHIFT}" ]; then
desc 'cleaned up all old namespaces'
if [ -n "$OPERATOR_NS" -a $(oc get project "$OPERATOR_NS" -o json | jq -r '.metadata.name') ]; then
oc delete --grace-period=0 --force=true project "$namespace" && sleep 120 || :
else
oc delete project "$namespace" && sleep 40 || :
fi
desc "create namespace $namespace"
oc new-project "$namespace"
oc project "$namespace"
oc adm policy add-scc-to-user hostaccess -z default || :
else
desc "cleaned up old namespaces $namespace"
kubectl_bin delete namespace "$namespace" --ignore-not-found || :
kubectl_bin wait --for=delete namespace "$namespace" || :
desc "create namespace $namespace"
kubectl_bin create namespace "$namespace"
kubectl_bin config set-context $(kubectl_bin config current-context) --namespace="$namespace"
fi
}
get_operator_pod() {
kubectl_bin get pods \
--selector=name=percona-server-mongodb-operator \
-o 'jsonpath={.items[].metadata.name}' ${OPERATOR_NS:+-n $OPERATOR_NS}
}
wait_pod() {
local pod=$1
set +o xtrace
retry=0
echo -n "waiting for pod/$pod to be ready"
until kubectl_bin get pod/$pod -o jsonpath='{.status.containerStatuses[0].ready}' 2>/dev/null | grep --quiet 'true'; do
sleep 1
echo -n .
let retry+=1
if [ $retry -ge 360 ]; then
kubectl_bin describe pod/$pod
kubectl_bin logs $pod
kubectl_bin logs ${OPERATOR_NS:+-n $OPERATOR_NS} $(get_operator_pod) \
| 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
echo ".OK"
set_debug
}
wait_cron() {
local backup=$1
set +o xtrace
retry=0
echo -n $backup
until kubectl_bin get cronjob/$backup -o jsonpath='{.status.lastScheduleTime}' 2>/dev/null | grep 'T'; do
sleep 1
echo -n .
let retry+=1
if [ $retry -ge 360 ]; then
kubectl_bin logs ${OPERATOR_NS:+-n $OPERATOR_NS} $(get_operator_pod) \
| 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_debug
}
wait_backup_agent() {
local agent_pod=$1
set +o xtrace
retry=0
echo -n $agent_pod
until [ "$(kubectl_bin logs $agent_pod -c backup-agent | egrep -v "\[ERROR\] pitr: check if on:|node:|starting PITR routine|\[agentCheckup\]" | cut -d' ' -f3- | tail -n 1)" == "listening for the commands" ]; do
sleep 5
echo -n .
let retry+=1
if [ $retry -ge 360 ]; then
kubectl_bin logs $agent_pod -c backup-agent \
| tail -100
echo max retry count $retry reached. something went wrong with operator or kubernetes cluster
exit 1
fi
done
echo
set_debug
}
wait_backup() {
local backup_name=$1
local target_state=${2:-"ready"}
set +o xtrace
retry=0
echo -n "waiting for ${backup_name} to reach ${target_state} state"
local current_status=
until [[ ${current_status} == ${target_state} ]]; do
sleep 1
echo -n .
let retry+=1
current_status=$(kubectl_bin get psmdb-backup $backup_name -o jsonpath='{.status.state}')
if [[ $retry -ge 360 || ${current_status} == 'error' ]]; then
kubectl_bin logs ${OPERATOR_NS:+-n $OPERATOR_NS} $(get_operator_pod) \
| grep -v 'level=info' \
| grep -v 'level=debug' \
| grep -v 'Getting tasks for pod' \
| grep -v 'Getting pods from source' \
| tail -100
echo "Backup object psmdb-backup/${backup_name} is in ${current_state} state."
echo something went wrong with operator or kubernetes cluster
exit 1
fi
done
echo
set_debug
}
wait_for_pbm_operations() {
local cluster=$1
set +o xtrace
echo -n "waiting for PBM operation to finish"
retry=0
until [[ $(kubectl_bin exec ${cluster}-rs0-0 -c backup-agent -- pbm status -o json -s running | jq -r .running.opID) == null ]]; do
if [ $retry -ge 540 ]; then
echo max retry count $retry reached. something went wrong with PBM operations
exit 1
fi
echo -n .
sleep 5
done
echo
set_debug
}
run_restore() {
local backup_name=$1
cat $test_dir/conf/restore.yml \
| $sed -e "s/name:/name: restore-$backup_name/" \
| $sed -e "s/backupName:/backupName: $backup_name/" \
| kubectl_bin apply -f -
}
run_restore_backupsource() {
local backupName=$1
local backupDest=$2
local storageName=$3
desc "run restore restore-$backupName from backup $backupName destination is $backupDest"
if [ -z "$storageName" ]; then
cat $test_dir/conf/restore-backupsource.yml \
| $sed -e "s/name:/name: restore-$backupName/" \
| $sed -e "s|BACKUP-NAME|$backupDest|" \
| $sed -e "/storageName/d" \
| kubectl_bin apply -f -
return
fi
cat $test_dir/conf/restore-backupsource.yml \
| $sed -e "s/name:/name: restore-$backupName/" \
| $sed -e "s|BACKUP-NAME|$backupDest|" \
| $sed -e "s/storageName:/storageName: $storageName/" \
| kubectl_bin apply -f -
}
wait_deployment() {
local name=$1
sleep 10
retry=0
echo -n $name
until kubectl_bin get deployment $name ${OPERATOR_NS:+-n $OPERATOR_NS} >/dev/null \
&& [ "$(kubectl_bin get deployment $name -o jsonpath='{.status.replicas}' ${OPERATOR_NS:+-n $OPERATOR_NS})" == "$(kubectl_bin get deployment $name -o jsonpath='{.status.readyReplicas}' ${OPERATOR_NS:+-n $OPERATOR_NS})" ]; do
sleep 1
echo -n .
let retry+=1
if [ $retry -ge 360 ]; then
kubectl_bin logs ${OPERATOR_NS:+-n $OPERATOR_NS} $(get_operator_pod) \
| 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
}
simple_data_check() {
local cluster_name=${1}
let last_pod="$2-1" || :
local isSharded=${3:-0}
local cluster_pfx=$4
if [ $isSharded -eq 1 ]; then
sleep 10 # give time for start mongos
wait_cluster_consistency "${cluster_name}"
compare_mongos_cmd "find" "myApp:myPass@$cluster$cluster_pfx.$namespace"
else
for i in $(seq 0 $last_pod); do
compare_mongo_cmd "find" "myApp:myPass@${cluster_name}${cluster_pfx}-${i}.${cluster_name}${cluster_pfx}.$namespace"
done
fi
}
wait_restore() {
local backup_name=$1
local cluster_name=$2
local target_state=${3:-"ready"}
local wait_cluster_consistency=${4:-1}
local wait_time=${5:-1780}
set +o xtrace
retry=0
echo -n "waiting psmdb-restore/restore-${backup_name} to reach ${target_state} state"
local current_state=
until [[ ${current_state} == ${target_state} ]]; do
sleep 0.5
echo -n .
let retry+=1
current_state=$(kubectl_bin get psmdb-restore restore-$backup_name -o jsonpath='{.status.state}')
if [[ $retry -ge $wait_time || ${current_state} == 'error' ]]; then
kubectl_bin logs ${OPERATOR_NS:+-n $OPERATOR_NS} $(get_operator_pod) \
| grep -v 'level=info' \
| grep -v 'level=debug' \
| grep -v 'Getting tasks for pod' \
| grep -v 'Getting pods from source' \
| tail -100
kubectl_bin get psmdb-restore restore-${backup_name} -o yaml
echo "Restore object restore-${backup_name} is in ${current_state} state."
echo something went wrong with operator or kubernetes cluster
exit 1
fi
done
echo
set_debug
if [ $wait_cluster_consistency -eq 1 ]; then
wait_cluster_consistency "${cluster_name}"
fi
}
apply_rbac() {
local operator_namespace=${OPERATOR_NS:-'psmdb-operator'}
local rbac=${1:-'rbac'}
cat ${src_dir}/deploy/${rbac}.yaml \
| sed -e "s^namespace: .*^namespace: $operator_namespace^" \
| kubectl_bin apply ${OPERATOR_NS:+-n $OPERATOR_NS} -f -
}
deploy_operator() {
desc 'start PSMDB operator'
local cr_file
if [ -f "${test_dir}/conf/crd.yaml" ]; then
cr_file="${test_dir}/conf/crd.yaml"
else
cr_file="${src_dir}/deploy/crd.yaml"
fi
kubectl_bin apply --server-side --force-conflicts -f "${cr_file}"
if [ -n "$OPERATOR_NS" ]; then
apply_rbac cw-rbac
yq eval '
(.spec.template.spec.containers[].image = "'${IMAGE}'") |
((.. | select(.[] == "DISABLE_TELEMETRY")) |= .value="true") |
((.. | select(.[] == "LOG_LEVEL")) |= .value="DEBUG")' ${src_dir}/deploy/cw-operator.yaml \
| kubectl_bin apply -f -
else
apply_rbac rbac
yq eval '
(.spec.template.spec.containers[].image = "'${IMAGE}'") |
((.. | select(.[] == "DISABLE_TELEMETRY")) |= .value="true") |
((.. | select(.[] == "LOG_LEVEL")) |= .value="DEBUG")' ${src_dir}/deploy/operator.yaml \
| kubectl_bin apply -f -
fi
sleep 2
wait_pod $(get_operator_pod)
}
deploy_operator_gh() {
local git_tag="$1"
desc 'start operator'
kubectl_bin apply -f "https://raw.githubusercontent.com/percona/percona-server-mongodb-operator/${git_tag}/deploy/crd.yaml" --server-side
local rbac_yaml="rbac"
local operator_yaml="operator"
if [ -n "${OPERATOR_NS}" ]; then
rbac_yaml="cw-rbac"
operator_yaml="cw-operator"
fi
kubectl_bin apply -f "https://raw.githubusercontent.com/percona/percona-server-mongodb-operator/${git_tag}/deploy/${rbac_yaml}.yaml"
curl -s "https://raw.githubusercontent.com/percona/percona-server-mongodb-operator/${git_tag}/deploy/${operator_yaml}.yaml" >"${tmp_dir}/${operator_yaml}_${git_tag}.yaml"
$sed -i -e "s^image: .*^image: ${IMAGE}^" "${tmp_dir}/${operator_yaml}_${git_tag}.yaml"
kubectl_bin apply -f "${tmp_dir}/${operator_yaml}_${git_tag}.yaml"
sleep 2
wait_pod "$(get_operator_pod)"
}
deploy_minio() {
desc 'install Minio'
helm uninstall minio-service || :
helm repo remove minio || :
helm repo add minio https://charts.min.io/
# kubectl_bin delete pvc minio-service --force
retry 10 60 helm install minio-service \
--version 5.0.14 \
--set replicas=1 \
--set mode=standalone \
--set resources.requests.memory=256Mi \
--set rootUser=rootuser \
--set rootPassword=rootpass123 \
--set "users[0].accessKey=some-access-key" \
--set "users[0].secretKey=some-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_bin get pods --selector=release=minio-service -o 'jsonpath={.items[].metadata.name}')
wait_pod $MINIO_POD
if [ -n "$OPERATOR_NS" ]; then
kubectl_bin create svc -n ${OPERATOR_NS} externalname minio-service --external-name="minio-service.${namespace}.svc.cluster.local" --tcp="9000"
fi
# create bucket
kubectl_bin run -i --rm aws-cli --image=perconalab/awscli --restart=Never -- \
bash -c 'AWS_ACCESS_KEY_ID=some-access-key AWS_SECRET_ACCESS_KEY=some-secret-key AWS_DEFAULT_REGION=us-east-1 \
/usr/bin/aws --endpoint-url http://minio-service:9000 s3 mb s3://operator-testing'
}
deploy_vault() {
name=${1:-vault-service}
desc "install Vault $name"
helm uninstall vault-service || :
helm repo remove hashicorp || :
helm repo add hashicorp https://helm.releases.hashicorp.com
destroy_vault
if [[ -n ${OPENSHIFT} ]]; then
oc patch clusterrole system:auth-delegator --type='json' -p '[{"op":"add","path":"/rules/-", "value":{"apiGroups":["security.openshift.io"], "resourceNames": ["privileged"], "resources":["securitycontextconstraints"],"verbs":["use"]}}]'
retry 10 60 helm install $name hashicorp/vault \
--disable-openapi-validation \
--set dataStorage.enabled=false \
--set global.openshift=true \
--set injector.image.repository="docker.io/hashicorp/vault-k8s" \
--set injector.agentImage.repository="docker.io/hashicorp/vault" \
--set server.image.repository="docker.io/hashicorp/vault"
else
retry 10 60 helm install $name hashicorp/vault \
--disable-openapi-validation \
--set dataStorage.enabled=false
fi
until kubectl_bin get pod/vault-service-0 -o jsonpath='{.status.phase}' 2>/dev/null | grep 'Running'; do
sleep 1
done
kubectl_bin exec pod/vault-service-0 -- vault operator init -key-shares=1 -key-threshold=1 -format=json >"${tmp_dir}"/vault-init
local unsealKey=$(jq -r ".unseal_keys_b64[]" <"${tmp_dir}"/vault-init)
local token=$(jq -r ".root_token" <"${tmp_dir}"/vault-init)
kubectl_bin exec pod/vault-service-0 -- vault operator unseal "${unsealKey}"
kubectl_bin exec -it pod/vault-service-0 -- sh <<EOF
vault login "${token}"
vault secrets enable -path secret kv-v2
EOF
kubectl_bin create secret generic vault-secret --from-literal=token="${token}"
}
destroy_vault() {
local vault_ns=$(helm list --all-namespaces --filter vault-service | tail -n1 | awk -F' ' '{print $2}' | sed 's/NAMESPACE//')
desc 'destroy vault'
for i in $(kubectl api-resources | grep vault | awk '{print $1}'); do timeout 30 kubectl delete ${i} --all --all-namespaces || :; done
if [ -n "${vault_ns}" ]; then
helm uninstall vault-service --namespace ${vault_ns} || :
fi
timeout 30 kubectl delete crd $(kubectl get crd | grep 'vault' | awk '{print $1}') || :
timeout 30 kubectl delete clusterrolebinding $(kubectl get clusterrolebinding | grep 'vault' | awk '{print $1}') || :
timeout 30 kubectl delete clusterrole $(kubectl get clusterrole | grep 'vault' | awk '{print $1}') || :
timeout 30 kubectl delete mutatingwebhookconfiguration $(kubectl get mutatingwebhookconfiguration | grep 'vault' | awk '{print $1}') || :
}
deploy_chaos_mesh() {
local chaos_mesh_ns=$1
destroy_chaos_mesh
desc 'install chaos-mesh'
helm repo add chaos-mesh https://charts.chaos-mesh.org
helm install chaos-mesh chaos-mesh/chaos-mesh --namespace=${chaos_mesh_ns} --set chaosDaemon.runtime=containerd --set chaosDaemon.socketPath=/run/containerd/containerd.sock --set dashboard.create=false --version 2.5.1
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//')
desc 'destroy chaos-mesh'
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}') || :
}
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
}
wait_for_running() {
local name="$1"
let last_pod="$(($2 - 1))" || :
local check_cluster_readyness="${3:-true}"
set_debug
local rs_name=${name/*-/}
local cluster_name=${name/-$rs_name/}
for i in $(seq 0 $last_pod); do
if [[ $i -eq $last_pod && $(kubectl_bin get psmdb ${cluster_name} -o jsonpath='{.spec.replsets[?(@.name=="'${rs_name}'")].arbiter.enabled}') == "true" ]]; then
wait_pod ${name}-arbiter-0
else
wait_pod ${name}-${i}
fi
done
if [[ $(kubectl_bin get psmdb ${cluster_name} -o jsonpath='{.spec.replsets[?(@.name=="'${rs_name}'")].non_voting.enabled}') == "true" ]]; then
last_pod=$(($(kubectl_bin get psmdb ${cluster_name} -o jsonpath='{.spec.replsets[?(@.name=="'${rs_name}'")].non_voting.size}') - 1))
for i in $(seq 0 $last_pod); do
wait_pod ${name}-nv-${i}
done
fi
sleep 10
if [[ ${check_cluster_readyness} == "true" ]]; then
set +x
echo -n "Waiting for cluster readyness"
local timeout=0
until [[ $(kubectl_bin get psmdb ${cluster_name} -o jsonpath={.status.state}) == "ready" ]]; do
sleep 1
timeout=$((timeout + 1))
echo -n '.'
if [[ ${timeout} -gt 1500 ]]; then
echo
echo "Waiting timeout has been reached. Exiting..."
exit 1
fi
done
echo
set_debug
fi
}
wait_for_delete() {
local res="$1"
local wait_time=${2:-60}
set +o xtrace
echo -n "waiting for $res to be deleted"
retry=0
until (kubectl_bin get $res || :) 2>&1 | grep NotFound; do
sleep 1
echo -n .
let retry+=1
if [ $retry -ge $wait_time ]; then
kubectl_bin logs ${OPERATOR_NS:+-n $OPERATOR_NS} $(get_operator_pod) \
| 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_debug
}
compare_generation() {
local generation="$1"
local resource_type="$2"
local resource_name="$3"
local current_generation
current_generation="$(kubectl_bin get ${resource_type} "${resource_name}" -o jsonpath='{.metadata.generation}')"
if [[ ${generation} != "${current_generation}" ]]; then
echo "Generation for ${resource_type}/${resource_name} is: ${current_generation}, but should be: ${generation}"
exit 1
fi
}
compare_kubectl() {
local resource="$1"
local postfix="$2"
local skip_generation_check="$3"
local expected_result=${test_dir}/compare/${resource//\//_}${postfix}.yml
local new_result="${tmp_dir}/${resource//\//_}.yml"
if [ -n "$OPENSHIFT" -a -f ${expected_result//.yml/-oc.yml} ]; then
desc "OPENSHIFT"
expected_result=${expected_result//.yml/-oc.yml}
if [ "$OPENSHIFT" = 4 -a -f ${expected_result//-oc.yml/-4-oc.yml} ]; then
expected_result=${expected_result//-oc.yml/-4-oc.yml}
fi
fi
kubectl_bin get -o yaml ${resource} \
| yq eval '
del(.metadata.ownerReferences[].apiVersion) |
del(.metadata.managedFields) |
del(.. | select(has("creationTimestamp")).creationTimestamp) |
del(.. | select(has("namespace")).namespace) |
del(.. | select(has("uid")).uid) |
del(.metadata.resourceVersion) |
del(.spec.template.spec.containers[].env[] | select(.name == "NAMESPACE")) |
del(.metadata.selfLink) |
del(.metadata.annotations."cloud.google.com/neg") |
del(.metadata.annotations."kubectl.kubernetes.io/last-applied-configuration") |
del(.. | select(has("image")).image) |
del(.. | select(has("clusterIP")).clusterIP) |
del(.. | select(has("clusterIPs")).clusterIPs) |
del(.. | select(has("dataSource")).dataSource) |
del(.. | select(has("procMount")).procMount) |
del(.. | select(has("storageClassName")).storageClassName) |
del(.. | select(has("finalizers")).finalizers) |
del(.. | select(has("kubernetes.io/pvc-protection"))."kubernetes.io/pvc-protection") |
del(.. | select(has("volumeName")).volumeName) |
del(.. | select(has("volume.beta.kubernetes.io/storage-provisioner"))."volume.beta.kubernetes.io/storage-provisioner") |
del(.. | select(has("volume.kubernetes.io/storage-provisioner"))."volume.kubernetes.io/storage-provisioner") |
del(.spec.volumeMode) |
del(.. | select(has("volume.kubernetes.io/selected-node"))."volume.kubernetes.io/selected-node") |
del(.. | select(has("percona.com/last-config-hash"))."percona.com/last-config-hash") |
del(.. | select(has("percona.com/configuration-hash"))."percona.com/configuration-hash") |
del(.. | select(has("percona.com/ssl-hash"))."percona.com/ssl-hash") |
del(.. | select(has("percona.com/ssl-internal-hash"))."percona.com/ssl-internal-hash") |
del(.spec.volumeClaimTemplates[].spec.volumeMode | select(. == "Filesystem")) |
del(.. | select(has("healthCheckNodePort")).healthCheckNodePort) |
del(.. | select(has("nodePort")).nodePort) |
del(.status) |
(.. | select(tag == "!!str")) |= sub("'$namespace'", "NAME_SPACE") |
del(.spec.volumeClaimTemplates[].apiVersion) |
del(.spec.volumeClaimTemplates[].kind) |
del(.spec.ipFamilies) |
del(.spec.ipFamilyPolicy) |
(.. | select(. == "extensions/v1beta1")) = "apps/v1" |
(.. | select(. == "batch/v1beta1")) = "batch/v1" ' - >${new_result}
yq -i eval 'del(.spec.persistentVolumeClaimRetentionPolicy)' ${new_result}
if version_gt "1.22"; then
yq -i eval 'del(.spec.internalTrafficPolicy)' ${new_result}
yq -i eval 'del(.spec.allocateLoadBalancerNodePorts)' ${new_result}
if [[ ${expected_result} == */cronjob* ]]; then
yq -i eval 'del(.metadata.generation)' ${new_result}
fi
fi
if [ -n "$skip_generation_check" ]; then
yq -i eval 'del(.metadata.generation)' ${new_result}
fi
diff -u "$expected_result" "$new_result"
}
run_mongo() {
local command="$1"
local uri="$2"
local driver=${3:-mongodb+srv}
local suffix=${4:-.svc.cluster.local}
local client_container=$(kubectl_bin get pods --selector=name=psmdb-client -o 'jsonpath={.items[].metadata.name}')
local mongo_flag="$5"
[[ $uri == *cfg* ]] && replica_set='cfg' || replica_set='rs0'
kubectl_bin exec ${client_container} -- \
bash -c "printf '$command\n' | mongo $driver://$uri$suffix/admin?ssl=false\&replicaSet=$replica_set $mongo_flag"
}
run_mongosh() {
local command="$1"
local uri="$2"
local driver=${3:-"mongodb+srv"}
local suffix=${4:-".svc.cluster.local"}
local mongo_flag="$5"
local client_container=$(kubectl_bin get pods --selector=name=psmdb-client -o 'jsonpath={.items[].metadata.name}')
[[ $uri == *cfg* ]] && replica_set='cfg' || replica_set='rs0'
kubectl_bin exec ${client_container} -- \
bash -c "printf '$command\n' | mongosh --quiet $driver://$uri$suffix/admin?ssl=false\&replicaSet=$replica_set $mongo_flag"
}
run_mongo_tls() {
local command="$1"
local uri="$2"
local driver=${3:-mongodb+srv}
local suffix=${4:-.svc.cluster.local}
local client_container=$(kubectl_bin get pods --selector=name=psmdb-client -o 'jsonpath={.items[].metadata.name}')
local mongo_flag="$5"
local port=${6:-"27017"}
suffix_port=$(echo "$suffix" | awk -F':' '{print $2}')
if [[ -z $suffix_port ]]; then
suffix="$suffix:$port"
fi
[[ $uri == *cfg* ]] && replica_set='cfg' || replica_set='rs0'
kubectl_bin exec ${client_container} -- \
bash -c "printf '$command\n' | mongo $driver://$uri$suffixt/admin?replicaSet=$replica_set --tls --tlsCAFile /etc/mongodb-ssl/ca.crt --tlsCertificateKeyFile /tmp/tls.pem --tlsAllowInvalidHostnames $mongo_flag"
}
run_mongos() {
local command="$1"
local uri="$2"
local driver=${3:-mongodb}
local suffix=${4:-.svc.cluster.local}
local mongo_flag="$5"
local port=${6:-"27017"}
local mongo_bin=${7:-mongo}
suffix_port=$(echo "$suffix" | awk -F':' '{print $2}')
if [[ -z $suffix_port ]]; then
suffix="$suffix:$port"
fi
local client_container=$(kubectl_bin get pods --selector=name=psmdb-client -o 'jsonpath={.items[].metadata.name}')
kubectl_bin exec ${client_container} -- \
bash -c "printf '$command\n' | ${mongo_bin} $driver://$uri$suffix/admin $mongo_flag"
}
run_script_mongos() {
local script="$1"
local uri="$2"
local driver=${3:-mongodb}
local suffix=${4:-.svc.cluster.local}
local mongo_flag="$5"
local mongo_bin=${6:-mongo}
local client_container=$(kubectl_bin get pods --selector=name=psmdb-client -o 'jsonpath={.items[].metadata.name}')
name="$(basename $script)"
kubectl_bin cp ${script} $namespace/${client_container}:/tmp
kubectl_bin exec ${client_container} -- \
bash -c "${mongo_bin} $driver://$uri$suffix/admin $mongo_flag /tmp/${name}"
}
get_pmm_service_ip() {
local service=$1
while (kubectl_bin get service/$service -o 'jsonpath={.spec.type}' 2>&1 || :) | grep -q NotFound; do
sleep 1
done
until kubectl_bin get service/$service -o 'jsonpath={.status.loadBalancer.ingress[]}' 2>&1 | egrep -q "hostname|ip"; do
sleep 1
done
kubectl_bin get service/$service -o 'jsonpath={.status.loadBalancer.ingress[].ip}'
kubectl_bin get service/$service -o 'jsonpath={.status.loadBalancer.ingress[].hostname}'
}
get_service_ip() {
local service=$1
local server_type=${2:-rs0}
if [ "$(kubectl_bin get psmdb/${service/-$server_type*/} -o 'jsonpath={.spec.replsets[].expose.enabled}')" != "true" ]; then
echo -n $service.${service/-rs0*/}-rs0
return
fi
while (kubectl_bin get service/$service -o 'jsonpath={.spec.type}' 2>&1 || :) | grep -q NotFound; do
sleep 1
done
service_type=$(kubectl_bin get service/"$service" -o 'jsonpath={.spec.type}')
if [ "$service_type" = "ClusterIP" ] || [ "$service_type" = "NodePort" ]; then
kubectl_bin get service/$service -o 'jsonpath={.spec.clusterIP}'
return
fi
until kubectl_bin get service/$service -o 'jsonpath={.status.loadBalancer.ingress[]}' 2>&1 | egrep -q "hostname|ip"; do
sleep 1
done
kubectl_bin get service/$service -o 'jsonpath={.status.loadBalancer.ingress[].ip}'
kubectl_bin get service/$service -o 'jsonpath={.status.loadBalancer.ingress[].hostname}'
}
compare_mongo_cmd() {
local command="$1"
local uri="$2"
local postfix="$3"
local suffix="$4"
local database="${5:-myApp}"
local collection="${6:-test}"
run_mongo "use ${database}\n db.${collection}.${command}()" "$uri" "mongodb" "$suffix" \
| egrep -v 'I NETWORK|W NETWORK|F NETWORK|Error saving history file|Percona Server for MongoDB|connecting to:|Unable to reach primary for set|Implicit session:|versions do not match|Error saving history file:' \
| $sed -re 's/ObjectId\("[0-9a-f]+"\)//; s/-[0-9]+.svc/-xxx.svc/' \
>$tmp_dir/${command}${postfix}
diff -u ${test_dir}/compare/${command}${postfix}.json $tmp_dir/${command}${postfix}
}
compare_mongos_cmd() {
local command="$1"
local uri="$2"
local postfix="$3"
local suffix="$4"
local database="${5:-myApp}"
local collection="${6:-test}"
local port="${7:-27017}"
run_mongos "use ${database}\n db.${collection}.${command}()" "$uri" "mongodb" "$suffix" "" "$port" \
| egrep -v 'I NETWORK|W NETWORK|Error saving history file|Percona Server for MongoDB|connecting to:|Unable to reach primary for set|Implicit session:|versions do not match|Error saving history file:' \
| $sed -re 's/ObjectId\("[0-9a-f]+"\)//; s/-[0-9]+.svc/-xxx.svc/' \
>$tmp_dir/${command}${postfix}
diff ${test_dir}/compare/${command}${postfix}.json $tmp_dir/${command}${postfix}
}
get_mongo_primary_endpoint() {
local uri="$1"
run_mongo 'db.isMaster().me' "$uri" "mongodb" ":27017" \
| egrep -v "Time|Percona Server for MongoDB|bye|BinData|NumberLong|connecting to|Error saving history file|I NETWORK|W NETWORK|Implicit session:|versions do not match" \
| sed -e 's^20[0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\.[0-9][0-9][0-9]+[0-9][0-9][0-9][0-9]^^' \
| grep ":27017$"
}
get_mongo_primary() {
local uri="$1"
local cluster="$2"
set_debug
endpoint=$(get_mongo_primary_endpoint $uri)
if [[ $endpoint =~ ".$cluster" ]]; then
echo $endpoint \
| cut -d . -f 1
else
kubectl_bin get service -o wide \
| grep " ${endpoint/:*/} " \
| awk '{print $1}'
fi
}
compare_mongo_user() {
local uri="$1"
local user="$2"
local expected_result=${test_dir}/compare/$user.json
if [[ $IMAGE_MONGOD =~ 4\.0 ]] && [ -f ${test_dir}/compare/$user-40.json ]; then
expected_result=${test_dir}/compare/$user-40.json
fi
if [[ $IMAGE_MONGOD =~ 4\.2 ]] && [ -f ${test_dir}/compare/$user-42.json ]; then
expected_result=${test_dir}/compare/$user-42.json
fi
if [[ $IMAGE_MONGOD =~ 4\.4 ]] && [ -f ${test_dir}/compare/$user-44.json ]; then
expected_result=${test_dir}/compare/$user-44.json
fi
if [[ $IMAGE_MONGOD =~ 5\.0 ]] && [ -f ${test_dir}/compare/$user-50.json ]; then
expected_result=${test_dir}/compare/$user-50.json
fi
if [[ $IMAGE_MONGOD =~ 6\.0 ]] && [ -f ${test_dir}/compare/$user-60.json ]; then
expected_result=${test_dir}/compare/$user-60.json
fi
if [[ $IMAGE_MONGOD =~ 7\.0 ]] && [ -f ${test_dir}/compare/$user-70.json ]; then
expected_result=${test_dir}/compare/$user-70.json
fi
if [[ $IMAGE_MONGOD =~ 8\.0 ]] && [ -f ${test_dir}/compare/$user-80.json ]; then
expected_result=${test_dir}/compare/$user-80.json
fi
run_mongo 'db.runCommand({connectionStatus:1,showPrivileges:true})' "$uri" \
| egrep -v "Time|Percona Server for MongoDB|bye|BinData|NumberLong|connecting to|Error saving history file|I NETWORK|W NETWORK|Implicit session:|versions do not match" \
| sed -e 's^20[0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\.[0-9][0-9][0-9]+[0-9][0-9][0-9][0-9]^^' \
| $sed -e '/"ok" : 1/,+4d' \
| sed -e '$s/,$/}/' \
| jq '.authInfo.authenticatedUserPrivileges|=sort_by(.resource.anyResource, .resource.cluster, .resource.db, .resource.collection)|.authInfo.authenticatedUserRoles|=sort_by(.role)' \
>$tmp_dir/$user.json
diff -u $expected_result $tmp_dir/$user.json
}
start_gke() {
gcloud container clusters create operator-testing-$RANDOM --zone europe-west3-c --project cloud-dev-112233 --preemptible --cluster-version 1.11
}
get_pumba() {
kubectl_bin get pods \
--selector=name=pumba \
-o 'jsonpath={.items[].metadata.name}'
}
run_pumba() {
local cmd="$*"
kubectl_bin exec -it "$(get_pumba)" -- /pumba -l info ${cmd}
}
deploy_cert_manager() {
desc 'deploy cert manager'
kubectl_bin create namespace cert-manager || :
kubectl_bin label namespace cert-manager certmanager.k8s.io/disable-validation=true || :
kubectl_bin apply -f "https://github.com/cert-manager/cert-manager/releases/download/v${CERT_MANAGER_VER}/cert-manager.yaml" --validate=false || : 2>/dev/null
kubectl_bin -n cert-manager wait pod -l app.kubernetes.io/instance=cert-manager --for=condition=ready
sleep 120
}
delete_crd() {
desc 'get and delete old CRDs and RBAC'
kubectl_bin delete -f "${src_dir}/deploy/crd.yaml" --ignore-not-found --wait=false || :
for crd_name in $(yq eval '.metadata.name' "${src_dir}/deploy/crd.yaml" | grep -v '\-\-\-'); do
kubectl get ${crd_name} --all-namespaces -o wide \
| grep -v 'NAMESPACE' \
| xargs -L 1 sh -xc 'kubectl patch '${crd_name}' -n $0 $1 --type=merge -p "{\"metadata\":{\"finalizers\":[]}}"' \
|| :
kubectl_bin wait --for=delete crd ${crd_name} || :
done
local rbac_yaml='rbac.yaml'
if [ -n "${OPERATOR_NS}" ]; then
rbac_yaml='cw-rbac.yaml'
fi
kubectl_bin delete -f "${src_dir}/deploy/$rbac_yaml" --ignore-not-found || true
}
destroy() {
local namespace="$1"
local ignore_logs="${2:-true}"
desc 'destroy cluster/operator and all other resources'
if [ ${ignore_logs} == "false" ] && [ "${DEBUG_TESTS}" == 1 ]; then
kubectl_bin logs ${OPERATOR_NS:+-n $OPERATOR_NS} $(get_operator_pod) \
| grep -v 'level=info' \
| grep -v 'level=debug' \
| grep -v 'Getting tasks for pod' \
| grep -v 'Getting pods from source' \
| grep -v 'the object has been modified' \
| grep -v 'get backup status: Job.batch' \
| $sed -r 's/"ts":[0-9.]+//; s^limits-[0-9.]+/^^g' \
| sort -u \
| tee $tmp_dir/operator.log
fi
#TODO: maybe will be enabled later
#diff $test_dir/compare/operator.log $tmp_dir/operator.log