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

noironetworks / aci-containers / 7615

pending completion
7615

push

travis-pro

GitHub
Merge pull request #1125 from noironetworks/travis-backport-kmr2

Travis backport kmr2

12040 of 21626 relevant lines covered (55.67%)

0.62 hits per line

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

75.62
/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

×
52
        cont.initNetworkPolicyInformerBase(
×
53
                cache.NewListWatchFromClient(
×
54
                        kubeClient.NetworkingV1().RESTClient(), "networkpolicies",
×
55
                        metav1.NamespaceAll, fields.Everything()))
×
56
}
×
57

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

77
func (cont *AciController) peerPodSelector(np *v1net.NetworkPolicy,
78
        peers []v1net.NetworkPolicyPeer) []index.PodSelector {
1✔
79

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

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

114
                }
115

116
        }
117
        return ret
1✔
118
}
119

120
func (cont *AciController) egressPodSelector(np *v1net.NetworkPolicy) []index.PodSelector {
1✔
121
        var ret []index.PodSelector
1✔
122

1✔
123
        for _, egress := range np.Spec.Egress {
2✔
124
                ret = append(ret, cont.peerPodSelector(np, egress.To)...)
1✔
125
        }
1✔
126

127
        return ret
1✔
128
}
129

130
func (cont *AciController) ingressPodSelector(np *v1net.NetworkPolicy) []index.PodSelector {
1✔
131
        var ret []index.PodSelector
1✔
132

1✔
133
        for _, ingress := range np.Spec.Ingress {
2✔
134
                ret = append(ret, cont.peerPodSelector(np, ingress.From)...)
1✔
135
        }
1✔
136

137
        return ret
1✔
138
}
139

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

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

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

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

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

268
                        if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
269
                                icmpin := apicapi.NewHostprotRule(discDn, "icmpv6-ingress")
1✔
270
                                icmpin.SetAttr("direction", "ingress")
1✔
271
                                icmpin.SetAttr("ethertype", "ipv6")
1✔
272
                                icmpin.SetAttr("protocol", "icmpv6")
1✔
273
                                icmpin.SetAttr("connTrack", "normal")
1✔
274
                                discSubj.AddChild(icmpin)
1✔
275
                        }
1✔
276
                }
277
                {
1✔
278
                        if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
279
                                icmpout := apicapi.NewHostprotRule(discDn, "icmp-egress")
1✔
280
                                icmpout.SetAttr("direction", "egress")
1✔
281
                                icmpout.SetAttr("ethertype", "ipv4")
1✔
282
                                icmpout.SetAttr("protocol", "icmp")
1✔
283
                                icmpout.SetAttr("connTrack", "normal")
1✔
284
                                discSubj.AddChild(icmpout)
1✔
285
                        }
1✔
286

287
                        if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
288
                                icmpout := apicapi.NewHostprotRule(discDn, "icmpv6-egress")
1✔
289
                                icmpout.SetAttr("direction", "egress")
1✔
290
                                icmpout.SetAttr("ethertype", "ipv6")
1✔
291
                                icmpout.SetAttr("protocol", "icmpv6")
1✔
292
                                icmpout.SetAttr("connTrack", "normal")
1✔
293
                                discSubj.AddChild(icmpout)
1✔
294
                        }
1✔
295
                }
296

297
                hppDiscovery.AddChild(discSubj)
1✔
298
        }
299

300
        return apicapi.ApicSlice{hppIngress, hppEgress, hppDiscovery}
1✔
301
}
302

303
func (cont *AciController) initStaticNetPolObjs() {
1✔
304
        cont.apicConn.WriteApicObjects(cont.config.AciPrefix+"_np_static",
1✔
305
                cont.staticNetPolObjs())
1✔
306
}
1✔
307

308
func networkPolicyLogger(log *logrus.Logger,
309
        np *v1net.NetworkPolicy) *logrus.Entry {
1✔
310
        return log.WithFields(logrus.Fields{
1✔
311
                "namespace": np.ObjectMeta.Namespace,
1✔
312
                "name":      np.ObjectMeta.Name,
1✔
313
        })
1✔
314
}
1✔
315

316
func (cont *AciController) queueNetPolUpdateByKey(key string) {
1✔
317
        cont.netPolQueue.Add(key)
1✔
318
}
1✔
319

320
func (cont *AciController) queueNetPolUpdate(netpol *v1net.NetworkPolicy) {
1✔
321
        key, err := cache.MetaNamespaceKeyFunc(netpol)
1✔
322
        if err != nil {
1✔
323
                networkPolicyLogger(cont.log, netpol).
×
324
                        Error("Could not create network policy key: ", err)
×
325
                return
×
326
        }
×
327
        cont.netPolQueue.Add(key)
1✔
328
}
329

330
func (cont *AciController) peerMatchesPod(npNs string,
331
        peer *v1net.NetworkPolicyPeer, pod *v1.Pod, podNs *v1.Namespace) bool {
1✔
332
        if peer.PodSelector != nil && npNs == pod.ObjectMeta.Namespace {
2✔
333
                selector, err :=
1✔
334
                        metav1.LabelSelectorAsSelector(peer.PodSelector)
1✔
335
                if err != nil {
1✔
336
                        cont.log.Error("Could not parse pod selector: ", err)
×
337
                } else {
1✔
338
                        return selector.Matches(labels.Set(pod.ObjectMeta.Labels))
1✔
339
                }
1✔
340
        }
341
        if peer.NamespaceSelector != nil {
2✔
342
                selector, err :=
1✔
343
                        metav1.LabelSelectorAsSelector(peer.NamespaceSelector)
1✔
344
                if err != nil {
1✔
345
                        cont.log.Error("Could not parse namespace selector: ", err)
×
346
                } else {
1✔
347
                        return selector.Matches(labels.Set(podNs.ObjectMeta.Labels))
1✔
348
                }
1✔
349
        }
350
        return false
×
351
}
352

353
func ipsForPod(pod *v1.Pod) []string {
1✔
354
        var ips []string
1✔
355
        podIPsField := reflect.ValueOf(pod.Status).FieldByName("PodIPs")
1✔
356
        if podIPsField.IsValid() {
2✔
357
                if len(pod.Status.PodIPs) > 0 {
1✔
358
                        for _, ip := range pod.Status.PodIPs {
×
359
                                ips = append(ips, ip.IP)
×
360
                        }
×
361
                        return ips
×
362
                }
363

364
        }
365
        if pod.Status.PodIP != "" {
2✔
366
                return []string{pod.Status.PodIP}
1✔
367
        }
1✔
368
        return nil
1✔
369
}
370

371
func ipBlockToSubnets(ipblock *v1net.IPBlock) ([]string, error) {
1✔
372
        _, nw, err := net.ParseCIDR(ipblock.CIDR)
1✔
373
        if err != nil {
1✔
374
                return nil, err
×
375
        }
×
376
        ips := ipam.New()
1✔
377
        ips.AddSubnet(nw)
1✔
378
        for _, except := range ipblock.Except {
2✔
379
                _, nw, err = net.ParseCIDR(except)
1✔
380
                if err != nil {
1✔
381
                        return nil, err
×
382
                }
×
383
                ips.RemoveSubnet(nw)
1✔
384
        }
385
        var subnets []string
1✔
386
        for _, r := range ips.FreeList {
2✔
387
                ipnets := ipam.Range2Cidr(r.Start, r.End)
1✔
388
                for _, n := range ipnets {
2✔
389
                        subnets = append(subnets, n.String())
1✔
390
                }
1✔
391
        }
392
        return subnets, nil
1✔
393
}
394

