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

noironetworks / aci-containers / 10628

16 May 2025 06:30PM UTC coverage: 68.723% (-0.07%) from 68.789%
10628

push

travis-pro

web-flow
Merge pull request #1522 from noironetworks/service-vlan-fix-backport

Skip service VLAN pre-provisioning for single leaf

0 of 13 new or added lines in 2 files covered. (0.0%)

11 existing lines in 4 files now uncovered.

13324 of 19388 relevant lines covered (68.72%)

0.78 hits per line

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

60.83
/pkg/controller/services.go
1
// Copyright 2016 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 WARRANTIES 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
package controller
16

17
import (
18
        "errors"
19
        "fmt"
20
        "net"
21
        "reflect"
22
        "regexp"
23
        "sort"
24
        "strconv"
25
        "strings"
26
        "time"
27

28
        "github.com/noironetworks/aci-containers/pkg/apicapi"
29
        "github.com/noironetworks/aci-containers/pkg/metadata"
30
        "github.com/noironetworks/aci-containers/pkg/util"
31
        "github.com/sirupsen/logrus"
32
        v1 "k8s.io/api/core/v1"
33
        discovery "k8s.io/api/discovery/v1"
34
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
35
        "k8s.io/apimachinery/pkg/fields"
36
        "k8s.io/apimachinery/pkg/labels"
37
        "k8s.io/client-go/kubernetes"
38
        "k8s.io/client-go/tools/cache"
39
)
40

41
// Default service contract scope value
42
const DefaultServiceContractScope = "context"
43

44
// Default service ext subnet scope - enable shared security
45
const DefaultServiceExtSubNetShared = false
46

47
func (cont *AciController) initEndpointsInformerFromClient(
48
        kubeClient kubernetes.Interface) {
×
49
        cont.initEndpointsInformerBase(
×
50
                cache.NewListWatchFromClient(
×
51
                        kubeClient.CoreV1().RESTClient(), "endpoints",
×
52
                        metav1.NamespaceAll, fields.Everything()))
×
53
}
×
54

55
func (cont *AciController) initEndpointSliceInformerFromClient(
56
        kubeClient kubernetes.Interface) {
×
57
        cont.initEndpointSliceInformerBase(
×
58
                cache.NewListWatchFromClient(
×
59
                        kubeClient.DiscoveryV1().RESTClient(), "endpointslices",
×
60
                        metav1.NamespaceAll, fields.Everything()))
×
61
}
×
62

63
func (cont *AciController) initEndpointSliceInformerBase(listWatch *cache.ListWatch) {
1✔
64
        cont.endpointSliceIndexer, cont.endpointSliceInformer = cache.NewIndexerInformer(
1✔
65
                listWatch, &discovery.EndpointSlice{}, 0,
1✔
66
                cache.ResourceEventHandlerFuncs{
1✔
67
                        AddFunc: func(obj interface{}) {
2✔
68
                                cont.endpointSliceAdded(obj)
1✔
69
                        },
1✔
70
                        UpdateFunc: func(oldobj interface{}, newobj interface{}) {
1✔
71
                                cont.endpointSliceUpdated(oldobj, newobj)
1✔
72
                        },
1✔
73
                        DeleteFunc: func(obj interface{}) {
1✔
74
                                cont.endpointSliceDeleted(obj)
1✔
75
                        },
1✔
76
                },
77
                cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
78
        )
79
}
80

81
func (cont *AciController) initEndpointsInformerBase(listWatch *cache.ListWatch) {
1✔
82
        cont.endpointsIndexer, cont.endpointsInformer = cache.NewIndexerInformer(
1✔
83
                listWatch, &v1.Endpoints{}, 0,
1✔
84
                cache.ResourceEventHandlerFuncs{
1✔
85
                        AddFunc: func(obj interface{}) {
2✔
86
                                cont.endpointsAdded(obj)
1✔
87
                        },
1✔
88
                        UpdateFunc: func(old interface{}, new interface{}) {
1✔
89
                                cont.endpointsUpdated(old, new)
1✔
90
                        },
1✔
91
                        DeleteFunc: func(obj interface{}) {
1✔
92
                                cont.endpointsDeleted(obj)
1✔
93
                        },
1✔
94
                },
95
                cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
96
        )
97
}
98

99
func (cont *AciController) initServiceInformerFromClient(
100
        kubeClient *kubernetes.Clientset) {
×
101
        cont.initServiceInformerBase(
×
102
                cache.NewListWatchFromClient(
×
103
                        kubeClient.CoreV1().RESTClient(), "services",
×
104
                        metav1.NamespaceAll, fields.Everything()))
×
105
}
×
106

107
func (cont *AciController) initServiceInformerBase(listWatch *cache.ListWatch) {
1✔
108
        cont.serviceIndexer, cont.serviceInformer = cache.NewIndexerInformer(
1✔
109
                listWatch, &v1.Service{}, 0,
1✔
110
                cache.ResourceEventHandlerFuncs{
1✔
111
                        AddFunc: func(obj interface{}) {
2✔
112
                                cont.serviceAdded(obj)
1✔
113
                        },
1✔
114
                        UpdateFunc: func(old interface{}, new interface{}) {
1✔
115
                                cont.serviceUpdated(old, new)
1✔
116
                        },
1✔
117
                        DeleteFunc: func(obj interface{}) {
×
118
                                cont.serviceDeleted(obj)
×
119
                        },
×
120
                },
121
                cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
122
        )
123
}
124

125
func serviceLogger(log *logrus.Logger, as *v1.Service) *logrus.Entry {
1✔
126
        return log.WithFields(logrus.Fields{
1✔
127
                "namespace": as.ObjectMeta.Namespace,
1✔
128
                "name":      as.ObjectMeta.Name,
1✔
129
                "type":      as.Spec.Type,
1✔
130
        })
1✔
131
}
1✔
132

133
func (cont *AciController) queueIPNetPolUpdates(ips map[string]bool) {
1✔
134
        for ipStr := range ips {
2✔
135
                ip := net.ParseIP(ipStr)
1✔
136
                if ip == nil {
1✔
137
                        continue
×
138
                }
139
                entries, err := cont.netPolSubnetIndex.ContainingNetworks(ip)
1✔
140
                if err != nil {
1✔
141
                        cont.log.Error("Corrupted network policy IP index, err: ", err)
×
142
                        return
×
143
                }
×
144
                for _, entry := range entries {
2✔
145
                        for npkey := range entry.(*ipIndexEntry).keys {
2✔
146
                                cont.queueNetPolUpdateByKey(npkey)
1✔
147
                        }
1✔
148
                }
149
        }
150
}
151

152
func (cont *AciController) queuePortNetPolUpdates(ports map[string]targetPort) {
1✔
153
        for portkey := range ports {
2✔
154
                entry := cont.targetPortIndex[portkey]
1✔
155
                if entry == nil {
2✔
156
                        continue
1✔
157
                }
158
                for npkey := range entry.networkPolicyKeys {
2✔
159
                        cont.queueNetPolUpdateByKey(npkey)
1✔
160
                }
1✔
161
        }
162
}
163

164
func (cont *AciController) queueNetPolForEpAddrs(addrs []v1.EndpointAddress) {
1✔
165
        for _, addr := range addrs {
2✔
166
                if addr.TargetRef == nil || addr.TargetRef.Kind != "Pod" ||
1✔
167
                        addr.TargetRef.Namespace == "" || addr.TargetRef.Name == "" {
2✔
168
                        continue
1✔
169
                }
170
                podkey := addr.TargetRef.Namespace + "/" + addr.TargetRef.Name
1✔
171
                npkeys := cont.netPolEgressPods.GetObjForPod(podkey)
1✔
172
                ps := make(map[string]bool)
1✔
173
                for _, npkey := range npkeys {
2✔
174
                        cont.queueNetPolUpdateByKey(npkey)
1✔
175
                        ps[npkey] = true
1✔
176
                }
1✔
177
                // Process if the  any matching namedport wildcard policy is present
178
                // ignore np already processed policies
179
                cont.queueMatchingNamedNp(ps, podkey)
1✔
180
        }
181
}
182

183
func (cont *AciController) queueMatchingNamedNp(served map[string]bool, podkey string) {
1✔
184
        cont.indexMutex.Lock()
1✔
185
        for npkey := range cont.nmPortNp {
2✔
186
                if _, ok := served[npkey]; !ok {
2✔
187
                        if cont.checkPodNmpMatchesNp(npkey, podkey) {
2✔
188
                                cont.queueNetPolUpdateByKey(npkey)
1✔
189
                        }
1✔
190
                }
191
        }
192
        cont.indexMutex.Unlock()
1✔
193
}
194
func (cont *AciController) queueEndpointsNetPolUpdates(endpoints *v1.Endpoints) {
1✔
195
        for _, subset := range endpoints.Subsets {
2✔
196
                cont.queueNetPolForEpAddrs(subset.Addresses)
1✔
197
                cont.queueNetPolForEpAddrs(subset.NotReadyAddresses)
1✔
198
        }
1✔
199
}
200

201
func (cont *AciController) returnServiceIps(ips []net.IP) {
1✔
202
        for _, ip := range ips {
2✔
203
                if ip.To4() != nil {
2✔
204
                        cont.serviceIps.DeallocateIp(ip)
1✔
205
                } else if ip.To16() != nil {
3✔
206
                        cont.serviceIps.DeallocateIp(ip)
1✔
207
                }
1✔
208
        }
209
}
210

211
func returnIps(pool *netIps, ips []net.IP) {
1✔
212
        for _, ip := range ips {
2✔
213
                if ip.To4() != nil {
2✔
214
                        pool.V4.AddIp(ip)
1✔
215
                } else if ip.To16() != nil {
3✔
216
                        pool.V6.AddIp(ip)
1✔
217
                }
1✔
218
        }
219
}
220

221
func (cont *AciController) staticMonPolName() string {
1✔
222
        return cont.aciNameForKey("monPol", cont.env.ServiceBd())
1✔
223
}
1✔
224

225
func (cont *AciController) staticMonPolDn() string {
1✔
226
        if cont.config.AciServiceMonitorInterval > 0 {
2✔
227
                return fmt.Sprintf("uni/tn-%s/ipslaMonitoringPol-%s",
1✔
228
                        cont.config.AciVrfTenant, cont.staticMonPolName())
1✔
229
        }
1✔
230
        return ""
×
231
}
232

233
func (cont *AciController) staticServiceObjs() apicapi.ApicSlice {
1✔
234
        var serviceObjs apicapi.ApicSlice
1✔
235

1✔
236
        // Service bridge domain
1✔
237
        bdName := cont.aciNameForKey("bd", cont.env.ServiceBd())
1✔
238
        bd := apicapi.NewFvBD(cont.config.AciVrfTenant, bdName)
1✔
239
        if apicapi.ApicVersion >= "6.0(4c)" {
1✔
240
                bd.SetAttr("serviceBdRoutingDisable", "yes")
×
241
        }
×
242
        bd.SetAttr("arpFlood", "yes")
1✔
243
        bd.SetAttr("ipLearning", "no")
1✔
244
        bd.SetAttr("unkMacUcastAct", cont.config.UnknownMacUnicastAction)
1✔
245
        bdToOut := apicapi.NewRsBdToOut(bd.GetDn(), cont.config.AciL3Out)
1✔
246
        bd.AddChild(bdToOut)
1✔
247
        bdToVrf := apicapi.NewRsCtx(bd.GetDn(), cont.config.AciVrf)
1✔
248
        bd.AddChild(bdToVrf)
1✔
249

1✔
250
        bdn := bd.GetDn()
1✔
251
        for _, cidr := range cont.config.NodeServiceSubnets {
2✔
252
                sn := apicapi.NewFvSubnet(bdn, cidr)
1✔
253
                bd.AddChild(sn)
1✔
254
        }
1✔
255
        serviceObjs = append(serviceObjs, bd)
1✔
256

1✔
257
        // Service IP SLA monitoring policy
1✔
258
        if cont.config.AciServiceMonitorInterval > 0 {
2✔
259
                monPol := apicapi.NewFvIPSLAMonitoringPol(cont.config.AciVrfTenant,
1✔
260
                        cont.staticMonPolName())
1✔
261
                monPol.SetAttr("slaFrequency",
1✔
262
                        strconv.Itoa(cont.config.AciServiceMonitorInterval))
1✔
263
                serviceObjs = append(serviceObjs, monPol)
1✔
264
        }
1✔
265

266
        return serviceObjs
1✔
267
}
268

269
func (cont *AciController) initStaticServiceObjs() {
1✔
270
        cont.apicConn.WriteApicObjects(cont.config.AciPrefix+"_service_static",
1✔
271
                cont.staticServiceObjs())
1✔
272
}
1✔
273

274
func (cont *AciController) updateServicesForNode(nodename string) {
1✔
275
        cont.serviceEndPoints.UpdateServicesForNode(nodename)
1✔
276
}
1✔
277

278
// must have index lock
279
func (cont *AciController) getActiveFabricPathDn(node string) string {
×
280
        var fabricPathDn string
×
281
        sz := len(cont.nodeOpflexDevice[node])
×
282
        for i := range cont.nodeOpflexDevice[node] {
×
283
                device := cont.nodeOpflexDevice[node][sz-1-i]
×
284
                if device.GetAttrStr("state") == "connected" {
×
285
                        fabricPathDn = device.GetAttrStr("fabricPathDn")
×
286
                        break
×
287
                }
288
        }
289
        return fabricPathDn
×
290
}
291

292
func (cont *AciController) getOpflexOdevCount(node string) (int, string) {
×
293
        fabricPathDnCount := make(map[string]int)
×
294
        var maxCount int
×
295
        var fabricPathDn string
×
296
        for _, device := range cont.nodeOpflexDevice[node] {
×
297
                fabricpathdn := device.GetAttrStr("fabricPathDn")
×
298
                count, ok := fabricPathDnCount[fabricpathdn]
×
299
                if ok {
×
300
                        fabricPathDnCount[fabricpathdn] = count + 1
×
301
                } else {
×
302
                        fabricPathDnCount[fabricpathdn] = 1
×
303
                }
×
304
                if fabricPathDnCount[fabricpathdn] >= maxCount {
×
305
                        maxCount = fabricPathDnCount[fabricpathdn]
×
306
                        fabricPathDn = fabricpathdn
×
307
                }
×
308
        }
309
        return maxCount, fabricPathDn
×
310
}
311

312
func deleteDevicesFromList(delDevices, devices apicapi.ApicSlice) apicapi.ApicSlice {
×
313
        var newDevices apicapi.ApicSlice
×
314
        for _, device := range devices {
×
315
                found := false
×
316
                for _, delDev := range delDevices {
×
317
                        if reflect.DeepEqual(delDev, device) {
×
318
                                found = true
×
319
                        }
×
320
                }
321
                if !found {
×
322
                        newDevices = append(newDevices, device)
×
323
                }
×
324
        }
325
        return newDevices
×
326
}
327

328
func (cont *AciController) getAciPodSubnet(pod string) (string, error) {
×
329
        podslice := strings.Split(pod, "-")
×
330
        if len(podslice) < 2 {
×
331
                return "", fmt.Errorf("Failed to get podid from pod")
×
332
        }
×
333
        podid := podslice[1]
×
334
        var subnet string
×
335
        args := []string{
×
336
                "query-target=self",
×
337
        }
×
338
        url := fmt.Sprintf("/api/node/mo/uni/controller/setuppol/setupp-%s.json?%s", podid, strings.Join(args, "&"))
×
339
        apicresp, err := cont.apicConn.GetApicResponse(url)
×
340
        if err != nil {
×
341
                cont.log.Debug("Failed to get APIC response, err: ", err.Error())
×
342
                return subnet, err
×
343
        }
×
344
        for _, obj := range apicresp.Imdata {
×
345
                for _, body := range obj {
×
346
                        tepPool, ok := body.Attributes["tepPool"].(string)
×
347
                        if ok {
×
348
                                subnet = tepPool
×
349
                                break
×
350
                        }
351
                }
352
        }
353
        return subnet, nil
×
354
}
355

356
func (cont *AciController) createAciPodAnnotation(node string) (aciPodAnnot, error) {
×
357
        odevCount, fabricPathDn := cont.getOpflexOdevCount(node)
×
358
        nodeAciPodAnnot := cont.nodeACIPod[node]
×
359
        isSingleOdev := nodeAciPodAnnot.isSingleOpflexOdev
×
360
        if (odevCount == 0) ||
×
361
                (odevCount == 1 && !isSingleOdev) ||
×
362
                (odevCount == 1 && isSingleOdev && !nodeAciPodAnnot.disconnectTime.IsZero()) {
×
363
                if nodeAciPodAnnot.aciPod != "none" {
×
364
                        if nodeAciPodAnnot.disconnectTime.IsZero() {
×
365
                                nodeAciPodAnnot.disconnectTime = time.Now()
×
366
                        } else {
×
367
                                currentTime := time.Now()
×
368
                                diff := currentTime.Sub(nodeAciPodAnnot.disconnectTime)
×
369
                                if diff.Seconds() > float64(cont.config.OpflexDeviceReconnectWaitTimeout) {
×
370
                                        nodeAciPodAnnot.aciPod = "none"
×
371
                                        nodeAciPodAnnot.disconnectTime = time.Time{}
×
372
                                }
×
373
                        }
374
                }
375
                if odevCount == 1 {
×
376
                        nodeAciPodAnnot.isSingleOpflexOdev = true
×
377
                }
×
378
                nodeAciPodAnnot.connectTime = time.Time{}
×
379
                return nodeAciPodAnnot, nil
×
380
        } else if (odevCount == 2) ||
×
381
                (odevCount == 1 && isSingleOdev && nodeAciPodAnnot.disconnectTime.IsZero()) {
×
382
                // when there is already a connected opflex device,
×
383
                // fabricPathDn will have latest pod iformation
×
384
                // and annotation will be in the form pod-<podid>-<subnet of pod>
×
385
                nodeAciPodAnnot.disconnectTime = time.Time{}
×
386
                nodeAciPod := nodeAciPodAnnot.aciPod
×
387
                if odevCount == 2 {
×
388
                        nodeAciPodAnnot.isSingleOpflexOdev = false
×
389
                }
×
390
                if odevCount == 1 && nodeAciPod == "none" {
×
391
                        if nodeAciPodAnnot.connectTime.IsZero() {
×
392
                                nodeAciPodAnnot.connectTime = time.Now()
×
393
                                return nodeAciPodAnnot, nil
×
394
                        } else {
×
395
                                currentTime := time.Now()
×
396
                                diff := currentTime.Sub(nodeAciPodAnnot.connectTime)
×
397
                                if diff.Seconds() < float64(10) {
×
398
                                        return nodeAciPodAnnot, nil
×
399
                                }
×
400
                        }
401
                }
402
                nodeAciPodAnnot.connectTime = time.Time{}
×
403
                pathSlice := strings.Split(fabricPathDn, "/")
×
404
                if len(pathSlice) > 1 {
×
405
                        pod := pathSlice[1]
×
406

×
407
                        // when there is difference in pod info avaliable from fabricPathDn
×
408
                        // and what we have in cache, update info in cache and change annotation on node
×
409
                        if !strings.Contains(nodeAciPod, pod) {
×
410
                                subnet, err := cont.getAciPodSubnet(pod)
×
411
                                if err != nil {
×
412
                                        cont.log.Error("Failed to get subnet of aci pod ", err.Error())
×
413
                                        return nodeAciPodAnnot, err
×
414
                                } else {
×
415
                                        nodeAciPodAnnot.aciPod = pod + "-" + subnet
×
416
                                        return nodeAciPodAnnot, nil
×
417
                                }
×
418
                        } else {
×
419
                                return nodeAciPodAnnot, nil
×
420
                        }
×
421
                } else {
×
422
                        cont.log.Error("Invalid fabricPathDn of opflexOdev of node ", node)
×
423
                        return nodeAciPodAnnot, fmt.Errorf("Invalid fabricPathDn of opflexOdev")
×
424
                }
×
425
        }
426
        return nodeAciPodAnnot, fmt.Errorf("Failed to get annotation for node %s", node)
×
427
}
428

