• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

noironetworks / aci-containers / 11112

15 Oct 2025 06:07AM UTC coverage: 65.363% (-0.5%) from 65.838%
11112

push

travis-pro

web-flow
Merge pull request #1592 from noironetworks/epg_with_overlapping_vlan

Added fix for EPG with same VLAN issue and updated cache structure

1 of 269 new or added lines in 2 files covered. (0.37%)

127 existing lines in 3 files now uncovered.

13372 of 20458 relevant lines covered (65.36%)

0.75 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/pkg/controller/aaepmonitor.go
1
// Copyright 2019 Cisco Systems, Inc.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRATIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
// Handlers for AaepMonitor CR updates.
16

17
package controller
18

19
import (
20
        "context"
21
        "crypto/sha256"
22
        "encoding/hex"
23
        "encoding/json"
24
        "fmt"
25
        "regexp"
26
        "strconv"
27
        "strings"
28

29
        amv1 "github.com/noironetworks/aci-containers/pkg/aaepmonitor/apis/aci.attachmentmonitor/v1"
30
        aaepmonitorclientset "github.com/noironetworks/aci-containers/pkg/aaepmonitor/clientset/versioned"
31
        "github.com/noironetworks/aci-containers/pkg/apicapi"
32

33
        nadapi "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
34
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
35
        "k8s.io/apimachinery/pkg/runtime"
36
        "k8s.io/apimachinery/pkg/watch"
37
        "k8s.io/client-go/tools/cache"
38
        "k8s.io/kubernetes/pkg/controller"
39
)
40

41
const (
42
        aaepMonitorCRDName = "aaepmonitors.aci.attachmentmonitor"
43
)
44

45
func (cont *AciController) queueAaepMonitorConfigByKey(key string) {
×
46
        cont.aaepMonitorConfigQueue.Add(key)
×
47
}
×
48

49
func aaepMonitorInit(cont *AciController, stopCh <-chan struct{}) {
×
50
        restconfig := cont.env.RESTConfig()
×
51
        aaepMonitorClient, err := aaepmonitorclientset.NewForConfig(restconfig)
×
52
        if err != nil {
×
53
                cont.log.Errorf("Failed to intialize aaepMonitorClient")
×
54
                return
×
55
        }
×
56

57
        cont.initAaepMonitorInformerFromClient(aaepMonitorClient)
×
58
        go cont.aaepMonitorInformer.Run(stopCh)
×
59
        go cont.processQueue(cont.aaepMonitorConfigQueue, cont.aaepMonitorInformer.GetIndexer(),
×
60
                func(obj interface{}) bool {
×
61
                        return cont.handleAaepMonitorConfigurationUpdate(obj)
×
62
                }, func(key string) bool {
×
63
                        return cont.handleAaepMonitorConfigurationDelete(key)
×
64
                }, nil, stopCh)
×
65
        cache.WaitForCacheSync(stopCh, cont.aaepMonitorInformer.HasSynced)
×
66
}
67

68
func (cont *AciController) initAaepMonitorInformerFromClient(
69
        aaepMonitorClient *aaepmonitorclientset.Clientset) {
×
70
        cont.initAaepMonitorInformerBase(
×
71
                &cache.ListWatch{
×
72
                        ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
×
73
                                return aaepMonitorClient.AciV1().AaepMonitors().List(context.TODO(), options)
×
74
                        },
×
75
                        WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
×
76
                                return aaepMonitorClient.AciV1().AaepMonitors().Watch(context.TODO(), options)
×
77
                        },
×
78
                })
79
}
80

81
func (cont *AciController) initAaepMonitorInformerBase(listWatch *cache.ListWatch) {
×
82
        cont.aaepMonitorInformer = cache.NewSharedIndexInformer(
×
83
                listWatch,
×
84
                &amv1.AaepMonitor{},
×
85
                controller.NoResyncPeriodFunc(),
×
86
                cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
×
87
        )
×
88
        cont.aaepMonitorInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
×
89
                AddFunc: func(obj interface{}) {
×
90
                        cont.aaepMonitorConfAdded(obj)
×
91
                },
×
92
                UpdateFunc: func(oldobj interface{}, newobj interface{}) {
×
93
                        cont.aaepMonitorConfUpdate(oldobj, newobj)
×
94
                },
×
95
                DeleteFunc: func(obj interface{}) {
×
96
                        cont.aaepMonitorConfDelete(obj)
×
97
                },
×
98
        })
99
}
100

101
func (cont *AciController) aaepMonitorConfAdded(obj interface{}) {
×
102
        aaepMonitorConfig, ok := obj.(*amv1.AaepMonitor)
×
103
        if !ok {
×
104
                cont.log.Error("aaepMonitorConfAdded: Bad object type")
×
105
                return
×
106
        }
×
107
        key, err := cache.MetaNamespaceKeyFunc(aaepMonitorConfig)
×
108
        if err != nil {
×
109
                return
×
110
        }
×
111
        cont.queueAaepMonitorConfigByKey(key)
×
112
}
113

114
func (cont *AciController) aaepMonitorConfUpdate(oldobj interface{}, newobj interface{}) {
×
115
        newAaepMonitorConfig := newobj.(*amv1.AaepMonitor)
×
116

×
117
        key, err := cache.MetaNamespaceKeyFunc(newAaepMonitorConfig)
×
118
        if err != nil {
×
119
                return
×
120
        }
×
121
        cont.queueAaepMonitorConfigByKey(key)
×
122
}
123

124
func (cont *AciController) aaepMonitorConfDelete(obj interface{}) {
×
125
        cont.indexMutex.Lock()
×
126
        defer cont.indexMutex.Unlock()
×
127
        aaepMonitorConfig, ok := obj.(*amv1.AaepMonitor)
×
128

×
129
        if !ok {
×
130
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
×
131
                if !ok {
×
132
                        cont.log.Errorf("Received unexpected object: ")
×
133
                        return
×
134
                }
×
135
                aaepMonitorConfig, ok = deletedState.Obj.(*amv1.AaepMonitor)
×
136
                if !ok {
×
137
                        cont.log.Errorf("DeletedFinalStateUnknown contained non-aaepmonitorconfiguration object: %v", deletedState.Obj)
×
138
                        return
×
139
                }
×
140
        }
141

142
        key, err := cache.MetaNamespaceKeyFunc(aaepMonitorConfig)
×
143
        if err != nil {
×
144
                return
×
145
        }
×
146
        cont.queueAaepMonitorConfigByKey("DELETED_" + key)
×
147
}
148

149
func (cont *AciController) handleAaepMonitorConfigurationUpdate(obj interface{}) bool {
×
150
        aaepMonitorConfig, ok := obj.(*amv1.AaepMonitor)
×
151
        if !ok {
×
152
                cont.log.Error("handleAaepMonitorConfigurationUpdate: Bad object type")
×
153
                return false
×
154
        }
×
155

156
        addedAaeps, removedAaeps := cont.getAaepDiff(aaepMonitorConfig.Spec.Aaeps)
×
157
        for _, aaepName := range addedAaeps {
×
158
                cont.reconcileNadData(aaepName)
×
159
        }
×
160

161
        for _, aaepName := range removedAaeps {
×
162
                cont.cleanAnnotationSubscriptions(aaepName)
×
163

×
164
                cont.indexMutex.Lock()
×
NEW
165
                aaepEpgAttachDataMap := cont.sharedAaepMonitor[aaepName]
×
166
                delete(cont.sharedAaepMonitor, aaepName)
×
167

×
NEW
168
                for epgDn, aaepEpgAttachData := range aaepEpgAttachDataMap {
×
NEW
169
                        cont.deleteNetworkAttachmentDefinition(aaepName, epgDn, aaepEpgAttachData, "AaepRemovedFromCR")
×
170
                }
×
171
                cont.indexMutex.Unlock()
×
172
        }
173

174
        return false
×
175
}
176

