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

noironetworks / aci-containers / 9880

13 Sep 2024 07:20AM UTC coverage: 69.912% (+0.02%) from 69.89%
9880

Pull #1396

travis-pro

web-flow
Merge c8926ac9f into 47ac39ec3
Pull Request #1396: Do not use cachedEpgDns to filter out fvRsDomAtt

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

3 existing lines in 2 files now uncovered.

13098 of 18735 relevant lines covered (69.91%)

0.8 hits per line

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

79.87
/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
        "context"
23
        "fmt"
24
        "net"
25
        "os"
26
        "reflect"
27
        "slices"
28
        "sort"
29
        "strconv"
30
        "strings"
31

32
        "github.com/sirupsen/logrus"
33
        "github.com/yl2chen/cidranger"
34

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

46
        "github.com/noironetworks/aci-containers/pkg/apicapi"
47
        hppv1 "github.com/noironetworks/aci-containers/pkg/hpp/apis/aci.hpp/v1"
48
        hppclset "github.com/noironetworks/aci-containers/pkg/hpp/clientset/versioned"
49
        "github.com/noironetworks/aci-containers/pkg/index"
50
        "github.com/noironetworks/aci-containers/pkg/ipam"
51
        "github.com/noironetworks/aci-containers/pkg/util"
52
        discovery "k8s.io/api/discovery/v1"
53
)
54

55
func (cont *AciController) initNetworkPolicyInformerFromClient(
56
        kubeClient kubernetes.Interface) {
×
57
        cont.initNetworkPolicyInformerBase(
×
58
                cache.NewListWatchFromClient(
×
59
                        kubeClient.NetworkingV1().RESTClient(), "networkpolicies",
×
60
                        metav1.NamespaceAll, fields.Everything()))
×
61
}
×
62

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

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

101
                switch {
1✔
102
                case peer.PodSelector != nil && peer.NamespaceSelector != nil:
1✔
103
                        ret = append(ret, index.PodSelector{
1✔
104
                                NsSelector:  nsselector,
1✔
105
                                PodSelector: podselector,
1✔
106
                        })
1✔
107
                case peer.PodSelector != nil:
1✔
108
                        ret = append(ret, index.PodSelector{
1✔
109
                                Namespace:   &np.ObjectMeta.Namespace,
1✔
110
                                PodSelector: podselector,
1✔
111
                        })
1✔
112
                case peer.NamespaceSelector != nil:
1✔
113
                        ret = append(ret, index.PodSelector{
1✔
114
                                NsSelector:  nsselector,
1✔
115
                                PodSelector: labels.Everything(),
1✔
116
                        })
1✔
117
                }
118
        }
119
        return ret
1✔
120
}
121

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

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

129
        return ret
1✔
130
}
131

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

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

139
        return ret
1✔
140
}
141

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

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

186
        remipupdate := func(pod *v1.Pod, deleted bool) {
2✔
187
                cont.queueRemoteIpConUpdate(pod, deleted)
1✔
188
        }
1✔
189

190
        cont.netPolIngressPods.SetObjUpdateCallback(npupdate)
1✔
191
        cont.netPolIngressPods.SetRemIpUpdateCallback(remipupdate)
1✔
192
        cont.netPolIngressPods.SetPodHashFunc(nphash)
1✔
193
        cont.netPolEgressPods.SetObjUpdateCallback(npupdate)
1✔
194
        cont.netPolEgressPods.SetRemIpUpdateCallback(remipupdate)
1✔
195
        cont.netPolEgressPods.SetPodHashFunc(nphash)
1✔
196
}
197

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

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

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

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

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

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

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

304
func (cont *AciController) getHppClient() (hppclset.Interface, bool) {
1✔
305
        env := cont.env.(*K8sEnvironment)
1✔
306
        hppcl := env.hppClient
1✔
307
        if hppcl == nil {
2✔
308
                cont.log.Error("hpp client not found")
1✔
309
                return nil, false
1✔
310
        }
1✔
311
        return hppcl, true
1✔
312
}
313

314
func (cont *AciController) createHostprotPol(hpp *hppv1.HostprotPol, ns string) bool {
1✔
315
        hppcl, ok := cont.getHppClient()
1✔
316
        if !ok {
2✔
317
                return false
1✔
318
        }
1✔
319

320
        cont.log.Debug("Creating HPP CR: ", hpp)
1✔
321
        _, err := hppcl.AciV1().HostprotPols(ns).Create(context.TODO(), hpp, metav1.CreateOptions{})
1✔
322
        if err != nil {
1✔
323
                cont.log.Error("Error creating HPP CR: ", err)
×
324
                return false
×
325
        }
×
326

327
        return true
1✔
328
}
329

330
func (cont *AciController) updateHostprotPol(hpp *hppv1.HostprotPol, ns string) bool {
1✔
331
        hppcl, ok := cont.getHppClient()
1✔
332
        if !ok {
2✔
333
                return false
1✔
334
        }
1✔
335

336
        cont.log.Debug("Updating HPP CR: ", hpp)
1✔
337
        _, err := hppcl.AciV1().HostprotPols(ns).Update(context.TODO(), hpp, metav1.UpdateOptions{})
1✔
338
        if err != nil {
1✔
339
                cont.log.Error("Error updating HPP CR: ", err)
×
340
                return false
×
341
        }
×
342

343
        return true
1✔
344
}
345

346
func (cont *AciController) deleteHostprotPol(hppName string, ns string) bool {
1✔
347
        hppcl, ok := cont.getHppClient()
1✔
348
        if !ok {
2✔
349
                return false
1✔
350
        }
1✔
351

352
        cont.log.Debug("Deleting HPP CR: ", hppName)
1✔
353
        err := hppcl.AciV1().HostprotPols(ns).Delete(context.TODO(), hppName, metav1.DeleteOptions{})
1✔
354
        if err != nil {
1✔
355
                cont.log.Error("Error deleting HPP CR: ", err)
×
356
                return false
×
357
        }
×
358

359
        return true
1✔
360
}
361

362
func (cont *AciController) getHostprotPol(hppName string, ns string) (*hppv1.HostprotPol, error) {
1✔
363
        hppcl, ok := cont.getHppClient()
1✔
364
        if !ok {
2✔
365
                return nil, fmt.Errorf("hpp client not found")
1✔
366
        }
1✔
367

368
        hpp, err := hppcl.AciV1().HostprotPols(ns).Get(context.TODO(), hppName, metav1.GetOptions{})
1✔
369
        if err != nil {
2✔
370
                return nil, err
1✔
371
        }
1✔
372
        cont.log.Debug("HPP CR found: ", hpp)
1✔
373
        return hpp, nil
1✔
374
}
375

376
func (cont *AciController) getHostprotRemoteIpContainer(name, ns string) (*hppv1.HostprotRemoteIpContainer, error) {
1✔
377
        hppcl, ok := cont.getHppClient()
1✔
378
        if !ok {
2✔
379
                return nil, fmt.Errorf("hpp client not found")
1✔
380
        }
1✔
381

382
        hpp, err := hppcl.AciV1().HostprotRemoteIpContainers(ns).Get(context.TODO(), name, metav1.GetOptions{})
1✔
383
        if err != nil {
2✔
384
                cont.log.Error("Error getting HostprotRemoteIpContainers CR: ", err)
1✔
385
                return nil, err
1✔
386
        }
1✔
387
        cont.log.Debug("HostprotRemoteIpContainers CR found: ", hpp)
1✔
388
        return hpp, nil
1✔
389
}
390

391
func (cont *AciController) createHostprotRemoteIpContainer(hppIpCont *hppv1.HostprotRemoteIpContainer, ns string) bool {
1✔
392
        hppcl, ok := cont.getHppClient()
1✔
393
        if !ok {
2✔
394
                return false
1✔
395
        }
1✔
396

397
        cont.log.Debug("Creating HostprotRemoteIpContainer CR: ", hppIpCont)
1✔
398
        _, err := hppcl.AciV1().HostprotRemoteIpContainers(ns).Create(context.TODO(), hppIpCont, metav1.CreateOptions{})
1✔
399
        if err != nil {
1✔
400
                cont.log.Error("Error creating HostprotRemoteIpContainer CR: ", err)
×
401
                return false
×
402
        }
×
403

404
        return true
1✔
405
}
406

407
func (cont *AciController) updateHostprotRemoteIpContainer(hppIpCont *hppv1.HostprotRemoteIpContainer, ns string) bool {
1✔
408
        hppcl, ok := cont.getHppClient()
1✔
409
        if !ok {
2✔
410
                return false
1✔
411
        }
1✔
412

413
        cont.log.Debug("Updating HostprotRemoteIpContainer CR: ", hppIpCont)
1✔
414
        _, err := hppcl.AciV1().HostprotRemoteIpContainers(ns).Update(context.TODO(), hppIpCont, metav1.UpdateOptions{})
1✔
415
        if err != nil {
1✔
416
                cont.log.Error("Error updating HostprotRemoteIpContainer CR: ", err)
×
417
                return false
×
418
        }
×
419

420
        return true
1✔
421
}
422

423
func (cont *AciController) deleteHostprotRemoteIpContainer(hppIpContName string, ns string) bool {
1✔
424
        hppcl, ok := cont.getHppClient()
1✔
425
        if !ok {
2✔
426
                return false
1✔
427
        }
1✔
428

429
        cont.log.Debug("Deleting HostprotRemoteIpContainer CR: ", hppIpContName)
1✔
430
        err := hppcl.AciV1().HostprotRemoteIpContainers(ns).Delete(context.TODO(), hppIpContName, metav1.DeleteOptions{})
1✔
431
        if err != nil {
1✔
432
                cont.log.Error("Error deleting HostprotRemoteIpContainer CR: ", err)
×
433
                return false
×
434
        }
×
435

436
        return true
1✔
437
}
438

439
func (cont *AciController) listHostprotPol(ns string) (*hppv1.HostprotPolList, error) {
1✔
440
        hppcl, ok := cont.getHppClient()
1✔
441
        if !ok {
1✔
442
                return nil, fmt.Errorf("hpp client not found")
×
443
        }
×
444

445
        hpps, err := hppcl.AciV1().HostprotPols(ns).List(context.TODO(), metav1.ListOptions{})
1✔
446
        if err != nil {
2✔
447
                cont.log.Error("Error listing HPP CR: ", err)
1✔
448
                return nil, err
1✔
449
        }
1✔
450
        return hpps, nil
×
451
}
452

453
func (cont *AciController) listHostprotRemoteIpContainers(ns string) (*hppv1.HostprotRemoteIpContainerList, error) {
1✔
454
        hppcl, ok := cont.getHppClient()
1✔
455
        if !ok {
1✔
456
                return nil, fmt.Errorf("hpp client not found")
×
457
        }
×
458

459
        hpRemoteIpConts, err := hppcl.AciV1().HostprotRemoteIpContainers(ns).List(context.TODO(), metav1.ListOptions{})
1✔
460
        if err != nil {
2✔
461
                cont.log.Error("Error getting HostprotRemoteIpContainers CRs: ", err)
1✔
462
                return nil, err
1✔
463
        }
1✔
464
        return hpRemoteIpConts, nil
×
465
}
466

467
func (cont *AciController) createStaticNetPolCrs() bool {
1✔
468
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
469

1✔
470
        createPol := func(labelKey, subjName, direction string, rules []hppv1.HostprotRule) bool {
2✔
471
                hppName := strings.ReplaceAll(labelKey, "_", "-")
1✔
472
                if _, err := cont.getHostprotPol(hppName, ns); errors.IsNotFound(err) {
2✔
473
                        hpp := &hppv1.HostprotPol{
1✔
474
                                ObjectMeta: metav1.ObjectMeta{
1✔
475
                                        Name:      hppName,
1✔
476
                                        Namespace: ns,
1✔
477
                                },
1✔
478
                                Spec: hppv1.HostprotPolSpec{
1✔
479
                                        Name:            labelKey,
1✔
480
                                        NetworkPolicies: []string{labelKey},
1✔
481
                                        HostprotSubj: []hppv1.HostprotSubj{
1✔
482
                                                {
1✔
483
                                                        Name:         subjName,
1✔
484
                                                        HostprotRule: rules,
1✔
485
                                                },
1✔
486
                                        },
1✔
487
                                },
1✔
488
                        }
1✔
489
                        if !cont.createHostprotPol(hpp, ns) {
1✔
490
                                return false
×
491
                        }
×
492
                }
493
                return true
1✔
494
        }
495

496
        if !createPol(cont.aciNameForKey("np", "static-ingress"), "ingress", "ingress", cont.getHostprotRules("ingress")) {
1✔
497
                return false
×
498
        }
×
499
        if !createPol(cont.aciNameForKey("np", "static-egress"), "egress", "egress", cont.getHostprotRules("egress")) {
1✔
500
                return false
×
501
        }
×
502
        if !createPol(cont.aciNameForKey("np", "static-discovery"), "discovery", "discovery", cont.getDiscoveryRules()) {
1✔
503
                return false
×
504
        }
×
505

506
        return true
1✔
507
}
508

509
func (cont *AciController) getHostprotRules(direction string) []hppv1.HostprotRule {
1✔
510
        var rules []hppv1.HostprotRule
1✔
511
        outbound := hppv1.HostprotRule{
1✔
512
                ConnTrack: "reflexive",
1✔
513
                Protocol:  "unspecified",
1✔
514
                FromPort:  "unspecified",
1✔
515
                ToPort:    "unspecified",
1✔
516
                Direction: direction,
1✔
517
        }
1✔
518

1✔
519
        if !cont.configuredPodNetworkIps.V6.Empty() {
1✔
520
                outbound.Name = "allow-all-reflexive-v6"
×
521
                outbound.Ethertype = "ipv6"
×
522
                rules = append(rules, outbound)
×
523
        }
×
524
        if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
525
                outbound.Name = "allow-all-reflexive"
1✔
526
                outbound.Ethertype = "ipv4"
1✔
527
                rules = append(rules, outbound)
1✔
528
        }
1✔
529

530
        return rules
1✔
531
}
532

