This repository has been archived by the owner on Mar 20, 2024. It is now read-only.
forked from cilium/cilium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rule.go
658 lines (570 loc) · 21.7 KB
/
rule.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
// Copyright 2016-2018 Authors of Cilium
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package policy
import (
"fmt"
"github.com/cilium/cilium/pkg/identity"
"github.com/cilium/cilium/pkg/labels"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/policy/api"
"github.com/cilium/cilium/pkg/policy/trafficdirection"
"k8s.io/apimachinery/pkg/apis/meta/v1"
)
type rule struct {
api.Rule
metadata *ruleMetadata
}
type ruleMetadata struct {
// mutex protects all fields in this type.
Mutex lock.RWMutex
// localRuleConsumers is the set of the endpoints which this rule selects
// which are node-local.
EndpointsSelected map[uint16]*identity.Identity
// AllEndpoints tracks which node-local Endpoints have been 'processed'.
// That is, it determines whether the Endpoint has actually been processed
// in relation to this rule. It does *not* encode whether the rule selects
// the endpoint; that is what EndpointsSelected is for.
AllEndpoints map[uint16]struct{}
}
func newRuleMetadata() *ruleMetadata {
return &ruleMetadata{
EndpointsSelected: make(map[uint16]*identity.Identity),
AllEndpoints: make(map[uint16]struct{}),
}
}
func (m *ruleMetadata) deleteID(id uint16) {
m.Mutex.Lock()
defer m.Mutex.Unlock()
delete(m.EndpointsSelected, id)
delete(m.AllEndpoints, id)
}
func (r *rule) String() string {
return fmt.Sprintf("%v", r.EndpointSelector)
}
func mergeL4Port(ctx *SearchContext, endpoints []api.EndpointSelector, existingFilter, filterToMerge *L4Filter) error {
// Handle cases where filter we are merging new rule with, new rule itself
// allows all traffic on L3, or both rules allow all traffic on L3.
//
// Case 1: either filter selects all endpoints, which means that this filter
// can now simply select all endpoints.
if existingFilter.AllowsAllAtL3() || filterToMerge.AllowsAllAtL3() {
existingFilter.Endpoints = api.EndpointSelectorSlice{api.WildcardEndpointSelector}
existingFilter.allowsAllAtL3 = true
} else {
// Case 2: no wildcard endpoint selectors in existing filter or in filter
// to merge, so just append endpoints.
existingFilter.Endpoints = append(existingFilter.Endpoints, endpoints...)
}
// Merge the L7-related data from the arguments provided to this function
// with the existing L7-related data already in the filter.
if filterToMerge.L7Parser != ParserTypeNone {
if existingFilter.L7Parser == ParserTypeNone {
existingFilter.L7Parser = filterToMerge.L7Parser
} else if filterToMerge.L7Parser != existingFilter.L7Parser {
ctx.PolicyTrace(" Merge conflict: mismatching parsers %s/%s\n", filterToMerge.L7Parser, existingFilter.L7Parser)
return fmt.Errorf("Cannot merge conflicting L7 parsers (%s/%s)", filterToMerge.L7Parser, existingFilter.L7Parser)
}
}
for hash, newL7Rules := range filterToMerge.L7RulesPerEp {
if ep, ok := existingFilter.L7RulesPerEp[hash]; ok {
switch {
case len(newL7Rules.HTTP) > 0:
if len(ep.Kafka) > 0 || len(ep.DNS) > 0 || ep.L7Proto != "" {
ctx.PolicyTrace(" Merge conflict: mismatching L7 rule types.\n")
return fmt.Errorf("Cannot merge conflicting L7 rule types")
}
for _, newRule := range newL7Rules.HTTP {
if !newRule.Exists(ep) {
ep.HTTP = append(ep.HTTP, newRule)
}
}
case len(newL7Rules.Kafka) > 0:
if len(ep.HTTP) > 0 || len(ep.DNS) > 0 || ep.L7Proto != "" {
ctx.PolicyTrace(" Merge conflict: mismatching L7 rule types.\n")
return fmt.Errorf("Cannot merge conflicting L7 rule types")
}
for _, newRule := range newL7Rules.Kafka {
if !newRule.Exists(ep) {
ep.Kafka = append(ep.Kafka, newRule)
}
}
case newL7Rules.L7Proto != "":
if len(ep.Kafka) > 0 || len(ep.HTTP) > 0 || len(ep.DNS) > 0 || (ep.L7Proto != "" && ep.L7Proto != newL7Rules.L7Proto) {
ctx.PolicyTrace(" Merge conflict: mismatching L7 rule types.\n")
return fmt.Errorf("Cannot merge conflicting L7 rule types")
}
if ep.L7Proto == "" {
ep.L7Proto = newL7Rules.L7Proto
}
for _, newRule := range newL7Rules.L7 {
if !newRule.Exists(ep) {
ep.L7 = append(ep.L7, newRule)
}
}
case len(newL7Rules.DNS) > 0:
if len(ep.HTTP) > 0 || len(ep.Kafka) > 0 || len(ep.L7) > 0 {
ctx.PolicyTrace(" Merge conflict: mismatching L7 rule types.\n")
return fmt.Errorf("Cannot merge conflicting L7 rule types")
}
for _, newRule := range newL7Rules.DNS {
if !newRule.Exists(ep) {
ep.DNS = append(ep.DNS, newRule)
}
}
default:
ctx.PolicyTrace(" No L7 rules to merge.\n")
}
existingFilter.L7RulesPerEp[hash] = ep
} else {
existingFilter.L7RulesPerEp[hash] = newL7Rules
}
}
return nil
}
// mergeL4IngressPort merges all rules which share the same port & protocol that
// select a given set of endpoints. It updates the L4Filter mapped to by the specified
// port and protocol with the contents of the provided PortRule. If the rule
// being merged has conflicting L7 rules with those already in the provided
// L4PolicyMap for the specified port-protocol tuple, it returns an error.
//
// If any rules contain L7 rules that overlap with the endpointsWithL3Override,
// then for the endpoints with L3 override, the L7 rules will be translated
// into L7 wildcards (ie, traffic will be forwarded to the proxy for endpoints
// matching those labels, but the proxy will allow all such traffic).
func mergeL4IngressPort(ctx *SearchContext, endpoints []api.EndpointSelector, endpointsWithL3Override []api.EndpointSelector, r api.PortRule, p api.PortProtocol,
proto api.L4Proto, ruleLabels labels.LabelArray, resMap L4PolicyMap) (int, error) {
key := p.Port + "/" + string(proto)
existingFilter, ok := resMap[key]
if !ok {
resMap[key] = CreateL4IngressFilter(endpoints, endpointsWithL3Override, r, p, proto, ruleLabels)
return 1, nil
}
// Create a new L4Filter based off of the arguments provided to this function
// for merging with the filter which is already in the policy map.
filterToMerge := CreateL4IngressFilter(endpoints, endpointsWithL3Override, r, p, proto, ruleLabels)
if err := mergeL4Port(ctx, endpoints, &existingFilter, &filterToMerge); err != nil {
return 0, err
}
existingFilter.DerivedFromRules = append(existingFilter.DerivedFromRules, ruleLabels)
resMap[key] = existingFilter
return 1, nil
}
func mergeL4Ingress(ctx *SearchContext, rule api.IngressRule, ruleLabels labels.LabelArray, resMap L4PolicyMap) (int, error) {
if len(rule.ToPorts) == 0 {
ctx.PolicyTrace(" No L4 %s rules\n", trafficdirection.Ingress)
return 0, nil
}
fromEndpoints := rule.GetSourceEndpointSelectors()
found := 0
if ctx.From != nil && len(fromEndpoints) > 0 {
if !fromEndpoints.Matches(ctx.From) {
ctx.PolicyTrace(" Labels %s not found", ctx.From)
return 0, nil
}
}
ctx.PolicyTrace(" Found all required labels")
// Daemon options may induce L3 allows for host/world. In this case, if
// we find any L7 rules matching host/world then we need to turn any L7
// restrictions on these endpoints into L7 allow-all so that the
// traffic is always allowed, but is also always redirected through the
// proxy
endpointsWithL3Override := []api.EndpointSelector{}
if option.Config.AlwaysAllowLocalhost() {
endpointsWithL3Override = append(endpointsWithL3Override, api.ReservedEndpointSelectors[labels.IDNameHost])
}
for _, r := range rule.ToPorts {
ctx.PolicyTrace(" Allows %s port %v from endpoints %v\n", trafficdirection.Ingress, r.Ports, fromEndpoints)
if r.Rules != nil && r.Rules.L7Proto != "" {
ctx.PolicyTrace(" l7proto: \"%s\"\n", r.Rules.L7Proto)
}
if !r.Rules.IsEmpty() {
for _, l7 := range r.Rules.HTTP {
ctx.PolicyTrace(" %+v\n", l7)
}
for _, l7 := range r.Rules.Kafka {
ctx.PolicyTrace(" %+v\n", l7)
}
for _, l7 := range r.Rules.L7 {
ctx.PolicyTrace(" %+v\n", l7)
}
}
for _, p := range r.Ports {
if p.Protocol != api.ProtoAny {
cnt, err := mergeL4IngressPort(ctx, fromEndpoints, endpointsWithL3Override, r, p, p.Protocol, ruleLabels, resMap)
if err != nil {
return found, err
}
found += cnt
} else {
cnt, err := mergeL4IngressPort(ctx, fromEndpoints, endpointsWithL3Override, r, p, api.ProtoTCP, ruleLabels, resMap)
if err != nil {
return found, err
}
found += cnt
cnt, err = mergeL4IngressPort(ctx, fromEndpoints, endpointsWithL3Override, r, p, api.ProtoUDP, ruleLabels, resMap)
if err != nil {
return found, err
}
found += cnt
}
}
}
return found, nil
}
func (state *traceState) selectRule(ctx *SearchContext, r *rule) {
ctx.PolicyTrace("* Rule %s: selected\n", r)
state.selectedRules++
}
func (state *traceState) unSelectRule(ctx *SearchContext, labels labels.LabelArray, r *rule) {
ctx.PolicyTraceVerbose(" Rule %s: did not select %+v\n", r, labels)
}
// resolveL4IngressPolicy determines whether (TODO ianvernon)
func (r *rule) resolveL4IngressPolicy(ctx *SearchContext, state *traceState, result *L4Policy, requirements []v1.LabelSelectorRequirement) (*L4Policy, error) {
if !ctx.rulesSelect {
if !r.EndpointSelector.Matches(ctx.To) {
state.unSelectRule(ctx, ctx.To, r)
return nil, nil
}
}
state.selectRule(ctx, r)
found := 0
if len(r.Ingress) == 0 {
ctx.PolicyTrace(" No L4 ingress rules\n")
}
for _, ingressRule := range r.Ingress {
ruleCopy := ingressRule
// For each FromEndpoints in each ingress rule, add requirements, which
// is a flattened list of all EndpointSelectors from all FromRequires
// from rules which select the labels in ctx.To. This ensures that
// FromRequires is taken into account even if it isn't part of the current
// rule over which we are iterating.
if len(requirements) > 0 {
// Create a deep copy of the rule, as we are going to modify FromEndpoints
// with requirementsSelector. We don't want to modify the rule itself
// in the policy repository.
ruleCopy = *ingressRule.DeepCopy()
// Update each EndpointSelector in FromEndpoints to contain requirements.
for idx := range ruleCopy.FromEndpoints {
ruleCopy.FromEndpoints[idx].MatchExpressions = append(ruleCopy.FromEndpoints[idx].MatchExpressions, requirements...)
ruleCopy.FromEndpoints[idx].SyncRequirementsWithLabelSelector()
}
ruleCopy.SetAggregatedSelectors()
}
cnt, err := mergeL4Ingress(ctx, ruleCopy, r.Rule.Labels.DeepCopy(), result.Ingress)
if err != nil {
return nil, err
}
if cnt > 0 {
found += cnt
}
}
if found > 0 {
return result, nil
}
return nil, nil
}
// ********************** CIDR POLICY **********************
// mergeCIDR inserts all of the CIDRs in ipRules to resMap. Returns the number
// of CIDRs added to resMap.
func mergeCIDR(ctx *SearchContext, dir string, ipRules []api.CIDR, ruleLabels labels.LabelArray, resMap *CIDRPolicyMap) int {
found := 0
for _, r := range ipRules {
strCIDR := string(r)
ctx.PolicyTrace(" Allows %s IP %s\n", dir, strCIDR)
found += resMap.Insert(strCIDR, ruleLabels)
}
return found
}
// resolveCIDRPolicy inserts the CIDRs from the specified rule into result if
// the rule corresponds to the current SearchContext. It returns the resultant
// CIDRPolicy containing the added ingress and egress CIDRs. If no CIDRs are
// added to result, a nil CIDRPolicy is returned.
func (r *rule) resolveCIDRPolicy(ctx *SearchContext, state *traceState, result *CIDRPolicy) *CIDRPolicy {
// Don't select rule if it doesn't apply to the given context.
if !ctx.rulesSelect {
if !r.EndpointSelector.Matches(ctx.To) {
state.unSelectRule(ctx, ctx.To, r)
return nil
}
}
state.selectRule(ctx, r)
found := 0
for _, ingressRule := range r.Ingress {
// TODO (ianvernon): GH-1658
var allCIDRs []api.CIDR
allCIDRs = append(allCIDRs, ingressRule.FromCIDR...)
allCIDRs = append(allCIDRs, api.ComputeResultantCIDRSet(ingressRule.FromCIDRSet)...)
// CIDR + L4 rules are handled via mergeL4Ingress(),
// skip them here.
if len(allCIDRs) > 0 && len(ingressRule.ToPorts) > 0 {
continue
}
if cnt := mergeCIDR(ctx, "Ingress", allCIDRs, r.Labels, &result.Ingress); cnt > 0 {
found += cnt
}
}
// CIDR egress policy is used for visibility of desired state in
// the API and for determining which prefix lengths are available,
// however it does not determine the actual CIDRs in the BPF maps
// for allowing traffic by CIDR!
for _, egressRule := range r.Egress {
var allCIDRs []api.CIDR
allCIDRs = append(allCIDRs, egressRule.ToCIDR...)
allCIDRs = append(allCIDRs, api.ComputeResultantCIDRSet(egressRule.ToCIDRSet)...)
// Unlike the Ingress policy which only counts L3 policy in
// this function, we count the CIDR+L4 policy in the
// desired egress CIDR policy here as well. This ensures
// proper computation of IPcache prefix lengths.
if cnt := mergeCIDR(ctx, "Egress", allCIDRs, r.Labels, &result.Egress); cnt > 0 {
found += cnt
}
}
if found > 0 {
return result
}
ctx.PolicyTrace(" No L3 rules\n")
return nil
}
// canReachIngress returns the decision as to whether the set of labels specified
// in ctx.From match with the label selectors specified in the ingress rules
// contained within r.
func (r *rule) canReachIngress(ctx *SearchContext, state *traceState) api.Decision {
if !ctx.rulesSelect {
if !r.EndpointSelector.Matches(ctx.To) {
state.unSelectRule(ctx, ctx.To, r)
return api.Undecided
}
}
state.selectRule(ctx, r)
for _, r := range r.Ingress {
for _, sel := range r.FromRequires {
ctx.PolicyTrace(" Requires from labels %+v", sel)
if !sel.Matches(ctx.From) {
ctx.PolicyTrace("- Labels %v not found\n", ctx.From)
state.constrainedRules++
return api.Denied
}
ctx.PolicyTrace("+ Found all required labels\n")
}
}
// separate loop is needed as failure to meet FromRequires always takes
// precedence over FromEndpoints and FromEntities
for _, r := range r.Ingress {
for _, sel := range r.GetSourceEndpointSelectors() {
ctx.PolicyTrace(" Allows from labels %+v", sel)
if sel.Matches(ctx.From) {
ctx.PolicyTrace(" Found all required labels")
if len(r.ToPorts) == 0 {
ctx.PolicyTrace("+ No L4 restrictions\n")
state.matchedRules++
return api.Allowed
}
ctx.PolicyTrace(" Rule restricts traffic to specific L4 destinations; deferring policy decision to L4 policy stage\n")
} else {
ctx.PolicyTrace(" Labels %v not found\n", ctx.From)
}
}
}
return api.Undecided
}
func (r *rule) matches(id uint16, securityIdentity *identity.Identity) bool {
r.metadata.Mutex.Lock()
defer r.metadata.Mutex.Unlock()
var ruleMatches bool
// Rule has already been processed, we can check the caches in the rule.
if _, ok := r.metadata.AllEndpoints[id]; ok {
// We can compare the pointers to the identity to see if they are
// equivalent here safely.
cachedIdentity, ok := r.metadata.EndpointsSelected[id]
// There could be a possibility that the same identifier mapped to a
// different identity in the cache previously. Ensure that identity to
// which identifier maps is the same.
if ok && cachedIdentity == securityIdentity {
return true
}
// If the cached identity is the same, but wasn't in EndpointsSelected,
// then rule doesn't match ; return false. If the identities aren't
// equal, then we have to fall back to label-based matching.
if cachedIdentity == securityIdentity {
return false
}
}
// Fall back to costly matching.
if ruleMatches = r.EndpointSelector.Matches(securityIdentity.LabelArray); ruleMatches {
// Update cache so we don't have to do costly matching again.
r.metadata.EndpointsSelected[id] = securityIdentity
} else {
delete(r.metadata.EndpointsSelected, id)
}
r.metadata.AllEndpoints[id] = struct{}{}
return ruleMatches
}
// ****************** EGRESS POLICY ******************
// canReachEgress returns the decision as to whether the set of labels specified
// in ctx.To match with the label selectors specified in the egress rules
// contained within r.
func (r *rule) canReachEgress(ctx *SearchContext, state *traceState) api.Decision {
if !ctx.rulesSelect {
if !r.EndpointSelector.Matches(ctx.From) {
state.unSelectRule(ctx, ctx.From, r)
return api.Undecided
}
}
state.selectRule(ctx, r)
for _, r := range r.Egress {
for _, sel := range r.ToRequires {
ctx.PolicyTrace(" Requires from labels %+v", sel)
if !sel.Matches(ctx.To) {
ctx.PolicyTrace("- Labels %v not found\n", ctx.To)
state.constrainedRules++
return api.Denied
}
ctx.PolicyTrace("+ Found all required labels\n")
}
}
// Separate loop is needed as failure to meet ToRequires always takes
// precedence over ToEndpoints and ToEntities
for _, r := range r.Egress {
for _, sel := range r.GetDestinationEndpointSelectors() {
ctx.PolicyTrace(" Allows to labels %+v", sel)
if sel.Matches(ctx.To) {
ctx.PolicyTrace(" Found all required labels")
if len(r.ToPorts) == 0 {
ctx.PolicyTrace("+ No L4 restrictions\n")
state.matchedRules++
return api.Allowed
}
ctx.PolicyTrace(" Rule restricts traffic from specific L4 destinations; deferring policy decision to L4 policy stage\n")
} else {
ctx.PolicyTrace(" Labels %v not found\n", ctx.To)
}
}
}
return api.Undecided
}
func mergeL4Egress(ctx *SearchContext, rule api.EgressRule, ruleLabels labels.LabelArray, resMap L4PolicyMap) (int, error) {
if len(rule.ToPorts) == 0 {
ctx.PolicyTrace(" No L4 %s rules\n", trafficdirection.Egress)
return 0, nil
}
toEndpoints := rule.GetDestinationEndpointSelectors()
found := 0
for _, r := range rule.ToPorts {
ctx.PolicyTrace(" Allows %s port %v to endpoints %v\n", trafficdirection.Egress, r.Ports, toEndpoints)
if r.Rules != nil && r.Rules.L7Proto != "" {
ctx.PolicyTrace(" l7proto: \"%s\"\n", r.Rules.L7Proto)
}
if !r.Rules.IsEmpty() {
for _, l7 := range r.Rules.HTTP {
ctx.PolicyTrace(" %+v\n", l7)
}
for _, l7 := range r.Rules.Kafka {
ctx.PolicyTrace(" %+v\n", l7)
}
for _, l7 := range r.Rules.L7 {
ctx.PolicyTrace(" %+v\n", l7)
}
}
for _, p := range r.Ports {
if p.Protocol != api.ProtoAny {
cnt, err := mergeL4EgressPort(ctx, toEndpoints, r, p, p.Protocol, ruleLabels, resMap)
if err != nil {
return found, err
}
found += cnt
} else {
cnt, err := mergeL4EgressPort(ctx, toEndpoints, r, p, api.ProtoTCP, ruleLabels, resMap)
if err != nil {
return found, err
}
found += cnt
cnt, err = mergeL4EgressPort(ctx, toEndpoints, r, p, api.ProtoUDP, ruleLabels, resMap)
if err != nil {
return found, err
}
found += cnt
}
}
}
return found, nil
}
// mergeL4EgressPort merges all rules which share the same port & protocol that
// select a given set of endpoints. It updates the L4Filter mapped to by the specified
// port and protocol with the contents of the provided PortRule. If the rule
// being merged has conflicting L7 rules with those already in the provided
// L4PolicyMap for the specified port-protocol tuple, it returns an error.
func mergeL4EgressPort(ctx *SearchContext, endpoints []api.EndpointSelector, r api.PortRule, p api.PortProtocol,
proto api.L4Proto, ruleLabels labels.LabelArray, resMap L4PolicyMap) (int, error) {
key := p.Port + "/" + string(proto)
existingFilter, ok := resMap[key]
if !ok {
resMap[key] = CreateL4EgressFilter(endpoints, r, p, proto, ruleLabels)
return 1, nil
}
// Create a new L4Filter based off of the arguments provided to this function
// for merging with the filter which is already in the policy map.
filterToMerge := CreateL4EgressFilter(endpoints, r, p, proto, ruleLabels)
if err := mergeL4Port(ctx, endpoints, &existingFilter, &filterToMerge); err != nil {
return 0, err
}
existingFilter.DerivedFromRules = append(existingFilter.DerivedFromRules, ruleLabels)
resMap[key] = existingFilter
return 1, nil
}
func (r *rule) resolveL4EgressPolicy(ctx *SearchContext, state *traceState, result *L4Policy, requirements []v1.LabelSelectorRequirement) (*L4Policy, error) {
if !ctx.rulesSelect {
if !r.EndpointSelector.Matches(ctx.From) {
state.unSelectRule(ctx, ctx.From, r)
return nil, nil
}
}
state.selectRule(ctx, r)
found := 0
if len(r.Egress) == 0 {
ctx.PolicyTrace(" No L4 rules\n")
}
for _, egressRule := range r.Egress {
ruleCopy := egressRule
// For each ToEndpoints in each egress rule, add the requirements, which
// is a flattened list of all EndpointSelectors from all ToRequires
// from rules which select the labels in ctx.From. This ensures that
// ToRequires is taken into account even if it isn't part of the current
// rule over which we are iterating.
if len(requirements) > 0 {
// Create a deep copy of the rule, as we are going to modify
// ToEndpoints with requirements; we don't want to modify the rule
// in the repository.
ruleCopy = *egressRule.DeepCopy()
for idx := range ruleCopy.ToEndpoints {
// Update each EndpointSelector in ToEndpoints to contain
// requirements.
ruleCopy.ToEndpoints[idx].MatchExpressions = append(ruleCopy.ToEndpoints[idx].MatchExpressions, requirements...)
ruleCopy.ToEndpoints[idx].SyncRequirementsWithLabelSelector()
}
ruleCopy.SetAggregatedSelectors()
}
cnt, err := mergeL4Egress(ctx, ruleCopy, r.Rule.Labels.DeepCopy(), result.Egress)
if err != nil {
return nil, err
}
if cnt > 0 {
found += cnt
}
}
if found > 0 {
return result, nil
}
return nil, nil
}