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

noironetworks / aci-containers / 9934

24 Sep 2024 08:46AM UTC coverage: 69.502% (-0.1%) from 69.632%
9934

push

travis-pro

web-flow
Merge pull request #1403 from noironetworks/annotation-error-fix

Reduce the frequency of error logs

0 of 30 new or added lines in 1 file covered. (0.0%)

15 existing lines in 4 files now uncovered.

13129 of 18890 relevant lines covered (69.5%)

0.79 hits per line

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

62.81
/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
        "sort"
23
        "strconv"
24
        "strings"
25
        "time"
26

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

265
        return serviceObjs
1✔
266
}
267

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
920
        return filter
1✔
921
}
1✔
922

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1223
        dc.AddChild(lif)
1✔
1224

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

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

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

1✔
1307
        var nodes []string
1✔
1308
        for node := range nodeMap {
2✔
1309
                nodes = append(nodes, node)
1✔
1310
        }
1✔
1311
        sort.Strings(nodes)
1✔
1312

1✔
1313
        name := cont.aciNameForKey("svc", "global")
1✔
1314
        var serviceObjs apicapi.ApicSlice
1✔
1315

1✔
1316
        // 1. Device cluster:
1✔
1317
        // The device cluster is a set of physical paths that need to be
1✔
1318
        // created for each node in the cluster, that correspond to the
1✔
1319
        // service interface for each node.
1✔
1320
        dc, dcDn := apicDeviceCluster(name, cont.config.AciVrfTenant,
1✔
1321
                cont.config.AciServicePhysDom, cont.config.AciServiceEncap,
1✔
1322
                nodes, nodeMap)
1✔
1323
        serviceObjs = append(serviceObjs, dc)
1✔
1324

1✔
1325
        // 2. Service graph template
1✔
1326
        // The service graph controls how the traffic will be redirected.
1✔
1327
        // A service graph must be created for each device cluster.
1✔
1328
        serviceObjs = append(serviceObjs,
1✔
1329
                apicServiceGraph(name, cont.config.AciVrfTenant, dcDn))
1✔
1330

1✔
1331
        cont.apicConn.WriteApicObjects(name, serviceObjs)
1✔
1332
}
1333

1334
func (cont *AciController) fabricPathLogger(node string,
1335
        obj apicapi.ApicObject) *logrus.Entry {
1✔
1336
        return cont.log.WithFields(logrus.Fields{
1✔
1337
                "fabricPath": obj.GetAttr("fabricPathDn"),
1✔
1338
                "mac":        obj.GetAttr("mac"),
1✔
1339
                "node":       node,
1✔
1340
                "obj":        obj,
1✔
1341
        })
1✔
1342
}
1✔
1343