533
func (cont *AciController) getDiscoveryRules() []hppv1.HostprotRule {
1✔
534
        rules := []hppv1.HostprotRule{
1✔
535
                {
1✔
536
                        Name:      "arp-ingress",
1✔
537
                        Direction: "ingress",
1✔
538
                        Ethertype: "arp",
1✔
539
                        ConnTrack: "normal",
1✔
540
                },
1✔
541
                {
1✔
542
                        Name:      "arp-egress",
1✔
543
                        Direction: "egress",
1✔
544
                        Ethertype: "arp",
1✔
545
                        ConnTrack: "normal",
1✔
546
                },
1✔
547
        }
1✔
548

1✔
549
        if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
550
                rules = append(rules,
1✔
551
                        hppv1.HostprotRule{
1✔
552
                                Name:      "icmp-ingress",
1✔
553
                                Direction: "ingress",
1✔
554
                                Ethertype: "ipv4",
1✔
555
                                Protocol:  "icmp",
1✔
556
                                ConnTrack: "normal",
1✔
557
                        },
1✔
558
                        hppv1.HostprotRule{
1✔
559
                                Name:      "icmp-egress",
1✔
560
                                Direction: "egress",
1✔
561
                                Ethertype: "ipv4",
1✔
562
                                Protocol:  "icmp",
1✔
563
                                ConnTrack: "normal",
1✔
564
                        },
1✔
565
                )
1✔
566
        }
1✔
567

568
        if !cont.configuredPodNetworkIps.V6.Empty() {
1✔
569
                rules = append(rules,
×
570
                        hppv1.HostprotRule{
×
571
                                Name:      "icmpv6-ingress",
×
572
                                Direction: "ingress",
×
573
                                Ethertype: "ipv6",
×
574
                                Protocol:  "icmpv6",
×
575
                                ConnTrack: "normal",
×
576
                        },
×
577
                        hppv1.HostprotRule{
×
578
                                Name:      "icmpv6-egress",
×
579
                                Direction: "egress",
×
580
                                Ethertype: "ipv6",
×
581
                                Protocol:  "icmpv6",
×
582
                                ConnTrack: "normal",
×
583
                        },
×
584
                )
×
585
        }
×
586

587
        return rules
1✔
588
}
589

590
func (cont *AciController) cleanStaleHppCrs() {
1✔
591
        sysNs := os.Getenv("SYSTEM_NAMESPACE")
1✔
592
        npNames := make(map[string]struct{})
1✔
593

1✔
594
        namespaces, err := cont.listNamespaces()
1✔
595
        if err != nil {
1✔
596
                cont.log.Error("Error listing namespaces: ", err)
×
597
                return
×
598
        }
×
599

600
        for _, ns := range namespaces.Items {
1✔
601
                netpols, err := cont.listNetworkPolicies(ns.Name)
×
602
                if err != nil {
×
603
                        cont.log.Error("Error listing network policies in namespace ", ns.Name, ": ", err)
×
604
                        continue
×
605
                }
606
                for _, np := range netpols.Items {
×
607
                        nsName := np.ObjectMeta.Namespace + "/" + np.ObjectMeta.Name
×
608
                        npNames[nsName] = struct{}{}
×
609
                }
×
610
        }
611

612
        hpps, err := cont.listHostprotPol(sysNs)
1✔
613
        if err != nil {
2✔
614
                cont.log.Error("Error listing HostprotPols: ", err)
1✔
615
                return
1✔
616
        }
1✔
617

618
        for _, hpp := range hpps.Items {
×
619
                for _, npName := range hpp.Spec.NetworkPolicies {
×
620
                        if _, exists := npNames[npName]; !exists {
×
621
                                if !cont.deleteHostprotPol(hpp.ObjectMeta.Name, sysNs) {
×
622
                                        cont.log.Error("Error deleting stale HostprotPol: ", hpp.ObjectMeta.Name)
×
623
                                }
×
624
                        }
625
                }
626
        }
627
}
628

629
func (cont *AciController) cleanStaleHostprotRemoteIpContainers() {
1✔
630
        sysNs := os.Getenv("SYSTEM_NAMESPACE")
1✔
631
        nsNames := make(map[string]struct{})
1✔
632

1✔
633
        namespaces, err := cont.listNamespaces()
1✔
634
        if err != nil {
1✔
635
                cont.log.Error("Error listing namespaces: ", err)
×
636
                return
×
637
        }
×
638

639
        for _, ns := range namespaces.Items {
1✔
640
                nsNames[ns.Name] = struct{}{}
×
641
        }
×
642

643
        hpRemIpConts, err := cont.listHostprotRemoteIpContainers(sysNs)
1✔
644
        if err != nil {
2✔
645
                cont.log.Error("Error listing HostprotRemoteIpContainers: ", err)
1✔
646
                return
1✔
647
        }
1✔
648

649
        for _, hpRemIpCont := range hpRemIpConts.Items {
×
650
                if _, exists := nsNames[hpRemIpCont.ObjectMeta.Name]; !exists {
×
651
                        if !cont.deleteHostprotRemoteIpContainer(hpRemIpCont.ObjectMeta.Name, sysNs) {
×
652
                                cont.log.Error("Error deleting stale HostprotRemoteIpContainer: ", hpRemIpCont.ObjectMeta.Name)
×
653
                        }
×
654
                }
655
        }
656
}
657

658
func (cont *AciController) initStaticNetPolObjs() {
1✔
659
        if cont.config.EnableHppDirect {
2✔
660
                cont.cleanStaleHostprotRemoteIpContainers()
1✔
661
                cont.cleanStaleHppCrs()
1✔
662

1✔
663
                if !cont.createStaticNetPolCrs() {
1✔
664
                        cont.log.Error("Error creating static HPP CRs")
×
665
                }
×
666
                return
1✔
667
        }
668

669
        cont.apicConn.WriteApicObjects(cont.config.AciPrefix+"_np_static", cont.staticNetPolObjs())
1✔
670
}
671

672
func networkPolicyLogger(log *logrus.Logger,
673
        np *v1net.NetworkPolicy) *logrus.Entry {
1✔
674
        return log.WithFields(logrus.Fields{
1✔
675
                "namespace": np.ObjectMeta.Namespace,
1✔
676
                "name":      np.ObjectMeta.Name,
1✔
677
        })
1✔
678
}
1✔
679

680
func (cont *AciController) queueNetPolUpdateByKey(key string) {
1✔
681
        cont.netPolQueue.Add(key)
1✔
682
}
1✔
683

684
func (cont *AciController) queueRemoteIpConUpdate(pod *v1.Pod, deleted bool) {
1✔
685
        cont.hppMutex.Lock()
1✔
686
        update := cont.updateNsRemoteIpCont(pod, deleted)
1✔
687
        if update {
2✔
688
                podns := pod.ObjectMeta.Namespace
1✔
689
                cont.remIpContQueue.Add(podns)
1✔
690
        }
1✔
691
        cont.hppMutex.Unlock()
1✔
692
}
693

694
func (cont *AciController) queueNetPolUpdate(netpol *v1net.NetworkPolicy) {
1✔
695
        key, err := cache.MetaNamespaceKeyFunc(netpol)
1✔
696
        if err != nil {
1✔
697
                networkPolicyLogger(cont.log, netpol).
×
698
                        Error("Could not create network policy key: ", err)
×
699
                return
×
700
        }
×
701
        cont.netPolQueue.Add(key)
1✔
702
}
703

704
func (cont *AciController) peerMatchesPod(npNs string,
705
        peer *v1net.NetworkPolicyPeer, pod *v1.Pod, podNs *v1.Namespace) bool {
1✔
706
        if peer.PodSelector != nil && npNs == pod.ObjectMeta.Namespace {
2✔
707
                selector, err :=
1✔
708
                        metav1.LabelSelectorAsSelector(peer.PodSelector)
1✔
709
                if err != nil {
1✔
710
                        cont.log.Error("Could not parse pod selector: ", err)
×
711
                } else {
1✔
712
                        return selector.Matches(labels.Set(pod.ObjectMeta.Labels))
1✔
713
                }
1✔
714
        }
715
        if peer.NamespaceSelector != nil {
2✔
716
                selector, err :=
1✔
717
                        metav1.LabelSelectorAsSelector(peer.NamespaceSelector)
1✔
718
                if err != nil {
1✔
719
                        cont.log.Error("Could not parse namespace selector: ", err)
×
720
                } else {
1✔
721
                        return selector.Matches(labels.Set(podNs.ObjectMeta.Labels))
1✔
722
                }
1✔
723
        }
724
        return false
×
725
}
726

727
func ipsForPod(pod *v1.Pod) []string {
1✔
728
        var ips []string
1✔
729
        podIPsField := reflect.ValueOf(pod.Status).FieldByName("PodIPs")
1✔
730
        if podIPsField.IsValid() {
2✔
731
                if len(pod.Status.PodIPs) > 0 {
1✔
732
                        for _, ip := range pod.Status.PodIPs {
×
733
                                ips = append(ips, ip.IP)
×
734
                        }
×
735
                        return ips
×
736
                }
737
        }
738
        if pod.Status.PodIP != "" {
2✔
739
                return []string{pod.Status.PodIP}
1✔
740
        }
1✔
741
        return nil
1✔
742
}
743

744
func ipBlockToSubnets(ipblock *v1net.IPBlock) ([]string, error) {
1✔
745
        _, nw, err := net.ParseCIDR(ipblock.CIDR)
1✔
746
        if err != nil {
1✔
747
                return nil, err
×
748
        }
×
749
        ips := ipam.New()
1✔
750
        ips.AddSubnet(nw)
1✔
751
        for _, except := range ipblock.Except {
2✔
752
                _, nw, err = net.ParseCIDR(except)
1✔
753
                if err != nil {
1✔
754
                        return nil, err
×
755
                }
×
756
                ips.RemoveSubnet(nw)
1✔
757
        }
758
        var subnets []string
1✔
759
        for _, r := range ips.FreeList {
2✔
760
                ipnets := ipam.Range2Cidr(r.Start, r.End)
1✔
761
                for _, n := range ipnets {
2✔
762
                        subnets = append(subnets, n.String())
1✔
763
                }
1✔
764
        }
765
        return subnets, nil
1✔
766
}
767

768
func parseCIDR(sub string) *net.IPNet {
1✔
769
        _, netw, err := net.ParseCIDR(sub)
1✔
770
        if err == nil {
2✔
771
                return netw
1✔
772
        }
1✔
773
        ip := net.ParseIP(sub)
1✔
774
        if ip == nil {
1✔
775
                return nil
×
776
        }
×
777
        var mask net.IPMask
1✔
778
        if ip.To4() != nil {
2✔
779
                mask = net.CIDRMask(32, 32)
1✔
780
        } else if ip.To16() != nil {
3✔
781
                mask = net.CIDRMask(128, 128)
1✔
782
        } else {
1✔
783
                return nil
×
784
        }
×
785
        return &net.IPNet{
1✔
786
                IP:   ip,
1✔
787
                Mask: mask,
1✔
788
        }
1✔
789
}
790

791
func netEqual(a, b net.IPNet) bool {
1✔
792
        return a.IP.Equal(b.IP) && bytes.Equal(a.Mask, b.Mask)
1✔
793
}
1✔
794

795
func (cont *AciController) updateIpIndexEntry(index cidranger.Ranger,
796
        subnetStr string, key string, add bool) bool {
1✔
797
        cidr := parseCIDR(subnetStr)
1✔
798
        if cidr == nil {
1✔
799
                cont.log.WithFields(logrus.Fields{
×
800
                        "subnet": subnetStr,
×
801
                        "netpol": key,
×
802
                }).Warning("Invalid subnet or IP")
×
803
                return false
×
804
        }
×
805

806
        entries, err := index.CoveredNetworks(*cidr)
1✔
807
        if err != nil {
1✔
808
                cont.log.Error("Corrupted subnet index: ", err)
×
809
                return false
×
810
        }
×
811
        if add {
2✔
812
                for _, entryObj := range entries {
2✔
813
                        if netEqual(entryObj.Network(), *cidr) {
2✔
814
                                entry := entryObj.(*ipIndexEntry)
1✔
815
                                existing := entry.keys[key]
1✔
816
                                entry.keys[key] = true
1✔
817
                                return !existing
1✔
818
                        }
1✔
819
                }
820

821
                entry := &ipIndexEntry{
1✔
822
                        ipNet: *cidr,
1✔
823
                        keys: map[string]bool{
1✔
824
                                key: true,
1✔
825
                        },
1✔
826
                }
1✔
827
                index.Insert(entry)
1✔
828
                return true
1✔
829
        } else {
1✔
830
                var existing bool
1✔
831
                for _, entryObj := range entries {
2✔
832
                        entry := entryObj.(*ipIndexEntry)
1✔
833
                        if entry.keys[key] {
2✔
834
                                existing = true
1✔
835
                                delete(entry.keys, key)
1✔
836
                        }
1✔
837
                        if len(entry.keys) == 0 {
2✔
838
                                index.Remove(entry.Network())
1✔
839
                        }
1✔
840
                }
841
                return existing
1✔
842
        }
843
}
844

845
func (cont *AciController) updateIpIndex(index cidranger.Ranger,
846
        oldSubnets map[string]bool, newSubnets map[string]bool, key string) {
1✔
847
        for subStr := range oldSubnets {
2✔
848
                if newSubnets[subStr] {
2✔
849
                        continue
1✔
850
                }
851
                cont.updateIpIndexEntry(index, subStr, key, false)
1✔
852
        }
853
        for subStr := range newSubnets {
2✔
854
                if oldSubnets[subStr] {
2✔
855
                        continue
1✔
856
                }
857
                cont.updateIpIndexEntry(index, subStr, key, true)
1✔
858
        }
859
}
860