177
func (cont *AciController) handleAaepMonitorConfigurationDelete(key string) bool {
×
178
        cont.indexMutex.Lock()
×
179
        defer cont.indexMutex.Unlock()
×
NEW
180
        for aaepName, aaepEpgAttachDataMap := range cont.sharedAaepMonitor {
×
181
                cont.cleanAnnotationSubscriptions(aaepName)
×
182

×
NEW
183
                for epgDn, aaepEpgAttachData := range aaepEpgAttachDataMap {
×
NEW
184
                        cont.deleteNetworkAttachmentDefinition(aaepName, epgDn, aaepEpgAttachData, "CRDeleted")
×
UNCOV
185
                }
×
186
        }
187

NEW
188
        cont.sharedAaepMonitor = make(map[string]map[string]*AaepEpgAttachData)
×
189
        return false
×
190
}
191

192
func (cont *AciController) handleAaepEpgAttach(infraRsObj apicapi.ApicObject) {
×
193
        infraRsObjDn := infraRsObj.GetDn()
×
194
        aaepName := cont.matchesAEPFilter(infraRsObjDn)
×
195
        if aaepName == "" {
×
196
                cont.log.Debugf("Unable to find AAEP from %s in monitoring list", infraRsObjDn)
×
197
                return
×
198
        }
×
199

200
        state := infraRsObj.GetAttrStr("state")
×
201
        if state != "formed" {
×
202
                cont.log.Debugf("Skipping NAD creation: %s is with state: %s", infraRsObjDn, state)
×
203
                return
×
204
        }
×
205

206
        epgDn := infraRsObj.GetAttrStr("tDn")
×
NEW
207
        encap := infraRsObj.GetAttrStr("encap")
×
NEW
208
        vlanID := cont.getVlanId(encap)
×
NEW
209

×
NEW
210
        if cont.checkDuplicateAaepEpgAttachRequest(aaepName, epgDn, vlanID) {
×
NEW
211
                cont.log.Infof("AAEP %s EPG %s attachment data already exists", aaepName, epgDn)
×
NEW
212
                return
×
NEW
213
        }
×
214

NEW
215
        if cont.checkVlanUsedInCluster(vlanID) {
×
NEW
216
                // This is needed when user updates vlan to the vlan already used in cluster
×
NEW
217
                cont.handleOverlappingVlan(aaepName, epgDn, vlanID)
×
NEW
218

×
NEW
219
                cont.log.Errorf("Skipping NAD creation: VLAN %d is already used in cluster", vlanID)
×
NEW
220
                return
×
NEW
221
        }
×
222

223
        defer cont.apicConn.AddImmediateSubscriptionDnLocked(epgDn, []string{"tagAnnotation"}, cont.handleAnnotationAdded,
×
224
                cont.handleAnnotationDeleted)
×
225

×
NEW
226
        epgVlanMap := &EpgVlanMap{
×
227
                epgDn:     epgDn,
×
228
                encapVlan: vlanID,
×
229
        }
×
230

×
NEW
231
        aaepEpgAttachData := cont.collectNadData(epgVlanMap)
×
NEW
232
        if aaepEpgAttachData == nil {
×
233
                return
×
234
        }
×
235

NEW
236
        if cont.checkIfEpgWithOverlappingVlan(aaepName, vlanID) {
×
NEW
237
                // This is needed when user updates vlan from non-overlapping to overlapping
×
NEW
238
                cont.handleOverlappingVlan(aaepName, epgDn, vlanID)
×
NEW
239

×
NEW
240
                cont.indexMutex.Lock()
×
NEW
241
                if cont.sharedAaepMonitor[aaepName] == nil {
×
NEW
242
                        cont.sharedAaepMonitor[aaepName] = make(map[string]*AaepEpgAttachData)
×
NEW
243
                }
×
NEW
244
                aaepEpgAttachData.nadCreated = false
×
NEW
245
                cont.sharedAaepMonitor[aaepName][epgDn] = aaepEpgAttachData
×
NEW
246
                cont.indexMutex.Unlock()
×
NEW
247
                cont.log.Errorf("Skipping NAD creation: EPG %s with AAEP %s has overlapping VLAN %d", epgDn, aaepName, vlanID)
×
NEW
248
                return
×
249
        }
250
        cont.indexMutex.Lock()
×
NEW
251
        oldAaepMonitorData := cont.getAaepEpgAttachDataLocked(aaepName, epgDn)
×
252
        cont.indexMutex.Unlock()
×
253

×
NEW
254
        cont.syncNADsWithAciState(aaepName, epgDn, oldAaepMonitorData, aaepEpgAttachData, "AaepEpgAttached")
×
255
}
256

257
func (cont *AciController) handleAaepEpgDetach(infraRsObjDn string) {
×
258
        aaepName := cont.matchesAEPFilter(infraRsObjDn)
×
259
        if aaepName == "" {
×
260
                cont.log.Debugf("Unable to find AAEP from %s in monitoring list", infraRsObjDn)
×
261
                return
×
262
        }
×
263

264
        epgDn := cont.getEpgDnFromInfraRsDn(infraRsObjDn)
×
265

×
NEW
266
        // Need to check if EPG is not attached with any other AAEP
×
267
        if !cont.isEpgAttachedWithAaep(epgDn) {
×
268
                cont.apicConn.UnsubscribeImmediateDnLocked(epgDn, []string{"tagAnnotation"})
×
269
        }
×
270

271
        cont.indexMutex.Lock()
×
NEW
272
        aaepEpgAttachData := cont.getAaepEpgAttachDataLocked(aaepName, epgDn)
×
273
        cont.indexMutex.Unlock()
×
274

×
NEW
275
        if aaepEpgAttachData == nil {
×
NEW
276
                cont.log.Debugf("Monitoring data not available for EPG %s with AAEP %s", epgDn, aaepName)
×
NEW
277
                return
×
NEW
278
        }
×
NEW
279
        if !cont.namespaceChecks(aaepEpgAttachData.namespaceName, epgDn) {
×
NEW
280
                cont.log.Debugf("Namespace %s not found", aaepEpgAttachData.namespaceName)
×
NEW
281
                return
×
NEW
282
        }
×
283

NEW
284
        if aaepEpgAttachData.nadCreated == false {
×
NEW
285
                cont.indexMutex.Lock()
×
NEW
286
                delete(cont.sharedAaepMonitor[aaepName], epgDn)
×
NEW
287
                cont.indexMutex.Unlock()
×
288
                return
×
289
        }
×
290

291
        cont.indexMutex.Lock()
×
NEW
292
        delete(cont.sharedAaepMonitor[aaepName], epgDn)
×
NEW
293
        cont.deleteNetworkAttachmentDefinition(aaepName, epgDn, aaepEpgAttachData, "AaepEpgDetached")
×
UNCOV
294
        cont.indexMutex.Unlock()
×
NEW
295
        cont.createNadForNextEpg(aaepName, aaepEpgAttachData.encapVlan)
×
296
}
297

