forked from cloudnative-pg/cloudnative-pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup-cluster.sh
executable file
·803 lines (673 loc) · 25.1 KB
/
setup-cluster.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
#!/usr/bin/env bash
##
## Copyright The CloudNativePG Contributors
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
# standard bash error handling
set -eEuo pipefail
if [ "${DEBUG-}" = true ]; then
set -x
fi
# Defaults
KIND_NODE_DEFAULT_VERSION=v1.32.0
K3D_NODE_DEFAULT_VERSION=v1.30.3
CSI_DRIVER_HOST_PATH_DEFAULT_VERSION=v1.15.0
EXTERNAL_SNAPSHOTTER_VERSION=v8.2.0
EXTERNAL_PROVISIONER_VERSION=v5.1.0
EXTERNAL_RESIZER_VERSION=v1.13.1
EXTERNAL_ATTACHER_VERSION=v4.8.0
K8S_VERSION=${K8S_VERSION-}
KUBECTL_VERSION=${KUBECTL_VERSION-}
CSI_DRIVER_HOST_PATH_VERSION=${CSI_DRIVER_HOST_PATH_VERSION:-$CSI_DRIVER_HOST_PATH_DEFAULT_VERSION}
ENGINE=${CLUSTER_ENGINE:-kind}
ENABLE_REGISTRY=${ENABLE_REGISTRY:-}
ENABLE_PYROSCOPE=${ENABLE_PYROSCOPE:-}
ENABLE_CSI_DRIVER=${ENABLE_CSI_DRIVER:-}
ENABLE_APISERVER_AUDIT=${ENABLE_APISERVER_AUDIT:-}
NODES=${NODES:-3}
# This option is telling the docker to use node image with certain arch, i.e kindest/node in kind.
# In M1/M2, if enable amd64 emulation then we keep it as linux/amd64.
# if did not enable amd64 emulation we need keep it as linux/arm64, otherwise, kind will not start success
DOCKER_DEFAULT_PLATFORM=${DOCKER_DEFAULT_PLATFORM:-}
# Testing the upgrade will require generating a second operator image, `-prime`
# The `load()` function will build and push this second image by default.
# The TEST_UPGRADE_TO_V1 can be set to false to skip this part of `load()`
TEST_UPGRADE_TO_V1=${TEST_UPGRADE_TO_V1:-true}
# Define the directories used by the script
ROOT_DIR=$(cd "$(dirname "$0")/../"; pwd)
HACK_DIR="${ROOT_DIR}/hack"
E2E_DIR="${HACK_DIR}/e2e"
TEMP_DIR="$(mktemp -d)"
LOG_DIR=${LOG_DIR:-$ROOT_DIR/_logs/}
trap 'rm -fr ${TEMP_DIR}' EXIT
# Operating System and Architecture
OS=$(uname | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case $ARCH in
x86_64) ARCH="amd64" ;;
aarch64) ARCH="arm64" ;;
esac
# If arm64 and user did not set it explicitly
if [ "${ARCH}" = "arm64" ] && [ "${DOCKER_DEFAULT_PLATFORM}" = "" ]; then
DOCKER_DEFAULT_PLATFORM=linux/arm64
fi
export DOCKER_DEFAULT_PLATFORM
# Constants
registry_volume=registry_dev_data
registry_name=registry.dev
# #########################################################################
# IMPORTANT: here we build a catalog of images that will be needed in the
# test run. The goal here is to pre-load all the images that are part of the
# HELPER_IMGS variable in the local container registry.
# #########################################################################
POSTGRES_IMG=${POSTGRES_IMG:-$(grep 'DefaultImageName.*=' "${ROOT_DIR}/pkg/versions/versions.go" | cut -f 2 -d \")}
E2E_PRE_ROLLING_UPDATE_IMG=${E2E_PRE_ROLLING_UPDATE_IMG:-${POSTGRES_IMG%.*}}
PGBOUNCER_IMG=${PGBOUNCER_IMG:-$(grep 'DefaultPgbouncerImage.*=' "${ROOT_DIR}/pkg/specs/pgbouncer/deployments.go" | cut -f 2 -d \")}
MINIO_IMG=${MINIO_IMG:-$(grep 'minioImage.*=' "${ROOT_DIR}/tests/utils/minio/minio.go" | cut -f 2 -d \")}
APACHE_IMG=${APACHE_IMG:-"httpd"}
HELPER_IMGS=("$POSTGRES_IMG" "$E2E_PRE_ROLLING_UPDATE_IMG" "$PGBOUNCER_IMG" "$MINIO_IMG" "$APACHE_IMG")
# #########################################################################
# Colors (only if using a terminal)
bright=
reset=
if [ -t 1 ]; then
bright=$(tput bold 2>/dev/null || true)
reset=$(tput sgr0 2>/dev/null || true)
fi
##
## KIND SUPPORT
##
install_kind() {
local bindir=$1
local binary="${bindir}/kind"
local version
# Get the latest release of kind unless specified in the environment
version=${KIND_VERSION:-$(
curl -s -LH "Accept:application/json" https://github.com/kubernetes-sigs/kind/releases/latest |
sed 's/.*"tag_name":"\([^"]\+\)".*/\1/'
)}
curl -s -L "https://kind.sigs.k8s.io/dl/${version}/kind-${OS}-${ARCH}" -o "${binary}"
chmod +x "${binary}"
}
load_image_kind() {
local cluster_name=$1
local image=$2
kind load -v 1 docker-image --name "${cluster_name}" "${image}"
}
create_cluster_kind() {
local k8s_version=$1
local cluster_name=$2
# Create kind config
config_file="${TEMP_DIR}/kind-config.yaml"
cat >"${config_file}" <<-EOF
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
networking:
apiServerAddress: "0.0.0.0"
kubeProxyMode: "ipvs"
# add to the apiServer certSANs the name of the docker (dind) service in order to be able to reach the cluster through it
kubeadmConfigPatchesJSON6902:
- group: kubeadm.k8s.io
version: v1beta2
kind: ClusterConfiguration
patch: |
- op: add
path: /apiServer/certSANs/-
value: docker
nodes:
- role: control-plane
EOF
if [ "${ENABLE_APISERVER_AUDIT}" = "true" ]; then
# Create the apiserver audit log directory beforehand, otherwise it will be
# generated within docker with root permissions
mkdir -p "${LOG_DIR}/apiserver"
touch "${LOG_DIR}/apiserver/kube-apiserver-audit.log"
cat >>"${config_file}" <<-EOF
kubeadmConfigPatches:
- |
kind: ClusterConfiguration
apiServer:
# enable auditing flags on the API server
extraArgs:
audit-log-path: /var/log/kubernetes/kube-apiserver-audit.log
audit-policy-file: /etc/kubernetes/policies/audit-policy.yaml
# mount new files / directories on the control plane
extraVolumes:
- name: audit-policies
hostPath: /etc/kubernetes/policies
mountPath: /etc/kubernetes/policies
readOnly: true
pathType: "DirectoryOrCreate"
- name: "audit-logs"
hostPath: "/var/log/kubernetes"
mountPath: "/var/log/kubernetes"
readOnly: false
pathType: DirectoryOrCreate
# mount the local file on the control plane
extraMounts:
- hostPath: ${E2E_DIR}/audit-policy.yaml
containerPath: /etc/kubernetes/policies/audit-policy.yaml
readOnly: true
- hostPath: ${LOG_DIR}/apiserver/
containerPath: /var/log/kubernetes/
EOF
fi
if [ "$NODES" -gt 1 ]; then
for ((i = 0; i < NODES; i++)); do
echo '- role: worker' >>"${config_file}"
done
fi
if [ -n "${DOCKER_REGISTRY_MIRROR:-}" ] || [ -n "${ENABLE_REGISTRY:-}" ]; then
# Add containerdConfigPatches section
cat >>"${config_file}" <<-EOF
containerdConfigPatches:
EOF
if [ -n "${DOCKER_REGISTRY_MIRROR:-}" ]; then
cat >>"${config_file}" <<-EOF
- |-
[plugins."io.containerd.grpc.v1.cri".registry.mirrors."docker.io"]
endpoint = ["${DOCKER_REGISTRY_MIRROR}"]
EOF
fi
if [ -n "${ENABLE_REGISTRY:-}" ]; then
cat >>"${config_file}" <<-EOF
- |-
[plugins."io.containerd.grpc.v1.cri".registry.mirrors."${registry_name}:5000"]
endpoint = ["http://${registry_name}:5000"]
EOF
fi
fi
# Create the cluster
kind create cluster --name "${cluster_name}" --image "kindest/node:${k8s_version}" --config "${config_file}"
if [ -n "${ENABLE_REGISTRY:-}" ]; then
docker network connect "kind" "${registry_name}" &>/dev/null || true
fi
# Workaround for https://kind.sigs.k8s.io/docs/user/known-issues/#pod-errors-due-to-too-many-open-files
for node in $(kind get nodes --name "${cluster_name}"); do
docker exec "$node" sysctl fs.inotify.max_user_watches=524288 fs.inotify.max_user_instances=512
done
}
export_logs_kind() {
local cluster_name=$1
kind export logs "${LOG_DIR}" --name "${cluster_name}"
}
destroy_kind() {
local cluster_name=$1
docker network disconnect "kind" "${registry_name}" &>/dev/null || true
kind delete cluster --name "${cluster_name}" || true
docker network rm "kind" &>/dev/null || true
}
check_registry_kind() {
[ -n "$(check_registry "kind")" ]
}
##
## K3D SUPPORT
##
install_k3d() {
local bindir=$1
curl -s https://raw.githubusercontent.com/rancher/k3d/main/install.sh | K3D_INSTALL_DIR=$bindir bash -s -- --no-sudo
}
create_cluster_k3d() {
local k8s_version=$1
local cluster_name=$2
local latest_k3s_tag
latest_k3s_tag=$(k3d version list k3s | grep -- "^${k8s_version//./\\.}"'\+-k3s[0-9]$' | tail -n 1)
local options=()
if [ -n "${DOCKER_REGISTRY_MIRROR:-}" ] || [ -n "${ENABLE_REGISTRY:-}" ]; then
config_file="${TEMP_DIR}/k3d-registries.yaml"
cat >"${config_file}" <<-EOF
mirrors:
EOF
if [ -n "${DOCKER_REGISTRY_MIRROR:-}" ]; then
cat >>"${config_file}" <<-EOF
"docker.io":
endpoint:
- "${DOCKER_REGISTRY_MIRROR}"
EOF
fi
if [ -n "${ENABLE_REGISTRY:-}" ]; then
cat >>"${config_file}" <<-EOF
"${registry_name}:5000":
endpoint:
- http://${registry_name}:5000
EOF
fi
options+=(--registry-config "${config_file}")
fi
local agents=()
if [ "$NODES" -gt 1 ]; then
agents=(-a "${NODES}")
fi
K3D_FIX_MOUNTS=1 k3d cluster create "${options[@]}" "${agents[@]}" -i "rancher/k3s:${latest_k3s_tag}" --no-lb "${cluster_name}" \
--k3s-arg "--disable=traefik@server:0" --k3s-arg "--disable=metrics-server@server:0" \
--k3s-arg "--node-taint=node-role.kubernetes.io/master:NoSchedule@server:0" #wokeignore:rule=master
if [ -n "${ENABLE_REGISTRY:-}" ]; then
docker network connect "k3d-${cluster_name}" "${registry_name}" &>/dev/null || true
fi
}
load_image_k3d() {
local cluster_name=$1
local image=$2
k3d image import "${image}" -c "${cluster_name}"
}
export_logs_k3d() {
local cluster_name=$1
while IFS= read -r line; do
NODES_LIST+=("$line")
done < <(k3d node list | awk "/${cluster_name}/{print \$1}")
for i in "${NODES_LIST[@]}"; do
mkdir -p "${LOG_DIR}/${i}"
docker cp -L "${i}:/var/log/." "${LOG_DIR}/${i}"
done
}
destroy_k3d() {
local cluster_name=$1
docker network disconnect "k3d-${cluster_name}" "${registry_name}" &>/dev/null || true
k3d cluster delete "${cluster_name}" || true
docker network rm "k3d-${cluster_name}" &>/dev/null || true
}
check_registry_k3d() {
[ -n "$(check_registry "k3d-${CLUSTER_NAME}")" ]
}
##
## GENERIC ROUTINES
##
install_kubectl() {
local bindir=$1
local binary="${bindir}/kubectl"
curl -sL "https://dl.k8s.io/release/v${KUBECTL_VERSION#v}/bin/${OS}/${ARCH}/kubectl" -o "${binary}"
chmod +x "${binary}"
}
# The following function makes sure we already have a Docker container
# with a bound volume to act as local registry. This is really needed
# to have an easy way to refresh the operator version that is running
# on the temporary cluster.
ensure_registry() {
[ -z "${ENABLE_REGISTRY:-}" ] && return
if ! docker volume inspect "${registry_volume}" &>/dev/null; then
docker volume create "${registry_volume}"
fi
if ! docker inspect "${registry_name}" &>/dev/null; then
docker container run -d --name "${registry_name}" -v "${registry_volume}:/var/lib/registry" --restart always -p 5000:5000 registry:2
fi
}
check_registry() {
local network=$1
docker network inspect "${network}" | \
jq -r ".[].Containers | .[] | select(.Name==\"${registry_name}\") | .Name"
}
deploy_fluentd() {
local FLUENTD_IMAGE=fluent/fluentd-kubernetes-daemonset:v1.14.3-debian-forward-1.0
local FLUENTD_LOCAL_IMAGE="${registry_name}:5000/fluentd-kubernetes-daemonset:local"
docker pull "${FLUENTD_IMAGE}"
docker tag "${FLUENTD_IMAGE}" "${FLUENTD_LOCAL_IMAGE}"
load_image "${CLUSTER_NAME}" "${FLUENTD_LOCAL_IMAGE}"
# Add fluentd service to export logs
kubectl apply -f "${E2E_DIR}/local-fluentd.yaml"
# Run the tests and destroy the cluster
# Do not fail out if the tests fail. We want the logs anyway.
ITER=0
NODE=$(kubectl get nodes --no-headers | wc -l | tr -d " ")
while true; do
if [[ $ITER -ge 300 ]]; then
echo "Time out waiting for FluentD readiness"
exit 1
fi
NUM_READY=$(kubectl get ds fluentd -n kube-system -o jsonpath='{.status.numberReady}')
if [[ "$NUM_READY" == "$NODE" ]]; then
echo "FluentD is Ready"
break
fi
sleep 1
((++ITER))
done
}
deploy_csi_host_path() {
echo "${bright}Starting deployment of CSI driver plugin... ${reset}"
CSI_BASE_URL=https://raw.githubusercontent.com/kubernetes-csi
## Install external snapshotter CRD
kubectl apply -f "${CSI_BASE_URL}"/external-snapshotter/"${EXTERNAL_SNAPSHOTTER_VERSION}"/client/config/crd/snapshot.storage.k8s.io_volumesnapshotclasses.yaml
kubectl apply -f "${CSI_BASE_URL}"/external-snapshotter/"${EXTERNAL_SNAPSHOTTER_VERSION}"/client/config/crd/snapshot.storage.k8s.io_volumesnapshotcontents.yaml
kubectl apply -f "${CSI_BASE_URL}"/external-snapshotter/"${EXTERNAL_SNAPSHOTTER_VERSION}"/client/config/crd/snapshot.storage.k8s.io_volumesnapshots.yaml
kubectl apply -f "${CSI_BASE_URL}"/external-snapshotter/"${EXTERNAL_SNAPSHOTTER_VERSION}"/deploy/kubernetes/snapshot-controller/rbac-snapshot-controller.yaml
kubectl apply -f "${CSI_BASE_URL}"/external-snapshotter/"${EXTERNAL_SNAPSHOTTER_VERSION}"/deploy/kubernetes/snapshot-controller/setup-snapshot-controller.yaml
kubectl apply -f "${CSI_BASE_URL}"/external-snapshotter/"${EXTERNAL_SNAPSHOTTER_VERSION}"/deploy/kubernetes/csi-snapshotter/rbac-csi-snapshotter.yaml
## Install external provisioner
kubectl apply -f "${CSI_BASE_URL}"/external-provisioner/"${EXTERNAL_PROVISIONER_VERSION}"/deploy/kubernetes/rbac.yaml
## Install external attacher
kubectl apply -f "${CSI_BASE_URL}"/external-attacher/"${EXTERNAL_ATTACHER_VERSION}"/deploy/kubernetes/rbac.yaml
## Install external resizer
kubectl apply -f "${CSI_BASE_URL}"/external-resizer/"${EXTERNAL_RESIZER_VERSION}"/deploy/kubernetes/rbac.yaml
## Install driver and plugin
kubectl apply -f "${CSI_BASE_URL}"/csi-driver-host-path/"${CSI_DRIVER_HOST_PATH_VERSION}"/deploy/kubernetes-1.27/hostpath/csi-hostpath-driverinfo.yaml
kubectl apply -f "${CSI_BASE_URL}"/csi-driver-host-path/"${CSI_DRIVER_HOST_PATH_VERSION}"/deploy/kubernetes-1.27/hostpath/csi-hostpath-plugin.yaml
## create volumesnapshotclass
kubectl apply -f "${CSI_BASE_URL}"/csi-driver-host-path/"${CSI_DRIVER_HOST_PATH_VERSION}"/deploy/kubernetes-1.27/hostpath/csi-hostpath-snapshotclass.yaml
## Prevent VolumeSnapshot E2e test to fail when taking a
## snapshot of a running PostgreSQL instance
kubectl patch volumesnapshotclass csi-hostpath-snapclass -p '{"parameters":{"ignoreFailedRead":"true"}}' --type merge
## create storage class
kubectl apply -f "${CSI_BASE_URL}"/csi-driver-host-path/"${CSI_DRIVER_HOST_PATH_VERSION}"/examples/csi-storageclass.yaml
kubectl annotate storageclass csi-hostpath-sc storage.kubernetes.io/default-snapshot-class=csi-hostpath-snapclass
echo "${bright} CSI driver plugin deployment has started. Waiting for the CSI plugin to be ready... ${reset}"
ITER=0
while true; do
if [[ $ITER -ge 300 ]]; then
echo "${bright}Timeout: The CSI plugin did not become ready within the expected time.${reset}"
exit 1
fi
NUM_SPEC=$(kubectl get statefulset csi-hostpathplugin -o jsonpath='{.spec.replicas}')
NUM_STATUS=$(kubectl get statefulset csi-hostpathplugin -o jsonpath='{.status.availableReplicas}')
if [[ "$NUM_SPEC" == "$NUM_STATUS" ]]; then
echo "${bright}Success: The CSI plugin is deployed and ready.${reset}"
break
fi
sleep 1
((++ITER))
done
}
deploy_pyroscope() {
helm repo add pyroscope-io https://grafana.github.io/helm-charts
values_file="${TEMP_DIR}/pyroscope_values.yaml"
cat >"${values_file}" <<-EOF
pyroscopeConfigs:
log-level: "debug"
EOF
helm -n cnpg-system install pyroscope pyroscope-io/pyroscope -f "${values_file}"
service_file="${TEMP_DIR}/pyroscope_service.yaml"
cat >"${service_file}" <<-EOF
apiVersion: v1
kind: Service
metadata:
name: cnpg-pprof
spec:
ports:
- targetPort: 6060
port: 6060
selector:
app: cnpg-pprof
type: ClusterIP
selector:
app.kubernetes.io/name: cloudnative-pg
EOF
kubectl -n cnpg-system apply -f "${service_file}"
annotations="${TEMP_DIR}/pyroscope_annotations.yaml"
cat >"${annotations}" <<- EOF
spec:
template:
metadata:
annotations:
profiles.grafana.com/memory.scrape: "true"
profiles.grafana.com/memory.port: "6060"
profiles.grafana.com/cpu.scrape: "true"
profiles.grafana.com/cpu.port: "6060"
profiles.grafana.com/goroutine.scrape: "true"
profiles.grafana.com/goroutine.port: "6060"
EOF
kubectl -n cnpg-system patch deployment cnpg-controller-manager --patch-file "${annotations}"
}
deploy_prometheus_crds() {
echo "${bright}Starting deployment of Prometheus CRDs... ${reset}"
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm -n kube-system install prometheus-operator-crds prometheus-community/prometheus-operator-crds
}
load_image_registry() {
local image=$1
local image_local_name=${image/${registry_name}/127.0.0.1}
docker tag "${image}" "${image_local_name}"
docker push -q "${image_local_name}"
}
load_image() {
local cluster_name=$1
local image=$2
if [ -z "${ENABLE_REGISTRY:-}" ]; then
"load_image_${ENGINE}" "${cluster_name}" "${image}"
else
load_image_registry "${image}"
fi
}
deploy_operator() {
kubectl delete ns cnpg-system 2> /dev/null || :
make -C "${ROOT_DIR}" deploy "CONTROLLER_IMG=${CONTROLLER_IMG}"
}
usage() {
cat >&2 <<EOF
Usage: $0 [-e {kind|k3d}] [-k <version>] [-r] <command>
Commands:
prepare <dest_dir> Downloads the prerequisite into <dest_dir>
create Create the test cluster
load Build and load the operator image in the cluster
load-helper-images Load the catalog of HELPER_IMGS into the local registry
deploy Deploy the operator manifests in the cluster
print-image Print the CONTROLLER_IMG name to be used inside
the cluster
export-logs Export the logs from the cluster inside the directory
${LOG_DIR}
destroy Destroy the cluster
pyroscope Deploy Pyroscope inside operator namespace
Options:
-e|--engine
<CLUSTER_ENGINE> Use the provided ENGINE to run the cluster.
Available options are 'kind' and 'k3d'. Default 'kind'.
Env: CLUSTER_ENGINE
-k|--k8s-version
<K8S_VERSION> Use the specified kubernetes full version number
(e.g., v1.27.0). Env: K8S_VERSION
-n|--nodes
<NODES> Create a cluster with the required number of nodes.
Used only during "create" command. Default: 3
Env: NODES
-r|--registry Enable local registry. Env: ENABLE_REGISTRY
To use long options you need to have GNU enhanced getopt available, otherwise
you can only use the short version of the options.
EOF
exit 1
}
##
## COMMANDS
##
prepare() {
local bindir=$1
echo "${bright}Installing cluster prerequisites in ${bindir}${reset}"
install_kubectl "${bindir}"
"install_${ENGINE}" "${bindir}"
echo "${bright}Done installing cluster prerequisites in ${bindir}${reset}"
}
create() {
echo "${bright}Creating ${ENGINE} cluster ${CLUSTER_NAME} with version ${K8S_VERSION}${reset}"
"create_cluster_${ENGINE}" "${K8S_VERSION}" "${CLUSTER_NAME}"
# Support for docker:dind service
if [ "${DOCKER_HOST:-}" == "tcp://docker:2376" ]; then
sed -i -E -e 's/0\.0\.0\.0/docker/g' "${HOME}/.kube/config"
fi
deploy_fluentd
deploy_csi_host_path
deploy_prometheus_crds
echo "${bright}Done creating ${ENGINE} cluster ${CLUSTER_NAME} with version ${K8S_VERSION}${reset}"
}
load_helper_images() {
echo "${bright}Loading helper images for tests on cluster ${CLUSTER_NAME}${reset}"
# Here we pre-load all the images defined in the HELPER_IMGS variable
# with the goal to speed up the runs.
for IMG in "${HELPER_IMGS[@]}"; do
docker pull "${IMG}"
"load_image_${ENGINE}" "${CLUSTER_NAME}" "${IMG}"
done
echo "${bright}Done loading helper images on cluster ${CLUSTER_NAME}${reset}"
}
load() {
# NOTE: this function will build the operator from the current source
# tree and push it either to the local registry or the cluster nodes.
# It will do the same with a `prime` version for test purposes.
#
# This code will NEVER run in the cloud CI/CD workflows, as there we do
# the build and push (into GH test registry) once in `builds`, before
# the strategy matrix blows up the number of executables
if [ -z "${ENABLE_REGISTRY}" ] && "check_registry_${ENGINE}"; then
ENABLE_REGISTRY=true
fi
echo "${bright}Building operator from current worktree${reset}"
CONTROLLER_IMG="$(ENABLE_REGISTRY="${ENABLE_REGISTRY}" print_image)"
make -C "${ROOT_DIR}" CONTROLLER_IMG="${CONTROLLER_IMG}" ARCH="${ARCH}" docker-build
echo "${bright}Loading new operator image on cluster ${CLUSTER_NAME}${reset}"
load_image "${CLUSTER_NAME}" "${CONTROLLER_IMG}"
echo "${bright}Done loading new operator image on cluster ${CLUSTER_NAME}${reset}"
if [[ "${TEST_UPGRADE_TO_V1}" != "false" ]]; then
# In order to test the case of upgrading from the current operator
# to a future one, we build and push an image with a different VERSION
# to force a different hash for the manager binary.
# (Otherwise the ONLINE upgrade won't trigger)
echo "${bright}Building a 'prime' operator from current worktree${reset}"
PRIME_CONTROLLER_IMG="${CONTROLLER_IMG}-prime"
CURRENT_VERSION=$(make -C "${ROOT_DIR}" -s print-version)
PRIME_VERSION="${CURRENT_VERSION}-prime"
make -C "${ROOT_DIR}" CONTROLLER_IMG="${PRIME_CONTROLLER_IMG}" VERSION="${PRIME_VERSION}" \
ARCH="${ARCH}" docker-build
load_image "${CLUSTER_NAME}" "${PRIME_CONTROLLER_IMG}"
echo "${bright}Done loading new 'prime' operator image on cluster ${CLUSTER_NAME}${reset}"
fi
}
deploy() {
if [ -z "${ENABLE_REGISTRY}" ] && "check_registry_${ENGINE}"; then
ENABLE_REGISTRY=true
fi
CONTROLLER_IMG="$(ENABLE_REGISTRY="${ENABLE_REGISTRY}" print_image)"
echo "${bright}Deploying manifests from current worktree on cluster ${CLUSTER_NAME}${reset}"
deploy_operator
echo "${bright}Done deploying manifests from current worktree on cluster ${CLUSTER_NAME}${reset}"
}
print_image() {
local tag=devel
if [ -n "${ENABLE_REGISTRY:-}" ] || "check_registry_${ENGINE}"; then
tag=latest
fi
echo "${registry_name}:5000/cloudnative-pg:${tag}"
}
export_logs() {
echo "${bright}Exporting logs from cluster ${CLUSTER_NAME} to ${LOG_DIR}${reset}"
"export_logs_${ENGINE}" "${CLUSTER_NAME}"
echo "${bright}Done exporting logs from cluster ${CLUSTER_NAME} to ${LOG_DIR}${reset}"
}
destroy() {
echo "${bright}Destroying ${ENGINE} cluster ${CLUSTER_NAME}${reset}"
"destroy_${ENGINE}" "${CLUSTER_NAME}"
echo "${bright}Done destroying ${ENGINE} cluster ${CLUSTER_NAME}${reset}"
}
pyroscope() {
echo "${bright} Deploying Pyroscope${reset}"
deploy_pyroscope
echo "${bright} Done deploying Pyroscope${reset}"
}
##
## MAIN
##
main() {
if ! getopt -T > /dev/null; then
# GNU enhanced getopt is available
parsed_opts=$(getopt -o e:k:n:r -l "engine:,k8s-version:,nodes:,registry" -- "$@") || usage
else
# Original getopt is available
parsed_opts=$(getopt e:k:n:r "$@") || usage
fi
eval "set -- $parsed_opts"
for o; do
case "${o}" in
-e | --engine)
shift
ENGINE=$1
shift
if [ "${ENGINE}" != "kind" ] && [ "${ENGINE}" != "k3d" ]; then
echo "ERROR: ${ENGINE} is not a valid engine! [kind, k3d]" >&2
echo >&2
usage
fi
;;
-k | --k8s-version)
shift
K8S_VERSION="v${1#v}"
shift
if ! [[ $K8S_VERSION =~ ^v1\.[0-9]+\.[0-9]+$ ]]; then
echo "ERROR: $K8S_VERSION is not a valid k8s version!" >&2
echo >&2
usage
fi
;;
-n | --nodes)
shift
NODES="${1}"
shift
if ! [[ $NODES =~ ^[1-9][0-9]*$ ]]; then
echo "ERROR: $NODES is not a positive integer!" >&2
echo >&2
usage
fi
;;
-r | --registry)
shift
ENABLE_REGISTRY=true
;;
--)
shift
break
;;
esac
done
# Check if command is missing
if [ "$#" -eq 0 ]; then
echo "ERROR: you must specify a command" >&2
echo >&2
usage
fi
if [ -z "${K8S_VERSION}" ]; then
case "${ENGINE}" in
kind)
K8S_VERSION=${KIND_NODE_DEFAULT_VERSION}
;;
k3d)
K8S_VERSION=${K3D_NODE_DEFAULT_VERSION}
;;
esac
fi
KUBECTL_VERSION=${KUBECTL_VERSION:-$K8S_VERSION}
# Only here the K8S_VERSION veriable contains its final value
# so we can set the default cluster name
CLUSTER_NAME=${CLUSTER_NAME:-pg-operator-e2e-${K8S_VERSION//./-}}
while [ "$#" -gt 0 ]; do
command=$1
shift
# Invoke the command
case "$command" in
prepare)
if [ "$#" -eq 0 ]; then
echo "ERROR: prepare requires a destination directory" >&2
echo >&2
usage
fi
dest_dir=$1
shift
prepare "${dest_dir}"
;;
create | load | load-helper-images | deploy | print-image | export-logs | destroy | pyroscope)
ensure_registry
"${command//-/_}"
;;
*)
echo "ERROR: unknown command ${command}" >&2
echo >&2
usage
;;
esac
done
}
main "$@"