861
func (cont *AciController) updateTargetPortIndex(service bool, key string,
862
        oldPorts map[string]targetPort, newPorts map[string]targetPort) {
1✔
863
        for portkey := range oldPorts {
2✔
864
                if _, ok := newPorts[portkey]; ok {
1✔
865
                        continue
×
866
                }
867

868
                entry, ok := cont.targetPortIndex[portkey]
1✔
869
                if !ok {
1✔
870
                        continue
×
871
                }
872

873
                if service {
1✔
874
                        delete(entry.serviceKeys, key)
×
875
                } else {
1✔
876
                        delete(entry.networkPolicyKeys, key)
1✔
877
                }
1✔
878
                if len(entry.serviceKeys) == 0 && len(entry.networkPolicyKeys) == 0 {
2✔
879
                        delete(cont.targetPortIndex, portkey)
1✔
880
                }
1✔
881
        }
882
        for portkey, port := range newPorts {
2✔
883
                if _, ok := oldPorts[portkey]; ok {
1✔
884
                        continue
×
885
                }
886
                entry := cont.targetPortIndex[portkey]
1✔
887
                if entry == nil {
2✔
888
                        entry = &portIndexEntry{
1✔
889
                                port:              port,
1✔
890
                                serviceKeys:       make(map[string]bool),
1✔
891
                                networkPolicyKeys: make(map[string]bool),
1✔
892
                        }
1✔
893
                        cont.targetPortIndex[portkey] = entry
1✔
894
                } else {
2✔
895
                        entry.port.ports = port.ports
1✔
896
                }
1✔
897

898
                if service {
2✔
899
                        entry.serviceKeys[key] = true
1✔
900
                } else {
2✔
901
                        entry.networkPolicyKeys[key] = true
1✔
902
                }
1✔
903
        }
904
}
905

906
func (cont *AciController) getPortNumsFromPortName(podKeys []string, portName string) []int {
1✔
907
        var ports []int
1✔
908
        portmap := make(map[int]bool)
1✔
909
        for _, podkey := range podKeys {
2✔
910
                podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
911
                if exists && err == nil {
2✔
912
                        pod := podobj.(*v1.Pod)
1✔
913
                        port, err := k8util.LookupContainerPortNumberByName(*pod, portName)
1✔
914
                        if err != nil {
1✔
915
                                continue
×
916
                        }
917
                        if _, ok := portmap[int(port)]; !ok {
2✔
918
                                ports = append(ports, int(port))
1✔
919
                                portmap[int(port)] = true
1✔
920
                        }
1✔
921
                }
922
        }
923
        if len(ports) == 0 {
2✔
924
                cont.log.Infof("No matching portnumbers for portname %s: ", portName)
1✔
925
        }
1✔
926
        cont.log.Debug("PortName: ", portName, "Mapping port numbers: ", ports)
1✔
927
        return ports
1✔
928
}
929

930
// get a map of target ports for egress rules that have no "To" clause
931
func (cont *AciController) getNetPolTargetPorts(np *v1net.NetworkPolicy) map[string]targetPort {
1✔
932
        ports := make(map[string]targetPort)
1✔
933
        for _, egress := range np.Spec.Egress {
2✔
934
                if len(egress.To) != 0 && !isNamedPortPresenInNp(np) {
2✔
935
                        continue
1✔
936
                }
937
                for _, port := range egress.Ports {
2✔
938
                        if port.Port == nil {
1✔
939
                                continue
×
940
                        }
941
                        proto := v1.ProtocolTCP
1✔
942
                        if port.Protocol != nil {
2✔
943
                                proto = *port.Protocol
1✔
944
                        }
1✔
945
                        npKey, _ := cache.MetaNamespaceKeyFunc(np)
1✔
946
                        var key string
1✔
947
                        var portnums []int
1✔
948
                        if port.Port.Type == intstr.Int {
2✔
949
                                key = portProto(&proto) + "-num-" + port.Port.String()
1✔
950
                                portnums = append(portnums, port.Port.IntValue())
1✔
951
                        } else {
2✔
952
                                if len(egress.To) != 0 {
2✔
953
                                        // TODO optimize this code instead going through all matching pods every time
1✔
954
                                        podKeys := cont.netPolEgressPods.GetPodForObj(npKey)
1✔
955
                                        portnums = cont.getPortNumsFromPortName(podKeys, port.Port.String())
1✔
956
                                } else {
2✔
957
                                        ctrNmpEntry, ok := cont.ctrPortNameCache[port.Port.String()]
1✔
958
                                        if ok {
2✔
959
                                                for key := range ctrNmpEntry.ctrNmpToPods {
2✔
960
                                                        val := strings.Split(key, "-")
1✔
961
                                                        if len(val) != 2 {
1✔
962
                                                                continue
×
963
                                                        }
964
                                                        if val[0] == portProto(&proto) {
2✔
965
                                                                port, _ := strconv.Atoi(val[1])
1✔
966
                                                                portnums = append(portnums, port)
1✔
967
                                                        }
1✔
968
                                                }
969
                                        }
970
                                }
971
                                if len(portnums) == 0 {
2✔
972
                                        continue
1✔
973
                                }
974
                                key = portProto(&proto) + "-name-" + port.Port.String()
1✔
975
                        }
976
                        ports[key] = targetPort{
1✔
977
                                proto: proto,
1✔
978
                                ports: portnums,
1✔
979
                        }
1✔
980
                }
981
        }
982
        return ports
1✔
983
}
984

985
type peerRemoteInfo struct {
986
        remotePods  []*v1.Pod
987
        podSelector *metav1.LabelSelector
988
}
989

990
func (cont *AciController) getPeerRemoteSubnets(peers []v1net.NetworkPolicyPeer,
991
        namespace string, peerPods []*v1.Pod, peerNs map[string]*v1.Namespace,
992
        logger *logrus.Entry) ([]string, []string, peerRemoteInfo, map[string]bool) {
1✔
993
        var remoteSubnets []string
1✔
994
        var peerremote peerRemoteInfo
1✔
995
        subnetMap := make(map[string]bool)
1✔
996
        var peerNsList []string
1✔
997
        if len(peers) > 0 {
2✔
998
                // only applies to matching pods
1✔
999
                for _, pod := range peerPods {
2✔
1000
                        for peerIx, peer := range peers {
2✔
1001
                                if ns, ok := peerNs[pod.ObjectMeta.Namespace]; ok &&
1✔
1002
                                        cont.peerMatchesPod(namespace,
1✔
1003
                                                &peers[peerIx], pod, ns) {
2✔
1004
                                        podIps := ipsForPod(pod)
1✔
1005
                                        for _, ip := range podIps {
2✔
1006
                                                if _, exists := subnetMap[ip]; !exists {
2✔
1007
                                                        subnetMap[ip] = true
1✔
1008
                                                        if cont.config.EnableHppDirect {
2✔
1009
                                                                peerremote.remotePods = append(peerremote.remotePods, pod)
1✔
1010
                                                                if !slices.Contains(peerNsList, pod.ObjectMeta.Namespace) {
2✔
1011
                                                                        peerNsList = append(peerNsList, pod.ObjectMeta.Namespace)
1✔
1012
                                                                }
1✔
1013
                                                        }
1014
                                                        remoteSubnets = append(remoteSubnets, ip)
1✔
1015
                                                }
1016
                                        }
1017
                                }
1018
                                if cont.config.EnableHppDirect && peer.PodSelector != nil {
2✔
1019
                                        peerremote.podSelector = peer.PodSelector
1✔
1020
                                }
1✔
1021
                        }
1022
                }
1023
                for _, peer := range peers {
2✔
1024
                        if peer.IPBlock == nil {
2✔
1025
                                continue
1✔
1026
                        }
1027
                        subs, err := ipBlockToSubnets(peer.IPBlock)
1✔
1028
                        if err != nil {
1✔
1029
                                logger.Warning("Invalid IPBlock in network policy rule: ", err)
×
1030
                        } else {
1✔
1031
                                for _, subnet := range subs {
2✔
1032
                                        subnetMap[subnet] = true
1✔
1033
                                }
1✔
1034
                                remoteSubnets = append(remoteSubnets, subs...)
1✔
1035
                        }
1036
                }
1037
        }
1038
        sort.Strings(remoteSubnets)
1✔
1039
        return remoteSubnets, peerNsList, peerremote, subnetMap
1✔
1040
}
1041

1042
func (cont *AciController) ipInPodSubnet(ip net.IP) bool {
×
1043
        for _, podsubnet := range cont.config.PodSubnet {
×
1044
                _, subnet, err := net.ParseCIDR(podsubnet)
×
1045
                if err == nil && subnet != nil {
×
1046
                        if subnet.Contains(ip) {
×
1047
                                return true
×
1048
                        }
×
1049
                }
1050
        }
1051
        return false
×
1052
}
1053

1054
func (cont *AciController) buildNetPolSubjRule(subj apicapi.ApicObject, ruleName,
1055
        direction, ethertype, proto, port string, remoteSubnets []string,
1056
        addPodSubnetAsRemIp bool) {
1✔
1057
        ruleNameWithEtherType := fmt.Sprintf("%s-%s", ruleName, ethertype)
1✔
1058
        rule := apicapi.NewHostprotRule(subj.GetDn(), ruleNameWithEtherType)
1✔
1059
        rule.SetAttr("direction", direction)
1✔
1060
        rule.SetAttr("ethertype", ethertype)
1✔
1061
        if proto != "" {
2✔
1062
                rule.SetAttr("protocol", proto)
1✔
1063
        }
1✔
1064

1065
        if addPodSubnetAsRemIp {
1✔
1066
                for _, podsubnet := range cont.config.PodSubnet {
×
1067
                        _, subnet, err := net.ParseCIDR(podsubnet)
×
1068
                        if err == nil && subnet != nil {
×
1069
                                if (ethertype == "ipv4" && subnet.IP.To4() != nil) || (ethertype == "ipv6" && subnet.IP.To4() == nil) {
×
1070
                                        rule.AddChild(apicapi.NewHostprotRemoteIp(rule.GetDn(), podsubnet))
×
1071
                                }
×
1072
                        }
1073
                }
1074
        }
1075
        for _, subnetStr := range remoteSubnets {
2✔
1076
                _, subnet, err := net.ParseCIDR(subnetStr)
1✔
1077
                if err == nil && subnet != nil {
2✔
1078
                        // subnetStr is a valid CIDR notation, check its IP version and add the subnet to the rule
1✔
1079
                        if (ethertype == "ipv4" && subnet.IP.To4() != nil) || (ethertype == "ipv6" && subnet.IP.To4() == nil) {
2✔
1080
                                rule.AddChild(apicapi.NewHostprotRemoteIp(rule.GetDn(), subnetStr))
1✔
1081
                        }
1✔
1082
                } else if ip := net.ParseIP(subnetStr); ip != nil {
2✔
1083
                        if addPodSubnetAsRemIp && cont.ipInPodSubnet(ip) {
1✔
1084
                                continue
×
1085
                        }
1086
                        if ethertype == "ipv6" && (ip.To16() != nil && ip.To4() == nil) || ethertype == "ipv4" && ip.To4() != nil {
2✔
1087
                                rule.AddChild(apicapi.NewHostprotRemoteIp(rule.GetDn(), subnetStr))
1✔
1088
                        }
1✔
1089
                }
1090
        }
1091
        if port != "" {
2✔
1092
                rule.SetAttr("toPort", port)
1✔
1093
        }
1✔
1094

1095
        subj.AddChild(rule)
1✔
1096
}
1097

1098
func (cont *AciController) buildLocalNetPolSubjRule(subj *hppv1.HostprotSubj, ruleName,
1099
        direction, ethertype, proto, port string, remoteNs []string,
1100
        podSelector *metav1.LabelSelector, remoteSubnets []string) {
1✔
1101
        rule := hppv1.HostprotRule{
1✔
1102
                ConnTrack: "reflexive",
1✔
1103
                Direction: "ingress",
1✔
1104
                Ethertype: "undefined",
1✔
1105
                Protocol:  "unspecified",
1✔
1106
                FromPort:  "unspecified",
1✔
1107
                ToPort:    "unspecified",
1✔
1108
        }
1✔
1109
        rule.Direction = direction
1✔
1110
        rule.Ethertype = ethertype
1✔
1111
        if proto != "" {
2✔
1112
                rule.Protocol = proto
1✔
1113
        }
1✔
1114
        rule.Name = ruleName
1✔
1115

1✔
1116
        rule.RsRemoteIpContainer = remoteNs
1✔
1117

1✔
1118
        if podSelector != nil {
2✔
1119
                filterContainer := hppv1.HostprotFilterContainer{}
1✔
1120
                for key, val := range podSelector.MatchLabels {
2✔
1121
                        filter := hppv1.HostprotFilter{
1✔
1122
                                Key: key,
1✔
1123
                        }
1✔
1124
                        filter.Values = append(filter.Values, val)
1✔
1125
                        filter.Operator = "Equals"
1✔
1126
                        filterContainer.HostprotFilter = append(filterContainer.HostprotFilter, filter)
1✔
1127
                }
1✔
1128
                for _, expressions := range podSelector.MatchExpressions {
2✔
1129
                        filter := hppv1.HostprotFilter{
1✔
1130
                                Key:      expressions.Key,
1✔
1131
                                Values:   expressions.Values,
1✔
1132
                                Operator: string(expressions.Operator),
1✔
1133
                        }
1✔
1134
                        filterContainer.HostprotFilter = append(filterContainer.HostprotFilter, filter)
1✔
1135
                }
1✔
1136
                rule.HostprotFilterContainer = filterContainer
1✔
1137
        }
1138

1139
        if port != "" {
2✔
1140
                rule.ToPort = port
1✔
1141
        }
1✔
1142

1143
        if strings.HasPrefix(ruleName, "service_") && remoteSubnets != nil {
1✔
1144
                rule.HostprotServiceRemoteIps = remoteSubnets
×
1145
        }
×
1146

1147
        subj.HostprotRule = append(subj.HostprotRule, rule)
1✔
1148
}
1149

1150
func (cont *AciController) buildNetPolSubjRules(ruleName string,
1151
        subj apicapi.ApicObject, direction string, peers []v1net.NetworkPolicyPeer,
1152
        remoteSubnets []string, ports []v1net.NetworkPolicyPort,
1153
        logger *logrus.Entry, npKey string, np *v1net.NetworkPolicy,
1154
        addPodSubnetAsRemIp bool) {
1✔
1155
        if len(peers) > 0 && len(remoteSubnets) == 0 {
2✔
1156
                // nonempty From matches no pods or IPBlocks; don't
1✔
1157
                // create the rule
1✔
1158
                return
1✔
1159
        }
1✔
1160
        if len(ports) == 0 {
2✔
1161
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
1162
                        cont.buildNetPolSubjRule(subj, ruleName, direction,
1✔
1163
                                "ipv4", "", "", remoteSubnets, addPodSubnetAsRemIp)
1✔
1164
                }
1✔
1165
                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
1166
                        cont.buildNetPolSubjRule(subj, ruleName, direction,
1✔
1167
                                "ipv6", "", "", remoteSubnets, addPodSubnetAsRemIp)
1✔
1168
                }
