Skip to content

Commit 8b0ae7c

Browse files
authored
Merge pull request #1686 from googs1025/add_sort
feature: sort pods by restarts count in RemovePodsHavingTooManyRestarts plugin
2 parents e466307 + 0a691de commit 8b0ae7c

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

pkg/framework/plugins/removepodshavingtoomanyrestarts/toomanyrestarts.go

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package removepodshavingtoomanyrestarts
1919
import (
2020
"context"
2121
"fmt"
22+
"sort"
2223

2324
v1 "k8s.io/api/core/v1"
2425
"k8s.io/apimachinery/pkg/runtime"
@@ -121,6 +122,15 @@ func (d *RemovePodsHavingTooManyRestarts) Deschedule(ctx context.Context, nodes
121122
Err: fmt.Errorf("error listing pods on a node: %v", err),
122123
}
123124
}
125+
126+
podRestarts := make(map[*v1.Pod]int32)
127+
for _, pod := range pods {
128+
podRestarts[pod] = getPodTotalRestarts(pod, d.args.IncludingInitContainers)
129+
}
130+
// sort pods by restarts count
131+
sort.Slice(pods, func(i, j int) bool {
132+
return podRestarts[pods[i]] > podRestarts[pods[j]]
133+
})
124134
totalPods := len(pods)
125135
loop:
126136
for i := 0; i < totalPods; i++ {
@@ -145,11 +155,7 @@ func (d *RemovePodsHavingTooManyRestarts) Deschedule(ctx context.Context, nodes
145155
func validateCanEvict(pod *v1.Pod, tooManyRestartsArgs *RemovePodsHavingTooManyRestartsArgs) error {
146156
var err error
147157

148-
restarts := calcContainerRestartsFromStatuses(pod.Status.ContainerStatuses)
149-
if tooManyRestartsArgs.IncludingInitContainers {
150-
restarts += calcContainerRestartsFromStatuses(pod.Status.InitContainerStatuses)
151-
}
152-
158+
restarts := getPodTotalRestarts(pod, tooManyRestartsArgs.IncludingInitContainers)
153159
if restarts < tooManyRestartsArgs.PodRestartThreshold {
154160
err = fmt.Errorf("number of container restarts (%v) not exceeding the threshold", restarts)
155161
}
@@ -165,3 +171,12 @@ func calcContainerRestartsFromStatuses(statuses []v1.ContainerStatus) int32 {
165171
}
166172
return restarts
167173
}
174+
175+
// getPodTotalRestarts get total restarts of a pod.
176+
func getPodTotalRestarts(pod *v1.Pod, includeInitContainers bool) int32 {
177+
restarts := calcContainerRestartsFromStatuses(pod.Status.ContainerStatuses)
178+
if includeInitContainers {
179+
restarts += calcContainerRestartsFromStatuses(pod.Status.InitContainerStatuses)
180+
}
181+
return restarts
182+
}

0 commit comments

Comments
 (0)