network-policy-api icon indicating copy to clipboard operation
network-policy-api copied to clipboard

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

Open gabrielggg opened this issue 8 months ago • 1 comments

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 avatar Jun 18 '24 21:06 gabrielggg