1✔
1169
        } else {
1✔
1170
                for j := range ports {
2✔
1171
                        proto := portProto(ports[j].Protocol)
1✔
1172
                        var portList []string
1✔
1173

1✔
1174
                        if ports[j].Port != nil {
2✔
1175
                                if ports[j].Port.Type == intstr.Int {
2✔
1176
                                        portList = append(portList, ports[j].Port.String())
1✔
1177
                                } else {
2✔
1178
                                        var portnums []int
1✔
1179
                                        if direction == "egress" {
2✔
1180
                                                portnums = append(portnums, cont.getPortNums(&ports[j])...)
1✔
1181
                                        } else {
2✔
1182
                                                // TODO need to handle empty Pod Selector
1✔
1183
                                                if reflect.DeepEqual(np.Spec.PodSelector, metav1.LabelSelector{}) {
1✔
1184
                                                        logger.Warning("Empty PodSelctor for NamedPort is not supported in ingress direction"+
×
1185
                                                                "port in network policy: ", ports[j].Port.String())
×
1186
                                                        continue
×
1187
                                                }
1188
                                                podKeys := cont.netPolPods.GetPodForObj(npKey)
1✔
1189
                                                portnums = cont.getPortNumsFromPortName(podKeys, ports[j].Port.String())
1✔
1190
                                        }
1191
                                        if len(portnums) == 0 {
2✔
1192
                                                logger.Warning("There is no matching  ports in ingress/egress direction "+
1✔
1193
                                                        "port in network policy: ", ports[j].Port.String())
1✔
1194
                                                continue
1✔
1195
                                        }
1196
                                        for _, portnum := range portnums {
2✔
1197
                                                portList = append(portList, strconv.Itoa(portnum))
1✔
1198
                                        }
1✔
1199
                                }
1200
                        }
1201
                        for i, port := range portList {
2✔
1202
                                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
1203
                                        cont.buildNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(i+j), direction,
1✔
1204
                                                "ipv4", proto, port, remoteSubnets, addPodSubnetAsRemIp)
1✔
1205
                                }
1✔
1206
                                if !cont.configuredPodNetworkIps.V6.Empty() {
2✔
1207
                                        cont.buildNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(i+j), direction,
1✔
1208
                                                "ipv6", proto, port, remoteSubnets, addPodSubnetAsRemIp)
1✔
1209
                                }
1✔
1210
                        }
1211
                        if len(portList) == 0 && proto != "" {
2✔
1212
                                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
1213
                                        cont.buildNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(j), direction,
1✔
1214
                                                "ipv4", proto, "", remoteSubnets, addPodSubnetAsRemIp)
1✔
1215
                                }
1✔
1216
                                if !cont.configuredPodNetworkIps.V6.Empty() {
1✔
1217
                                        cont.buildNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(j), direction,
×
1218
                                                "ipv6", proto, "", remoteSubnets, addPodSubnetAsRemIp)
×
1219
                                }
×
1220
                        }
1221
                }
1222
        }
1223
}
1224

1225
func (cont *AciController) buildLocalNetPolSubjRules(ruleName string,
1226
        subj *hppv1.HostprotSubj, direction string, peerNs []string,
1227
        podSelector *metav1.LabelSelector, ports []v1net.NetworkPolicyPort,
1228
        logger *logrus.Entry, npKey string, np *v1net.NetworkPolicy) {
1✔
1229
        if len(ports) == 0 {
2✔
1230
                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
1231
                        cont.buildLocalNetPolSubjRule(subj, ruleName+"-ipv4", direction,
1✔
1232
                                "ipv4", "", "", peerNs, podSelector, nil)
1✔
1233
                }
1✔
1234
                if !cont.configuredPodNetworkIps.V6.Empty() {
1✔
1235
                        cont.buildLocalNetPolSubjRule(subj, ruleName+"-ipv6", direction,
×
1236
                                "ipv6", "", "", peerNs, podSelector, nil)
×
1237
                }
×
1238
        } else {
1✔
1239
                for j := range ports {
2✔
1240
                        proto := portProto(ports[j].Protocol)
1✔
1241
                        var portList []string
1✔
1242

1✔
1243
                        if ports[j].Port != nil {
2✔
1244
                                if ports[j].Port.Type == intstr.Int {
2✔
1245
                                        portList = append(portList, ports[j].Port.String())
1✔
1246
                                } else {
1✔
1247
                                        var portnums []int
×
1248
                                        if direction == "egress" {
×
1249
                                                portnums = append(portnums, cont.getPortNums(&ports[j])...)
×
1250
                                        } else {
×
1251
                                                // TODO need to handle empty Pod Selector
×
1252
                                                if reflect.DeepEqual(np.Spec.PodSelector, metav1.LabelSelector{}) {
×
1253
                                                        logger.Warning("Empty PodSelctor for NamedPort is not supported in ingress direction"+
×
1254
                                                                "port in network policy: ", ports[j].Port.String())
×
1255
                                                        continue
×
1256
                                                }
1257
                                                podKeys := cont.netPolPods.GetPodForObj(npKey)
×
1258
                                                portnums = cont.getPortNumsFromPortName(podKeys, ports[j].Port.String())
×
1259
                                        }
1260
                                        if len(portnums) == 0 {
×
1261
                                                logger.Warning("There is no matching  ports in ingress/egress direction "+
×
1262
                                                        "port in network policy: ", ports[j].Port.String())
×
1263
                                                continue
×
1264
                                        }
1265
                                        for _, portnum := range portnums {
×
1266
                                                portList = append(portList, strconv.Itoa(portnum))
×
1267
                                        }
×
1268
                                }
1269
                        }
1270
                        for i, port := range portList {
2✔
1271
                                if !cont.configuredPodNetworkIps.V4.Empty() {
2✔
1272
                                        cont.buildLocalNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(i+j)+"-ipv4", direction,
1✔
1273
                                                "ipv4", proto, port, peerNs, podSelector, nil)
1✔
1274
                                }
1✔
1275
                                if !cont.configuredPodNetworkIps.V6.Empty() {
1✔
1276
                                        cont.buildLocalNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(i+j)+"-ipv6", direction,
×
1277
                                                "ipv6", proto, port, peerNs, podSelector, nil)
×
1278
                                }
×
1279
                        }
1280
                        if len(portList) == 0 && proto != "" {
1✔
1281
                                if !cont.configuredPodNetworkIps.V4.Empty() {
×
1282
                                        cont.buildLocalNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(j)+"-ipv4", direction,
×
1283
                                                "ipv4", proto, "", peerNs, podSelector, nil)
×
1284
                                }
×
1285
                                if !cont.configuredPodNetworkIps.V6.Empty() {
×
1286
                                        cont.buildLocalNetPolSubjRule(subj, ruleName+"_"+strconv.Itoa(j)+"-ipv6", direction,
×
1287
                                                "ipv6", proto, "", peerNs, podSelector, nil)
×
1288
                                }
×
1289
                        }
1290
                }
1291
        }
1292
}
1293

1294
func (cont *AciController) getPortNums(port *v1net.NetworkPolicyPort) []int {
1✔
1295
        portkey := portKey(port)
1✔
1296
        cont.indexMutex.Lock()
1✔
1297
        defer cont.indexMutex.Unlock()
1✔
1298
        cont.log.Debug("PortKey1: ", portkey)
1✔
1299
        entry := cont.targetPortIndex[portkey]
1✔
1300
        var length int
1✔
1301
        if entry == nil || len(entry.port.ports) == 0 {
2✔
1302
                return []int{}
1✔
1303
        }
1✔
1304
        length = len(entry.port.ports)
1✔
1305
        ports := make([]int, length)
1✔
1306
        copy(ports, entry.port.ports)
1✔
1307
        return ports
1✔
1308
}
1309
func portProto(protocol *v1.Protocol) string {
1✔
1310
        proto := "tcp"
1✔
1311
        if protocol != nil && *protocol == v1.ProtocolUDP {
2✔
1312
                proto = "udp"
1✔
1313
        } else if protocol != nil && *protocol == v1.ProtocolSCTP {
3✔
1314
                proto = "sctp"
1✔
1315
        }
1✔
1316
        return proto
1✔
1317
}
1318

1319
func portKey(p *v1net.NetworkPolicyPort) string {
1✔
1320
        portType := ""
1✔
1321
        port := ""
1✔
1322
        if p != nil && p.Port != nil {
2✔
1323
                if p.Port.Type == intstr.Int {
2✔
1324
                        portType = "num"
1✔
1325
                } else {
2✔
1326
                        portType = "name"
1✔
1327
                }
1✔
1328
                port = p.Port.String()
1✔
1329
                return portProto(p.Protocol) + "-" + portType + "-" + port
1✔
1330
        }
1331
        return ""
1✔
1332
}
1333

1334
func checkEndpoints(subnetIndex cidranger.Ranger,
1335
        addresses []v1.EndpointAddress) bool {
1✔
1336
        for _, addr := range addresses {
2✔
1337
                ip := net.ParseIP(addr.IP)
1✔
1338
                if ip == nil {
1✔
1339
                        return false
×
1340
                }
×
1341
                contains, err := subnetIndex.Contains(ip)
1✔
1342
                if err != nil || !contains {
2✔
1343
                        return false
1✔
1344
                }
1✔
1345
        }
1346

1347
        return true
1✔
1348
}
1349
func checkEndpointslices(subnetIndex cidranger.Ranger,
1350
        addresses []string) bool {
1✔
1351
        for _, addr := range addresses {
2✔
1352
                ip := net.ParseIP(addr)
1✔
1353
                if ip == nil {
1✔
1354
                        return false
×
1355
                }
×
1356
                contains, err := subnetIndex.Contains(ip)
1✔
1357
                if err != nil || !contains {
2✔
1358
                        return false
1✔
1359
                }
1✔
1360
        }
1361
        return true
1✔
1362
}
1363

1364
type portRemoteSubnet struct {
1365
        port           *v1net.NetworkPolicyPort
1366
        subnetMap      map[string]bool
1367
        hasNamedTarget bool
1368
}
1369

1370
func updatePortRemoteSubnets(portRemoteSubs map[string]*portRemoteSubnet,
1371
        portkey string, port *v1net.NetworkPolicyPort, subnetMap map[string]bool,
1372
        hasNamedTarget bool) {
1✔
1373
        if prs, ok := portRemoteSubs[portkey]; ok {
1✔
1374
                for s := range subnetMap {
×
1375
                        prs.subnetMap[s] = true
×
1376
                }
×
1377
                prs.hasNamedTarget = hasNamedTarget || prs.hasNamedTarget
×
1378
        } else {
1✔
1379
                portRemoteSubs[portkey] = &portRemoteSubnet{
1✔
1380
                        port:           port,
1✔
1381
                        subnetMap:      subnetMap,
1✔
1382
                        hasNamedTarget: hasNamedTarget,
1✔
1383
                }
1✔
1384
        }
1✔
1385
}
1386

1387
func portServiceAugmentKey(proto, port string) string {
1✔
1388
        return proto + "-" + port
1✔
1389
}
1✔
1390

1391
type portServiceAugment struct {
1392
        proto string
1393
        port  string
1394
        ipMap map[string]bool
1395
}
1396

1397
func updateServiceAugment(portAugments map[string]*portServiceAugment, proto, port, ip string) {
1✔
1398
        key := portServiceAugmentKey(proto, port)
1✔
1399
        if psa, ok := portAugments[key]; ok {
1✔
1400
                psa.ipMap[ip] = true
×
1401
        } else {
1✔
1402
                portAugments[key] = &portServiceAugment{
1✔
1403
                        proto: proto,
1✔
1404
                        port:  port,
1✔
1405
                        ipMap: map[string]bool{ip: true},
1✔
1406
                }
1✔
1407
        }
1✔
1408
}
1409

1410
func updateServiceAugmentForService(portAugments map[string]*portServiceAugment,
1411
        proto, port string, service *v1.Service) {
1✔
1412
        if service.Spec.ClusterIP != "" {
2✔
1413
                updateServiceAugment(portAugments,
1✔
1414
                        proto, port, service.Spec.ClusterIP)
1✔
1415
        }
1✔
1416
        for _, ig := range service.Status.LoadBalancer.Ingress {
1✔
1417
                if ig.IP == "" {
×
1418
                        continue
×
1419
                }
1420
                updateServiceAugment(portAugments,
×
1421
                        proto, port, ig.IP)
×
1422
        }
1423
}
1424

1425
// build service augment by matching peers against the endpoints ip
1426
// index
1427
func (cont *AciController) getServiceAugmentBySubnet(
1428
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
1429
        logger *logrus.Entry) {
1✔
1430
        matchedServices := make(map[string]bool)
1✔
1431
        subnetIndex := cidranger.NewPCTrieRanger()
1✔
1432

1✔
1433
        // find candidate service endpoints objects that include
1✔
1434
        // endpoints selected by the egress rule
1✔
1435
        cont.indexMutex.Lock()
1✔
1436
        for sub := range prs.subnetMap {
2✔
1437
                cidr := parseCIDR(sub)
1✔
1438
                if cidr == nil {
1✔
1439
                        continue
×
1440
                }
1441
                subnetIndex.Insert(cidranger.NewBasicRangerEntry(*cidr))
1✔
1442

1✔
1443
                entries, err := cont.endpointsIpIndex.CoveredNetworks(*cidr)
1✔
1444
                if err != nil {
1✔
1445
                        logger.Error("endpointsIpIndex corrupted: ", err)
×
1446
                        continue
×
1447
                }
1448
                for _, entry := range entries {
2✔
1449
                        e := entry.(*ipIndexEntry)
1✔
1450
                        for servicekey := range e.keys {
2✔
1451
                                matchedServices[servicekey] = true
1✔
1452
                        }
1✔
1453
                }
1454
        }
1455
        cont.indexMutex.Unlock()
1✔
1456

1✔
1457
        // if all endpoints are selected by egress rule, allow egress
1✔
1458
        // to the service cluster IP as well as to the endpoints
1✔
1459
        // themselves
1✔
1460
        for servicekey := range matchedServices {
2✔
1461
                serviceobj, _, err := cont.serviceIndexer.GetByKey(servicekey)
1✔
1462
                if err != nil {
1✔
1463
                        logger.Error("Could not lookup service for "+
×
1464
                                servicekey+": ", err.Error())
×
1465
                        continue
×
1466
                }
1467
                if serviceobj == nil {
1✔
1468
                        continue
×
1469
                }
1470
                service := serviceobj.(*v1.Service)
1✔
1471
                cont.serviceEndPoints.SetNpServiceAugmentForService(servicekey, service,
1✔
1472
                        prs, portAugments, subnetIndex, logger)
1✔
1473
        }
1474
}
1475

