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

noironetworks / aci-containers / 8744

29 Feb 2024 06:17AM UTC coverage: 66.427% (-0.01%) from 66.441%
8744

push

travis-pro

web-flow
Merge pull request #1278 from noironetworks/snat-lock-fixes

Added missing lock in SNAT path

4 of 4 new or added lines in 1 file covered. (100.0%)

9 existing lines in 3 files now uncovered.

12740 of 19179 relevant lines covered (66.43%)

0.75 hits per line

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

77.53
/pkg/controller/network_policy.go
1
// Copyright 2017 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
// Handlers for network policy updates.  Generate ACI security groups
16
// based on Kubernetes network policies.
17

18
package controller
19

20
import (
21
        "bytes"
22
        "fmt"
23
        "net"
24
        "reflect"
25
        "sort"
26
        "strconv"
27
        "strings"
28

29
        "github.com/sirupsen/logrus"
30
        "github.com/yl2chen/cidranger"
31

32
        v1 "k8s.io/api/core/v1"
33
        v1net "k8s.io/api/networking/v1"
34
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
35
        "k8s.io/apimachinery/pkg/fields"
36
        "k8s.io/apimachinery/pkg/labels"
37
        "k8s.io/apimachinery/pkg/util/intstr"
38
        "k8s.io/client-go/kubernetes"
39
        "k8s.io/client-go/tools/cache"
40
        k8util "k8s.io/kubectl/pkg/util"
41

42
        "github.com/noironetworks/aci-containers/pkg/apicapi"
43
        "github.com/noironetworks/aci-containers/pkg/index"
44
        "github.com/noironetworks/aci-containers/pkg/ipam"
45
        "github.com/noironetworks/aci-containers/pkg/util"
46
        discovery "k8s.io/api/discovery/v1"
47
)
48

49
func (cont *AciController) initNetworkPolicyInformerFromClient(
50
        kubeClient kubernetes.Interface) {
×
51
        cont.initNetworkPolicyInformerBase(
×
52
                cache.NewListWatchFromClient(
×
53
                        kubeClient.NetworkingV1().RESTClient(), "networkpolicies",
×
54
                        metav1.NamespaceAll, fields.Everything()))
×
55
}
×
56

57
func (cont *AciController) initNetworkPolicyInformerBase(listWatch *cache.ListWatch) {
1✔
58
        cont.networkPolicyIndexer, cont.networkPolicyInformer =
1✔
59
                cache.NewIndexerInformer(
1✔
60
                        listWatch, &v1net.NetworkPolicy{}, 0,
1✔
61
                        cache.ResourceEventHandlerFuncs{
1✔
62
                                AddFunc: func(obj interface{}) {
2✔
63
                                        cont.networkPolicyAdded(obj)
1✔
64
                                },
1✔
65
                                UpdateFunc: func(oldobj interface{}, newobj interface{}) {
×
66
                                        cont.networkPolicyChanged(oldobj, newobj)
×
67
                                },
×
68
                                DeleteFunc: func(obj interface{}) {
1✔
69
                                        cont.networkPolicyDeleted(obj)
1✔
70
                                },
1✔
71
                        },
72
                        cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
73
                )
74
}
75

76
func (cont *AciController) peerPodSelector(np *v1net.NetworkPolicy,
77
        peers []v1net.NetworkPolicyPeer) []index.PodSelector {
1✔
78
        var ret []index.PodSelector
1✔
79
        for _, peer := range peers {
2✔
80
                podselector, err :=
1✔
81
                        metav1.LabelSelectorAsSelector(peer.PodSelector)
1✔
82
                if err != nil {
1✔
83
                        networkPolicyLogger(cont.log, np).
×
84
                                Error("Could not create selector: ", err)
×
85
                        continue
×
86
                }
87
                nsselector, err := metav1.
1✔
88
                        LabelSelectorAsSelector(peer.NamespaceSelector)
1✔
89
                if err != nil {
1✔
90
                        networkPolicyLogger(cont.log, np).
×
91
                                Error("Could not create selector: ", err)
×
92
                        continue
×
93
                }
94

95
                switch {
1✔
96
                case peer.PodSelector != nil && peer.NamespaceSelector != nil:
1✔
97
                        ret = append(ret, index.PodSelector{
1✔
98
                                NsSelector:  nsselector,
1✔
99
                                PodSelector: podselector,
1✔
100
                        })
1✔
101
                case peer.PodSelector != nil:
1✔
102
                        ret = append(ret, index.PodSelector{
1✔
103
                                Namespace:   &np.ObjectMeta.Namespace,
1✔
104
                                PodSelector: podselector,
1✔
105
                        })
1✔
106
                case peer.NamespaceSelector != nil:
1✔
107
                        ret = append(ret, index.PodSelector{
1✔
108
                                NsSelector:  nsselector,
1✔
109
                                PodSelector: labels.Everything(),
1✔
110
                        })
1✔
111
                }
112
        }
113
        return ret
1✔
114
}
115

116
func (cont *AciController) egressPodSelector(np *v1net.NetworkPolicy) []index.PodSelector {
1✔
117
        var ret []index.PodSelector
1✔
118

1✔
119
        for _, egress := range np.Spec.Egress {
2✔
120
                ret = append(ret, cont.peerPodSelector(np, egress.To)...)
1✔
121
        }
1✔
122

123
        return ret
1✔
124
}
125

126
func (cont *AciController) ingressPodSelector(np *v1net.NetworkPolicy) []index.PodSelector {
1✔
127
        var ret []index.PodSelector
1✔
128

1✔
129
        for _, ingress := range np.Spec.Ingress {
2✔
130
                ret = append(ret, cont.peerPodSelector(np, ingress.From)...)
1✔
131
        }
1✔
132

133
        return ret
1✔
134
}
135

136
func (cont *AciController) initNetPolPodIndex() {
1✔
137
        cont.netPolPods = index.NewPodSelectorIndex(
1✔
138
                cont.log,
1✔
139
                cont.podIndexer, cont.namespaceIndexer, cont.networkPolicyIndexer,
1✔
140
                cache.MetaNamespaceKeyFunc,
1✔
141
                func(obj interface{}) []index.PodSelector {
2✔
142
                        np := obj.(*v1net.NetworkPolicy)
1✔
143
                        return index.PodSelectorFromNsAndSelector(np.ObjectMeta.Namespace,
1✔
144
                                &np.Spec.PodSelector)
1✔
145
                },
1✔
146
        )
147
        cont.netPolPods.SetPodUpdateCallback(func(podkey string) {
2✔
148
                podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
149
                if exists && err == nil {
2✔
150
                        cont.queuePodUpdate(podobj.(*v1.Pod))
1✔
151
                }
1✔
152
        })
153

154
        cont.netPolIngressPods = index.NewPodSelectorIndex(
1✔
155
                cont.log,
1✔
156
                cont.podIndexer, cont.namespaceIndexer, cont.networkPolicyIndexer,
1✔
157
                cache.MetaNamespaceKeyFunc,
1✔
158
                func(obj interface{}) []index.PodSelector {
2✔
159
                        return cont.ingressPodSelector(obj.(*v1net.NetworkPolicy))
1✔
160
                },
1✔
161
        )
162
        cont.netPolEgressPods = index.NewPodSelectorIndex(
1✔
163
                cont.log,
1✔
164
                cont.podIndexer, cont.namespaceIndexer, cont.networkPolicyIndexer,
1✔
165
                cache.MetaNamespaceKeyFunc,
1✔
166
                func(obj interface{}) []index.PodSelector {
2✔
167
                        return cont.egressPodSelector(obj.(*v1net.NetworkPolicy))
1✔
168
                },
1✔
169
        )
170
        npupdate := func(npkey string) {
2✔
171
                npobj, exists, err := cont.networkPolicyIndexer.GetByKey(npkey)
1✔
172
                if exists && err == nil {
2✔
173
                        cont.queueNetPolUpdate(npobj.(*v1net.NetworkPolicy))
1✔
174
                }
1✔
175
        }
176
        nphash := func(pod *v1.Pod) string {
2✔
177
                return pod.Status.PodIP
1✔
178
        }
1✔
179
        cont.netPolIngressPods.SetObjUpdateCallback(npupdate)
1✔
180
        cont.netPolIngressPods.SetPodHashFunc(nphash)
1✔
181
        cont.netPolEgressPods.SetObjUpdateCallback(npupdate)
1✔
182
        cont.netPolEgressPods.SetPodHashFunc(nphash)
1✔
183
}
184

185
func (cont *AciController) staticNetPolObjs() apicapi.ApicSlice {
1✔
186
        hppIngress :=
1✔
187
                apicapi.NewHostprotPol(cont.config.AciPolicyTenant,
1✔
188
                        cont.aciNameForKey("np", "static-ingress"))
1✔
189
        {
2✔
190
                ingressSubj := apicapi.NewHostprotSubj(hppIngress.GetDn(), "ingress")
1✔
191
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
192
                        outbound := apicapi.NewHostprotRule(ingressSubj.GetDn(),
1✔
193
                                "allow-all-reflexive-v6")
1✔
194
                        outbound.SetAttr("direction", "ingress")
1✔
195
                        outbound.SetAttr("ethertype", "ipv6")
1✔
196
                        ingressSubj.AddChild(outbound)
1✔
197
                }
1✔
198
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
199
                        outbound := apicapi.NewHostprotRule(ingressSubj.GetDn(),
1✔
200
                                "allow-all-reflexive")
1✔
201
                        outbound.SetAttr("direction", "ingress")
1✔
202
                        outbound.SetAttr("ethertype", "ipv4")
1✔
203
                        ingressSubj.AddChild(outbound)
1✔
204
                }
1✔
205
                hppIngress.AddChild(ingressSubj)
1✔
206
        }
207

208
        hppEgress :=
1✔
209
                apicapi.NewHostprotPol(cont.config.AciPolicyTenant,
1✔
210
                        cont.aciNameForKey("np", "static-egress"))