429
func (cont *AciController) createNodeAciPodAnnotation(node string) (aciPodAnnot, error) {
×
430
        odevCount, fabricPathDn := cont.getOpflexOdevCount(node)
×
431
        nodeAciPodAnnot := cont.nodeACIPodAnnot[node]
×
432
        isSingleOdev := nodeAciPodAnnot.isSingleOpflexOdev
×
433
        if (odevCount == 0) ||
×
434
                (odevCount == 1 && !isSingleOdev) {
×
435
                if nodeAciPodAnnot.aciPod != "none" {
×
436
                        nodeAciPodAnnot.aciPod = "none"
×
437
                }
×
438
                if odevCount == 1 {
×
439
                        nodeAciPodAnnot.isSingleOpflexOdev = true
×
440
                }
×
441
                nodeAciPodAnnot.connectTime = time.Time{}
×
442
                return nodeAciPodAnnot, nil
×
443
        } else if (odevCount == 2) ||
×
444
                (odevCount == 1 && isSingleOdev) {
×
445
                nodeAciPod := nodeAciPodAnnot.aciPod
×
446
                if odevCount == 2 {
×
447
                        nodeAciPodAnnot.isSingleOpflexOdev = false
×
448
                }
×
449
                if odevCount == 1 && nodeAciPod == "none" {
×
450
                        if nodeAciPodAnnot.connectTime.IsZero() {
×
451
                                nodeAciPodAnnot.connectTime = time.Now()
×
452
                                return nodeAciPodAnnot, nil
×
453
                        } else {
×
454
                                currentTime := time.Now()
×
455
                                diff := currentTime.Sub(nodeAciPodAnnot.connectTime)
×
456
                                if diff.Seconds() < float64(10) {
×
457
                                        return nodeAciPodAnnot, nil
×
458
                                }
×
459
                        }
460
                }
461
                nodeAciPodAnnot.connectTime = time.Time{}
×
462
                pathSlice := strings.Split(fabricPathDn, "/")
×
463
                if len(pathSlice) > 1 {
×
464

×
465
                        nodeAciPodAnnot.aciPod = pathSlice[1]
×
466
                        return nodeAciPodAnnot, nil
×
467
                } else {
×
468
                        cont.log.Error("Invalid fabricPathDn of opflexOdev of node ", node)
×
469
                        return nodeAciPodAnnot, fmt.Errorf("Invalid fabricPathDn of opflexOdev")
×
470
                }
×
471
        }
472
        return nodeAciPodAnnot, fmt.Errorf("Failed to get annotation for node %s", node)
×
473
}
474

475
func (cont *AciController) checkChangeOfOpflexOdevAciPod() {
×
476
        var nodeAnnotationUpdates []string
×
477
        cont.apicConn.SyncMutex.Lock()
×
478
        syncDone := cont.apicConn.SyncDone
×
479
        cont.apicConn.SyncMutex.Unlock()
×
480

×
481
        if !syncDone {
×
482
                return
×
483
        }
×
484

485
        cont.indexMutex.Lock()
×
486
        for node := range cont.nodeACIPodAnnot {
×
487
                annot, err := cont.createNodeAciPodAnnotation(node)
×
488
                if err != nil {
×
489
                        if strings.Contains(fmt.Sprint(err), "Failed to get annotation") {
×
490
                                now := time.Now()
×
491
                                if annot.lastErrorTime.IsZero() || now.Sub(annot.lastErrorTime).Seconds() >= 60 {
×
492
                                        annot.lastErrorTime = now
×
493
                                        cont.nodeACIPodAnnot[node] = annot
×
494
                                        cont.log.Error(err.Error())
×
495
                                }
×
496
                        } else {
×
497
                                cont.log.Error(err.Error())
×
498
                        }
×
499
                } else {
×
500
                        if annot != cont.nodeACIPodAnnot[node] {
×
501
                                cont.nodeACIPodAnnot[node] = annot
×
502
                                nodeAnnotationUpdates = append(nodeAnnotationUpdates, node)
×
503
                        }
×
504
                }
505
        }
506
        cont.indexMutex.Unlock()
×
507
        if len(nodeAnnotationUpdates) > 0 {
×
508
                for _, updatednode := range nodeAnnotationUpdates {
×
509
                        go cont.env.NodeAnnotationChanged(updatednode)
×
510
                }
×
511
        }
512
}
513

514
func (cont *AciController) checkChangeOfOdevAciPod() {
×
515
        var nodeAnnotationUpdates []string
×
516
        cont.apicConn.SyncMutex.Lock()
×
517
        syncDone := cont.apicConn.SyncDone
×
518
        cont.apicConn.SyncMutex.Unlock()
×
519

×
520
        if !syncDone {
×
521
                return
×
522
        }
×
523

524
        cont.indexMutex.Lock()
×
525
        for node := range cont.nodeACIPod {
×
526
                annot, err := cont.createAciPodAnnotation(node)
×
527
                if err != nil {
×
528
                        if strings.Contains(fmt.Sprint(err), "Failed to get annotation") {
×
529
                                now := time.Now()
×
530
                                if annot.lastErrorTime.IsZero() || now.Sub(annot.lastErrorTime).Seconds() >= 60 {
×
531
                                        annot.lastErrorTime = now
×
532
                                        cont.nodeACIPod[node] = annot
×
533
                                        cont.log.Error(err.Error())
×
534
                                }
×
535
                        } else {
×
536
                                cont.log.Error(err.Error())
×
537
                        }
×
538
                } else {
×
539
                        if annot != cont.nodeACIPod[node] {
×
540
                                cont.nodeACIPod[node] = annot
×
541
                                nodeAnnotationUpdates = append(nodeAnnotationUpdates, node)
×
542
                        }
×
543
                }
544
        }
545
        cont.indexMutex.Unlock()
×
546
        if len(nodeAnnotationUpdates) > 0 {
×
547
                for _, updatednode := range nodeAnnotationUpdates {
×
548
                        go cont.env.NodeAnnotationChanged(updatednode)
×
549
                }
×
550
        }
551
}
552

553
func (cont *AciController) deleteOldOpflexDevices() {
1✔
554
        var nodeUpdates []string
1✔
555
        cont.indexMutex.Lock()
1✔
556
        for node, devices := range cont.nodeOpflexDevice {
1✔
557
                var delDevices apicapi.ApicSlice
×
558
                fabricPathDn := cont.getActiveFabricPathDn(node)
×
559
                if fabricPathDn != "" {
×
560
                        for _, device := range devices {
×
561
                                if device.GetAttrStr("delete") == "true" && device.GetAttrStr("fabricPathDn") != fabricPathDn {
×
562
                                        deleteTimeStr := device.GetAttrStr("deleteTime")
×
563
                                        deleteTime, err := time.Parse(time.RFC3339, deleteTimeStr)
×
564
                                        if err != nil {
×
565
                                                cont.log.Error("Failed to parse opflex device delete time: ", err)
×
566
                                                continue
×
567
                                        }
568
                                        now := time.Now()
×
569
                                        diff := now.Sub(deleteTime)
×
570
                                        if diff.Seconds() >= cont.config.OpflexDeviceDeleteTimeout {
×
571
                                                delDevices = append(delDevices, device)
×
572
                                        }
×
573
                                }
574
                        }
575
                        if len(delDevices) > 0 {
×
576
                                newDevices := deleteDevicesFromList(delDevices, devices)
×
577
                                cont.nodeOpflexDevice[node] = newDevices
×
578
                                cont.log.Info("Opflex device list for node ", node, " after deleting stale entries: ", cont.nodeOpflexDevice[node])
×
579
                                if len(newDevices) == 0 {
×
580
                                        delete(cont.nodeOpflexDevice, node)
×
581
                                }
×
582
                                nodeUpdates = append(nodeUpdates, node)
×
583
                        }
584
                }
585
        }
586
        cont.indexMutex.Unlock()
1✔
587
        if len(nodeUpdates) > 0 {
1✔
588
                cont.postOpflexDeviceDelete(nodeUpdates)
×
589
        }
×
590
}
591

592
// must have index lock
593
func (cont *AciController) setDeleteFlagForOldDevices(node, fabricPathDn string) {
1✔
594
        for _, device := range cont.nodeOpflexDevice[node] {
2✔
595
                if device.GetAttrStr("fabricPathDn") != fabricPathDn {
1✔
596
                        t := time.Now()
×
597
                        device.SetAttr("delete", "true")
×
598
                        device.SetAttr("deleteTime", t.Format(time.RFC3339))
×
599
                }
×
600
        }
601
}
602

603
// must have index lock
604
func (cont *AciController) fabricPathForNode(name string) (string, bool) {
1✔
605
        sz := len(cont.nodeOpflexDevice[name])
1✔
606
        for i := range cont.nodeOpflexDevice[name] {
2✔
607
                device := cont.nodeOpflexDevice[name][sz-1-i]
1✔
608
                deviceState := device.GetAttrStr("state")
1✔
609
                if deviceState == "connected" {
2✔
610
                        if deviceState != device.GetAttrStr("prevState") {
2✔
611
                                cont.fabricPathLogger(device.GetAttrStr("hostName"), device).Info("Processing fabric path for node ",
1✔
612
                                        "when connected device state is found")
1✔
613
                                device.SetAttr("prevState", deviceState)
1✔
614
                        }
1✔
615
                        fabricPathDn := device.GetAttrStr("fabricPathDn")
1✔
616
                        cont.setDeleteFlagForOldDevices(name, fabricPathDn)
1✔
617
                        return fabricPathDn, true
1✔
618
                } else {
1✔
619
                        device.SetAttr("prevState", deviceState)
1✔
620
                }
1✔
621
        }
622
        if sz > 0 {
2✔
623
                // When the opflex-device for a node changes, for example during a live migration,
1✔
624
                // we end up with both the old and the new device objects till the old object
1✔
625
                // ages out on APIC. The new object is at end of the devices list (see opflexDeviceChanged),
1✔
626
                // so we return the fabricPathDn of the last opflex-device.
1✔
627
                cont.fabricPathLogger(cont.nodeOpflexDevice[name][sz-1].GetAttrStr("hostName"),
1✔
628
                        cont.nodeOpflexDevice[name][sz-1]).Info("Processing fabricPathDn for node")
1✔
629
                return cont.nodeOpflexDevice[name][sz-1].GetAttrStr("fabricPathDn"), true
1✔
630
        }
1✔
631
        return "", false
1✔
632
}
633

634
// must have index lock
635
func (cont *AciController) deviceMacForNode(name string) (string, bool) {
1✔
636
        sz := len(cont.nodeOpflexDevice[name])
1✔
637
        if sz > 0 {
2✔
638
                // When the opflex-device for a node changes, for example when the
1✔
639
                // node is recreated, we end up with both the old and the new
1✔
640
                // device objects till the old object ages out on APIC. The
1✔
641
                // new object is at end of the devices list (see
1✔
642
                // opflexDeviceChanged), so we return the MAC address of the
1✔
643
                // last opflex-device.
1✔
644
                return cont.nodeOpflexDevice[name][sz-1].GetAttrStr("mac"), true
1✔
645
        }
1✔
646
        return "", false
1✔
647
}
648

649
func apicRedirectDst(rpDn string, ip string, mac string,
650
        descr string, healthGroupDn string, enablePbrTracking bool) apicapi.ApicObject {
1✔
651
        dst := apicapi.NewVnsRedirectDest(rpDn, ip, mac).SetAttr("descr", descr)
1✔
652
        if healthGroupDn != "" && enablePbrTracking {
2✔
653
                dst.AddChild(apicapi.NewVnsRsRedirectHealthGroup(dst.GetDn(),
1✔
654
                        healthGroupDn))
1✔
655
        }
1✔
656
        return dst
1✔
657
}
658

659
func (cont *AciController) apicRedirectPol(name string, tenantName string, nodes []string,
660
        nodeMap map[string]*metadata.ServiceEndpoint,
661
        monPolDn string, enablePbrTracking bool) (apicapi.ApicObject, string) {
1✔
662
        rp := apicapi.NewVnsSvcRedirectPol(tenantName, name)
1✔
663
        rp.SetAttr("thresholdDownAction", "deny")
1✔
664
        rpDn := rp.GetDn()
1✔
665
        for _, node := range nodes {
2✔
666
                cont.indexMutex.Lock()
1✔
667
                serviceEp, ok := nodeMap[node]
1✔
668
                if !ok {
1✔
669
                        continue
×
670
                }
671
                if serviceEp.Ipv4 != nil {
2✔
672
                        rp.AddChild(apicRedirectDst(rpDn, serviceEp.Ipv4.String(),
1✔
673
                                serviceEp.Mac, node, serviceEp.HealthGroupDn, enablePbrTracking))
1✔
674
                }
1✔
675
                if serviceEp.Ipv6 != nil {
1✔
676
                        rp.AddChild(apicRedirectDst(rpDn, serviceEp.Ipv6.String(),
×
677
                                serviceEp.Mac, node, serviceEp.HealthGroupDn, enablePbrTracking))
×
678
                }
×
679
                cont.indexMutex.Unlock()
1✔
680
        }
681
        if monPolDn != "" && enablePbrTracking {
2✔
682
                rp.AddChild(apicapi.NewVnsRsIPSLAMonitoringPol(rpDn, monPolDn))
1✔
683
        }
1✔
684
        return rp, rpDn
1✔
685
}
686

687
func apicExtNetCreate(enDn string, ingress string, ipv4 bool,
688
        cidr bool, sharedSec bool) apicapi.ApicObject {
1✔
689
        if !cidr {
2✔
690
                if ipv4 {
2✔
691
                        ingress += "/32"
1✔
692
                } else {
1✔
693
                        ingress += "/128"
×
694
                }
×
695
        }
696
        subnet := apicapi.NewL3extSubnet(enDn, ingress, "", "")
1✔
697
        if sharedSec {
2✔
698
                subnet.SetAttr("scope", "import-security,shared-security")
1✔
699
        }
1✔
700
        return subnet
1✔
701
}
702

703
func apicExtNet(name string, tenantName string, l3Out string,
704
        ingresses []string, sharedSecurity bool, snat bool) apicapi.ApicObject {
1✔
705
        en := apicapi.NewL3extInstP(tenantName, l3Out, name)
1✔
706
        enDn := en.GetDn()
1✔
707
        if snat {
2✔
708
                en.AddChild(apicapi.NewFvRsCons(enDn, name))
1✔
709
        } else {
2✔
710
                en.AddChild(apicapi.NewFvRsProv(enDn, name))
1✔
711
        }
1✔
712

713
        for _, ingress := range ingresses {
2✔
714
                ip, _, _ := net.ParseCIDR(ingress)
1✔
715
                // If ingress is a subnet
1✔
716
                if ip != nil {
2✔
717
                        if ip != nil && ip.To4() != nil {
2✔
718
                                subnet := apicExtNetCreate(enDn, ingress, true, true, sharedSecurity)
1✔
719
                                en.AddChild(subnet)
1✔
720
                        } else if ip != nil && ip.To16() != nil {
1✔
721
                                subnet := apicExtNetCreate(enDn, ingress, false, true, sharedSecurity)
×
722
                                en.AddChild(subnet)
×
723
                        }
×
724
                } else {
1✔
725
                        // If ingress is an IP address
1✔
726
                        ip := net.ParseIP(ingress)
1✔
727
                        if ip != nil && ip.To4() != nil {
2✔
728
                                subnet := apicExtNetCreate(enDn, ingress, true, false, sharedSecurity)
1✔
729
                                en.AddChild(subnet)
1✔
730
                        } else if ip != nil && ip.To16() != nil {
1✔
731
                                subnet := apicExtNetCreate(enDn, ingress, false, false, sharedSecurity)
×
732
                                en.AddChild(subnet)
×
733
                        }
×
734
                }
735
        }
736
        return en
1✔
737
}
738

739
func apicDefaultEgCons(conName string, tenantName string,
740
        appProfile string, epg string) apicapi.ApicObject {
×
741
        enDn := fmt.Sprintf("uni/tn-%s/ap-%s/epg-%s", tenantName, appProfile, epg)
×
742
        return apicapi.NewFvRsCons(enDn, conName)
×
743
}
×
744