1476
// build service augment by matching against services with a given
1477
// target port
1478
func (cont *AciController) getServiceAugmentByPort(
1479
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
1480
        logger *logrus.Entry) {
1✔
1481
        // nil port means it matches against all ports.  If we're here, it
1✔
1482
        // means this is a rule that matches all ports with all
1✔
1483
        // destinations, so there's no need to augment anything.
1✔
1484
        if prs.port == nil ||
1✔
1485
                prs.port.Port == nil {
2✔
1486
                return
1✔
1487
        }
1✔
1488

1489
        portkey := portKey(prs.port)
1✔
1490
        cont.indexMutex.Lock()
1✔
1491
        entries := make(map[string]*portIndexEntry)
1✔
1492
        entry := cont.targetPortIndex[portkey]
1✔
1493
        if entry != nil && prs.port.Port.Type == intstr.String {
2✔
1494
                for _, port := range entry.port.ports {
2✔
1495
                        portstring := strconv.Itoa(port)
1✔
1496
                        key := portProto(prs.port.Protocol) + "-" + "num" + "-" + portstring
1✔
1497
                        portEntry := cont.targetPortIndex[key]
1✔
1498
                        if portEntry != nil {
2✔
1499
                                entries[portstring] = portEntry
1✔
1500
                        }
1✔
1501
                }
1502
        } else if entry != nil {
2✔
1503
                if len(entry.port.ports) > 0 {
2✔
1504
                        entries[strconv.Itoa(entry.port.ports[0])] = entry
1✔
1505
                }
1✔
1506
        }
1507
        for key, portentry := range entries {
2✔
1508
                for servicekey := range portentry.serviceKeys {
2✔
1509
                        serviceobj, _, err := cont.serviceIndexer.GetByKey(servicekey)
1✔
1510
                        if err != nil {
1✔
1511
                                logger.Error("Could not lookup service for "+
×
1512
                                        servicekey+": ", err.Error())
×
1513
                                continue
×
1514
                        }
1515
                        if serviceobj == nil {
1✔
1516
                                continue
×
1517
                        }
1518
                        service := serviceobj.(*v1.Service)
1✔
1519

1✔
1520
                        for _, svcPort := range service.Spec.Ports {
2✔
1521
                                if svcPort.Protocol != *prs.port.Protocol ||
1✔
1522
                                        svcPort.TargetPort.String() !=
1✔
1523
                                                key {
1✔
1524
                                        continue
×
1525
                                }
1526
                                proto := portProto(&svcPort.Protocol)
1✔
1527
                                port := strconv.Itoa(int(svcPort.Port))
1✔
1528

1✔
1529
                                updateServiceAugmentForService(portAugments,
1✔
1530
                                        proto, port, service)
1✔
1531

1✔
1532
                                logger.WithFields(logrus.Fields{
1✔
1533
                                        "proto":   proto,
1✔
1534
                                        "port":    port,
1✔
1535
                                        "service": servicekey,
1✔
1536
                                }).Debug("Allowing egress for service by port")
1✔
1537
                        }
1538
                }
1539
        }
1540
        cont.indexMutex.Unlock()
1✔
1541
}
1542

1543
// The egress NetworkPolicy API were designed with the iptables
1544
// implementation in mind and don't contemplate that the layer 4 load
1545
// balancer could happen separately from the policy.  In particular,
1546
// it expects load balancer operations to be applied before the policy
1547
// is applied in both directions, so network policies would apply only
1548
// to pods and not to service IPs. This presents a problem for egress
1549
// policies on ACI since the security groups are applied before load
1550
// balancer operations when egressing, and after when ingressing.
1551
//
1552
// To solve this problem, we use some indexes to discover situations
1553
// when an egress policy covers all the endpoints associated with a
1554
// particular service, and automatically add a rule that allows egress
1555
// to the corresponding service cluster IP and ports.
1556
//
1557
// Note that this differs slightly from the behavior you'd see if you
1558
// applied the load balancer rule first: If the egress policy allows
1559
// access to a subset of the allowed IPs you'd see random failures
1560
// depending on which destination is chosen, while with this approach
1561
// it's all or nothing.  This should not impact any correctly-written
1562
// network policies.
1563
//
1564
// To do this, we work first from the set of pods and subnets matches
1565
// by the egress policy.  We use this to find using the
1566
// endpointsIpIndex all services that contain at least one of the
1567
// matched pods or subnets.  For each of these candidate services, we
1568
// find service ports for which _all_ referenced endpoints are allowed
1569
// by the egress policy.  Note that a service will have the service
1570
// port and the target port; the NetworkPolicy (confusingly) refers to
1571
// the target port.
1572
//
1573
// Once confirmed matches are found, we augment the egress policy with
1574
// extra rules to allow egress to the service IPs and service ports.
1575
//
1576
// As a special case, for rules that match everything, we also have a
1577
// backup index that works through ports which should allow more
1578
// efficient matching when allowing egress to all.
1579
func (cont *AciController) buildServiceAugment(subj apicapi.ApicObject,
1580
        localsubj *hppv1.HostprotSubj,
1581
        portRemoteSubs map[string]*portRemoteSubnet, logger *logrus.Entry) {
1✔
1582
        portAugments := make(map[string]*portServiceAugment)
1✔
1583
        for _, prs := range portRemoteSubs {
2✔
1584
                // TODO ipv6
1✔
1585
                if prs.subnetMap["0.0.0.0/0"] {
2✔
1586
                        cont.getServiceAugmentByPort(prs, portAugments, logger)
1✔
1587
                } else {
2✔
1588
                        cont.getServiceAugmentBySubnet(prs, portAugments, logger)
1✔
1589
                }
1✔
1590
        }
1591
        for _, augment := range portAugments {
2✔
1592
                var remoteIpsv4 []string
1✔
1593
                var remoteIpsv6 []string
1✔
1594
                for ipstr := range augment.ipMap {
2✔
1595
                        ip := net.ParseIP(ipstr)
1✔
1596
                        if ip == nil {
1✔
1597
                                continue
×
1598
                        } else if ip.To4() != nil {
2✔
1599
                                remoteIpsv4 = append(remoteIpsv4, ipstr)
1✔
1600
                        } else if ip.To16() != nil {
3✔
1601
                                remoteIpsv6 = append(remoteIpsv6, ipstr)
1✔
1602
                        }
1✔
1603
                }
1604
                cont.log.Debug("Service Augment: ", augment)
1✔
1605
                if !cont.config.EnableHppDirect && subj != nil {
2✔
1606
                        if len(remoteIpsv4) > 0 {
2✔
1607
                                cont.buildNetPolSubjRule(subj,
1✔
1608
                                        "service_"+augment.proto+"_"+augment.port,
1✔
1609
                                        "egress", "ipv4", augment.proto, augment.port, remoteIpsv4, false)
1✔
1610
                        }
1✔
1611
                        if len(remoteIpsv6) > 0 {
2✔
1612
                                cont.buildNetPolSubjRule(subj,
1✔
1613
                                        "service_"+augment.proto+"_"+augment.port,
1✔
1614
                                        "egress", "ipv6", augment.proto, augment.port, remoteIpsv6, false)
1✔
1615
                        }
1✔
1616
                } else if cont.config.EnableHppDirect && localsubj != nil {
×
1617
                        if len(remoteIpsv4) > 0 {
×
1618
                                cont.buildLocalNetPolSubjRule(localsubj,
×
1619
                                        "service_"+augment.proto+"_"+augment.port,
×
1620
                                        "egress", "ipv4", augment.proto, augment.port, nil, nil, remoteIpsv4)
×
1621
                        }
×
1622
                        if len(remoteIpsv6) > 0 {
×
1623
                                cont.buildLocalNetPolSubjRule(localsubj,
×
1624
                                        "service_"+augment.proto+"_"+augment.port,
×
1625
                                        "egress", "ipv6", augment.proto, augment.port, nil, nil, remoteIpsv6)
×
1626
                        }
×
1627
                }
1628
        }
1629
}
1630

1631
func isAllowAllForAllNamespaces(peers []v1net.NetworkPolicyPeer) bool {
1✔
1632
        addPodSubnetAsRemIp := false
1✔
1633
        if peers != nil && len(peers) > 0 {
2✔
1634
                var emptyPodSel, emptyNsSel bool
1✔
1635
                emptyPodSel = true
1✔
1636
                for _, peer := range peers {
2✔
1637
                        // namespaceSelector: {}
1✔
1638
                        if peer.NamespaceSelector != nil && peer.NamespaceSelector.MatchLabels == nil && peer.NamespaceSelector.MatchExpressions == nil {
1✔
1639
                                emptyNsSel = true
×
1640
                        }
×
1641
                        // podSelector has some fields
1642
                        if peer.PodSelector != nil && (peer.PodSelector.MatchLabels != nil || peer.PodSelector.MatchExpressions != nil) {
2✔
1643
                                emptyPodSel = false
1✔
1644
                        }
1✔
1645
                }
1646
                if emptyNsSel && emptyPodSel {
1✔
1647
                        addPodSubnetAsRemIp = true
×
1648
                }
×
1649
        }
1650
        return addPodSubnetAsRemIp
1✔
1651
}
1652

1653
func (cont *AciController) handleRemIpContUpdate(ns string) bool {
1✔
1654
        cont.hppMutex.Lock()
1✔
1655
        defer cont.hppMutex.Unlock()
1✔
1656

1✔
1657
        sysNs := os.Getenv("SYSTEM_NAMESPACE")
1✔
1658
        aobj, err := cont.getHostprotRemoteIpContainer(ns, sysNs)
1✔
1659
        isUpdate := err == nil
1✔
1660

1✔
1661
        if err != nil && !errors.IsNotFound(err) {
1✔
1662
                cont.log.Error("Error getting HostprotRemoteIpContainers CR: ", err)
×
1663
                return true
×
1664
        }
×
1665

1666
        if !isUpdate {
2✔
1667
                aobj = &hppv1.HostprotRemoteIpContainer{
1✔
1668
                        ObjectMeta: metav1.ObjectMeta{
1✔
1669
                                Name:      ns,
1✔
1670
                                Namespace: sysNs,
1✔
1671
                        },
1✔
1672
                        Spec: hppv1.HostprotRemoteIpContainerSpec{
1✔
1673
                                Name:             ns,
1✔
1674
                                HostprotRemoteIp: []hppv1.HostprotRemoteIp{},
1✔
1675
                        },
1✔
1676
                }
1✔
1677
        } else {
1✔
1678
                cont.log.Debug("HostprotRemoteIpContainers CR already exists: ", aobj)
×
1679
        }
×
1680

1681
        remIpCont, exists := cont.nsRemoteIpCont[ns]
1✔
1682
        if !exists {
2✔
1683
                if isUpdate {
1✔
1684
                        if !cont.deleteHostprotRemoteIpContainer(ns, sysNs) {
×
1685
                                return true
×
1686
                        }
×
1687
                } else {
1✔
1688
                        cont.log.Error("Couldn't find the ns in nsRemoteIpCont cache: ", ns)
1✔
1689
                        return false
1✔
1690
                }
1✔
1691
        }
1692

1693
        aobj.Spec.HostprotRemoteIp = buildHostprotRemoteIpList(remIpCont)
1✔
1694

1✔
1695
        if isUpdate {
1✔
1696
                if !cont.updateHostprotRemoteIpContainer(aobj, sysNs) {
×
1697
                        return true
×
1698
                }
×
1699
        } else {
1✔
1700
                if !cont.createHostprotRemoteIpContainer(aobj, sysNs) {
1✔
1701
                        return true
×
1702
                }
×
1703
        }
1704

1705
        return false
1✔
1706
}
1707

1708
func buildHostprotRemoteIpList(remIpCont map[string]map[string]string) []hppv1.HostprotRemoteIp {
1✔
1709
        hostprotRemoteIpList := []hppv1.HostprotRemoteIp{}
1✔
1710

1✔
1711
        for ip, labels := range remIpCont {
2✔
1712
                remIpObj := hppv1.HostprotRemoteIp{
1✔
1713
                        Addr: ip,
1✔
1714
                }
1✔
1715
                for key, val := range labels {
2✔
1716
                        remIpObj.HppEpLabel = append(remIpObj.HppEpLabel, hppv1.HppEpLabel{
1✔
1717
                                Key:   key,
1✔
1718
                                Value: val,
1✔
1719
                        })
1✔
1720
                }
1✔
1721
                hostprotRemoteIpList = append(hostprotRemoteIpList, remIpObj)
1✔
1722
        }
1723

1724
        return hostprotRemoteIpList
1✔
1725
}
1726