1✔
211
        {
2✔
212
                egressSubj := apicapi.NewHostprotSubj(hppEgress.GetDn(), "egress")
1✔
213
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
214
                        outbound := apicapi.NewHostprotRule(egressSubj.GetDn(),
1✔
215
                                "allow-all-reflexive-v6")
1✔
216
                        outbound.SetAttr("direction", "egress")
1✔
217
                        outbound.SetAttr("ethertype", "ipv6")
1✔
218
                        egressSubj.AddChild(outbound)
1✔
219
                }
1✔
220
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
221
                        outbound := apicapi.NewHostprotRule(egressSubj.GetDn(),
1✔
222
                                "allow-all-reflexive")
1✔
223
                        outbound.SetAttr("direction", "egress")
1✔
224
                        outbound.SetAttr("ethertype", "ipv4")
1✔
225
                        egressSubj.AddChild(outbound)
1✔
226
                }
1✔
227
                hppEgress.AddChild(egressSubj)
1✔
228
        }
229

230
        hppDiscovery :=
1✔
231
                apicapi.NewHostprotPol(cont.config.AciPolicyTenant,
1✔
232
                        cont.aciNameForKey("np", "static-discovery"))
1✔
233
        {
2✔
234
                discSubj := apicapi.NewHostprotSubj(hppDiscovery.GetDn(), "discovery")
1✔
235
                discDn := discSubj.GetDn()
1✔
236
                {
2✔
237
                        arpin := apicapi.NewHostprotRule(discDn, "arp-ingress")
1✔
238
                        arpin.SetAttr("direction", "ingress")
1✔
239
                        arpin.SetAttr("ethertype", "arp")
1✔
240
                        arpin.SetAttr("connTrack", "normal")
1✔
241
                        discSubj.AddChild(arpin)
1✔
242
                }
1✔
243
                {
1✔
244
                        arpout := apicapi.NewHostprotRule(discDn, "arp-egress")
1✔
245
                        arpout.SetAttr("direction", "egress")
1✔
246
                        arpout.SetAttr("ethertype", "arp")
1✔
247
                        arpout.SetAttr("connTrack", "normal")
1✔
248
                        discSubj.AddChild(arpout)
1✔
249
                }
1✔
250
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
251
                        icmpin := apicapi.NewHostprotRule(discDn, "icmp-ingress")
1✔
252
                        icmpin.SetAttr("direction", "ingress")
1✔
253
                        icmpin.SetAttr("ethertype", "ipv4")
1✔
254
                        icmpin.SetAttr("protocol", "icmp")
1✔
255
                        icmpin.SetAttr("connTrack", "normal")
1✔
256
                        discSubj.AddChild(icmpin)
1✔
257
                }
1✔
258

259
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
260
                        icmpin := apicapi.NewHostprotRule(discDn, "icmpv6-ingress")
1✔
261
                        icmpin.SetAttr("direction", "ingress")
1✔
262
                        icmpin.SetAttr("ethertype", "ipv6")
1✔
263
                        icmpin.SetAttr("protocol", "icmpv6")
1✔
264
                        icmpin.SetAttr("connTrack", "normal")
1✔
265
                        discSubj.AddChild(icmpin)
1✔
266
                }
1✔
267
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
268
                        icmpout := apicapi.NewHostprotRule(discDn, "icmp-egress")
1✔
269
                        icmpout.SetAttr("direction", "egress")
1✔
270
                        icmpout.SetAttr("ethertype", "ipv4")
1✔
271
                        icmpout.SetAttr("protocol", "icmp")
1✔
272
                        icmpout.SetAttr("connTrack", "normal")
1✔
273
                        discSubj.AddChild(icmpout)
1✔
274
                }
1✔
275

276
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
277
                        icmpout := apicapi.NewHostprotRule(discDn, "icmpv6-egress")
1✔
278
                        icmpout.SetAttr("direction", "egress")
1✔
279
                        icmpout.SetAttr("ethertype", "ipv6")
1✔
280
                        icmpout.SetAttr("protocol", "icmpv6")
1✔
281
                        icmpout.SetAttr("connTrack", "normal")
1✔
282
                        discSubj.AddChild(icmpout)
1✔
283
                }
1✔
284

285
                hppDiscovery.AddChild(discSubj)
1✔
286
        }
287

288
        return apicapi.ApicSlice{hppIngress, hppEgress, hppDiscovery}
1✔
289
}
290

291
func (cont *AciController) initStaticNetPolObjs() {
1✔
292
        cont.apicConn.WriteApicObjects(cont.config.AciPrefix+"_np_static",
1✔
293
                cont.staticNetPolObjs())
1✔
294
}
1✔
295

296
func networkPolicyLogger(log *logrus.Logger,
297
        np *v1net.NetworkPolicy) *logrus.Entry {
1✔
298
        return log.WithFields(logrus.Fields{
1✔
299
                "namespace": np.ObjectMeta.Namespace,
1✔
300
                "name":      np.ObjectMeta.Name,
1✔
301
        })
1✔
302
}
1✔
303

304
func (cont *AciController) queueNetPolUpdateByKey(key string) {
1✔
305
        cont.netPolQueue.Add(key)
1✔
306
}
1✔
307

308
func (cont *AciController) queueNetPolUpdate(netpol *v1net.NetworkPolicy) {
1✔
309
        key, err := cache.MetaNamespaceKeyFunc(netpol)
1✔
310
        if err != nil {
1✔
311
                networkPolicyLogger(cont.log, netpol).
×
312
                        Error("Could not create network policy key: ", err)
×
313
                return
×
314
        }
×
315
        cont.netPolQueue.Add(key)
1✔
316
}
317

318
func (cont *AciController) peerMatchesPod(npNs string,
319
        peer *v1net.NetworkPolicyPeer, pod *v1.Pod, podNs *v1.Namespace) bool {
1✔
320
        if peer.PodSelector != nil && npNs == pod.ObjectMeta.Namespace {
2✔
321
                selector, err :=
1✔
322
                        metav1.LabelSelectorAsSelector(peer.PodSelector)
1✔
323
                if err != nil {
1✔
324
                        cont.log.Error("Could not parse pod selector: ", err)
×
325
                } else {
1✔
326
                        return selector.Matches(labels.Set(pod.ObjectMeta.Labels))
1✔
327
                }
1✔
328
        }
329
        if peer.NamespaceSelector != nil {
2✔
330
                selector, err :=
1✔
331
                        metav1.LabelSelectorAsSelector(peer.NamespaceSelector)
1✔
332
                if err != nil {
1✔
333
                        cont.log.Error("Could not parse namespace selector: ", err)
×
334
                } else {
1✔
335
                        return selector.Matches(labels.Set(podNs.ObjectMeta.Labels))
1✔
336
                }
1✔
337
        }
338
        return false
×
339
}
340

341
func ipsForPod(pod *v1.Pod) []string {
1✔
342
        var ips []string
1✔
343
        podIPsField := reflect.ValueOf(pod.Status).FieldByName("PodIPs")
1✔
344
        if podIPsField.IsValid() {
2✔
345
                if len(pod.Status.PodIPs) > 0 {
1✔
346
                        for _, ip := range pod.Status.PodIPs {
×
347
                                ips = append(ips, ip.IP)
×
348
                        }
×
349
                        return ips
×
350
                }
351
        }
352
        if pod.Status.PodIP != "" {
2✔
353
                return []string{pod.Status.PodIP}
1✔
354
        }
1✔
355
        return nil
1✔
356
}
357

358
func ipBlockToSubnets(ipblock *v1net.IPBlock) ([]string, error) {
1✔
359
        _, nw, err := net.ParseCIDR(ipblock.CIDR)
1✔
360
        if err != nil {
1✔
361
                return nil, err
×
362
        }
×
363
        ips := ipam.New()
1✔
364
        ips.AddSubnet(nw)
1✔
365
        for _, except := range ipblock.Except {
2✔
366
                _, nw, err = net.ParseCIDR(except)
1✔
367
                if err != nil {
1✔
368
                        return nil, err
×
369
                }
×
370
                ips.RemoveSubnet(nw)
1✔
371
        }
372
        var subnets []string
1✔
373
        for _, r := range ips.FreeList {
2✔
374
                ipnets := ipam.Range2Cidr(r.Start, r.End)
1✔
375
                for _, n := range ipnets {
2✔
376
                        subnets = append(subnets, n.String())
1✔
377
                }
1✔
378
        }
379
        return subnets, nil
1✔
380
}
381

382
func parseCIDR(sub string) *net.IPNet {
1✔
383
        _, netw, err := net.ParseCIDR(sub)
1✔
384
        if err == nil {
2✔
385
                return netw
1✔
386
        }
1✔
387
        ip := net.ParseIP(sub)
1✔
388
        if ip == nil {
1✔
389
                return nil
×
390
        }
×
391
        var mask net.IPMask
1✔
392
        if ip.To4() != nil {
2✔
393
                mask = net.CIDRMask(32, 32)
1✔
394
        } else if ip.To16() != nil {
3✔
395
                mask = net.CIDRMask(128, 128)
1✔
396
        } else {
1✔
397
                return nil
×
398
        }
×
399
        return &net.IPNet{
1✔
400
                IP:   ip,
1✔
401
                Mask: mask,
1✔
402
        }
1✔
403
}
404

405
func netEqual(a, b net.IPNet) bool {
1✔
406
        return a.IP.Equal(b.IP) && bytes.Equal(a.Mask, b.Mask)
1✔
407
}
1✔
408

