-
Notifications
You must be signed in to change notification settings - Fork 80
/
fdb_operator_client.go
742 lines (698 loc) · 22.9 KB
/
fdb_operator_client.go
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
/*
* fdb_operator_client.go
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2023 Apple Inc. and the FoundationDB project authors
*
* 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.
*/
package fixtures
import (
"bytes"
ctx "context"
"errors"
"fmt"
"html/template"
"io"
"log"
"strings"
"time"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
fdbv1beta2 "github.com/FoundationDB/fdb-kubernetes-operator/api/v1beta2"
"github.com/onsi/gomega"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer/yaml"
yamlutil "k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
operatorDeploymentName = "fdb-kubernetes-operator-controller-manager"
foundationdbServiceAccount = "fdb-kubernetes"
// The configuration for the RBAC setup for the operator deployment
operatorRBAC = `apiVersion: v1
kind: ServiceAccount
metadata:
name: fdb-kubernetes-operator-controller-manager
namespace: {{ .Namespace }}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: fdb-kubernetes-operator-manager-role
namespace: {{ .Namespace }}
rules:
- apiGroups:
- ""
resources:
- pods
- configmaps
- persistentvolumeclaims
- events
- secrets
- services
verbs:
- get
- watch
- list
- create
- update
- patch
- delete
- apiGroups:
- ""
resources:
- pods/exec
verbs:
- create
- apiGroups:
- apps.foundationdb.org
resources:
- foundationdbclusters
- foundationdbbackups
- foundationdbrestores
verbs:
- get
- list
- watch
- create
- update
- patch
- delete
- apiGroups:
- ""
resources:
- pods/exec
verbs:
- create
- apiGroups:
- apps.foundationdb.org
resources:
- foundationdbclusters/status
- foundationdbbackups/status
- foundationdbrestores/status
verbs:
- get
- update
- patch
- apiGroups:
- admissionregistration.k8s.io
resources:
- mutatingwebhookconfigurations
- validatingwebhookconfigurations
verbs:
- get
- list
- watch
- create
- update
- patch
- delete
- apiGroups:
- apps
resources:
- deployments
verbs:
- get
- list
- watch
- create
- update
- patch
- delete
- apiGroups:
- coordination.k8s.io
resources:
- leases
verbs:
- get
- list
- watch
- create
- update
- patch
- delete
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: fdb-kubernetes-operator-manager-rolebinding
namespace: {{ .Namespace }}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: fdb-kubernetes-operator-manager-role
subjects:
- kind: ServiceAccount
name: fdb-kubernetes-operator-controller-manager
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: {{ .Namespace }}-operator-manager-clusterrole
rules:
- apiGroups:
- ""
resources:
- nodes
verbs:
- get
- watch
- list
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: {{ .Namespace }}-operator-manager-clusterrolebinding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: {{ .Namespace }}-operator-manager-clusterrole
subjects:
- kind: ServiceAccount
name: fdb-kubernetes-operator-controller-manager
namespace: {{ .Namespace }}`
// operatorDeployment is a string that contains all the deployment settings used to deploy the operator.
// Embedding it as a string make the test suite portable.
operatorDeployment = `
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: fdb-kubernetes-operator-controller-manager
control-plane: controller-manager
name: fdb-kubernetes-operator-controller-manager
namespace: {{ .Namespace }}
spec:
replicas: 2
selector:
matchLabels:
app: fdb-kubernetes-operator-controller-manager
template:
metadata:
labels:
app: fdb-kubernetes-operator-controller-manager
control-plane: controller-manager
annotations:
prometheus.io/scrape: 'true'
prometheus.io/port: '8080'
spec:
initContainers:
{{ range $index, $version := .SidecarVersions }}
- name: foundationdb-kubernetes-init-{{ $index }}
image: {{ .BaseImage }}:{{ .SidecarTag}}
imagePullPolicy: {{ .ImagePullPolicy }}
command:
- /bin/bash
# This is a workaround for a change of the version schema that was never tested/supported
args:
- -c
- echo "{{ .FDBVersion.String }}" > /var/fdb/version && runuser -u fdb -g fdb -- /entrypoint.bash --copy-library {{ .FDBVersion.Compact }} --copy-binary fdbcli --copy-binary fdbbackup --copy-binary fdbrestore --output-dir /var/output-files/{{ .FDBVersion.String }} --init-mode
volumeMounts:
- name: fdb-binaries
mountPath: /var/output-files
securityContext:
runAsUser: 0
runAsGroup: 0
# Install this library in a special location to force the operator to
# use it as the primary library.
{{ if .CopyAsPrimary }}
- name: foundationdb-kubernetes-init-7-1-primary
image: {{ .BaseImage }}:{{ .SidecarTag}}
imagePullPolicy: {{ .ImagePullPolicy }}
args:
# Note that we are only copying a library, rather than copying any binaries.
- "--copy-library"
- "{{ .FDBVersion.Compact }}"
- "--output-dir"
- "/var/output-files/primary" # Note that we use primary as the subdirectory rather than specifying the FoundationDB version like we did in the other examples.
- "--init-mode"
volumeMounts:
- name: fdb-binaries
mountPath: /var/output-files
{{ end }}
{{ end }}
containers:
- command:
- /manager
args:` + operatorArgs +
`
image: {{ .OperatorImage }}
name: manager
imagePullPolicy: Always
env:
- name: LD_LIBRARY_PATH
value: /usr/bin/fdb/primary/lib
- name: WATCH_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: FDB_TLS_CERTIFICATE_FILE
value: /tmp/fdb-certs/tls.crt
- name: FDB_TLS_CA_FILE
value: /tmp/fdb-certs/ca.pem
- name: FDB_TLS_KEY_FILE
value: /tmp/fdb-certs/tls.key
- name: FDB_NETWORK_OPTION_EXTERNAL_CLIENT_DIRECTORY
value: /usr/bin/fdb
# FDB 7.3 adds a check for loading external client library, which doesn't work with 6.3.
# Consider remove this option once 6.3 is no longer being used.
- name: FDB_NETWORK_OPTION_IGNORE_EXTERNAL_CLIENT_FAILURES
value: ""
- name: FDB_BLOB_CREDENTIALS
value: /tmp/backup-credentials/credentials
# TODO (johscheuer): once we can generate certificates per Pod remove this!
- name: DISABLE_SIDECAR_TLS_CHECK
value: "1"
- name: FDB_NETWORK_OPTION_TRACE_ENABLE
value: "/var/log/fdb"
- name: FDB_NETWORK_OPTION_TRACE_FORMAT
value: json
ports:
- name: metrics
containerPort: 8080
resources:
requests:
cpu: {{ .CPURequests }}
memory: {{ .MemoryRequests }}
securityContext:
allowPrivilegeEscalation: false
privileged: false
readOnlyRootFilesystem: false
volumeMounts:
- mountPath: /tmp
name: tmp
- mountPath: /var/log/fdb
name: fdb-trace-logs
- name: fdb-certs
mountPath: /tmp/fdb-certs
readOnly: true
- name: fdb-binaries
mountPath: /usr/bin/fdb
- name: backup-credentials
mountPath: /tmp/backup-credentials
readOnly: true
securityContext:
fsGroup: 4059
runAsGroup: 4059
runAsUser: 4059
serviceAccountName: fdb-kubernetes-operator-controller-manager
terminationGracePeriodSeconds: 10
volumes:
- emptyDir: {}
name: tmp
- emptyDir: {}
name: fdb-trace-logs
- name: backup-credentials
secret:
secretName: {{ .BackupSecretName }}
optional: true
- name: fdb-certs
secret:
secretName: {{ .SecretName }}
- name: fdb-binaries
emptyDir: {}`
// operatorDeploymentUnifiedImage ...
operatorDeploymentUnifiedImage = `
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: fdb-kubernetes-operator-controller-manager
control-plane: controller-manager
name: fdb-kubernetes-operator-controller-manager
namespace: {{ .Namespace }}
spec:
replicas: 2
selector:
matchLabels:
app: fdb-kubernetes-operator-controller-manager
template:
metadata:
labels:
app: fdb-kubernetes-operator-controller-manager
control-plane: controller-manager
annotations:
prometheus.io/scrape: 'true'
prometheus.io/port: '8080'
spec:
initContainers:
{{ range $index, $version := .SidecarVersions }}
- name: foundationdb-kubernetes-init-{{ $index }}
image: {{ .BaseImage }}:{{ .SidecarTag}}
imagePullPolicy: {{ .ImagePullPolicy }}
args:
- --mode
- init
- --output-dir
- /var/output-files
- --copy-binary
- fdbcli
- --copy-binary
- fdbbackup
- --copy-binary
- fdbrestore
- --copy-library
- "{{ .FDBVersion.Compact }}"
{{ if .CopyAsPrimary }}
- --copy-primary-library
- "{{ .FDBVersion.Compact }}"
{{ end }}
volumeMounts:
- name: fdb-binaries
mountPath: /var/output-files
securityContext:
runAsUser: 0
runAsGroup: 0
{{ end }}
containers:
- command:
- /manager
args:` + operatorArgs +
`
image: {{ .OperatorImage }}
name: manager
imagePullPolicy: Always
env:
- name: LD_LIBRARY_PATH
value: /usr/bin/fdb
- name: WATCH_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: FDB_TLS_CERTIFICATE_FILE
value: /tmp/fdb-certs/tls.crt
- name: FDB_TLS_CA_FILE
value: /tmp/fdb-certs/ca.pem
- name: FDB_TLS_KEY_FILE
value: /tmp/fdb-certs/tls.key
- name: FDB_NETWORK_OPTION_EXTERNAL_CLIENT_DIRECTORY
value: /usr/bin/fdb
# FDB 7.3 adds a check for loading external client library, which doesn't work with 6.3.
# Consider remove this option once 6.3 is no longer being used.
- name: FDB_NETWORK_OPTION_IGNORE_EXTERNAL_CLIENT_FAILURES
value: ""
- name: FDB_BLOB_CREDENTIALS
value: /tmp/backup-credentials/credentials
# TODO (johscheuer): once we can generate certificates per Pod remove this!
- name: DISABLE_SIDECAR_TLS_CHECK
value: "1"
- name: FDB_NETWORK_OPTION_TRACE_ENABLE
value: "/var/log/fdb"
- name: FDB_NETWORK_OPTION_TRACE_FORMAT
value: json
ports:
- name: metrics
containerPort: 8080
resources:
requests:
cpu: {{ .CPURequests }}
memory: {{ .MemoryRequests }}
securityContext:
allowPrivilegeEscalation: false
privileged: false
readOnlyRootFilesystem: false
volumeMounts:
- mountPath: /tmp
name: tmp
- mountPath: /var/log/fdb
name: fdb-trace-logs
- name: fdb-certs
mountPath: /tmp/fdb-certs
readOnly: true
- name: fdb-binaries
mountPath: /usr/bin/fdb
- name: backup-credentials
mountPath: /tmp/backup-credentials
readOnly: true
securityContext:
fsGroup: 4059
runAsGroup: 4059
runAsUser: 4059
serviceAccountName: fdb-kubernetes-operator-controller-manager
terminationGracePeriodSeconds: 10
volumes:
- emptyDir: {}
name: tmp
- emptyDir: {}
name: fdb-trace-logs
- name: backup-credentials
secret:
secretName: {{ .BackupSecretName }}
optional: true
- name: fdb-certs
secret:
secretName: {{ .SecretName }}
- name: fdb-binaries
emptyDir: {}`
operatorArgs = `
- --max-concurrent-reconciles=5
- --zap-log-level=debug
- --minimum-required-uptime-for-cc-bounce=60s
#- --server-side-apply
# We are setting low values here as the e2e test are taking down processes multiple times
# and having a high wait time between recoveries will increase the reliability of the cluster but also
# increase the time our e2e test take.
- --minimum-recovery-time-for-inclusion=1.0
- --minimum-recovery-time-for-exclusion=1.0
- --cluster-label-key-for-node-trigger=foundationdb.org/fdb-cluster-name
- --enable-node-index
`
)
// operatorConfig represents the configuration of the operator Deployment.
type operatorConfig struct {
// OperatorImage represents the operator image that should be used in the Deployment.
OperatorImage string
// SecretName represents the Kubernetes secret that contains the certificates for communicating with the FoundationDB
// cluster.
SecretName string
// BackupSecretName represents the secret that should be used to communicate with the backup blobstore.
BackupSecretName string
// SidecarVersions represents the sidecar configurations for different FoundationDB versions.
SidecarVersions []SidecarConfig
// Namespace represents the namespace for the Deployment and all associated resources
Namespace string
// ImagePullPolicy represents the pull policy for the operator container.
ImagePullPolicy corev1.PullPolicy
// CPURequests defined the CPU that should be requested.
CPURequests string
// MemoryRequests defined the Memory that should be requested.
MemoryRequests string
}
// SidecarConfig represents the configuration for a sidecar. This can be used for templating.
type SidecarConfig struct {
// BaseImage the image reference without a tag.
BaseImage string
// SidecarTag represents the image tag for this configuration.
SidecarTag string
// FDBVersion represents the FoundationDB version for this config.
FDBVersion fdbv1beta2.Version
// ImagePullPolicy represents the pull policy for the sidecar.
ImagePullPolicy corev1.PullPolicy
// CopyAsPrimary if true the version should be copied as primary library.
CopyAsPrimary bool
}
// GetSidecarConfigs returns the sidecar configs. The sidecar configs can be used to template applications that will use
// all provided sidecar versions to inject FDB client libraries.
func (factory *Factory) GetSidecarConfigs() []SidecarConfig {
var hasCopyPrimarySet bool
additionalSidecarVersions := factory.GetAdditionalSidecarVersions()
sidecarConfigs := make([]SidecarConfig, 0, len(additionalSidecarVersions)+1)
image := factory.GetSidecarImage()
if factory.options.featureOperatorUnifiedImage {
image = factory.GetFoundationDBImage()
}
defaultConfig := getDefaultSidecarConfig(
image,
factory.GetFDBVersion(),
factory.getImagePullPolicy(),
factory.options.featureOperatorUnifiedImage,
)
if factory.GetFDBVersion().SupportsDNSInClusterFile() {
defaultConfig.CopyAsPrimary = true
hasCopyPrimarySet = true
}
sidecarConfigs = append(
sidecarConfigs,
defaultConfig,
)
baseImage := sidecarConfigs[0].BaseImage
// Add all other versions that are required e.g. for major or minor upgrades.
for _, version := range additionalSidecarVersions {
// Don't add the sidecar another time if we already added it
if version.Equal(factory.GetFDBVersion()) {
continue
}
sidecarConfig := getSidecarConfig(baseImage, "", version, factory.getImagePullPolicy(), factory.options.featureOperatorUnifiedImage)
if !hasCopyPrimarySet && version.SupportsDNSInClusterFile() {
sidecarConfig.CopyAsPrimary = true
hasCopyPrimarySet = true
}
sidecarConfigs = append(
sidecarConfigs,
sidecarConfig,
)
}
return sidecarConfigs
}
func getDefaultSidecarConfig(sidecarImage string, version fdbv1beta2.Version, imagePullPolicy corev1.PullPolicy, useUnifiedImage bool) SidecarConfig {
defaultSidecarImage := strings.SplitN(sidecarImage, ":", 2)
var tag string
if len(defaultSidecarImage) > 1 {
tag = defaultSidecarImage[1]
}
return getSidecarConfig(defaultSidecarImage[0], tag, version, imagePullPolicy, useUnifiedImage)
}
func getSidecarConfig(baseImage string, tag string, version fdbv1beta2.Version, imagePullPolicy corev1.PullPolicy, useUnifiedImage bool) SidecarConfig {
if tag == "" && !useUnifiedImage {
tag = fmt.Sprintf("%s-1", version)
}
return SidecarConfig{
BaseImage: baseImage,
FDBVersion: version,
SidecarTag: tag,
ImagePullPolicy: imagePullPolicy,
}
}
//nolint:revive
func (factory *Factory) getOperatorConfig(namespace string) *operatorConfig {
cpuRequests := "500m"
MemoryRequests := "1024Mi"
if factory.options.cloudProvider == cloudProviderKind {
cpuRequests = "0"
MemoryRequests = "0"
}
return &operatorConfig{
OperatorImage: factory.GetOperatorImage(),
SecretName: factory.GetSecretName(),
BackupSecretName: factory.GetBackupSecretName(),
Namespace: namespace,
SidecarVersions: factory.GetSidecarConfigs(),
ImagePullPolicy: factory.getImagePullPolicy(),
CPURequests: cpuRequests,
MemoryRequests: MemoryRequests,
}
}
func (factory *Factory) ensureFDBOperatorExists(namespace string) error {
// TODO: we also want to ensure that the CRDs are installed as an option
return factory.CreateFDBOperatorIfAbsent(namespace)
}
// CreateFDBOperatorIfAbsent creates the operator Deployment based on the template.
func (factory *Factory) CreateFDBOperatorIfAbsent(namespace string) error {
operatorRBACTemplate, err := template.New("operatorRBAC").Parse(operatorRBAC)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
buf := bytes.Buffer{}
gomega.Expect(operatorRBACTemplate.Execute(&buf, factory.getOperatorConfig(namespace))).NotTo(gomega.HaveOccurred())
decoder := yamlutil.NewYAMLOrJSONDecoder(&buf, 100000)
for {
var rawObj runtime.RawExtension
err := decoder.Decode(&rawObj)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
obj, _, err := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme).
Decode(rawObj.Raw, nil, nil)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
unstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
unstructuredObj := &unstructured.Unstructured{Object: unstructuredMap}
gomega.Expect(
factory.CreateIfAbsent(unstructuredObj),
).NotTo(gomega.HaveOccurred())
}
deploymentTemplate := operatorDeployment
if factory.options.featureOperatorUnifiedImage {
deploymentTemplate = operatorDeploymentUnifiedImage
}
operatorDeploymentTemplate, err := template.New("operatorDeployment").Parse(deploymentTemplate)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
buf = bytes.Buffer{}
gomega.Expect(operatorDeploymentTemplate.Execute(&buf, factory.getOperatorConfig(namespace))).NotTo(gomega.HaveOccurred())
decoder = yamlutil.NewYAMLOrJSONDecoder(&buf, 100000)
for {
var rawObj runtime.RawExtension
err := decoder.Decode(&rawObj)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
obj, _, err := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme).
Decode(rawObj.Raw, nil, nil)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
unstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
unstructuredObj := &unstructured.Unstructured{Object: unstructuredMap}
gomega.Expect(
factory.CreateIfAbsent(unstructuredObj),
).NotTo(gomega.HaveOccurred())
}
// Make sure the Operator Pods are running before moving forward.
factory.WaitUntilOperatorPodsRunning(namespace)
return nil
}
// GetOperatorPods returns the operator Pods in the provided namespace.
func (factory *Factory) GetOperatorPods(namespace string) *corev1.PodList {
pods := &corev1.PodList{}
gomega.Eventually(func() error {
return factory.GetControllerRuntimeClient().
List(ctx.TODO(), pods, client.InNamespace(namespace), client.MatchingLabels(map[string]string{"app": operatorDeploymentName}))
}).WithTimeout(1 * time.Minute).WithPolling(1 * time.Second).ShouldNot(gomega.HaveOccurred())
return pods
}
// WaitUntilOperatorPodsRunning waits until the Operator Pods are running.
func (factory *Factory) WaitUntilOperatorPodsRunning(namespace string) {
deployment := &appsv1.Deployment{}
gomega.Expect(
factory.GetControllerRuntimeClient().
Get(ctx.TODO(), client.ObjectKey{Name: operatorDeploymentName, Namespace: namespace}, deployment),
).NotTo(gomega.HaveOccurred())
expectedReplicas := int(pointer.Int32Deref(deployment.Spec.Replicas, 1))
gomega.Eventually(func(g gomega.Gomega) int {
pods := factory.GetOperatorPods(namespace)
var runningReplicas int
for _, pod := range pods.Items {
if pod.Status.Phase == corev1.PodRunning && pod.DeletionTimestamp.IsZero() {
runningReplicas++
continue
}
// If the Pod is not running after 120 seconds we delete it and let the Deployment controller create a new Pod.
if time.Since(pod.CreationTimestamp.Time).Seconds() > 120.0 {
log.Println("operator Pod", pod.Name, "not running after 120 seconds, going to delete this Pod, status:", pod.Status)
err := factory.GetControllerRuntimeClient().Delete(ctx.TODO(), &pod)
if k8serrors.IsNotFound(err) {
continue
}
g.Expect(err).NotTo(gomega.HaveOccurred())
}
}
return runningReplicas
}).WithTimeout(10 * time.Minute).WithPolling(2 * time.Second).Should(gomega.BeNumerically(">=", expectedReplicas))
}
// RecreateOperatorPods will recreate all operator Pods in the specified namespace and wait until the new Pods are
// up and running.
func (factory *Factory) RecreateOperatorPods(namespace string) {
gomega.Expect(
factory.GetControllerRuntimeClient().
DeleteAllOf(ctx.TODO(), &corev1.Pod{}, client.InNamespace(namespace), client.MatchingLabels(map[string]string{"app": operatorDeploymentName})),
).NotTo(gomega.HaveOccurred())
factory.WaitUntilOperatorPodsRunning(namespace)
}