1727
func (cont *AciController) deleteHppCr(np *v1net.NetworkPolicy) bool {
1✔
1728
        key, err := cache.MetaNamespaceKeyFunc(np)
1✔
1729
        logger := networkPolicyLogger(cont.log, np)
1✔
1730
        if err != nil {
1✔
1731
                logger.Error("Could not create network policy key: ", err)
×
1732
                return false
×
1733
        }
×
1734
        hash, err := util.CreateHashFromNetPol(np)
1✔
1735
        if err != nil {
1✔
1736
                logger.Error("Could not create hash from network policy: ", err)
×
1737
                return false
×
1738
        }
×
1739
        labelKey := cont.aciNameForKey("np", hash)
1✔
1740
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1741
        hppName := strings.ReplaceAll(labelKey, "_", "-")
1✔
1742
        hpp, _ := cont.getHostprotPol(hppName, ns)
1✔
1743
        if hpp == nil {
2✔
1744
                logger.Error("Could not find hostprotPol: ", hppName)
1✔
1745
                return false
1✔
1746
        }
1✔
1747
        netPols := hpp.Spec.NetworkPolicies
1✔
1748
        newNetPols := make([]string, 0)
1✔
1749
        for _, npName := range netPols {
2✔
1750
                if npName != key {
2✔
1751
                        newNetPols = append(newNetPols, npName)
1✔
1752
                }
1✔
1753
        }
1754

1755
        hpp.Spec.NetworkPolicies = newNetPols
1✔
1756

1✔
1757
        if len(newNetPols) > 0 {
2✔
1758
                return cont.updateHostprotPol(hpp, ns)
1✔
1759
        } else {
2✔
1760
                return cont.deleteHostprotPol(hppName, ns)
1✔
1761
        }
1✔
1762
}
1763

1764
func (cont *AciController) updateNodeIpsHostprotRemoteIpContainer(nodeIps map[string]bool) {
1✔
1765
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1766
        name := "nodeips"
1✔
1767

1✔
1768
        aobj, err := cont.getHostprotRemoteIpContainer(name, ns)
1✔
1769
        isUpdate := err == nil
1✔
1770

1✔
1771
        if err != nil && !errors.IsNotFound(err) {
1✔
1772
                cont.log.Error("Error getting HostprotRemoteIpContainers CR: ", err)
×
1773
                return
×
1774
        }
×
1775

1776
        if !isUpdate {
2✔
1777
                aobj = &hppv1.HostprotRemoteIpContainer{
1✔
1778
                        ObjectMeta: metav1.ObjectMeta{
1✔
1779
                                Name:      name,
1✔
1780
                                Namespace: ns,
1✔
1781
                        },
1✔
1782
                        Spec: hppv1.HostprotRemoteIpContainerSpec{
1✔
1783
                                Name:             name,
1✔
1784
                                HostprotRemoteIp: []hppv1.HostprotRemoteIp{},
1✔
1785
                        },
1✔
1786
                }
1✔
1787
        } else {
2✔
1788
                cont.log.Debug("HostprotRemoteIpContainers CR already exists: ", aobj)
1✔
1789
        }
1✔
1790

1791
        existingIps := make(map[string]bool)
1✔
1792
        for _, ip := range aobj.Spec.HostprotRemoteIp {
2✔
1793
                existingIps[ip.Addr] = true
1✔
1794
        }
1✔
1795

1796
        for ip := range nodeIps {
2✔
1797
                if !existingIps[ip] {
2✔
1798
                        aobj.Spec.HostprotRemoteIp = append(aobj.Spec.HostprotRemoteIp, hppv1.HostprotRemoteIp{Addr: ip})
1✔
1799
                }
1✔
1800
        }
1801

1802
        if isUpdate {
2✔
1803
                cont.updateHostprotRemoteIpContainer(aobj, ns)
1✔
1804
        } else {
2✔
1805
                cont.createHostprotRemoteIpContainer(aobj, ns)
1✔
1806
        }
1✔
1807
}
1808

1809
func (cont *AciController) deleteNodeIpsHostprotRemoteIpContainer(nodeIps map[string]bool) {
1✔
1810
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1811
        name := "nodeips"
1✔
1812

1✔
1813
        aobj, _ := cont.getHostprotRemoteIpContainer(name, ns)
1✔
1814
        if aobj == nil {
1✔
1815
                return
×
1816
        }
×
1817

1818
        newHostprotRemoteIps := aobj.Spec.HostprotRemoteIp[:0]
1✔
1819
        for _, hostprotRemoteIp := range aobj.Spec.HostprotRemoteIp {
2✔
1820
                if len(nodeIps) > 0 && !nodeIps[hostprotRemoteIp.Addr] {
2✔
1821
                        newHostprotRemoteIps = append(newHostprotRemoteIps, hostprotRemoteIp)
1✔
1822
                }
1✔
1823
        }
1824

1825
        aobj.Spec.HostprotRemoteIp = newHostprotRemoteIps
1✔
1826

1✔
1827
        if len(newHostprotRemoteIps) > 0 {
2✔
1828
                cont.updateHostprotRemoteIpContainer(aobj, ns)
1✔
1829
        } else {
2✔
1830
                cont.deleteHostprotRemoteIpContainer(name, ns)
1✔
1831
        }
1✔
1832
}
1833

1834
func (cont *AciController) updateNodeHostprotRemoteIpContainer(name string, nodeIps map[string]bool) {
1✔
1835
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1836

1✔
1837
        aobj, err := cont.getHostprotRemoteIpContainer(name, ns)
1✔
1838
        isUpdate := err == nil
1✔
1839

1✔
1840
        if err != nil && !errors.IsNotFound(err) {
1✔
1841
                cont.log.Error("Error getting HostprotRemoteIpContainers CR: ", err)
×
1842
                return
×
1843
        }
×
1844

1845
        if !isUpdate {
2✔
1846
                aobj = &hppv1.HostprotRemoteIpContainer{
1✔
1847
                        ObjectMeta: metav1.ObjectMeta{
1✔
1848
                                Name:      name,
1✔
1849
                                Namespace: ns,
1✔
1850
                        },
1✔
1851
                        Spec: hppv1.HostprotRemoteIpContainerSpec{
1✔
1852
                                Name:             name,
1✔
1853
                                HostprotRemoteIp: []hppv1.HostprotRemoteIp{},
1✔
1854
                        },
1✔
1855
                }
1✔
1856
        } else {
2✔
1857
                cont.log.Debug("HostprotRemoteIpContainers CR already exists: ", aobj)
1✔
1858
        }
1✔
1859

1860
        aobj.Spec.HostprotRemoteIp = make([]hppv1.HostprotRemoteIp, 0, len(nodeIps))
1✔
1861
        for ip := range nodeIps {
2✔
1862
                aobj.Spec.HostprotRemoteIp = append(aobj.Spec.HostprotRemoteIp, hppv1.HostprotRemoteIp{Addr: ip})
1✔
1863
        }
1✔
1864

1865
        if isUpdate {
2✔
1866
                cont.updateHostprotRemoteIpContainer(aobj, ns)
1✔
1867
        } else {
2✔
1868
                cont.createHostprotRemoteIpContainer(aobj, ns)
1✔
1869
        }
1✔
1870
}
1871

1872
func (cont *AciController) deleteNodeHostprotRemoteIpContainer(name string) {
1✔
1873
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1874

1✔
1875
        if _, err := cont.getHostprotRemoteIpContainer(name, ns); err == nil {
2✔
1876
                cont.deleteHostprotRemoteIpContainer(name, ns)
1✔
1877
        }
1✔
1878
}
1879

1880
func (cont *AciController) createNodeHostProtPol(name, nodeName string, nodeIps map[string]bool) {
1✔
1881
        ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
1882
        hppName := strings.ReplaceAll(name, "_", "-")
1✔
1883

1✔
1884
        hpp, err := cont.getHostprotPol(hppName, ns)
1✔
1885
        isUpdate := hpp != nil && err == nil
1✔
1886

1✔
1887
        if err != nil && !errors.IsNotFound(err) {
1✔
1888
                cont.log.Error("Error getting HPP CR: ", err)
×
1889
                return
×
1890
        }
×
1891

1892
        if !isUpdate {
1✔
1893
                hpp = &hppv1.HostprotPol{
×
1894
                        ObjectMeta: metav1.ObjectMeta{
×
1895
                                Name:      hppName,
×
1896
                                Namespace: ns,
×
1897
                        },
×
1898
                        Spec: hppv1.HostprotPolSpec{
×
1899
                                Name:            name,
×
1900
                                NetworkPolicies: []string{name},
×
1901
                                HostprotSubj:    []hppv1.HostprotSubj{},
×
1902
                        },
×
1903
                }
×
1904
        } else {
1✔
1905
                cont.log.Debug("HPP CR already exists: ", hpp)
1✔
1906
                hpp.Spec.HostprotSubj = []hppv1.HostprotSubj{}
1✔
1907
        }
1✔
1908

1909
        if len(nodeIps) > 0 {
2✔
1910
                cont.updateNodeHostprotRemoteIpContainer(nodeName, nodeIps)
1✔
1911
                cont.updateNodeIpsHostprotRemoteIpContainer(nodeIps)
1✔
1912

1✔
1913
                hostprotSubj := hppv1.HostprotSubj{
1✔
1914
                        Name: "local-node",
1✔
1915
                        HostprotRule: []hppv1.HostprotRule{
1✔
1916
                                {
1✔
1917
                                        Name:                "allow-all-egress",
1✔
1918
                                        Direction:           "egress",
1✔
1919
                                        Ethertype:           "ipv4",
1✔
1920
                                        ConnTrack:           "normal",
1✔
1921
                                        RsRemoteIpContainer: []string{nodeName},
1✔
1922
                                },
1✔
1923
                                {
1✔
1924
                                        Name:                "allow-all-ingress",
1✔
1925
                                        Direction:           "ingress",
1✔
1926
                                        Ethertype:           "ipv4",
1✔
1927
                                        ConnTrack:           "normal",
1✔
1928
                                        RsRemoteIpContainer: []string{nodeName},
1✔
1929
                                },
1✔
1930
                        },
1✔
1931
                }
1✔
1932

1✔
1933
                hpp.Spec.HostprotSubj = append(hpp.Spec.HostprotSubj, hostprotSubj)
1✔
1934
        } else {
2✔
1935
                cont.deleteNodeHostprotRemoteIpContainer(nodeName)
1✔
1936
                cont.deleteNodeIpsHostprotRemoteIpContainer(nodeIps)
1✔
1937
        }
1✔
1938

1939
        if isUpdate {
2✔
1940
                cont.updateHostprotPol(hpp, ns)
1✔
1941
        } else {
1✔
1942
                cont.createHostprotPol(hpp, ns)
×
1943
        }
×
1944
}
1945

1946
func (cont *AciController) handleNetPolUpdate(np *v1net.NetworkPolicy) bool {
1✔
1947
        if cont.config.ChainedMode {
1✔
1948
                return false
×
1949
        }
×
1950
        key, err := cache.MetaNamespaceKeyFunc(np)
1✔
1951
        logger := networkPolicyLogger(cont.log, np)
1✔
1952
        if err != nil {
1✔
1953
                logger.Error("Could not create network policy key: ", err)
×
1954
                return false
×
1955
        }
×
1956

1957
        peerPodKeys := cont.netPolIngressPods.GetPodForObj(key)
1✔
1958
        peerPodKeys =
1✔
1959
                append(peerPodKeys, cont.netPolEgressPods.GetPodForObj(key)...)
1✔
1960
        var peerPods []*v1.Pod
1✔
1961
        peerNs := make(map[string]*v1.Namespace)
1✔
1962
        for _, podkey := range peerPodKeys {
2✔
1963
                podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
1964
                if exists && err == nil {
2✔
1965
                        pod := podobj.(*v1.Pod)
1✔
1966
                        if _, nsok := peerNs[pod.ObjectMeta.Namespace]; !nsok {
2✔
1967
                                nsobj, exists, err :=
1✔
1968
                                        cont.namespaceIndexer.GetByKey(pod.ObjectMeta.Namespace)
1✔
1969
                                if !exists || err != nil {
1✔
1970
                                        continue
×
1971
                                }
1972
                                peerNs[pod.ObjectMeta.Namespace] = nsobj.(*v1.Namespace)
1✔
1973
                        }
1974
                        peerPods = append(peerPods, pod)
1✔
1975
                }
1976
        }
1977
        ptypeset := make(map[v1net.PolicyType]bool)
1✔
1978
        for _, t := range np.Spec.PolicyTypes {
2✔
1979
                ptypeset[t] = true
1✔
1980
        }
1✔
1981
        var labelKey string
1✔
1982

1✔
1983
        if !cont.config.EnableHppDirect {
2✔
1984
                if cont.config.HppOptimization {
2✔
1985
                        hash, err := util.CreateHashFromNetPol(np)
1✔
1986
                        if err != nil {
1✔
1987
                                logger.Error("Could not create hash from network policy: ", err)
×
1988
                                return false
×
1989
                        }
×
1990
                        labelKey = cont.aciNameForKey("np", hash)
1✔
1991
                } else {
1✔
1992
                        labelKey = cont.aciNameForKey("np", key)
1✔
1993
                }
1✔
1994
                hpp := apicapi.NewHostprotPol(cont.config.AciPolicyTenant, labelKey)
1✔
1995
                // Generate ingress policies
1✔
1996
                if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeIngress] {
2✔
1997
                        subjIngress :=
1✔
1998
                                apicapi.NewHostprotSubj(hpp.GetDn(), "networkpolicy-ingress")
1✔
1999

1✔
2000
                        for i, ingress := range np.Spec.Ingress {
2✔
2001
                                addPodSubnetAsRemIp := isAllowAllForAllNamespaces(ingress.From)
1✔
2002
                                remoteSubnets, _, _, _ := cont.getPeerRemoteSubnets(ingress.From,
1✔
2003
                                        np.Namespace, peerPods, peerNs, logger)
1✔
2004
                                cont.buildNetPolSubjRules(strconv.Itoa(i), subjIngress,
1✔
2005
                                        "ingress", ingress.From, remoteSubnets, ingress.Ports, logger, key, np, addPodSubnetAsRemIp)
1✔
2006
                        }
1✔
2007
                        hpp.AddChild(subjIngress)
1✔
2008
                }
2009
                // Generate egress policies
2010
                if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeEgress] {
2✔
2011
                        subjEgress :=
1✔
2012
                                apicapi.NewHostprotSubj(hpp.GetDn(), "networkpolicy-egress")
1✔
2013

1✔
2014
                        portRemoteSubs := make(map[string]*portRemoteSubnet)
1✔
2015

1✔
2016
                        for i, egress := range np.Spec.Egress {
2✔
2017
                                addPodSubnetAsRemIp := isAllowAllForAllNamespaces(egress.To)
1✔
2018
                                remoteSubnets, _, _, subnetMap := cont.getPeerRemoteSubnets(egress.To,
1✔
2019
                                        np.Namespace, peerPods, peerNs, logger)
1✔
2020
                                cont.buildNetPolSubjRules(strconv.Itoa(i), subjEgress,
1✔
2021
                                        "egress", egress.To, remoteSubnets, egress.Ports, logger, key, np, addPodSubnetAsRemIp)
1✔
2022

1✔
2023
                                // creating a rule to egress to all on a given port needs
1✔
2024
                                // to enable access to any service IPs/ports that have
1✔
2025
                                // that port as their target port.
1✔
2026
                                if len(egress.To) == 0 {
2✔
2027
                                        subnetMap = map[string]bool{
1✔
2028
                                                "0.0.0.0/0": true,
1✔
2029
                                        }
1✔
2030
                                }
1✔
2031
                                for idx := range egress.Ports {
2✔
2032
                                        port := egress.Ports[idx]
1✔
2033
                                        portkey := portKey(&port)
1✔
2034
                                        updatePortRemoteSubnets(portRemoteSubs, portkey, &port, subnetMap,
1✔
2035
                                                port.Port != nil && port.Port.Type == intstr.Int)
1✔
2036
                                }
1✔
2037
                                if len(egress.Ports) == 0 {
2✔
2038
                                        updatePortRemoteSubnets(portRemoteSubs, "", nil, subnetMap,
1✔
2039
                                                false)
1✔
2040
                                }
1✔
2041
                        }
2042
                        cont.buildServiceAugment(subjEgress, nil, portRemoteSubs, logger)
1✔
2043
                        hpp.AddChild(subjEgress)
1✔
2044
                }