298
func (cont *AciController) handleAnnotationAdded(obj apicapi.ApicObject) bool {
×
299
        annotationDn := obj.GetDn()
×
300
        epgDn := annotationDn[:strings.Index(annotationDn, "/annotationKey-")]
×
301
        aaepMonitorDataMap := cont.getAaepMonitoringDataForEpg(epgDn)
×
302

×
303
        for aaepName, aaepMonitorData := range aaepMonitorDataMap {
×
304
                if aaepMonitorData == nil {
×
305
                        cont.log.Debugf("Insufficient data for NAD creation: Monitoring data not available for EPG %s with AAEP %s", epgDn, aaepName)
×
306
                        continue
×
307
                }
308

NEW
309
                if _, exists := aaepMonitorData[epgDn]; !exists {
×
NEW
310
                        cont.log.Debugf("EPG %s not found in monitoring data for AAEP %s", epgDn, aaepName)
×
NEW
311
                        continue
×
312
                }
313

NEW
314
                aaepEpgAttachData := aaepMonitorData[epgDn]
×
NEW
315
                if !cont.namespaceChecks(aaepEpgAttachData.namespaceName, epgDn) {
×
316
                        cont.log.Debugf("Insufficient data for NAD creation: Namespace not exist, in case of EPG %s with AAEP %s", epgDn, aaepName)
×
317
                        continue
×
318
                }
319

NEW
320
                if cont.checkIfEpgWithOverlappingVlan(aaepName, aaepEpgAttachData.encapVlan) {
×
NEW
321
                        cont.log.Debugf("Skipping EPG annotation add handling: EPG %s with AAEP %s has overlapping VLAN %d", epgDn,
×
NEW
322
                                aaepName, aaepEpgAttachData.encapVlan)
×
NEW
323
                        continue
×
324
                }
325

326
                cont.indexMutex.Lock()
×
NEW
327
                oldAaepMonitorData := cont.getAaepEpgAttachDataLocked(aaepName, epgDn)
×
328
                cont.indexMutex.Unlock()
×
NEW
329
                cont.syncNADsWithAciState(aaepName, epgDn, oldAaepMonitorData, aaepEpgAttachData, "NamespaceAnnotationAdded")
×
330
        }
331

332
        return true
×
333
}
334

335
func (cont *AciController) handleAnnotationDeleted(annotationDn string) {
×
336
        epgDn := annotationDn[:strings.Index(annotationDn, "/annotationKey-")]
×
337

×
338
        aaepMonitorDataMap := cont.getAaepMonitoringDataForEpg(epgDn)
×
339

×
340
        for aaepName, aaepMonitorData := range aaepMonitorDataMap {
×
341
                cont.indexMutex.Lock()
×
NEW
342
                oldAaepMonitorData := cont.getAaepEpgAttachDataLocked(aaepName, epgDn)
×
343
                cont.indexMutex.Unlock()
×
344

×
345
                if oldAaepMonitorData == nil {
×
346
                        cont.log.Debugf("Monitoring data not available for EPG %s with AAEP %s", epgDn, aaepName)
×
347
                        continue
×
348
                }
349

NEW
350
                if oldAaepMonitorData.nadCreated == false {
×
NEW
351
                        cont.indexMutex.Lock()
×
NEW
352
                        delete(cont.sharedAaepMonitor[aaepName], epgDn)
×
NEW
353
                        cont.indexMutex.Unlock()
×
NEW
354
                        continue
×
355
                }
356

357
                if aaepMonitorData == nil {
×
358
                        cont.indexMutex.Lock()
×
NEW
359
                        delete(cont.sharedAaepMonitor[aaepName], epgDn)
×
NEW
360
                        cont.deleteNetworkAttachmentDefinition(aaepName, epgDn, oldAaepMonitorData, "NamespaceAnnotationRemoved")
×
361
                        cont.indexMutex.Unlock()
×
362
                        continue
×
363
                }
364

NEW
365
                aaepEpgAttachData, exists := aaepMonitorData[epgDn]
×
NEW
366
                if !exists || aaepEpgAttachData == nil {
×
NEW
367
                        cont.indexMutex.Lock()
×
NEW
368
                        delete(cont.sharedAaepMonitor[aaepName], epgDn)
×
NEW
369
                        cont.deleteNetworkAttachmentDefinition(aaepName, epgDn, oldAaepMonitorData, "NamespaceAnnotationRemoved")
×
NEW
370
                        cont.indexMutex.Unlock()
×
NEW
371
                        continue
×
372
                }
373

NEW
374
                cont.syncNADsWithAciState(aaepName, epgDn, oldAaepMonitorData, aaepEpgAttachData, "NamespaceAnnotationRemoved")
×
375
        }
376
}
377

NEW
378
func (cont *AciController) collectNadData(epgVlanMap *EpgVlanMap) *AaepEpgAttachData {
×
NEW
379
        epgDn := epgVlanMap.epgDn
×
380
        epgAnnotations := cont.getEpgAnnotations(epgDn)
×
381
        namespaceName, nadName := cont.getSpecificEPGAnnotation(epgAnnotations)
×
382

×
383
        if !cont.namespaceChecks(namespaceName, epgDn) {
×
NEW
384
                cont.log.Debugf("Namespace not exist, in case of EPG %s", epgDn)
×
385
                return nil
×
386
        }
×
387

NEW
388
        aaepMonitoringData := &AaepEpgAttachData{
×
NEW
389
                encapVlan:     epgVlanMap.encapVlan,
×
390
                nadName:       nadName,
×
391
                namespaceName: namespaceName,
×
NEW
392
                nadCreated:    true,
×
393
        }
×
394

×
395
        return aaepMonitoringData
×
396
}
397

NEW
398
func (cont *AciController) getAaepEpgAttachDataLocked(aaepName, epgDn string) *AaepEpgAttachData {
×
NEW
399
        aaepEpgAttachDataMap, exists := cont.sharedAaepMonitor[aaepName]
×
NEW
400
        if !exists || aaepEpgAttachDataMap == nil {
×
401
                cont.log.Debugf("AAEP %s EPG %s attachment data not found", aaepName, epgDn)
×
NEW
402
                return nil
×
403
        }
×
404

NEW
405
        aaepEpgAttachData, exists := aaepEpgAttachDataMap[epgDn]
×
NEW
406
        if !exists || aaepEpgAttachData == nil {
×
NEW
407
                cont.log.Debugf("AAEP %s EPG %s attachment data not found", aaepName, epgDn)
×
NEW
408
                return nil
×
409
        }
×
410

NEW
411
        cont.log.Infof("Found attachment data: %v for EPG : %s AAEP: %s", *aaepEpgAttachData, epgDn, aaepName)
×
NEW
412
        return aaepEpgAttachData
×
413
}
414

415
func (cont *AciController) matchesAEPFilter(infraRsObjDn string) string {
×
416
        cont.indexMutex.Lock()
×
417
        defer cont.indexMutex.Unlock()
×
418
        var aaepName string
×
419
        for aaepName = range cont.sharedAaepMonitor {
×
420
                expectedPrefix := fmt.Sprintf("uni/infra/attentp-%s/", aaepName)
×
421
                if strings.HasPrefix(infraRsObjDn, expectedPrefix) {
×
422
                        return aaepName
×
423
                }
×
424
        }
425
        return ""
×
426
}
427

428
func (cont *AciController) getEpgDnFromInfraRsDn(infraRsObjDn string) string {
×
429
        re := regexp.MustCompile(`\[(.*?)\]`)
×
430
        match := re.FindStringSubmatch(infraRsObjDn)
×
431

×
432
        var epgDn string
×
433
        if len(match) > 1 {
×
434
                epgDn = match[1]
×
435
                return epgDn
×
436
        }
×
437

438
        return epgDn
×
439
}
440

NEW
441
func (cont *AciController) getAaepMonitoringDataForEpg(epgDn string) map[string]map[string]*AaepEpgAttachData {
×
NEW
442
        aaepEpgAttachData := make(map[string]map[string]*AaepEpgAttachData)
×
443

×
444
        cont.indexMutex.Lock()
×
445
        defer cont.indexMutex.Unlock()
×
NEW
446
        for aaepName := range cont.sharedAaepMonitor {
×
447
                encap := cont.getEncapFromAaepEpgAttachObj(aaepName, epgDn)
×
448

×
449
                if encap != "" {
×
450
                        vlanID := cont.getVlanId(encap)
×
NEW
451
                        epgVlanMap := EpgVlanMap{
×
452
                                epgDn:     epgDn,
×
453
                                encapVlan: vlanID,
×
454
                        }
×
NEW
455
                        if aaepEpgAttachData[aaepName] == nil {
×
NEW
456
                                aaepEpgAttachData[aaepName] = make(map[string]*AaepEpgAttachData)
×
NEW
457
                        }
×
NEW
458
                        aaepEpgAttachData[aaepName][epgDn] = cont.collectNadData(&epgVlanMap)
×
459
                }
460
        }
461

NEW
462
        return aaepEpgAttachData
×
463
}
464