1344
func (cont *AciController) setOpenStackSystemId() string {
×
1345

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

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

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

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

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

1427
func (cont *AciController) opflexDeviceChanged(obj apicapi.ApicObject) {
1✔
1428
        devType := obj.GetAttrStr("devType")
1✔
1429
        domName := obj.GetAttrStr("domName")
1✔
1430
        ctrlrName := obj.GetAttrStr("ctrlrName")
1✔
1431

1✔
1432
        if !cont.config.DisableServiceVlanPreprovisioning && strings.Contains(cont.config.Flavor, "openstack") {
1✔
1433
                if cont.openStackOpflexOdevUpdate(obj) {
×
1434
                        cont.log.Info("OpenStack opflexODev for ", obj.GetAttrStr("hostName"), " is added")
×
1435
                        cont.updateDeviceCluster()
×
1436
                }
×
1437
        }
1438
        if (devType == cont.env.OpFlexDeviceType()) && (domName == cont.config.AciVmmDomain) && (ctrlrName == cont.config.AciVmmController) {
2✔
1439
                cont.fabricPathLogger(obj.GetAttrStr("hostName"), obj).Debug("Processing opflex device update")
1✔
1440
                if obj.GetAttrStr("state") == "disconnected" {
2✔
1441
                        cont.fabricPathLogger(obj.GetAttrStr("hostName"), obj).Debug("Opflex device disconnected")
1✔
1442
                        cont.indexMutex.Lock()
1✔
1443
                        for node, devices := range cont.nodeOpflexDevice {
1✔
1444
                                if node == obj.GetAttrStr("hostName") {
×
1445
                                        for _, device := range devices {
×
1446
                                                if device.GetDn() == obj.GetDn() {
×
1447
                                                        device.SetAttr("state", "disconnected")
×
1448
                                                        cont.fabricPathLogger(device.GetAttrStr("hostName"), device).Debug("Opflex device cache updated for disconnected node")
×
1449
                                                }
×
1450
                                        }
1451
                                        cont.log.Info("Opflex device list for node ", obj.GetAttrStr("hostName"), ": ", devices)
×
1452
                                        break
×
1453
                                }
1454
                        }
1455
                        cont.indexMutex.Unlock()
1✔
1456
                        cont.updateDeviceCluster()
1✔
1457
                        return
1✔
1458
                }
1459
                var nodeUpdates []string
1✔
1460

1✔
1461
                cont.indexMutex.Lock()
1✔
1462
                nodefound := false
1✔
1463
                for node, devices := range cont.nodeOpflexDevice {
2✔
1464
                        found := false
1✔
1465

1✔
1466
                        if node == obj.GetAttrStr("hostName") {
2✔
1467
                                nodefound = true
1✔
1468
                        }
1✔
1469

1470
                        for i, device := range devices {
2✔
1471
                                if device.GetDn() != obj.GetDn() {
2✔
1472
                                        continue
1✔
1473
                                }
1474
                                found = true
1✔
1475

1✔
1476
                                if obj.GetAttrStr("hostName") != node {
2✔
1477
                                        cont.fabricPathLogger(node, device).
1✔
1478
                                                Debug("Moving opflex device from node")
1✔
1479

1✔
1480
                                        devices = append(devices[:i], devices[i+1:]...)
1✔
1481
                                        cont.nodeOpflexDevice[node] = devices
1✔
1482
                                        nodeUpdates = append(nodeUpdates, node)
1✔
1483
                                        break
1✔
1484
                                } else if (device.GetAttrStr("mac") != obj.GetAttrStr("mac")) ||
1✔
1485
                                        (device.GetAttrStr("fabricPathDn") != obj.GetAttrStr("fabricPathDn")) ||
1✔
1486
                                        (device.GetAttrStr("state") != obj.GetAttrStr("state")) {
2✔
1487
                                        cont.fabricPathLogger(node, obj).
1✔
1488
                                                Debug("Updating opflex device")
1✔
1489

1✔
1490
                                        devices = append(append(devices[:i], devices[i+1:]...), obj)
1✔
1491
                                        cont.nodeOpflexDevice[node] = devices
1✔
1492
                                        nodeUpdates = append(nodeUpdates, node)
1✔
1493
                                        break
1✔
1494
                                }
1495
                        }
1496
                        if !found && obj.GetAttrStr("hostName") == node {
2✔
1497
                                cont.fabricPathLogger(node, obj).
1✔
1498
                                        Debug("Appending opflex device")
1✔
1499

1✔
1500
                                devices = append(devices, obj)
1✔
1501
                                cont.nodeOpflexDevice[node] = devices
1✔
1502
                                nodeUpdates = append(nodeUpdates, node)
1✔
1503
                        }
1✔
1504
                }
1505
                if !nodefound {
2✔
1506
                        node := obj.GetAttrStr("hostName")
1✔
1507
                        cont.fabricPathLogger(node, obj).Debug("Adding opflex device")
1✔
1508
                        cont.nodeOpflexDevice[node] = apicapi.ApicSlice{obj}
1✔
1509
                        nodeUpdates = append(nodeUpdates, node)
1✔
1510
                }
1✔
1511
                cont.log.Info("Opflex device list for node ", obj.GetAttrStr("hostName"), ": ", cont.nodeOpflexDevice[obj.GetAttrStr("hostName")])
1✔
1512
                cont.indexMutex.Unlock()
1✔
1513

1✔
1514
                for _, node := range nodeUpdates {
2✔
1515
                        cont.env.NodeServiceChanged(node)
1✔
1516
                        cont.erspanSyncOpflexDev()
1✔
1517
                }
1✔
1518
                cont.updateDeviceCluster()
1✔
1519
        }
1520
}
1521

1522
func (cont *AciController) postOpflexDeviceDelete(nodes []string) {
1✔
1523
        cont.updateDeviceCluster()
1✔
1524
        for _, node := range nodes {
2✔
1525
                cont.env.NodeServiceChanged(node)
1✔
1526
                cont.erspanSyncOpflexDev()
1✔
1527
        }
1✔
1528
}
1529

1530
func (cont *AciController) opflexDeviceDeleted(dn string) {
1✔
1531
        var nodeUpdates []string
1✔
1532
        var dnFound bool //to check if the dn belongs to this cluster
1✔
1533
        cont.log.Info("Processing opflex device delete notification of ", dn)
1✔
1534
        cont.indexMutex.Lock()
1✔
1535
        for node, devices := range cont.nodeOpflexDevice {
2✔
1536
                for i, device := range devices {
2✔
1537
                        if device.GetDn() != dn {
2✔
1538
                                continue
1✔
1539
                        }
1540
                        dnFound = true
1✔
1541
                        cont.fabricPathLogger(node, device).
1✔
1542
                                Debug("Deleting opflex device path")
1✔
1543
                        devices = append(devices[:i], devices[i+1:]...)
1✔
1544
                        cont.nodeOpflexDevice[node] = devices
1✔
1545
                        cont.log.Info("Deleted opflex device of node ", node, ": ", dn)
1✔
1546
                        nodeUpdates = append(nodeUpdates, node)
1✔
1547
                        break
1✔
1548
                }
1549
                if len(devices) == 0 {
2✔
1550
                        delete(cont.nodeOpflexDevice, node)
1✔
1551
                }
1✔
1552
        }
1553

1554
        // For clusters other than OpenShift On OpenStack,
1555
        // openStackFabricPathDnMap will be empty
1556
        for host, opflexOdevInfo := range cont.openStackFabricPathDnMap {
1✔
1557
                if _, ok := opflexOdevInfo.opflexODevDn[dn]; ok {
×
1558
                        cont.log.Info("Received OpenStack opflexODev delete notification for ", dn)
×
1559
                        delete(opflexOdevInfo.opflexODevDn, dn)
×
1560
                        if len(opflexOdevInfo.opflexODevDn) < 1 {
×
1561
                                delete(cont.openStackFabricPathDnMap, host)
×
1562
                                cont.log.Info("OpenStack opflexODev of host ", host, " is deleted from cache")
×
1563
                                dnFound = true
×
1564
                        } else {
×
1565
                                cont.openStackFabricPathDnMap[host] = opflexOdevInfo
×
1566
                        }
×
1567
                        break
×
1568
                }
1569
        }
1570
        cont.indexMutex.Unlock()
1✔
1571

1✔
1572
        if dnFound {
2✔
1573
                cont.postOpflexDeviceDelete(nodeUpdates)
1✔
1574
        }
1✔
1575
}
1576

1577
func (cont *AciController) writeApicSvc(key string, service *v1.Service) {
1✔
1578
        if cont.config.ChainedMode {
1✔
1579
                return
×
1580
        }
×
1581
        aobj := apicapi.NewVmmInjectedSvc(cont.vmmDomainProvider(),
1✔
1582
                cont.config.AciVmmDomain, cont.config.AciVmmController,
1✔
1583
                service.Namespace, service.Name)
1✔
1584
        aobjDn := aobj.GetDn()
1✔
1585
        aobj.SetAttr("guid", string(service.UID))
1✔
1586

1✔
1587
        svcns := service.ObjectMeta.Namespace
1✔
1588
        _, exists, err := cont.namespaceIndexer.GetByKey(svcns)
1✔
1589
        if err != nil {
1✔
1590
                cont.log.Error("Failed to lookup ns : ", svcns, " ", err)
×
1591
                return
×
1592
        }
×
1593
        if !exists {
2✔
1594
                cont.log.Debug("Namespace of service ", service.ObjectMeta.Name, ": ", svcns, " doesn't exist, hence not sending an update to the APIC")
1✔
1595
                return
1✔
1596
        }
1✔
1597

1598
        if !cont.serviceEndPoints.SetServiceApicObject(aobj, service) {
2✔
1599
                return
1✔
1600
        }
1✔
1601
        var setApicSvcDnsName bool
1✔
1602
        if len(cont.config.ApicHosts) != 0 && apicapi.ApicVersion >= "5.1" {
1✔
1603
                setApicSvcDnsName = true
×
1604
        }
×
1605
        // APIC model only allows one of these
1606
        for _, ingress := range service.Status.LoadBalancer.Ingress {
1✔
1607
                if ingress.IP != "" && ingress.IP != "0.0.0.0" {
×
1608
                        aobj.SetAttr("lbIp", ingress.IP)
×
1609
                } else if ingress.Hostname != "" {
×
1610
                        ipList, err := net.LookupHost(ingress.Hostname)
×
1611
                        if err == nil && len(ipList) > 0 {
×
1612
                                aobj.SetAttr("lbIp", ipList[0])
×
1613
                        } else {
×
1614
                                cont.log.Errorf("Lookup: err: %v, ipList: %+v", err, ipList)
×
1615
                        }
×
1616
                }
1617
                break
×
1618
        }
1619
        if service.Spec.ClusterIP != "" && service.Spec.ClusterIP != "None" {
2✔
1620
                aobj.SetAttr("clusterIp", service.Spec.ClusterIP)
1✔
1621
        }
1✔
1622

1623
        var t string
1✔
1624
        switch service.Spec.Type {
1✔
1625
        case v1.ServiceTypeClusterIP:
×
1626
                t = "clusterIp"
×
1627
        case v1.ServiceTypeNodePort:
×
1628
                t = "nodePort"
×
1629
        case v1.ServiceTypeLoadBalancer:
1✔
1630
                t = "loadBalancer"
1✔
1631
        case v1.ServiceTypeExternalName:
×
1632
                t = "externalName"
×
1633
        }
1634
        if t != "" {
2✔
1635
                aobj.SetAttr("type", t)
1✔
1636
        }
1✔
1637

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

×
1641
                for _, ingress := range service.Status.LoadBalancer.Ingress {
×
1642
                        if ingress.Hostname != "" {
×
1643
                                aobj.SetAttr("dnsName", ingress.Hostname)
×
1644
                        } else if ingress.IP != "" && ingress.IP != "0.0.0.0" {
×
1645
                                aobj.SetAttr("dnsName", dnsName)
×
1646
                        }
×
1647
                }
1648
                if t == "clusterIp" || t == "nodePort" || t == "externalName" {
×
1649
                        aobj.SetAttr("dnsName", dnsName)
×
1650
                }
×
1651
        }
1652
        for _, port := range service.Spec.Ports {
2✔
1653
                proto := getProtocolStr(port.Protocol)
1✔
1654
                p := apicapi.NewVmmInjectedSvcPort(aobjDn,
1✔
1655
                        strconv.Itoa(int(port.Port)), proto, port.TargetPort.String())
1✔
1656
                p.SetAttr("nodePort", strconv.Itoa(int(port.NodePort)))
1✔
1657
                aobj.AddChild(p)
1✔
1658
        }
1✔
1659
        if cont.config.EnableVmmInjectedLabels && service.ObjectMeta.Labels != nil && apicapi.ApicVersion >= "5.2" {
1✔
1660
                for key, val := range service.ObjectMeta.Labels {
×
1661
                        newLabelKey := cont.aciNameForKey("label", key)
×
1662
                        label := apicapi.NewVmmInjectedLabel(aobj.GetDn(),
×
1663
                                newLabelKey, val)
×
1664
                        aobj.AddChild(label)
×
1665
                }
×
1666
        }
1667
        name := cont.aciNameForKey("service-vmm", key)
1✔
1668
        cont.log.Debug("Write Service Object: ", aobj)
1✔
1669
        cont.apicConn.WriteApicObjects(name, apicapi.ApicSlice{aobj})
1✔
1670
        cont.log.Debugf("svcObject: %+v", aobj)
1✔
1671
}
1672

1673
func removeAllConditions(conditions []metav1.Condition, conditionType string) []metav1.Condition {
1✔
1674
        i := 0
1✔
1675
        for _, cond := range conditions {
1✔
1676
                if cond.Type != conditionType {
×
1677
                        conditions[i] = cond
×
1678
                }
×
1679
        }
1680
        return conditions[:i]
1✔
1681
}
1682

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

1✔
1686
        var condition metav1.Condition
1✔
1687
        if success {
2✔
1688
                condition.Status = metav1.ConditionTrue
1✔
1689
        } else {
2✔
1690
                condition.Status = metav1.ConditionFalse
1✔
1691
                condition.Message = message
1✔
1692
        }
1✔
1693
        condition.Type = conditionType
1✔
1694
        condition.Reason = reason
1✔
1695
        condition.LastTransitionTime = metav1.Time{time.Now()}
1✔
1696
        for _, cond := range service.Status.Conditions {
2✔
1697
                if cond.Type == conditionType &&
1✔
1698
                        cond.Status == condition.Status &&
1✔
1699
                        cond.Message == condition.Message &&
1✔
1700
                        cond.Reason == condition.Reason {
2✔
1701
                        return false
1✔
1702
                }
1✔
1703
        }