745
func apicExtNetCons(conName string, tenantName string,
746
        l3Out string, net string) apicapi.ApicObject {
1✔
747
        enDn := fmt.Sprintf("uni/tn-%s/out-%s/instP-%s", tenantName, l3Out, net)
1✔
748
        return apicapi.NewFvRsCons(enDn, conName)
1✔
749
}
1✔
750

751
func apicExtNetProv(conName string, tenantName string,
752
        l3Out string, net string) apicapi.ApicObject {
1✔
753
        enDn := fmt.Sprintf("uni/tn-%s/out-%s/instP-%s", tenantName, l3Out, net)
1✔
754
        return apicapi.NewFvRsProv(enDn, conName)
1✔
755
}
1✔
756

757
// Helper function to check if a string item exists in a slice
758
func stringInSlice(str string, list []string) bool {
1✔
759
        for _, v := range list {
2✔
760
                if v == str {
2✔
761
                        return true
1✔
762
                }
1✔
763
        }
764
        return false
×
765
}
766

767
func validScope(scope string) bool {
1✔
768
        validValues := []string{"", "context", "tenant", "global"}
1✔
769
        return stringInSlice(scope, validValues)
1✔
770
}
1✔
771

772
func (cont *AciController) getGraphNameFromContract(name, tenantName string) (string, error) {
×
773
        var graphName string
×
774
        args := []string{
×
775
                "query-target=subtree",
×
776
        }
×
777
        url := fmt.Sprintf("/api/node/mo/uni/tn-%s/brc-%s.json?%s", tenantName, name, strings.Join(args, "&"))
×
778
        apicresp, err := cont.apicConn.GetApicResponse(url)
×
779
        if err != nil {
×
780
                cont.log.Debug("Failed to get APIC response, err: ", err.Error())
×
781
                return graphName, err
×
782
        }
×
783
        for _, obj := range apicresp.Imdata {
×
784
                for class, body := range obj {
×
785
                        if class == "vzRsSubjGraphAtt" {
×
786
                                tnVnsAbsGraphName, ok := body.Attributes["tnVnsAbsGraphName"].(string)
×
787
                                if ok {
×
788
                                        graphName = tnVnsAbsGraphName
×
789
                                }
×
790
                                break
×
791
                        }
792
                }
793
        }
794
        cont.log.Debug("graphName: ", graphName)
×
795
        return graphName, err
×
796
}
797

798
func apicContract(conName string, tenantName string,
799
        graphName string, scopeName string, isSnatPbrFltrChain bool,
800
        customSGAnnot bool) apicapi.ApicObject {
1✔
801
        con := apicapi.NewVzBrCP(tenantName, conName)
1✔
802
        if scopeName != "" && scopeName != "context" {
2✔
803
                con.SetAttr("scope", scopeName)
1✔
804
        }
1✔
805
        cs := apicapi.NewVzSubj(con.GetDn(), "loadbalancedservice")
1✔
806
        csDn := cs.GetDn()
1✔
807
        if isSnatPbrFltrChain {
2✔
808
                cs.SetAttr("revFltPorts", "no")
1✔
809
                inTerm := apicapi.NewVzInTerm(csDn)
1✔
810
                outTerm := apicapi.NewVzOutTerm(csDn)
1✔
811
                inTerm.AddChild(apicapi.NewVzRsInTermGraphAtt(inTerm.GetDn(), graphName))
1✔
812
                inTerm.AddChild(apicapi.NewVzRsFiltAtt(inTerm.GetDn(), conName+"_fromCons-toProv"))
1✔
813
                outTerm.AddChild(apicapi.NewVzRsOutTermGraphAtt(outTerm.GetDn(), graphName))
1✔
814
                outTerm.AddChild(apicapi.NewVzRsFiltAtt(outTerm.GetDn(), conName+"_fromProv-toCons"))
1✔
815
                cs.AddChild(inTerm)
1✔
816
                cs.AddChild(outTerm)
1✔
817
        } else {
2✔
818
                cs.AddChild(apicapi.NewVzRsSubjGraphAtt(csDn, graphName, customSGAnnot))
1✔
819
                cs.AddChild(apicapi.NewVzRsSubjFiltAtt(csDn, conName))
1✔
820
        }
1✔
821
        con.AddChild(cs)
1✔
822
        return con
1✔
823
}
824

825
func apicDevCtx(name string, tenantName string,
826
        graphName string, deviceName string, bdName string, rpDn string, isSnatPbrFltrChain bool) apicapi.ApicObject {
1✔
827
        cc := apicapi.NewVnsLDevCtx(tenantName, name, graphName, "loadbalancer")
1✔
828
        ccDn := cc.GetDn()
1✔
829
        graphDn := fmt.Sprintf("uni/tn-%s/lDevVip-%s", tenantName, deviceName)
1✔
830
        lifDn := fmt.Sprintf("%s/lIf-%s", graphDn, "interface")
1✔
831
        bdDn := fmt.Sprintf("uni/tn-%s/BD-%s", tenantName, bdName)
1✔
832
        cc.AddChild(apicapi.NewVnsRsLDevCtxToLDev(ccDn, graphDn))
1✔
833
        rpDnBase := rpDn
1✔
834
        for _, ctxConn := range []string{"consumer", "provider"} {
2✔
835
                lifCtx := apicapi.NewVnsLIfCtx(ccDn, ctxConn)
1✔
836
                if isSnatPbrFltrChain {
2✔
837
                        if ctxConn == "consumer" {
2✔
838
                                rpDn = rpDnBase + "_Cons"
1✔
839
                        } else {
2✔
840
                                rpDn = rpDnBase + "_Prov"
1✔
841
                        }
1✔
842
                }
843
                lifCtxDn := lifCtx.GetDn()
1✔
844
                lifCtx.AddChild(apicapi.NewVnsRsLIfCtxToSvcRedirectPol(lifCtxDn, rpDn))
1✔
845
                lifCtx.AddChild(apicapi.NewVnsRsLIfCtxToBD(lifCtxDn, bdDn))
1✔
846
                lifCtx.AddChild(apicapi.NewVnsRsLIfCtxToLIf(lifCtxDn, lifDn))
1✔
847
                cc.AddChild(lifCtx)
1✔
848
        }
849
        return cc
1✔
850
}
851

852
func apicFilterEntry(filterDn string, count string, p_start string,
853
        p_end string, protocol string, stateful string, snat bool, outTerm bool) apicapi.ApicObject {
1✔
854
        fe := apicapi.NewVzEntry(filterDn, count)
1✔
855
        fe.SetAttr("etherT", "ip")
1✔
856
        fe.SetAttr("prot", protocol)
1✔
857
        if snat {
2✔
858
                if outTerm {
2✔
859
                        if protocol == "tcp" {
2✔
860
                                fe.SetAttr("tcpRules", "est")
1✔
861
                        }
1✔
862
                        // Reverse the ports for outTerm
863
                        fe.SetAttr("dFromPort", p_start)
1✔
864
                        fe.SetAttr("dToPort", p_end)
1✔
865
                } else {
1✔
866
                        fe.SetAttr("sFromPort", p_start)
1✔
867
                        fe.SetAttr("sToPort", p_end)
1✔
868
                }
1✔
869
        } else {
1✔
870
                fe.SetAttr("dFromPort", p_start)
1✔
871
                fe.SetAttr("dToPort", p_end)
1✔
872
        }
1✔
873
        fe.SetAttr("stateful", stateful)
1✔
874
        return fe
1✔
875
}
876
func apicFilter(name string, tenantName string,
877
        portSpec []v1.ServicePort, snat bool, snatRange portRangeSnat) apicapi.ApicObject {
1✔
878
        filter := apicapi.NewVzFilter(tenantName, name)
1✔
879
        filterDn := filter.GetDn()
1✔
880

1✔
881
        var i int
1✔
882
        var port v1.ServicePort
1✔
883
        for i, port = range portSpec {
2✔
884
                pstr := strconv.Itoa(int(port.Port))
1✔
885
                proto := getProtocolStr(port.Protocol)
1✔
886
                fe := apicFilterEntry(filterDn, strconv.Itoa(i), pstr,
1✔
887
                        pstr, proto, "no", false, false)
1✔
888
                filter.AddChild(fe)
1✔
889
        }
1✔
890

891
        if snat {
1✔
892
                portSpec := []portRangeSnat{snatRange}
×
893
                p_start := strconv.Itoa(portSpec[0].start)
×
894
                p_end := strconv.Itoa(portSpec[0].end)
×
895

×
896
                fe1 := apicFilterEntry(filterDn, strconv.Itoa(i+1), p_start,
×
897
                        p_end, "tcp", "no", false, false)
×
898
                filter.AddChild(fe1)
×
899
                fe2 := apicFilterEntry(filterDn, strconv.Itoa(i+2), p_start,
×
900
                        p_end, "udp", "no", false, false)
×
901
                filter.AddChild(fe2)
×
902
        }
×
903
        return filter
1✔
904
}
905

906
func apicFilterSnat(name string, tenantName string,
907
        portSpec []portRangeSnat, outTerm bool) apicapi.ApicObject {
1✔
908
        filter := apicapi.NewVzFilter(tenantName, name)
1✔
909
        filterDn := filter.GetDn()
1✔
910

1✔
911
        p_start := strconv.Itoa(portSpec[0].start)
1✔
912
        p_end := strconv.Itoa(portSpec[0].end)
1✔
913

1✔
914
        fe := apicFilterEntry(filterDn, "0", p_start,
1✔
915
                p_end, "tcp", "no", true, outTerm)
1✔
916
        filter.AddChild(fe)
1✔
917
        fe1 := apicFilterEntry(filterDn, "1", p_start,
1✔
918
                p_end, "udp", "no", true, outTerm)
1✔
919
        filter.AddChild(fe1)
1✔
920

1✔
921
        return filter
1✔
922
}
1✔
923

924
func (cont *AciController) updateServiceDeviceInstance(key string,
925
        service *v1.Service) error {
1✔
926
        cont.indexMutex.Lock()
1✔
927
        nodeMap := make(map[string]*metadata.ServiceEndpoint)
1✔
928
        cont.serviceEndPoints.GetnodesMetadata(key, service, nodeMap)
1✔
929
        cont.indexMutex.Unlock()
1✔
930

1✔
931
        var nodes []string
1✔
932
        for node := range nodeMap {
2✔
933
                nodes = append(nodes, node)
1✔
934
        }
1✔
935
        sort.Strings(nodes)
1✔
936
        name := cont.aciNameForKey("svc", key)
1✔
937
        var conScope string
1✔
938
        scopeVal, ok := service.ObjectMeta.Annotations[metadata.ServiceContractScopeAnnotation]
1✔
939
        if ok {
2✔
940
                normScopeVal := strings.ToLower(scopeVal)
1✔
941
                if !validScope(normScopeVal) {
1✔
942
                        errString := "Invalid service contract scope value provided " + scopeVal
×
943
                        err := errors.New(errString)
×
944
                        serviceLogger(cont.log, service).Error("Could not create contract: ", err)
×
945
                        return err
×
946
                } else {
1✔
947
                        conScope = normScopeVal
1✔
948
                }
1✔
949
        } else {
1✔
950
                conScope = DefaultServiceContractScope
1✔
951
        }
1✔
952

953
        var sharedSecurity bool
1✔
954
        if conScope == "global" {
2✔
955
                sharedSecurity = true
1✔
956
        } else {
2✔
957
                sharedSecurity = DefaultServiceExtSubNetShared
1✔
958
        }
1✔
959

960
        graphName := cont.aciNameForKey("svc", "global")
1✔
961
        deviceName := cont.aciNameForKey("svc", "global")
1✔
962
        _, customSGAnnPresent := service.ObjectMeta.Annotations[metadata.ServiceGraphNameAnnotation]
1✔
963
        if customSGAnnPresent {
1✔
964
                customSG, err := cont.getGraphNameFromContract(name, cont.config.AciVrfTenant)
×
965
                if err == nil {
×
966
                        graphName = customSG
×
967
                }
×
968
        }
969
        cont.log.Debug("Using service graph ", graphName, " for service ", key)
1✔
970

1✔
971
        var serviceObjs apicapi.ApicSlice
1✔
972
        if len(nodes) > 0 {
2✔
973
                // 1. Service redirect policy
1✔
974
                // The service redirect policy contains the MAC address
1✔
975
                // and IP address of each of the service endpoints for
1✔
976
                // each node that hosts a pod for this service.  The
1✔
977
                // example below shows the case of two nodes.
1✔
978
                rp, rpDn :=
1✔
979
                        cont.apicRedirectPol(name, cont.config.AciVrfTenant, nodes,
1✔
980
                                nodeMap, cont.staticMonPolDn(), cont.config.AciPbrTrackingNonSnat)
1✔
981
                serviceObjs = append(serviceObjs, rp)
1✔
982

1✔
983
                // 2. Service graph contract and external network
1✔
984
                // The service graph contract must be bound to the service
1✔
985
                // graph.  This contract must be consumed by the default
1✔
986
                // layer 3 network and provided by the service layer 3
1✔
987
                // network.
1✔
988
                {
2✔
989
                        var ingresses []string
1✔
990
                        for _, ingress := range service.Status.LoadBalancer.Ingress {
2✔
991
                                ingresses = append(ingresses, ingress.IP)
1✔
992
                        }
1✔
993
                        serviceObjs = append(serviceObjs,
1✔
994
                                apicExtNet(name, cont.config.AciVrfTenant,
1✔
995
                                        cont.config.AciL3Out, ingresses, sharedSecurity, false))
1✔
996
                }
997

998
                contract := apicContract(name, cont.config.AciVrfTenant, graphName, conScope, false, customSGAnnPresent)
1✔
999
                serviceObjs = append(serviceObjs, contract)
1✔
1000
                for _, net := range cont.config.AciExtNetworks {
2✔
1001
                        serviceObjs = append(serviceObjs,
1✔
1002
                                apicExtNetCons(name, cont.config.AciVrfTenant,
1✔
1003
                                        cont.config.AciL3Out, net))
1✔
1004
                }
1✔
1005

1006
                if cont.config.AddExternalContractToDefaultEPG && service.Spec.Type == v1.ServiceTypeLoadBalancer {
1✔
1007
                        defaultEpgTenant := cont.config.DefaultEg.PolicySpace
×
1008
                        defaultEpgStringSplit := strings.Split(cont.config.DefaultEg.Name, "|")
×
1009
                        var defaultEpgName, appProfile string
×
1010
                        if len(defaultEpgStringSplit) > 1 {
×
1011
                                appProfile = defaultEpgStringSplit[0]
×
1012
                                defaultEpgName = defaultEpgStringSplit[1]
×
1013
                        } else {
×
1014
                                appProfile = cont.config.AppProfile
×
1015
                                defaultEpgName = defaultEpgStringSplit[0]
×
1016
                        }
×
1017
                        serviceObjs = append(serviceObjs,
×
1018
                                apicDefaultEgCons(name, defaultEpgTenant, appProfile, defaultEpgName))
×
1019
                }
1020

1021
                defaultPortRange := portRangeSnat{start: cont.config.SnatDefaultPortRangeStart,
1✔
1022
                        end: cont.config.SnatDefaultPortRangeEnd}
1✔
1023

1✔
1024
                _, snat := cont.snatServices[key]
1✔
1025
                filter := apicFilter(name, cont.config.AciVrfTenant,
1✔
1026
                        service.Spec.Ports, snat, defaultPortRange)
1✔
1027
                serviceObjs = append(serviceObjs, filter)
1✔
1028

1✔
1029
                // 3. Device cluster context
1✔
1030
                // The logical device context binds the service contract
1✔
1031
                // to the redirect policy and the device cluster and
1✔
1032
                // bridge domain for the device cluster.
1✔
1033
                serviceObjs = append(serviceObjs,
1✔
1034
                        apicDevCtx(name, cont.config.AciVrfTenant, graphName, deviceName,
1✔
1035
                                cont.aciNameForKey("bd", cont.env.ServiceBd()), rpDn, false))
1✔
1036
        }
1037

1038
        cont.apicConn.WriteApicObjects(name, serviceObjs)
1✔
1039
        return nil
1✔
1040
}
1041

