Skip to content

Commit

Permalink
Refactor network policy matching logic (#4626)
Browse files Browse the repository at this point in the history
Signed-off-by: oilbeater <liumengxinfly@gmail.com>
  • Loading branch information
oilbeater committed Oct 17, 2024
1 parent 603be72 commit aa7f680
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions pkg/controller/network_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package controller
import (
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"unicode"
Expand Down Expand Up @@ -854,7 +855,8 @@ func (c *Controller) podMatchNetworkPolicies(pod *corev1.Pod) []string {

func (c *Controller) svcMatchNetworkPolicies(svc *corev1.Service) ([]string, error) {
// find all match pod
pods, err := c.podsLister.Pods(svc.Namespace).List(labels.Everything())
sel := labels.Set(svc.Spec.Selector).AsSelector()
pods, err := c.podsLister.Pods(svc.Namespace).List(sel)
if err != nil {
return nil, fmt.Errorf("failed to list pods, %v", err)
}
Expand All @@ -865,11 +867,12 @@ func (c *Controller) svcMatchNetworkPolicies(svc *corev1.Service) ([]string, err
return nil, fmt.Errorf("failed to list netpols, %v", err)
}
match := []string{}
ns, _ := c.namespacesLister.Get(svc.Namespace)
for _, pod := range pods {
podNs, _ := c.namespacesLister.Get(pod.Namespace)
for _, np := range nps {
if isPodMatchNetworkPolicy(pod, *podNs, np, np.Namespace) {
match = append(match, fmt.Sprintf("%s/%s", np.Namespace, np.Name))
event := fmt.Sprintf("%s/%s", np.Namespace, np.Name)
if isPodMatchNetworkPolicy(pod, *ns, np, np.Namespace) && !slices.Contains(match, event) {
match = append(match, event)
klog.V(3).Infof("svc %s/%s match np %s/%s", svc.Namespace, svc.Name, np.Namespace, np.Name)
}
}
Expand Down

0 comments on commit aa7f680

Please sign in to comment.