1704

1705
        service.Status.Conditions = removeAllConditions(service.Status.Conditions, conditionType)
1✔
1706
        service.Status.Conditions = append(service.Status.Conditions, condition)
1✔
1707
        return true
1✔
1708
}
1709

1710
func (cont *AciController) validateRequestedIps(lbIpList []string) (net.IP, net.IP, bool) {
1✔
1711
        var ipv4, ipv6 net.IP
1✔
1712
        for _, lbIp := range lbIpList {
2✔
1713
                ip := net.ParseIP(lbIp)
1✔
1714
                if ip != nil {
2✔
1715
                        if ip.To4() != nil {
2✔
1716
                                if ipv4.Equal(net.IP{}) {
2✔
1717
                                        ipv4 = ip
1✔
1718
                                } else {
2✔
1719
                                        cont.log.Error("Annotation should have only one ipv4")
1✔
1720
                                        return ipv4, ipv6, false
1✔
1721
                                }
1✔
1722
                        } else if ip.To16() != nil {
2✔
1723
                                if ipv6.Equal(net.IP{}) {
2✔
1724
                                        ipv6 = ip
1✔
1725
                                } else {
2✔
1726
                                        cont.log.Error("Annotation should have only one ipv6")
1✔
1727
                                        return ipv4, ipv6, false
1✔
1728
                                }
1✔
1729
                        }
1730
                }
1731
        }
1732
        return ipv4, ipv6, true
1✔
1733
}
1734

1735
func (cont *AciController) returnUnusedStaticIngressIps(staticIngressIps, requestedIps []net.IP) {
1✔
1736
        for _, staticIp := range staticIngressIps {
2✔
1737
                found := false
1✔
1738
                for _, reqIp := range requestedIps {
2✔
1739
                        if reqIp.Equal(staticIp) {
2✔
1740
                                found = true
1✔
1741
                        }
1✔
1742
                }
1743
                if !found {
2✔
1744
                        returnIps(cont.staticServiceIps, []net.IP{staticIp})
1✔
1745
                }
1✔
1746
        }
1747
}
1748

1749
func (cont *AciController) allocateServiceIps(servicekey string,
1750
        service *v1.Service) bool {
1✔
1751
        logger := serviceLogger(cont.log, service)
1✔
1752
        cont.indexMutex.Lock()
1✔
1753
        meta, ok := cont.serviceMetaCache[servicekey]
1✔
1754
        if !ok {
2✔
1755
                meta = &serviceMeta{}
1✔
1756
                cont.serviceMetaCache[servicekey] = meta
1✔
1757

1✔
1758
                // Read any existing IPs and attempt to allocate them to the pod
1✔
1759
                for _, ingress := range service.Status.LoadBalancer.Ingress {
2✔
1760
                        ip := net.ParseIP(ingress.IP)
1✔
1761
                        if ip == nil {
1✔
1762
                                continue
×
1763
                        }
1764
                        if ip.To4() != nil {
2✔
1765
                                if cont.serviceIps.GetV4IpCache()[0].RemoveIp(ip) {
2✔
1766
                                        meta.ingressIps = append(meta.ingressIps, ip)
1✔
1767
                                } else if cont.staticServiceIps.V4.RemoveIp(ip) {
3✔
1768
                                        meta.staticIngressIps = append(meta.staticIngressIps, ip)
1✔
1769
                                }
1✔
1770
                        } else if ip.To16() != nil {
2✔
1771
                                if cont.serviceIps.GetV6IpCache()[0].RemoveIp(ip) {
2✔
1772
                                        meta.ingressIps = append(meta.ingressIps, ip)
1✔
1773
                                } else if cont.staticServiceIps.V6.RemoveIp(ip) {
3✔
1774
                                        meta.staticIngressIps = append(meta.staticIngressIps, ip)
1✔
1775
                                }
1✔
1776
                        }
1777
                }
1778
        }
1779

1780
        if !cont.serviceSyncEnabled {
2✔
1781
                cont.indexMutex.Unlock()
1✔
1782
                return false
1✔
1783
        }
1✔
1784

1785
        var requestedIps []net.IP
1✔
1786
        // try to give the requested load balancer IP to the pod
1✔
1787
        lbIps, ok := service.ObjectMeta.Annotations[metadata.LbIpAnnotation]
1✔
1788
        if ok {
2✔
1789
                lbIpList := strings.Split(lbIps, ",")
1✔
1790
                ipv4, ipv6, valid := cont.validateRequestedIps(lbIpList)
1✔
1791
                if valid {
2✔
1792
                        if ipv4 != nil {
2✔
1793
                                requestedIps = append(requestedIps, ipv4)
1✔
1794
                        }
1✔
1795
                        if ipv6 != nil {
2✔
1796
                                requestedIps = append(requestedIps, ipv6)
1✔
1797
                        }
1✔
1798
                } else {
1✔
1799
                        cont.returnServiceIps(meta.ingressIps)
1✔
1800
                        cont.log.Error("Invalid LB IP annotation for service ", servicekey)
1✔
1801
                        condUpdated := cont.updateServiceCondition(service, false, "InvalidAnnotation", "Invalid Loadbalancer IP annotation")
1✔
1802
                        if condUpdated {
2✔
1803
                                _, err := cont.updateServiceStatus(service)
1✔
1804
                                if err != nil {
1✔
1805
                                        logger.Error("Failed to update service status : ", err)
×
1806
                                        cont.indexMutex.Unlock()
×
1807
                                        return true
×
1808
                                }
×
1809
                        }
1810
                        cont.indexMutex.Unlock()
1✔
1811
                        return false
1✔
1812
                }
1813
        } else {
1✔
1814
                requestedIp := net.ParseIP(service.Spec.LoadBalancerIP)
1✔
1815
                if requestedIp != nil {
2✔
1816
                        requestedIps = append(requestedIps, requestedIp)
1✔
1817
                }
1✔
1818
        }
1819
        if len(requestedIps) > 0 {
2✔
1820
                meta.requestedIps = []net.IP{}
1✔
1821
                for _, requestedIp := range requestedIps {
2✔
1822
                        hasRequestedIp := false
1✔
1823
                        for _, ip := range meta.staticIngressIps {
2✔
1824
                                if reflect.DeepEqual(requestedIp, ip) {
2✔
1825
                                        hasRequestedIp = true
1✔
1826
                                }
1✔
1827
                        }
1828
                        if !hasRequestedIp {
2✔
1829
                                if requestedIp.To4() != nil &&
1✔
1830
                                        cont.staticServiceIps.V4.RemoveIp(requestedIp) {
2✔
1831
                                        hasRequestedIp = true
1✔
1832
                                } else if requestedIp.To16() != nil &&
2✔
1833
                                        cont.staticServiceIps.V6.RemoveIp(requestedIp) {
2✔
1834
                                        hasRequestedIp = true
1✔
1835
                                }
1✔
1836
                        }
1837
                        if hasRequestedIp {
2✔
1838
                                meta.requestedIps = append(meta.requestedIps, requestedIp)
1✔
1839
                        }
1✔
1840
                }
1841
                cont.returnUnusedStaticIngressIps(meta.staticIngressIps, meta.requestedIps)
1✔
1842
                meta.staticIngressIps = meta.requestedIps
1✔
1843
                cont.returnServiceIps(meta.ingressIps)
1✔
1844
                meta.ingressIps = nil
1✔
1845
                // If no requested ips are allocatable
1✔
1846
                if len(meta.requestedIps) < 1 {
2✔
1847
                        logger.Error("No Requested Ip addresses available for service ", servicekey)
1✔
1848
                        condUpdated := cont.updateServiceCondition(service, false, "RequestedIpsNotAllocatable", "The requested ips for loadbalancer service are not available or not in extern static range")
1✔
1849
                        if condUpdated {
2✔
1850
                                _, err := cont.updateServiceStatus(service)
1✔
1851
                                if err != nil {
1✔
1852
                                        cont.indexMutex.Unlock()
×
1853
                                        logger.Error("Failed to update service status: ", err)
×
1854
                                        return true
×
1855
                                }
×
1856
                        }
1857
                        cont.indexMutex.Unlock()
1✔
1858
                        return false
1✔
1859
                }
1860
        } else if len(meta.requestedIps) > 0 {
1✔
1861
                meta.requestedIps = nil
×
1862
                returnIps(cont.staticServiceIps, meta.staticIngressIps)
×
1863
                meta.staticIngressIps = nil
×
1864
        }
×
1865
        ingressIps := make([]net.IP, 0)
1✔
1866
        ingressIps = append(ingressIps, meta.ingressIps...)
1✔
1867
        ingressIps = append(ingressIps, meta.staticIngressIps...)
1✔
1868

1✔
1869
        var ipv4, ipv6 net.IP
1✔
1870
        for _, ip := range ingressIps {
2✔
1871
                if ip.To4() != nil {
2✔
1872
                        ipv4 = ip
1✔
1873
                } else if ip.To16() != nil {
3✔
1874
                        ipv6 = ip
1✔
1875
                }
1✔
1876
        }
1877
        var clusterIPv4, clusterIPv6 net.IP
1✔
1878
        clusterIPs := append([]string{service.Spec.ClusterIP}, service.Spec.ClusterIPs...)
1✔
1879
        for _, ipStr := range clusterIPs {
2✔
1880
                ip := net.ParseIP(ipStr)
1✔
1881
                if ip == nil {
1✔
1882
                        continue
×
1883
                }
1884
                if ip.To4() != nil && clusterIPv4 == nil {
2✔
1885
                        clusterIPv4 = ip
1✔
1886
                } else if ip.To16() != nil && strings.Contains(ip.String(), ":") && clusterIPv6 == nil {
3✔
1887
                        clusterIPv6 = ip
1✔
1888
                }
1✔
1889
        }
1890
        if clusterIPv4 != nil && ipv4 == nil {
2✔
1891
                if len(requestedIps) < 1 {
2✔
1892
                        ipv4, _ = cont.serviceIps.AllocateIp(true)
1✔
1893
                        if ipv4 != nil {
2✔
1894
                                ingressIps = append(ingressIps, ipv4)
1✔
1895
                        }
1✔
1896
                }
1897
        } else if clusterIPv4 == nil && ipv4 != nil {
1✔
1898
                cont.removeIpFromIngressIPList(&ingressIps, ipv4)
×
1899
        }
×
1900

1901
        if clusterIPv6 != nil && ipv6 == nil {
2✔
1902
                if len(requestedIps) < 1 {
2✔
1903
                        ipv6, _ = cont.serviceIps.AllocateIp(false)
1✔
1904
                        if ipv6 != nil {
2✔
1905
                                ingressIps = append(ingressIps, ipv6)
1✔
1906
                        }
1✔
1907
                }
1908
        } else if clusterIPv6 == nil && ipv6 != nil {
1✔
1909
                cont.removeIpFromIngressIPList(&ingressIps, ipv6)
×
1910
        }
×
1911

1912
        if len(requestedIps) < 1 {
2✔
1913
                meta.ingressIps = ingressIps
1✔
1914
        }
1✔
1915
        if ipv4 == nil && ipv6 == nil {
2✔
1916
                logger.Error("No IP addresses available for service")
1✔
1917
                cont.indexMutex.Unlock()
1✔
1918
                return true
1✔
1919
        }
1✔
1920
        cont.indexMutex.Unlock()
1✔
1921
        var newIngress []v1.LoadBalancerIngress
1✔
1922
        for _, ip := range meta.ingressIps {
2✔
1923
                newIngress = append(newIngress, v1.LoadBalancerIngress{IP: ip.String()})
1✔
1924
        }
1✔
1925
        for _, ip := range meta.staticIngressIps {
2✔
1926
                newIngress = append(newIngress, v1.LoadBalancerIngress{IP: ip.String()})
1✔
1927
        }
1✔
1928

1929
        ipUpdated := false
1✔
1930
        if !reflect.DeepEqual(newIngress, service.Status.LoadBalancer.Ingress) {
2✔
1931
                service.Status.LoadBalancer.Ingress = newIngress
1✔
1932

1✔
1933
                logger.WithFields(logrus.Fields{
1✔
1934
                        "status": service.Status.LoadBalancer.Ingress,
1✔
1935
                }).Info("Updating service load balancer status")
1✔
1936

1✔
1937
                ipUpdated = true
1✔
1938
        }
1✔
1939

1940
        success := true
1✔
1941
        reason := "Success"
1✔
1942
        message := ""
1✔
1943
        if len(requestedIps) > 0 && len(requestedIps) != len(meta.staticIngressIps) {
1✔
1944
                success = false
×
1945
                reason = "OneIpNotAllocatable"
×
1946
                message = "One of the requested Ips is not allocatable"
×
1947
        }
×
1948
        condUpdated := cont.updateServiceCondition(service, success, reason, message)
1✔
1949
        if ipUpdated || condUpdated {
2✔
1950
                _, err := cont.updateServiceStatus(service)
1✔
1951
                if err != nil {
1✔
1952
                        logger.Error("Failed to update service status: ", err)
×
1953
                        return true
×
1954
                }
×
1955
        }
1956
        return false
1✔
1957
}
1958

