Skip to content

Commit 74d13f1

Browse files
authored
Bump k8s apis to 1.27, refactor to support contexts (#1523)
1 parent 376ed2a commit 74d13f1

File tree

89 files changed

+1905
-2112
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

89 files changed

+1905
-2112
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,4 @@ diagnostics
100100
Pipfile
101101
Pipfile.lock
102102
.community-operator-dev
103+
*.iml

cmd/readiness/main.go

+7-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"context"
45
"encoding/json"
56
"fmt"
67
"io"
@@ -42,7 +43,7 @@ func init() {
4243
// - If MongoDB: then just the 'statuses[0].IsInGoalState` field is used to learn if the Agent has reached the goal
4344
// - if AppDB: the 'mmsStatus[0].lastGoalVersionAchieved' field is compared with the one from mounted automation config
4445
// Additionally if the previous check hasn't returned 'true' an additional check for wait steps is being performed
45-
func isPodReady(conf config.Config) (bool, error) {
46+
func isPodReady(ctx context.Context, conf config.Config) (bool, error) {
4647
healthStatus, err := parseHealthStatus(conf.HealthStatusReader)
4748
if err != nil {
4849
logger.Errorf("There was problem parsing health status file: %s", err)
@@ -56,7 +57,7 @@ func isPodReady(conf config.Config) (bool, error) {
5657
}
5758

5859
// If the agent has reached the goal state
59-
inGoalState, err := isInGoalState(healthStatus, conf)
60+
inGoalState, err := isInGoalState(ctx, healthStatus, conf)
6061
if err != nil {
6162
logger.Errorf("There was problem checking the health status: %s", err)
6263
return false, err
@@ -159,9 +160,9 @@ func isWaitStep(status *health.StepStatus) bool {
159160
return false
160161
}
161162

162-
func isInGoalState(health health.Status, conf config.Config) (bool, error) {
163+
func isInGoalState(ctx context.Context, health health.Status, conf config.Config) (bool, error) {
163164
if isHeadlessMode() {
164-
return headless.PerformCheckHeadlessMode(health, conf)
165+
return headless.PerformCheckHeadlessMode(ctx, health, conf)
165166
}
166167
return performCheckOMMode(health), nil
167168
}
@@ -216,6 +217,7 @@ func initLogger(l *lumberjack.Logger) {
216217
}
217218

218219
func main() {
220+
ctx := context.Background()
219221
clientSet, err := kubernetesClientset()
220222
if err != nil {
221223
panic(err)
@@ -238,7 +240,7 @@ func main() {
238240
panic(err)
239241
}
240242

241-
ready, err := isPodReady(cfg)
243+
ready, err := isPodReady(ctx, cfg)
242244
if err != nil {
243245
panic(err)
244246
}

cmd/readiness/readiness_test.go

+10-6
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
// TestDeadlockDetection verifies that if the agent is stuck in "WaitAllRsMembersUp" phase (started > 15 seconds ago)
2323
// then the function returns "ready"
2424
func TestDeadlockDetection(t *testing.T) {
25+
ctx := context.Background()
2526
type TestConfig struct {
2627
conf config.Config
2728
isErrorExpected bool
@@ -108,7 +109,7 @@ func TestDeadlockDetection(t *testing.T) {
108109
for testName, _ := range tests {
109110
testConfig := tests[testName]
110111
t.Run(testName, func(t *testing.T) {
111-
ready, err := isPodReady(testConfig.conf)
112+
ready, err := isPodReady(ctx, testConfig.conf)
112113
if testConfig.isErrorExpected {
113114
assert.Error(t, err)
114115
} else {
@@ -241,8 +242,9 @@ func TestObtainingCurrentStep(t *testing.T) {
241242
// In this case, the Readiness Probe needs to return Ready and let the StatefulSet Controller to proceed
242243
// with the Pod rollout.
243244
func TestReadyWithWaitForCorrectBinaries(t *testing.T) {
245+
ctx := context.Background()
244246
c := testConfigWithMongoUp("testdata/health-status-ok-with-WaitForCorrectBinaries.json", time.Second*30)
245-
ready, err := isPodReady(c)
247+
ready, err := isPodReady(ctx, c)
246248

247249
assert.True(t, ready)
248250
assert.NoError(t, err)
@@ -254,26 +256,28 @@ func TestReadyWithWaitForCorrectBinaries(t *testing.T) {
254256
// (as Agent doesn't marks all the step statuses finished when it reaches the goal) but this doesn't affect the result
255257
// as the whole plan is complete already
256258
func TestHeadlessAgentHasntReachedGoal(t *testing.T) {
259+
ctx := context.Background()
257260
t.Setenv(headlessAgent, "true")
258261
c := testConfig("testdata/health-status-ok.json")
259262
c.ClientSet = fake.NewSimpleClientset(testdata.TestPod(c.Namespace, c.Hostname), testdata.TestSecret(c.Namespace, c.AutomationConfigSecretName, 6))
260-
ready, err := isPodReady(c)
263+
ready, err := isPodReady(ctx, c)
261264
assert.False(t, ready)
262265
assert.NoError(t, err)
263-
thePod, _ := c.ClientSet.CoreV1().Pods(c.Namespace).Get(context.TODO(), c.Hostname, metav1.GetOptions{})
266+
thePod, _ := c.ClientSet.CoreV1().Pods(c.Namespace).Get(ctx, c.Hostname, metav1.GetOptions{})
264267
assert.Equal(t, map[string]string{"agent.mongodb.com/version": "5"}, thePod.Annotations)
265268
}
266269

267270
// TestHeadlessAgentReachedGoal verifies that the probe reports "true" if the config version is equal to the
268271
// last achieved version of the Agent
269272
func TestHeadlessAgentReachedGoal(t *testing.T) {
273+
ctx := context.Background()
270274
t.Setenv(headlessAgent, "true")
271275
c := testConfig("testdata/health-status-ok.json")
272276
c.ClientSet = fake.NewSimpleClientset(testdata.TestPod(c.Namespace, c.Hostname), testdata.TestSecret(c.Namespace, c.AutomationConfigSecretName, 5))
273-
ready, err := isPodReady(c)
277+
ready, err := isPodReady(ctx, c)
274278
assert.True(t, ready)
275279
assert.NoError(t, err)
276-
thePod, _ := c.ClientSet.CoreV1().Pods(c.Namespace).Get(context.TODO(), c.Hostname, metav1.GetOptions{})
280+
thePod, _ := c.ClientSet.CoreV1().Pods(c.Namespace).Get(ctx, c.Hostname, metav1.GetOptions{})
277281
assert.Equal(t, map[string]string{"agent.mongodb.com/version": "5"}, thePod.Annotations)
278282
}
279283

cmd/versionhook/main.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const (
2727
)
2828

2929
func main() {
30+
ctx := context.Background()
3031
logger := setupLogger()
3132

3233
logger.Info("Running version change post-start hook")
@@ -57,7 +58,7 @@ func main() {
5758

5859
if shouldDelete {
5960
logger.Infof("Pod should be deleted")
60-
if err := deletePod(); err != nil {
61+
if err := deletePod(ctx); err != nil {
6162
// We should not raise an error if the Pod could not be deleted. It can have even
6263
// worse consequences: Pod being restarted with the same version, and the agent
6364
// killing it immediately after.
@@ -182,7 +183,7 @@ func isWaitingToBeDeleted(healthStatus agent.MmsDirectorStatus) bool {
182183
}
183184

184185
// deletePod attempts to delete the pod this mongod is running in
185-
func deletePod() error {
186+
func deletePod(ctx context.Context) error {
186187
thisPod, err := getThisPod()
187188
if err != nil {
188189
return fmt.Errorf("could not get pod: %s", err)
@@ -192,7 +193,7 @@ func deletePod() error {
192193
return fmt.Errorf("could not get client: %s", err)
193194
}
194195

195-
if err := k8sClient.Delete(context.TODO(), &thisPod); err != nil {
196+
if err := k8sClient.Delete(ctx, &thisPod); err != nil {
196197
return fmt.Errorf("could not delete pod: %s", err)
197198
}
198199
return nil

config/crd/bases/mongodbcommunity.mongodb.com_mongodbcommunity.yaml

+8-11
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
1+
12
---
23
apiVersion: apiextensions.k8s.io/v1
34
kind: CustomResourceDefinition
45
metadata:
56
annotations:
6-
controller-gen.kubebuilder.io/version: v0.11.3
7-
service.binding: path={.metadata.name}-{.spec.users[0].db}-{.spec.users[0].name},objectType=Secret
8-
service.binding/connectionString: path={.metadata.name}-{.spec.users[0].db}-{.spec.users[0].name},objectType=Secret,sourceKey=connectionString.standardSrv
9-
service.binding/password: path={.metadata.name}-{.spec.users[0].db}-{.spec.users[0].name},objectType=Secret,sourceKey=password
10-
service.binding/provider: community
11-
service.binding/type: mongodb
12-
service.binding/username: path={.metadata.name}-{.spec.users[0].db}-{.spec.users[0].name},objectType=Secret,sourceKey=username
7+
controller-gen.kubebuilder.io/version: v0.4.1
138
creationTimestamp: null
149
name: mongodbcommunity.mongodbcommunity.mongodb.com
1510
spec:
@@ -290,7 +285,6 @@ spec:
290285
TODO: Add other useful fields. apiVersion, kind, uid?'
291286
type: string
292287
type: object
293-
x-kubernetes-map-type: atomic
294288
agentMode:
295289
description: AgentMode contains the authentication mode used
296290
by the automation agent.
@@ -419,7 +413,6 @@ spec:
419413
TODO: Add other useful fields. apiVersion, kind, uid?'
420414
type: string
421415
type: object
422-
x-kubernetes-map-type: atomic
423416
caConfigMapRef:
424417
description: CaConfigMap is a reference to a ConfigMap containing
425418
the certificate for the CA which signed the server certificates
@@ -432,7 +425,6 @@ spec:
432425
TODO: Add other useful fields. apiVersion, kind, uid?'
433426
type: string
434427
type: object
435-
x-kubernetes-map-type: atomic
436428
certificateKeySecretRef:
437429
description: CertificateKeySecret is a reference to a Secret
438430
containing a private key and certificate to use for TLS.
@@ -450,7 +442,6 @@ spec:
450442
TODO: Add other useful fields. apiVersion, kind, uid?'
451443
type: string
452444
type: object
453-
x-kubernetes-map-type: atomic
454445
enabled:
455446
type: boolean
456447
optional:
@@ -602,3 +593,9 @@ spec:
602593
storage: true
603594
subresources:
604595
status: {}
596+
status:
597+
acceptedNames:
598+
kind: ""
599+
plural: ""
600+
conditions: []
601+
storedVersions: []

controllers/mongodb_cleanup.go

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package controllers
22

33
import (
4+
"context"
45
apiErrors "k8s.io/apimachinery/pkg/api/errors"
56
"k8s.io/apimachinery/pkg/types"
67

@@ -9,14 +10,14 @@ import (
910
)
1011

1112
// cleanupPemSecret cleans up the old pem secret generated for the agent certificate.
12-
func (r *ReplicaSetReconciler) cleanupPemSecret(currentMDB mdbv1.MongoDBCommunitySpec, lastAppliedMDBSpec mdbv1.MongoDBCommunitySpec, namespace string) {
13+
func (r *ReplicaSetReconciler) cleanupPemSecret(ctx context.Context, currentMDB mdbv1.MongoDBCommunitySpec, lastAppliedMDBSpec mdbv1.MongoDBCommunitySpec, namespace string) {
1314
if currentMDB.GetAgentAuthMode() == lastAppliedMDBSpec.GetAgentAuthMode() {
1415
return
1516
}
1617

1718
if !currentMDB.IsAgentX509() && lastAppliedMDBSpec.IsAgentX509() {
1819
agentCertSecret := lastAppliedMDBSpec.GetAgentCertificateRef()
19-
if err := r.client.DeleteSecret(types.NamespacedName{
20+
if err := r.client.DeleteSecret(ctx, types.NamespacedName{
2021
Namespace: namespace,
2122
Name: agentCertSecret + "-pem",
2223
}); err != nil {
@@ -30,11 +31,11 @@ func (r *ReplicaSetReconciler) cleanupPemSecret(currentMDB mdbv1.MongoDBCommunit
3031
}
3132

3233
// cleanupScramSecrets cleans up old scram secrets based on the last successful applied mongodb spec.
33-
func (r *ReplicaSetReconciler) cleanupScramSecrets(currentMDB mdbv1.MongoDBCommunitySpec, lastAppliedMDBSpec mdbv1.MongoDBCommunitySpec, namespace string) {
34+
func (r *ReplicaSetReconciler) cleanupScramSecrets(ctx context.Context, currentMDB mdbv1.MongoDBCommunitySpec, lastAppliedMDBSpec mdbv1.MongoDBCommunitySpec, namespace string) {
3435
secretsToDelete := getScramSecretsToDelete(currentMDB, lastAppliedMDBSpec)
3536

3637
for _, s := range secretsToDelete {
37-
if err := r.client.DeleteSecret(types.NamespacedName{
38+
if err := r.client.DeleteSecret(ctx, types.NamespacedName{
3839
Name: s,
3940
Namespace: namespace,
4041
}); err != nil {

controllers/mongodb_cleanup_test.go

+7-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package controllers
22

33
import (
4+
"context"
45
mdbv1 "github.com/mongodb/mongodb-kubernetes-operator/api/v1"
56
kubeClient "github.com/mongodb/mongodb-kubernetes-operator/pkg/kube/client"
67
"github.com/stretchr/testify/assert"
@@ -98,6 +99,7 @@ func TestReplicaSetReconcilerCleanupScramSecrets(t *testing.T) {
9899

99100
}
100101
func TestReplicaSetReconcilerCleanupPemSecret(t *testing.T) {
102+
ctx := context.Background()
101103
lastAppliedSpec := mdbv1.MongoDBCommunitySpec{
102104
Security: mdbv1.Security{
103105
Authentication: mdbv1.Authentication{
@@ -134,21 +136,21 @@ func TestReplicaSetReconcilerCleanupPemSecret(t *testing.T) {
134136
},
135137
}
136138

137-
mgr := kubeClient.NewManager(&mdb)
139+
mgr := kubeClient.NewManager(ctx, &mdb)
138140

139141
client := kubeClient.NewClient(mgr.GetClient())
140-
err := createAgentCertPemSecret(client, mdb, "CERT", "KEY", "")
142+
err := createAgentCertPemSecret(ctx, client, mdb, "CERT", "KEY", "")
141143
assert.NoError(t, err)
142144

143145
r := NewReconciler(mgr)
144146

145-
secret, err := r.client.GetSecret(mdb.AgentCertificatePemSecretNamespacedName())
147+
secret, err := r.client.GetSecret(ctx, mdb.AgentCertificatePemSecretNamespacedName())
146148
assert.NoError(t, err)
147149
assert.Equal(t, "CERT", string(secret.Data["tls.crt"]))
148150
assert.Equal(t, "KEY", string(secret.Data["tls.key"]))
149151

150-
r.cleanupPemSecret(mdb.Spec, lastAppliedSpec, "my-ns")
152+
r.cleanupPemSecret(ctx, mdb.Spec, lastAppliedSpec, "my-ns")
151153

152-
_, err = r.client.GetSecret(mdb.AgentCertificatePemSecretNamespacedName())
154+
_, err = r.client.GetSecret(ctx, mdb.AgentCertificatePemSecretNamespacedName())
153155
assert.Error(t, err)
154156
}

0 commit comments

Comments
 (0)