@@ -2,9 +2,11 @@ package matcher
2
2
3
3
import (
4
4
"fmt"
5
+ "github.com/mattfenwick/collections/pkg/builtins"
6
+ "github.com/mattfenwick/collections/pkg/slices"
5
7
"github.com/mattfenwick/cyclonus/pkg/kube"
6
8
"github.com/olekukonko/tablewriter"
7
- "sort "
9
+ "golang.org/x/exp/maps "
8
10
"strings"
9
11
)
10
12
@@ -26,19 +28,9 @@ func NewPolicyWithTargets(ingress []*Target, egress []*Target) *Policy {
26
28
}
27
29
28
30
func (p * Policy ) SortedTargets () ([]* Target , []* Target ) {
29
- var ingress , egress []* Target
30
- for _ , rule := range p .Ingress {
31
- ingress = append (ingress , rule )
32
- }
33
- sort .Slice (ingress , func (i , j int ) bool {
34
- return ingress [i ].GetPrimaryKey () < ingress [j ].GetPrimaryKey ()
35
- })
36
- for _ , rule := range p .Egress {
37
- egress = append (egress , rule )
38
- }
39
- sort .Slice (egress , func (i , j int ) bool {
40
- return egress [i ].GetPrimaryKey () < egress [j ].GetPrimaryKey ()
41
- })
31
+ key := func (t * Target ) string { return t .GetPrimaryKey () }
32
+ ingress := slices .SortOnBy (key , builtins .CompareOrdered [string ], maps .Values (p .Ingress ))
33
+ egress := slices .SortOnBy (key , builtins .CompareOrdered [string ], maps .Values (p .Egress ))
42
34
return ingress , egress
43
35
}
44
36
@@ -114,7 +106,8 @@ func (ar *AllowedResult) Table() string {
114
106
}
115
107
116
108
func addTargetsToTable (table * tablewriter.Table , ruleType string , action string , targets []* Target ) {
117
- for _ , t := range targets {
109
+ sortedTargets := slices .SortOnBy (func (t * Target ) string { return t .GetPrimaryKey () }, builtins .CompareOrdered [string ], targets )
110
+ for _ , t := range sortedTargets {
118
111
targetString := fmt .Sprintf ("namespace: %s\n %s" , t .Namespace , kube .LabelSelectorTableLines (t .PodSelector ))
119
112
table .Append ([]string {ruleType , action , targetString })
120
113
}
@@ -160,15 +153,10 @@ func (p *Policy) IsIngressOrEgressAllowed(traffic *Traffic, isIngress bool) *Dir
160
153
}
161
154
162
155
// 3. Check if any matching targets allow this traffic
163
- var allowers []* Target
164
- var deniers []* Target
165
- for _ , target := range matchingTargets {
166
- if target .Allows (peer , traffic .ResolvedPort , traffic .ResolvedPortName , traffic .Protocol ) {
167
- allowers = append (allowers , target )
168
- } else {
169
- deniers = append (deniers , target )
170
- }
171
- }
156
+ pair := slices .Partition (func (t * Target ) bool {
157
+ return t .Allows (peer , traffic .ResolvedPort , traffic .ResolvedPortName , traffic .Protocol )
158
+ }, matchingTargets )
159
+ allowers , deniers := pair .Fst , pair .Snd
172
160
173
161
return & DirectionResult {AllowingTargets : allowers , DenyingTargets : deniers }
174
162
}
0 commit comments