1959
func (cont *AciController) handleServiceDelete(servicekey string) bool {
1✔
1960
        if cont.config.ChainedMode {
1✔
1961
                return false
×
1962
        }
×
1963
        cont.clearLbService(servicekey)
1✔
1964
        cont.apicConn.ClearApicObjects(cont.aciNameForKey("service-vmm",
1✔
1965
                servicekey))
1✔
1966
        return false
1✔
1967
}
1968

1969
func (cont *AciController) handleServiceUpdate(service *v1.Service) bool {
1✔
1970
        servicekey, err := cache.MetaNamespaceKeyFunc(service)
1✔
1971
        if err != nil {
1✔
1972
                serviceLogger(cont.log, service).
×
1973
                        Error("Could not create service key: ", err)
×
1974
                return false
×
1975
        }
×
1976
        if cont.config.ChainedMode {
1✔
1977
                return false
×
1978
        }
×
1979
        var requeue bool
1✔
1980
        isLoadBalancer := service.Spec.Type == v1.ServiceTypeLoadBalancer
1✔
1981
        if isLoadBalancer {
2✔
1982
                if *cont.config.AllocateServiceIps {
2✔
1983
                        requeue = cont.allocateServiceIps(servicekey, service)
1✔
1984
                }
1✔
1985
                cont.indexMutex.Lock()
1✔
1986
                if cont.serviceSyncEnabled {
2✔
1987
                        cont.indexMutex.Unlock()
1✔
1988
                        err = cont.updateServiceDeviceInstance(servicekey, service)
1✔
1989
                        if err != nil {
1✔
1990
                                serviceLogger(cont.log, service).
×
1991
                                        Error("Failed to update service device Instance: ", err)
×
1992
                                return true
×
1993
                        }
×
1994
                } else {
1✔
1995
                        cont.indexMutex.Unlock()
1✔
1996
                }
1✔
1997
        } else {
1✔
1998
                cont.clearLbService(servicekey)
1✔
1999
        }
1✔
2000
        cont.writeApicSvc(servicekey, service)
1✔
2001
        return requeue
1✔
2002
}
2003

2004
func (cont *AciController) clearLbService(servicekey string) {
1✔
2005
        cont.indexMutex.Lock()
1✔
2006
        if meta, ok := cont.serviceMetaCache[servicekey]; ok {
2✔
2007
                cont.returnServiceIps(meta.ingressIps)
1✔
2008
                returnIps(cont.staticServiceIps, meta.staticIngressIps)
1✔
2009
                delete(cont.serviceMetaCache, servicekey)
1✔
2010
        }
1✔
2011
        cont.indexMutex.Unlock()
1✔
2012
        cont.apicConn.ClearApicObjects(cont.aciNameForKey("svc", servicekey))
1✔
2013
}
2014

2015
func getEndpointsIps(endpoints *v1.Endpoints) map[string]bool {
1✔
2016
        ips := make(map[string]bool)
1✔
2017
        for _, subset := range endpoints.Subsets {
2✔
2018
                for _, addr := range subset.Addresses {
2✔
2019
                        ips[addr.IP] = true
1✔
2020
                }
1✔
2021
                for _, addr := range subset.NotReadyAddresses {
1✔
2022
                        ips[addr.IP] = true
×
2023
                }
×
2024
        }
2025
        return ips
1✔
2026
}
2027

2028
func getServiceTargetPorts(service *v1.Service) map[string]targetPort {
1✔
2029
        ports := make(map[string]targetPort)
1✔
2030
        for _, port := range service.Spec.Ports {
2✔
2031
                portNum := port.TargetPort.IntValue()
1✔
2032
                if portNum <= 0 {
2✔
2033
                        portNum = int(port.Port)
1✔
2034
                }
1✔
2035
                key := portProto(&port.Protocol) + "-num-" + strconv.Itoa(portNum)
1✔
2036
                ports[key] = targetPort{
1✔
2037
                        proto: port.Protocol,
1✔
2038
                        ports: []int{portNum},
1✔
2039
                }
1✔
2040
        }
2041
        return ports
1✔
2042
}
2043