465
func (cont *AciController) cleanAnnotationSubscriptions(aaepName string) {
×
NEW
466
        epgVlanMapList := cont.getAaepEpgAttObjDetails(aaepName)
×
NEW
467
        if epgVlanMapList == nil {
×
468
                return
×
469
        }
×
470

NEW
471
        for _, epgVlanMap := range epgVlanMapList {
×
NEW
472
                cont.apicConn.UnsubscribeImmediateDnLocked(epgVlanMap.epgDn, []string{"tagAnnotation"})
×
UNCOV
473
        }
×
474
}
475

476
func (cont *AciController) syncNADsWithAciState(aaepName string, epgDn string, oldAaepEpgAttachData,
NEW
477
        aaepEpgAttachData *AaepEpgAttachData, syncReason string) {
×
NEW
478
        if oldAaepEpgAttachData == nil {
×
479
                cont.indexMutex.Lock()
×
NEW
480
                needCacheChange := cont.createNetworkAttachmentDefinition(aaepName, epgDn, aaepEpgAttachData, syncReason)
×
481
                if needCacheChange {
×
NEW
482
                        if cont.sharedAaepMonitor[aaepName] == nil {
×
NEW
483
                                cont.sharedAaepMonitor[aaepName] = make(map[string]*AaepEpgAttachData)
×
NEW
484
                        }
×
NEW
485
                        cont.sharedAaepMonitor[aaepName][epgDn] = aaepEpgAttachData
×
486
                }
487
                cont.indexMutex.Unlock()
×
488
        } else {
×
NEW
489
                if oldAaepEpgAttachData.namespaceName != aaepEpgAttachData.namespaceName {
×
490
                        cont.indexMutex.Lock()
×
NEW
491
                        delete(cont.sharedAaepMonitor[aaepName], epgDn)
×
NEW
492
                        cont.deleteNetworkAttachmentDefinition(aaepName, epgDn, oldAaepEpgAttachData, syncReason)
×
493
                        cont.indexMutex.Unlock()
×
494

×
495
                        cont.indexMutex.Lock()
×
NEW
496
                        needCacheChange := cont.createNetworkAttachmentDefinition(aaepName, epgDn, aaepEpgAttachData, syncReason)
×
497
                        if needCacheChange {
×
NEW
498
                                if cont.sharedAaepMonitor[aaepName] == nil {
×
NEW
499
                                        cont.sharedAaepMonitor[aaepName] = make(map[string]*AaepEpgAttachData)
×
NEW
500
                                }
×
NEW
501
                                cont.sharedAaepMonitor[aaepName][epgDn] = aaepEpgAttachData
×
502
                        }
503
                        cont.indexMutex.Unlock()
×
504
                        return
×
505
                }
506

NEW
507
                if oldAaepEpgAttachData.nadName != aaepEpgAttachData.nadName || oldAaepEpgAttachData.encapVlan != aaepEpgAttachData.encapVlan {
×
508
                        cont.indexMutex.Lock()
×
NEW
509
                        needCacheChange := cont.createNetworkAttachmentDefinition(aaepName, epgDn, aaepEpgAttachData, syncReason)
×
510
                        if needCacheChange {
×
NEW
511
                                delete(cont.sharedAaepMonitor[aaepName], epgDn)
×
NEW
512
                                cont.sharedAaepMonitor[aaepName][epgDn] = aaepEpgAttachData
×
513
                        }
×
514
                        cont.indexMutex.Unlock()
×
515
                }
516

NEW
517
                if oldAaepEpgAttachData.encapVlan != aaepEpgAttachData.encapVlan {
×
NEW
518
                        cont.createNadForNextEpg(aaepName, oldAaepEpgAttachData.encapVlan)
×
NEW
519
                }
×
520
        }
521
}
522

523
func (cont *AciController) addDeferredNADs(namespaceName string) {
×
524
        cont.indexMutex.Lock()
×
525
        defer cont.indexMutex.Unlock()
×
526
        for aaepName := range cont.sharedAaepMonitor {
×
NEW
527
                epgVlanMapList := cont.getAaepEpgAttObjDetails(aaepName)
×
528

×
NEW
529
                if epgVlanMapList == nil {
×
530
                        continue
×
531
                }
532

NEW
533
                for _, epgVlanMap := range epgVlanMapList {
×
NEW
534
                        aaepEpgAttachData := cont.collectNadData(&epgVlanMap)
×
NEW
535
                        if aaepEpgAttachData == nil || aaepEpgAttachData.namespaceName != namespaceName {
×
UNCOV
536
                                continue
×
537
                        }
538

NEW
539
                        epgDn := epgVlanMap.epgDn
×
NEW
540
                        needCacheChange := cont.createNetworkAttachmentDefinition(aaepName, epgDn, aaepEpgAttachData, "NamespaceCreated")
×
541
                        if needCacheChange {
×
NEW
542
                                if cont.sharedAaepMonitor[aaepName] == nil {
×
NEW
543
                                        cont.sharedAaepMonitor[aaepName] = make(map[string]*AaepEpgAttachData)
×
NEW
544
                                }
×
NEW
545
                                cont.sharedAaepMonitor[aaepName][epgDn] = aaepEpgAttachData
×
546
                        }
547
                }
548
        }
549
}
550

551
func (cont *AciController) cleanNADs(namespaceName string) {
×
552
        cont.indexMutex.Lock()
×
553
        defer cont.indexMutex.Unlock()
×
554
        for aaepName := range cont.sharedAaepMonitor {
×
NEW
555
                aaepEpgAttachDataMap, exists := cont.sharedAaepMonitor[aaepName]
×
NEW
556
                if !exists || aaepEpgAttachDataMap == nil {
×
UNCOV
557
                        continue
×
558
                }
559

NEW
560
                var epgsToDelete []string
×
NEW
561
                for epgDn, aaepEpgData := range aaepEpgAttachDataMap {
×
562
                        if aaepEpgData.namespaceName != namespaceName {
×
NEW
563
                                epgsToDelete = append(epgsToDelete, epgDn)
×
564
                        }
×
565
                }
566

NEW
567
                for _, epgDn := range epgsToDelete {
×
NEW
568
                        delete(cont.sharedAaepMonitor[aaepName], epgDn)
×
NEW
569
                }
×
570
        }
571
}
572