395
func parseCIDR(sub string) *net.IPNet {
1✔
396
        _, netw, err := net.ParseCIDR(sub)
1✔
397
        if err == nil {
2✔
398
                return netw
1✔
399
        }
1✔
400
        ip := net.ParseIP(sub)
1✔
401
        if ip == nil {
1✔
402
                return nil
×
403
        }
×
404
        var mask net.IPMask
1✔
405
        if ip.To4() != nil {
2✔
406
                mask = net.CIDRMask(32, 32)
1✔
407
        } else if ip.To16() != nil {
3✔
408
                mask = net.CIDRMask(128, 128)
1✔
409
        } else {
1✔
410
                return nil
×
411
        }
×
412
        return &net.IPNet{
1✔
413
                IP:   ip,
1✔
414
                Mask: mask,
1✔
415
        }
1✔
416
}
417

418
func netEqual(a net.IPNet, b net.IPNet) bool {
1✔
419
        return a.IP.Equal(b.IP) && bytes.Equal(a.Mask, b.Mask)
1✔
420
}
1✔
421

422
func (cont *AciController) updateIpIndexEntry(index cidranger.Ranger,
423
        subnetStr string, key string, add bool) bool {
1✔
424

1✔
425
        net := parseCIDR(subnetStr)
1✔
426
        if net == nil {
1✔
427
                cont.log.WithFields(logrus.Fields{
×
428
                        "subnet": subnetStr,
×
429
                        "netpol": key,
×
430
                }).Warning("Invalid subnet or IP")
×
431
        }
×
432

433
        entries, err := index.CoveredNetworks(*net)
1✔
434
        if err != nil {
1✔
435
                cont.log.Error("Corrupted subnet index: ", err)
×
436
                return false
×
437
        }
×
438
        if add {
2✔
439
                for _, entryObj := range entries {
2✔
440
                        if netEqual(entryObj.Network(), *net) {
2✔
441
                                entry := entryObj.(*ipIndexEntry)
1✔
442
                                existing := entry.keys[key]
1✔
443
                                entry.keys[key] = true
1✔
444
                                return !existing
1✔
445
                        }
1✔
446
                }
447

448
                entry := &ipIndexEntry{
1✔
449
                        ipNet: *net,
1✔
450
                        keys: map[string]bool{
1✔
451
                                key: true,
1✔
452
                        },
1✔
453
                }
1✔
454
                index.Insert(entry)
1✔
455
                return true
1✔
456
        } else {
1✔
457
                var existing bool
1✔
458
                for _, entryObj := range entries {
2✔
459
                        entry := entryObj.(*ipIndexEntry)
1✔
460
                        if entry.keys[key] {
2✔
461
                                existing = true
1✔
462
                                delete(entry.keys, key)
1✔
463
                        }
1✔
464
                        if len(entry.keys) == 0 {
2✔
465
                                index.Remove(entry.Network())
1✔
466
                        }
1✔
467
                }
468
                return existing
1✔
469
        }
470
}
471

472
func (cont *AciController) updateIpIndex(index cidranger.Ranger,
473
        oldSubnets map[string]bool, newSubnets map[string]bool, key string) {
1✔
474

1✔
475
        for subStr := range oldSubnets {
2✔
476
                if newSubnets[subStr] {
2✔
477
                        continue
1✔
478
                }
479
                cont.updateIpIndexEntry(index, subStr, key, false)
1✔
480
        }
481
        for subStr := range newSubnets {
2✔
482
                if oldSubnets[subStr] {
2✔
483
                        continue
1✔
484
                }
485
                cont.updateIpIndexEntry(index, subStr, key, true)
1✔
486
        }
487
}
488

489
func (cont *AciController) updateTargetPortIndex(service bool, key string,
490
        oldPorts map[string]targetPort, newPorts map[string]targetPort) {
1✔
491
        for portkey := range oldPorts {
2✔
492
                if _, ok := newPorts[portkey]; ok {
1✔
493
                        continue
×
494
                }
495

496
                entry, ok := cont.targetPortIndex[portkey]
1✔
497
                if !ok {
1✔
498
                        continue
×
499
                }
500

501
                if service {
1✔
502
                        delete(entry.serviceKeys, key)
×
503
                } else {
1✔
504
                        delete(entry.networkPolicyKeys, key)
1✔
505
                }
1✔
506
                if len(entry.serviceKeys) == 0 && len(entry.networkPolicyKeys) == 0 {
2✔
507
                        delete(cont.targetPortIndex, portkey)
1✔
508
                }
1✔
509
        }
510
        for portkey, port := range newPorts {
2✔
511
                if _, ok := oldPorts[portkey]; ok {
1✔
512
                        continue
×
513
                }
514
                entry := cont.targetPortIndex[portkey]
1✔
515
                if entry == nil {
2✔
516
                        entry = &portIndexEntry{
1✔
517
                                port:              port,
1✔
518
                                serviceKeys:       make(map[string]bool),
1✔
519
                                networkPolicyKeys: make(map[string]bool),
1✔
520
                        }
1✔
521
                        cont.targetPortIndex[portkey] = entry
1✔
522
                } else {
2✔
523
                        entry.port.ports = port.ports
1✔
524
                }
1✔
525

526
                if service {
2✔
527
                        entry.serviceKeys[key] = true
1✔
528
                } else {
2✔
529
                        entry.networkPolicyKeys[key] = true
1✔
530
                }
1✔
531
        }
532
}
533
func (cont *AciController) getPortNumsFromPortName(podKeys []string, portName string) []int {
1✔
534
        var ports []int
1✔
535
        portmap := make(map[int]bool)
1✔
536
        for _, podkey := range podKeys {
2✔
537
                podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
538
                if exists && err == nil {
2✔
539
                        pod := podobj.(*v1.Pod)
1✔
540
                        port, err := k8util.LookupContainerPortNumberByName(*pod, portName)
1✔
541
                        if err != nil {
1✔
542
                                continue
×
543
                        }
544
                        if _, ok := portmap[int(port)]; !ok {
2✔
545
                                ports = append(ports, int(port))
1✔
546
                                portmap[int(port)] = true
1✔
547
                        }
1✔
548
                }
549
        }
550
        if len(ports) == 0 {
2✔
551
                cont.log.Infof("No matching portnumbers for portname %s: ", portName)
1✔
552
        }
1✔
553
        cont.log.Debug("PortName: ", portName, "Mapping port numbers: ", ports)
1✔
554
        return ports
1✔
555
}
556

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

