kubeshark/kubernetes/utils.go
M. Mert Yildiran cb60a4cc4c
🔨 Move cli folder contents into project root (#1253)
* Remove `logger` module

* Remove `shared` module

* Move `cli` folder contents into project root

* Fix linter

* Change the module name from `github.com/kubeshark/kubeshark/cli` to `github.com/kubeshark/kubeshark`

* Set the default `Makefile` rule to `build`

* Add `lint` rule

* Fix the linter errors
2022-11-26 01:17:50 +03:00

96 lines
2.5 KiB
Go

package kubernetes
import (
"regexp"
"github.com/kubeshark/worker/models"
core "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func GetNodeHostToTappedPodsMap(tappedPods []core.Pod) models.NodeToPodsMap {
nodeToTappedPodMap := make(models.NodeToPodsMap)
for _, pod := range tappedPods {
minimizedPod := getMinimizedPod(pod)
existingList := nodeToTappedPodMap[pod.Spec.NodeName]
if existingList == nil {
nodeToTappedPodMap[pod.Spec.NodeName] = []core.Pod{minimizedPod}
} else {
nodeToTappedPodMap[pod.Spec.NodeName] = append(nodeToTappedPodMap[pod.Spec.NodeName], minimizedPod)
}
}
return nodeToTappedPodMap
}
func getMinimizedPod(fullPod core.Pod) core.Pod {
return core.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: fullPod.Name,
Namespace: fullPod.Namespace,
},
Status: core.PodStatus{
PodIP: fullPod.Status.PodIP,
ContainerStatuses: getMinimizedContainerStatuses(fullPod),
},
}
}
func getMinimizedContainerStatuses(fullPod core.Pod) []core.ContainerStatus {
result := make([]core.ContainerStatus, len(fullPod.Status.ContainerStatuses))
for i, container := range fullPod.Status.ContainerStatuses {
result[i] = core.ContainerStatus{
ContainerID: container.ContainerID,
}
}
return result
}
func excludeKubesharkPods(pods []core.Pod) []core.Pod {
kubesharkPrefixRegex := regexp.MustCompile("^" + KubesharkResourcesPrefix)
nonKubesharkPods := make([]core.Pod, 0)
for _, pod := range pods {
if !kubesharkPrefixRegex.MatchString(pod.Name) {
nonKubesharkPods = append(nonKubesharkPods, pod)
}
}
return nonKubesharkPods
}
func getPodArrayDiff(oldPods []core.Pod, newPods []core.Pod) (added []core.Pod, removed []core.Pod) {
added = getMissingPods(newPods, oldPods)
removed = getMissingPods(oldPods, newPods)
return added, removed
}
//returns pods present in pods1 array and missing in pods2 array
func getMissingPods(pods1 []core.Pod, pods2 []core.Pod) []core.Pod {
missingPods := make([]core.Pod, 0)
for _, pod1 := range pods1 {
var found = false
for _, pod2 := range pods2 {
if pod1.UID == pod2.UID {
found = true
break
}
}
if !found {
missingPods = append(missingPods, pod1)
}
}
return missingPods
}
func GetPodInfosForPods(pods []core.Pod) []*models.PodInfo {
podInfos := make([]*models.PodInfo, 0)
for _, pod := range pods {
podInfos = append(podInfos, &models.PodInfo{Name: pod.Name, Namespace: pod.Namespace, NodeName: pod.Spec.NodeName})
}
return podInfos
}