NEW
573
func (cont *AciController) getAaepEpgAttObjDetails(aaepName string) []EpgVlanMap {
×
574
        uri := fmt.Sprintf("/api/node/mo/uni/infra/attentp-%s.json?query-target=subtree&target-subtree-class=infraRsFuncToEpg", aaepName)
×
575

×
576
        resp, err := cont.apicConn.GetApicResponse(uri)
×
577
        if err != nil {
×
578
                cont.log.Errorf("Failed to get response from APIC: %v", err)
×
579
                return nil
×
580
        }
×
581

582
        if len(resp.Imdata) == 0 {
×
583
                cont.log.Debugf("Can't find EPGs attached with AAEP %s", aaepName)
×
584
                return nil
×
585
        }
×
586

NEW
587
        epgVlanMapList := make([]EpgVlanMap, 0)
×
588
        for _, respImdata := range resp.Imdata {
×
589
                aaepEpgAttachObj, ok := respImdata["infraRsFuncToEpg"]
×
590
                if !ok {
×
591
                        cont.log.Debugf("Empty AAEP EPG attachment object")
×
592
                        continue
×
593
                }
594

595
                if state, hasState := aaepEpgAttachObj.Attributes["state"].(string); hasState {
×
596
                        if state != "formed" {
×
597
                                aaepEpgAttchDn := aaepEpgAttachObj.Attributes["dn"].(string)
×
598
                                cont.log.Debugf("%s is with state: %s", aaepEpgAttchDn, state)
×
599
                                continue
×
600
                        }
601
                }
602
                vlanID := 0
×
603
                if encap, hasEncap := aaepEpgAttachObj.Attributes["encap"].(string); hasEncap {
×
604
                        vlanID = cont.getVlanId(encap)
×
605
                }
×
606

NEW
607
                epgVlanMap := EpgVlanMap{
×
608
                        epgDn:     aaepEpgAttachObj.Attributes["tDn"].(string),
×
609
                        encapVlan: vlanID,
×
610
                }
×
NEW
611
                epgVlanMapList = append(epgVlanMapList, epgVlanMap)
×
612
        }
613

NEW
614
        return epgVlanMapList
×
615
}
616

617
func (cont *AciController) getEpgAnnotations(epgDn string) map[string]string {
×
618
        uri := fmt.Sprintf("/api/node/mo/%s.json?query-target=subtree&target-subtree-class=tagAnnotation", epgDn)
×
619
        resp, err := cont.apicConn.GetApicResponse(uri)
×
620
        if err != nil {
×
621
                cont.log.Errorf("Failed to get response from APIC: %v", err)
×
622
                return nil
×
623
        }
×
624

625
        annotationsMap := make(map[string]string)
×
626
        for _, respImdata := range resp.Imdata {
×
627
                annotationObj, ok := respImdata["tagAnnotation"]
×
628
                if !ok {
×
629
                        cont.log.Debugf("Empty tag annotation of EPG %s", epgDn)
×
630
                        continue
×
631
                }
632

633
                key := annotationObj.Attributes["key"].(string)
×
634
                annotationsMap[key] = annotationObj.Attributes["value"].(string)
×
635
        }
636

637
        return annotationsMap
×
638
}
639

640
func (cont *AciController) getSpecificEPGAnnotation(annotations map[string]string) (string, string) {
×
641
        namespaceNameAnnotationKey := cont.config.CnoIdentifier + "-namespace"
×
642
        namespaceName, exists := annotations[namespaceNameAnnotationKey]
×
643
        if !exists {
×
644
                cont.log.Debugf("Annotation with key '%s' not found", namespaceNameAnnotationKey)
×
645
        }
×
646

647
        nadNameAnnotationKey := cont.config.CnoIdentifier + "-nad"
×
648
        nadName, exists := annotations[nadNameAnnotationKey]
×
649
        if !exists {
×
650
                cont.log.Debugf("Annotation with key '%s' not found", nadNameAnnotationKey)
×
651
        }
×
652
        return namespaceName, nadName
×
653
}
654

655
func (cont *AciController) namespaceChecks(namespaceName string, epgDn string) bool {
×
656
        if namespaceName == "" {
×
657
                cont.log.Debugf("Defering NAD operation for EPG %s: Namespace name not provided in EPG annotation", epgDn)
×
658
                return false
×
659
        }
×
660

661
        kubeClient := cont.env.(*K8sEnvironment).kubeClient
×
662
        _, err := kubeClient.CoreV1().Namespaces().Get(context.TODO(), namespaceName, metav1.GetOptions{})
×
663
        namespaceExists := err == nil
×
664
        if !namespaceExists {
×
665
                cont.log.Debugf("Defering NAD operation for EPG %s: Namespace %s not exists", epgDn, namespaceName)
×
666
                return false
×
667
        }
×
668

669
        return true
×
670
}
671

672
func (cont *AciController) reconcileNadData(aaepName string) {
×
NEW
673
        epgVlanMapList := cont.getAaepEpgAttObjDetails(aaepName)
×
674

×
NEW
675
        for _, epgVlanMap := range epgVlanMapList {
×
NEW
676
                if cont.checkVlanUsedInCluster(epgVlanMap.encapVlan) {
×
NEW
677
                        cont.log.Errorf("Skipping NAD creation: VLAN %d is already used in cluster", epgVlanMap.encapVlan)
×
NEW
678
                        continue
×
679
                }
NEW
680
                aaepEpgAttachData := cont.collectNadData(&epgVlanMap)
×
NEW
681
                if aaepEpgAttachData == nil {
×
NEW
682
                        cont.apicConn.AddImmediateSubscriptionDnLocked(epgVlanMap.epgDn,
×
683
                                []string{"tagAnnotation"}, cont.handleAnnotationAdded,
×
684
                                cont.handleAnnotationDeleted)
×
685
                        continue
×
686
                }
687

NEW
688
                epgDn := epgVlanMap.epgDn
×
NEW
689
                if cont.checkIfEpgWithOverlappingVlan(aaepName, aaepEpgAttachData.encapVlan) {
×
NEW
690
                        aaepEpgAttachData.nadCreated = false
×
NEW
691
                        cont.indexMutex.Lock()
×
NEW
692
                        if cont.sharedAaepMonitor[aaepName] == nil {
×
NEW
693
                                cont.sharedAaepMonitor[aaepName] = make(map[string]*AaepEpgAttachData)
×
NEW
694
                        }
×
NEW
695
                        cont.sharedAaepMonitor[aaepName][epgDn] = aaepEpgAttachData
×
NEW
696
                        cont.indexMutex.Unlock()
×
NEW
697
                        cont.log.Errorf("Skipping NAD creation: EPG %s with AAEP %s has overlapping VLAN %d",
×
NEW
698
                                epgDn, aaepName, aaepEpgAttachData.encapVlan)
×
NEW
699
                        continue
×
700
                }
701

702
                cont.indexMutex.Lock()
×
NEW
703
                needCacheChange := cont.createNetworkAttachmentDefinition(aaepName, epgDn, aaepEpgAttachData, "AaepAddedInCR")
×
704
                if needCacheChange {
×
NEW
705
                        if cont.sharedAaepMonitor[aaepName] == nil {
×
NEW
706
                                cont.sharedAaepMonitor[aaepName] = make(map[string]*AaepEpgAttachData)
×
NEW
707
                        }
×
NEW
708
                        cont.sharedAaepMonitor[aaepName][epgDn] = aaepEpgAttachData
×
709
                }
710
                cont.indexMutex.Unlock()
×
711

×
NEW
712
                cont.apicConn.AddImmediateSubscriptionDnLocked(epgDn,
×
713
                        []string{"tagAnnotation"}, cont.handleAnnotationAdded,
×
714
                        cont.handleAnnotationDeleted)
×
715
        }
716

717
        cont.indexMutex.Lock()
×
718
        if _, ok := cont.sharedAaepMonitor[aaepName]; !ok {
×
NEW
719
                cont.sharedAaepMonitor[aaepName] = make(map[string]*AaepEpgAttachData)
×
720
        }
×
721
        cont.indexMutex.Unlock()
×
722
}
723

724
// clean converts a string to lowercase, removes underscores and dots,
725
// and replaces any other invalid character with a hyphen.
726
func cleanApicResourceNames(apicResource string) string {
×
727
        apicResource = strings.ToLower(apicResource)
×
728
        var stringBuilder strings.Builder
×
729
        for _, character := range apicResource {
×
730
                switch {
×
731
                case character == '_' || character == '.':
×
732
                        continue
×
733
                case (character >= 'a' && character <= 'z') || (character >= '0' && character <= '9') || character == '-':
×
734
                        stringBuilder.WriteRune(character)
×
735
                default:
×
736
                        stringBuilder.WriteRune('-')
×
737
                }
738
        }
739
        return strings.Trim(stringBuilder.String(), "-")
×
740
}
741