2045
                if cont.config.HppOptimization {
2✔
2046
                        cont.addToHppCache(labelKey, key, apicapi.ApicSlice{hpp}, &hppv1.HostprotPol{})
1✔
2047
                }
1✔
2048
                cont.apicConn.WriteApicObjects(labelKey, apicapi.ApicSlice{hpp})
1✔
2049
        } else {
1✔
2050
                hash, err := util.CreateHashFromNetPol(np)
1✔
2051
                if err != nil {
1✔
2052
                        logger.Error("Could not create hash from network policy: ", err)
×
2053
                        return false
×
2054
                }
×
2055
                labelKey = cont.aciNameForKey("np", hash)
1✔
2056
                ns := os.Getenv("SYSTEM_NAMESPACE")
1✔
2057
                hppName := strings.ReplaceAll(labelKey, "_", "-")
1✔
2058
                hpp, err := cont.getHostprotPol(hppName, ns)
1✔
2059
                isUpdate := err == nil
1✔
2060

1✔
2061
                if err != nil && !errors.IsNotFound(err) {
1✔
2062
                        logger.Error("Error getting HPP CR: ", err)
×
2063
                        return false
×
2064
                }
×
2065

2066
                if isUpdate {
1✔
2067
                        logger.Debug("HPP CR already exists: ", hpp)
×
2068
                        if !slices.Contains(hpp.Spec.NetworkPolicies, key) {
×
2069
                                hpp.Spec.NetworkPolicies = append(hpp.Spec.NetworkPolicies, key)
×
2070
                        }
×
2071
                        hpp.Spec.HostprotSubj = nil
×
2072
                } else {
1✔
2073
                        hpp = &hppv1.HostprotPol{
1✔
2074
                                ObjectMeta: metav1.ObjectMeta{
1✔
2075
                                        Name:      hppName,
1✔
2076
                                        Namespace: ns,
1✔
2077
                                },
1✔
2078
                                Spec: hppv1.HostprotPolSpec{
1✔
2079
                                        Name:            labelKey,
1✔
2080
                                        NetworkPolicies: []string{key},
1✔
2081
                                        HostprotSubj:    nil,
1✔
2082
                                },
1✔
2083
                        }
1✔
2084
                }
1✔
2085

2086
                // Generate ingress policies
2087
                if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeIngress] {
2✔
2088
                        subjIngress := &hppv1.HostprotSubj{
1✔
2089
                                Name:         "networkpolicy-ingress",
1✔
2090
                                HostprotRule: []hppv1.HostprotRule{},
1✔
2091
                        }
1✔
2092

1✔
2093
                        for i, ingress := range np.Spec.Ingress {
2✔
2094
                                remoteSubnets, peerNsList, peerremote, _ := cont.getPeerRemoteSubnets(ingress.From,
1✔
2095
                                        np.Namespace, peerPods, peerNs, logger)
1✔
2096
                                if isAllowAllForAllNamespaces(ingress.From) {
1✔
2097
                                        peerNsList = append(peerNsList, "nodeips")
×
2098
                                }
×
2099
                                if !(len(ingress.From) > 0 && len(remoteSubnets) == 0) {
2✔
2100
                                        cont.buildLocalNetPolSubjRules(strconv.Itoa(i), subjIngress,
1✔
2101
                                                "ingress", peerNsList, peerremote.podSelector, ingress.Ports,
1✔
2102
                                                logger, key, np)
1✔
2103
                                }
1✔
2104
                        }
2105
                        hpp.Spec.HostprotSubj = append(hpp.Spec.HostprotSubj, *subjIngress)
1✔
2106
                }
2107

2108
                if np.Spec.PolicyTypes == nil || ptypeset[v1net.PolicyTypeEgress] {
2✔
2109
                        subjEgress := &hppv1.HostprotSubj{
1✔
2110
                                Name:         "networkpolicy-egress",
1✔
2111
                                HostprotRule: []hppv1.HostprotRule{},
1✔
2112
                        }
1✔
2113

1✔
2114
                        portRemoteSubs := make(map[string]*portRemoteSubnet)
1✔
2115

1✔
2116
                        for i, egress := range np.Spec.Egress {
2✔
2117
                                remoteSubnets, peerNsList, peerremote, subnetMap := cont.getPeerRemoteSubnets(egress.To,
1✔
2118
                                        np.Namespace, peerPods, peerNs, logger)
1✔
2119
                                if isAllowAllForAllNamespaces(egress.To) {
1✔
2120
                                        peerNsList = append(peerNsList, "nodeips")
×
2121
                                }
×
2122
                                if !(len(egress.To) > 0 && len(remoteSubnets) == 0) {
2✔
2123
                                        cont.buildLocalNetPolSubjRules(strconv.Itoa(i), subjEgress,
1✔
2124
                                                "egress", peerNsList, peerremote.podSelector, egress.Ports, logger, key, np)
1✔
2125
                                }
1✔
2126

2127
                                if len(egress.To) == 0 {
2✔
2128
                                        subnetMap = map[string]bool{"0.0.0.0/0": true}
1✔
2129
                                }
1✔
2130
                                for idx := range egress.Ports {
2✔
2131
                                        port := egress.Ports[idx]
1✔
2132
                                        portkey := portKey(&port)
1✔
2133
                                        updatePortRemoteSubnets(portRemoteSubs, portkey, &port, subnetMap,
1✔
2134
                                                port.Port != nil && port.Port.Type == intstr.Int)
1✔
2135
                                }
1✔
2136
                                if len(egress.Ports) == 0 {
1✔
2137
                                        updatePortRemoteSubnets(portRemoteSubs, "", nil, subnetMap,
×
2138
                                                false)
×
2139
                                }
×
2140
                        }
2141
                        cont.buildServiceAugment(nil, subjEgress, portRemoteSubs, logger)
1✔
2142
                        hpp.Spec.HostprotSubj = append(hpp.Spec.HostprotSubj, *subjEgress)
1✔
2143
                }
2144

2145
                cont.addToHppCache(labelKey, key, apicapi.ApicSlice{}, hpp)
1✔
2146

1✔
2147
                if isUpdate {
1✔
2148
                        cont.updateHostprotPol(hpp, ns)
×
2149
                } else {
1✔
2150
                        cont.createHostprotPol(hpp, ns)
1✔
2151
                }
1✔
2152
        }
2153
        return false
1✔
2154
}
2155

2156
func (cont *AciController) updateNsRemoteIpCont(pod *v1.Pod, deleted bool) bool {
1✔
2157
        podips := ipsForPod(pod)
1✔
2158
        podns := pod.ObjectMeta.Namespace
1✔
2159
        podlabels := pod.ObjectMeta.Labels
1✔
2160
        remipcont, ok := cont.nsRemoteIpCont[podns]
1✔
2161

1✔
2162
        if deleted {
2✔
2163
                if !ok {
2✔
2164
                        return true
1✔
2165
                }
1✔
2166

2167
                present := false
1✔
2168
                for _, ip := range podips {
1✔
2169
                        if _, ipok := remipcont[ip]; ipok {
×
2170
                                delete(remipcont, ip)
×
2171
                                present = true
×
2172
                        }
×
2173
                }
2174

2175
                if len(remipcont) < 1 {
1✔
2176
                        delete(cont.nsRemoteIpCont, podns)
×
2177
                        cont.apicConn.ClearApicObjects(cont.aciNameForKey("hostprot-ns-", podns))
×
2178
                        return false
×
2179
                }
×
2180

2181
                if !present {
2✔
2182
                        return false
1✔
2183
                }
1✔
2184
        } else {
1✔
2185
                if !ok {
2✔
2186
                        remipcont = make(remoteIpCont)
1✔
2187
                        cont.nsRemoteIpCont[podns] = remipcont
1✔
2188
                }
1✔
2189

2190
                for _, ip := range podips {
2✔
2191
                        remipcont[ip] = podlabels
1✔
2192
                }
1✔
2193
        }
2194

2195
        return true
1✔
2196
}
2197

2198
func (cont *AciController) addToHppCache(labelKey, key string, hpp apicapi.ApicSlice, hppcr *hppv1.HostprotPol) {
1✔
2199
        cont.indexMutex.Lock()
1✔
2200
        hppRef, ok := cont.hppRef[labelKey]
1✔
2201
        if ok {
2✔
2202
                var found bool
1✔
2203
                for _, npkey := range hppRef.Npkeys {
2✔
2204
                        if npkey == key {
2✔
2205
                                found = true
1✔
2206
                                break
1✔
2207
                        }
2208
                }
2209
                if !found {
1✔
2210
                        hppRef.RefCount++
×
2211
                        hppRef.Npkeys = append(hppRef.Npkeys, key)
×
2212
                }
×
2213
                hppRef.HppObj = hpp
1✔
2214
                hppRef.HppCr = *hppcr
1✔
2215
                cont.hppRef[labelKey] = hppRef
1✔
2216
        } else {
1✔
2217
                var newHppRef hppReference
1✔
2218
                newHppRef.RefCount++
1✔
2219
                newHppRef.HppObj = hpp
1✔
2220
                newHppRef.HppCr = *hppcr
1✔
2221
                newHppRef.Npkeys = append(newHppRef.Npkeys, key)
1✔
2222
                cont.hppRef[labelKey] = newHppRef
1✔
2223
        }
1✔
2224
        cont.indexMutex.Unlock()
1✔
2225
}
2226

2227
func (cont *AciController) removeFromHppCache(np *v1net.NetworkPolicy, key string) (string, bool) {
1✔
2228
        var labelKey string
1✔
2229
        var noRef bool
1✔
2230
        hash, err := util.CreateHashFromNetPol(np)
1✔
2231
        if err != nil {
1✔
2232
                cont.log.Error("Could not create hash from network policy: ", err)
×
2233
                cont.log.Error("Failed to remove np from hpp cache")
×
2234
                return labelKey, noRef
×
2235
        }
×
2236
        labelKey = cont.aciNameForKey("np", hash)
1✔
2237
        cont.indexMutex.Lock()
1✔
2238
        hppRef, ok := cont.hppRef[labelKey]
1✔
2239
        if ok {
2✔
2240
                for i, npkey := range hppRef.Npkeys {
2✔
2241
                        if npkey == key {
2✔
2242
                                hppRef.Npkeys = append(hppRef.Npkeys[:i], hppRef.Npkeys[i+1:]...)
1✔
2243
                                hppRef.RefCount--
1✔
2244
                                break
1✔
2245
                        }
2246
                }
2247
                if hppRef.RefCount > 0 {
1✔
2248
                        cont.hppRef[labelKey] = hppRef
×
2249
                } else {
1✔
2250
                        delete(cont.hppRef, labelKey)
1✔
2251
                        noRef = true
1✔
2252
                }
1✔
2253
        }
2254
        cont.indexMutex.Unlock()
1✔
2255
        return labelKey, noRef
1✔
2256
}
2257

2258
func getNetworkPolicyEgressIpBlocks(np *v1net.NetworkPolicy) map[string]bool {
1✔
2259
        subnets := make(map[string]bool)
1✔
2260
        for _, egress := range np.Spec.Egress {
2✔
2261
                for _, to := range egress.To {
2✔
2262
                        if to.IPBlock != nil && to.IPBlock.CIDR != "" {
2✔
2263
                                subnets[to.IPBlock.CIDR] = true
1✔
2264
                        }
1✔
2265
                }
2266
        }
2267
        return subnets
1✔
2268
}
2269

2270
func (cont *AciController) networkPolicyAdded(obj interface{}) {
1✔
2271
        np := obj.(*v1net.NetworkPolicy)
1✔
2272
        npkey, err := cache.MetaNamespaceKeyFunc(np)
1✔
2273
        if err != nil {
1✔
2274
                networkPolicyLogger(cont.log, np).
×
2275
                        Error("Could not create network policy key: ", err)
×
2276
                return
×
2277
        }
×
2278
        if cont.config.ChainedMode {
1✔
2279
                return
×
2280
        }
×
2281
        cont.netPolPods.UpdateSelectorObj(obj)
1✔
2282
        cont.netPolIngressPods.UpdateSelectorObj(obj)
1✔
2283
        cont.netPolEgressPods.UpdateSelectorObj(obj)
1✔
2284
        cont.indexMutex.Lock()
1✔
2285
        subnets := getNetworkPolicyEgressIpBlocks(np)
1✔
2286
        cont.updateIpIndex(cont.netPolSubnetIndex, nil, subnets, npkey)
1✔
2287

1✔
2288
        ports := cont.getNetPolTargetPorts(np)
1✔
2289
        cont.updateTargetPortIndex(false, npkey, nil, ports)
1✔
2290
        if isNamedPortPresenInNp(np) {
2✔
2291
                cont.nmPortNp[npkey] = true
1✔
2292
        }
1✔
2293
        cont.indexMutex.Unlock()
1✔
2294
        cont.queueNetPolUpdateByKey(npkey)
1✔
2295
}
2296