612
func (cont *AciController) getPeerRemoteSubnets(peers []v1net.NetworkPolicyPeer,
613
        namespace string, peerPods []*v1.Pod, peerNs map[string]*v1.Namespace,
614
        logger *logrus.Entry) ([]string, map[string]bool) {
1✔
615

1✔
616
        var remoteSubnets []string
1✔
617
        subnetMap := make(map[string]bool)
1✔
618
        if len(peers) > 0 {
2✔
619
                // only applies to matching pods
1✔
620
                for _, pod := range peerPods {
2✔
621
                        for _, peer := range peers {
2✔
622
                                if ns, ok := peerNs[pod.ObjectMeta.Namespace]; ok &&
1✔
623
                                        cont.peerMatchesPod(namespace,
1✔
624
                                                &peer, pod, ns) {
2✔
625
                                        podIps := ipsForPod(pod)
1✔
626
                                        for _, ip := range podIps {
2✔
627
                                                if _, exists := subnetMap[ip]; !exists {
2✔
628
                                                        subnetMap[ip] = true
1✔
629
                                                        remoteSubnets = append(remoteSubnets, ip)
1✔
630
                                                }
1✔
631
                                        }
632
                                }
633
                        }
634
                }
635
                for _, peer := range peers {
2✔
636
                        if peer.IPBlock == nil {
2✔
637
                                continue
1✔
638
                        }
639
                        subs, err := ipBlockToSubnets(peer.IPBlock)
1✔
640
                        if err != nil {
1✔
641
                                logger.Warning("Invalid IPBlock in network policy rule: ", err)
×
642
                        } else {
1✔
643
                                for _, subnet := range subs {
2✔
644
                                        subnetMap[subnet] = true
1✔
645
                                }
1✔
646
                                remoteSubnets = append(remoteSubnets, subs...)
1✔
647
                        }
648
                }
649
        }
650
        sort.Strings(remoteSubnets)
1✔
651
        return remoteSubnets, subnetMap
1✔
652
}
653

654
func buildNetPolSubjRule(subj apicapi.ApicObject, ruleName string,
655
        direction string, ethertype string, proto string, port string,
656
        remoteSubnets []string) {
1✔
657
        ruleNameWithEtherType := fmt.Sprintf("%s-%s", ruleName, ethertype)
1✔
658
        rule := apicapi.NewHostprotRule(subj.GetDn(), ruleNameWithEtherType)
1✔
659
        rule.SetAttr("direction", direction)
1✔
660
        rule.SetAttr("ethertype", ethertype)
1✔
661
        if proto != "" {
2✔
662
                rule.SetAttr("protocol", proto)
1✔
663
        }
1✔
664
        for _, subnetStr := range remoteSubnets {
2✔
665
                _, subnet, err := net.ParseCIDR(subnetStr)
1✔
666
                if err == nil && subnet != nil {
2✔
667

1✔
668
                        // subnetStr is a valid CIDR notation, check its IP version and add the subnet to the rule
1✔
669
                        if (ethertype == "ipv4" && subnet.IP.To4() != nil) || (ethertype == "ipv6" && subnet.IP.To4() == nil) {
2✔
670
                                rule.AddChild(apicapi.NewHostprotRemoteIp(rule.GetDn(), subnetStr))
1✔
671
                        }
1✔
672
                } else if ip := net.ParseIP(subnetStr); ip != nil {
2✔
673
                        if ethertype == "ipv6" && (ip.To16() != nil && ip.To4() == nil) || ethertype == "ipv4" && ip.To4() != nil {
2✔
674
                                rule.AddChild(apicapi.NewHostprotRemoteIp(rule.GetDn(), subnetStr))
1✔
675
                        }
1✔
676
                }
677
        }
678
        if port != "" {
2✔
679
                rule.SetAttr("toPort", port)
1✔
680
        }
1✔
681

682
        subj.AddChild(rule)
1✔
683
}
684

685
func (cont *AciController) buildNetPolSubjRules(ruleName string,
686
        subj apicapi.ApicObject, direction string, peers []v1net.NetworkPolicyPeer,
687
        remoteSubnets []string, ports []v1net.NetworkPolicyPort,
688
        logger *logrus.Entry, npKey string, np *v1net.NetworkPolicy) {
1✔
689
        if len(peers) > 0 && len(remoteSubnets) == 0 {
2✔
690
                // nonempty From matches no pods or IPBlocks; don't
1✔
691
                // create the rule
1✔
692
                return
1✔
693
        }
1✔
694
        if len(ports) == 0 {
2✔
695
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
696
                        buildNetPolSubjRule(subj, ruleName, direction,
1✔
697
                                "ipv4", "", "", remoteSubnets)
1✔
698
                }
1✔
699
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
700
                        buildNetPolSubjRule(subj, ruleName, direction,
1✔
701
                                "ipv6", "", "", remoteSubnets)
1✔
702
                }