742
func (cont *AciController) generateDefaultNadName(aaepName, epgDn string) string {
×
743
        parts := strings.Split(epgDn, "/")
×
744

×
745
        tenant := parts[1][3:]
×
746
        appProfile := parts[2][3:]
×
747
        epgName := parts[3][4:]
×
748

×
749
        apicResourceNames := tenant + appProfile + epgName + aaepName
×
750
        hashBytes := sha256.Sum256([]byte(apicResourceNames))
×
751
        hash := hex.EncodeToString(hashBytes[:])[:16]
×
752

×
753
        return fmt.Sprintf("%s-%s-%s-%s",
×
754
                cleanApicResourceNames(tenant), cleanApicResourceNames(appProfile), cleanApicResourceNames(epgName), hash)
×
755
}
×
756

757
func (cont *AciController) isNADUpdateRequired(aaepName string, epgDn string, nadData *AaepEpgAttachData,
NEW
758
        existingNAD *nadapi.NetworkAttachmentDefinition) bool {
×
NEW
759
        vlanID := nadData.encapVlan
×
760
        namespaceName := nadData.namespaceName
×
761
        customNadName := nadData.nadName
×
NEW
762
        defaultNadName := cont.generateDefaultNadName(aaepName, epgDn)
×
763
        existingAnnotaions := existingNAD.ObjectMeta.Annotations
×
764
        if existingAnnotaions != nil {
×
765
                if existingNAD.ObjectMeta.Annotations["aci-sync-status"] == "out-of-sync" || existingNAD.ObjectMeta.Annotations["cno-name"] != customNadName {
×
766
                        return true
×
767
                }
×
768
        } else {
×
769
                // NAD exists, check if VLAN needs to be updated
×
770
                existingConfig := existingNAD.Spec.Config
×
771
                if existingConfig != "" {
×
772
                        var existingCNVConfig map[string]interface{}
×
773
                        if json.Unmarshal([]byte(existingConfig), &existingCNVConfig) == nil {
×
774
                                if existingVLAN, ok := existingCNVConfig["vlan"].(float64); ok {
×
775
                                        if int(existingVLAN) == vlanID {
×
776
                                                // VLAN hasn't changed, no update needed
×
NEW
777
                                                cont.log.Infof("NetworkAttachmentDefinition %s already exists with correct VLAN %d in namespace %s",
×
NEW
778
                                                        defaultNadName, vlanID, namespaceName)
×
779
                                                return false
×
780
                                        }
×
781
                                } else if vlanID == 0 {
×
782
                                        // Both existing and new have no VLAN, no update needed
×
783
                                        cont.log.Infof("NetworkAttachmentDefinition %s already exists with no VLAN in namespace %s", defaultNadName, namespaceName)
×
784
                                        return false
×
785
                                }
×
786
                        }
787
                }
788
        }
789

790
        return true
×
791
}
792

NEW
793
func (cont *AciController) createNetworkAttachmentDefinition(aaepName string, epgDn string, nadData *AaepEpgAttachData, createReason string) bool {
×
794
        bridge := cont.config.BridgeName
×
795
        if bridge == "" {
×
796
                cont.log.Errorf("Linux bridge name must be specified when creating NetworkAttachmentDefinitions")
×
797
                return false
×
798
        }
×
799

NEW
800
        vlanID := nadData.encapVlan
×
801
        namespaceName := nadData.namespaceName
×
802
        customNadName := nadData.nadName
×
NEW
803
        defaultNadName := cont.generateDefaultNadName(aaepName, epgDn)
×
804
        nadClient := cont.env.(*K8sEnvironment).nadClient
×
805
        mtu := 1500
×
806

×
807
        // Check if NAD already exists
×
808
        existingNAD, err := nadClient.K8sCniCncfIoV1().NetworkAttachmentDefinitions(namespaceName).Get(context.TODO(), defaultNadName, metav1.GetOptions{})
×
809
        nadExists := err == nil
×
810

×
NEW
811
        if nadExists && !cont.isNADUpdateRequired(aaepName, epgDn, nadData, existingNAD) {
×
812
                return true
×
813
        }
×
814

815
        cnvBridgeConfig := map[string]any{
×
816
                "cniVersion":       "0.3.1",
×
817
                "name":             defaultNadName,
×
818
                "type":             "bridge",
×
819
                "isDefaultGateway": true,
×
820
                "bridge":           bridge,
×
821
                "mtu":              mtu,
×
822
        }
×
823

×
824
        if vlanID > 0 {
×
825
                cnvBridgeConfig["vlan"] = vlanID
×
826
        }
×
827

828
        configJSON, err := json.Marshal(cnvBridgeConfig)
×
829
        if err != nil {
×
830
                cont.log.Errorf("Failed to marshal CNV bridge config: %v", err)
×
831
                return false
×
832
        }
×
833

834
        nad := &nadapi.NetworkAttachmentDefinition{
×
835
                TypeMeta: metav1.TypeMeta{
×
836
                        APIVersion: "k8s.cni.cncf.io/v1",
×
837
                        Kind:       "NetworkAttachmentDefinition",
×
838
                },
×
839
                ObjectMeta: metav1.ObjectMeta{
×
840
                        Name:      defaultNadName,
×
841
                        Namespace: namespaceName,
×
842
                        Labels: map[string]string{
×
843
                                "managed-by": "cisco-network-operator",
×
844
                                "vlan":       strconv.Itoa(vlanID),
×
845
                        },
×
846
                        Annotations: map[string]string{
×
847
                                "managed-by":      "cisco-network-operator",
×
848
                                "vlan":            strconv.Itoa(vlanID),
×
849
                                "cno-name":        customNadName,
×
850
                                "aci-sync-status": "in-sync",
×
851
                                "aaep-name":       aaepName,
×
NEW
852
                                "epg-dn":          epgDn,
×
853
                        },
×
854
                },
×
855
                Spec: nadapi.NetworkAttachmentDefinitionSpec{
×
856
                        Config: string(configJSON),
×
857
                },
×
858
        }
×
859

×
860
        if nadExists {
×
861
                nad.ObjectMeta.ResourceVersion = existingNAD.ObjectMeta.ResourceVersion
×
862

×
863
                updatedNad, err := nadClient.K8sCniCncfIoV1().NetworkAttachmentDefinitions(namespaceName).Update(context.TODO(), nad, metav1.UpdateOptions{})
×
864

×
865
                if err != nil {
×
866
                        cont.log.Errorf("Failed to update NetworkAttachmentDefinition %s from namespace %s : %v", customNadName, namespaceName, err)
×
867
                        return false
×
868
                }
×
869

870
                cont.log.Debugf("Existing NAD Annotations: %v, %s", existingNAD.ObjectMeta.Annotations, createReason)
×
871
                if existingNAD.ObjectMeta.Annotations["aci-sync-status"] == "out-of-sync" {
×
872
                        cont.submitEvent(updatedNad, createReason, cont.getNADRevampMessage(createReason))
×
873
                }
×
874
                cont.log.Infof("Updated NetworkAttachmentDefinition %s from namespace %s", defaultNadName, namespaceName)
×
875
        } else {
×
876
                _, err = nadClient.K8sCniCncfIoV1().NetworkAttachmentDefinitions(namespaceName).Create(context.TODO(), nad, metav1.CreateOptions{})
×
877
                if err != nil {
×
878
                        cont.log.Errorf("Failed to create NetworkAttachmentDefinition %s in namespace %s : %v", customNadName, namespaceName, err)
×
879
                        return false
×
880
                }
×
881
                cont.log.Infof("Created NetworkAttachmentDefinition %s in namespace %s", defaultNadName, namespaceName)
×
882
        }
883

884
        return true
×
885
}
886