1042
func (cont *AciController) updateServiceDeviceInstanceSnat(key string) error {
1✔
1043
        nodeList := cont.nodeIndexer.List()
1✔
1044
        cont.indexMutex.Lock()
1✔
1045
        if len(cont.nodeServiceMetaCache) == 0 {
2✔
1046
                cont.indexMutex.Unlock()
1✔
1047
                return nil
1✔
1048
        }
1✔
1049
        nodeMap := make(map[string]*metadata.ServiceEndpoint)
1✔
1050
        sort.Slice(nodeList, func(i, j int) bool {
2✔
1051
                nodeA := nodeList[i].(*v1.Node)
1✔
1052
                nodeB := nodeList[j].(*v1.Node)
1✔
1053
                return nodeA.ObjectMeta.Name < nodeB.ObjectMeta.Name
1✔
1054
        })
1✔
1055
        for itr, nodeItem := range nodeList {
2✔
1056
                if itr == cont.config.MaxSvcGraphNodes {
1✔
1057
                        break
×
1058
                }
1059
                node := nodeItem.(*v1.Node)
1✔
1060
                nodeName := node.ObjectMeta.Name
1✔
1061
                nodeMeta, ok := cont.nodeServiceMetaCache[nodeName]
1✔
1062
                if !ok {
2✔
1063
                        continue
1✔
1064
                }
1065
                _, ok = cont.fabricPathForNode(nodeName)
1✔
1066
                if !ok {
1✔
1067
                        continue
×
1068
                }
1069
                nodeLabels := node.ObjectMeta.Labels
1✔
1070
                excludeNode := cont.nodeLabelsInExcludeList(nodeLabels)
1✔
1071
                if excludeNode {
1✔
1072
                        continue
×
1073
                }
1074
                nodeMap[nodeName] = &nodeMeta.serviceEp
1✔
1075
        }
1076
        cont.indexMutex.Unlock()
1✔
1077

1✔
1078
        var nodes []string
1✔
1079
        for node := range nodeMap {
2✔
1080
                nodes = append(nodes, node)
1✔
1081
        }
1✔
1082
        sort.Strings(nodes)
1✔
1083
        name := cont.aciNameForKey("snat", key)
1✔
1084
        var conScope = cont.config.SnatSvcContractScope
1✔
1085
        sharedSecurity := true
1✔
1086

1✔
1087
        graphName := cont.aciNameForKey("svc", "global")
1✔
1088
        var serviceObjs apicapi.ApicSlice
1✔
1089
        if len(nodes) > 0 {
2✔
1090
                // 1. Service redirect policy
1✔
1091
                // The service redirect policy contains the MAC address
1✔
1092
                // and IP address of each of the service endpoints for
1✔
1093
                // each node that hosts a pod for this service.
1✔
1094
                // For SNAT with the introduction of filter-chain usage, to work-around
1✔
1095
                // an APIC limitation, creating two PBR policies with same nodes.
1✔
1096
                var rpDn string
1✔
1097
                var rp apicapi.ApicObject
1✔
1098
                if cont.apicConn.SnatPbrFltrChain {
2✔
1099
                        rpCons, rpDnCons :=
1✔
1100
                                cont.apicRedirectPol(name+"_Cons", cont.config.AciVrfTenant, nodes,
1✔
1101
                                        nodeMap, cont.staticMonPolDn(), true)
1✔
1102
                        serviceObjs = append(serviceObjs, rpCons)
1✔
1103
                        rpProv, _ :=
1✔
1104
                                cont.apicRedirectPol(name+"_Prov", cont.config.AciVrfTenant, nodes,
1✔
1105
                                        nodeMap, cont.staticMonPolDn(), true)
1✔
1106
                        serviceObjs = append(serviceObjs, rpProv)
1✔
1107
                        rpDn = strings.TrimSuffix(rpDnCons, "_Cons")
1✔
1108
                } else {
1✔
1109
                        rp, rpDn =
×
1110
                                cont.apicRedirectPol(name, cont.config.AciVrfTenant, nodes,
×
1111
                                        nodeMap, cont.staticMonPolDn(), true)
×
1112
                        serviceObjs = append(serviceObjs, rp)
×
1113
                }
×
1114
                // 2. Service graph contract and external network
1115
                // The service graph contract must be bound to the
1116
                // service
1117
                // graph.  This contract must be consumed by the default
1118
                // layer 3 network and provided by the service layer 3
1119
                // network.
1120
                {
1✔
1121
                        var ingresses []string
1✔
1122
                        for _, policy := range cont.snatPolicyCache {
2✔
1123
                                ingresses = append(ingresses, policy.SnatIp...)
1✔
1124
                        }
1✔
1125
                        serviceObjs = append(serviceObjs,
1✔
1126
                                apicExtNet(name, cont.config.AciVrfTenant,
1✔
1127
                                        cont.config.AciL3Out, ingresses, sharedSecurity, true))
1✔
1128
                }
1129

1130
                contract := apicContract(name, cont.config.AciVrfTenant, graphName, conScope, cont.apicConn.SnatPbrFltrChain, false)
1✔
1131
                serviceObjs = append(serviceObjs, contract)
1✔
1132

1✔
1133
                for _, net := range cont.config.AciExtNetworks {
2✔
1134
                        serviceObjs = append(serviceObjs,
1✔
1135
                                apicExtNetProv(name, cont.config.AciVrfTenant,
1✔
1136
                                        cont.config.AciL3Out, net))
1✔
1137
                }
1✔
1138

1139
                defaultPortRange := portRangeSnat{start: cont.config.SnatDefaultPortRangeStart,
1✔
1140
                        end: cont.config.SnatDefaultPortRangeEnd}
1✔
1141
                portSpec := []portRangeSnat{defaultPortRange}
1✔
1142
                if cont.apicConn.SnatPbrFltrChain {
2✔
1143
                        filterIn := apicFilterSnat(name+"_fromCons-toProv", cont.config.AciVrfTenant, portSpec, false)
1✔
1144
                        serviceObjs = append(serviceObjs, filterIn)
1✔
1145
                        filterOut := apicFilterSnat(name+"_fromProv-toCons", cont.config.AciVrfTenant, portSpec, true)
1✔
1146
                        serviceObjs = append(serviceObjs, filterOut)
1✔
1147
                } else {
1✔
1148
                        filter := apicFilterSnat(name, cont.config.AciVrfTenant, portSpec, false)
×
1149
                        serviceObjs = append(serviceObjs, filter)
×
1150
                }
×
1151
                // 3. Device cluster context
1152
                // The logical device context binds the service contract
1153
                // to the redirect policy and the device cluster and
1154
                // bridge domain for the device cluster.
1155
                serviceObjs = append(serviceObjs,
1✔
1156
                        apicDevCtx(name, cont.config.AciVrfTenant, graphName, graphName,
1✔
1157
                                cont.aciNameForKey("bd", cont.env.ServiceBd()), rpDn, cont.apicConn.SnatPbrFltrChain))
1✔
1158
        }
1159
        cont.apicConn.WriteApicObjects(name, serviceObjs)
1✔
1160
        return nil
1✔
1161
}
1162

1163
func (cont *AciController) nodeLabelsInExcludeList(Labels map[string]string) bool {
1✔
1164
        nodeSnatRedirectExclude := cont.config.NodeSnatRedirectExclude
1✔
1165

1✔
1166
        for _, nodeGroup := range nodeSnatRedirectExclude {
1✔
1167
                if len(nodeGroup.Labels) == 0 {
×
1168
                        continue
×
1169
                }
1170
                matchFound := true
×
1171
                for _, label := range nodeGroup.Labels {
×
1172
                        if _, ok := Labels["node-role.kubernetes.io/"+label]; !ok {
×
1173
                                matchFound = false
×
1174
                                break
×
1175
                        }
1176
                }
1177
                if matchFound {
×
1178
                        return true
×
1179
                }
×
1180
        }
1181
        return false
1✔
1182
}
1183

1184
func (cont *AciController) queueServiceUpdateByKey(key string) {
1✔
1185
        cont.serviceQueue.Add(key)
1✔
1186
}
1✔
1187

1188
func (cont *AciController) queueServiceUpdate(service *v1.Service) {
1✔
1189
        key, err := cache.MetaNamespaceKeyFunc(service)
1✔
1190
        if err != nil {
1✔
1191
                serviceLogger(cont.log, service).
×
1192
                        Error("Could not create service key: ", err)
×
1193
                return
×
1194
        }
×
1195
        cont.serviceQueue.Add(key)
1✔
1196
}
1197

1198
func apicDeviceCluster(name string, vrfTenant string,
1199
        physDom string, encap string,
1200
        nodes []string, nodeMap map[string]string) (apicapi.ApicObject, string) {
1✔
1201
        dc := apicapi.NewVnsLDevVip(vrfTenant, name)
1✔
1202
        dc.SetAttr("managed", "no")
1✔
1203
        dcDn := dc.GetDn()
1✔
1204
        dc.AddChild(apicapi.NewVnsRsALDevToPhysDomP(dcDn,
1✔
1205
                fmt.Sprintf("uni/phys-%s", physDom)))
1✔
1206
        lif := apicapi.NewVnsLIf(dcDn, "interface")
1✔
1207
        lif.SetAttr("encap", encap)
1✔
1208
        lifDn := lif.GetDn()
1✔
1209

1✔
1210
        for _, node := range nodes {
2✔
1211
                path, ok := nodeMap[node]
1✔
1212
                if !ok {
1✔
1213
                        continue
×
1214
                }
1215

1216
                cdev := apicapi.NewVnsCDev(dcDn, node)
1✔
1217
                cif := apicapi.NewVnsCif(cdev.GetDn(), "interface")
1✔
1218
                cif.AddChild(apicapi.NewVnsRsCIfPathAtt(cif.GetDn(), path))
1✔
1219
                cdev.AddChild(cif)
1✔
1220
                lif.AddChild(apicapi.NewVnsRsCIfAttN(lifDn, cif.GetDn()))
1✔
1221
                dc.AddChild(cdev)
1✔
1222
        }
1223

1224
        dc.AddChild(lif)
1✔
1225

1✔
1226
        return dc, dcDn
1✔
1227
}
1228

1229
func apicServiceGraph(name string, tenantName string,
1230
        dcDn string) apicapi.ApicObject {
1✔
1231
        sg := apicapi.NewVnsAbsGraph(tenantName, name)
1✔
1232
        sgDn := sg.GetDn()
1✔
1233
        var provDn string
1✔
1234
        var consDn string
1✔
1235
        var cTermDn string
1✔
1236
        var pTermDn string
1✔
1237
        {
2✔
1238
                an := apicapi.NewVnsAbsNode(sgDn, "loadbalancer")
1✔
1239
                an.SetAttr("managed", "no")
1✔
1240
                an.SetAttr("routingMode", "Redirect")
1✔
1241
                anDn := an.GetDn()
1✔
1242
                cons := apicapi.NewVnsAbsFuncConn(anDn, "consumer")
1✔
1243
                consDn = cons.GetDn()
1✔
1244
                an.AddChild(cons)
1✔
1245
                prov := apicapi.NewVnsAbsFuncConn(anDn, "provider")
1✔
1246
                provDn = prov.GetDn()
1✔
1247
                an.AddChild(prov)
1✔
1248
                an.AddChild(apicapi.NewVnsRsNodeToLDev(anDn, dcDn))
1✔
1249
                sg.AddChild(an)
1✔
1250
        }
1✔
1251
        {
1✔
1252
                tnc := apicapi.NewVnsAbsTermNodeCon(sgDn, "T1")
1✔
1253
                tncDn := tnc.GetDn()
1✔
1254
                cTerm := apicapi.NewVnsAbsTermConn(tncDn)
1✔
1255
                cTermDn = cTerm.GetDn()
1✔
1256
                tnc.AddChild(cTerm)
1✔
1257
                tnc.AddChild(apicapi.NewVnsInTerm(tncDn))
1✔
1258
                tnc.AddChild(apicapi.NewVnsOutTerm(tncDn))
1✔
1259
                sg.AddChild(tnc)
1✔
1260
        }
1✔
1261
        {
1✔
1262
                tnp := apicapi.NewVnsAbsTermNodeProv(sgDn, "T2")
1✔
1263
                tnpDn := tnp.GetDn()
1✔
1264
                pTerm := apicapi.NewVnsAbsTermConn(tnpDn)
1✔
1265
                pTermDn = pTerm.GetDn()
1✔
1266
                tnp.AddChild(pTerm)
1✔
1267
                tnp.AddChild(apicapi.NewVnsInTerm(tnpDn))
1✔
1268
                tnp.AddChild(apicapi.NewVnsOutTerm(tnpDn))
1✔
1269
                sg.AddChild(tnp)
1✔
1270
        }
1✔
1271
        {
1✔
1272
                acc := apicapi.NewVnsAbsConnection(sgDn, "C1")
1✔
1273
                acc.SetAttr("connDir", "provider")
1✔
1274
                accDn := acc.GetDn()
1✔
1275
                acc.AddChild(apicapi.NewVnsRsAbsConnectionConns(accDn, consDn))
1✔
1276
                acc.AddChild(apicapi.NewVnsRsAbsConnectionConns(accDn, cTermDn))
1✔
1277
                sg.AddChild(acc)
1✔
1278
        }
1✔
1279
        {
1✔
1280
                acp := apicapi.NewVnsAbsConnection(sgDn, "C2")
1✔
1281
                acp.SetAttr("connDir", "provider")
1✔
1282
                acpDn := acp.GetDn()
1✔
1283
                acp.AddChild(apicapi.NewVnsRsAbsConnectionConns(acpDn, provDn))
1✔
1284
                acp.AddChild(apicapi.NewVnsRsAbsConnectionConns(acpDn, pTermDn))
1✔
1285
                sg.AddChild(acp)
1✔
1286
        }
1✔
1287
        return sg
1✔
1288
}
1289
func (cont *AciController) updateDeviceCluster() {
1✔
1290
        nodeMap := make(map[string]string)
1✔
1291
        cont.indexMutex.Lock()
1✔
1292
        for node := range cont.nodeOpflexDevice {
2✔
1293
                cont.log.Debug("Processing node in nodeOpflexDevice cache : ", node)
1✔
1294
                fabricPath, ok := cont.fabricPathForNode(node)
1✔
1295
                if !ok {
2✔
1296
                        continue
1✔
1297
                }
1298
                nodeMap[node] = fabricPath
1✔
1299
        }
1300

1301
        // For clusters other than OpenShift On OpenStack,
1302
        // openStackFabricPathDnMap will be empty
1303
        for host, opflexOdevInfo := range cont.openStackFabricPathDnMap {
1✔
1304
                nodeMap[host] = opflexOdevInfo.fabricPathDn
×
1305
        }
×
1306

1307
        // For OpenShift On OpenStack clusters,
1308
        // hostFabricPathDnMap will be empty
1309
        for host, fabricPathDn := range cont.hostFabricPathDnMap {
1✔
1310
                nodeMap[host] = fabricPathDn
×
1311
        }
×
1312
        cont.indexMutex.Unlock()
1✔
1313

1✔
1314
        var nodes []string
1✔
1315
        for node := range nodeMap {
2✔
1316
                nodes = append(nodes, node)
1✔
1317
        }
1✔
1318
        sort.Strings(nodes)
1✔
1319

1✔
1320
        name := cont.aciNameForKey("svc", "global")
1✔
1321
        var serviceObjs apicapi.ApicSlice
1✔
1322

1✔
1323
        // 1. Device cluster:
1✔
1324
        // The device cluster is a set of physical paths that need to be
1✔
1325
        // created for each node in the cluster, that correspond to the
1✔
1326
        // service interface for each node.
1✔
1327
        dc, dcDn := apicDeviceCluster(name, cont.config.AciVrfTenant,
1✔
1328
                cont.config.AciServicePhysDom, cont.config.AciServiceEncap,
1✔
1329
                nodes, nodeMap)
1✔
1330
        serviceObjs = append(serviceObjs, dc)
1✔
1331

1✔
1332
        // 2. Service graph template
1✔
1333
        // The service graph controls how the traffic will be redirected.
1✔
1334
        // A service graph must be created for each device cluster.
1✔
1335
        serviceObjs = append(serviceObjs,
1✔
1336
                apicServiceGraph(name, cont.config.AciVrfTenant, dcDn))
1✔
1337

1✔
1338
        cont.apicConn.WriteApicObjects(name, serviceObjs)
1✔
1339
}
1340

1341
func (cont *AciController) fabricPathLogger(node string,
1342
        obj apicapi.ApicObject) *logrus.Entry {
1✔
1343
        return cont.log.WithFields(logrus.Fields{
1✔
1344
                "fabricPath": obj.GetAttr("fabricPathDn"),
1✔
1345
                "mac":        obj.GetAttr("mac"),
1✔
1346
                "node":       node,
1✔
1347
                "obj":        obj,
1✔
1348
        })
1✔
1349
}
1✔
1350

1351
func (cont *AciController) setOpenStackSystemId() string {
×
1352

×
1353
        // 1) get opflexIDEp with containerName == <node name of any one of the openshift nodes>
×
1354
        // 2) extract OpenStack system id from compHvDn attribute
×
1355
        //    comp/prov-OpenStack/ctrlr-[k8s-scale]-k8s-scale/hv-overcloud-novacompute-0 - sample compHvDn,
×
1356
        //    where k8s-scale is the system id
×
1357

×
1358
        var systemId string
×
1359
        nodeList := cont.nodeIndexer.List()
×
1360
        if len(nodeList) < 1 {
×
1361
                return systemId
×
1362
        }
×
1363
        node := nodeList[0].(*v1.Node)
×
1364
        nodeName := node.ObjectMeta.Name
×
1365
        opflexIDEpFilter := fmt.Sprintf("query-target-filter=and(eq(opflexIDEp.containerName,\"%s\"))", nodeName)
×
1366
        opflexIDEpArgs := []string{
×
1367
                opflexIDEpFilter,
×
1368
        }
×
1369
        url := fmt.Sprintf("/api/node/class/opflexIDEp.json?%s", strings.Join(opflexIDEpArgs, "&"))
×
1370
        apicresp, err := cont.apicConn.GetApicResponse(url)
×
1371
        if err != nil {
×
1372
                cont.log.Error("Failed to get APIC response, err: ", err.Error())
×
1373
                return systemId
×
1374
        }
×
1375
        for _, obj := range apicresp.Imdata {
×
1376
                for _, body := range obj {
×
1377
                        compHvDn, ok := body.Attributes["compHvDn"].(string)
×
1378
                        if ok {
×
1379
                                systemId = compHvDn[strings.IndexByte(compHvDn, '[')+1 : strings.IndexByte(compHvDn, ']')]
×
1380
                                break
×
1381
                        }
1382
                }
1383
        }
1384
        cont.indexMutex.Lock()
×
1385
        cont.openStackSystemId = systemId
×
1386
        cont.log.Info("Setting OpenStack system id : ", cont.openStackSystemId)
×
1387
        cont.indexMutex.Unlock()
×
1388
        return systemId
×
1389
}
1390