409
func (cont *AciController) updateIpIndexEntry(index cidranger.Ranger,
410
        subnetStr string, key string, add bool) bool {
1✔
411
        cidr := parseCIDR(subnetStr)
1✔
412
        if cidr == nil {
1✔
413
                cont.log.WithFields(logrus.Fields{
×
414
                        "subnet": subnetStr,
×
415
                        "netpol": key,
×
416
                }).Warning("Invalid subnet or IP")
×
417
                return false
×
418
        }
×
419

420
        entries, err := index.CoveredNetworks(*cidr)
1✔
421
        if err != nil {
1✔
422
                cont.log.Error("Corrupted subnet index: ", err)
×
423
                return false
×
424
        }
×
425
        if add {
2✔
426
                for _, entryObj := range entries {
2✔
427
                        if netEqual(entryObj.Network(), *cidr) {
2✔
428
                                entry := entryObj.(*ipIndexEntry)
1✔
429
                                existing := entry.keys[key]
1✔
430
                                entry.keys[key] = true
1✔
431
                                return !existing
1✔
432
                        }
1✔
433
                }
434

435
                entry := &ipIndexEntry{
1✔
436
                        ipNet: *cidr,
1✔
437
                        keys: map[string]bool{
1✔
438
                                key: true,
1✔
439
                        },
1✔
440
                }
1✔
441
                index.Insert(entry)
1✔
442
                return true
1✔
443
        } else {
1✔
444
                var existing bool
1✔
445
                for _, entryObj := range entries {
2✔
446
                        entry := entryObj.(*ipIndexEntry)
1✔
447
                        if entry.keys[key] {
2✔
448
                                existing = true
1✔
449
                                delete(entry.keys, key)
1✔
450
                        }
1✔
451
                        if len(entry.keys) == 0 {
2✔
452
                                index.Remove(entry.Network())
1✔
453
                        }
1✔
454
                }
455
                return existing
1✔
456
        }
457
}
458

459
func (cont *AciController) updateIpIndex(index cidranger.Ranger,
460
        oldSubnets map[string]bool, newSubnets map[string]bool, key string) {
1✔
461
        for subStr := range oldSubnets {
2✔
462
                if newSubnets[subStr] {
2✔
463
                        continue
1✔
464
                }
465
                cont.updateIpIndexEntry(index, subStr, key, false)
1✔
466
        }
467
        for subStr := range newSubnets {
2✔
468
                if oldSubnets[subStr] {
2✔
469
                        continue
1✔
470
                }
471
                cont.updateIpIndexEntry(index, subStr, key, true)
1✔
472
        }
473
}
474

475
func (cont *AciController) updateTargetPortIndex(service bool, key string,
476
        oldPorts map[string]targetPort, newPorts map[string]targetPort) {
1✔
477
        for portkey := range oldPorts {
2✔
478
                if _, ok := newPorts[portkey]; ok {
1✔
479
                        continue
×
480
                }
481

482
                entry, ok := cont.targetPortIndex[portkey]
1✔
483
                if !ok {
1✔
484
                        continue
×
485
                }
486

487
                if service {
1✔
488
                        delete(entry.serviceKeys, key)
×
489
                } else {
1✔
490
                        delete(entry.networkPolicyKeys, key)
1✔
491
                }
1✔
492
                if len(entry.serviceKeys) == 0 && len(entry.networkPolicyKeys) == 0 {
2✔
493
                        delete(cont.targetPortIndex, portkey)
1✔
494
                }
1✔
495
        }
496
        for portkey, port := range newPorts {
2✔
497
                if _, ok := oldPorts[portkey]; ok {
1✔
498
                        continue
×
499
                }
500
                entry := cont.targetPortIndex[portkey]
1✔
501
                if entry == nil {
2✔
502
                        entry = &portIndexEntry{
1✔
503
                                port:              port,
1✔
504
                                serviceKeys:       make(map[string]bool),
1✔
505
                                networkPolicyKeys: make(map[string]bool),
1✔
506
                        }
1✔
507
                        cont.targetPortIndex[portkey] = entry
1✔
508
                } else {
2✔
509
                        entry.port.ports = port.ports
1✔
510
                }
1✔
511

512
                if service {
2✔
513
                        entry.serviceKeys[key] = true
1✔
514
                } else {
2✔
515
                        entry.networkPolicyKeys[key] = true
1✔
516
                }
1✔
517
        }
518
}
519

520
func (cont *AciController) getPortNumsFromPortName(podKeys []string, portName string) []int {
1✔
521
        var ports []int
1✔
522
        portmap := make(map[int]bool)
1✔
523
        for _, podkey := range podKeys {
2✔
524
                podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
525
                if exists && err == nil {
2✔
526
                        pod := podobj.(*v1.Pod)
1✔
527
                        port, err := k8util.LookupContainerPortNumberByName(*pod, portName)
1✔
528
                        if err != nil {
1✔
529
                                continue
×
530
                        }
531
                        if _, ok := portmap[int(port)]; !ok {
2✔
532
                                ports = append(ports, int(port))
1✔
533
                                portmap[int(port)] = true
1✔
534
                        }
1✔
535
                }
536
        }
537
        if len(ports) == 0 {
2✔
538
                cont.log.Infof("No matching portnumbers for portname %s: ", portName)
1✔
539
        }
1✔
540
        cont.log.Debug("PortName: ", portName, "Mapping port numbers: ", ports)
1✔
541
        return ports
1✔
542
}
543

544
// get a map of target ports for egress rules that have no "To" clause
545
func (cont *AciController) getNetPolTargetPorts(np *v1net.NetworkPolicy) map[string]targetPort {
1✔
546
        ports := make(map[string]targetPort)
1✔
547
        for _, egress := range np.Spec.Egress {
2✔
548
                if len(egress.To) != 0 && !isNamedPortPresenInNp(np) {
2✔
549
                        continue
1✔
550
                }
551
                for _, port := range egress.Ports {
2✔
552
                        if port.Port == nil {
1✔
553
                                continue
×
554
                        }
555
                        proto := v1.ProtocolTCP
1✔
556
                        if port.Protocol != nil {
2✔
557
                                proto = *port.Protocol
1✔
558
                        }
1✔
559
                        npKey, _ := cache.MetaNamespaceKeyFunc(np)
1✔
560
                        var key string
1✔
561
                        var portnums []int
1✔
562
                        if port.Port.Type == intstr.Int {
2✔
563
                                key = portProto(&proto) + "-num-" + port.Port.String()
1✔
564
                                portnums = append(portnums, port.Port.IntValue())
1✔
565
                        } else {
2✔
566
                                if len(egress.To) != 0 {
2✔
567
                                        // TODO optimize this code instead going through all matching pods every time
1✔
568
                                        podKeys := cont.netPolEgressPods.GetPodForObj(npKey)
1✔
569
                                        portnums = cont.getPortNumsFromPortName(podKeys, port.Port.String())
1✔
570
                                } else {
2✔
571
                                        ctrNmpEntry, ok := cont.ctrPortNameCache[port.Port.String()]
1✔
572
                                        if ok {
2✔
573
                                                for key := range ctrNmpEntry.ctrNmpToPods {
2✔
574
                                                        val := strings.Split(key, "-")
1✔
575
                                                        if len(val) != 2 {
1✔
576
                                                                continue
×
577
                                                        }
578
                                                        if val[0] == portProto(&proto) {
2✔
579
                                                                port, _ := strconv.Atoi(val[1])
1✔
580
                                                                portnums = append(portnums, port)
1✔
581
                                                        }
1✔
582
                                                }
583
                                        }
584
                                }
585
                                if len(portnums) == 0 {
2✔
586
                                        continue
1✔
587
                                }
588
                                key = portProto(&proto) + "-name-" + port.Port.String()
1✔
589
                        }
590
                        ports[key] = targetPort{
1✔
591
                                proto: proto,
1✔
592
                                ports: portnums,
1✔
593
                        }
1✔
594
                }
595
        }
596
        return ports
1✔
597
}
598

599
func (cont *AciController) getPeerRemoteSubnets(peers []v1net.NetworkPolicyPeer,
600
        namespace string, peerPods []*v1.Pod, peerNs map[string]*v1.Namespace,
601
        logger *logrus.Entry) ([]string, map[string]bool) {
1✔
602
        var remoteSubnets []string
1✔
603
        subnetMap := make(map[string]bool)
1✔
604
        if len(peers) > 0 {
2✔
605
                // only applies to matching pods
1✔
606
                for _, pod := range peerPods {
2✔
607
                        for peerIx := range peers {
2✔
608
                                if ns, ok := peerNs[pod.ObjectMeta.Namespace]; ok &&
1✔
609
                                        cont.peerMatchesPod(namespace,
1✔
610
                                                &peers[peerIx], pod, ns) {
2✔
611
                                        podIps := ipsForPod(pod)
1✔
612
                                        for _, ip := range podIps {
2✔
613
                                                if _, exists := subnetMap[ip]; !exists {
2✔
614
                                                        subnetMap[ip] = true
1✔
615
                                                        remoteSubnets = append(remoteSubnets, ip)
1✔
616
                                                }
1✔
617
                                        }
618
                                }
619
                        }
620
                }
621
                for _, peer := range peers {
2✔
622
                        if peer.IPBlock == nil {
2✔
623
                                continue
1✔
624
                        }
625
                        subs, err := ipBlockToSubnets(peer.IPBlock)
1✔
626
                        if err != nil {
1✔
627
                                logger.Warning("Invalid IPBlock in network policy rule: ", err)
×
628
                        } else {
1✔
629
                                for _, subnet := range subs {
2✔
630
                                        subnetMap[subnet] = true
1✔
631
                                }
1✔
632
                                remoteSubnets = append(remoteSubnets, subs...)
1✔
633
                        }
634
                }
635
        }
636
        sort.Strings(remoteSubnets)
1✔
637
        return remoteSubnets, subnetMap
1✔
638
}
639

640
func (cont *AciController) ipInPodSubnet(ip net.IP) bool {
×
641
        for _, podsubnet := range cont.config.PodSubnet {
×
642
                _, subnet, err := net.ParseCIDR(podsubnet)
×
643
                if err == nil && subnet != nil {
×
644
                        if subnet.Contains(ip) {
×
645
                                return true
×
646
                        }
×
647
                }
648
        }
649
        return false
×
650
}
651

