@@ -19,6 +19,7 @@ package removepodshavingtoomanyrestarts
19
19
import (
20
20
"context"
21
21
"fmt"
22
+ "sort"
22
23
23
24
v1 "k8s.io/api/core/v1"
24
25
"k8s.io/apimachinery/pkg/runtime"
@@ -121,6 +122,15 @@ func (d *RemovePodsHavingTooManyRestarts) Deschedule(ctx context.Context, nodes
121
122
Err : fmt .Errorf ("error listing pods on a node: %v" , err ),
122
123
}
123
124
}
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
+ })
124
134
totalPods := len (pods )
125
135
loop:
126
136
for i := 0 ; i < totalPods ; i ++ {
@@ -145,11 +155,7 @@ func (d *RemovePodsHavingTooManyRestarts) Deschedule(ctx context.Context, nodes
145
155
func validateCanEvict (pod * v1.Pod , tooManyRestartsArgs * RemovePodsHavingTooManyRestartsArgs ) error {
146
156
var err error
147
157
148
- restarts := calcContainerRestartsFromStatuses (pod .Status .ContainerStatuses )
149
- if tooManyRestartsArgs .IncludingInitContainers {
150
- restarts += calcContainerRestartsFromStatuses (pod .Status .InitContainerStatuses )
151
- }
152
-
158
+ restarts := getPodTotalRestarts (pod , tooManyRestartsArgs .IncludingInitContainers )
153
159
if restarts < tooManyRestartsArgs .PodRestartThreshold {
154
160
err = fmt .Errorf ("number of container restarts (%v) not exceeding the threshold" , restarts )
155
161
}
@@ -165,3 +171,12 @@ func calcContainerRestartsFromStatuses(statuses []v1.ContainerStatus) int32 {
165
171
}
166
172
return restarts
167
173
}
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