2044
func (cont *AciController) endpointsAdded(obj interface{}) {
1✔
2045
        endpoints := obj.(*v1.Endpoints)
1✔
2046
        servicekey, err := cache.MetaNamespaceKeyFunc(obj.(*v1.Endpoints))
1✔
2047
        if err != nil {
1✔
2048
                cont.log.Error("Could not create service key: ", err)
×
2049
                return
×
2050
        }
×
2051

2052
        ips := getEndpointsIps(endpoints)
1✔
2053
        cont.indexMutex.Lock()
1✔
2054
        cont.updateIpIndex(cont.endpointsIpIndex, nil, ips, servicekey)
1✔
2055
        cont.queueIPNetPolUpdates(ips)
1✔
2056
        cont.indexMutex.Unlock()
1✔
2057

1✔
2058
        cont.queueEndpointsNetPolUpdates(endpoints)
1✔
2059

1✔
2060
        cont.queueServiceUpdateByKey(servicekey)
1✔
2061
}
2062

2063
func (cont *AciController) endpointsDeleted(obj interface{}) {
1✔
2064
        endpoints, isEndpoints := obj.(*v1.Endpoints)
1✔
2065
        if !isEndpoints {
1✔
2066
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
×
2067
                if !ok {
×
2068
                        cont.log.Error("Received unexpected object: ", obj)
×
2069
                        return
×
2070
                }
×
2071
                endpoints, ok = deletedState.Obj.(*v1.Endpoints)
×
2072
                if !ok {
×
2073
                        cont.log.Error("DeletedFinalStateUnknown contained non-Endpoints object: ", deletedState.Obj)
×
2074
                        return
×
2075
                }
×
2076
        }
2077
        servicekey, err := cache.MetaNamespaceKeyFunc(endpoints)
1✔
2078
        if err != nil {
1✔
2079
                cont.log.Error("Could not create service key: ", err)
×
2080
                return
×
2081
        }
×
2082

2083
        ips := getEndpointsIps(endpoints)
1✔
2084
        cont.indexMutex.Lock()
1✔
2085
        cont.updateIpIndex(cont.endpointsIpIndex, ips, nil, servicekey)
1✔
2086
        cont.queueIPNetPolUpdates(ips)
1✔
2087
        cont.indexMutex.Unlock()
1✔
2088

1✔
2089
        cont.queueEndpointsNetPolUpdates(endpoints)
1✔
2090

1✔
2091
        cont.queueServiceUpdateByKey(servicekey)
1✔
2092
}
2093

2094
func (cont *AciController) endpointsUpdated(oldEps, newEps interface{}) {
1✔
2095
        oldendpoints := oldEps.(*v1.Endpoints)
1✔
2096
        newendpoints := newEps.(*v1.Endpoints)
1✔
2097
        servicekey, err := cache.MetaNamespaceKeyFunc(newendpoints)
1✔
2098
        if err != nil {
1✔
2099
                cont.log.Error("Could not create service key: ", err)
×
2100
                return
×
2101
        }
×
2102

2103
        oldIps := getEndpointsIps(oldendpoints)
1✔
2104
        newIps := getEndpointsIps(newendpoints)
1✔
2105
        if !reflect.DeepEqual(oldIps, newIps) {
2✔
2106
                cont.indexMutex.Lock()
1✔
2107
                cont.queueIPNetPolUpdates(oldIps)
1✔
2108
                cont.updateIpIndex(cont.endpointsIpIndex, oldIps, newIps, servicekey)
1✔
2109
                cont.queueIPNetPolUpdates(newIps)
1✔
2110
                cont.indexMutex.Unlock()
1✔
2111
        }
1✔
2112

2113
        if !reflect.DeepEqual(oldendpoints.Subsets, newendpoints.Subsets) {
2✔
2114
                cont.queueEndpointsNetPolUpdates(oldendpoints)
1✔
2115
                cont.queueEndpointsNetPolUpdates(newendpoints)
1✔
2116
        }
1✔
2117

2118
        cont.queueServiceUpdateByKey(servicekey)
1✔
2119
}
2120

2121
func (cont *AciController) serviceAdded(obj interface{}) {
1✔
2122
        service := obj.(*v1.Service)
1✔
2123
        servicekey, err := cache.MetaNamespaceKeyFunc(service)
1✔
2124
        if err != nil {
1✔
2125
                serviceLogger(cont.log, service).
×
2126
                        Error("Could not create service key: ", err)
×
2127
                return
×
2128
        }
×
2129

2130
        ports := getServiceTargetPorts(service)
1✔
2131
        cont.indexMutex.Lock()
1✔
2132
        cont.queuePortNetPolUpdates(ports)
1✔
2133
        cont.updateTargetPortIndex(true, servicekey, nil, ports)
1✔
2134
        cont.indexMutex.Unlock()
1✔
2135

1✔
2136
        cont.queueServiceUpdateByKey(servicekey)
1✔
2137
}
2138

2139
func (cont *AciController) serviceUpdated(oldSvc, newSvc interface{}) {
1✔
2140
        oldservice := oldSvc.(*v1.Service)
1✔
2141
        newservice := newSvc.(*v1.Service)
1✔
2142
        servicekey, err := cache.MetaNamespaceKeyFunc(newservice)
1✔
2143
        if err != nil {
1✔
2144
                serviceLogger(cont.log, newservice).
×
2145
                        Error("Could not create service key: ", err)
×
2146
                return
×
2147
        }
×
2148
        oldPorts := getServiceTargetPorts(oldservice)
1✔
2149
        newPorts := getServiceTargetPorts(newservice)
1✔
2150
        if !reflect.DeepEqual(oldPorts, newPorts) {
1✔
2151
                cont.indexMutex.Lock()
×
2152
                cont.queuePortNetPolUpdates(oldPorts)
×
2153
                cont.updateTargetPortIndex(true, servicekey, oldPorts, newPorts)
×
2154
                cont.queuePortNetPolUpdates(newPorts)
×
2155
                cont.indexMutex.Unlock()
×
2156
        }
×
2157
        cont.queueServiceUpdateByKey(servicekey)
1✔
2158
}
2159

2160
func (cont *AciController) serviceDeleted(obj interface{}) {
1✔
2161
        service, isService := obj.(*v1.Service)
1✔
2162
        if !isService {
1✔
2163
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
×
2164
                if !ok {
×
2165
                        serviceLogger(cont.log, service).
×
2166
                                Error("Received unexpected object: ", obj)
×
2167
                        return
×
2168
                }
×
2169
                service, ok = deletedState.Obj.(*v1.Service)
×
2170
                if !ok {
×
2171
                        serviceLogger(cont.log, service).
×
2172
                                Error("DeletedFinalStateUnknown contained non-Services object: ", deletedState.Obj)
×
2173
                        return
×
2174
                }
×
2175
        }
2176
        servicekey, err := cache.MetaNamespaceKeyFunc(service)
1✔
2177
        if err != nil {
1✔
2178
                serviceLogger(cont.log, service).
×
2179
                        Error("Could not create service key: ", err)
×
2180
                return
×
2181
        }
×
2182

2183
        ports := getServiceTargetPorts(service)
1✔
2184
        cont.indexMutex.Lock()
1✔
2185
        cont.updateTargetPortIndex(true, servicekey, ports, nil)
1✔
2186
        cont.queuePortNetPolUpdates(ports)
1✔
2187
        delete(cont.snatServices, servicekey)
1✔
2188
        cont.indexMutex.Unlock()
1✔
2189

1✔
2190
        deletedServiceKey := "DELETED_" + servicekey
1✔
2191
        cont.queueServiceUpdateByKey(deletedServiceKey)
1✔
2192
}
2193

2194
func (cont *AciController) serviceFullSync() {
1✔
2195
        cache.ListAll(cont.serviceIndexer, labels.Everything(),
1✔
2196
                func(sobj interface{}) {
2✔
2197
                        cont.queueServiceUpdate(sobj.(*v1.Service))
1✔
2198
                })
1✔
2199
}
2200

2201
func (cont *AciController) getEndpointSliceIps(endpointSlice *discovery.EndpointSlice) map[string]bool {
1✔
2202
        ips := make(map[string]bool)
1✔
2203
        for _, endpoints := range endpointSlice.Endpoints {
2✔
2204
                for _, addr := range endpoints.Addresses {
2✔
2205
                        ips[addr] = true
1✔
2206
                }
1✔
2207
        }
2208
        return ips
1✔
2209
}
2210

2211
func (cont *AciController) notReadyEndpointPresent(endpointSlice *discovery.EndpointSlice) bool {
×
2212
        for _, endpoints := range endpointSlice.Endpoints {
×
2213
                if (endpoints.Conditions.Ready != nil && !*endpoints.Conditions.Ready) &&
×
2214
                        (endpoints.Conditions.Terminating == nil || !*endpoints.Conditions.Terminating) {
×
2215
                        return true
×
2216
                }
×
2217
        }
2218
        return false
×
2219
}
2220