652
func (cont *AciController) buildNetPolSubjRule(subj apicapi.ApicObject, ruleName,
653
        direction, ethertype, proto, port string, remoteSubnets []string,
654
        addPodSubnetAsRemIp bool) {
1✔
655
        ruleNameWithEtherType := fmt.Sprintf("%s-%s", ruleName, ethertype)
1✔
656
        rule := apicapi.NewHostprotRule(subj.GetDn(), ruleNameWithEtherType)
1✔
657
        rule.SetAttr("direction", direction)
1✔
658
        rule.SetAttr("ethertype", ethertype)
1✔
659
        if proto != "" {
2✔
660
                rule.SetAttr("protocol", proto)
1✔
661
        }
1✔
662

663
        if addPodSubnetAsRemIp {
1✔
664
                for _, podsubnet := range cont.config.PodSubnet {
×
665
                        _, subnet, err := net.ParseCIDR(podsubnet)
×
666
                        if err == nil && subnet != nil {
×
667
                                if (ethertype == "ipv4" && subnet.IP.To4() != nil) || (ethertype == "ipv6" && subnet.IP.To4() == nil) {
×
668
                                        rule.AddChild(apicapi.NewHostprotRemoteIp(rule.GetDn(), podsubnet))
×
669
                                }
×
670
                        }
671
                }
672
        }
673
        for _, subnetStr := range remoteSubnets {
2✔
674
                _, subnet, err := net.ParseCIDR(subnetStr)
1✔
675
                if err == nil && subnet != nil {
2✔
676
                        // subnetStr is a valid CIDR notation, check its IP version and add the subnet to the rule
1✔
677
                        if (ethertype == "ipv4" && subnet.IP.To4() != nil) || (ethertype == "ipv6" && subnet.IP.To4() == nil) {
2✔
678
                                rule.AddChild(apicapi.NewHostprotRemoteIp(rule.GetDn(), subnetStr))
1✔
679
                        }
1✔
680
                } else if ip := net.ParseIP(subnetStr); ip != nil {
2✔
681
                        if addPodSubnetAsRemIp && cont.ipInPodSubnet(ip) {
1✔
682
                                continue
×
683
                        }
684
                        if ethertype == "ipv6" && (ip.To16() != nil && ip.To4() == nil) || ethertype == "ipv4" && ip.To4() != nil {
2✔
685
                                rule.AddChild(apicapi.NewHostprotRemoteIp(rule.GetDn(), subnetStr))
1✔
686
                        }
1✔
687
                }
688
        }
689
        if port != "" {
2✔
690
                rule.SetAttr("toPort", port)
1✔
691
        }
1✔
692

693
        subj.AddChild(rule)
1✔
694
}
695

696
func (cont *AciController) buildNetPolSubjRules(ruleName string,
697
        subj apicapi.ApicObject, direction string, peers []v1net.NetworkPolicyPeer,
698
        remoteSubnets []string, ports []v1net.NetworkPolicyPort,
699
        logger *logrus.Entry, npKey string, np *v1net.NetworkPolicy,
700
        addPodSubnetAsRemIp bool) {
1✔
701
        if len(peers) > 0 && len(remoteSubnets) == 0 {
2✔
702
                // nonempty From matches no pods or IPBlocks; don't
1✔
703
                // create the rule
1✔
704
                return
1✔
705
        }
1✔
706
        if len(ports) == 0 {
2✔
707
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
708
                        cont.buildNetPolSubjRule(subj, ruleName, direction,
1✔
709
                                "ipv4", "", "", remoteSubnets, addPodSubnetAsRemIp)
1✔
710
                }
1✔
711
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
712
                        cont.buildNetPolSubjRule(subj, ruleName, direction,
1✔
713
                                "ipv6", "", "", remoteSubnets, addPodSubnetAsRemIp)
1✔
714
                }
1✔
715
        } else {
1✔
716
                for j := range ports {
2✔
717
                        proto := portProto(ports[j].Protocol)
1✔
718
                        var portList []string
1✔
719

1✔
720
                        if ports[j].Port != nil {
2✔
721
                                if ports[j].Port.Type == intstr.Int {
2✔
722
                                        portList = append(portList, ports[j].Port.String())
1✔
723
                                } else {
2✔
724
                                        var portnums []int
1✔
725
                                        if direction == "egress" {
2✔
726
                                                portnums = append(portnums, cont.getPortNums(&ports[j])...)
1✔
727
                                        } else {
2✔
728
                                                // TODO need to handle empty Pod Selector
1✔
729
                                                if reflect.DeepEqual(np.Spec.PodSelector, metav1.LabelSelector{}) {
1✔
730
                                                        logger.Warning("Empty PodSelctor for NamedPort is not supported in ingress direction"+
×
731
                                                                "port in network policy: ", ports[j].Port.String())
×
732
                                                        continue
×
733
                                                }
734
                                                podKeys := cont.netPolPods.GetPodForObj(npKey)
1✔
735
                                                portnums = cont.getPortNumsFromPortName(podKeys, ports[j].Port.String())
1✔
736
                                        }
737
                                        if len(portnums) == 0 {
2✔
738
                                                logger.Warning("There is no matching  ports in ingress/egress direction "+
1✔
739
                                                        "port in network policy: ", ports[j].Port.String())
1✔
740
                                                continue
1✔
741
                                        }
742
                                        for _, portnum := range portnums {
2✔
743
                                                portList = append(portList, strconv.Itoa(portnum))
1✔
744
                                        }
1✔
745
                                }
746
                        }
747
                        for i, port := range portList {
2✔
748
                                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
749
                                        cont.buildNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(i+j), direction,
1✔
750
                                                "ipv4", proto, port, remoteSubnets, addPodSubnetAsRemIp)
1✔
751
                                }
1✔
752
                                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
753
                                        cont.buildNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(i+j), direction,
1✔
754
                                                "ipv6", proto, port, remoteSubnets, addPodSubnetAsRemIp)
1✔
755
                                }
1✔
756
                        }
757
                }
758
        }
759
}
760

761
func (cont *AciController) getPortNums(port *v1net.NetworkPolicyPort) []int {
1✔
762
        portkey := portKey(port)
1✔
763
        cont.indexMutex.Lock()
1✔
764
        defer cont.indexMutex.Unlock()
1✔
765
        cont.log.Debug("PortKey1: ", portkey)
1✔
766
        entry := cont.targetPortIndex[portkey]
1✔
767
        var length int
1✔
768
        if entry == nil || len(entry.port.ports) == 0 {
2✔
769
                return []int{}
1✔
770
        }
1✔
771
        length = len(entry.port.ports)
1✔
772
        ports := make([]int, length)
1✔
773
        copy(ports, entry.port.ports)
1✔
774
        return ports
1✔
775
}
776
func portProto(protocol *v1.Protocol) string {
1✔
777
        proto := "tcp"
1✔
778
        if protocol != nil && *protocol == v1.ProtocolUDP {
2✔
779
                proto = "udp"
1✔
780
        } else if protocol != nil && *protocol == v1.ProtocolSCTP {
3✔
781
                proto = "sctp"
1✔
782
        }
1✔
783
        return proto
1✔
784
}
785

786
func portKey(p *v1net.NetworkPolicyPort) string {
1✔
787
        portType := ""
1✔
788
        port := ""
1✔
789
        if p != nil && p.Port != nil {
2✔
790
                if p.Port.Type == intstr.Int {
2✔
791
                        portType = "num"
1✔
792
                } else {
2✔
793
                        portType = "name"
1✔
794
                }
1✔
795
                port = p.Port.String()
1✔
796
                return portProto(p.Protocol) + "-" + portType + "-" + port
1✔
797
        }
798
        return ""
1✔
799
}
800

801
func checkEndpoints(subnetIndex cidranger.Ranger,
802
        addresses []v1.EndpointAddress) bool {
1✔
803
        for _, addr := range addresses {
2✔
804
                ip := net.ParseIP(addr.IP)
1✔
805
                if ip == nil {
1✔
806
                        return false
×
807
                }
×
808
                contains, err := subnetIndex.Contains(ip)
1✔
809
                if err != nil || !contains {
2✔
810
                        return false
1✔
811
                }
1✔
812
        }
813

814
        return true
1✔
815
}
816
func checkEndpointslices(subnetIndex cidranger.Ranger,
817
        addresses []string) bool {
1✔
818
        for _, addr := range addresses {
2✔
819
                ip := net.ParseIP(addr)
1✔
820
                if ip == nil {
1✔
821
                        return false
×
822
                }
×
823
                contains, err := subnetIndex.Contains(ip)
1✔
824
                if err != nil || !contains {
2✔
825
                        return false
1✔
826
                }
1✔
827
        }
828
        return true
1✔
829
}
830

831
type portRemoteSubnet struct {
832
        port           *v1net.NetworkPolicyPort
833
        subnetMap      map[string]bool
834
        hasNamedTarget bool
835
}
836

837
func updatePortRemoteSubnets(portRemoteSubs map[string]*portRemoteSubnet,
838
        portkey string, port *v1net.NetworkPolicyPort, subnetMap map[string]bool,
839
        hasNamedTarget bool) {
1✔
840
        if prs, ok := portRemoteSubs[portkey]; ok {
1✔
841
                for s := range subnetMap {
×
842
                        prs.subnetMap[s] = true
×
843
                }
×
844
                prs.hasNamedTarget = hasNamedTarget || prs.hasNamedTarget
×
845
        } else {
1✔
846
                portRemoteSubs[portkey] = &portRemoteSubnet{
1✔
847
                        port:           port,
1✔
848
                        subnetMap:      subnetMap,
1✔
849
                        hasNamedTarget: hasNamedTarget,
1✔
850
                }
1✔
851
        }
1✔
852
}
853