2297
func (cont *AciController) networkPolicyChanged(oldobj interface{},
2298
        newobj interface{}) {
×
2299
        oldnp := oldobj.(*v1net.NetworkPolicy)
×
2300
        newnp := newobj.(*v1net.NetworkPolicy)
×
2301
        npkey, err := cache.MetaNamespaceKeyFunc(newnp)
×
2302
        if err != nil {
×
2303
                networkPolicyLogger(cont.log, newnp).
×
2304
                        Error("Could not create network policy key: ", err)
×
2305
                return
×
2306
        }
×
2307

2308
        if cont.config.HppOptimization || cont.config.EnableHppDirect {
×
2309
                if !reflect.DeepEqual(oldnp.Spec, newnp.Spec) {
×
2310
                        cont.removeFromHppCache(oldnp, npkey)
×
2311
                }
×
2312
        }
2313

2314
        cont.indexMutex.Lock()
×
2315
        oldSubnets := getNetworkPolicyEgressIpBlocks(oldnp)
×
2316
        newSubnets := getNetworkPolicyEgressIpBlocks(newnp)
×
2317
        cont.updateIpIndex(cont.netPolSubnetIndex, oldSubnets, newSubnets, npkey)
×
2318

×
2319
        oldPorts := cont.getNetPolTargetPorts(oldnp)
×
2320
        newPorts := cont.getNetPolTargetPorts(newnp)
×
2321
        cont.updateTargetPortIndex(false, npkey, oldPorts, newPorts)
×
2322
        cont.indexMutex.Unlock()
×
2323

×
2324
        if !reflect.DeepEqual(oldnp.Spec.PodSelector, newnp.Spec.PodSelector) {
×
2325
                cont.netPolPods.UpdateSelectorObjNoCallback(newobj)
×
2326
        }
×
2327
        if !reflect.DeepEqual(oldnp.Spec.PolicyTypes, newnp.Spec.PolicyTypes) {
×
2328
                peerPodKeys := cont.netPolPods.GetPodForObj(npkey)
×
2329
                for _, podkey := range peerPodKeys {
×
2330
                        cont.podQueue.Add(podkey)
×
2331
                }
×
2332
        }
2333
        var queue bool
×
2334
        if !reflect.DeepEqual(oldnp.Spec.Ingress, newnp.Spec.Ingress) {
×
2335
                cont.netPolIngressPods.UpdateSelectorObjNoCallback(newobj)
×
2336
                queue = true
×
2337
        }
×
2338
        if !reflect.DeepEqual(oldnp.Spec.Egress, newnp.Spec.Egress) {
×
2339
                cont.netPolEgressPods.UpdateSelectorObjNoCallback(newobj)
×
2340
                queue = true
×
2341
        }
×
2342
        if cont.config.EnableHppDirect {
×
2343
                cont.deleteHppCr(oldnp)
×
2344
        }
×
2345
        if queue {
×
2346
                cont.queueNetPolUpdateByKey(npkey)
×
2347
        }
×
2348
}
2349

2350
func (cont *AciController) networkPolicyDeleted(obj interface{}) {
1✔
2351
        np, isNetworkpolicy := obj.(*v1net.NetworkPolicy)
1✔
2352
        if !isNetworkpolicy {
1✔
2353
                deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
×
2354
                if !ok {
×
2355
                        networkPolicyLogger(cont.log, np).
×
2356
                                Error("Received unexpected object: ", obj)
×
2357
                        return
×
2358
                }
×
2359
                np, ok = deletedState.Obj.(*v1net.NetworkPolicy)
×
2360
                if !ok {
×
2361
                        networkPolicyLogger(cont.log, np).
×
2362
                                Error("DeletedFinalStateUnknown contained non-Networkpolicy object: ", deletedState.Obj)
×
2363
                        return
×
2364
                }
×
2365
        }
2366
        npkey, err := cache.MetaNamespaceKeyFunc(np)
1✔
2367
        if err != nil {
1✔
2368
                networkPolicyLogger(cont.log, np).
×
2369
                        Error("Could not create network policy key: ", err)
×
2370
                return
×
2371
        }
×
2372

2373
        var labelKey string
1✔
2374
        var noHppRef bool
1✔
2375
        if cont.config.HppOptimization || cont.config.EnableHppDirect {
1✔
2376
                labelKey, noHppRef = cont.removeFromHppCache(np, npkey)
×
2377
        } else {
1✔
2378
                labelKey = cont.aciNameForKey("np", npkey)
1✔
2379
                noHppRef = true
1✔
2380
        }
1✔
2381

2382
        cont.indexMutex.Lock()
1✔
2383
        subnets := getNetworkPolicyEgressIpBlocks(np)
1✔
2384
        cont.updateIpIndex(cont.netPolSubnetIndex, subnets, nil, npkey)
1✔
2385

1✔
2386
        ports := cont.getNetPolTargetPorts(np)
1✔
2387
        cont.updateTargetPortIndex(false, npkey, ports, nil)
1✔
2388
        if isNamedPortPresenInNp(np) {
2✔
2389
                delete(cont.nmPortNp, npkey)
1✔
2390
        }
1✔
2391
        cont.indexMutex.Unlock()
1✔
2392

1✔
2393
        cont.netPolPods.DeleteSelectorObj(obj)
1✔
2394
        cont.netPolIngressPods.DeleteSelectorObj(obj)
1✔
2395
        cont.netPolEgressPods.DeleteSelectorObj(obj)
1✔
2396
        if noHppRef && labelKey != "" {
2✔
2397
                cont.apicConn.ClearApicObjects(labelKey)
1✔
2398
        }
1✔
2399
        if cont.config.EnableHppDirect {
1✔
2400
                cont.deleteHppCr(np)
×
2401
        }
×
2402
}
2403

2404
func (sep *serviceEndpoint) SetNpServiceAugmentForService(servicekey string, service *v1.Service, prs *portRemoteSubnet,
2405
        portAugments map[string]*portServiceAugment, subnetIndex cidranger.Ranger, logger *logrus.Entry) {
1✔
2406
        cont := sep.cont
1✔
2407
        endpointsobj, _, err := cont.endpointsIndexer.GetByKey(servicekey)
1✔
2408
        if err != nil {
1✔
2409
                logger.Error("Could not lookup endpoints for "+
×
2410
                        servicekey+": ", err.Error())
×
2411
                return
×
2412
        }
×
2413
        if endpointsobj == nil {
1✔
2414
                return
×
2415
        }
×
2416
        endpoints := endpointsobj.(*v1.Endpoints)
1✔
2417
        portstrings := make(map[string]bool)
1✔
2418
        ports := cont.getPortNums(prs.port)
1✔
2419
        for _, port := range ports {
2✔
2420
                portstrings[strconv.Itoa(port)] = true
1✔
2421
        }
1✔
2422
        for _, svcPort := range service.Spec.Ports {
2✔
2423
                _, ok := portstrings[svcPort.TargetPort.String()]
1✔
2424
                if prs.port != nil &&
1✔
2425
                        (svcPort.Protocol != *prs.port.Protocol || !ok) {
1✔
2426
                        // egress rule does not match service target port
×
2427
                        continue
×
2428
                }
2429
                for _, subset := range endpoints.Subsets {
2✔
2430
                        var foundEpPort *v1.EndpointPort
1✔
2431
                        for ix := range subset.Ports {
2✔
2432
                                if subset.Ports[ix].Name == svcPort.Name ||
1✔
2433
                                        (len(service.Spec.Ports) == 1 &&
1✔
2434
                                                subset.Ports[ix].Name == "") {
2✔
2435
                                        foundEpPort = &subset.Ports[ix]
1✔
2436
                                        break
1✔
2437
                                }
2438
                        }
2439
                        if foundEpPort == nil {
1✔
2440
                                continue
×
2441
                        }
2442

2443
                        incomplete := false
1✔
2444
                        incomplete = incomplete ||
1✔
2445
                                !checkEndpoints(subnetIndex, subset.Addresses)
1✔
2446
                        incomplete = incomplete || !checkEndpoints(subnetIndex,
1✔
2447
                                subset.NotReadyAddresses)
1✔
2448

1✔
2449
                        if incomplete {
2✔
2450
                                continue
1✔
2451
                        }
2452

2453
                        proto := portProto(&foundEpPort.Protocol)
1✔
2454
                        port := strconv.Itoa(int(svcPort.Port))
1✔
2455
                        updateServiceAugmentForService(portAugments,
1✔
2456
                                proto, port, service)
1✔
2457

1✔
2458
                        logger.WithFields(logrus.Fields{
1✔
2459
                                "proto":   proto,
1✔
2460
                                "port":    port,
1✔
2461
                                "service": servicekey,
1✔
2462
                        }).Debug("Allowing egress for service by subnet match")
1✔
2463
                }
2464
        }
2465
}
2466

2467
func (seps *serviceEndpointSlice) SetNpServiceAugmentForService(servicekey string, service *v1.Service,
2468
        prs *portRemoteSubnet, portAugments map[string]*portServiceAugment,
2469
        subnetIndex cidranger.Ranger, logger *logrus.Entry) {
1✔
2470
        cont := seps.cont
1✔
2471
        portstrings := make(map[string]bool)
1✔
2472
        ports := cont.getPortNums(prs.port)
1✔
2473
        for _, port := range ports {
2✔
2474
                portstrings[strconv.Itoa(port)] = true
1✔
2475
        }
1✔
2476
        label := map[string]string{discovery.LabelServiceName: service.ObjectMeta.Name}
1✔
2477
        selector := labels.SelectorFromSet(label)
1✔
2478
        cache.ListAllByNamespace(cont.endpointSliceIndexer, service.ObjectMeta.Namespace, selector,
1✔
2479
                func(endpointSliceobj interface{}) {
2✔
2480
                        endpointSlices := endpointSliceobj.(*discovery.EndpointSlice)
1✔
2481
                        for _, svcPort := range service.Spec.Ports {
2✔
2482
                                _, ok := portstrings[svcPort.TargetPort.String()]
1✔
2483
                                if prs.port != nil &&
1✔
2484
                                        (svcPort.Protocol != *prs.port.Protocol || !ok) {
1✔
UNCOV
2485
                                        // egress rule does not match service target port
×
UNCOV
2486
                                        continue
×
2487
                                }
2488
                                var foundEpPort *discovery.EndpointPort
1✔
2489
                                for ix := range endpointSlices.Ports {
2✔
2490
                                        if *endpointSlices.Ports[ix].Name == svcPort.Name ||
1✔
2491
                                                (len(service.Spec.Ports) == 1 &&
1✔
2492
                                                        *endpointSlices.Ports[ix].Name == "") {
2✔
2493
                                                foundEpPort = &endpointSlices.Ports[ix]
1✔
2494
                                                cont.log.Debug("Found EpPort: ", foundEpPort)
1✔
2495
                                                break
1✔
2496
                                        }
2497
                                }
2498
                                if foundEpPort == nil {
1✔
2499
                                        return
×
2500
                                }
×
2501
                                // @FIXME for non ready address
2502
                                incomplete := false
1✔
2503
                                for _, endpoint := range endpointSlices.Endpoints {
2✔
2504
                                        incomplete = incomplete || !checkEndpointslices(subnetIndex, endpoint.Addresses)
1✔
2505
                                }
1✔
2506
                                if incomplete {
2✔
2507
                                        continue
1✔
2508
                                }
2509
                                proto := portProto(foundEpPort.Protocol)
1✔
2510
                                port := strconv.Itoa(int(svcPort.Port))
1✔
2511
                                cont.log.Debug("updateServiceAugmentForService: ", service)
1✔
2512
                                updateServiceAugmentForService(portAugments,
1✔
2513
                                        proto, port, service)
1✔
2514

1✔
2515
                                logger.WithFields(logrus.Fields{
1✔
2516
                                        "proto":   proto,
1✔
2517
                                        "port":    port,
1✔
2518
                                        "service": servicekey,
1✔
2519
                                }).Debug("Allowing egress for service by subnet match")
1✔
2520
                        }
2521
                })
2522
}
2523

2524
func isNamedPortPresenInNp(np *v1net.NetworkPolicy) bool {
1✔
2525
        for _, egress := range np.Spec.Egress {
2✔
2526
                for _, p := range egress.Ports {
2✔
2527
                        if p.Port.Type == intstr.String {
2✔
2528
                                return true
1✔
2529
                        }
1✔
2530
                }
2531
        }
2532
        return false
1✔
2533
}
2534

2535
func (cont *AciController) checkPodNmpMatchesNp(npkey, podkey string) bool {
1✔
2536
        podobj, exists, err := cont.podIndexer.GetByKey(podkey)
1✔
2537
        if err != nil {
1✔
2538
                return false
×
2539
        }
×
2540
        if !exists || podobj == nil {
1✔
2541
                return false
×
2542
        }
×
2543
        pod := podobj.(*v1.Pod)
1✔
2544
        npobj, npexists, nperr := cont.networkPolicyIndexer.GetByKey(npkey)
1✔
2545
        if npexists && nperr == nil && npobj != nil {
2✔
2546
                np := npobj.(*v1net.NetworkPolicy)
1✔
2547
                for _, egress := range np.Spec.Egress {
2✔
2548
                        for _, p := range egress.Ports {
2✔
2549
                                if p.Port.Type == intstr.String {
2✔
2550
                                        _, err := k8util.LookupContainerPortNumberByName(*pod, p.Port.String())
1✔
2551
                                        if err == nil {
2✔
2552
                                                return true
1✔
2553
                                        }
1✔
2554
                                }
2555
                        }
2556
                }
2557
        }
2558
        return false
1✔
2559
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc