-
Notifications
You must be signed in to change notification settings - Fork 66
/
datafederation_controller.go
287 lines (239 loc) · 11.7 KB
/
datafederation_controller.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
package atlasdatafederation
import (
"context"
"errors"
"fmt"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/event"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/controller/connectionsecret"
"go.mongodb.org/atlas/mongodbatlas"
ctrl "sigs.k8s.io/controller-runtime"
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/internal/kube"
akov2 "github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/api/v1"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/api/v1/status"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/controller/atlas"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/controller/customresource"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/controller/statushandler"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/controller/watch"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/controller/workflow"
)
// AtlasDataFederationReconciler reconciles an DataFederation object
type AtlasDataFederationReconciler struct {
watch.DeprecatedResourceWatcher
Client client.Client
Log *zap.SugaredLogger
Scheme *runtime.Scheme
GlobalPredicates []predicate.Predicate
EventRecorder record.EventRecorder
AtlasProvider atlas.Provider
ObjectDeletionProtection bool
SubObjectDeletionProtection bool
}
// +kubebuilder:rbac:groups=atlas.mongodb.com,resources=atlasdatafederations,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=atlas.mongodb.com,resources=atlasdatafederations/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=atlas.mongodb.com,namespace=default,resources=atlasdatafederations,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=atlas.mongodb.com,namespace=default,resources=atlasdatafederations/status,verbs=get;update;patch
// +kubebuilder:rbac:groups="",resources=events,verbs=create;patch
func (r *AtlasDataFederationReconciler) Reconcile(context context.Context, req ctrl.Request) (ctrl.Result, error) {
log := r.Log.With("atlasdatafederation", req.NamespacedName)
dataFederation := &akov2.AtlasDataFederation{}
result := customresource.PrepareResource(context, r.Client, req, dataFederation, log)
if !result.IsOk() {
return result.ReconcileResult(), nil
}
if customresource.ReconciliationShouldBeSkipped(dataFederation) {
log.Infow(fmt.Sprintf("-> Skipping AtlasDataFederation reconciliation as annotation %s=%s", customresource.ReconciliationPolicyAnnotation, customresource.ReconciliationPolicySkip), "spec", dataFederation.Spec)
if !dataFederation.GetDeletionTimestamp().IsZero() {
err := customresource.ManageFinalizer(context, r.Client, dataFederation, customresource.UnsetFinalizer)
if err != nil {
result = workflow.Terminate(workflow.Internal, err.Error())
log.Errorw("failed to remove finalizer", "error", err)
return result.ReconcileResult(), nil
}
}
return workflow.OK().ReconcileResult(), nil
}
ctx := customresource.MarkReconciliationStarted(r.Client, dataFederation, log, context)
log.Infow("-> Starting AtlasDataFederation reconciliation", "spec", dataFederation.Spec, "status", dataFederation.Status)
defer statushandler.Update(ctx, r.Client, r.EventRecorder, dataFederation)
resourceVersionIsValid := customresource.ValidateResourceVersion(ctx, dataFederation, r.Log)
if !resourceVersionIsValid.IsOk() {
r.Log.Debugf("AtlasDataFederation validation result: %v", resourceVersionIsValid)
return resourceVersionIsValid.ReconcileResult(), nil
}
if !r.AtlasProvider.IsResourceSupported(dataFederation) {
result := workflow.Terminate(workflow.AtlasGovUnsupported, "the AtlasDataFederation is not supported by Atlas for government").
WithoutRetry()
ctx.SetConditionFromResult(status.DataFederationReadyType, result)
return result.ReconcileResult(), nil
}
project := &akov2.AtlasProject{}
if result := r.readProjectResource(context, dataFederation, project); !result.IsOk() {
ctx.SetConditionFromResult(status.DataFederationReadyType, result)
return result.ReconcileResult(), nil
}
atlasClient, orgID, err := r.AtlasProvider.Client(ctx.Context, project.ConnectionSecretObjectKey(), log)
if err != nil {
result := workflow.Terminate(workflow.AtlasAPIAccessNotConfigured, err.Error())
ctx.SetConditionFromResult(status.DataFederationReadyType, result)
return result.ReconcileResult(), nil
}
ctx.OrgID = orgID
ctx.Client = atlasClient
// Setting protection flag to static false because ownership detection is disabled.
owner, err := customresource.IsOwner(dataFederation, false, customresource.IsResourceManagedByOperator, managedByAtlas(context, atlasClient, project.ID(), log))
if err != nil {
result = workflow.Terminate(workflow.Internal, fmt.Sprintf("unable to resolve ownership for deletion protection: %s", err))
ctx.SetConditionFromResult(status.DataFederationReadyType, result)
log.Error(result.GetMessage())
return result.ReconcileResult(), nil
}
if !owner {
result = workflow.Terminate(
workflow.AtlasDeletionProtection,
"unable to reconcile DataFederation: it already exists in Atlas, it was not previously managed by the operator, and the deletion protection is enabled.",
)
ctx.SetConditionFromResult(status.DataFederationReadyType, result)
log.Error(result.GetMessage())
return result.ReconcileResult(), nil
}
if result = r.ensureDataFederation(ctx, project, dataFederation); !result.IsOk() {
ctx.SetConditionFromResult(status.DataFederationReadyType, result)
return result.ReconcileResult(), nil
}
if result = r.ensurePrivateEndpoints(ctx, project, dataFederation); !result.IsOk() {
ctx.SetConditionFromResult(status.DataFederationPEReadyType, result)
return result.ReconcileResult(), nil
}
if result = r.ensureConnectionSecrets(ctx, project, dataFederation); !result.IsOk() {
return result.ReconcileResult(), nil
}
if dataFederation.GetDeletionTimestamp().IsZero() {
if !customresource.HaveFinalizer(dataFederation, customresource.FinalizerLabel) {
err = r.Client.Get(context, kube.ObjectKeyFromObject(dataFederation), dataFederation)
if err != nil {
result = workflow.Terminate(workflow.Internal, err.Error())
return result.ReconcileResult(), nil
}
customresource.SetFinalizer(dataFederation, customresource.FinalizerLabel)
if err = r.Client.Update(context, dataFederation); err != nil {
result = workflow.Terminate(workflow.Internal, err.Error())
log.Errorw("failed to add finalizer", "error", err)
return result.ReconcileResult(), nil
}
}
}
if !dataFederation.GetDeletionTimestamp().IsZero() {
if customresource.HaveFinalizer(dataFederation, customresource.FinalizerLabel) {
if customresource.IsResourcePolicyKeepOrDefault(dataFederation, r.ObjectDeletionProtection) {
log.Info("Not removing AtlasDataFederation from Atlas as per configuration")
} else {
if err = r.deleteDataFederationFromAtlas(context, atlasClient, dataFederation, project, log); err != nil {
log.Errorf("failed to remove DataFederation from Atlas: %s", err)
result = workflow.Terminate(workflow.Internal, err.Error())
ctx.SetConditionFromResult(status.DataFederationReadyType, result)
return result.ReconcileResult(), nil
}
}
if err = customresource.ManageFinalizer(context, r.Client, dataFederation, customresource.UnsetFinalizer); err != nil {
result = workflow.Terminate(workflow.AtlasFinalizerNotRemoved, err.Error())
log.Errorw("failed to remove finalizer", "error", err)
return result.ReconcileResult(), nil
}
} else {
return result.ReconcileResult(), nil
}
}
err = customresource.ApplyLastConfigApplied(context, project, r.Client)
if err != nil {
result = workflow.Terminate(workflow.Internal, err.Error())
ctx.SetConditionFromResult(status.DataFederationReadyType, result)
log.Error(result.GetMessage())
return result.ReconcileResult(), nil
}
ctx.SetConditionTrue(status.ReadyType)
return workflow.OK().ReconcileResult(), nil
}
func (r *AtlasDataFederationReconciler) deleteDataFederationFromAtlas(ctx context.Context, client *mongodbatlas.Client, df *akov2.AtlasDataFederation, project *akov2.AtlasProject, log *zap.SugaredLogger) error {
log.Infof("Deleting DataFederation instance: %s from Atlas", df.Spec.Name)
_, err := client.DataFederation.Delete(ctx, project.ID(), df.Spec.Name)
var apiError *mongodbatlas.ErrorResponse
if errors.As(err, &apiError) && apiError.Error() == "DATA_LAKE_TENANT_NOT_FOUND_FOR_NAME" {
log.Info("DataFederation doesn't exist or is already deleted")
return nil
}
if err != nil {
log.Errorw("Can not delete Atlas DataFederation", "error", err)
return err
}
return nil
}
func (r *AtlasDataFederationReconciler) readProjectResource(ctx context.Context, dataFederation *akov2.AtlasDataFederation, project *akov2.AtlasProject) workflow.Result {
if err := r.Client.Get(ctx, dataFederation.AtlasProjectObjectKey(), project); err != nil {
return workflow.Terminate(workflow.Internal, err.Error())
}
return workflow.OK()
}
func (r *AtlasDataFederationReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
Named("AtlasDataFederation").
Watches(&akov2.AtlasDataFederation{}, &watch.EventHandlerWithDelete{Controller: r}, builder.WithPredicates(r.GlobalPredicates...)).
For(&akov2.AtlasDataFederation{}, builder.WithPredicates(r.GlobalPredicates...)).
Complete(r)
}
// Delete implements a handler for the Delete event
func (r *AtlasDataFederationReconciler) Delete(ctx context.Context, e event.DeleteEvent) error {
dataFederation, ok := e.Object.(*akov2.AtlasDataFederation)
if !ok {
r.Log.Errorf("Ignoring malformed Delete() call (expected type %T, got %T)", &akov2.AtlasDeployment{}, e.Object)
return nil
}
log := r.Log.With("atlasdatafederation", kube.ObjectKeyFromObject(dataFederation))
log.Infow("-> Starting AtlasDataFederation deletion", "spec", dataFederation.Spec)
project := &akov2.AtlasProject{}
if result := r.readProjectResource(ctx, dataFederation, project); !result.IsOk() {
return errors.New("cannot read project resource")
}
log = log.With("projectID", project.Status.ID, "dataFederationName", dataFederation.Spec.Name)
// We always remove the connection secrets even if the deployment is not removed from Atlas
secrets, err := connectionsecret.ListByDeploymentName(ctx, r.Client, dataFederation.Namespace, project.ID(), dataFederation.Spec.Name)
if err != nil {
return fmt.Errorf("failed to find connection secrets for the user: %w", err)
}
for i := range secrets {
if err := r.Client.Delete(ctx, &secrets[i]); err != nil {
if k8serrors.IsNotFound(err) {
continue
}
log.Errorw("Failed to delete secret", "secretName", secrets[i].Name, "error", err)
}
}
return nil
}
func managedByAtlas(ctx context.Context, atlasClient *mongodbatlas.Client, projectID string, log *zap.SugaredLogger) customresource.AtlasChecker {
return func(resource akov2.AtlasCustomResource) (bool, error) {
dataFederation, ok := resource.(*akov2.AtlasDataFederation)
if !ok {
return false, errors.New("failed to match resource type as AtlasDataFederation")
}
atlasDataFederation, _, err := atlasClient.DataFederation.Get(ctx, projectID, dataFederation.Spec.Name)
if err != nil {
var apiError *mongodbatlas.ErrorResponse
if errors.As(err, &apiError) && (apiError.ErrorCode == atlas.DataFederationTenantNotFound || apiError.ErrorCode == atlas.ResourceNotFound) {
return false, nil
}
return false, err
}
isSame, err := dataFederationMatchesSpec(log, atlasDataFederation, dataFederation)
if err != nil {
return true, nil
}
return !isSame, nil
}
}