854
func portServiceAugmentKey(proto, port string) string {
1✔
855
        return proto + "-" + port
1✔
856
}
1✔
857

858
type portServiceAugment struct {
859
        proto string
860
        port  string
861
        ipMap map[string]bool
862
}
863

864
func updateServiceAugment(portAugments map[string]*portServiceAugment, proto, port, ip string) {
1✔
865
        key := portServiceAugmentKey(proto, port)
1✔
866
        if psa, ok := portAugments[key]; ok {
1✔
867
                psa.ipMap[ip] = true
×
868
        } else {
1✔
869
                portAugments[key] = &portServiceAugment{
1✔
870
                        proto: proto,
1✔
871
                        port:  port,
1✔
872
                        ipMap: map[string]bool{ip: true},
1✔
873
                }
1✔
874
        }
1✔
875
}
876

877
func updateServiceAugmentForService(portAugments map[string]*portServiceAugment,
878
        proto, port string, service *v1.Service) {
1✔
879
        if service.Spec.ClusterIP != "" {
2✔
880
                updateServiceAugment(portAugments,
1✔
881
                        proto, port, service.Spec.ClusterIP)
1✔
882
        }
1✔
883
        for _, ig := range service.Status.LoadBalancer.Ingress {
1✔
884
                if ig.IP == "" {
×
885
                        continue
×
886
                }
887
                updateServiceAugment(portAugments,
×
888
                        proto, port, ig.IP)
×
889
        }
890
}
891

892
// build service augment by matching peers against the endpoints ip
893
// index
894
func (cont *AciController) getServiceAugmentBySubnet(
895
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
896
        logger *logrus.Entry) {
1✔
897
        matchedServices := make(map[string]bool)
1✔
898
        subnetIndex := cidranger.NewPCTrieRanger()
1✔
899

1✔
900
        // find candidate service endpoints objects that include
1✔
901
        // endpoints selected by the egress rule
1✔
902
        cont.indexMutex.Lock()
1✔
903
        for sub := range prs.subnetMap {
2✔
904
                cidr := parseCIDR(sub)
1✔
905
                if cidr == nil {
1✔
906
                        continue
×
907
                }
908
                subnetIndex.Insert(cidranger.NewBasicRangerEntry(*cidr))
1✔
909

1✔
910
                entries, err := cont.endpointsIpIndex.CoveredNetworks(*cidr)
1✔
911
                if err != nil {
1✔
912
                        logger.Error("endpointsIpIndex corrupted: ", err)
×
913
                        continue
×
914
                }
915
                for _, entry := range entries {
2✔
916
                        e := entry.(*ipIndexEntry)
1✔
917
                        for servicekey := range e.keys {
2✔
918
                                matchedServices[servicekey] = true
1✔
919
                        }
1✔
920
                }
921
        }
922
        cont.indexMutex.Unlock()
1✔
923

1✔
924
        // if all endpoints are selected by egress rule, allow egress
1✔
925
        // to the service cluster IP as well as to the endpoints
1✔
926
        // themselves
1✔
927
        for servicekey := range matchedServices {
2✔
928
                serviceobj, _, err := cont.serviceIndexer.GetByKey(servicekey)
1✔
929
                if err != nil {
1✔
930
                        logger.Error("Could not lookup service for "+
×
931
                                servicekey+": ", err.Error())
×
932
                        continue
×
933
                }
934
                if serviceobj == nil {
1✔
UNCOV
935
                        continue
×
936
                }
937
                service := serviceobj.(*v1.Service)
1✔
938
                cont.serviceEndPoints.SetNpServiceAugmentForService(servicekey, service,
1✔
939
                        prs, portAugments, subnetIndex, logger)
1✔
940
        }
941
}
942

943
// build service augment by matching against services with a given
944
// target port
945
func (cont *AciController) getServiceAugmentByPort(
946
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
947
        logger *logrus.Entry) {
1✔
948
        // nil port means it matches against all ports.  If we're here, it
1✔
949
        // means this is a rule that matches all ports with all
1✔
950
        // destinations, so there's no need to augment anything.
1✔
951
        if prs.port == nil ||
1✔
952
                prs.port.Port == nil {
2✔
953
                return
1✔
954
        }
1✔
955

956
        portkey := portKey(prs.port)
1✔
957
        cont.indexMutex.Lock()
1✔
958
        entries := make(map[string]*portIndexEntry)
1✔
959
        entry := cont.targetPortIndex[portkey]
1✔
960
        if entry != nil && prs.port.Port.Type == intstr.String {
2✔
961
                for _, port := range entry.port.ports {
2✔
962
                        portstring := strconv.Itoa(port)
1✔
963
                        key := portProto(prs.port.Protocol) + "-" + "num" + "-" + portstring
1✔
964
                        portEntry := cont.targetPortIndex[key]
1✔
965
                        if portEntry != nil {
2✔
966
                                entries[portstring] = portEntry
1✔
967
                        }
1✔
968
                }
969
        } else if entry != nil {
2✔
970
                if len(entry.port.ports) > 0 {
2✔
971
                        entries[strconv.Itoa(entry.port.ports[0])] = entry
1✔
972
                }
1✔
973
        }
974
        for key, portentry := range entries {
2✔
975
                for servicekey := range portentry.serviceKeys {
2✔
976
                        serviceobj, _, err := cont.serviceIndexer.GetByKey(servicekey)
1✔
977
                        if err != nil {
1✔
978
                                logger.Error("Could not lookup service for "+
×
979
                                        servicekey+": ", err.Error())
×
980
                                continue
×
981
                        }
982
                        if serviceobj == nil {
1✔
983
                                continue
×
984
                        }
985
                        service := serviceobj.(*v1.Service)
1✔
986

1✔
987
                        for _, svcPort := range service.Spec.Ports {
2✔
988
                                if svcPort.Protocol != *prs.port.Protocol ||
1✔
989
                                        svcPort.TargetPort.String() !=
1✔
990
                                                key {
1✔
991
                                        continue
×
992
                                }
993
                                proto := portProto(&svcPort.Protocol)
1✔
994
                                port := strconv.Itoa(int(svcPort.Port))
1✔
995

1✔
996
                                updateServiceAugmentForService(portAugments,
1✔
997
                                        proto, port, service)
1✔
998

1✔
999
                                logger.WithFields(logrus.Fields{
1✔
1000
                                        "proto":   proto,
1✔
1001
                                        "port":    port,
1✔
1002
                                        "service": servicekey,
1✔
1003
                                }).Debug("Allowing egress for service by port")
1✔
1004
                        }
1005
                }
1006
        }
1007
        cont.indexMutex.Unlock()
1✔
1008
}
1009

1010
// The egress NetworkPolicy API were designed with the iptables
1011
// implementation in mind and don't contemplate that the layer 4 load
1012
// balancer could happen separately from the policy.  In particular,
1013
// it expects load balancer operations to be applied before the policy
1014
// is applied in both directions, so network policies would apply only
1015
// to pods and not to service IPs. This presents a problem for egress
1016
// policies on ACI since the security groups are applied before load
1017
// balancer operations when egressing, and after when ingressing.
1018
//
1019
// To solve this problem, we use some indexes to discover situations
1020
// when an egress policy covers all the endpoints associated with a
1021
// particular service, and automatically add a rule that allows egress
1022
// to the corresponding service cluster IP and ports.
1023
//
1024
// Note that this differs slightly from the behavior you'd see if you
1025
// applied the load balancer rule first: If the egress policy allows
1026
// access to a subset of the allowed IPs you'd see random failures
1027
// depending on which destination is chosen, while with this approach
1028
// it's all or nothing.  This should not impact any correctly-written
1029
// network policies.
1030
//
1031
// To do this, we work first from the set of pods and subnets matches
1032
// by the egress policy.  We use this to find using the
1033
// endpointsIpIndex all services that contain at least one of the
1034
// matched pods or subnets.  For each of these candidate services, we
1035
// find service ports for which _all_ referenced endpoints are allowed
1036
// by the egress policy.  Note that a service will have the service
1037
// port and the target port; the NetworkPolicy (confusingly) refers to
1038
// the target port.
1039
//
1040
// Once confirmed matches are found, we augment the egress policy with
1041
// extra rules to allow egress to the service IPs and service ports.
1042
//
1043
// As a special case, for rules that match everything, we also have a
1044
// backup index that works through ports which should allow more
1045
// efficient matching when allowing egress to all.
1046
func (cont *AciController) buildServiceAugment(subj apicapi.ApicObject,
1047
        portRemoteSubs map[string]*portRemoteSubnet, logger *logrus.Entry) {
1✔
1048
        portAugments := make(map[string]*portServiceAugment)
1✔
1049
        for _, prs := range portRemoteSubs {
2✔
1050
                // TODO ipv6
1✔
1051
                if prs.subnetMap["0.0.0.0/0"] {
2✔
1052
                        cont.getServiceAugmentByPort(prs, portAugments, logger)
1✔
1053
                } else {
2✔
1054
                        cont.getServiceAugmentBySubnet(prs, portAugments, logger)
1✔
1055
                }
1✔
1056
        }
1057
        for _, augment := range portAugments {
2✔
1058
                var remoteIpsv4 []string
1✔
1059
                var remoteIpsv6 []string
1✔
1060
                for ipstr := range augment.ipMap {
2✔
1061
                        ip := net.ParseIP(ipstr)
1✔
1062
                        if ip == nil {
1✔
1063
                                continue
×
1064
                        } else if ip.To4() != nil {
2✔
1065
                                remoteIpsv4 = append(remoteIpsv4, ipstr)
1✔
1066
                        } else if ip.To16() != nil {
3✔
1067
                                remoteIpsv6 = append(remoteIpsv6, ipstr)
1✔
1068
                        }
1✔
1069
                }
1070
                cont.log.Debug("Service Augment: ", augment)
1✔
1071
                if len(remoteIpsv4) > 0 {
2✔
1072
                        cont.buildNetPolSubjRule(subj,
1✔
1073
                                "service_"+augment.proto+"_"+augment.port,
1✔
1074
                                "egress", "ipv4", augment.proto, augment.port, remoteIpsv4, false)
1✔
1075
                }
1✔
1076
                if len(remoteIpsv6) > 0 {
2✔
1077
                        cont.buildNetPolSubjRule(subj,
1✔
1078
                                "service_"+augment.proto+"_"+augment.port,
1✔
1079
                                "egress", "ipv6", augment.proto, augment.port, remoteIpsv6, false)
1✔
1080
                }
1✔
1081
        }
1082
}
1083

