-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathremote_objects.go
422 lines (389 loc) · 15 KB
/
remote_objects.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
package remotedatabasenodeset
import (
"context"
"fmt"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/ydb-platform/ydb-kubernetes-operator/api/v1alpha1"
ydbannotations "github.com/ydb-platform/ydb-kubernetes-operator/internal/annotations"
. "github.com/ydb-platform/ydb-kubernetes-operator/internal/controllers/constants" //nolint:revive,stylecheck
ydblabels "github.com/ydb-platform/ydb-kubernetes-operator/internal/labels"
"github.com/ydb-platform/ydb-kubernetes-operator/internal/resources"
)
func (r *Reconciler) initRemoteObjectsStatus(
ctx context.Context,
remoteDatabaseNodeSet *resources.RemoteDatabaseNodeSetResource,
remoteObjects []client.Object,
) (bool, ctrl.Result, error) {
r.Log.Info("running step initRemoteObjectsStatus")
for _, remoteObj := range remoteObjects {
existInStatus := false
for idx := range remoteDatabaseNodeSet.Status.RemoteResources {
if resources.EqualRemoteResourceWithObject(
&remoteDatabaseNodeSet.Status.RemoteResources[idx],
remoteObj,
) {
existInStatus = true
break
}
}
if !existInStatus {
remoteDatabaseNodeSet.CreateRemoteResourceStatus(remoteObj)
return r.updateStatusRemoteObjects(ctx, remoteDatabaseNodeSet, StatusUpdateRequeueDelay)
}
}
r.Log.Info("complete step initRemoteObjectsStatus")
return Continue, ctrl.Result{}, nil
}
func (r *Reconciler) syncRemoteObjects(
ctx context.Context,
remoteDatabaseNodeSet *resources.RemoteDatabaseNodeSetResource,
remoteObjects []client.Object,
) (bool, ctrl.Result, error) {
r.Log.Info("running step syncRemoteObjects")
for _, remoteObj := range remoteObjects {
remoteObjName := remoteObj.GetName()
remoteObjKind := remoteObj.GetObjectKind().GroupVersionKind().Kind
remoteObjRV := remoteObj.GetResourceVersion()
var remoteResource *v1alpha1.RemoteResource
for idx := range remoteDatabaseNodeSet.Status.RemoteResources {
if resources.EqualRemoteResourceWithObject(&remoteDatabaseNodeSet.Status.RemoteResources[idx], remoteObj) {
remoteResource = &remoteDatabaseNodeSet.Status.RemoteResources[idx]
break
}
}
// Get object to sync from remote cluster
remoteGetErr := r.RemoteClient.Get(ctx, types.NamespacedName{
Name: remoteObj.GetName(),
Namespace: remoteObj.GetNamespace(),
}, remoteObj)
// Resource not found on remote cluster or internal kubernetes error
if remoteGetErr != nil {
if apierrors.IsNotFound(remoteGetErr) {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ProvisioningFailed",
fmt.Sprintf("Resource %s with name %s was not found on remote cluster: %s", remoteObjKind, remoteObjName, remoteGetErr),
)
r.RemoteRecorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ProvisioningFailed",
fmt.Sprintf("Resource %s with name %s was not found: %s", remoteObjKind, remoteObjName, remoteGetErr),
)
} else {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to get resource %s with name %s on remote cluster: %s", remoteObjKind, remoteObjName, remoteGetErr),
)
r.RemoteRecorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to get resource %s with name %s: %s", remoteObjKind, remoteObjName, remoteGetErr),
)
}
remoteDatabaseNodeSet.UpdateRemoteResourceStatus(remoteResource, metav1.ConditionFalse, remoteObjRV)
return r.updateStatusRemoteObjects(ctx, remoteDatabaseNodeSet, DefaultRequeueDelay)
}
// Check object existence in local cluster
localObj := resources.CreateResource(remoteObj)
getErr := r.Client.Get(ctx, types.NamespacedName{
Name: localObj.GetName(),
Namespace: localObj.GetNamespace(),
}, localObj)
// Handler for kubernetes internal error
if getErr != nil && !apierrors.IsNotFound(getErr) {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to get resource %s with name %s: %s", remoteObjKind, remoteObjName, getErr),
)
remoteDatabaseNodeSet.UpdateRemoteResourceStatus(remoteResource, metav1.ConditionFalse, remoteObjRV)
return r.updateStatusRemoteObjects(ctx, remoteDatabaseNodeSet, DefaultRequeueDelay)
}
// Try to create non-existing remote object in local cluster
if apierrors.IsNotFound(getErr) {
createErr := r.Client.Create(ctx, localObj)
if createErr != nil {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to create resource %s with name %s: %s", remoteObjKind, remoteObjName, getErr),
)
remoteDatabaseNodeSet.UpdateRemoteResourceStatus(remoteResource, metav1.ConditionFalse, remoteObjRV)
return r.updateStatusRemoteObjects(ctx, remoteDatabaseNodeSet, DefaultRequeueDelay)
}
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeNormal,
"Provisioning",
fmt.Sprintf("RemoteSync CREATE resource %s with name %s", remoteObjKind, remoteObjName),
)
remoteDatabaseNodeSet.UpdateRemoteResourceStatus(remoteResource, metav1.ConditionFalse, remoteObjRV)
return r.updateStatusRemoteObjects(ctx, remoteDatabaseNodeSet, StatusUpdateRequeueDelay)
}
// Get patch diff between remote object and existing object
remoteDatabaseNodeSet.SetPrimaryResourceAnnotations(remoteObj)
patchResult, patchErr := resources.GetPatchResult(localObj, remoteObj)
if patchErr != nil {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to get diff for remote resource %s with name %s: %s", remoteObjKind, remoteObjName, patchErr),
)
remoteDatabaseNodeSet.UpdateRemoteResourceStatus(remoteResource, metav1.ConditionFalse, remoteObjRV)
return r.updateStatusRemoteObjects(ctx, remoteDatabaseNodeSet, DefaultRequeueDelay)
}
// Try to update existing object in local cluster by rawPatch
if !patchResult.IsEmpty() {
updateErr := r.Client.Patch(ctx, localObj, client.RawPatch(types.StrategicMergePatchType, patchResult.Patch))
if updateErr != nil {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to update resource %s with name %s: %v", remoteObjKind, remoteObjName, updateErr),
)
remoteDatabaseNodeSet.UpdateRemoteResourceStatus(remoteResource, metav1.ConditionFalse, remoteObjRV)
return r.updateStatusRemoteObjects(ctx, remoteDatabaseNodeSet, DefaultRequeueDelay)
}
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeNormal,
"Provisioning",
fmt.Sprintf("RemoteSync UPDATE resource %s with name %s resourceVersion %s", remoteObjKind, remoteObjName, remoteObj.GetResourceVersion()),
)
remoteDatabaseNodeSet.UpdateRemoteResourceStatus(remoteResource, metav1.ConditionTrue, remoteObjRV)
return r.updateStatusRemoteObjects(ctx, remoteDatabaseNodeSet, StatusUpdateRequeueDelay)
}
if !meta.IsStatusConditionTrue(remoteResource.Conditions, RemoteResourceSyncedCondition) {
remoteDatabaseNodeSet.UpdateRemoteResourceStatus(remoteResource, metav1.ConditionTrue, remoteObjRV)
return r.updateStatusRemoteObjects(ctx, remoteDatabaseNodeSet, StatusUpdateRequeueDelay)
}
}
r.Log.Info("complete step syncRemoteObjects")
return Continue, ctrl.Result{}, nil
}
func (r *Reconciler) removeUnusedRemoteObjects(
ctx context.Context,
remoteDatabaseNodeSet *resources.RemoteDatabaseNodeSetResource,
remoteObjects []client.Object,
) (bool, ctrl.Result, error) {
r.Log.Info("running step removeUnusedRemoteResources")
// We should check every remote resource to need existence in cluster
// Get processed remote resources from object Status
candidatesToDelete := []v1alpha1.RemoteResource{}
for idx := range remoteDatabaseNodeSet.Status.RemoteResources {
// Remove remote resource from candidates to delete if it declared
// to using in current RemoteDatabaseNodeSet spec
existInSpec := false
for _, remoteObj := range remoteObjects {
if resources.EqualRemoteResourceWithObject(
&remoteDatabaseNodeSet.Status.RemoteResources[idx],
remoteObj,
) {
existInSpec = true
break
}
}
if !existInSpec {
candidatesToDelete = append(candidatesToDelete, remoteDatabaseNodeSet.Status.RemoteResources[idx])
}
}
if len(candidatesToDelete) == 0 {
r.Log.Info("complete step removeUnusedRemoteObjects")
return Continue, ctrl.Result{}, nil
}
existInDatabase := false
anotherDatabaseNodeSets, err := r.getAnotherDatabaseNodeSets(ctx, remoteDatabaseNodeSet)
if err != nil {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to check remote resource usage in another: %v", err),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, err
}
if len(anotherDatabaseNodeSets) > 0 {
existInDatabase = true
}
// Check RemoteResource usage in DatabaseNodeSet
for _, remoteResource := range candidatesToDelete {
remoteObj, err := resources.ConvertRemoteResourceToObject(remoteResource, remoteDatabaseNodeSet.Namespace)
if err != nil {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to convert RemoteResource %s with name %s to object: %v", remoteResource.Kind, remoteResource.Name, err),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, err
}
localObj := resources.CreateResource(remoteObj)
if err := r.Client.Get(ctx, types.NamespacedName{
Name: localObj.GetName(),
Namespace: localObj.GetNamespace(),
}, localObj); err != nil {
if apierrors.IsNotFound(err) {
continue
}
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to get RemoteResource %s with name %s as object: %v", remoteResource.Kind, remoteResource.Name, err),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, err
}
// Remove annotation if no one another DatabaseNodeSet
if !existInDatabase {
// Try to update existing object in local cluster by rawPatch
patch := []byte(fmt.Sprintf(`{"metadata": {"annotations": {"%s": null}}}`, ydbannotations.PrimaryResourceStorage))
updateErr := r.Client.Patch(ctx, localObj, client.RawPatch(types.StrategicMergePatchType, patch))
if updateErr != nil {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to update resource %s with name %s: %s", remoteResource.Kind, remoteResource.Name, err),
)
} else {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeNormal,
"Provisioning",
fmt.Sprintf("RemoteSync UPDATE resource %s with name %s unset primaryResource annotation", remoteResource.Kind, remoteResource.Name),
)
}
}
// Delete resource if annotation `ydb.tech/primary-resource-storage` does not exist
_, existInStorage := localObj.GetAnnotations()[ydbannotations.PrimaryResourceStorage]
if !existInStorage {
// Try to delete unused resource from local cluster
deleteErr := r.Client.Delete(ctx, localObj)
if deleteErr != nil {
if !apierrors.IsNotFound(deleteErr) {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to delete resource %s with name %s: %s", remoteResource.Kind, remoteResource.Name, err),
)
}
} else {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeNormal,
"Provisioning",
fmt.Sprintf("RemoteSync DELETE resource %s with name %s", remoteResource.Kind, remoteResource.Name),
)
}
}
remoteDatabaseNodeSet.RemoveRemoteResourceStatus(remoteObj)
}
return r.updateStatusRemoteObjects(ctx, remoteDatabaseNodeSet, StatusUpdateRequeueDelay)
}
func (r *Reconciler) updateStatusRemoteObjects(
ctx context.Context,
remoteDatabaseNodeSet *resources.RemoteDatabaseNodeSetResource,
requeueAfter time.Duration,
) (bool, ctrl.Result, error) {
crRemoteDatabaseNodeSet := &v1alpha1.RemoteDatabaseNodeSet{}
getErr := r.RemoteClient.Get(ctx, types.NamespacedName{
Name: remoteDatabaseNodeSet.Name,
Namespace: remoteDatabaseNodeSet.Namespace,
}, crRemoteDatabaseNodeSet)
if getErr != nil {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed fetching CR before status update for remote resources on remote cluster: %v", getErr),
)
r.RemoteRecorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed fetching CR before status update for remote resources: %v", getErr),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, getErr
}
crRemoteDatabaseNodeSet.Status.RemoteResources = append([]v1alpha1.RemoteResource{}, remoteDatabaseNodeSet.Status.RemoteResources...)
updateErr := r.RemoteClient.Status().Update(ctx, crRemoteDatabaseNodeSet)
if updateErr != nil {
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to update status for remote resources on remote cluster: %s", updateErr),
)
r.RemoteRecorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to update status for remote resources: %s", updateErr),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, updateErr
}
r.Recorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeNormal,
"StatusChanged",
"Status for remote resources updated on remote cluster",
)
r.RemoteRecorder.Event(
remoteDatabaseNodeSet,
corev1.EventTypeNormal,
"StatusChanged",
"Status for remote resources updated",
)
return Stop, ctrl.Result{RequeueAfter: requeueAfter}, nil
}
func (r *Reconciler) getAnotherDatabaseNodeSets(
ctx context.Context,
remoteDatabaseNodeSet *resources.RemoteDatabaseNodeSetResource,
) ([]v1alpha1.DatabaseNodeSet, error) {
// Create label requirement that label `ydb.tech/database-nodeset` which not equal
// to current DatabaseNodeSet object for exclude current nodeSet from List result
labelRequirement, err := labels.NewRequirement(
ydblabels.DatabaseNodeSetComponent,
selection.NotEquals,
[]string{remoteDatabaseNodeSet.Labels[ydblabels.DatabaseNodeSetComponent]},
)
if err != nil {
return nil, err
}
// Search another DatabaseNodeSets in current namespace with the same DatabaseRef
// but exclude current nodeSet from result
databaseNodeSets := v1alpha1.DatabaseNodeSetList{}
if err := r.Client.List(
ctx,
&databaseNodeSets,
client.InNamespace(remoteDatabaseNodeSet.Namespace),
client.MatchingLabelsSelector{
Selector: labels.NewSelector().Add(*labelRequirement),
},
client.MatchingFields{
DatabaseRefField: remoteDatabaseNodeSet.Spec.DatabaseRef.Name,
},
); err != nil {
return nil, err
}
return databaseNodeSets.Items, nil
}