1✔
703
        } else {
1✔
704
                for j, p := range ports {
2✔
705
                        proto := portProto(p.Protocol)
1✔
706
                        var ports []string
1✔
707

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

749
func (cont *AciController) getPortNums(port *v1net.NetworkPolicyPort) []int {
1✔
750
        portkey := portKey(port)
1✔
751
        cont.indexMutex.Lock()
1✔
752
        defer cont.indexMutex.Unlock()
1✔
753
        cont.log.Debug("PortKey1: ", portkey)
1✔
754
        entry, _ := cont.targetPortIndex[portkey]
1✔
755
        var length int
1✔
756
        if entry == nil || len(entry.port.ports) == 0 {
2✔
757
                return []int{}
1✔
758
        }
1✔
759
        length = len(entry.port.ports)
1✔
760
        ports := make([]int, length)
1✔
761
        if entry != nil {
2✔
762
                copy(ports, entry.port.ports)
1✔
763
        }
1✔
764
        return ports
1✔
765
}
766
func portProto(protocol *v1.Protocol) string {
1✔
767
        proto := "tcp"
1✔
768
        if protocol != nil && *protocol == v1.ProtocolUDP {
2✔
769
                proto = "udp"
1✔
770
        } else if protocol != nil && *protocol == v1.ProtocolSCTP {
3✔
771
                proto = "sctp"
1✔
772
        }
1✔
773
        return proto
1✔
774
}
775

776
func portKey(p *v1net.NetworkPolicyPort) string {
1✔
777
        portType := ""
1✔
778
        port := ""
1✔
779
        if p != nil && p.Port != nil {
2✔
780
                if p.Port.Type == intstr.Int {
2✔
781
                        portType = "num"
1✔
782
                } else {
2✔
783
                        portType = "name"
1✔
784
                }
1✔
785
                port = p.Port.String()
1✔
786
                return portProto(p.Protocol) + "-" + portType + "-" + port
1✔
787
        }
788
        return ""
1✔
789
}
790

791
func checkEndpoints(subnetIndex cidranger.Ranger,
792
        addresses []v1.EndpointAddress) bool {
1✔
793

1✔
794
        for _, addr := range addresses {
2✔
795
                ip := net.ParseIP(addr.IP)
1✔
796
                if ip == nil {
1✔
797
                        return false
×
798
                }
×
799
                contains, err := subnetIndex.Contains(ip)
1✔
800
                if err != nil || !contains {
2✔
801
                        return false
1✔
802
                }
1✔
803
        }
804

805
        return true
1✔
806
}
807
func checkEndpointslices(subnetIndex cidranger.Ranger,
808
        addresses []string) bool {
1✔
809

1✔
810
        for _, addr := range addresses {
2✔
811
                ip := net.ParseIP(addr)
1✔
812
                if ip == nil {
1✔
813
                        return false
×
814
                }
×
815
                contains, err := subnetIndex.Contains(ip)
1✔
816
                if err != nil || !contains {
2✔
817
                        return false
1✔
818
                }
1✔
819
        }
820
        return true
1✔
821
}
822

823
type portRemoteSubnet struct {
824
        port           *v1net.NetworkPolicyPort
825
        subnetMap      map[string]bool
826
        hasNamedTarget bool
827
}
828

829
func updatePortRemoteSubnets(portRemoteSubs map[string]*portRemoteSubnet,
830
        portkey string, port *v1net.NetworkPolicyPort, subnetMap map[string]bool,
831
        hasNamedTarget bool) {
1✔
832

1✔
833
        if prs, ok := portRemoteSubs[portkey]; ok {
1✔
834
                for s := range subnetMap {
×
835
                        prs.subnetMap[s] = true
×
836
                }
×
837
                prs.hasNamedTarget = hasNamedTarget || prs.hasNamedTarget
×
838
        } else {
1✔
839
                portRemoteSubs[portkey] = &portRemoteSubnet{
1✔
840
                        port:           port,
1✔
841
                        subnetMap:      subnetMap,
1✔
842
                        hasNamedTarget: hasNamedTarget,
1✔
843
                }
1✔
844
        }
1✔
845
}
846

847
func portServiceAugmentKey(proto string, port string) string {
1✔
848
        return proto + "-" + port
1✔
849
}
1✔
850

851
type portServiceAugment struct {
852
        proto string
853
        port  string
854
        ipMap map[string]bool
855
}
856

857
func updateServiceAugment(portAugments map[string]*portServiceAugment,
858
        proto string, port string, ip string) {
1✔
859
        key := portServiceAugmentKey(proto, port)
1✔
860
        if psa, ok := portAugments[key]; ok {
1✔
861
                psa.ipMap[ip] = true
×
862
        } else {
1✔
863
                portAugments[key] = &portServiceAugment{
1✔
864
                        proto: proto,
1✔
865
                        port:  port,
1✔
866
                        ipMap: map[string]bool{ip: true},
1✔
867
                }
1✔
868
        }
1✔
869
}
870

871
func updateServiceAugmentForService(portAugments map[string]*portServiceAugment,
872
        proto string, port string, service *v1.Service) {
1✔
873

1✔
874
        if service.Spec.ClusterIP != "" {
2✔
875
                updateServiceAugment(portAugments,
1✔
876
                        proto, port, service.Spec.ClusterIP)
1✔
877
        }
1✔
878
        for _, ig := range service.Status.LoadBalancer.Ingress {
1✔
879
                if ig.IP == "" {
×
880
                        continue
×
881
                }
882
                updateServiceAugment(portAugments,
×
883
                        proto, port, ig.IP)
×
884
        }
885

886
}
887

888
// build service augment by matching peers against the endpoints ip
889
// index
890
func (cont *AciController) getServiceAugmentBySubnet(subj apicapi.ApicObject,
891
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
892
        logger *logrus.Entry) {
1✔
893

1✔
894
        matchedServices := make(map[string]bool)
1✔
895
        subnetIndex := cidranger.NewPCTrieRanger()
1✔
896

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

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

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

940
// build service augment by matching against services with a given
941
// target port
942
func (cont *AciController) getServiceAugmentByPort(subj apicapi.ApicObject,
943
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
944
        logger *logrus.Entry) {
1✔
945

1✔
946
        // nil port means it matches against all ports.  If we're here, it
1✔
947
        // means this is a rule that matches all ports with all
1✔
948
        // destinations, so there's no need to augment anything.
1✔
949
        if prs.port == nil ||
1✔
950
                prs.port.Port == nil {
2✔
951
                return
1✔
952
        }
1✔
953

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

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

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

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

1009
// The egress NetworkPolicy API were designed with the iptables
1010
// implementation in mind and don't contemplate that the layer 4 load
1011
// balancer could happen separately from the policy.  In particular,
1012
// it expects load balancer operations to be applied before the policy
1013
// is applied in both directions, so network policies would apply only
1014
// to pods and not to service IPs. This presents a problem for egress
1015
// policies on ACI since the security groups are applied before load
1016
// balancer operations when egressing, and after when ingressing.
1017
//
1018
// To solve this problem, we use some indexes to discover situations
1019
// when an egress policy covers all the endpoints associated with a
1020
// particular service, and automatically add a rule that allows egress
1021
// to the corresponding service cluster IP and ports.
1022
//
1023
// Note that this differs slightly from the behavior you'd see if you
1024
// applied the load balancer rule first: If the egress policy allows
1025
// access to a subset of the allowed IPs you'd see random failures
1026
// depending on which destination is chosen, while with this approach
1027
// it's all or nothing.  This should not impact any correctly-written
1028
// network policies.
1029
//
1030
// To do this, we work first from the set of pods and subnets matches
1031
// by the egress policy.  We use this to find using the
1032
// endpointsIpIndex all services that contain at least one of the
1033
// matched pods or subnets.  For each of these candidate services, we
1034
// find service ports for which _all_ referenced endpoints are allowed
1035
// by the egress policy.  Note that a service will have the service
1036
// port and the target port; the NetworkPolicy (confusingly) refers to
1037
// the target port.
1038
//
1039
// Once confirmed matches are found, we augment the egress policy with
1040
// extra rules to allow egress to the service IPs and service ports.
1041
//
1042
// As a special case, for rules that match everything, we also have a
1043
// backup index that works through ports which should allow more
1044
// efficient matching when allowing egress to all.
1045
func (cont *AciController) buildServiceAugment(subj apicapi.ApicObject,
1046
        portRemoteSubs map[string]*portRemoteSubnet, logger *logrus.Entry) {
1✔
1047

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(subj, prs, portAugments, logger)
1✔
1053
                } else {
2✔
1054
                        cont.getServiceAugmentBySubnet(subj, 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
                        buildNetPolSubjRule(subj,
1✔
1073
                                "service_"+augment.proto+"_"+augment.port,
1✔
1074
                                "egress", "ipv4", augment.proto, augment.port, remoteIpsv4)
1✔
1075
                }
1✔
1076
                if len(remoteIpsv6) > 0 {
2✔
1077
                        buildNetPolSubjRule(subj,
1✔
1078
                                "service_"+augment.proto+"_"+augment.port,
1✔
1079
                                "egress", "ipv6", augment.proto, augment.port, remoteIpsv6)
1✔
1080
                }
1✔
1081
        }
1082
}
1083

1084
func (cont *AciController) handleNetPolUpdate(np *v1net.NetworkPolicy) bool {
1✔
1085
        key, err := cache.MetaNamespaceKeyFunc(np)
1✔
1086
        logger := networkPolicyLogger(cont.log, np)
1✔
1087
        if err != nil {
1✔
1088
                logger.Error("Could not create network policy key: ", err)
×
1089
                return false
×
1090
        }
×
1091

1092
        peerPodKeys := cont.netPolIngressPods.GetPodForObj(key)
1✔
1093
        peerPodKeys =
1✔
1094
                append(peerPodKeys, cont.netPolEgressPods.GetPodForObj(key)...)
1✔
1095
        var peerPods []*v1.Pod
1✔
1096
        peerNs := make(map[string]*v1.Namespace)
1✔
1097
        for _, podkey := range peerPodKeys {
2✔
1098
                podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
1099
                if exists && err == nil {
2✔
1100
                        pod := podobj.(*v1.Pod)
1✔
1101
                        if _, nsok := peerNs[pod.ObjectMeta.Namespace]; !nsok {
2✔
1102
                                nsobj, exists, err :=
1✔
1103
                                        cont.namespaceIndexer.GetByKey(pod.ObjectMeta.Namespace)
1✔
1104
                                if !exists || err != nil {
1✔
1105
                                        continue
×
1106
                                }
1107
                                peerNs[pod.ObjectMeta.Namespace] = nsobj.(*v1.Namespace)
1✔
1108
                        }
1109
                        peerPods = append(peerPods, pod)
1✔
1110
                }
1111
        }
1112
        ptypeset := make(map[v1net.PolicyType]bool)
1✔
1113
        for _, t := range np.Spec.PolicyTypes {
2✔
1114
                ptypeset[t] = true
1✔
1115
        }
1✔
1116
        var labelKey string
1✔
1117

1✔
1118
        if cont.config.HppOptimization {
2✔
1119
                hash, err := util.CreateHashFromNetPol(np)
1✔
1120
                if err != nil {
1✔
1121
                        logger.Error("Could not create hash from network policy: ", err)
×
1122
                        return false
×
1123
                }
×
1124
                labelKey = cont.aciNameForKey("np", hash)
1✔
1125
        } else {
1✔
1126
                labelKey = cont.aciNameForKey("np", key)
1✔
1127
        }
1✔
1128
        hpp := apicapi.NewHostprotPol(cont.config.AciPolicyTenant, labelKey)
1✔
1129
        // Generate ingress policies
1✔
1130
        if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeIngress] {
2✔
1131
                subjIngress :=
1✔
1132
                        apicapi.NewHostprotSubj(hpp.GetDn(), "networkpolicy-ingress")
1✔
1133

1✔
1134
                for i, ingress := range np.Spec.Ingress {
2✔
1135
                        remoteSubnets, _ := cont.getPeerRemoteSubnets(ingress.From,
1✔
1136
                                np.Namespace, peerPods, peerNs, logger)
1✔
1137
                        cont.buildNetPolSubjRules(strconv.Itoa(i), subjIngress,
1✔
1138
                                "ingress", ingress.From, remoteSubnets, ingress.Ports, logger, key, np)
1✔
1139
                }
1✔
1140
                hpp.AddChild(subjIngress)
1✔
1141
        }
1142
        // Generate egress policies
1143
        if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeEgress] {
2✔
1144
                subjEgress :=
1✔
1145
                        apicapi.NewHostprotSubj(hpp.GetDn(), "networkpolicy-egress")
1✔
1146

1✔
1147
                portRemoteSubs := make(map[string]*portRemoteSubnet)
1✔
1148

1✔
1149
                for i, egress := range np.Spec.Egress {
2✔
1150
                        remoteSubnets, subnetMap := cont.getPeerRemoteSubnets(egress.To,
1✔
1151
                                np.Namespace, peerPods, peerNs, logger)
1✔
1152
                        cont.buildNetPolSubjRules(strconv.Itoa(i), subjEgress,
1✔
1153
                                "egress", egress.To, remoteSubnets, egress.Ports, logger, key, np)
1✔
1154

1✔
1155
                        // creating a rule to egress to all on a given port needs
1✔
1156
                        // to enable access to any service IPs/ports that have
1✔
1157
                        // that port as their target port.
1✔
1158
                        if len(egress.To) == 0 {
2✔
1159
                                subnetMap = map[string]bool{
1✔
1160
                                        "0.0.0.0/0": true,
1✔
1161
                                }
1✔
1162
                        }
1✔
1163
                        for _, p := range egress.Ports {
2✔
1164
                                portkey := portKey(&p)
1✔
1165
                                port := p
1✔
1166
                                updatePortRemoteSubnets(portRemoteSubs, portkey, &port, subnetMap,
1✔
1167
                                        p.Port != nil && p.Port.Type == intstr.Int)
1✔
1168
                        }
1✔
1169
                        if len(egress.Ports) == 0 {
2✔
1170
                                updatePortRemoteSubnets(portRemoteSubs, "", nil, subnetMap,
1✔
1171
                                        false)
1✔
1172
                        }
1✔
1173
                }
1174
                cont.buildServiceAugment(subjEgress, portRemoteSubs, logger)
1✔
1175
                hpp.AddChild(subjEgress)
1✔
1176
        }
1177
        if cont.config.HppOptimization {
2✔
1178
                cont.addToHppCache(labelKey, key, apicapi.ApicSlice{hpp})
1✔
1179
        }
1✔
1180
        cont.apicConn.WriteApicObjects(labelKey, apicapi.ApicSlice{hpp})
1✔
1181
        return false
1✔
1182
}
1183

1184
func (cont *AciController) addToHppCache(labelKey string, key string, hpp apicapi.ApicSlice) {
1✔
1185
        cont.indexMutex.Lock()
1✔
1186
        hppRef, ok := cont.hppRef[labelKey]
1✔
1187
        if ok {
2✔
1188
                var found bool
1✔
1189
                for _, npkey := range hppRef.Npkeys {
2✔
1190
                        if npkey == key {
2✔
1191
                                found = true
1✔
1192
                                break
1✔
1193
                        }
1194
                }
1195
                if !found {
1✔
1196
                        hppRef.RefCount++
×
1197
                        hppRef.Npkeys = append(hppRef.Npkeys, key)
×
1198
                }
×
1199
                hppRef.HppObj = hpp
1✔
1200
                cont.hppRef[labelKey] = hppRef
1✔
1201
        } else {
1✔
1202
                var newHppRef hppReference
1✔
1203
                newHppRef.RefCount++
1✔
1204
                newHppRef.HppObj = hpp
1✔
1205
                newHppRef.Npkeys = append(newHppRef.Npkeys, key)
1✔
1206
                cont.hppRef[labelKey] = newHppRef
1✔
1207
        }
1✔
1208
        cont.indexMutex.Unlock()
1✔
1209
}
1210

1211
func (cont *AciController) removeFromHppCache(np *v1net.NetworkPolicy, key string) (string, bool) {
×
1212
        var labelKey string
×
1213
        var noRef bool
×
1214
        hash, err := util.CreateHashFromNetPol(np)
×
1215
        if err != nil {
×
1216
                cont.log.Error("Could not create hash from network policy: ", err)
×
1217
                cont.log.Error("Failed to remove np from hpp cache")
×
1218
                return labelKey, noRef
×
1219
        }
×
1220
        labelKey = cont.aciNameForKey("np", hash)
×
1221
        cont.indexMutex.Lock()
×
1222
        hppRef, ok := cont.hppRef[labelKey]
×
1223
        if ok {
×
1224
                for i, npkey := range hppRef.Npkeys {
×
1225
                        if npkey == key {
×
1226
                                hppRef.Npkeys = append(hppRef.Npkeys[:i], hppRef.Npkeys[i+1:]...)
×
1227
                                hppRef.RefCount--
×
1228
                                break
×
1229
                        }
1230
                }
1231
                if hppRef.RefCount > 0 {
×
1232
                        cont.hppRef[labelKey] = hppRef
×
1233
                } else {
×
1234
                        delete(cont.hppRef, labelKey)
×
1235
                        noRef = true
×
1236
                }
×
1237
        }
1238
        cont.indexMutex.Unlock()
×
1239
        return labelKey, noRef
×
1240

1241
}
1242

1243
func getNetworkPolicyEgressIpBlocks(np *v1net.NetworkPolicy) map[string]bool {
1✔
1244
        subnets := make(map[string]bool)
1✔
1245

1✔
1246
        for _, egress := range np.Spec.Egress {
2✔
1247
                for _, to := range egress.To {
2✔
1248
                        if to.IPBlock != nil && to.IPBlock.CIDR != "" {
2✔
1249
                                subnets[to.IPBlock.CIDR] = true
1✔
1250
                        }
1✔
1251
                }
1252
        }
1253
        return subnets
1✔
1254
}
1255

1256
func (cont *AciController) networkPolicyAdded(obj interface{}) {
1✔
1257
        np := obj.(*v1net.NetworkPolicy)
1✔
1258
        npkey, err := cache.MetaNamespaceKeyFunc(np)
1✔
1259
        if err != nil {
1✔
1260
                networkPolicyLogger(cont.log, np).
×
1261
                        Error("Could not create network policy key: ", err)
×
1262
                return
×
1263
        }
×
1264
        cont.writeApicNP(npkey, np)
1✔
1265
        cont.netPolPods.UpdateSelectorObj(obj)
1✔
1266
        cont.netPolIngressPods.UpdateSelectorObj(obj)
1✔
1267
        cont.netPolEgressPods.UpdateSelectorObj(obj)
1✔
1268
        cont.indexMutex.Lock()
1✔
1269
        subnets := getNetworkPolicyEgressIpBlocks(np)
1✔
1270
        cont.updateIpIndex(cont.netPolSubnetIndex, nil, subnets, npkey)
1✔
1271

1✔
1272
        ports := cont.getNetPolTargetPorts(np)
1✔
1273
        cont.updateTargetPortIndex(false, npkey, nil, ports)
1✔
1274
        if isNamedPortPresenInNp(np) {
2✔
1275
                cont.nmPortNp[npkey] = true
1✔
1276
        }
1✔
1277
        cont.indexMutex.Unlock()
1✔
1278
        cont.queueNetPolUpdateByKey(npkey)
1✔
1279
}
1280

1281
func (cont *AciController) writeApicNP(npKey string, np *v1net.NetworkPolicy) {
1✔
1282
        if cont.config.LBType == lbTypeAci {
2✔
1283
                return
1✔
1284
        }
1✔
1285

1286
        npObj := apicapi.NewVmmInjectedNwPol(cont.vmmDomainProvider(),
×
1287
                cont.config.AciVmmDomain, cont.config.AciVmmController,
×
1288
                np.ObjectMeta.Namespace, np.ObjectMeta.Name)
×
1289
        setAttr := func(name, attr string) {
×
1290
                if attr != "" {
×
1291
                        npObj.SetAttr(name, attr)
×
1292
                }
×
1293
        }
1294
        setAttr("ingress", ingressStr(np))
×
1295
        setAttr("egress", egressStr(np))
×
1296
        key := cont.aciNameForKey("NwPol", npKey)
×
1297
        cont.log.Debugf("Writing %s %+v", key, npObj)
×
1298
        cont.apicConn.WriteApicObjects(key, apicapi.ApicSlice{npObj})
×
1299
}
1300

1301
func labelSelectorToStr(labelsel *metav1.LabelSelector) string {
×
1302
        var str string
×
1303
        if labelsel != nil {
×
1304
                str = "["
×
1305
                for key, val := range labelsel.MatchLabels {
×
1306
                        keyval := key + "_" + val
×
1307
                        str += keyval
×
1308
                }
×
1309
                for _, expressions := range labelsel.MatchExpressions {
×
1310
                        str += expressions.Key
×
1311
                        str += string(expressions.Operator)
×
1312
                        for _, values := range expressions.Values {
×
1313
                                str += values
×
1314
                        }
×
1315
                }
1316
                str += "]"
×
1317
        }
1318
        return str
×
1319
}
1320

1321
func selectorsToStr(peers []v1net.NetworkPolicyPeer, ns string) string {
×
1322
        var str string
×
1323
        for _, p := range peers {
×
1324
                podSel := labelSelectorToStr(p.PodSelector)
×
1325
                str += podSel
×
1326
                nsSel := labelSelectorToStr(p.NamespaceSelector)
×
1327
                if podSel != "" && nsSel == "" {
×
1328
                        str += ns
×
1329
                } else {
×
1330
                        str += nsSel
×
1331
                }
×
1332
        }
1333
        return str
×
1334
}
1335

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

1352
        pStr = strings.TrimSuffix(pStr, "+")
×
1353
        pStr += "]"
×
1354
        return pStr
×
1355
}
1356

