diff --git a/pkg/framework/plugins/removepodshavingtoomanyrestarts/toomanyrestarts.go b/pkg/framework/plugins/removepodshavingtoomanyrestarts/toomanyrestarts.go index fb9656971..4379fcd8d 100644 --- a/pkg/framework/plugins/removepodshavingtoomanyrestarts/toomanyrestarts.go +++ b/pkg/framework/plugins/removepodshavingtoomanyrestarts/toomanyrestarts.go @@ -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 +}