1084
func isAllowAllForAllNamespaces(peers []v1net.NetworkPolicyPeer) bool {
1✔
1085
        addPodSubnetAsRemIp := false
1✔
1086
        if peers != nil && len(peers) > 0 {
2✔
1087
                var emptyPodSel, emptyNsSel bool
1✔
1088
                emptyPodSel = true
1✔
1089
                for _, peer := range peers {
2✔
1090
                        // namespaceSelector: {}
1✔
1091
                        if peer.NamespaceSelector != nil && peer.NamespaceSelector.MatchLabels == nil && peer.NamespaceSelector.MatchExpressions == nil {
1✔
1092
                                emptyNsSel = true
×
1093
                        }
×
1094
                        // podSelector has some fields
1095
                        if peer.PodSelector != nil && (peer.PodSelector.MatchLabels != nil || peer.PodSelector.MatchExpressions != nil) {
2✔
1096
                                emptyPodSel = false
1✔
1097
                        }
1✔
1098
                }
1099
                if emptyNsSel && emptyPodSel {
1✔
1100
                        addPodSubnetAsRemIp = true
×
1101
                }
×
1102
        }
1103
        return addPodSubnetAsRemIp
1✔
1104
}
1105

1106
func (cont *AciController) handleNetPolUpdate(np *v1net.NetworkPolicy) bool {
1✔
1107
        if cont.config.ChainedMode {
1✔
1108
                return false
×
1109
        }
×
1110
        key, err := cache.MetaNamespaceKeyFunc(np)
1✔
1111
        logger := networkPolicyLogger(cont.log, np)
1✔
1112
        if err != nil {
1✔
1113
                logger.Error("Could not create network policy key: ", err)
×
1114
                return false
×
1115
        }
×
1116

1117
        peerPodKeys := cont.netPolIngressPods.GetPodForObj(key)
1✔
1118
        peerPodKeys =
1✔
1119
                append(peerPodKeys, cont.netPolEgressPods.GetPodForObj(key)...)
1✔
1120
        var peerPods []*v1.Pod
1✔
1121
        peerNs := make(map[string]*v1.Namespace)
1✔
1122
        for _, podkey := range peerPodKeys {
2✔
1123
                podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
1124
                if exists && err == nil {
2✔
1125
                        pod := podobj.(*v1.Pod)
1✔
1126
                        if _, nsok := peerNs[pod.ObjectMeta.Namespace]; !nsok {
2✔
1127
                                nsobj, exists, err :=
1✔
1128
                                        cont.namespaceIndexer.GetByKey(pod.ObjectMeta.Namespace)
1✔
1129
                                if !exists || err != nil {
1✔
1130
                                        continue
×
1131
                                }
1132
                                peerNs[pod.ObjectMeta.Namespace] = nsobj.(*v1.Namespace)
1✔
1133
                        }
1134
                        peerPods = append(peerPods, pod)
1✔
1135
                }
1136
        }
1137
        ptypeset := make(map[v1net.PolicyType]bool)
1✔
1138
        for _, t := range np.Spec.PolicyTypes {
2✔
1139
                ptypeset[t] = true
1✔
1140
        }
1✔
1141
        var labelKey string
1✔
1142

1✔
1143
        if cont.config.HppOptimization {
2✔
1144
                hash, err := util.CreateHashFromNetPol(np)
1✔
1145
                if err != nil {
1✔
1146
                        logger.Error("Could not create hash from network policy: ", err)
×
1147
                        return false
×
1148
                }
×
1149
                labelKey = cont.aciNameForKey("np", hash)
1✔
1150
        } else {
1✔
1151
                labelKey = cont.aciNameForKey("np", key)
1✔
1152
        }
1✔
1153
        hpp := apicapi.NewHostprotPol(cont.config.AciPolicyTenant, labelKey)
1✔
1154
        // Generate ingress policies
1✔
1155
        if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeIngress] {
2✔
1156
                subjIngress :=
1✔
1157
                        apicapi.NewHostprotSubj(hpp.GetDn(), "networkpolicy-ingress")
1✔
1158

1✔
1159
                for i, ingress := range np.Spec.Ingress {
2✔
1160
                        addPodSubnetAsRemIp := isAllowAllForAllNamespaces(ingress.From)
1✔
1161
                        remoteSubnets, _ := cont.getPeerRemoteSubnets(ingress.From,
1✔
1162
                                np.Namespace, peerPods, peerNs, logger)
1✔
1163
                        cont.buildNetPolSubjRules(strconv.Itoa(i), subjIngress,
1✔
1164
                                "ingress", ingress.From, remoteSubnets, ingress.Ports, logger, key, np, addPodSubnetAsRemIp)
1✔
1165
                }
1✔
1166
                hpp.AddChild(subjIngress)
1✔
1167
        }
1168
        // Generate egress policies
1169
        if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeEgress] {
2✔
1170
                subjEgress :=
1✔
1171
                        apicapi.NewHostprotSubj(hpp.GetDn(), "networkpolicy-egress")
1✔
1172

1✔
1173
                portRemoteSubs := make(map[string]*portRemoteSubnet)
1✔
1174

1✔
1175
                for i, egress := range np.Spec.Egress {
2✔
1176
                        addPodSubnetAsRemIp := isAllowAllForAllNamespaces(egress.To)
1✔
1177
                        remoteSubnets, subnetMap := cont.getPeerRemoteSubnets(egress.To,
1✔
1178
                                np.Namespace, peerPods, peerNs, logger)
1✔
1179
                        cont.buildNetPolSubjRules(strconv.Itoa(i), subjEgress,
1✔
1180
                                "egress", egress.To, remoteSubnets, egress.Ports, logger, key, np, addPodSubnetAsRemIp)
1✔
1181

1✔
1182
                        // creating a rule to egress to all on a given port needs
1✔
1183
                        // to enable access to any service IPs/ports that have
1✔
1184
                        // that port as their target port.
1✔
1185
                        if len(egress.To) == 0 {
2✔
1186
                                subnetMap = map[string]bool{
1✔
1187
                                        "0.0.0.0/0": true,
1✔
1188
                                }
1✔
1189
                        }
1✔
1190
                        for idx := range egress.Ports {
2✔
1191
                                port := egress.Ports[idx]
1✔
1192
                                portkey := portKey(&port)
1✔
1193
                                updatePortRemoteSubnets(portRemoteSubs, portkey, &port, subnetMap,
1✔
1194
                                        port.Port != nil && port.Port.Type == intstr.Int)
1✔
1195
                        }
1✔
1196
                        if len(egress.Ports) == 0 {
2✔
1197
                                updatePortRemoteSubnets(portRemoteSubs, "", nil, subnetMap,
1✔
1198
                                        false)
1✔
1199
                        }
1✔
1200
                }
1201
                cont.buildServiceAugment(subjEgress, portRemoteSubs, logger)
1✔
1202
                hpp.AddChild(subjEgress)
1✔
1203
        }
1204
        if cont.config.HppOptimization {
2✔
1205
                cont.addToHppCache(labelKey, key, apicapi.ApicSlice{hpp})
1✔
1206
        }
1✔
1207
        cont.apicConn.WriteApicObjects(labelKey, apicapi.ApicSlice{hpp})
1✔
1208
        return false
1✔
1209
}
1210

1211
func (cont *AciController) addToHppCache(labelKey, key string, hpp apicapi.ApicSlice) {
1✔
1212
        cont.indexMutex.Lock()
1✔
1213
        hppRef, ok := cont.hppRef[labelKey]
1✔
1214
        if ok {
2✔
1215
                var found bool
1✔
1216
                for _, npkey := range hppRef.Npkeys {
2✔
1217
                        if npkey == key {
2✔
1218
                                found = true
1✔
1219
                                break
1✔
1220
                        }
1221
                }
1222
                if !found {
1✔
1223
                        hppRef.RefCount++
×
1224
                        hppRef.Npkeys = append(hppRef.Npkeys, key)
×
1225
                }
×
1226
                hppRef.HppObj = hpp
1✔
1227
                cont.hppRef[labelKey] = hppRef
1✔
1228
        } else {
1✔
1229
                var newHppRef hppReference
1✔
1230
                newHppRef.RefCount++
1✔
1231
                newHppRef.HppObj = hpp
1✔
1232
                newHppRef.Npkeys = append(newHppRef.Npkeys, key)
1✔
1233
                cont.hppRef[labelKey] = newHppRef
1✔
1234
        }
1✔
1235
        cont.indexMutex.Unlock()
1✔
1236
}
1237

