1
0
mirror of https://github.com/kubernetes-sigs/descheduler.git synced 2026-01-26 05:14:13 +01:00

feature: sort pods by restarts count in RemovePodsHavingTooManyRestarts plugin

This commit is contained in:
googs1025
2025-05-09 13:15:38 +08:00
parent e466307d7c
commit 0a691debfb

View File

@@ -19,6 +19,7 @@ package removepodshavingtoomanyrestarts
import (
"context"
"fmt"
"sort"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
@@ -121,6 +122,15 @@ func (d *RemovePodsHavingTooManyRestarts) Deschedule(ctx context.Context, nodes
Err: fmt.Errorf("error listing pods on a node: %v", err),
}
}
podRestarts := make(map[*v1.Pod]int32)
for _, pod := range pods {
podRestarts[pod] = getPodTotalRestarts(pod, d.args.IncludingInitContainers)
}
// sort pods by restarts count
sort.Slice(pods, func(i, j int) bool {
return podRestarts[pods[i]] > podRestarts[pods[j]]
})
totalPods := len(pods)
loop:
for i := 0; i < totalPods; i++ {
@@ -145,11 +155,7 @@ func (d *RemovePodsHavingTooManyRestarts) Deschedule(ctx context.Context, nodes
func validateCanEvict(pod *v1.Pod, tooManyRestartsArgs *RemovePodsHavingTooManyRestartsArgs) error {
var err error
restarts := calcContainerRestartsFromStatuses(pod.Status.ContainerStatuses)
if tooManyRestartsArgs.IncludingInitContainers {
restarts += calcContainerRestartsFromStatuses(pod.Status.InitContainerStatuses)
}
restarts := getPodTotalRestarts(pod, tooManyRestartsArgs.IncludingInitContainers)
if restarts < tooManyRestartsArgs.PodRestartThreshold {
err = fmt.Errorf("number of container restarts (%v) not exceeding the threshold", restarts)
}
@@ -165,3 +171,12 @@ func calcContainerRestartsFromStatuses(statuses []v1.ContainerStatus) int32 {
}
return restarts
}
// getPodTotalRestarts get total restarts of a pod.
func getPodTotalRestarts(pod *v1.Pod, includeInitContainers bool) int32 {
restarts := calcContainerRestartsFromStatuses(pod.Status.ContainerStatuses)
if includeInitContainers {
restarts += calcContainerRestartsFromStatuses(pod.Status.InitContainerStatuses)
}
return restarts
}