Skip to content

Commit 6d9a918

Browse files
authored
CLOUDP-277876: Reap orphan connection secrets (#1856)
* CLOUDP-277876: Reap orphan connection secrets Signed-off-by: jose.vazquez <[email protected]> * Use debug log * Reuse local contains func --------- Signed-off-by: jose.vazquez <[email protected]>
1 parent a545b35 commit 6d9a918

File tree

4 files changed

+196
-2
lines changed

4 files changed

+196
-2
lines changed

pkg/controller/atlasdatabaseuser/atlasdatabaseuser_controller_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"errors"
66
"reflect"
77
"testing"
8-
"time"
98

109
"github.com/google/go-cmp/cmp"
1110
"github.com/google/go-cmp/cmp/cmpopts"
@@ -409,7 +408,7 @@ func TestReady(t *testing.T) {
409408
},
410409
},
411410
passwordVersion: "1",
412-
expectedResult: workflow.Requeue(15 * time.Minute).ReconcileResult(),
411+
expectedResult: workflow.Requeue(workflow.StandaloneResourceRequeuePeriod).ReconcileResult(),
413412
expectedConditions: []api.Condition{
414413
api.TrueCondition(api.ReadyType),
415414
api.TrueCondition(api.DatabaseUserReadyType),

pkg/controller/atlasdatabaseuser/databaseuser.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,18 @@ func (r *AtlasDatabaseUserReconciler) readiness(ctx *workflow.Context, atlasProj
188188
return r.terminate(ctx, atlasDatabaseUser, api.DatabaseUserReadyType, workflow.Internal, true, err)
189189
}
190190

191+
removedOrphanSecrets, err := connectionsecret.ReapOrphanConnectionSecrets(
192+
ctx.Context, r.Client, atlasProject.ID, atlasDatabaseUser.Namespace, allDeploymentNames)
193+
if err != nil {
194+
return r.terminate(ctx, atlasDatabaseUser, api.DatabaseUserReadyType, workflow.Internal, true, err)
195+
}
196+
if len(removedOrphanSecrets) > 0 {
197+
r.Log.Debug("Removed %d orphan secrets on project %s bound to an non existent deployment:")
198+
for _, orphan := range removedOrphanSecrets {
199+
r.Log.Debug("Removed orphan secret %q", orphan)
200+
}
201+
}
202+
191203
deploymentsToCheck := allDeploymentNames
192204
if atlasDatabaseUser.Spec.Scopes != nil {
193205
deploymentsToCheck = filterScopeDeployments(atlasDatabaseUser, allDeploymentNames)

pkg/controller/connectionsecret/connectionsecrets.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import (
77

88
"go.mongodb.org/atlas/mongodbatlas"
99
"go.uber.org/zap"
10+
corev1 "k8s.io/api/core/v1"
11+
"k8s.io/apimachinery/pkg/labels"
1012
"k8s.io/client-go/tools/record"
1113
"sigs.k8s.io/controller-runtime/pkg/client"
1214

@@ -20,6 +22,35 @@ import (
2022

2123
const ConnectionSecretsEnsuredEvent = "ConnectionSecretsEnsured"
2224

25+
func ReapOrphanConnectionSecrets(ctx context.Context, k8sClient client.Client, projectID, namespace string, projectDeploymentNames []string) ([]string, error) {
26+
secretList := &corev1.SecretList{}
27+
labelSelector := labels.SelectorFromSet(labels.Set{TypeLabelKey: CredLabelVal, ProjectLabelKey: projectID})
28+
err := k8sClient.List(context.Background(), secretList, &client.ListOptions{
29+
LabelSelector: labelSelector,
30+
Namespace: namespace,
31+
})
32+
if err != nil {
33+
return nil, fmt.Errorf("failed listing possible orphan secrets: %w", err)
34+
}
35+
36+
removedOrphanSecrets := []string{}
37+
for _, secret := range secretList.Items {
38+
clusterName, ok := secret.Labels[ClusterLabelKey]
39+
if !ok {
40+
continue
41+
}
42+
if clusterExists := stringutil.Contains(projectDeploymentNames, clusterName); clusterExists {
43+
continue
44+
}
45+
if err := k8sClient.Delete(ctx, &secret); err != nil {
46+
return nil, fmt.Errorf("failed to remove orphan connection Secret: %w", err)
47+
} else {
48+
removedOrphanSecrets = append(removedOrphanSecrets, fmt.Sprintf("%s/%s", namespace, secret.Name))
49+
}
50+
}
51+
return removedOrphanSecrets, nil
52+
}
53+
2354
func CreateOrUpdateConnectionSecrets(ctx *workflow.Context, k8sClient client.Client, ds deployment.AtlasDeploymentsService, recorder record.EventRecorder, project *project.Project, dbUser akov2.AtlasDatabaseUser) workflow.Result {
2455
conns, err := ds.ListDeploymentConnections(ctx.Context, project.ID)
2556
if err != nil {
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
package connectionsecret_test
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"testing"
7+
8+
corev1 "k8s.io/api/core/v1"
9+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
10+
"k8s.io/apimachinery/pkg/runtime"
11+
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
12+
"sigs.k8s.io/controller-runtime/pkg/client"
13+
"sigs.k8s.io/controller-runtime/pkg/client/fake"
14+
15+
"github.com/stretchr/testify/assert"
16+
17+
akov2 "github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/api/v1"
18+
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/controller/connectionsecret"
19+
)
20+
21+
const (
22+
testProjectID = "123456"
23+
24+
testNamespace = "some-namespace"
25+
)
26+
27+
func TestReapOrphanConnectionSecrets(t *testing.T) {
28+
scheme := runtime.NewScheme()
29+
utilruntime.Must(corev1.AddToScheme(scheme))
30+
utilruntime.Must(akov2.AddToScheme(scheme))
31+
32+
for _, tc := range []struct {
33+
title string
34+
deployments []string
35+
objects []client.Object
36+
expectedErr error
37+
expectedRemovals []string
38+
}{
39+
{
40+
title: "Empty list of secrets returns empty list of removals",
41+
expectedRemovals: []string{},
42+
},
43+
44+
{
45+
title: "Matching secrets do not get removed",
46+
deployments: sampleDeployments(),
47+
objects: matchingSecrets(),
48+
expectedRemovals: []string{},
49+
},
50+
51+
{
52+
title: "Secrets to non existing clusters get removed",
53+
deployments: sampleDeployments(),
54+
objects: merge(matchingSecrets(), nonMatchingSecrets()),
55+
expectedRemovals: namesOf(nonMatchingSecrets()),
56+
},
57+
} {
58+
t.Run(tc.title, func(t *testing.T) {
59+
fakeClient := fake.NewClientBuilder().
60+
WithScheme(scheme).
61+
WithObjects(tc.objects...).Build()
62+
removedOrphans, err := connectionsecret.ReapOrphanConnectionSecrets(
63+
context.Background(),
64+
fakeClient,
65+
testProjectID,
66+
testNamespace,
67+
tc.deployments,
68+
)
69+
assert.Equal(t, tc.expectedErr, err)
70+
assert.Equal(t, tc.expectedRemovals, removedOrphans)
71+
})
72+
}
73+
}
74+
75+
func sampleDeployments() []string {
76+
return []string{"cluster1", "serverless2"}
77+
}
78+
79+
func matchingSecrets() []client.Object {
80+
return []client.Object{
81+
&corev1.Secret{
82+
ObjectMeta: metav1.ObjectMeta{
83+
Name: "secret1",
84+
Namespace: testNamespace,
85+
Labels: map[string]string{
86+
connectionsecret.ClusterLabelKey: "cluster1",
87+
connectionsecret.ProjectLabelKey: testProjectID,
88+
connectionsecret.TypeLabelKey: connectionsecret.CredLabelVal,
89+
},
90+
},
91+
},
92+
93+
&corev1.Secret{
94+
ObjectMeta: metav1.ObjectMeta{
95+
Name: "secret2",
96+
Namespace: testNamespace,
97+
Labels: map[string]string{
98+
connectionsecret.ClusterLabelKey: "serverless2",
99+
connectionsecret.ProjectLabelKey: testProjectID,
100+
connectionsecret.TypeLabelKey: connectionsecret.CredLabelVal,
101+
},
102+
},
103+
},
104+
}
105+
}
106+
107+
func nonMatchingSecrets() []client.Object {
108+
return []client.Object{
109+
&corev1.Secret{
110+
ObjectMeta: metav1.ObjectMeta{
111+
Name: "secret3",
112+
Namespace: testNamespace,
113+
Labels: map[string]string{
114+
connectionsecret.ClusterLabelKey: "cluster3",
115+
connectionsecret.ProjectLabelKey: testProjectID,
116+
connectionsecret.TypeLabelKey: connectionsecret.CredLabelVal,
117+
},
118+
},
119+
},
120+
121+
&corev1.Secret{
122+
ObjectMeta: metav1.ObjectMeta{
123+
Name: "secret4",
124+
Namespace: testNamespace,
125+
Labels: map[string]string{
126+
connectionsecret.ClusterLabelKey: "serverless4",
127+
connectionsecret.ProjectLabelKey: testProjectID,
128+
connectionsecret.TypeLabelKey: connectionsecret.CredLabelVal,
129+
},
130+
},
131+
},
132+
}
133+
}
134+
135+
func namesOf(objs []client.Object) []string {
136+
names := make([]string, 0, len(objs))
137+
for _, obj := range objs {
138+
names = append(names, fmt.Sprintf("%s/%s", obj.GetNamespace(), obj.GetName()))
139+
}
140+
return names
141+
}
142+
143+
func merge(objs ...[]client.Object) []client.Object {
144+
if len(objs) == 0 {
145+
return []client.Object{}
146+
}
147+
result := objs[0]
148+
for i := 1; i < len(objs); i++ {
149+
result = append(result, objs[i]...)
150+
}
151+
return result
152+
}

0 commit comments

Comments
 (0)