2221
func (cont *AciController) getEndpointSliceEpIps(endpoints *discovery.Endpoint) map[string]bool {
×
2222
        ips := make(map[string]bool)
×
2223
        for _, addr := range endpoints.Addresses {
×
2224
                ips[addr] = true
×
2225
        }
×
2226
        return ips
×
2227
}
2228

2229
func (cont *AciController) processDelayedEpSlices() {
1✔
2230
        var processEps []DelayedEpSlice
1✔
2231
        cont.indexMutex.Lock()
1✔
2232
        for i := 0; i < len(cont.delayedEpSlices); i++ {
1✔
2233
                delayedepslice := cont.delayedEpSlices[i]
×
2234
                if time.Now().After(delayedepslice.DelayedTime) {
×
2235
                        var toprocess DelayedEpSlice
×
2236
                        err := util.DeepCopyObj(&delayedepslice, &toprocess)
×
2237
                        if err != nil {
×
2238
                                cont.log.Error(err)
×
2239
                                continue
×
2240
                        }
2241
                        processEps = append(processEps, toprocess)
×
2242
                        cont.delayedEpSlices = append(cont.delayedEpSlices[:i], cont.delayedEpSlices[i+1:]...)
×
2243
                }
2244
        }
2245

2246
        cont.indexMutex.Unlock()
1✔
2247
        for _, epslice := range processEps {
1✔
2248
                //ignore the epslice if newly added endpoint is not ready
×
2249
                if cont.notReadyEndpointPresent(epslice.NewEpSlice) {
×
2250
                        cont.log.Debug("Ignoring the update as the new endpoint is not ready : ", epslice.NewEpSlice)
×
2251
                } else {
×
2252
                        cont.log.Debug("Processing update of epslice : ", epslice.NewEpSlice)
×
2253
                        cont.doendpointSliceUpdated(epslice.OldEpSlice, epslice.NewEpSlice)
×
2254
                }
×
2255
        }
2256
}
2257

2258
func (cont *AciController) endpointSliceAdded(obj interface{}) {
1✔
2259
        endpointslice, ok := obj.(*discovery.EndpointSlice)
1✔
2260
        if !ok {
1✔
2261
                cont.log.Error("error processing Endpointslice object: ", obj)
×
2262
                return
×
2263
        }
×
2264
        servicekey, valid := getServiceKey(endpointslice)
1✔
2265
        if !valid {
1✔
2266
                return
×
2267
        }
×
2268
        ips := cont.getEndpointSliceIps(endpointslice)
1✔
2269
        cont.indexMutex.Lock()
1✔
2270
        cont.updateIpIndex(cont.endpointsIpIndex, nil, ips, servicekey)
1✔
2271
        cont.queueIPNetPolUpdates(ips)
1✔
2272
        cont.indexMutex.Unlock()
1✔
2273

1✔
2274
        cont.queueEndpointSliceNetPolUpdates(endpointslice)
1✔
2275

1✔
2276
        cont.queueServiceUpdateByKey(servicekey)
1✔
2277
        cont.log.Info("EndPointSlice Object Added: ", servicekey)
1✔
2278
}
2279

2280
func (cont *AciController) endpointSliceDeleted(obj interface{}) {
1✔
2281
        endpointslice, isEndpointslice := obj.(*discovery.EndpointSlice)
1✔
2282
        if !isEndpointslice {
1✔
2283
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
×
2284
                if !ok {
×
2285
                        cont.log.Error("Received unexpected object: ", obj)
×
2286
                        return
×
2287
                }
×
2288
                endpointslice, ok = deletedState.Obj.(*discovery.EndpointSlice)
×
2289
                if !ok {
×
2290
                        cont.log.Error("DeletedFinalStateUnknown contained non-Endpointslice object: ", deletedState.Obj)
×
2291
                        return
×
2292
                }
×
2293
        }
2294
        servicekey, valid := getServiceKey(endpointslice)
1✔
2295
        if !valid {
1✔
2296
                return
×
2297
        }
×
2298
        ips := cont.getEndpointSliceIps(endpointslice)
1✔
2299
        cont.indexMutex.Lock()
1✔
2300
        cont.updateIpIndex(cont.endpointsIpIndex, ips, nil, servicekey)
1✔
2301
        cont.queueIPNetPolUpdates(ips)
1✔
2302
        cont.indexMutex.Unlock()
1✔
2303
        cont.queueEndpointSliceNetPolUpdates(endpointslice)
1✔
2304
        cont.queueServiceUpdateByKey(servicekey)
1✔
2305
}
2306

2307
// Checks if the given service is present in the user configured list of services
2308
// for pbr delay and if present, returns the servie specific delay if configured
2309
func (cont *AciController) svcInAddDelayList(name, ns string) (int, bool) {
×
2310
        for _, svc := range cont.config.ServiceGraphEndpointAddDelay.Services {
×
2311
                if svc.Name == name && svc.Namespace == ns {
×
2312
                        return svc.Delay, true
×
2313
                }
×
2314
        }
2315
        return 0, false
×
2316
}
2317

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

×
2322
        // if any endpoint is removed from endpontslice
×
2323
        if len(newendpointslice.Endpoints) < len(oldendpointslice.Endpoints) {
×
2324
                del = true
×
2325
        }
×
2326

2327
        if !del {
×
2328
                // if any one of the endpoint is in terminating state
×
2329
                for _, endpoint := range newendpointslice.Endpoints {
×
2330
                        if endpoint.Conditions.Terminating != nil && *endpoint.Conditions.Terminating {
×
2331
                                del = true
×
2332
                                break
×
2333
                        }
2334
                }
2335
        }
2336
        if !del {
×
2337
                // if any one of endpoint moved from ready state to not-ready state
×
2338
                for ix := range oldendpointslice.Endpoints {
×
2339
                        oldips := cont.getEndpointSliceEpIps(&oldendpointslice.Endpoints[ix])
×
2340
                        for newIx := range newendpointslice.Endpoints {
×
2341
                                newips := cont.getEndpointSliceEpIps(&newendpointslice.Endpoints[newIx])
×
2342
                                if reflect.DeepEqual(oldips, newips) {
×
2343
                                        if (oldendpointslice.Endpoints[ix].Conditions.Ready != nil && *oldendpointslice.Endpoints[ix].Conditions.Ready) &&
×
2344
                                                (newendpointslice.Endpoints[newIx].Conditions.Ready != nil && !*newendpointslice.Endpoints[newIx].Conditions.Ready) {
×
2345
                                                del = true
×
2346
                                        }
×
2347
                                        break
×
2348
                                }
2349
                        }
2350
                }
2351
        }
2352
        return del
×
2353
}
2354

2355
func (cont *AciController) doendpointSliceUpdatedDelay(oldendpointslice *discovery.EndpointSlice,
2356
        newendpointslice *discovery.EndpointSlice) {
×
2357
        svc, ns, valid := getServiceNameAndNs(newendpointslice)
×
2358
        if !valid {
×
2359
                return
×
2360
        }
×
2361
        svckey, valid := getServiceKey(newendpointslice)
×
2362
        if !valid {
×
2363
                return
×
2364
        }
×
2365
        delay := cont.config.ServiceGraphEndpointAddDelay.Delay
×
2366
        svcDelay, exists := cont.svcInAddDelayList(svc, ns)
×
2367
        if svcDelay > 0 {
×
2368
                delay = svcDelay
×
2369
        }
×
2370
        delayedsvc := exists && delay > 0
×
2371
        if delayedsvc {
×
2372
                cont.log.Debug("Delay of ", delay, " seconds is applicable for svc :", svc, " in ns: ", ns)
×
2373
                var delayedepslice DelayedEpSlice
×
2374
                delayedepslice.OldEpSlice = oldendpointslice
×
2375
                delayedepslice.ServiceKey = svckey
×
2376
                delayedepslice.NewEpSlice = newendpointslice
×
2377
                currentTime := time.Now()
×
2378
                delayedepslice.DelayedTime = currentTime.Add(time.Duration(delay) * time.Second)
×
2379
                cont.indexMutex.Lock()
×
2380
                cont.delayedEpSlices = append(cont.delayedEpSlices, &delayedepslice)
×
2381
                cont.indexMutex.Unlock()
×
2382
        } else {
×
2383
                cont.doendpointSliceUpdated(oldendpointslice, newendpointslice)
×
2384
        }
×
2385

2386
        if delayedsvc && cont.isDeleteEndpointSlice(oldendpointslice, newendpointslice) {
×
2387
                cont.log.Debug("Proceeding by ignoring delay as the update is due to delete of endpoint")
×
2388
                cont.doendpointSliceUpdated(oldendpointslice, newendpointslice)
×
2389
        }
×
2390
}
2391