NEW
887
func (cont *AciController) deleteNetworkAttachmentDefinition(aaepName string, epgDn string, nadData *AaepEpgAttachData, deleteReason string) {
×
888
        namespaceName := nadData.namespaceName
×
889

×
890
        kubeClient := cont.env.(*K8sEnvironment).kubeClient
×
891
        _, err := kubeClient.CoreV1().Namespaces().Get(context.TODO(), namespaceName, metav1.GetOptions{})
×
892
        namespaceExists := err == nil
×
893
        if !namespaceExists {
×
894
                cont.log.Debugf("Defering NAD deletion for EPG %s: Namespace %s not exists", epgDn, namespaceName)
×
895
                return
×
896
        }
×
897

NEW
898
        nadName := cont.generateDefaultNadName(aaepName, epgDn)
×
899
        nadClient := cont.env.(*K8sEnvironment).nadClient
×
900

×
901
        nadDetails, err := nadClient.K8sCniCncfIoV1().NetworkAttachmentDefinitions(namespaceName).Get(context.TODO(), nadName, metav1.GetOptions{})
×
902
        nadExists := err == nil
×
903

×
904
        if nadExists {
×
905
                if !cont.isVmmLiteNAD(nadDetails) {
×
906
                        return
×
907
                }
×
908

909
                if cont.isNADinUse(namespaceName, nadName) {
×
910
                        nadDetails.ObjectMeta.Annotations["aci-sync-status"] = "out-of-sync"
×
911
                        _, err = nadClient.K8sCniCncfIoV1().NetworkAttachmentDefinitions(namespaceName).Update(context.TODO(), nadDetails, metav1.UpdateOptions{})
×
912
                        if err != nil {
×
913
                                cont.log.Errorf("Failed to add out-of-sync annotation to the NAD %s from namespace %s : %v", nadName, namespaceName, err)
×
914
                                return
×
915
                        }
×
916
                        cont.submitEvent(nadDetails, deleteReason, cont.getNADDeleteMessage(deleteReason))
×
917
                        cont.log.Infof("Added annotation out-of-sync for NAD %s from namespace %s", nadName, namespaceName)
×
918
                        return
×
919
                }
920

921
                delete(nadDetails.ObjectMeta.Annotations, "managed-by")
×
922
                _, err = nadClient.K8sCniCncfIoV1().NetworkAttachmentDefinitions(namespaceName).Update(context.TODO(), nadDetails, metav1.UpdateOptions{})
×
923
                if err != nil {
×
924
                        cont.log.Errorf("Failed to remove VMM lite annotation from NetworkAttachmentDefinition %s from namespace %s: %v", nadName, namespaceName, err)
×
925
                        return
×
926
                }
×
927

928
                nadClient.K8sCniCncfIoV1().NetworkAttachmentDefinitions(namespaceName).Delete(context.TODO(), nadName, metav1.DeleteOptions{})
×
929
                cont.log.Infof("Deleted NAD %s from %s namespace", nadName, namespaceName)
×
930
        } else {
×
931
                cont.log.Debugf("NAD %s not there to delete in namespace %s", nadName, namespaceName)
×
932
        }
×
933
}
934

935
func (cont *AciController) getVlanId(encap string) int {
×
936
        if after, ok := strings.CutPrefix(encap, "vlan-"); ok {
×
937
                vlanStr := after
×
938
                if vlanID, err := strconv.Atoi(vlanStr); err == nil && vlanID > 0 {
×
939
                        return vlanID
×
940
                }
×
941
        } else if after, ok := strings.CutPrefix(encap, "vlan"); ok {
×
942
                vlanStr := after
×
943
                if vlanID, err := strconv.Atoi(vlanStr); err == nil && vlanID > 0 {
×
944
                        return vlanID
×
945
                }
×
946
        }
947

948
        return 0
×
949
}
950

951
func (cont *AciController) getAaepDiff(crAaeps []string) (addedAaeps, removedAaeps []string) {
×
952
        crAaepMap := make(map[string]bool)
×
953
        for _, crAaep := range crAaeps {
×
954
                crAaepMap[crAaep] = true
×
955
        }
×
956

957
        cont.indexMutex.Lock()
×
958
        for _, crAaep := range crAaeps {
×
959
                if _, ok := cont.sharedAaepMonitor[crAaep]; !ok {
×
960
                        addedAaeps = append(addedAaeps, crAaep)
×
961
                }
×
962
        }
963
        cont.indexMutex.Unlock()
×
964

×
965
        cont.indexMutex.Lock()
×
966
        for cachedAaep := range cont.sharedAaepMonitor {
×
967
                if !crAaepMap[cachedAaep] {
×
968
                        removedAaeps = append(removedAaeps, cachedAaep)
×
969
                }
×
970
        }
971
        cont.indexMutex.Unlock()
×
972

×
973
        return
×
974
}
975

976
func (cont *AciController) getEncapFromAaepEpgAttachObj(aaepName, epgDn string) string {
×
977
        uri := fmt.Sprintf("/api/node/mo/uni/infra/attentp-%s/gen-default/rsfuncToEpg-[%s].json?query-target=self", aaepName, epgDn)
×
978
        resp, err := cont.apicConn.GetApicResponse(uri)
×
979
        if err != nil {
×
980
                cont.log.Errorf("Failed to get response from APIC: AAEP %s and EPG %s ERROR: %v", aaepName, epgDn, err)
×
981
                return ""
×
982
        }
×
983

984
        for _, obj := range resp.Imdata {
×
985
                lresp, ok := obj["infraRsFuncToEpg"]
×
986
                if !ok {
×
987
                        cont.log.Errorf("InfraRsFuncToEpg object not found in response for %s", uri)
×
988
                        break
×
989
                }
990
                if val, ok := lresp.Attributes["encap"]; ok {
×
991
                        encap := val.(string)
×
992
                        return encap
×
993
                } else {
×
994
                        cont.log.Errorf("Encap missing for infraRsFuncToEpg object for %s: %v", uri, err)
×
995
                        break
×
996
                }
997
        }
998

999
        return ""
×
1000
}
1001

1002
func (cont *AciController) isVmmLiteNAD(nadDetails *nadapi.NetworkAttachmentDefinition) bool {
×
1003
        return nadDetails.ObjectMeta.Annotations["managed-by"] == "cisco-network-operator"
×
1004
}
×
1005

1006
func (cont *AciController) isNADinUse(namespaceName string, nadName string) bool {
×
1007
        kubeClient := cont.env.(*K8sEnvironment).kubeClient
×
1008
        pods, err := kubeClient.CoreV1().Pods(namespaceName).List(context.TODO(), metav1.ListOptions{})
×
1009
        if err == nil {
×
1010
                var networks []map[string]string
×
1011
                for _, pod := range pods.Items {
×
1012
                        networksAnn, ok := pod.Annotations["k8s.v1.cni.cncf.io/networks"]
×
1013
                        if ok && (networksAnn == nadName) {
×
1014
                                cont.log.Infof("NAD %s is still used by Pod %s/%s", nadName, namespaceName, pod.Name)
×
1015
                                return true
×
1016
                        }
×
1017
                        if err := json.Unmarshal([]byte(networksAnn), &networks); err != nil {
×
1018
                                cont.log.Errorf("Error while getting pod annotations: %v", err)
×
1019
                                return false
×
1020
                        }
×
1021
                        for _, network := range networks {
×
1022
                                if ok && (network["name"] == nadName) {
×
1023
                                        cont.log.Infof("NAD %s is still used by VM %s/%s", nadName, namespaceName, pod.Name)
×
1024
                                        return true
×
1025
                                }
×
1026
                        }
1027
                }
1028
        }
1029
        return false
×
1030
}
1031

