kubernetes-sigs / network-policy-api

This repo addresses further work involving Kubernetes network security beyond the initial NetworkPolicy resource
Apache License 2.0
54 stars 29 forks source link

[Policy Assistant] Avoid unnecessary api calls to get all the pods in the namespace. #236

Open gabrielggg opened 3 months ago

gabrielggg commented 3 months ago

When calling functions that use the translate func (for example DeploymentsToTrafficPeers func), we are getting all the pods on the namespace one time per each deployment on that specific namespace , so that is not correct. Ideally, we'd get all pods in the namespace only once.

Example code snippet from DeploymentsToTrafficPeers func to take as reference (source file: https://github.com/kubernetes-sigs/network-policy-api/blob/main/cmd/policy-assistant/pkg/matcher/traffic.go):

for _, deployment := range kubeDeployments {
            tmpInternalPeer := InternalPeer{
                Workload: namespace.Name + "/deployment/" + deployment.Name,
            }
            tmpPeer := TrafficPeer{
                Internal: &tmpInternalPeer,
            }
            tmpPeerTranslated := tmpPeer.Translate() //here we are calling the translate func inside a loop and 
                        //the translate func is making the same api call to the api server multiple times
            if tmpPeerTranslated.Internal.Workload != "" {
                deploymentPeers = append(deploymentPeers, tmpPeerTranslated)
            }

        }

And inside the translate func we are doing this call:

 utils.DoOrDie(err)
 ns, err := kubeClient.GetNamespace(workloadMetadata[0])
 utils.DoOrDie(err)
 kubePods, err := kube.GetPodsInNamespaces(kubeClient, []string{workloadMetadata[0]})

_Originally posted by @huntergregory in https://github.com/kubernetes-sigs/network-policy-api/pull/227#discussion_r1645048124_

gabrielggg commented 3 months ago

/assign