2392
func (cont *AciController) endpointSliceUpdated(oldobj, newobj interface{}) {
1✔
2393
        oldendpointslice, ok := oldobj.(*discovery.EndpointSlice)
1✔
2394
        if !ok {
1✔
2395
                cont.log.Error("error processing Endpointslice object: ", oldobj)
×
2396
                return
×
2397
        }
×
2398
        newendpointslice, ok := newobj.(*discovery.EndpointSlice)
1✔
2399
        if !ok {
1✔
2400
                cont.log.Error("error processing Endpointslice object: ", newobj)
×
2401
                return
×
2402
        }
×
2403
        if cont.config.ServiceGraphEndpointAddDelay.Delay > 0 {
1✔
2404
                cont.doendpointSliceUpdatedDelay(oldendpointslice, newendpointslice)
×
2405
        } else {
1✔
2406
                cont.doendpointSliceUpdated(oldendpointslice, newendpointslice)
1✔
2407
        }
1✔
2408
}
2409

2410
func (cont *AciController) doendpointSliceUpdated(oldendpointslice *discovery.EndpointSlice,
2411
        newendpointslice *discovery.EndpointSlice) {
1✔
2412
        servicekey, valid := getServiceKey(newendpointslice)
1✔
2413
        if !valid {
1✔
2414
                return
×
2415
        }
×
2416
        oldIps := cont.getEndpointSliceIps(oldendpointslice)
1✔
2417
        newIps := cont.getEndpointSliceIps(newendpointslice)
1✔
2418
        if !reflect.DeepEqual(oldIps, newIps) {
2✔
2419
                cont.indexMutex.Lock()
1✔
2420
                cont.queueIPNetPolUpdates(oldIps)
1✔
2421
                cont.updateIpIndex(cont.endpointsIpIndex, oldIps, newIps, servicekey)
1✔
2422
                cont.queueIPNetPolUpdates(newIps)
1✔
2423
                cont.indexMutex.Unlock()
1✔
2424
        }
1✔
2425

2426
        if !reflect.DeepEqual(oldendpointslice.Endpoints, newendpointslice.Endpoints) {
2✔
2427
                cont.queueEndpointSliceNetPolUpdates(oldendpointslice)
1✔
2428
                cont.queueEndpointSliceNetPolUpdates(newendpointslice)
1✔
2429
        }
1✔
2430
        cont.log.Debug("EndPointSlice Object Update: ", servicekey)
1✔
2431
        cont.queueServiceUpdateByKey(servicekey)
1✔
2432
}
2433

2434
func (cont *AciController) queueEndpointSliceNetPolUpdates(endpointslice *discovery.EndpointSlice) {
1✔
2435
        for _, endpoint := range endpointslice.Endpoints {
2✔
2436
                if endpoint.TargetRef == nil || endpoint.TargetRef.Kind != "Pod" ||
1✔
2437
                        endpoint.TargetRef.Namespace == "" || endpoint.TargetRef.Name == "" {
2✔
2438
                        continue
1✔
2439
                }
2440
                if endpoint.Conditions.Ready != nil && !*endpoint.Conditions.Ready {
1✔
2441
                        continue
×
2442
                }
2443
                podkey := endpoint.TargetRef.Namespace + "/" + endpoint.TargetRef.Name
1✔
2444
                npkeys := cont.netPolEgressPods.GetObjForPod(podkey)
1✔
2445
                ps := make(map[string]bool)
1✔
2446
                for _, npkey := range npkeys {
2✔
2447
                        cont.queueNetPolUpdateByKey(npkey)
1✔
2448
                }
1✔
2449
                // Process if the  any matching namedport wildcard policy is present
2450
                // ignore np already processed policies
2451
                cont.queueMatchingNamedNp(ps, podkey)
1✔
2452
        }
2453
}
2454

2455
func getServiceKey(endPointSlice *discovery.EndpointSlice) (string, bool) {
1✔
2456
        serviceName, ok := endPointSlice.Labels[discovery.LabelServiceName]
1✔
2457
        if !ok {
1✔
2458
                return "", false
×
2459
        }
×
2460
        return endPointSlice.ObjectMeta.Namespace + "/" + serviceName, true
1✔
2461
}
2462

2463
func getServiceNameAndNs(endPointSlice *discovery.EndpointSlice) (string, string, bool) {
×
2464
        serviceName, ok := endPointSlice.Labels[discovery.LabelServiceName]
×
2465
        if !ok {
×
2466
                return "", "", false
×
2467
        }
×
2468
        return serviceName, endPointSlice.ObjectMeta.Namespace, true
×
2469
}
2470

2471
// can be called with index lock
2472
func (sep *serviceEndpoint) UpdateServicesForNode(nodename string) {
1✔
2473
        cont := sep.cont
1✔
2474
        cache.ListAll(cont.endpointsIndexer, labels.Everything(),
1✔
2475
                func(endpointsobj interface{}) {
2✔
2476
                        endpoints := endpointsobj.(*v1.Endpoints)
1✔
2477
                        for _, subset := range endpoints.Subsets {
2✔
2478
                                for _, addr := range subset.Addresses {
2✔
2479
                                        if addr.NodeName != nil && *addr.NodeName == nodename {
2✔
2480
                                                servicekey, err :=
1✔
2481
                                                        cache.MetaNamespaceKeyFunc(endpointsobj.(*v1.Endpoints))
1✔
2482
                                                if err != nil {
1✔
2483
                                                        cont.log.Error("Could not create endpoints key: ", err)
×
2484
                                                        return
×
2485
                                                }
×
2486
                                                cont.queueServiceUpdateByKey(servicekey)
1✔
2487
                                                return
1✔
2488
                                        }
2489
                                }
2490
                        }
2491
                })
2492
}
2493

2494
func (seps *serviceEndpointSlice) UpdateServicesForNode(nodename string) {
1✔
2495
        // 1. List all the endpointslice and check for matching nodename
1✔
2496
        // 2. if it matches trigger the Service update and mark it visited
1✔
2497
        cont := seps.cont
1✔
2498
        visited := make(map[string]bool)
1✔
2499
        cache.ListAll(cont.endpointSliceIndexer, labels.Everything(),
1✔
2500
                func(endpointSliceobj interface{}) {
2✔
2501
                        endpointSlices := endpointSliceobj.(*discovery.EndpointSlice)
1✔
2502
                        for _, endpoint := range endpointSlices.Endpoints {
2✔
2503
                                if endpoint.NodeName != nil && *endpoint.NodeName == nodename {
2✔
2504
                                        servicekey, valid := getServiceKey(endpointSlices)
1✔
2505
                                        if !valid {
1✔
2506
                                                return
×
2507
                                        }
×
2508
                                        if _, ok := visited[servicekey]; !ok {
2✔
2509
                                                cont.queueServiceUpdateByKey(servicekey)
1✔
2510
                                                visited[servicekey] = true
1✔
2511
                                                return
1✔
2512
                                        }
1✔
2513
                                }
2514
                        }
2515
                })
2516
}
2517
func (cont *AciController) setNodeMap(nodeMap map[string]*metadata.ServiceEndpoint, nodeName string) {
1✔
2518
        nodeMeta, ok := cont.nodeServiceMetaCache[nodeName]
1✔
2519
        if !ok {
1✔
UNCOV
2520
                return
×
UNCOV
2521
        }
×
2522
        _, ok = cont.fabricPathForNode(nodeName)
1✔
2523
        if !ok {
2✔
2524
                return
1✔
2525
        }
1✔
2526
        nodeMap[nodeName] = &nodeMeta.serviceEp
1✔
2527
}
2528

2529
// 2 cases when epslices corresponding to given service is presnt in delayedEpSlices:
2530
//  1. endpoint not present in delayedEpSlices of the service
2531
//  2. endpoint present in delayedEpSlices of the service but in not ready state
2532
//
2533
// indexMutex lock must be acquired before calling the function
2534
func (cont *AciController) isDelayedEndpoint(endpoint *discovery.Endpoint, svckey string) bool {
×
2535
        delayed := false
×
2536
        endpointips := cont.getEndpointSliceEpIps(endpoint)
×
2537
        for _, delayedepslices := range cont.delayedEpSlices {
×
2538
                if delayedepslices.ServiceKey == svckey {
×
2539
                        var found bool
×
2540
                        epslice := delayedepslices.OldEpSlice
×
2541
                        for ix := range epslice.Endpoints {
×
2542
                                epips := cont.getEndpointSliceEpIps(&epslice.Endpoints[ix])
×
2543
                                if reflect.DeepEqual(endpointips, epips) {
×
2544
                                        // case 2
×
2545
                                        if epslice.Endpoints[ix].Conditions.Ready != nil && !*epslice.Endpoints[ix].Conditions.Ready {
×
2546
                                                delayed = true
×
2547
                                        }
×
2548
                                        found = true
×
2549
                                }
2550
                        }
2551
                        // case 1
2552
                        if !found {
×
2553
                                delayed = true
×
2554
                        }
×
2555
                }
2556
        }
2557
        return delayed
×
2558
}
2559