1032
func (cont *AciController) getNADDeleteMessage(deleteReason string) string {
×
1033
        messagePrefix := "NAD is in use by pods: "
×
1034
        switch {
×
1035
        case deleteReason == "NamespaceAnnotationRemoved":
×
1036
                return messagePrefix + "Either EPG deleted or namespace name EPG annotaion removed"
×
1037
        case deleteReason == "AaepEpgDetached":
×
1038
                return messagePrefix + "EPG detached from AAEP"
×
1039
        case deleteReason == "CRDeleted":
×
1040
                return messagePrefix + "aaepmonitor CR deleted"
×
1041
        case deleteReason == "AaepRemovedFromCR":
×
1042
                return messagePrefix + "AAEP removed from aaepmonitor CR"
×
NEW
1043
        case deleteReason == "AaepEpgAttachedWithVlanUsedInCluster":
×
NEW
1044
                return messagePrefix + "EPG with AAEP has overlapping VLAN with existing cluster VLAN"
×
NEW
1045
        case deleteReason == "AaepEpgAttachedWithOverlappingVlan":
×
NEW
1046
                return messagePrefix + "EPG with AAEP has overlapping VLAN with another EPG"
×
1047
        }
1048
        return messagePrefix + "One or many pods are using NAD"
×
1049
}
1050

1051
func (cont *AciController) getNADRevampMessage(createReason string) string {
×
1052
        messagePrefix := "NAD is in sync: "
×
1053
        switch {
×
1054
        case createReason == "NamespaceAnnotationAdded":
×
1055
                return messagePrefix + "Namespace name EPG annotaion added"
×
1056
        case createReason == "AaepEpgAttached":
×
1057
                return messagePrefix + "EPG attached with AAEP"
×
1058
        case createReason == "AaepAddedInCR":
×
1059
                return messagePrefix + "AAEP added back in aaepmonitor CR"
×
1060
        case createReason == "NamespaceCreated":
×
1061
                return messagePrefix + "Namespace created back"
×
NEW
1062
        case createReason == "NextEpgNadCreation":
×
NEW
1063
                return messagePrefix + "Next EPG NAD creation"
×
1064
        }
1065
        return messagePrefix + "NAD synced with ACI"
×
1066
}
1067

1068
func (cont *AciController) isEpgAttachedWithAaep(epgDn string) bool {
×
NEW
1069
        cont.indexMutex.Lock()
×
NEW
1070
        defer cont.indexMutex.Unlock()
×
1071
        for aaepName := range cont.sharedAaepMonitor {
×
1072
                encap := cont.getEncapFromAaepEpgAttachObj(aaepName, epgDn)
×
1073
                if encap != "" {
×
1074
                        return true
×
1075
                }
×
1076
        }
1077
        return false
×
1078
}
1079

NEW
1080
func (cont *AciController) checkDuplicateAaepEpgAttachRequest(aaepName, epgDn string, vlanID int) bool {
×
NEW
1081
        cont.indexMutex.Lock()
×
NEW
1082
        defer cont.indexMutex.Unlock()
×
NEW
1083
        aaepEpgAttachDataMap, exists := cont.sharedAaepMonitor[aaepName]
×
NEW
1084
        if !exists || aaepEpgAttachDataMap == nil {
×
NEW
1085
                return false
×
1086
        }
×
1087

NEW
1088
        aaepEpgAttachData, exists := aaepEpgAttachDataMap[epgDn]
×
NEW
1089
        if !exists || aaepEpgAttachData == nil {
×
NEW
1090
                return false
×
NEW
1091
        }
×
1092

NEW
1093
        if vlanID == aaepEpgAttachData.encapVlan {
×
NEW
1094
                return true
×
NEW
1095
        }
×
NEW
1096
        return false
×
1097
}
1098

NEW
1099
func (cont *AciController) checkIfEpgWithOverlappingVlan(aaepName string, vlanId int) bool {
×
NEW
1100
        cont.indexMutex.Lock()
×
NEW
1101
        defer cont.indexMutex.Unlock()
×
NEW
1102
        aaepEpgAttachDataMap, exists := cont.sharedAaepMonitor[aaepName]
×
NEW
1103
        if !exists || aaepEpgAttachDataMap == nil {
×
NEW
1104
                return false
×
NEW
1105
        }
×
1106

NEW
1107
        for _, aaepEpgData := range aaepEpgAttachDataMap {
×
NEW
1108
                if vlanId == aaepEpgData.encapVlan {
×
NEW
1109
                        return true
×
NEW
1110
                }
×
1111
        }
NEW
1112
        return false
×
1113
}
1114

NEW
1115
func (cont *AciController) createNadForNextEpg(aaepName string, vlanId int) {
×
NEW
1116
        cont.indexMutex.Lock()
×
NEW
1117
        defer cont.indexMutex.Unlock()
×
NEW
1118

×
NEW
1119
        aaepEpgAttachDataMap := cont.sharedAaepMonitor[aaepName]
×
NEW
1120
        for epgDn, aaepEpgAttachData := range aaepEpgAttachDataMap {
×
NEW
1121
                if aaepEpgAttachData.encapVlan != vlanId || aaepEpgAttachData.nadCreated {
×
NEW
1122
                        continue
×
1123
                }
NEW
1124
                if !cont.namespaceChecks(aaepEpgAttachData.namespaceName, epgDn) {
×
NEW
1125
                        continue
×
1126
                }
1127

NEW
1128
                needCacheChange := cont.createNetworkAttachmentDefinition(aaepName, epgDn, aaepEpgAttachData, "NextEpgNadCreation")
×
NEW
1129
                if needCacheChange {
×
NEW
1130
                        aaepEpgAttachData.nadCreated = true
×
NEW
1131
                        if cont.sharedAaepMonitor[aaepName] == nil {
×
NEW
1132
                                cont.sharedAaepMonitor[aaepName] = make(map[string]*AaepEpgAttachData)
×
NEW
1133
                        }
×
NEW
1134
                        cont.sharedAaepMonitor[aaepName][epgDn] = aaepEpgAttachData
×
1135
                }
1136
        }
1137
}
1138

NEW
1139
func (cont *AciController) checkVlanUsedInCluster(vlanId int) bool {
×
NEW
1140
        if vlanId == cont.config.KubeapiVlan {
×
NEW
1141
                return true
×
NEW
1142
        }
×
NEW
1143
        return false
×
1144
}
1145

NEW
1146
func (cont *AciController) handleOverlappingVlan(aaepName, epgDn string, vlanID int) {
×
NEW
1147
        cont.indexMutex.Lock()
×
NEW
1148
        oldAaepMonitorData := cont.getAaepEpgAttachDataLocked(aaepName, epgDn)
×
NEW
1149
        cont.indexMutex.Unlock()
×
NEW
1150

×
NEW
1151
        if oldAaepMonitorData != nil {
×
NEW
1152
                cont.indexMutex.Lock()
×
NEW
1153
                delete(cont.sharedAaepMonitor[aaepName], epgDn)
×
NEW
1154
                if oldAaepMonitorData.nadCreated {
×
NEW
1155
                        cont.log.Debugf("Deleting NAD for EPG %s with AAEP %s due to overlapping VLAN %d", epgDn, aaepName, vlanID)
×
NEW
1156
                        cont.deleteNetworkAttachmentDefinition(aaepName, epgDn, oldAaepMonitorData, "AaepEpgAttachedWithVlanUsedInCluster")
×
NEW
1157
                }
×
NEW
1158
                cont.indexMutex.Unlock()
×
NEW
1159
                if oldAaepMonitorData.nadCreated {
×
NEW
1160
                        cont.createNadForNextEpg(aaepName, oldAaepMonitorData.encapVlan)
×
UNCOV
1161
                }
×
1162
        }
1163
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc