Skip to content

Commit

Permalink
Refactor network policy matching logic
Browse files Browse the repository at this point in the history
Signed-off-by: oilbeater <[email protected]>
  • Loading branch information
oilbeater committed Oct 17, 2024
1 parent 1c19fc7 commit 61c33b0
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions pkg/controller/network_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,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, %w", err)
}
Expand All @@ -692,11 +693,12 @@ func (c *Controller) svcMatchNetworkPolicies(svc *corev1.Service) ([]string, err
return nil, fmt.Errorf("failed to list netpols, %w", 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 61c33b0

Please sign in to comment.