2560
// set nodemap only if endoint is ready and not in delayedEpSlices
2561
func (cont *AciController) setNodeMapDelay(nodeMap map[string]*metadata.ServiceEndpoint,
2562
        endpoint *discovery.Endpoint, service *v1.Service) {
×
2563
        svckey, err := cache.MetaNamespaceKeyFunc(service)
×
2564
        if err != nil {
×
2565
                cont.log.Error("Could not create service key: ", err)
×
2566
                return
×
2567
        }
×
2568
        if cont.config.NoWaitForServiceEpReadiness ||
×
2569
                (endpoint.Conditions.Ready != nil && *endpoint.Conditions.Ready) {
×
2570
                if endpoint.NodeName != nil && *endpoint.NodeName != "" {
×
2571
                        // donot setNodeMap for endpoint if:
×
2572
                        //   endpoint is newly added
×
2573
                        //   endpoint status changed from not ready to ready
×
2574
                        if !cont.isDelayedEndpoint(endpoint, svckey) {
×
2575
                                cont.setNodeMap(nodeMap, *endpoint.NodeName)
×
2576
                        }
×
2577
                }
2578
        }
2579
}
2580

2581
func (sep *serviceEndpoint) GetnodesMetadata(key string,
2582
        service *v1.Service, nodeMap map[string]*metadata.ServiceEndpoint) {
1✔
2583
        cont := sep.cont
1✔
2584
        endpointsobj, exists, err := cont.endpointsIndexer.GetByKey(key)
1✔
2585
        if err != nil {
1✔
2586
                cont.log.Error("Could not lookup endpoints for " +
×
2587
                        key + ": " + err.Error())
×
2588
        }
×
2589
        if exists && endpointsobj != nil {
2✔
2590
                endpoints := endpointsobj.(*v1.Endpoints)
1✔
2591
                for _, subset := range endpoints.Subsets {
2✔
2592
                        for _, addr := range subset.Addresses {
2✔
2593
                                if addr.NodeName == nil {
2✔
2594
                                        continue
1✔
2595
                                }
2596
                                cont.setNodeMap(nodeMap, *addr.NodeName)
1✔
2597
                        }
2598
                }
2599
        }
2600
        cont.log.Info("NodeMap: ", nodeMap)
1✔
2601
}
2602

2603
func (seps *serviceEndpointSlice) GetnodesMetadata(key string,
2604
        service *v1.Service, nodeMap map[string]*metadata.ServiceEndpoint) {
1✔
2605
        cont := seps.cont
1✔
2606
        // 1. Get all the Endpoint slices matching the label service-name
1✔
2607
        // 2. update the node map matching with endpoints nodes name
1✔
2608
        label := map[string]string{discovery.LabelServiceName: service.ObjectMeta.Name}
1✔
2609
        selector := labels.SelectorFromSet(label)
1✔
2610
        cache.ListAllByNamespace(cont.endpointSliceIndexer, service.ObjectMeta.Namespace, selector,
1✔
2611
                func(endpointSliceobj interface{}) {
2✔
2612
                        endpointSlices := endpointSliceobj.(*discovery.EndpointSlice)
1✔
2613
                        for ix := range endpointSlices.Endpoints {
2✔
2614
                                if cont.config.ServiceGraphEndpointAddDelay.Delay > 0 {
1✔
2615
                                        cont.setNodeMapDelay(nodeMap, &endpointSlices.Endpoints[ix], service)
×
2616
                                } else if cont.config.NoWaitForServiceEpReadiness ||
1✔
2617
                                        (endpointSlices.Endpoints[ix].Conditions.Ready != nil && *endpointSlices.Endpoints[ix].Conditions.Ready) {
2✔
2618
                                        if endpointSlices.Endpoints[ix].NodeName != nil && *endpointSlices.Endpoints[ix].NodeName != "" {
2✔
2619
                                                cont.setNodeMap(nodeMap, *endpointSlices.Endpoints[ix].NodeName)
1✔
2620
                                        }
1✔
2621
                                }
2622
                        }
2623
                })
2624
        cont.log.Debug("NodeMap: ", nodeMap)
1✔
2625
}
2626

2627
func (sep *serviceEndpoint) SetServiceApicObject(aobj apicapi.ApicObject, service *v1.Service) bool {
1✔
2628
        cont := sep.cont
1✔
2629
        key, err := cache.MetaNamespaceKeyFunc(service)
1✔
2630
        if err != nil {
1✔
2631
                serviceLogger(cont.log, service).
×
2632
                        Error("Could not create service key: ", err)
×
2633
                return false
×
2634
        }
×
2635
        endpointsobj, _, err := cont.endpointsIndexer.GetByKey(key)
1✔
2636
        if err != nil {
1✔
2637
                cont.log.Error("Could not lookup endpoints for " +
×
2638
                        key + ": " + err.Error())
×
2639
                return false
×
2640
        }
×
2641
        if endpointsobj != nil {
2✔
2642
                for _, subset := range endpointsobj.(*v1.Endpoints).Subsets {
2✔
2643
                        for _, addr := range subset.Addresses {
2✔
2644
                                if addr.TargetRef == nil || addr.TargetRef.Kind != "Pod" {
1✔
2645
                                        continue
×
2646
                                }
2647
                                aobj.AddChild(apicapi.NewVmmInjectedSvcEp(aobj.GetDn(),
1✔
2648
                                        addr.TargetRef.Name))
1✔
2649
                        }
2650
                }
2651
        }
2652
        return true
1✔
2653
}
2654

2655
func (seps *serviceEndpointSlice) SetServiceApicObject(aobj apicapi.ApicObject, service *v1.Service) bool {
1✔
2656
        cont := seps.cont
1✔
2657
        label := map[string]string{discovery.LabelServiceName: service.ObjectMeta.Name}
1✔
2658
        selector := labels.SelectorFromSet(label)
1✔
2659
        epcount := 0
1✔
2660
        childs := make(map[string]struct{})
1✔
2661
        var exists = struct{}{}
1✔
2662
        cache.ListAllByNamespace(cont.endpointSliceIndexer, service.ObjectMeta.Namespace, selector,
1✔
2663
                func(endpointSliceobj interface{}) {
2✔
2664
                        endpointSlices := endpointSliceobj.(*discovery.EndpointSlice)
1✔
2665
                        for _, endpoint := range endpointSlices.Endpoints {
2✔
2666
                                if endpoint.TargetRef == nil || endpoint.TargetRef.Kind != "Pod" {
1✔
2667
                                        continue
×
2668
                                }
2669
                                epcount++
1✔
2670
                                childs[endpoint.TargetRef.Name] = exists
1✔
2671
                                cont.log.Debug("EndPoint added: ", endpoint.TargetRef.Name)
1✔
2672
                        }
2673
                })
2674
        for child := range childs {
2✔
2675
                aobj.AddChild(apicapi.NewVmmInjectedSvcEp(aobj.GetDn(), child))
1✔
2676
        }
1✔
2677
        return epcount != 0
1✔
2678
}
2679

2680
func getProtocolStr(proto v1.Protocol) string {
1✔
2681
        var protostring string
1✔
2682
        switch proto {
1✔
2683
        case v1.ProtocolUDP:
1✔
2684
                protostring = "udp"
1✔
2685
        case v1.ProtocolTCP:
1✔
2686
                protostring = "tcp"
1✔
2687
        case v1.ProtocolSCTP:
×
2688
                protostring = "sctp"
×
2689
        default:
×
2690
                protostring = "tcp"
×
2691
        }
2692
        return protostring
1✔
2693
}
2694

2695
func (cont *AciController) removeIpFromIngressIPList(ingressIps *[]net.IP, ip net.IP) {
×
2696
        cont.returnServiceIps([]net.IP{ip})
×
2697
        index := -1
×
2698
        for i, v := range *ingressIps {
×
2699
                if v.Equal(ip) {
×
2700
                        index = i
×
2701
                        break
×
2702
                }
2703
        }
2704
        if index == -1 {
×
2705
                return
×
2706
        }
×
2707
        *ingressIps = append((*ingressIps)[:index], (*ingressIps)[index+1:]...)
×
2708
}
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

© 2025 Coveralls, Inc