1391
// Returns true when a new OpenStack opflexODev is added
1392
func (cont *AciController) openStackOpflexOdevUpdate(obj apicapi.ApicObject) bool {
×
1393

×
1394
        // If opflexOdev compHvDn contains comp/prov-OpenShift/ctrlr-[<systemid>]-<systemid>,
×
1395
        // it means that it is an OpenStack OpflexOdev which belongs to OpenStack with system id <systemid>
×
1396

×
1397
        var deviceClusterUpdate bool
×
1398
        compHvDn := obj.GetAttrStr("compHvDn")
×
1399
        if strings.Contains(compHvDn, "prov-OpenStack") {
×
1400
                cont.indexMutex.Lock()
×
1401
                systemId := cont.openStackSystemId
×
1402
                cont.indexMutex.Unlock()
×
1403
                if systemId == "" {
×
1404
                        systemId = cont.setOpenStackSystemId()
×
1405
                }
×
1406
                if systemId == "" {
×
1407
                        cont.log.Error("Failed  to get OpenStack system id")
×
1408
                        return deviceClusterUpdate
×
1409
                }
×
1410
                prefix := fmt.Sprintf("comp/prov-OpenStack/ctrlr-[%s]-%s", systemId, systemId)
×
1411
                if strings.Contains(compHvDn, prefix) {
×
1412
                        cont.log.Info("Received notification for OpenStack opflexODev update, hostName: ",
×
1413
                                obj.GetAttrStr("hostName"), " dn: ", obj.GetAttrStr("dn"))
×
1414
                        cont.indexMutex.Lock()
×
1415
                        opflexOdevInfo, ok := cont.openStackFabricPathDnMap[obj.GetAttrStr("hostName")]
×
1416
                        if ok {
×
1417
                                opflexOdevInfo.opflexODevDn[obj.GetAttrStr("dn")] = struct{}{}
×
1418
                                cont.openStackFabricPathDnMap[obj.GetAttrStr("hostName")] = opflexOdevInfo
×
1419
                        } else {
×
1420
                                var openstackopflexodevinfo openstackOpflexOdevInfo
×
1421
                                opflexODevDn := make(map[string]struct{})
×
1422
                                opflexODevDn[obj.GetAttrStr("dn")] = struct{}{}
×
1423
                                openstackopflexodevinfo.fabricPathDn = obj.GetAttrStr("fabricPathDn")
×
1424
                                openstackopflexodevinfo.opflexODevDn = opflexODevDn
×
1425
                                cont.openStackFabricPathDnMap[obj.GetAttrStr("hostName")] = openstackopflexodevinfo
×
1426
                                deviceClusterUpdate = true
×
1427
                        }
×
1428
                        cont.indexMutex.Unlock()
×
1429
                }
1430
        }
1431
        return deviceClusterUpdate
×
1432
}
1433

1434
func (cont *AciController) infraRtAttEntPDeleted(dn string) {
×
1435
        // dn format : uni/infra/attentp-k8s-scale-esxi-aaep/rtattEntP-[uni/infra/funcprof/accbundle-esxi1-vpc-ipg]
×
1436
        re := regexp.MustCompile(`accbundle-([^]]+)`)
×
1437
        cont.log.Info("Processing delete of infraRtAttEntP: ", dn)
×
1438
        matches := re.FindStringSubmatch(dn)
×
1439
        if len(matches) < 2 {
×
1440
                cont.log.Error("Failed to extract ipg from dn : ", dn)
×
1441
                return
×
1442
        }
×
1443
        host := matches[1]
×
1444

×
1445
        cont.indexMutex.Lock()
×
1446
        _, ok := cont.hostFabricPathDnMap[host]
×
1447
        if ok {
×
1448
                delete(cont.hostFabricPathDnMap, host)
×
1449
                cont.log.Info("Deleted ipg : ", host)
×
1450
        }
×
1451
        cont.indexMutex.Unlock()
×
1452

×
1453
        if ok {
×
1454
                cont.updateDeviceCluster()
×
1455
        }
×
1456
}
1457

1458
func (cont *AciController) infraRtAttEntPChanged(obj apicapi.ApicObject) {
×
1459
        var tdn string
×
1460
        for _, body := range obj {
×
1461
                var ok bool
×
1462
                tdn, ok = body.Attributes["tDn"].(string)
×
1463
                if !ok {
×
1464
                        cont.log.Error("tDn missing in infraRtAttEntP")
×
1465
                        return
×
1466
                }
×
1467
        }
1468
        var updated bool
×
1469
        if tdn != "" {
×
1470
                cont.log.Info("infraRtAttEntP updated, tDn : ", tdn)
×
NEW
1471

×
NEW
1472
                // tdn format for vpc : /uni/infra/funcprof/accbundle-esxi1-vpc-ipg
×
NEW
1473
                // tdn format for single leaf : /uni/infra/funcprof/accportgrp-IPG_CLIENT_SIM
×
NEW
1474

×
NEW
1475
                // Ignore processing of single leaf
×
NEW
1476
                if !strings.Contains(tdn, "/accbundle-") {
×
NEW
1477
                        cont.log.Info("Skipping processing of infraRtAttEntP update, not applicable for non-VPC configuration: ", tdn)
×
NEW
1478
                        return
×
NEW
1479
                }
×
1480

1481
                // extract esxi1-vpc-ipg
1482
                parts := strings.Split(tdn, "/")
×
1483
                lastPart := parts[len(parts)-1]
×
1484
                host := strings.TrimPrefix(lastPart, "accbundle-")
×
1485
                assocGrpFilter := fmt.Sprintf(`query-target-filter=and(eq(infraPortSummary.assocGrp,"%s"))`, tdn)
×
1486
                url := fmt.Sprintf("/api/class/infraPortSummary.json?%s", assocGrpFilter)
×
1487
                apicresp, err := cont.apicConn.GetApicResponse(url)
×
1488
                if err != nil {
×
1489
                        cont.log.Error("Failed to get APIC response, err: ", err.Error())
×
1490
                        return
×
1491
                }
×
1492
                for _, obj := range apicresp.Imdata {
×
1493
                        for _, body := range obj {
×
1494
                                pcPortDn, ok := body.Attributes["pcPortDn"].(string)
×
NEW
1495
                                if ok && pcPortDn != "" {
×
1496
                                        cont.indexMutex.Lock()
×
1497
                                        fabricPathDn, exists := cont.hostFabricPathDnMap[host]
×
1498
                                        if !exists || (exists && fabricPathDn != pcPortDn) {
×
1499
                                                cont.hostFabricPathDnMap[host] = pcPortDn
×
1500
                                                cont.log.Info("Updated fabricPathDn of ipg :", host, " to: ", pcPortDn)
×
1501
                                                updated = true
×
1502
                                        }
×
1503
                                        cont.indexMutex.Unlock()
×
1504
                                        break
×
1505
                                }
1506
                        }
1507
                }
1508

1509
        }
1510
        if updated {
×
1511
                cont.updateDeviceCluster()
×
1512
        }
×
1513
        return
×
1514
}
1515

1516
func (cont *AciController) opflexDeviceChanged(obj apicapi.ApicObject) {
1✔
1517
        devType := obj.GetAttrStr("devType")
1✔
1518
        domName := obj.GetAttrStr("domName")
1✔
1519
        ctrlrName := obj.GetAttrStr("ctrlrName")
1✔
1520

1✔
1521
        if !cont.config.DisableServiceVlanPreprovisioning && strings.Contains(cont.config.Flavor, "openstack") {
1✔
1522
                if cont.openStackOpflexOdevUpdate(obj) {
×
1523
                        cont.log.Info("OpenStack opflexODev for ", obj.GetAttrStr("hostName"), " is added")
×
1524
                        cont.updateDeviceCluster()
×
1525
                }
×
1526
        }
1527
        if (devType == cont.env.OpFlexDeviceType()) && (domName == cont.config.AciVmmDomain) && (ctrlrName == cont.config.AciVmmController) {
2✔
1528
                cont.fabricPathLogger(obj.GetAttrStr("hostName"), obj).Debug("Processing opflex device update")
1✔
1529
                if obj.GetAttrStr("state") == "disconnected" {
2✔
1530
                        cont.fabricPathLogger(obj.GetAttrStr("hostName"), obj).Debug("Opflex device disconnected")
1✔
1531
                        cont.indexMutex.Lock()
1✔
1532
                        for node, devices := range cont.nodeOpflexDevice {
1✔
1533
                                if node == obj.GetAttrStr("hostName") {
×
1534
                                        for _, device := range devices {
×
1535
                                                if device.GetDn() == obj.GetDn() {
×
1536
                                                        device.SetAttr("state", "disconnected")
×
1537
                                                        cont.fabricPathLogger(device.GetAttrStr("hostName"), device).Debug("Opflex device cache updated for disconnected node")
×
1538
                                                }
×
1539
                                        }
1540
                                        cont.log.Info("Opflex device list for node ", obj.GetAttrStr("hostName"), ": ", devices)
×
1541
                                        break
×
1542
                                }
1543
                        }
1544
                        cont.indexMutex.Unlock()
1✔
1545
                        cont.updateDeviceCluster()
1✔
1546
                        return
1✔
1547
                }
1548
                var nodeUpdates []string
1✔
1549

1✔
1550
                cont.indexMutex.Lock()
1✔
1551
                nodefound := false
1✔
1552
                for node, devices := range cont.nodeOpflexDevice {
2✔
1553
                        found := false
1✔
1554

1✔
1555
                        if node == obj.GetAttrStr("hostName") {
2✔
1556
                                nodefound = true
1✔
1557
                        }
1✔
1558

1559
                        for i, device := range devices {
2✔
1560
                                if device.GetDn() != obj.GetDn() {
2✔
1561
                                        continue
1✔
1562
                                }
1563
                                found = true
1✔
1564

1✔
1565
                                if obj.GetAttrStr("hostName") != node {
2✔
1566
                                        cont.fabricPathLogger(node, device).
1✔
1567
                                                Debug("Moving opflex device from node")
1✔
1568

1✔
1569
                                        devices = append(devices[:i], devices[i+1:]...)
1✔
1570
                                        cont.nodeOpflexDevice[node] = devices
1✔
1571
                                        nodeUpdates = append(nodeUpdates, node)
1✔
1572
                                        break
1✔
1573
                                } else if (device.GetAttrStr("mac") != obj.GetAttrStr("mac")) ||
1✔
1574
                                        (device.GetAttrStr("fabricPathDn") != obj.GetAttrStr("fabricPathDn")) ||
1✔
1575
                                        (device.GetAttrStr("state") != obj.GetAttrStr("state")) {
2✔
1576
                                        cont.fabricPathLogger(node, obj).
1✔
1577
                                                Debug("Updating opflex device")
1✔
1578

1✔
1579
                                        devices = append(append(devices[:i], devices[i+1:]...), obj)
1✔
1580
                                        cont.nodeOpflexDevice[node] = devices
1✔
1581
                                        nodeUpdates = append(nodeUpdates, node)
1✔
1582
                                        break
1✔
1583
                                }
1584
                        }
1585
                        if !found && obj.GetAttrStr("hostName") == node {
2✔
1586
                                cont.fabricPathLogger(node, obj).
1✔
1587
                                        Debug("Appending opflex device")
1✔
1588

1✔
1589
                                devices = append(devices, obj)
1✔
1590
                                cont.nodeOpflexDevice[node] = devices
1✔
1591
                                nodeUpdates = append(nodeUpdates, node)
1✔
1592
                        }
1✔
1593
                }
1594
                if !nodefound {
2✔
1595
                        node := obj.GetAttrStr("hostName")
1✔
1596
                        cont.fabricPathLogger(node, obj).Debug("Adding opflex device")
1✔
1597
                        cont.nodeOpflexDevice[node] = apicapi.ApicSlice{obj}
1✔
1598
                        nodeUpdates = append(nodeUpdates, node)
1✔
1599
                }
1✔
1600
                cont.log.Info("Opflex device list for node ", obj.GetAttrStr("hostName"), ": ", cont.nodeOpflexDevice[obj.GetAttrStr("hostName")])
1✔
1601
                cont.indexMutex.Unlock()
1✔
1602

1✔
1603
                for _, node := range nodeUpdates {
2✔
1604
                        cont.env.NodeServiceChanged(node)
1✔
1605
                        cont.erspanSyncOpflexDev()
1✔
1606
                }
1✔
1607
                cont.updateDeviceCluster()
1✔
1608
        }
1609
}
1610

1611
func (cont *AciController) postOpflexDeviceDelete(nodes []string) {
1✔
1612
        cont.updateDeviceCluster()
1✔
1613
        for _, node := range nodes {
2✔
1614
                cont.env.NodeServiceChanged(node)
1✔
1615
                cont.erspanSyncOpflexDev()
1✔
1616
        }
1✔
1617
}
1618

1619
func (cont *AciController) opflexDeviceDeleted(dn string) {
1✔
1620
        var nodeUpdates []string
1✔
1621
        var dnFound bool //to check if the dn belongs to this cluster
1✔
1622
        cont.log.Info("Processing opflex device delete notification of ", dn)
1✔
1623
        cont.indexMutex.Lock()
1✔
1624
        for node, devices := range cont.nodeOpflexDevice {
2✔
1625
                for i, device := range devices {
2✔
1626
                        if device.GetDn() != dn {
2✔
1627
                                continue
1✔
1628
                        }
1629
                        dnFound = true
1✔
1630
                        cont.fabricPathLogger(node, device).
1✔
1631
                                Debug("Deleting opflex device path")
1✔
1632
                        devices = append(devices[:i], devices[i+1:]...)
1✔
1633
                        cont.nodeOpflexDevice[node] = devices
1✔
1634
                        cont.log.Info("Deleted opflex device of node ", node, ": ", dn)
1✔
1635
                        nodeUpdates = append(nodeUpdates, node)
1✔
1636
                        break
1✔
1637
                }
1638
                if len(devices) == 0 {
2✔
1639
                        delete(cont.nodeOpflexDevice, node)
1✔
1640
                }
1✔
1641
        }
1642

1643
        // For clusters other than OpenShift On OpenStack,
1644
        // openStackFabricPathDnMap will be empty
1645
        for host, opflexOdevInfo := range cont.openStackFabricPathDnMap {
1✔
1646
                if _, ok := opflexOdevInfo.opflexODevDn[dn]; ok {
×
1647
                        cont.log.Info("Received OpenStack opflexODev delete notification for ", dn)
×
1648
                        delete(opflexOdevInfo.opflexODevDn, dn)
×
1649
                        if len(opflexOdevInfo.opflexODevDn) < 1 {
×
1650
                                delete(cont.openStackFabricPathDnMap, host)
×
1651
                                cont.log.Info("OpenStack opflexODev of host ", host, " is deleted from cache")
×
1652
                                dnFound = true
×
1653
                        } else {
×
1654
                                cont.openStackFabricPathDnMap[host] = opflexOdevInfo
×
1655
                        }
×
1656
                        break
×
1657
                }
1658
        }
1659
        cont.indexMutex.Unlock()
1✔
1660

1✔
1661
        if dnFound {
2✔
1662
                cont.postOpflexDeviceDelete(nodeUpdates)
1✔
1663
        }
1✔
1664
}
1665

1666
func (cont *AciController) writeApicSvc(key string, service *v1.Service) {
1✔
1667
        if cont.config.ChainedMode {
1✔
1668
                return
×
1669
        }
×
1670
        aobj := apicapi.NewVmmInjectedSvc(cont.vmmDomainProvider(),
1✔
1671
                cont.config.AciVmmDomain, cont.config.AciVmmController,
1✔
1672
                service.Namespace, service.Name)
1✔
1673
        aobjDn := aobj.GetDn()
1✔
1674
        aobj.SetAttr("guid", string(service.UID))
1✔
1675

1✔
1676
        svcns := service.ObjectMeta.Namespace
1✔
1677
        _, exists, err := cont.namespaceIndexer.GetByKey(svcns)
1✔
1678
        if err != nil {
1✔
1679
                cont.log.Error("Failed to lookup ns : ", svcns, " ", err)
×
1680
                return
×
1681
        }
×
1682
        if !exists {
2✔
1683
                cont.log.Debug("Namespace of service ", service.ObjectMeta.Name, ": ", svcns, " doesn't exist, hence not sending an update to the APIC")
1✔
1684
                return
1✔
1685
        }
1✔
1686

1687
        if !cont.serviceEndPoints.SetServiceApicObject(aobj, service) {
2✔
1688
                return
1✔
1689
        }
1✔
1690
        var setApicSvcDnsName bool
1✔
1691
        if len(cont.config.ApicHosts) != 0 && apicapi.ApicVersion >= "5.1" {
1✔
1692
                setApicSvcDnsName = true
×
1693
        }
×
1694
        // APIC model only allows one of these
1695
        for _, ingress := range service.Status.LoadBalancer.Ingress {
1✔
1696
                if ingress.IP != "" && ingress.IP != "0.0.0.0" {
×
1697
                        aobj.SetAttr("lbIp", ingress.IP)
×
1698
                } else if ingress.Hostname != "" {
×
1699
                        ipList, err := net.LookupHost(ingress.Hostname)
×
1700
                        if err == nil && len(ipList) > 0 {
×
1701
                                aobj.SetAttr("lbIp", ipList[0])
×
1702
                        } else {
×
1703
                                cont.log.Errorf("Lookup: err: %v, ipList: %+v", err, ipList)
×
1704
                        }
×
1705
                }
1706
                break
×
1707
        }
1708
        if service.Spec.ClusterIP != "" && service.Spec.ClusterIP != "None" {
2✔
1709
                aobj.SetAttr("clusterIp", service.Spec.ClusterIP)
1✔
1710
        }
1✔
1711

1712
        var t string
1✔
1713
        switch service.Spec.Type {
1✔
1714
        case v1.ServiceTypeClusterIP:
×
1715
                t = "clusterIp"
×
1716
        case v1.ServiceTypeNodePort:
×
1717
                t = "nodePort"
×
1718
        case v1.ServiceTypeLoadBalancer:
1✔
1719
                t = "loadBalancer"
1✔
1720
        case v1.ServiceTypeExternalName:
×
1721
                t = "externalName"
×
1722
        }
1723
        if t != "" {
2✔
1724
                aobj.SetAttr("type", t)
1✔
1725
        }
1✔
1726

1727
        if setApicSvcDnsName || cont.config.Flavor == "k8s-overlay" {
1✔
1728
                dnsName := fmt.Sprintf("%s.%s.svc.cluster.local", service.Name, service.Namespace)
×
1729

×
1730
                for _, ingress := range service.Status.LoadBalancer.Ingress {
×
1731
                        if ingress.Hostname != "" {
×
1732
                                aobj.SetAttr("dnsName", ingress.Hostname)
×
1733
                        } else if ingress.IP != "" && ingress.IP != "0.0.0.0" {
×
1734
                                aobj.SetAttr("dnsName", dnsName)
×
1735
                        }
×
1736
                }
1737
                if t == "clusterIp" || t == "nodePort" || t == "externalName" {
×
1738
                        aobj.SetAttr("dnsName", dnsName)
×
1739
                }
×
1740
        }
1741
        for _, port := range service.Spec.Ports {
2✔
1742
                proto := getProtocolStr(port.Protocol)
1✔
1743
                p := apicapi.NewVmmInjectedSvcPort(aobjDn,
1✔
1744
                        strconv.Itoa(int(port.Port)), proto, port.TargetPort.String())
1✔
1745
                p.SetAttr("nodePort", strconv.Itoa(int(port.NodePort)))
1✔
1746
                aobj.AddChild(p)
1✔
1747
        }
1✔
1748
        if cont.config.EnableVmmInjectedLabels && service.ObjectMeta.Labels != nil && apicapi.ApicVersion >= "5.2" {
1✔
1749
                for key, val := range service.ObjectMeta.Labels {
×
1750
                        newLabelKey := cont.aciNameForKey("label", key)
×
1751
                        label := apicapi.NewVmmInjectedLabel(aobj.GetDn(),
×
1752
                                newLabelKey, val)
×
1753
                        aobj.AddChild(label)
×
1754
                }
×
1755
        }
1756
        name := cont.aciNameForKey("service-vmm", key)
1✔
1757
        cont.log.Debug("Write Service Object: ", aobj)
1✔
1758
        cont.apicConn.WriteApicObjects(name, apicapi.ApicSlice{aobj})
1✔
1759
        cont.log.Debugf("svcObject: %+v", aobj)
1✔
1760
}
1761