1357
func portsToStr(ports []v1net.NetworkPolicyPort) string {
×
1358
        pStr := "["
×
1359

×
1360
        for _, p := range ports {
×
1361
                if p.Protocol != nil {
×
1362
                        pStr += string(*p.Protocol)
×
1363
                }
×
1364
                if p.Port != nil {
×
1365
                        pStr += ":" + p.Port.String()
×
1366
                }
×
1367
                pStr += "+"
×
1368
        }
1369

1370
        pStr = strings.TrimSuffix(pStr, "+")
×
1371
        pStr += "]"
×
1372
        return pStr
×
1373
}
1374

1375
func egressStrSorted(np *v1net.NetworkPolicy) string {
×
1376
        eStr := ""
×
1377
        for _, rule := range np.Spec.Egress {
×
1378
                eStr += selectorsToStr(rule.To, np.Namespace)
×
1379
                eStr += peersToStr(rule.To)
×
1380
                eStr += portsToStr(rule.Ports)
×
1381
                eStr += "+"
×
1382
        }
×
1383
        eStr = strings.TrimSuffix(eStr, "+")
×
1384
        return eStr
×
1385
}
1386

1387
func ingressStrSorted(np *v1net.NetworkPolicy) string {
×
1388
        iStr := ""
×
1389
        for _, rule := range np.Spec.Ingress {
×
1390
                iStr += selectorsToStr(rule.From, np.Namespace)
×
1391
                iStr += peersToStr(rule.From)
×
1392
                iStr += portsToStr(rule.Ports)
×
1393
                iStr += "+"
×
1394
        }
×
1395
        iStr = strings.TrimSuffix(iStr, "+")
×
1396
        return iStr
×
1397
}
1398