1238
func (cont *AciController) removeFromHppCache(np *v1net.NetworkPolicy, key string) (string, bool) {
×
1239
        var labelKey string
×
1240
        var noRef bool
×
1241
        hash, err := util.CreateHashFromNetPol(np)
×
1242
        if err != nil {
×
1243
                cont.log.Error("Could not create hash from network policy: ", err)
×
1244
                cont.log.Error("Failed to remove np from hpp cache")
×
1245
                return labelKey, noRef
×
1246
        }
×
1247
        labelKey = cont.aciNameForKey("np", hash)
×
1248
        cont.indexMutex.Lock()
×
1249
        hppRef, ok := cont.hppRef[labelKey]
×
1250
        if ok {
×
1251
                for i, npkey := range hppRef.Npkeys {
×
1252
                        if npkey == key {
×
1253
                                hppRef.Npkeys = append(hppRef.Npkeys[:i], hppRef.Npkeys[i+1:]...)
×
1254
                                hppRef.RefCount--
×
1255
                                break
×
1256
                        }
1257
                }
1258
                if hppRef.RefCount > 0 {
×
1259
                        cont.hppRef[labelKey] = hppRef
×
1260
                } else {
×
1261
                        delete(cont.hppRef, labelKey)
×
1262
                        noRef = true
×
1263
                }
×
1264
        }
1265
        cont.indexMutex.Unlock()
×
1266
        return labelKey, noRef
×
1267
}
1268

1269
func getNetworkPolicyEgressIpBlocks(np *v1net.NetworkPolicy) map[string]bool {
1✔
1270
        subnets := make(map[string]bool)
1✔
1271
        for _, egress := range np.Spec.Egress {
2✔
1272
                for _, to := range egress.To {
2✔
1273
                        if to.IPBlock != nil && to.IPBlock.CIDR != "" {
2✔
1274
                                subnets[to.IPBlock.CIDR] = true
1✔
1275
                        }
1✔
1276
                }
1277
        }
1278
        return subnets
1✔
1279
}
1280

1281
func (cont *AciController) networkPolicyAdded(obj interface{}) {
1✔
1282
        np := obj.(*v1net.NetworkPolicy)
1✔
1283
        npkey, err := cache.MetaNamespaceKeyFunc(np)
1✔
1284
        if err != nil {
1✔
1285
                networkPolicyLogger(cont.log, np).
×
1286
                        Error("Could not create network policy key: ", err)
×
1287
                return
×
1288
        }
×
1289
        cont.writeApicNP(npkey, np)
1✔
1290
        if cont.config.ChainedMode {
1✔
1291
                return
×
1292
        }
×
1293
        cont.netPolPods.UpdateSelectorObj(obj)
1✔
1294
        cont.netPolIngressPods.UpdateSelectorObj(obj)
1✔
1295
        cont.netPolEgressPods.UpdateSelectorObj(obj)
1✔
1296
        cont.indexMutex.Lock()
1✔
1297
        subnets := getNetworkPolicyEgressIpBlocks(np)
1✔
1298
        cont.updateIpIndex(cont.netPolSubnetIndex, nil, subnets, npkey)
1✔
1299

1✔
1300
        ports := cont.getNetPolTargetPorts(np)
1✔
1301
        cont.updateTargetPortIndex(false, npkey, nil, ports)
1✔
1302
        if isNamedPortPresenInNp(np) {
2✔
1303
                cont.nmPortNp[npkey] = true
1✔
1304
        }
1✔
1305
        cont.indexMutex.Unlock()
1✔
1306
        cont.queueNetPolUpdateByKey(npkey)
1✔
1307
}
1308

1309
func (cont *AciController) writeApicNP(npKey string, np *v1net.NetworkPolicy) {
1✔
1310
        if cont.config.LBType == lbTypeAci {
2✔
1311
                return
1✔
1312
        }
1✔
1313
        if cont.config.ChainedMode {
×
1314
                return
×
1315
        }
×
1316

1317
        npObj := apicapi.NewVmmInjectedNwPol(cont.vmmDomainProvider(),
×
1318
                cont.config.AciVmmDomain, cont.config.AciVmmController,
×
1319
                np.ObjectMeta.Namespace, np.ObjectMeta.Name)
×
1320
        setAttr := func(name, attr string) {
×
1321
                if attr != "" {
×
1322
                        npObj.SetAttr(name, attr)
×
1323
                }
×
1324
        }
1325
        setAttr("ingress", ingressStr(np))
×
1326
        setAttr("egress", egressStr(np))
×
1327
        key := cont.aciNameForKey("NwPol", npKey)
×
1328
        cont.log.Debugf("Writing %s %+v", key, npObj)
×
1329
        cont.apicConn.WriteApicObjects(key, apicapi.ApicSlice{npObj})
×
1330
}
1331

1332
func peersToStr(peers []v1net.NetworkPolicyPeer) string {
×
1333
        pStr := "["
×
1334
        for _, p := range peers {
×
1335
                if p.IPBlock != nil {
×
1336
                        pStr += p.IPBlock.CIDR
×
1337
                        if len(p.IPBlock.Except) != 0 {
×
1338
                                pStr += "[except"
×
1339
                                for _, e := range p.IPBlock.Except {
×
1340
                                        pStr += fmt.Sprintf("-%s", e)
×
1341
                                }
×
1342
                                pStr += "]"
×
1343
                        }
1344
                        pStr += "+"
×
1345
                }
1346
        }
1347

1348
        pStr = strings.TrimSuffix(pStr, "+")
×
1349
        pStr += "]"
×
1350
        return pStr
×
1351
}
1352

1353
func portsToStr(ports []v1net.NetworkPolicyPort) string {
×
1354
        pStr := "["
×
1355

×
1356
        for _, p := range ports {
×
1357
                if p.Protocol != nil {
×
1358
                        pStr += string(*p.Protocol)
×
1359
                }
×
1360
                if p.Port != nil {
×
1361
                        pStr += ":" + p.Port.String()
×
1362
                }
×
1363
                pStr += "+"
×
1364
        }
1365

1366
        pStr = strings.TrimSuffix(pStr, "+")
×
1367
        pStr += "]"
×
1368
        return pStr
×
1369
}
1370

1371
func ingressStr(np *v1net.NetworkPolicy) string {
×
1372
        iStr := ""
×
1373
        for _, rule := range np.Spec.Ingress {
×
1374
                iStr += peersToStr(rule.From)
×
1375
                iStr += ":" + portsToStr(rule.Ports)
×
1376
                iStr += "+"
×
1377
        }
×
1378
        iStr = strings.TrimSuffix(iStr, "+")
×
1379
        return iStr
×
1380
}
1381

1382
func egressStr(np *v1net.NetworkPolicy) string {
×
1383
        eStr := ""
×
1384
        for _, rule := range np.Spec.Egress {
×
1385
                eStr += peersToStr(rule.To)
×
1386
                eStr += ":" + portsToStr(rule.Ports)
×
1387
                eStr += "+"
×
1388
        }
×
1389
        eStr = strings.TrimSuffix(eStr, "+")
×
1390
        return eStr
×
1391
}
1392

1393
func (cont *AciController) networkPolicyChanged(oldobj interface{},
1394
        newobj interface{}) {
×
1395
        oldnp := oldobj.(*v1net.NetworkPolicy)
×
1396
        newnp := newobj.(*v1net.NetworkPolicy)
×
1397
        npkey, err := cache.MetaNamespaceKeyFunc(newnp)
×
1398
        if err != nil {
×
1399
                networkPolicyLogger(cont.log, newnp).
×
1400
                        Error("Could not create network policy key: ", err)
×
1401
                return
×
1402
        }
×
1403

1404
        if cont.config.HppOptimization {
×
1405
                cont.removeFromHppCache(oldnp, npkey)
×
1406
        }
×
1407

1408
        cont.writeApicNP(npkey, newnp)
×
1409
        cont.indexMutex.Lock()
×
1410
        oldSubnets := getNetworkPolicyEgressIpBlocks(oldnp)
×
1411
        newSubnets := getNetworkPolicyEgressIpBlocks(newnp)
×
1412
        cont.updateIpIndex(cont.netPolSubnetIndex, oldSubnets, newSubnets, npkey)
×
1413

×
1414
        oldPorts := cont.getNetPolTargetPorts(oldnp)
×
1415
        newPorts := cont.getNetPolTargetPorts(newnp)
×
1416
        cont.updateTargetPortIndex(false, npkey, oldPorts, newPorts)
×
1417
        cont.indexMutex.Unlock()
×
1418

×
1419
        if !reflect.DeepEqual(oldnp.Spec.PodSelector, newnp.Spec.PodSelector) {
×
1420
                cont.netPolPods.UpdateSelectorObjNoCallback(newobj)
×
1421
        }
×
1422
        if !reflect.DeepEqual(oldnp.Spec.PolicyTypes, newnp.Spec.PolicyTypes) {
×
1423
                peerPodKeys := cont.netPolPods.GetPodForObj(npkey)
×
1424
                for _, podkey := range peerPodKeys {
×
1425
                        cont.podQueue.Add(podkey)
×
1426
                }
×
1427
        }
1428
        var queue bool
×
1429
        if !reflect.DeepEqual(oldnp.Spec.Ingress, newnp.Spec.Ingress) {
×
1430
                cont.netPolIngressPods.UpdateSelectorObjNoCallback(newobj)
×
1431
                queue = true
×
1432
        }
×
1433
        if !reflect.DeepEqual(oldnp.Spec.Egress, newnp.Spec.Egress) {
×
1434
                cont.netPolEgressPods.UpdateSelectorObjNoCallback(newobj)
×
1435
                queue = true
×
1436
        }
×
1437
        if queue {
×
1438
                cont.queueNetPolUpdateByKey(npkey)
×
1439
        }
×
1440
}
1441