1762
func removeAllConditions(conditions []metav1.Condition, conditionType string) []metav1.Condition {
1✔
1763
        i := 0
1✔
1764
        for _, cond := range conditions {
1✔
1765
                if cond.Type != conditionType {
×
1766
                        conditions[i] = cond
×
1767
                }
×
1768
        }
1769
        return conditions[:i]
1✔
1770
}
1771

1772
func (cont *AciController) updateServiceCondition(service *v1.Service, success bool, reason string, message string) bool {
1✔
1773
        conditionType := "LbIpamAllocation"
1✔
1774

1✔
1775
        var condition metav1.Condition
1✔
1776
        if success {
2✔
1777
                condition.Status = metav1.ConditionTrue
1✔
1778
        } else {
2✔
1779
                condition.Status = metav1.ConditionFalse
1✔
1780
                condition.Message = message
1✔
1781
        }
1✔
1782
        condition.Type = conditionType
1✔
1783
        condition.Reason = reason
1✔
1784
        condition.LastTransitionTime = metav1.Time{time.Now()}
1✔
1785
        for _, cond := range service.Status.Conditions {
2✔
1786
                if cond.Type == conditionType &&
1✔
1787
                        cond.Status == condition.Status &&
1✔
1788
                        cond.Message == condition.Message &&
1✔
1789
                        cond.Reason == condition.Reason {
2✔
1790
                        return false
1✔
1791
                }
1✔
1792
        }
1793

1794
        service.Status.Conditions = removeAllConditions(service.Status.Conditions, conditionType)
1✔
1795
        service.Status.Conditions = append(service.Status.Conditions, condition)
1✔
1796
        return true
1✔
1797
}
1798

1799
func (cont *AciController) validateRequestedIps(lbIpList []string) (net.IP, net.IP, bool) {
1✔
1800
        var ipv4, ipv6 net.IP
1✔
1801
        for _, lbIp := range lbIpList {
2✔
1802
                ip := net.ParseIP(lbIp)
1✔
1803
                if ip != nil {
2✔
1804
                        if ip.To4() != nil {
2✔
1805
                                if ipv4.Equal(net.IP{}) {
2✔
1806
                                        ipv4 = ip
1✔
1807
                                } else {
2✔
1808
                                        cont.log.Error("Annotation should have only one ipv4")
1✔
1809
                                        return ipv4, ipv6, false
1✔
1810
                                }
1✔
1811
                        } else if ip.To16() != nil {
2✔
1812
                                if ipv6.Equal(net.IP{}) {
2✔
1813
                                        ipv6 = ip
1✔
1814
                                } else {
2✔
1815
                                        cont.log.Error("Annotation should have only one ipv6")
1✔
1816
                                        return ipv4, ipv6, false
1✔
1817
                                }
1✔
1818
                        }
1819
                }
1820
        }
1821
        return ipv4, ipv6, true
1✔
1822
}
1823

1824
func (cont *AciController) returnUnusedStaticIngressIps(staticIngressIps, requestedIps []net.IP) {
1✔
1825
        for _, staticIp := range staticIngressIps {
2✔
1826
                found := false
1✔
1827
                for _, reqIp := range requestedIps {
2✔
1828
                        if reqIp.Equal(staticIp) {
2✔
1829
                                found = true
1✔
1830
                        }
1✔
1831
                }
1832
                if !found {
2✔
1833
                        returnIps(cont.staticServiceIps, []net.IP{staticIp})
1✔
1834
                }
1✔
1835
        }
1836
}
1837

1838
func (cont *AciController) allocateServiceIps(servicekey string,
1839
        service *v1.Service) bool {
1✔
1840
        logger := serviceLogger(cont.log, service)
1✔
1841
        cont.indexMutex.Lock()
1✔
1842
        meta, ok := cont.serviceMetaCache[servicekey]
1✔
1843
        if !ok {
2✔
1844
                meta = &serviceMeta{}
1✔
1845
                cont.serviceMetaCache[servicekey] = meta
1✔
1846

1✔
1847
                // Read any existing IPs and attempt to allocate them to the pod
1✔
1848
                for _, ingress := range service.Status.LoadBalancer.Ingress {
2✔
1849
                        ip := net.ParseIP(ingress.IP)
1✔
1850
                        if ip == nil {
1✔
1851
                                continue
×
1852
                        }
1853
                        if ip.To4() != nil {
2✔
1854
                                if cont.serviceIps.GetV4IpCache()[0].RemoveIp(ip) {
2✔
1855
                                        meta.ingressIps = append(meta.ingressIps, ip)
1✔
1856
                                } else if cont.staticServiceIps.V4.RemoveIp(ip) {
3✔
1857
                                        meta.staticIngressIps = append(meta.staticIngressIps, ip)
1✔
1858
                                }
1✔
1859
                        } else if ip.To16() != nil {
2✔
1860
                                if cont.serviceIps.GetV6IpCache()[0].RemoveIp(ip) {
2✔
1861
                                        meta.ingressIps = append(meta.ingressIps, ip)
1✔
1862
                                } else if cont.staticServiceIps.V6.RemoveIp(ip) {
3✔
1863
                                        meta.staticIngressIps = append(meta.staticIngressIps, ip)
1✔
1864
                                }
1✔
1865
                        }
1866
                }
1867
        }
1868

1869
        if !cont.serviceSyncEnabled {
2✔
1870
                cont.indexMutex.Unlock()
1✔
1871
                return false
1✔
1872
        }
1✔
1873

1874
        var requestedIps []net.IP
1✔
1875
        // try to give the requested load balancer IP to the pod
1✔
1876
        lbIps, ok := service.ObjectMeta.Annotations[metadata.LbIpAnnotation]
1✔
1877
        if ok {
2✔
1878
                lbIpList := strings.Split(lbIps, ",")
1✔
1879
                ipv4, ipv6, valid := cont.validateRequestedIps(lbIpList)
1✔
1880
                if valid {
2✔
1881
                        if ipv4 != nil {
2✔
1882
                                requestedIps = append(requestedIps, ipv4)
1✔
1883
                        }
1✔
1884
                        if ipv6 != nil {
2✔
1885
                                requestedIps = append(requestedIps, ipv6)
1✔
1886
                        }
1✔
1887
                } else {
1✔
1888
                        cont.returnServiceIps(meta.ingressIps)
1✔
1889
                        cont.log.Error("Invalid LB IP annotation for service ", servicekey)
1✔
1890
                        condUpdated := cont.updateServiceCondition(service, false, "InvalidAnnotation", "Invalid Loadbalancer IP annotation")
1✔
1891
                        if condUpdated {
2✔
1892
                                _, err := cont.updateServiceStatus(service)
1✔
1893
                                if err != nil {
1✔
1894
                                        logger.Error("Failed to update service status : ", err)
×
1895
                                        cont.indexMutex.Unlock()
×
1896
                                        return true
×
1897
                                }
×
1898
                        }
1899
                        cont.indexMutex.Unlock()
1✔
1900
                        return false
1✔
1901
                }
1902
        } else {
1✔
1903
                requestedIp := net.ParseIP(service.Spec.LoadBalancerIP)
1✔
1904
                if requestedIp != nil {
2✔
1905
                        requestedIps = append(requestedIps, requestedIp)
1✔
1906
                }
1✔
1907
        }
1908
        if len(requestedIps) > 0 {
2✔
1909
                meta.requestedIps = []net.IP{}
1✔
1910
                for _, requestedIp := range requestedIps {
2✔
1911
                        hasRequestedIp := false
1✔
1912
                        for _, ip := range meta.staticIngressIps {
2✔
1913
                                if reflect.DeepEqual(requestedIp, ip) {
2✔
1914
                                        hasRequestedIp = true
1✔
1915
                                }
1✔
1916
                        }
1917
                        if !hasRequestedIp {
2✔
1918
                                if requestedIp.To4() != nil &&
1✔
1919
                                        cont.staticServiceIps.V4.RemoveIp(requestedIp) {
2✔
1920
                                        hasRequestedIp = true
1✔
1921
                                } else if requestedIp.To16() != nil &&
2✔
1922
                                        cont.staticServiceIps.V6.RemoveIp(requestedIp) {
2✔
1923
                                        hasRequestedIp = true
1✔
1924
                                }
1✔
1925
                        }
1926
                        if hasRequestedIp {
2✔
1927
                                meta.requestedIps = append(meta.requestedIps, requestedIp)
1✔
1928
                        }
1✔
1929
                }
1930
                cont.returnUnusedStaticIngressIps(meta.staticIngressIps, meta.requestedIps)
1✔
1931
                meta.staticIngressIps = meta.requestedIps
1✔
1932
                cont.returnServiceIps(meta.ingressIps)
1✔
1933
                meta.ingressIps = nil
1✔
1934
                // If no requested ips are allocatable
1✔
1935
                if len(meta.requestedIps) < 1 {
2✔
1936
                        logger.Error("No Requested Ip addresses available for service ", servicekey)
1✔
1937
                        condUpdated := cont.updateServiceCondition(service, false, "RequestedIpsNotAllocatable", "The requested ips for loadbalancer service are not available or not in extern static range")
1✔
1938
                        if condUpdated {
2✔
1939
                                _, err := cont.updateServiceStatus(service)
1✔
1940
                                if err != nil {
1✔
1941
                                        cont.indexMutex.Unlock()
×
1942
                                        logger.Error("Failed to update service status: ", err)
×
1943
                                        return true
×
1944
                                }
×
1945
                        }
1946
                        cont.indexMutex.Unlock()
1✔
1947
                        return false
1✔
1948
                }
1949
        } else if len(meta.requestedIps) > 0 {
1✔
1950
                meta.requestedIps = nil
×
1951
                returnIps(cont.staticServiceIps, meta.staticIngressIps)
×
1952
                meta.staticIngressIps = nil
×
1953
        }
×
1954
        ingressIps := make([]net.IP, 0)
1✔
1955
        ingressIps = append(ingressIps, meta.ingressIps...)
1✔
1956
        ingressIps = append(ingressIps, meta.staticIngressIps...)
1✔
1957

1✔
1958
        var ipv4, ipv6 net.IP
1✔
1959
        for _, ip := range ingressIps {
2✔
1960
                if ip.To4() != nil {
2✔
1961
                        ipv4 = ip
1✔
1962
                } else if ip.To16() != nil {
3✔
1963
                        ipv6 = ip
1✔
1964
                }
1✔
1965
        }
1966
        var clusterIPv4, clusterIPv6 net.IP
1✔
1967
        clusterIPs := append([]string{service.Spec.ClusterIP}, service.Spec.ClusterIPs...)
1✔
1968
        for _, ipStr := range clusterIPs {
2✔
1969
                ip := net.ParseIP(ipStr)
1✔
1970
                if ip == nil {
1✔
1971
                        continue
×
1972
                }
1973
                if ip.To4() != nil && clusterIPv4 == nil {
2✔
1974
                        clusterIPv4 = ip
1✔
1975
                } else if ip.To16() != nil && strings.Contains(ip.String(), ":") && clusterIPv6 == nil {
3✔
1976
                        clusterIPv6 = ip
1✔
1977
                }
1✔
1978
        }
1979
        if clusterIPv4 != nil && ipv4 == nil {
2✔
1980
                if len(requestedIps) < 1 {
2✔
1981
                        ipv4, _ = cont.serviceIps.AllocateIp(true)
1✔
1982
                        if ipv4 != nil {
2✔
1983
                                ingressIps = append(ingressIps, ipv4)
1✔
1984
                        }
1✔
1985
                }
1986
        } else if clusterIPv4 == nil && ipv4 != nil {
1✔
1987
                cont.removeIpFromIngressIPList(&ingressIps, ipv4)
×
1988
        }
×
1989

1990
        if clusterIPv6 != nil && ipv6 == nil {
2✔
1991
                if len(requestedIps) < 1 {
2✔
1992
                        ipv6, _ = cont.serviceIps.AllocateIp(false)
1✔
1993
                        if ipv6 != nil {
2✔
1994
                                ingressIps = append(ingressIps, ipv6)
1✔
1995
                        }
1✔
1996
                }
1997
        } else if clusterIPv6 == nil && ipv6 != nil {
1✔
1998
                cont.removeIpFromIngressIPList(&ingressIps, ipv6)
×
1999
        }
×
2000

2001
        if len(requestedIps) < 1 {
2✔
2002
                meta.ingressIps = ingressIps
1✔
2003
        }
1✔
2004
        if ipv4 == nil && ipv6 == nil {
2✔
2005
                logger.Error("No IP addresses available for service")
1✔
2006
                cont.indexMutex.Unlock()
1✔
2007
                return true
1✔
2008
        }
1✔
2009
        cont.indexMutex.Unlock()
1✔
2010
        var newIngress []v1.LoadBalancerIngress
1✔
2011
        for _, ip := range meta.ingressIps {
2✔
2012
                newIngress = append(newIngress, v1.LoadBalancerIngress{IP: ip.String()})
1✔
2013
        }
1✔
2014
        for _, ip := range meta.staticIngressIps {
2✔
2015
                newIngress = append(newIngress, v1.LoadBalancerIngress{IP: ip.String()})
1✔
2016
        }
1✔
2017

2018
        ipUpdated := false
1✔
2019
        if !reflect.DeepEqual(newIngress, service.Status.LoadBalancer.Ingress) {
2✔
2020
                service.Status.LoadBalancer.Ingress = newIngress
1✔
2021

1✔
2022
                logger.WithFields(logrus.Fields{
1✔
2023
                        "status": service.Status.LoadBalancer.Ingress,
1✔
2024
                }).Info("Updating service load balancer status")
1✔
2025

1✔
2026
                ipUpdated = true
1✔
2027
        }
1✔
2028

2029
        success := true
1✔
2030
        reason := "Success"
1✔
2031
        message := ""
1✔
2032
        if len(requestedIps) > 0 && len(requestedIps) != len(meta.staticIngressIps) {
1✔
2033
                success = false
×
2034
                reason = "OneIpNotAllocatable"
×
2035
                message = "One of the requested Ips is not allocatable"
×
2036
        }
×
2037
        condUpdated := cont.updateServiceCondition(service, success, reason, message)
1✔
2038
        if ipUpdated || condUpdated {
2✔
2039
                _, err := cont.updateServiceStatus(service)
1✔
2040
                if err != nil {
1✔
2041
                        logger.Error("Failed to update service status: ", err)
×
2042
                        return true
×
2043
                }
×
2044
        }
2045
        return false
1✔
2046
}
2047

2048
func (cont *AciController) handleServiceDelete(servicekey string) bool {
1✔
2049
        if cont.config.ChainedMode {
1✔
2050
                return false
×
2051
        }
×
2052
        cont.clearLbService(servicekey)
1✔
2053
        cont.apicConn.ClearApicObjects(cont.aciNameForKey("service-vmm",
1✔
2054
                servicekey))
1✔
2055
        return false
1✔
2056
}
2057

2058
func (cont *AciController) handleServiceUpdate(service *v1.Service) bool {
1✔
2059
        servicekey, err := cache.MetaNamespaceKeyFunc(service)
1✔
2060
        if err != nil {
1✔
2061
                serviceLogger(cont.log, service).
×
2062
                        Error("Could not create service key: ", err)
×
2063
                return false
×
2064
        }
×
2065
        if cont.config.ChainedMode {
1✔
2066
                return false
×
2067
        }
×
2068
        var requeue bool
1✔
2069
        isLoadBalancer := service.Spec.Type == v1.ServiceTypeLoadBalancer
1✔
2070
        if isLoadBalancer {
2✔
2071
                if *cont.config.AllocateServiceIps {
2✔
2072
                        requeue = cont.allocateServiceIps(servicekey, service)
1✔
2073
                }
1✔
2074
                cont.indexMutex.Lock()
1✔
2075
                if cont.serviceSyncEnabled {
2✔
2076
                        cont.indexMutex.Unlock()
1✔
2077
                        err = cont.updateServiceDeviceInstance(servicekey, service)
1✔
2078
                        if err != nil {
1✔
2079
                                serviceLogger(cont.log, service).
×
2080
                                        Error("Failed to update service device Instance: ", err)
×
2081
                                return true
×
2082
                        }
×
2083
                } else {
1✔
2084
                        cont.indexMutex.Unlock()
1✔
2085
                }
1✔
2086
        } else {
1✔
2087
                cont.clearLbService(servicekey)
1✔
2088
        }
1✔
2089
        cont.writeApicSvc(servicekey, service)
1✔
2090
        return requeue
1✔
2091
}
2092