1399
func sortPolicyTypes(pType []v1net.PolicyType) []string {
×
1400
        var strPolicyTypes []string
×
1401
        for _, pt := range pType {
×
1402
                strPolicyTypes = append(strPolicyTypes, string(pt))
×
1403
        }
×
1404
        sort.Slice(strPolicyTypes, func(i, j int) bool {
×
1405
                return strPolicyTypes[i] < strPolicyTypes[j]
×
1406
        })
×
1407
        return strPolicyTypes
×
1408
}
1409

1410
func ingressStr(np *v1net.NetworkPolicy) string {
×
1411
        iStr := ""
×
1412
        for _, rule := range np.Spec.Ingress {
×
1413
                iStr += peersToStr(rule.From)
×
1414
                iStr += ":" + portsToStr(rule.Ports)
×
1415
                iStr += "+"
×
1416
        }
×
1417
        iStr = strings.TrimSuffix(iStr, "+")
×
1418
        return iStr
×
1419
}
1420

1421
func egressStr(np *v1net.NetworkPolicy) string {
×
1422
        eStr := ""
×
1423
        for _, rule := range np.Spec.Egress {
×
1424
                eStr += peersToStr(rule.To)
×
1425
                eStr += ":" + portsToStr(rule.Ports)
×
1426
                eStr += "+"
×
1427
        }
×
1428
        eStr = strings.TrimSuffix(eStr, "+")
×
1429
        return eStr
×
1430
}
1431