1442
func (cont *AciController) networkPolicyDeleted(obj interface{}) {
1✔
1443
        np, isNetworkpolicy := obj.(*v1net.NetworkPolicy)
1✔
1444
        if !isNetworkpolicy {
1✔
1445
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
×
1446
                if !ok {
×
1447
                        networkPolicyLogger(cont.log, np).
×
1448
                                Error("Received unexpected object: ", obj)
×
1449
                        return
×
1450
                }
×
1451
                np, ok = deletedState.Obj.(*v1net.NetworkPolicy)
×
1452
                if !ok {
×
1453
                        networkPolicyLogger(cont.log, np).
×
1454
                                Error("DeletedFinalStateUnknown contained non-Networkpolicy object: ", deletedState.Obj)
×
1455
                        return
×
1456
                }
×
1457
        }
1458
        npkey, err := cache.MetaNamespaceKeyFunc(np)
1✔
1459
        if err != nil {
1✔
1460
                networkPolicyLogger(cont.log, np).
×
1461
                        Error("Could not create network policy key: ", err)
×
1462
                return
×
1463
        }
×
1464

1465
        if cont.config.LBType != lbTypeAci {
1✔
1466
                cont.apicConn.ClearApicObjects(cont.aciNameForKey("NwPol", npkey))
×
1467
        }
×
1468

1469
        var labelKey string
1✔
1470
        var noHppRef bool
1✔
1471
        if cont.config.HppOptimization {
1✔
1472
                labelKey, noHppRef = cont.removeFromHppCache(np, npkey)
×
1473
        } else {
1✔
1474
                labelKey = cont.aciNameForKey("np", npkey)
1✔
1475
                noHppRef = true
1✔
1476
        }
1✔
1477

1478
        cont.indexMutex.Lock()
1✔
1479
        subnets := getNetworkPolicyEgressIpBlocks(np)
1✔
1480
        cont.updateIpIndex(cont.netPolSubnetIndex, subnets, nil, npkey)
1✔
1481

1✔
1482
        ports := cont.getNetPolTargetPorts(np)
1✔
1483
        cont.updateTargetPortIndex(false, npkey, ports, nil)
1✔
1484
        if isNamedPortPresenInNp(np) {
2✔
1485
                delete(cont.nmPortNp, npkey)
1✔
1486
        }
1✔
1487
        cont.indexMutex.Unlock()
1✔
1488

1✔
1489
        cont.netPolPods.DeleteSelectorObj(obj)
1✔
1490
        cont.netPolIngressPods.DeleteSelectorObj(obj)
1✔
1491
        cont.netPolEgressPods.DeleteSelectorObj(obj)
1✔
1492
        if noHppRef && labelKey != "" {
2✔
1493
                cont.apicConn.ClearApicObjects(labelKey)
1✔
1494
        }
1✔
1495
}
1496

1497
func (sep *serviceEndpoint) SetNpServiceAugmentForService(servicekey string, service *v1.Service, prs *portRemoteSubnet,
1498
        portAugments map[string]*portServiceAugment, subnetIndex cidranger.Ranger, logger *logrus.Entry) {
1✔
1499
        cont := sep.cont
1✔
1500
        endpointsobj, _, err := cont.endpointsIndexer.GetByKey(servicekey)
1✔
1501
        if err != nil {
1✔
1502
                logger.Error("Could not lookup endpoints for "+
×
1503
                        servicekey+": ", err.Error())
×
1504
                return
×
1505
        }
×
1506
        if endpointsobj == nil {
1✔
1507
                return
×
1508
        }
×
1509
        endpoints := endpointsobj.(*v1.Endpoints)
1✔
1510
        portstrings := make(map[string]bool)
1✔
1511
        ports := cont.getPortNums(prs.port)
1✔
1512
        for _, port := range ports {
2✔
1513
                portstrings[strconv.Itoa(port)] = true
1✔
1514
        }
1✔
1515
        for _, svcPort := range service.Spec.Ports {
2✔
1516
                _, ok := portstrings[svcPort.TargetPort.String()]
1✔
1517
                if prs.port != nil &&
1✔
1518
                        (svcPort.Protocol != *prs.port.Protocol || !ok) {
1✔
UNCOV
1519
                        // egress rule does not match service target port
×
UNCOV
1520
                        continue
×
1521
                }
1522
                for _, subset := range endpoints.Subsets {
2✔
1523
                        var foundEpPort *v1.EndpointPort
1✔
1524
                        for ix := range subset.Ports {
2✔
1525
                                if subset.Ports[ix].Name == svcPort.Name ||
1✔
1526
                                        (len(service.Spec.Ports) == 1 &&
1✔
1527
                                                subset.Ports[ix].Name == "") {
2✔
1528
                                        foundEpPort = &subset.Ports[ix]
1✔
1529
                                        break
1✔
1530
                                }
1531
                        }
1532
                        if foundEpPort == nil {
1✔
1533
                                continue
×
1534
                        }
1535

1536
                        incomplete := false
1✔
1537
                        incomplete = incomplete ||
1✔
1538
                                !checkEndpoints(subnetIndex, subset.Addresses)
1✔
1539
                        incomplete = incomplete || !checkEndpoints(subnetIndex,
1✔
1540
                                subset.NotReadyAddresses)
1✔
1541

1✔
1542
                        if incomplete {
2✔
1543
                                continue
1✔
1544
                        }
1545

1546
                        proto := portProto(&foundEpPort.Protocol)
1✔
1547
                        port := strconv.Itoa(int(svcPort.Port))
1✔
1548
                        updateServiceAugmentForService(portAugments,
1✔
1549
                                proto, port, service)
1✔
1550

1✔
1551
                        logger.WithFields(logrus.Fields{
1✔
1552
                                "proto":   proto,
1✔
1553
                                "port":    port,
1✔
1554
                                "service": servicekey,
1✔
1555
                        }).Debug("Allowing egress for service by subnet match")
1✔
1556
                }
1557
        }
1558
}
1559

1560
func (seps *serviceEndpointSlice) SetNpServiceAugmentForService(servicekey string, service *v1.Service,
1561
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
1562
        subnetIndex cidranger.Ranger, logger *logrus.Entry) {
1✔
1563
        cont := seps.cont
1✔
1564
        portstrings := make(map[string]bool)
1✔
1565
        ports := cont.getPortNums(prs.port)
1✔
1566
        for _, port := range ports {
2✔
1567
                portstrings[strconv.Itoa(port)] = true
1✔
1568
        }
1✔
1569
        label := map[string]string{"kubernetes.io/service-name": service.ObjectMeta.Name}
1✔
1570
        selector := labels.SelectorFromSet(label)
1✔
1571
        cache.ListAllByNamespace(cont.endpointSliceIndexer, service.ObjectMeta.Namespace, selector,
1✔
1572
                func(endpointSliceobj interface{}) {
2✔
1573
                        endpointSlices := endpointSliceobj.(*discovery.EndpointSlice)
1✔
1574
                        for _, svcPort := range service.Spec.Ports {
2✔
1575
                                _, ok := portstrings[svcPort.TargetPort.String()]
1✔
1576
                                if prs.port != nil &&
1✔
1577
                                        (svcPort.Protocol != *prs.port.Protocol || !ok) {
1✔
1578
                                        // egress rule does not match service target port
×
1579
                                        continue
×
1580
                                }
1581
                                var foundEpPort *discovery.EndpointPort
1✔
1582
                                for ix := range endpointSlices.Ports {
2✔
1583
                                        if *endpointSlices.Ports[ix].Name == svcPort.Name ||
1✔
1584
                                                (len(service.Spec.Ports) == 1 &&
1✔
1585
                                                        *endpointSlices.Ports[ix].Name == "") {
2✔
1586
                                                foundEpPort = &endpointSlices.Ports[ix]
1✔
1587
                                                cont.log.Debug("Found EpPort: ", foundEpPort)
1✔
1588
                                                break
1✔
1589
                                        }
1590
                                }
1591
                                if foundEpPort == nil {
1✔
1592
                                        return
×
1593
                                }
×
1594
                                // @FIXME for non ready address
1595
                                incomplete := false
1✔
1596
                                for _, endpoint := range endpointSlices.Endpoints {
2✔
1597
                                        incomplete = incomplete || !checkEndpointslices(subnetIndex, endpoint.Addresses)
1✔
1598
                                }
1✔
1599
                                if incomplete {
2✔
1600
                                        continue
1✔
1601
                                }
1602
                                proto := portProto(foundEpPort.Protocol)
1✔
1603
                                port := strconv.Itoa(int(svcPort.Port))
1✔
1604
                                cont.log.Debug("updateServiceAugmentForService: ", service)
1✔
1605
                                updateServiceAugmentForService(portAugments,
1✔
1606
                                        proto, port, service)
1✔
1607

1✔
1608
                                logger.WithFields(logrus.Fields{
1✔
1609
                                        "proto":   proto,
1✔
1610
                                        "port":    port,
1✔
1611
                                        "service": servicekey,
1✔
1612
                                }).Debug("Allowing egress for service by subnet match")
1✔
1613
                        }
1614
                })
1615
}
1616

1617
func isNamedPortPresenInNp(np *v1net.NetworkPolicy) bool {
1✔
1618
        for _, egress := range np.Spec.Egress {
2✔
1619
                for _, p := range egress.Ports {
2✔
1620
                        if p.Port.Type == intstr.String {
2✔
1621
                                return true
1✔
1622
                        }
1✔
1623
                }
1624
        }
1625
        return false
1✔
1626
}
1627

1628
func (cont *AciController) checkPodNmpMatchesNp(npkey, podkey string) bool {
1✔
1629
        podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
1630
        if err != nil {
1✔
1631
                return false
×
1632
        }
×
1633
        if !exists || podobj == nil {
2✔
1634
                return false
1✔
1635
        }
1✔
1636
        pod := podobj.(*v1.Pod)
1✔
1637
        npobj, npexists, nperr := cont.networkPolicyIndexer.GetByKey(npkey)
1✔
1638
        if npexists && nperr == nil && npobj != nil {
2✔
1639
                np := npobj.(*v1net.NetworkPolicy)
1✔
1640
                for _, egress := range np.Spec.Egress {
2✔
1641
                        for _, p := range egress.Ports {
2✔
1642
                                if p.Port.Type == intstr.String {
2✔
1643
                                        _, err := k8util.LookupContainerPortNumberByName(*pod, p.Port.String())
1✔
1644
                                        if err == nil {
2✔
1645
                                                return true
1✔
1646
                                        }
1✔
1647
                                }
1648
                        }
1649
                }
1650
        }
1651
        return false
1✔
1652
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc