-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathsubnetbinding_controller.go
More file actions
607 lines (558 loc) · 23.8 KB
/
subnetbinding_controller.go
File metadata and controls
607 lines (558 loc) · 23.8 KB
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
package subnetbinding
import (
"context"
"fmt"
"reflect"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/util/retry"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"github.com/vmware-tanzu/nsx-operator/pkg/apis/vpc/v1alpha1"
"github.com/vmware-tanzu/nsx-operator/pkg/controllers/common"
"github.com/vmware-tanzu/nsx-operator/pkg/logger"
servicecommon "github.com/vmware-tanzu/nsx-operator/pkg/nsx/services/common"
"github.com/vmware-tanzu/nsx-operator/pkg/nsx/services/subnet"
"github.com/vmware-tanzu/nsx-operator/pkg/nsx/services/subnetbinding"
"github.com/vmware-tanzu/nsx-operator/pkg/nsx/services/vlanpool"
)
var (
log = logger.Log
)
type errorWithRetry struct {
error
retry bool
message string
}
// Reconciler reconciles a SubnetConnectionBindingMap object
type Reconciler struct {
Client client.Client
Scheme *runtime.Scheme
SubnetService *subnet.SubnetService
SubnetBindingService *subnetbinding.BindingService
VlanPoolService *vlanpool.Service
StatusUpdater common.StatusUpdater
}
func (r *Reconciler) RestoreReconcile() error {
return nil
}
func (r *Reconciler) StartController(mgr ctrl.Manager, _ webhook.Server) error {
// Start the controller
if err := r.setupWithManager(mgr); err != nil {
log.Error(err, "Failed to create controller", "controller", "SubnetConnectionBindingMap")
return err
}
// Setup field indexers
if err := r.SetupFieldIndexers(mgr); err != nil {
log.Error(err, "Failed to setup field indexers", "controller", "SubnetConnectionBindingMap")
return err
}
// Start garbage collector in a separate goroutine
go common.GenericGarbageCollector(make(chan bool), servicecommon.GCInterval, r.CollectGarbage)
return nil
}
func NewReconciler(mgr ctrl.Manager, subnetService *subnet.SubnetService, subnetBindingService *subnetbinding.BindingService) *Reconciler {
recorder := mgr.GetEventRecorderFor("subnetconnectionbindingmap-controller") //nolint:staticcheck // record.EventRecorder; StatusUpdater not on events.EventRecorder yet
// Create the SubnetConnectionBindingMap Reconciler with the necessary services and configuration
return &Reconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
SubnetService: subnetService,
SubnetBindingService: subnetBindingService,
VlanPoolService: vlanpool.NewService(subnetBindingService),
StatusUpdater: common.NewStatusUpdater(mgr.GetClient(), subnetBindingService.NSXConfig, recorder, common.MetricResTypeSubnetConnectionBindingMap, "SubnetConnectionBindingMap", "SubnetConnectionBindingMap"),
}
}
func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
startTime := time.Now()
defer func() {
log.Info("Finished reconciling SubnetConnectionBindingMap", "SubnetConnectionBindingMap", req.NamespacedName, "duration(ms)", time.Since(startTime).Milliseconds())
}()
r.StatusUpdater.IncreaseSyncTotal()
bindingMapCR := &v1alpha1.SubnetConnectionBindingMap{}
if err := r.Client.Get(ctx, req.NamespacedName, bindingMapCR); err != nil {
if apierrors.IsNotFound(err) {
r.StatusUpdater.IncreaseDeleteTotal()
// Try to delete NSX SubnetConnectionBindingMaps if exists
if err := r.SubnetBindingService.DeleteSubnetConnectionBindingMapsByCRName(req.Name, req.Namespace); err != nil {
log.Error(err, "Failed to delete NSX SubnetConnectionBindingMap", "SubnetConnectionBindingMap", req.NamespacedName)
r.StatusUpdater.DeleteFail(req.NamespacedName, nil, err)
return common.ResultRequeue, nil
}
r.StatusUpdater.DeleteSuccess(req.NamespacedName, nil)
return common.ResultNormal, nil
}
log.Error(err, "Unable to fetch SubnetConnectionBindingMap CR", "SubnetConnectionBindingMap", req.NamespacedName)
return common.ResultRequeue, nil
}
// Create or update SubnetConnectionBindingMap
r.StatusUpdater.IncreaseUpdateTotal()
childSubnetPath, parentSubnetPaths, err := r.validateDependency(ctx, bindingMapCR)
if err != nil {
// Update SubnetConnectionBindingMap with not-ready condition
r.StatusUpdater.UpdateFail(ctx, bindingMapCR, err, "dependent Subnets are not ready", updateBindingMapStatusWithUnreadyCondition, "DependencyNotReady", err.message)
if !err.retry {
return common.ResultNormal, nil
}
// Requeue after 60s to support the case that the dependent Subnet is not nested.
return common.ResultRequeueAfter60sec, nil
}
if vlanErr := r.reconcileVlanTrafficTag(ctx, bindingMapCR, parentSubnetPaths); vlanErr != nil {
r.StatusUpdater.UpdateFail(ctx, bindingMapCR, vlanErr, "failed to reconcile VLAN traffic tag", updateBindingMapStatusWithUnreadyCondition, "VlanAllocationFailed", vlanErr.message)
if !vlanErr.retry {
return common.ResultNormal, nil
}
return common.ResultRequeue, nil
}
if err := r.SubnetBindingService.CreateOrUpdateSubnetConnectionBindingMap(bindingMapCR, childSubnetPath, parentSubnetPaths); err != nil {
// Update SubnetConnectionBindingMap with not-ready condition
r.StatusUpdater.UpdateFail(ctx, bindingMapCR, err, "failure to configure SubnetConnectionBindingMaps on NSX", updateBindingMapStatusWithUnreadyCondition, "ConfigureFailed", fmt.Sprintf("Failed to realize SubnetConnectionBindingMap %s on NSX", req.Name))
return common.ResultRequeue, nil
}
// Update SubnetConnectionBindingMap with ready condition
r.StatusUpdater.UpdateSuccess(ctx, bindingMapCR, updateBindingMapStatusWithReadyCondition)
return common.ResultNormal, nil
}
// CollectGarbage collects the stale SubnetConnectionBindingMaps and deletes them on NSX which have been removed from K8s.
// It implements the interface GarbageCollector method.
func (r *Reconciler) CollectGarbage(ctx context.Context) error {
startTime := time.Now()
defer func() {
log.Info("SubnetConnectionBindingMap garbage collection completed", "duration(ms)", time.Since(startTime).Milliseconds())
}()
bindingMapIdSetByCRs, err := r.listBindingMapIDsFromCRs(ctx)
if err != nil {
log.Error(err, "Failed to list SubnetConnectionBindingMap CRs")
return err
}
bindingMapIdSetInStore := r.SubnetBindingService.ListSubnetConnectionBindingMapCRUIDsInStore()
if err = r.SubnetBindingService.DeleteMultiSubnetConnectionBindingMapsByCRs(bindingMapIdSetInStore.Difference(bindingMapIdSetByCRs)); err != nil {
log.Error(err, "Failed to delete stale SubnetConnectionBindingMaps")
return err
}
return nil
}
var PredicateFuncsForBindingMaps = predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
oldBindingMap := e.ObjectOld.(*v1alpha1.SubnetConnectionBindingMap)
newBindingMap := e.ObjectNew.(*v1alpha1.SubnetConnectionBindingMap)
return !reflect.DeepEqual(oldBindingMap.Spec, newBindingMap.Spec)
},
CreateFunc: func(e event.CreateEvent) bool {
return true
},
DeleteFunc: func(e event.DeleteEvent) bool {
return true
},
GenericFunc: func(e event.GenericEvent) bool {
return false
},
}
func (r *Reconciler) setupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.SubnetConnectionBindingMap{}, builder.WithPredicates(PredicateFuncsForBindingMaps)).
WithOptions(controller.Options{
MaxConcurrentReconciles: common.NumReconcile(),
}).
Watches(
&v1alpha1.Subnet{},
&common.EnqueueRequestForDependency{
Client: r.Client,
RequeueByUpdate: requeueBindingMapsBySubnetUpdate,
ResourceType: "Subnet"},
builder.WithPredicates(PredicateFuncsForSubnets),
).
Watches(
&v1alpha1.SubnetSet{},
&common.EnqueueRequestForDependency{
Client: r.Client,
RequeueByUpdate: requeueBindingMapsBySubnetSetUpdate,
ResourceType: "SubnetSet"},
builder.WithPredicates(PredicateFuncsForSubnetSets),
).
Complete(r)
}
func (r *Reconciler) listBindingMapIDsFromCRs(ctx context.Context) (sets.Set[string], error) {
bmIDs := sets.New[string]()
connectionBindingMapList := &v1alpha1.SubnetConnectionBindingMapList{}
err := r.Client.List(ctx, connectionBindingMapList)
if err != nil {
return nil, err
}
for _, bm := range connectionBindingMapList.Items {
bmIDs.Insert(string(bm.UID))
}
return bmIDs, nil
}
func getVpcPath(subnetPath string) (string, *errorWithRetry) {
info, err := servicecommon.ParseVPCResourcePath(subnetPath)
if err != nil {
return "", &errorWithRetry{
message: fmt.Sprintf("Invalid Subnet path %s", subnetPath),
retry: false,
error: fmt.Errorf("failed to parse Subnet path %s", subnetPath),
}
}
return info.GetVPCPath(), nil
}
// validateDependency validates the following conditions:
// 1. the dependent Subnet/SubnetSet is not realized. In this case, a not-retry error is returned, and the
// Subnet/SubnetSet readiness update will actively trigger a requeue event
// 2. the associated Subnet is already used as a target Subnet in another SubnetConnectionBindingMap CR, or the target
// Subnet already has associated SubnetConnectionBindingMap CR. In this case, a retry error is returned.
// 3. the target Subnet is a pre-created Subnet or target SubnetSet is a pre-created SubnetSet.
// In this case, a not-retry error is returned.
// 4. the associated Subnet is a pre-created Subnet in a VPC different from the target Subnet Namespace VPC
// In this case, not-retry error is returned.
func (r *Reconciler) validateDependency(ctx context.Context, bindingMap *v1alpha1.SubnetConnectionBindingMap) (string, []string, *errorWithRetry) {
childSubnetPaths, childSubnetCR, err := r.validateVpcSubnetsBySubnetCR(ctx, bindingMap.Namespace, bindingMap.Spec.SubnetName, false)
if err != nil {
return "", nil, err
}
childSubnetPath := childSubnetPaths[0]
var parentSubnetPaths []string
if bindingMap.Spec.TargetSubnetName != "" {
var parentSubnetCR *v1alpha1.Subnet
parentSubnetPaths, parentSubnetCR, err = r.validateVpcSubnetsBySubnetCR(ctx, bindingMap.Namespace, bindingMap.Spec.TargetSubnetName, true)
if err != nil {
return "", nil, err
}
// Check if the target Subnet is pre-created Subnet
if _, ok := parentSubnetCR.GetAnnotations()[servicecommon.AnnotationAssociatedResource]; ok {
return "", nil, &errorWithRetry{
message: fmt.Sprintf("Target Subnet %s/%s is a pre-created Subnet", bindingMap.Namespace, bindingMap.Spec.TargetSubnetName),
error: fmt.Errorf("pre-created Subnet %s/%s cannot be a target Subnet", bindingMap.Namespace, bindingMap.Spec.TargetSubnetName),
retry: false,
}
}
} else {
parentSubnetPaths, err = r.validateVpcSubnetsBySubnetSetCR(ctx, bindingMap.Namespace, bindingMap.Spec.TargetSubnetSetName)
if err != nil {
return "", nil, err
}
}
// If child Subnet is a pre-created Subnet, check if it is in the same vpc as parent Subnet
if _, ok := childSubnetCR.GetAnnotations()[servicecommon.AnnotationAssociatedResource]; ok {
childVpcPath, err := getVpcPath(childSubnetPath)
if err != nil {
return "", nil, err
}
parentVpcPath, err := getVpcPath(parentSubnetPaths[0])
if err != nil {
return "", nil, err
}
if childVpcPath != parentVpcPath {
return "", nil, &errorWithRetry{
message: fmt.Sprintf("Subnet %s and target Subnet %s are in different VPCs", childSubnetPath, parentSubnetPaths[0]),
retry: false,
error: fmt.Errorf("Subnet and target Subnet are in different VPCs"),
}
}
}
return childSubnetPath, parentSubnetPaths, nil
}
func (r *Reconciler) reconcileVlanTrafficTag(ctx context.Context, bindingMap *v1alpha1.SubnetConnectionBindingMap, parentSubnetPaths []string) *errorWithRetry {
if bindingMap.Spec.HasVlanTrafficTag() {
vlan := *bindingMap.Spec.VLANTrafficTag
if err := r.VlanPoolService.ValidateManualVlan(parentSubnetPaths, vlan, string(bindingMap.UID)); err != nil {
return &errorWithRetry{
message: err.Error(),
error: err,
retry: true,
}
}
return nil
}
childSubnet := &v1alpha1.Subnet{}
childSubnetKey := types.NamespacedName{Namespace: bindingMap.Namespace, Name: bindingMap.Spec.SubnetName}
if err := r.Client.Get(ctx, childSubnetKey, childSubnet); err != nil {
log.Error(err, "Failed to get Subnet CR for VLAN auto allocation", "Subnet", childSubnetKey.String())
return &errorWithRetry{
message: fmt.Sprintf("Unable to get Subnet CR %s for VLAN auto allocation", bindingMap.Spec.SubnetName),
error: fmt.Errorf("failed to get Subnet %s in Namespace %s: %w", bindingMap.Spec.SubnetName, bindingMap.Namespace, err),
retry: false,
}
}
preferred := int64(-1)
if childSubnet.Status.VLANExtension.VLANID != 0 {
preferred = int64(childSubnet.Status.VLANExtension.VLANID)
}
vlan, err := r.VlanPoolService.Allocate(parentSubnetPaths, string(bindingMap.UID), preferred)
if err != nil {
return &errorWithRetry{
message: err.Error(),
error: err,
retry: true,
}
}
if err := r.patchSpecVlanTrafficTag(ctx, bindingMap, vlan); err != nil {
return &errorWithRetry{
message: fmt.Sprintf("Failed to update spec.vlanTrafficTag: %v", err),
error: err,
retry: true,
}
}
bindingMap.Spec.VLANTrafficTag = v1alpha1.VLANTrafficTagPtr(vlan)
return nil
}
func (r *Reconciler) patchSpecVlanTrafficTag(ctx context.Context, bindingMap *v1alpha1.SubnetConnectionBindingMap, vlan int64) error {
key := types.NamespacedName{Namespace: bindingMap.Namespace, Name: bindingMap.Name}
return retry.RetryOnConflict(retry.DefaultRetry, func() error {
latest := &v1alpha1.SubnetConnectionBindingMap{}
if err := r.Client.Get(ctx, key, latest); err != nil {
return err
}
if latest.Spec.HasVlanTrafficTag() && *latest.Spec.VLANTrafficTag == vlan {
return nil
}
latest.Spec.VLANTrafficTag = v1alpha1.VLANTrafficTagPtr(vlan)
return r.Client.Update(ctx, latest)
})
}
func (r *Reconciler) validateVpcSubnetsBySubnetCR(ctx context.Context, namespace, name string, isTarget bool) ([]string, *v1alpha1.Subnet, *errorWithRetry) {
subnetCR := &v1alpha1.Subnet{}
subnetKey := types.NamespacedName{Namespace: namespace, Name: name}
// Check the Subnet CR existence.
err := r.Client.Get(ctx, subnetKey, subnetCR)
if err != nil {
log.Error(err, "Failed to get Subnet CR", "Subnet", subnetKey.String())
return nil, subnetCR, &errorWithRetry{
message: fmt.Sprintf("Unable to get Subnet CR %s", name),
retry: false,
error: fmt.Errorf("failed to get Subnet %s in Namespace %s with error: %v", name, namespace, err),
}
}
// Check if the Subnet CR is nested.
if !isTarget {
bms, err := r.getSubnetConnectionBindingMapsByParentSubnet(ctx, namespace, name)
if err != nil {
// Retry for CR list error
log.Error(err, "Failed to get SubnetConnectionBindingMaps with Subnet as targetSubnet", "Subnet", subnetKey.String())
return nil, subnetCR, &errorWithRetry{
message: fmt.Sprintf("Failed to get SubnetConnectionBindingMaps with Subnet as targetSubnet %s", name),
retry: true,
error: err,
}
}
if len(bms) > 0 {
return nil, subnetCR, &errorWithRetry{
message: fmt.Sprintf("Subnet CR %s is working as target by %s", name, bms),
error: fmt.Errorf("Subnet %s already works as target in SubnetConnectionBindingMap %s", name, bms),
retry: true,
}
}
} else {
bms, err := r.getSubnetConnectionBindingMapsByChildSubnet(ctx, namespace, name)
if err != nil {
// Retry for CR list error
log.Error(err, "Failed to get SubnetConnectionBindingMaps with Subnet as associated Subnet", "Subnet", subnetKey.String())
return nil, subnetCR, &errorWithRetry{
message: fmt.Sprintf("Failed to get SubnetConnectionBindingMaps with Subnet as associated Subnet %s", name),
retry: true,
error: err,
}
}
if len(bms) > 0 {
return nil, subnetCR, &errorWithRetry{
message: fmt.Sprintf("Target Subnet CR %s is associated by %s", name, bms),
error: fmt.Errorf("target Subnet %s is already associated by SubnetConnectionBindingMap %s", name, bms),
retry: true,
}
}
}
// Check the Subnet CR realization.
var subnetPaths []string
if anno, ok := subnetCR.GetAnnotations()[servicecommon.AnnotationAssociatedResource]; ok {
realized := false
for _, con := range subnetCR.Status.Conditions {
if con.Type == v1alpha1.Ready && con.Status == corev1.ConditionTrue {
realized = true
break
}
}
if !realized {
return nil, subnetCR, &errorWithRetry{
message: fmt.Sprintf("Subnet CR %s is not realized on NSX", name),
retry: false,
error: err,
}
}
path, err := servicecommon.GetSubnetPathFromAssociatedResource(anno)
if err != nil {
// No need to retry as not support associated resource annotation
// changing after Subnet creation.
log.Error(err, "Failed to get NSX Subnet path for shared Subnet", "Subnet", subnetKey.String())
return nil, subnetCR, &errorWithRetry{
message: fmt.Sprintf("Failed to get NSX Subnet path for shared Subnet %s", name),
retry: false,
error: err,
}
}
subnetPaths = append(subnetPaths, path)
} else {
subnets := r.SubnetService.ListSubnetCreatedBySubnet(string(subnetCR.UID))
for _, subnet := range subnets {
subnetPaths = append(subnetPaths, *subnet.Path)
}
}
if len(subnetPaths) == 0 {
log.Info("NSX VpcSubnets by Subnet CR do not exist", "Subnet", subnetKey.String())
return nil, subnetCR, &errorWithRetry{
message: fmt.Sprintf("Subnet CR %s is not realized on NSX", name),
retry: false,
error: fmt.Errorf("not found NSX VpcSubnets created by Subnet CR '%s/%s'", namespace, name),
}
}
return subnetPaths, subnetCR, nil
}
func (r *Reconciler) validateVpcSubnetsBySubnetSetCR(ctx context.Context, namespace, name string) ([]string, *errorWithRetry) {
subnetSetCR := &v1alpha1.SubnetSet{}
subnetSetKey := types.NamespacedName{Namespace: namespace, Name: name}
err := r.Client.Get(ctx, subnetSetKey, subnetSetCR)
if err != nil {
log.Error(err, "Failed to get SubnetSet CR", "SubnetSet", subnetSetKey.String())
return nil, &errorWithRetry{
message: fmt.Sprintf("Unable to get SubnetSet CR %s", name),
error: fmt.Errorf("failed to get SubnetSet %s in Namespace %s with error: %v", name, namespace, err),
retry: false,
}
}
if subnetSetCR.Spec.SubnetNames != nil {
return nil, &errorWithRetry{
message: fmt.Sprintf("Target SubnetSet %s/%s is a SubnetSet with pre-created Subnets", namespace, name),
error: fmt.Errorf("SubnetSet with pre-created Subnets %s/%s cannot be a target SubnetSet", namespace, name),
retry: false,
}
}
subnets := r.SubnetService.ListSubnetCreatedBySubnetSet(string(subnetSetCR.UID))
if len(subnets) == 0 {
log.Info("NSX VpcSubnets by SubnetSet CR do not exist", "SubnetSet", subnetSetKey.String())
return nil, &errorWithRetry{
message: fmt.Sprintf("SubnetSet CR %s is not realized on NSX", name),
error: fmt.Errorf("no existing NSX VpcSubnet created by SubnetSet CR '%s/%s'", namespace, name),
retry: false,
}
}
subnetPaths := make([]string, len(subnets))
for i := range subnets {
subnetPaths[i] = *subnets[i].Path
}
return subnetPaths, nil
}
func (r *Reconciler) getSubnetConnectionBindingMapsByParentSubnet(ctx context.Context, ns, name string) ([]types.NamespacedName, error) {
bmKeys := []types.NamespacedName{}
subnetBindingList := &v1alpha1.SubnetConnectionBindingMapList{}
err := r.Client.List(ctx, subnetBindingList, client.InNamespace(ns), client.MatchingFields{"spec.targetSubnetName": name})
if err != nil {
return nil, fmt.Errorf("failed to list SubnetConnectionBindingMap CRs: %w", err)
}
for _, bm := range subnetBindingList.Items {
bmKeys = append(bmKeys, types.NamespacedName{Namespace: bm.Namespace, Name: bm.Name})
}
return bmKeys, nil
}
func (r *Reconciler) getSubnetConnectionBindingMapsByChildSubnet(ctx context.Context, ns, name string) ([]types.NamespacedName, error) {
bmKeys := []types.NamespacedName{}
subnetBindingList := &v1alpha1.SubnetConnectionBindingMapList{}
err := r.Client.List(ctx, subnetBindingList, client.InNamespace(ns), client.MatchingFields{"spec.subnetName": name})
if err != nil {
return nil, fmt.Errorf("failed to list SubnetConnectionBindingMap CRs: %w", err)
}
for _, bm := range subnetBindingList.Items {
bmKeys = append(bmKeys, types.NamespacedName{Namespace: bm.Namespace, Name: bm.Name})
}
return bmKeys, nil
}
func updateBindingMapStatusWithUnreadyCondition(c client.Client, ctx context.Context, obj client.Object, _ metav1.Time, _ error, args ...interface{}) {
bindingMap := obj.(*v1alpha1.SubnetConnectionBindingMap)
reason := args[0].(string)
msg := args[1].(string)
condition := v1alpha1.Condition{
Type: v1alpha1.Ready,
Status: corev1.ConditionFalse,
Reason: reason,
Message: msg,
}
updateBindingMapCondition(c, ctx, bindingMap, condition)
}
func updateBindingMapStatusWithReadyCondition(c client.Client, ctx context.Context, obj client.Object, _ metav1.Time, _ ...interface{}) {
bindingMap := obj.(*v1alpha1.SubnetConnectionBindingMap)
condition := v1alpha1.Condition{
Type: v1alpha1.Ready,
Status: corev1.ConditionTrue,
}
updateBindingMapCondition(c, ctx, bindingMap, condition)
}
func updateBindingMapCondition(c client.Client, ctx context.Context, bindingMap *v1alpha1.SubnetConnectionBindingMap, condition v1alpha1.Condition) {
condition.LastTransitionTime = metav1.Now()
key := types.NamespacedName{Namespace: bindingMap.Namespace, Name: bindingMap.Name}
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
// Fetch the latest version of the object
latestBindingMap := &v1alpha1.SubnetConnectionBindingMap{}
if err := c.Get(ctx, key, latestBindingMap); err != nil {
return err
}
// Check if the update is needed
newConditions := []v1alpha1.Condition{condition}
for _, cond := range latestBindingMap.Status.Conditions {
if cond.Type == condition.Type {
if cond.Status == condition.Status && cond.Reason == condition.Reason && cond.Message == condition.Message {
return nil
}
continue
}
newConditions = append(newConditions, cond)
}
latestBindingMap.Status.Conditions = newConditions
return c.Status().Update(ctx, latestBindingMap)
})
if err != nil {
log.Error(err, "Failed to update SubnetConnectionBindingMap status", "Namespace", bindingMap.Namespace, "Name", bindingMap.Name)
return
}
log.Debug("Updated SubnetConnectionBindingMap status", "Namespace", bindingMap.Namespace, "Name", bindingMap.Name)
}
// subnetConnectionBindingMapSubnetNameIndexFunc is an index function that indexes SubnetConnectionBindingMap by namespace and subnet name
func subnetConnectionBindingMapSubnetNameIndexFunc(obj client.Object) []string {
if binding, ok := obj.(*v1alpha1.SubnetConnectionBindingMap); !ok {
log.Info("Invalid object", "type", reflect.TypeOf(obj))
return []string{}
} else {
if binding.Spec.SubnetName == "" {
return []string{}
}
return []string{binding.Spec.SubnetName}
}
}
// subnetConnectionBindingMapSubnetNameIndexFunc is an index function that indexes SubnetConnectionBindingMap by namespace and subnet name
func subnetConnectionBindingMapTargetSubnetNameIndexFunc(obj client.Object) []string {
if binding, ok := obj.(*v1alpha1.SubnetConnectionBindingMap); !ok {
log.Info("Invalid object", "type", reflect.TypeOf(obj))
return []string{}
} else {
if binding.Spec.TargetSubnetName == "" {
return []string{}
}
return []string{binding.Spec.TargetSubnetName}
}
}
// SetupFieldIndexers sets up the field indexers for SubnetConnectionBindingMap
func (r *Reconciler) SetupFieldIndexers(mgr ctrl.Manager) error {
if err := mgr.GetFieldIndexer().IndexField(context.TODO(), &v1alpha1.SubnetConnectionBindingMap{}, "spec.subnetName", subnetConnectionBindingMapSubnetNameIndexFunc); err != nil {
return err
}
if err := mgr.GetFieldIndexer().IndexField(context.TODO(), &v1alpha1.SubnetConnectionBindingMap{}, "spec.targetSubnetName", subnetConnectionBindingMapTargetSubnetNameIndexFunc); err != nil {
return err
}
return nil
}