1432
func (cont *AciController) networkPolicyChanged(oldobj interface{},
1433
        newobj interface{}) {
×
1434

×
1435
        oldnp := oldobj.(*v1net.NetworkPolicy)
×
1436
        newnp := newobj.(*v1net.NetworkPolicy)
×
1437
        npkey, err := cache.MetaNamespaceKeyFunc(newnp)
×
1438
        if err != nil {
×
1439
                networkPolicyLogger(cont.log, newnp).
×
1440
                        Error("Could not create network policy key: ", err)
×
1441
                return
×
1442
        }
×
1443

1444
        if cont.config.HppOptimization {
×
1445
                cont.removeFromHppCache(oldnp, npkey)
×
1446
        }
×
1447

1448
        cont.writeApicNP(npkey, newnp)
×
1449
        cont.indexMutex.Lock()
×
1450
        oldSubnets := getNetworkPolicyEgressIpBlocks(oldnp)
×
1451
        newSubnets := getNetworkPolicyEgressIpBlocks(newnp)
×
1452
        cont.updateIpIndex(cont.netPolSubnetIndex, oldSubnets, newSubnets, npkey)
×
1453

×
1454
        oldPorts := cont.getNetPolTargetPorts(oldnp)
×
1455
        newPorts := cont.getNetPolTargetPorts(newnp)
×
1456
        cont.updateTargetPortIndex(false, npkey, oldPorts, newPorts)
×
1457
        cont.indexMutex.Unlock()
×
1458

×
1459
        if !reflect.DeepEqual(oldnp.Spec.PodSelector, newnp.Spec.PodSelector) {
×
1460
                cont.netPolPods.UpdateSelectorObjNoCallback(newobj)
×
1461
        }
×
1462
        if !reflect.DeepEqual(oldnp.Spec.PolicyTypes, newnp.Spec.PolicyTypes) {
×
1463
                peerPodKeys := cont.netPolPods.GetPodForObj(npkey)
×
1464
                for _, podkey := range peerPodKeys {
×
1465
                        cont.podQueue.Add(podkey)
×
1466
                }
×
1467
        }
1468
        var queue bool
×
1469
        if !reflect.DeepEqual(oldnp.Spec.Ingress, newnp.Spec.Ingress) {
×
1470
                cont.netPolIngressPods.UpdateSelectorObjNoCallback(newobj)
×
1471
                queue = true
×
1472
        }
×
1473
        if !reflect.DeepEqual(oldnp.Spec.Egress, newnp.Spec.Egress) {
×
1474
                cont.netPolEgressPods.UpdateSelectorObjNoCallback(newobj)
×
1475
                queue = true
×
1476
        }
×
1477
        if queue {
×
1478
                cont.queueNetPolUpdateByKey(npkey)
×
1479
        }
×
1480
}
1481

1482
func (cont *AciController) networkPolicyDeleted(obj interface{}) {
1✔
1483
        np, isNetworkpolicy := obj.(*v1net.NetworkPolicy)
1✔
1484
        if !isNetworkpolicy {
1✔
1485
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
×
1486
                if !ok {
×
1487
                        networkPolicyLogger(cont.log, np).
×
1488
                                Error("Received unexpected object: ", obj)
×
1489
                        return
×
1490
                }
×
1491
                np, ok = deletedState.Obj.(*v1net.NetworkPolicy)
×
1492
                if !ok {
×
1493
                        networkPolicyLogger(cont.log, np).
×
1494
                                Error("DeletedFinalStateUnknown contained non-Networkpolicy object: ", deletedState.Obj)
×
1495
                        return
×
1496
                }
×
1497
        }
1498
        npkey, err := cache.MetaNamespaceKeyFunc(np)
1✔
1499
        if err != nil {
1✔
1500
                networkPolicyLogger(cont.log, np).
×
1501
                        Error("Could not create network policy key: ", err)
×
1502
                return
×
1503
        }
×
1504

1505
        if cont.config.LBType != lbTypeAci {
1✔
1506
                cont.apicConn.ClearApicObjects(cont.aciNameForKey("NwPol", npkey))
×
1507
        }
×
1508

1509
        var labelKey string
1✔
1510
        var noHppRef bool
1✔
1511
        if cont.config.HppOptimization {
1✔
1512
                labelKey, noHppRef = cont.removeFromHppCache(np, npkey)
×
1513
        } else {
1✔
1514
                labelKey = cont.aciNameForKey("np", npkey)
1✔
1515
                noHppRef = true
1✔
1516
        }
1✔
1517

1518
        cont.indexMutex.Lock()
1✔
1519
        subnets := getNetworkPolicyEgressIpBlocks(np)
1✔
1520
        cont.updateIpIndex(cont.netPolSubnetIndex, subnets, nil, npkey)
1✔
1521

1✔
1522
        ports := cont.getNetPolTargetPorts(np)
1✔
1523
        cont.updateTargetPortIndex(false, npkey, ports, nil)
1✔
1524
        if isNamedPortPresenInNp(np) {
2✔
1525
                delete(cont.nmPortNp, npkey)
1✔
1526
        }
1✔
1527
        cont.indexMutex.Unlock()
1✔
1528

1✔
1529
        cont.netPolPods.DeleteSelectorObj(obj)
1✔
1530
        cont.netPolIngressPods.DeleteSelectorObj(obj)
1✔
1531
        cont.netPolEgressPods.DeleteSelectorObj(obj)
1✔
1532
        if noHppRef && labelKey != "" {
2✔
1533
                cont.apicConn.ClearApicObjects(labelKey)
1✔
1534
        }
1✔
1535
}
1536