2093
func (cont *AciController) clearLbService(servicekey string) {
1✔
2094
        cont.indexMutex.Lock()
1✔
2095
        if meta, ok := cont.serviceMetaCache[servicekey]; ok {
2✔
2096
                cont.returnServiceIps(meta.ingressIps)
1✔
2097
                returnIps(cont.staticServiceIps, meta.staticIngressIps)
1✔
2098
                delete(cont.serviceMetaCache, servicekey)
1✔
2099
        }
1✔
2100
        cont.indexMutex.Unlock()
1✔
2101
        cont.apicConn.ClearApicObjects(cont.aciNameForKey("svc", servicekey))
1✔
2102
}
2103

2104
func getEndpointsIps(endpoints *v1.Endpoints) map[string]bool {
1✔
2105
        ips := make(map[string]bool)
1✔
2106
        for _, subset := range endpoints.Subsets {
2✔
2107
                for _, addr := range subset.Addresses {
2✔
2108
                        ips[addr.IP] = true
1✔
2109
                }
1✔
2110
                for _, addr := range subset.NotReadyAddresses {
1✔
2111
                        ips[addr.IP] = true
×
2112
                }
×
2113
        }
2114
        return ips
1✔
2115
}
2116

2117
func getServiceTargetPorts(service *v1.Service) map[string]targetPort {
1✔
2118
        ports := make(map[string]targetPort)
1✔
2119
        for _, port := range service.Spec.Ports {
2✔
2120
                portNum := port.TargetPort.IntValue()
1✔
2121
                if portNum <= 0 {
2✔
2122
                        portNum = int(port.Port)
1✔
2123
                }
1✔
2124
                key := portProto(&port.Protocol) + "-num-" + strconv.Itoa(portNum)
1✔
2125
                ports[key] = targetPort{
1✔
2126
                        proto: port.Protocol,
1✔
2127
                        ports: []int{portNum},
1✔
2128
                }
1✔
2129
        }
2130
        return ports
1✔
2131
}
2132

2133
func (cont *AciController) endpointsAdded(obj interface{}) {
1✔
2134
        endpoints := obj.(*v1.Endpoints)
1✔
2135
        servicekey, err := cache.MetaNamespaceKeyFunc(obj.(*v1.Endpoints))
1✔
2136
        if err != nil {
1✔
2137
                cont.log.Error("Could not create service key: ", err)
×
2138
                return
×
2139
        }
×
2140

2141
        ips := getEndpointsIps(endpoints)
1✔
2142
        cont.indexMutex.Lock()
1✔
2143
        cont.updateIpIndex(cont.endpointsIpIndex, nil, ips, servicekey)
1✔
2144
        cont.queueIPNetPolUpdates(ips)
1✔
2145
        cont.indexMutex.Unlock()
1✔
2146

1✔
2147
        cont.queueEndpointsNetPolUpdates(endpoints)
1✔
2148

1✔
2149
        cont.queueServiceUpdateByKey(servicekey)
1✔
2150
}
2151

2152
func (cont *AciController) endpointsDeleted(obj interface{}) {
1✔
2153
        endpoints, isEndpoints := obj.(*v1.Endpoints)
1✔
2154
        if !isEndpoints {
1✔
2155
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
×
2156
                if !ok {
×
2157
                        cont.log.Error("Received unexpected object: ", obj)
×
2158
                        return
×
2159
                }
×
2160
                endpoints, ok = deletedState.Obj.(*v1.Endpoints)
×
2161
                if !ok {
×
2162
                        cont.log.Error("DeletedFinalStateUnknown contained non-Endpoints object: ", deletedState.Obj)
×
2163
                        return
×
2164
                }
×
2165
        }
2166
        servicekey, err := cache.MetaNamespaceKeyFunc(endpoints)
1✔
2167
        if err != nil {
1✔
2168
                cont.log.Error("Could not create service key: ", err)
×
2169
                return
×
2170
        }
×
2171

2172
        ips := getEndpointsIps(endpoints)
1✔
2173
        cont.indexMutex.Lock()
1✔
2174
        cont.updateIpIndex(cont.endpointsIpIndex, ips, nil, servicekey)
1✔
2175
        cont.queueIPNetPolUpdates(ips)
1✔
2176
        cont.indexMutex.Unlock()
1✔
2177

1✔
2178
        cont.queueEndpointsNetPolUpdates(endpoints)
1✔
2179

1✔
2180
        cont.queueServiceUpdateByKey(servicekey)
1✔
2181
}
2182

2183
func (cont *AciController) endpointsUpdated(oldEps, newEps interface{}) {
1✔
2184
        oldendpoints := oldEps.(*v1.Endpoints)
1✔
2185
        newendpoints := newEps.(*v1.Endpoints)
1✔
2186
        servicekey, err := cache.MetaNamespaceKeyFunc(newendpoints)
1✔
2187
        if err != nil {
1✔
2188
                cont.log.Error("Could not create service key: ", err)
×
2189
                return
×
2190
        }
×
2191

2192
        oldIps := getEndpointsIps(oldendpoints)
1✔
2193
        newIps := getEndpointsIps(newendpoints)
1✔
2194
        if !reflect.DeepEqual(oldIps, newIps) {
2✔
2195
                cont.indexMutex.Lock()
1✔
2196
                cont.queueIPNetPolUpdates(oldIps)
1✔
2197
                cont.updateIpIndex(cont.endpointsIpIndex, oldIps, newIps, servicekey)
1✔
2198
                cont.queueIPNetPolUpdates(newIps)
1✔
2199
                cont.indexMutex.Unlock()
1✔
2200
        }
1✔
2201

2202
        if !reflect.DeepEqual(oldendpoints.Subsets, newendpoints.Subsets) {
2✔
2203
                cont.queueEndpointsNetPolUpdates(oldendpoints)
1✔
2204
                cont.queueEndpointsNetPolUpdates(newendpoints)
1✔
2205
        }
1✔
2206

2207
        cont.queueServiceUpdateByKey(servicekey)
1✔
2208
}
2209

2210
func (cont *AciController) serviceAdded(obj interface{}) {
1✔
2211
        service := obj.(*v1.Service)
1✔
2212
        servicekey, err := cache.MetaNamespaceKeyFunc(service)
1✔
2213
        if err != nil {
1✔
2214
                serviceLogger(cont.log, service).
×
2215
                        Error("Could not create service key: ", err)
×
2216
                return
×
2217
        }
×
2218

2219
        ports := getServiceTargetPorts(service)
1✔
2220
        cont.indexMutex.Lock()
1✔
2221
        cont.queuePortNetPolUpdates(ports)
1✔
2222
        cont.updateTargetPortIndex(true, servicekey, nil, ports)
1✔
2223
        cont.indexMutex.Unlock()
1✔
2224

1✔
2225
        cont.queueServiceUpdateByKey(servicekey)
1✔
2226
}
2227

2228
func (cont *AciController) serviceUpdated(oldSvc, newSvc interface{}) {
1✔
2229
        oldservice := oldSvc.(*v1.Service)
1✔
2230
        newservice := newSvc.(*v1.Service)
1✔
2231
        servicekey, err := cache.MetaNamespaceKeyFunc(newservice)
1✔
2232
        if err != nil {
1✔
2233
                serviceLogger(cont.log, newservice).
×
2234
                        Error("Could not create service key: ", err)
×
2235
                return
×
2236
        }
×
2237
        oldPorts := getServiceTargetPorts(oldservice)
1✔
2238
        newPorts := getServiceTargetPorts(newservice)
1✔
2239
        if !reflect.DeepEqual(oldPorts, newPorts) {
1✔
2240
                cont.indexMutex.Lock()
×
2241
                cont.queuePortNetPolUpdates(oldPorts)
×
2242
                cont.updateTargetPortIndex(true, servicekey, oldPorts, newPorts)
×
2243
                cont.queuePortNetPolUpdates(newPorts)
×
2244
                cont.indexMutex.Unlock()
×
2245
        }
×
2246
        cont.queueServiceUpdateByKey(servicekey)
1✔
2247
}
2248

2249
func (cont *AciController) serviceDeleted(obj interface{}) {
1✔
2250
        service, isService := obj.(*v1.Service)
1✔
2251
        if !isService {
1✔
2252
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
×
2253
                if !ok {
×
2254
                        serviceLogger(cont.log, service).
×
2255
                                Error("Received unexpected object: ", obj)
×
2256
                        return
×
2257
                }
×
2258
                service, ok = deletedState.Obj.(*v1.Service)
×
2259
                if !ok {
×
2260
                        serviceLogger(cont.log, service).
×
2261
                                Error("DeletedFinalStateUnknown contained non-Services object: ", deletedState.Obj)
×
2262
                        return
×
2263
                }
×
2264
        }
2265
        servicekey, err := cache.MetaNamespaceKeyFunc(service)
1✔
2266
        if err != nil {
1✔
2267
                serviceLogger(cont.log, service).
×
2268
                        Error("Could not create service key: ", err)
×
2269
                return
×
2270
        }
×
2271

2272
        ports := getServiceTargetPorts(service)
1✔
2273
        cont.indexMutex.Lock()
1✔
2274
        cont.updateTargetPortIndex(true, servicekey, ports, nil)
1✔
2275
        cont.queuePortNetPolUpdates(ports)
1✔
2276
        delete(cont.snatServices, servicekey)
1✔
2277
        cont.indexMutex.Unlock()
1✔
2278

1✔
2279
        deletedServiceKey := "DELETED_" + servicekey
1✔
2280
        cont.queueServiceUpdateByKey(deletedServiceKey)
1✔
2281
}
2282

2283
func (cont *AciController) serviceFullSync() {
1✔
2284
        cache.ListAll(cont.serviceIndexer, labels.Everything(),
1✔
2285
                func(sobj interface{}) {
2✔
2286
                        cont.queueServiceUpdate(sobj.(*v1.Service))
1✔
2287
                })
1✔
2288
}
2289

2290
func (cont *AciController) getEndpointSliceIps(endpointSlice *discovery.EndpointSlice) map[string]bool {
1✔
2291
        ips := make(map[string]bool)
1✔
2292
        for _, endpoints := range endpointSlice.Endpoints {
2✔
2293
                for _, addr := range endpoints.Addresses {
2✔
2294
                        ips[addr] = true
1✔
2295
                }
1✔
2296
        }
2297
        return ips
1✔
2298
}
2299

2300
func (cont *AciController) notReadyEndpointPresent(endpointSlice *discovery.EndpointSlice) bool {
×
2301
        for _, endpoints := range endpointSlice.Endpoints {
×
2302
                if (endpoints.Conditions.Ready != nil && !*endpoints.Conditions.Ready) &&
×
2303
                        (endpoints.Conditions.Terminating == nil || !*endpoints.Conditions.Terminating) {
×
2304
                        return true
×
2305
                }
×
2306
        }
2307
        return false
×
2308
}
2309

2310
func (cont *AciController) getEndpointSliceEpIps(endpoints *discovery.Endpoint) map[string]bool {
×
2311
        ips := make(map[string]bool)
×
2312
        for _, addr := range endpoints.Addresses {
×
2313
                ips[addr] = true
×
2314
        }
×
2315
        return ips
×
2316
}
2317

2318
func (cont *AciController) processDelayedEpSlices() {
1✔
2319
        var processEps []DelayedEpSlice
1✔
2320
        cont.indexMutex.Lock()
1✔
2321
        for i := 0; i < len(cont.delayedEpSlices); i++ {
1✔
2322
                delayedepslice := cont.delayedEpSlices[i]
×
2323
                if time.Now().After(delayedepslice.DelayedTime) {
×
2324
                        var toprocess DelayedEpSlice
×
2325
                        err := util.DeepCopyObj(&delayedepslice, &toprocess)
×
2326
                        if err != nil {
×
2327
                                cont.log.Error(err)
×
2328
                                continue
×
2329
                        }
2330
                        processEps = append(processEps, toprocess)
×
2331
                        cont.delayedEpSlices = append(cont.delayedEpSlices[:i], cont.delayedEpSlices[i+1:]...)
×
2332
                }
2333
        }
2334

2335
        cont.indexMutex.Unlock()
1✔
2336
        for _, epslice := range processEps {
1✔
2337
                //ignore the epslice if newly added endpoint is not ready
×
2338
                if cont.notReadyEndpointPresent(epslice.NewEpSlice) {
×
2339
                        cont.log.Debug("Ignoring the update as the new endpoint is not ready : ", epslice.NewEpSlice)
×
2340
                } else {
×
2341
                        cont.log.Debug("Processing update of epslice : ", epslice.NewEpSlice)
×
2342
                        cont.doendpointSliceUpdated(epslice.OldEpSlice, epslice.NewEpSlice)
×
2343
                }
×
2344
        }
2345
}
2346

2347
func (cont *AciController) endpointSliceAdded(obj interface{}) {
1✔
2348
        endpointslice, ok := obj.(*discovery.EndpointSlice)
1✔
2349
        if !ok {
1✔
2350
                cont.log.Error("error processing Endpointslice object: ", obj)
×
2351
                return
×
2352
        }
×
2353
        servicekey, valid := getServiceKey(endpointslice)
1✔
2354
        if !valid {
1✔
2355
                return
×
2356
        }
×
2357
        ips := cont.getEndpointSliceIps(endpointslice)
1✔
2358
        cont.indexMutex.Lock()
1✔
2359
        cont.updateIpIndex(cont.endpointsIpIndex, nil, ips, servicekey)
1✔
2360
        cont.queueIPNetPolUpdates(ips)
1✔
2361
        cont.indexMutex.Unlock()
1✔
2362

1✔
2363
        cont.queueEndpointSliceNetPolUpdates(endpointslice)
1✔
2364

1✔
2365
        cont.queueServiceUpdateByKey(servicekey)
1✔
2366
        cont.log.Info("EndPointSlice Object Added: ", servicekey)
1✔
2367
}
2368

2369
func (cont *AciController) endpointSliceDeleted(obj interface{}) {
1✔
2370
        endpointslice, isEndpointslice := obj.(*discovery.EndpointSlice)
1✔
2371
        if !isEndpointslice {
1✔
2372
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
×
2373
                if !ok {
×
2374
                        cont.log.Error("Received unexpected object: ", obj)
×
2375
                        return
×
2376
                }
×
2377
                endpointslice, ok = deletedState.Obj.(*discovery.EndpointSlice)
×
2378
                if !ok {
×
2379
                        cont.log.Error("DeletedFinalStateUnknown contained non-Endpointslice object: ", deletedState.Obj)
×
2380
                        return
×
2381
                }
×
2382
        }
2383
        servicekey, valid := getServiceKey(endpointslice)
1✔
2384
        if !valid {
1✔
2385
                return
×
2386
        }
×
2387
        ips := cont.getEndpointSliceIps(endpointslice)
1✔
2388
        cont.indexMutex.Lock()
1✔
2389
        cont.updateIpIndex(cont.endpointsIpIndex, ips, nil, servicekey)
1✔
2390
        cont.queueIPNetPolUpdates(ips)
1✔
2391
        cont.indexMutex.Unlock()
1✔
2392
        cont.queueEndpointSliceNetPolUpdates(endpointslice)
1✔
2393
        cont.queueServiceUpdateByKey(servicekey)
1✔
2394
}
2395

2396
// Checks if the given service is present in the user configured list of services
2397
// for pbr delay and if present, returns the servie specific delay if configured
2398
func (cont *AciController) svcInAddDelayList(name, ns string) (int, bool) {
×
2399
        for _, svc := range cont.config.ServiceGraphEndpointAddDelay.Services {
×
2400
                if svc.Name == name && svc.Namespace == ns {
×
2401
                        return svc.Delay, true
×
2402
                }
×
2403
        }
2404
        return 0, false
×
2405
}
2406

2407
// Check if the endpointslice update notification has any deletion of enpoint
2408
func (cont *AciController) isDeleteEndpointSlice(oldendpointslice, newendpointslice *discovery.EndpointSlice) bool {
×
2409
        del := false
×
2410

×
2411
        // if any endpoint is removed from endpontslice
×
2412
        if len(newendpointslice.Endpoints) < len(oldendpointslice.Endpoints) {
×
2413
                del = true
×
2414
        }
×
2415

2416
        if !del {
×
2417
                // if any one of the endpoint is in terminating state
×
2418
                for _, endpoint := range newendpointslice.Endpoints {
×
2419
                        if endpoint.Conditions.Terminating != nil && *endpoint.Conditions.Terminating {
×
2420
                                del = true
×
2421
                                break
×
2422
                        }
2423
                }
2424
        }
2425
        if !del {
×
2426
                // if any one of endpoint moved from ready state to not-ready state
×
2427
                for ix := range oldendpointslice.Endpoints {
×
2428
                        oldips := cont.getEndpointSliceEpIps(&oldendpointslice.Endpoints[ix])
×
2429
                        for newIx := range newendpointslice.Endpoints {
×
2430
                                newips := cont.getEndpointSliceEpIps(&newendpointslice.Endpoints[newIx])
×
2431
                                if reflect.DeepEqual(oldips, newips) {
×
2432
                                        if (oldendpointslice.Endpoints[ix].Conditions.Ready != nil && *oldendpointslice.Endpoints[ix].Conditions.Ready) &&
×
2433
                                                (newendpointslice.Endpoints[newIx].Conditions.Ready != nil && !*newendpointslice.Endpoints[newIx].Conditions.Ready) {
×
2434
                                                del = true
×
2435
                                        }
×
2436
                                        break
×
2437
                                }
2438
                        }
2439
                }
2440
        }
2441
        return del
×
2442
}
2443