1537
func (sep *serviceEndpoint) SetNpServiceAugmentForService(servicekey string, service *v1.Service, prs *portRemoteSubnet,
1538
        portAugments map[string]*portServiceAugment, subnetIndex cidranger.Ranger, logger *logrus.Entry) {
1✔
1539
        cont := sep.cont
1✔
1540
        endpointsobj, _, err := cont.endpointsIndexer.GetByKey(servicekey)
1✔
1541
        if err != nil {
1✔
1542
                logger.Error("Could not lookup endpoints for "+
×
1543
                        servicekey+": ", err.Error())
×
1544
                return
×
1545
        }
×
1546
        if endpointsobj == nil {
1✔
1547
                return
×
1548
        }
×
1549
        endpoints := endpointsobj.(*v1.Endpoints)
1✔
1550
        portstrings := make(map[string]bool)
1✔
1551
        ports := cont.getPortNums(prs.port)
1✔
1552
        for _, port := range ports {
2✔
1553
                portstrings[strconv.Itoa(port)] = true
1✔
1554
        }
1✔
1555
        for _, svcPort := range service.Spec.Ports {
2✔
1556
                _, ok := portstrings[svcPort.TargetPort.String()]
1✔
1557
                if prs.port != nil &&
1✔
1558
                        (svcPort.Protocol != *prs.port.Protocol || !ok) {
1✔
1559
                        // egress rule does not match service target port
×
1560
                        continue
×
1561
                }
1562
                for _, subset := range endpoints.Subsets {
2✔
1563
                        var foundEpPort *v1.EndpointPort
1✔
1564
                        for _, endpointPort := range subset.Ports {
2✔
1565
                                if endpointPort.Name == svcPort.Name ||
1✔
1566
                                        (len(service.Spec.Ports) == 1 &&
1✔
1567
                                                endpointPort.Name == "") {
2✔
1568
                                        foundEpPort = &endpointPort
1✔
1569
                                        break
1✔
1570
                                }
1571
                        }
1572
                        if foundEpPort == nil {
1✔
1573
                                continue
×
1574
                        }
1575

1576
                        incomplete := false
1✔
1577
                        incomplete = incomplete ||
1✔
1578
                                !checkEndpoints(subnetIndex, subset.Addresses)
1✔
1579
                        incomplete = incomplete || !checkEndpoints(subnetIndex,
1✔
1580
                                subset.NotReadyAddresses)
1✔
1581

1✔
1582
                        if incomplete {
2✔
1583
                                continue
1✔
1584
                        }
1585

1586
                        proto := portProto(&foundEpPort.Protocol)
1✔
1587
                        port := strconv.Itoa(int(svcPort.Port))
1✔
1588
                        updateServiceAugmentForService(portAugments,
1✔
1589
                                proto, port, service)
1✔
1590

1✔
1591
                        logger.WithFields(logrus.Fields{
1✔
1592
                                "proto":   proto,
1✔
1593
                                "port":    port,
1✔
1594
                                "service": servicekey,
1✔
1595
                        }).Debug("Allowing egress for service by subnet match")
1✔
1596
                }
1597
        }
1598
}
1599

1600
func (seps *serviceEndpointSlice) SetNpServiceAugmentForService(servicekey string, service *v1.Service,
1601
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
1602
        subnetIndex cidranger.Ranger, logger *logrus.Entry) {
1✔
1603
        cont := seps.cont
1✔
1604
        portstrings := make(map[string]bool)
1✔
1605
        ports := cont.getPortNums(prs.port)
1✔
1606
        for _, port := range ports {
2✔
1607
                portstrings[strconv.Itoa(port)] = true
1✔
1608
        }
1✔
1609
        label := map[string]string{"kubernetes.io/service-name": service.ObjectMeta.Name}
1✔
1610
        selector := labels.SelectorFromSet(labels.Set(label))
1✔
1611
        cache.ListAllByNamespace(cont.endpointSliceIndexer, service.ObjectMeta.Namespace, selector,
1✔
1612
                func(endpointSliceobj interface{}) {
2✔
1613
                        endpointSlices := endpointSliceobj.(*discovery.EndpointSlice)
1✔
1614
                        for _, svcPort := range service.Spec.Ports {
2✔
1615
                                _, ok := portstrings[svcPort.TargetPort.String()]
1✔
1616
                                if prs.port != nil &&
1✔
1617
                                        (svcPort.Protocol != *prs.port.Protocol || !ok) {
2✔
1618
                                        // egress rule does not match service target port
1✔
1619
                                        continue
1✔
1620
                                }
1621
                                var foundEpPort *discovery.EndpointPort
1✔
1622
                                for _, endpointPort := range endpointSlices.Ports {
2✔
1623
                                        if *endpointPort.Name == svcPort.Name ||
1✔
1624
                                                (len(service.Spec.Ports) == 1 &&
1✔
1625
                                                        *endpointPort.Name == "") {
2✔
1626
                                                foundEpPort = &endpointPort
1✔
1627
                                                cont.log.Debug("Found EpPort: ", foundEpPort)
1✔
1628
                                                break
1✔
1629
                                        }
1630
                                }
1631
                                if foundEpPort == nil {
1✔
1632
                                        return
×
1633
                                }
×
1634
                                // @FIXME for non ready address
1635
                                incomplete := false
1✔
1636
                                for _, endpoint := range endpointSlices.Endpoints {
2✔
1637
                                        incomplete = incomplete || !checkEndpointslices(subnetIndex, endpoint.Addresses)
1✔
1638
                                }
1✔
1639
                                if incomplete {
2✔
1640
                                        continue
1✔
1641
                                }
1642
                                proto := portProto(foundEpPort.Protocol)
1✔
1643
                                port := strconv.Itoa(int(svcPort.Port))
1✔
1644
                                cont.log.Debug("updateServiceAugmentForService: ", service)
1✔
1645
                                updateServiceAugmentForService(portAugments,
1✔
1646
                                        proto, port, service)
1✔
1647

1✔
1648
                                logger.WithFields(logrus.Fields{
1✔
1649
                                        "proto":   proto,
1✔
1650
                                        "port":    port,
1✔
1651
                                        "service": servicekey,
1✔
1652
                                }).Debug("Allowing egress for service by subnet match")
1✔
1653
                        }
1654
                })
1655
}
1656

1657
func isNamedPortPresenInNp(np *v1net.NetworkPolicy) bool {
1✔
1658
        for _, egress := range np.Spec.Egress {
2✔
1659
                for _, p := range egress.Ports {
2✔
1660
                        if p.Port.Type == intstr.String {
2✔
1661
                                return true
1✔
1662
                        }
1✔
1663
                }
1664
        }
1665
        return false
1✔
1666
}
1667

1668
func (cont *AciController) checkPodNmpMatchesNp(npkey, podkey string) bool {
1✔
1669
        podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
1670
        if err != nil {
1✔
1671
                return false
×
1672
        }
×
1673
        if !exists || podobj == nil {
1✔
1674
                return false
×
1675
        }
×
1676
        pod := podobj.(*v1.Pod)
1✔
1677
        npobj, npexists, nperr := cont.networkPolicyIndexer.GetByKey(npkey)
1✔
1678
        if npexists && nperr == nil && npobj != nil {
2✔
1679
                np := npobj.(*v1net.NetworkPolicy)
1✔
1680
                for _, egress := range np.Spec.Egress {
2✔
1681
                        for _, p := range egress.Ports {
2✔
1682
                                if p.Port.Type == intstr.String {
2✔
1683
                                        _, err := k8util.LookupContainerPortNumberByName(*pod, p.Port.String())
1✔
1684
                                        if err == nil {
2✔
1685
                                                return true
1✔
1686
                                        }
1✔
1687
                                }
1688
                        }
1689
                }
1690
        }
1691
        return false
1✔
1692
}
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