2444
func (cont *AciController) doendpointSliceUpdatedDelay(oldendpointslice *discovery.EndpointSlice,
2445
        newendpointslice *discovery.EndpointSlice) {
×
2446
        svc, ns, valid := getServiceNameAndNs(newendpointslice)
×
2447
        if !valid {
×
2448
                return
×
2449
        }
×
2450
        svckey, valid := getServiceKey(newendpointslice)
×
2451
        if !valid {
×
2452
                return
×
2453
        }
×
2454
        delay := cont.config.ServiceGraphEndpointAddDelay.Delay
×
2455
        svcDelay, exists := cont.svcInAddDelayList(svc, ns)
×
2456
        if svcDelay > 0 {
×
2457
                delay = svcDelay
×
2458
        }
×
2459
        delayedsvc := exists && delay > 0
×
2460
        if delayedsvc {
×
2461
                cont.log.Debug("Delay of ", delay, " seconds is applicable for svc :", svc, " in ns: ", ns)
×
2462
                var delayedepslice DelayedEpSlice
×
2463
                delayedepslice.OldEpSlice = oldendpointslice
×
2464
                delayedepslice.ServiceKey = svckey
×
2465
                delayedepslice.NewEpSlice = newendpointslice
×
2466
                currentTime := time.Now()
×
2467
                delayedepslice.DelayedTime = currentTime.Add(time.Duration(delay) * time.Second)
×
2468
                cont.indexMutex.Lock()
×
2469
                cont.delayedEpSlices = append(cont.delayedEpSlices, &delayedepslice)
×
2470
                cont.indexMutex.Unlock()
×
2471
        } else {
×
2472
                cont.doendpointSliceUpdated(oldendpointslice, newendpointslice)
×
2473
        }
×
2474

2475
        if delayedsvc && cont.isDeleteEndpointSlice(oldendpointslice, newendpointslice) {
×
2476
                cont.log.Debug("Proceeding by ignoring delay as the update is due to delete of endpoint")
×
2477
                cont.doendpointSliceUpdated(oldendpointslice, newendpointslice)
×
2478
        }
×
2479
}
2480

2481
func (cont *AciController) endpointSliceUpdated(oldobj, newobj interface{}) {
1✔
2482
        oldendpointslice, ok := oldobj.(*discovery.EndpointSlice)
1✔
2483
        if !ok {
1✔
2484
                cont.log.Error("error processing Endpointslice object: ", oldobj)
×
2485
                return
×
2486
        }
×
2487
        newendpointslice, ok := newobj.(*discovery.EndpointSlice)
1✔
2488
        if !ok {
1✔
2489
                cont.log.Error("error processing Endpointslice object: ", newobj)
×
2490
                return
×
2491
        }
×
2492
        if cont.config.ServiceGraphEndpointAddDelay.Delay > 0 {
1✔
2493
                cont.doendpointSliceUpdatedDelay(oldendpointslice, newendpointslice)
×
2494
        } else {
1✔
2495
                cont.doendpointSliceUpdated(oldendpointslice, newendpointslice)
1✔
2496
        }
1✔
2497
}
2498

2499
func (cont *AciController) doendpointSliceUpdated(oldendpointslice *discovery.EndpointSlice,
2500
        newendpointslice *discovery.EndpointSlice) {
1✔
2501
        servicekey, valid := getServiceKey(newendpointslice)
1✔
2502
        if !valid {
1✔
2503
                return
×
2504
        }
×
2505
        oldIps := cont.getEndpointSliceIps(oldendpointslice)
1✔
2506
        newIps := cont.getEndpointSliceIps(newendpointslice)
1✔
2507
        if !reflect.DeepEqual(oldIps, newIps) {
2✔
2508
                cont.indexMutex.Lock()
1✔
2509
                cont.queueIPNetPolUpdates(oldIps)
1✔
2510
                cont.updateIpIndex(cont.endpointsIpIndex, oldIps, newIps, servicekey)
1✔
2511
                cont.queueIPNetPolUpdates(newIps)
1✔
2512
                cont.indexMutex.Unlock()
1✔
2513
        }
1✔
2514

2515
        if !reflect.DeepEqual(oldendpointslice.Endpoints, newendpointslice.Endpoints) {
2✔
2516
                cont.queueEndpointSliceNetPolUpdates(oldendpointslice)
1✔
2517
                cont.queueEndpointSliceNetPolUpdates(newendpointslice)
1✔
2518
        }
1✔
2519
        cont.log.Debug("EndPointSlice Object Update: ", servicekey)
1✔
2520
        cont.queueServiceUpdateByKey(servicekey)
1✔
2521
}
2522

2523
func (cont *AciController) queueEndpointSliceNetPolUpdates(endpointslice *discovery.EndpointSlice) {
1✔
2524
        for _, endpoint := range endpointslice.Endpoints {
2✔
2525
                if endpoint.TargetRef == nil || endpoint.TargetRef.Kind != "Pod" ||
1✔
2526
                        endpoint.TargetRef.Namespace == "" || endpoint.TargetRef.Name == "" {
2✔
2527
                        continue
1✔
2528
                }
2529
                if endpoint.Conditions.Ready != nil && !*endpoint.Conditions.Ready {
1✔
2530
                        continue
×
2531
                }
2532
                podkey := endpoint.TargetRef.Namespace + "/" + endpoint.TargetRef.Name
1✔
2533
                npkeys := cont.netPolEgressPods.GetObjForPod(podkey)
1✔
2534
                ps := make(map[string]bool)
1✔
2535
                for _, npkey := range npkeys {
2✔
2536
                        cont.queueNetPolUpdateByKey(npkey)
1✔
2537
                }
1✔
2538
                // Process if the  any matching namedport wildcard policy is present
2539
                // ignore np already processed policies
2540
                cont.queueMatchingNamedNp(ps, podkey)
1✔
2541
        }
2542
}
2543

2544
func getServiceKey(endPointSlice *discovery.EndpointSlice) (string, bool) {
1✔
2545
        serviceName, ok := endPointSlice.Labels[discovery.LabelServiceName]
1✔
2546
        if !ok {
1✔
2547
                return "", false
×
2548
        }
×
2549
        return endPointSlice.ObjectMeta.Namespace + "/" + serviceName, true
1✔
2550
}
2551

2552
func getServiceNameAndNs(endPointSlice *discovery.EndpointSlice) (string, string, bool) {
×
2553
        serviceName, ok := endPointSlice.Labels[discovery.LabelServiceName]
×
2554
        if !ok {
×
2555
                return "", "", false
×
2556
        }
×
2557
        return serviceName, endPointSlice.ObjectMeta.Namespace, true
×
2558
}
2559

2560
// can be called with index lock
2561
func (sep *serviceEndpoint) UpdateServicesForNode(nodename string) {
1✔
2562
        cont := sep.cont
1✔
2563
        cache.ListAll(cont.endpointsIndexer, labels.Everything(),
1✔
2564
                func(endpointsobj interface{}) {
2✔
2565
                        endpoints := endpointsobj.(*v1.Endpoints)
1✔
2566
                        for _, subset := range endpoints.Subsets {
2✔
2567
                                for _, addr := range subset.Addresses {
2✔
2568
                                        if addr.NodeName != nil && *addr.NodeName == nodename {
2✔
2569
                                                servicekey, err :=
1✔
2570
                                                        cache.MetaNamespaceKeyFunc(endpointsobj.(*v1.Endpoints))
1✔
2571
                                                if err != nil {
1✔
2572
                                                        cont.log.Error("Could not create endpoints key: ", err)
×
2573
                                                        return
×
2574
                                                }
×
2575
                                                cont.queueServiceUpdateByKey(servicekey)
1✔
2576
                                                return
1✔
2577
                                        }
2578
                                }
2579
                        }
2580
                })
2581
}
2582

2583
func (seps *serviceEndpointSlice) UpdateServicesForNode(nodename string) {
1✔
2584
        // 1. List all the endpointslice and check for matching nodename
1✔
2585
        // 2. if it matches trigger the Service update and mark it visited
1✔
2586
        cont := seps.cont
1✔
2587
        visited := make(map[string]bool)
1✔
2588
        cache.ListAll(cont.endpointSliceIndexer, labels.Everything(),
1✔
2589
                func(endpointSliceobj interface{}) {
2✔
2590
                        endpointSlices := endpointSliceobj.(*discovery.EndpointSlice)
1✔
2591
                        for _, endpoint := range endpointSlices.Endpoints {
2✔
2592
                                if endpoint.NodeName != nil && *endpoint.NodeName == nodename {
2✔
2593
                                        servicekey, valid := getServiceKey(endpointSlices)
1✔
2594
                                        if !valid {
1✔
2595
                                                return
×
2596
                                        }
×
2597
                                        if _, ok := visited[servicekey]; !ok {
2✔
2598
                                                cont.queueServiceUpdateByKey(servicekey)
1✔
2599
                                                visited[servicekey] = true
1✔
2600
                                                return
1✔
2601
                                        }
1✔
2602
                                }
2603
                        }
2604
                })
2605
}
2606
func (cont *AciController) setNodeMap(nodeMap map[string]*metadata.ServiceEndpoint, nodeName string) {
1✔
2607
        nodeMeta, ok := cont.nodeServiceMetaCache[nodeName]
1✔
2608
        if !ok {
1✔
UNCOV
2609
                return
×
UNCOV
2610
        }
×
2611
        _, ok = cont.fabricPathForNode(nodeName)
1✔
2612
        if !ok {
2✔
2613
                return
1✔
2614
        }
1✔
2615
        nodeMap[nodeName] = &nodeMeta.serviceEp
1✔
2616
}
2617

2618
// 2 cases when epslices corresponding to given service is presnt in delayedEpSlices:
2619
//  1. endpoint not present in delayedEpSlices of the service
2620
//  2. endpoint present in delayedEpSlices of the service but in not ready state
2621
//
2622
// indexMutex lock must be acquired before calling the function
2623
func (cont *AciController) isDelayedEndpoint(endpoint *discovery.Endpoint, svckey string) bool {
×
2624
        delayed := false
×
2625
        endpointips := cont.getEndpointSliceEpIps(endpoint)
×
2626
        for _, delayedepslices := range cont.delayedEpSlices {
×
2627
                if delayedepslices.ServiceKey == svckey {
×
2628
                        var found bool
×
2629
                        epslice := delayedepslices.OldEpSlice
×
2630
                        for ix := range epslice.Endpoints {
×
2631
                                epips := cont.getEndpointSliceEpIps(&epslice.Endpoints[ix])
×
2632
                                if reflect.DeepEqual(endpointips, epips) {
×
2633
                                        // case 2
×
2634
                                        if epslice.Endpoints[ix].Conditions.Ready != nil && !*epslice.Endpoints[ix].Conditions.Ready {
×
2635
                                                delayed = true
×
2636
                                        }
×
2637
                                        found = true
×
2638
                                }
2639
                        }
2640
                        // case 1
2641
                        if !found {
×
2642
                                delayed = true
×
2643
                        }
×
2644
                }
2645
        }
2646
        return delayed
×
2647
}
2648

2649
// set nodemap only if endoint is ready and not in delayedEpSlices
2650
func (cont *AciController) setNodeMapDelay(nodeMap map[string]*metadata.ServiceEndpoint,
2651
        endpoint *discovery.Endpoint, service *v1.Service) {
×
2652
        svckey, err := cache.MetaNamespaceKeyFunc(service)
×
2653
        if err != nil {
×
2654
                cont.log.Error("Could not create service key: ", err)
×
2655
                return
×
2656
        }
×
2657
        if cont.config.NoWaitForServiceEpReadiness ||
×
2658
                (endpoint.Conditions.Ready != nil && *endpoint.Conditions.Ready) {
×
2659
                if endpoint.NodeName != nil && *endpoint.NodeName != "" {
×
2660
                        // donot setNodeMap for endpoint if:
×
2661
                        //   endpoint is newly added
×
2662
                        //   endpoint status changed from not ready to ready
×
2663
                        if !cont.isDelayedEndpoint(endpoint, svckey) {
×
2664
                                cont.setNodeMap(nodeMap, *endpoint.NodeName)
×
2665
                        }
×
2666
                }
2667
        }
2668
}
2669

2670
func (sep *serviceEndpoint) GetnodesMetadata(key string,
2671
        service *v1.Service, nodeMap map[string]*metadata.ServiceEndpoint) {
1✔
2672
        cont := sep.cont
1✔
2673
        endpointsobj, exists, err := cont.endpointsIndexer.GetByKey(key)
1✔
2674
        if err != nil {
1✔
2675
                cont.log.Error("Could not lookup endpoints for " +
×
2676
                        key + ": " + err.Error())
×
2677
        }
×
2678
        if exists && endpointsobj != nil {
2✔
2679
                endpoints := endpointsobj.(*v1.Endpoints)
1✔
2680
                for _, subset := range endpoints.Subsets {
2✔
2681
                        for _, addr := range subset.Addresses {
2✔
2682
                                if addr.NodeName == nil {
2✔
2683
                                        continue
1✔
2684
                                }
2685
                                cont.setNodeMap(nodeMap, *addr.NodeName)
1✔
2686
                        }
2687
                }
2688
        }
2689
        cont.log.Info("NodeMap: ", nodeMap)
1✔
2690
}
2691

2692
func (seps *serviceEndpointSlice) GetnodesMetadata(key string,
2693
        service *v1.Service, nodeMap map[string]*metadata.ServiceEndpoint) {
1✔
2694
        cont := seps.cont
1✔
2695
        // 1. Get all the Endpoint slices matching the label service-name
1✔
2696
        // 2. update the node map matching with endpoints nodes name
1✔
2697
        label := map[string]string{discovery.LabelServiceName: service.ObjectMeta.Name}
1✔
2698
        selector := labels.SelectorFromSet(label)
1✔
2699
        cache.ListAllByNamespace(cont.endpointSliceIndexer, service.ObjectMeta.Namespace, selector,
1✔
2700
                func(endpointSliceobj interface{}) {
2✔
2701
                        endpointSlices := endpointSliceobj.(*discovery.EndpointSlice)
1✔
2702
                        for ix := range endpointSlices.Endpoints {
2✔
2703
                                if cont.config.ServiceGraphEndpointAddDelay.Delay > 0 {
1✔
2704
                                        cont.setNodeMapDelay(nodeMap, &endpointSlices.Endpoints[ix], service)
×
2705
                                } else if cont.config.NoWaitForServiceEpReadiness ||
1✔
2706
                                        (endpointSlices.Endpoints[ix].Conditions.Ready != nil && *endpointSlices.Endpoints[ix].Conditions.Ready) {
2✔
2707
                                        if endpointSlices.Endpoints[ix].NodeName != nil && *endpointSlices.Endpoints[ix].NodeName != "" {
2✔
2708
                                                cont.setNodeMap(nodeMap, *endpointSlices.Endpoints[ix].NodeName)
1✔
2709
                                        }
1✔
2710
                                }
2711
                        }
2712
                })
2713
        cont.log.Debug("NodeMap: ", nodeMap)
1✔
2714
}
2715

2716
func (sep *serviceEndpoint) SetServiceApicObject(aobj apicapi.ApicObject, service *v1.Service) bool {
1✔
2717
        cont := sep.cont
1✔
2718
        key, err := cache.MetaNamespaceKeyFunc(service)
1✔
2719
        if err != nil {
1✔
2720
                serviceLogger(cont.log, service).
×
2721
                        Error("Could not create service key: ", err)
×
2722
                return false
×
2723
        }
×
2724
        endpointsobj, _, err := cont.endpointsIndexer.GetByKey(key)
1✔
2725
        if err != nil {
1✔
2726
                cont.log.Error("Could not lookup endpoints for " +
×
2727
                        key + ": " + err.Error())
×
2728
                return false
×
2729
        }
×
2730
        if endpointsobj != nil {
2✔
2731
                for _, subset := range endpointsobj.(*v1.Endpoints).Subsets {
2✔
2732
                        for _, addr := range subset.Addresses {
2✔
2733
                                if addr.TargetRef == nil || addr.TargetRef.Kind != "Pod" {
1✔
2734
                                        continue
×
2735
                                }
2736
                                aobj.AddChild(apicapi.NewVmmInjectedSvcEp(aobj.GetDn(),
1✔
2737
                                        addr.TargetRef.Name))
1✔
2738
                        }
2739
                }
2740
        }
2741
        return true
1✔
2742
}
2743

2744
func (seps *serviceEndpointSlice) SetServiceApicObject(aobj apicapi.ApicObject, service *v1.Service) bool {
1✔
2745
        cont := seps.cont
1✔
2746
        label := map[string]string{discovery.LabelServiceName: service.ObjectMeta.Name}
1✔
2747
        selector := labels.SelectorFromSet(label)
1✔
2748
        epcount := 0
1✔
2749
        childs := make(map[string]struct{})
1✔
2750
        var exists = struct{}{}
1✔
2751
        cache.ListAllByNamespace(cont.endpointSliceIndexer, service.ObjectMeta.Namespace, selector,
1✔
2752
                func(endpointSliceobj interface{}) {
2✔
2753
                        endpointSlices := endpointSliceobj.(*discovery.EndpointSlice)
1✔
2754
                        for _, endpoint := range endpointSlices.Endpoints {
2✔
2755
                                if endpoint.TargetRef == nil || endpoint.TargetRef.Kind != "Pod" {
1✔
2756
                                        continue
×
2757
                                }
2758
                                epcount++
1✔
2759
                                childs[endpoint.TargetRef.Name] = exists
1✔
2760
                                cont.log.Debug("EndPoint added: ", endpoint.TargetRef.Name)
1✔
2761
                        }
2762
                })
2763
        for child := range childs {
2✔
2764
                aobj.AddChild(apicapi.NewVmmInjectedSvcEp(aobj.GetDn(), child))
1✔
2765
        }
1✔
2766
        return epcount != 0
1✔
2767
}
2768

2769
func getProtocolStr(proto v1.Protocol) string {
1✔
2770
        var protostring string
1✔
2771
        switch proto {
1✔
2772
        case v1.ProtocolUDP:
1✔
2773
                protostring = "udp"
1✔
2774
        case v1.ProtocolTCP:
1✔
2775
                protostring = "tcp"
1✔
2776
        case v1.ProtocolSCTP:
×
2777
                protostring = "sctp"
×
2778
        default:
×
2779
                protostring = "tcp"
×
2780
        }
2781
        return protostring
1✔
2782
}
2783

2784
func (cont *AciController) removeIpFromIngressIPList(ingressIps *[]net.IP, ip net.IP) {
×
2785
        cont.returnServiceIps([]net.IP{ip})
×
2786
        index := -1
×
2787
        for i, v := range *ingressIps {
×
2788
                if v.Equal(ip) {
×
2789
                        index = i
×
2790
                        break
×
2791
                }
2792
        }
2793
        if index == -1 {
×
2794
                return
×
2795
        }
×
2796
        *ingressIps = append((*ingressIps)[:index], (*ingressIps)[index+1:]...)
×
2797
}
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