generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 301
/
Copy pathpreemption.go
382 lines (345 loc) · 12.4 KB
/
preemption.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/*
Copyright 2023 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package preemption
import (
"context"
"sort"
"sync/atomic"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/workqueue"
"k8s.io/klog/v2"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
kueue "sigs.k8s.io/kueue/apis/kueue/v1beta1"
"sigs.k8s.io/kueue/pkg/cache"
"sigs.k8s.io/kueue/pkg/scheduler/flavorassigner"
"sigs.k8s.io/kueue/pkg/util/priority"
"sigs.k8s.io/kueue/pkg/util/routine"
"sigs.k8s.io/kueue/pkg/workload"
)
const parallelPreemptions = 8
type Preemptor struct {
client client.Client
recorder record.EventRecorder
// stubs
applyPreemption func(context.Context, *kueue.Workload) error
}
func New(cl client.Client, recorder record.EventRecorder) *Preemptor {
p := &Preemptor{
client: cl,
recorder: recorder,
}
p.applyPreemption = p.applyPreemptionWithSSA
return p
}
func (p *Preemptor) OverrideApply(f func(context.Context, *kueue.Workload) error) {
p.applyPreemption = f
}
func candidatesOnlyFromQueue(candidates []*workload.Info, clusterQueue string) []*workload.Info {
result := make([]*workload.Info, 0)
for _, wi := range candidates {
if wi.ClusterQueue == clusterQueue {
result = append(result, wi)
}
}
return result
}
// GetTargets returns the list of workloads that should be evicted in order to make room for wl.
func (p *Preemptor) GetTargets(wl workload.Info, assignment flavorassigner.Assignment, snapshot *cache.Snapshot) []*workload.Info {
resPerFlv := resourcesRequiringPreemption(assignment)
cq := snapshot.ClusterQueues[wl.ClusterQueue]
candidates := findCandidates(wl.Obj, cq, resPerFlv)
if len(candidates) == 0 {
return nil
}
sort.Slice(candidates, candidatesOrdering(candidates, cq.Name, time.Now()))
sameQueueCandidates := candidatesOnlyFromQueue(candidates, wl.ClusterQueue)
var targets []*workload.Info
// To avoid flapping, Kueue only allows preemption of workloads from the same
// queue if borrowing. Preemption of workloads from queues can happen only
// if not borrowing at the same time. Kueue prioritizes preemption of
// workloads from the other queues (that borrowed resources) first, before
// trying to preempt more own workloads and borrow at the same time.
if len(sameQueueCandidates) == len(candidates) {
// There is no risk of preemption of workloads from the other queue,
// so we can try borrowing.
targets = minimalPreemptions(&wl, assignment, snapshot, resPerFlv, candidates, true)
} else {
// There is a risk of preemption of workloads from the other queue in the
// cohort, proceeding without borrowing.
targets = minimalPreemptions(&wl, assignment, snapshot, resPerFlv, candidates, false)
if len(targets) == 0 {
// Another attempt. This time only candidates from the same queue, but
// with borrowing. The previous attempt didn't try borrowing and had broader
// scope of preemption.
targets = minimalPreemptions(&wl, assignment, snapshot, resPerFlv, sameQueueCandidates, true)
}
}
return targets
}
// IssuePreemptions marks the target workloads as evicted.
func (p *Preemptor) IssuePreemptions(ctx context.Context, targets []*workload.Info, cq *cache.ClusterQueue) (int, error) {
log := ctrl.LoggerFrom(ctx)
errCh := routine.NewErrorChannel()
ctx, cancel := context.WithCancel(ctx)
var successfullyPreempted int64
defer cancel()
workqueue.ParallelizeUntil(ctx, parallelPreemptions, len(targets), func(i int) {
target := targets[i]
if !meta.IsStatusConditionTrue(target.Obj.Status.Conditions, kueue.WorkloadEvicted) {
err := p.applyPreemption(ctx, target.Obj)
if err != nil {
errCh.SendErrorWithCancel(err, cancel)
return
}
origin := "ClusterQueue"
if cq.Name != target.ClusterQueue {
origin = "cohort"
}
log.V(3).Info("Preempted", "targetWorkload", klog.KObj(target.Obj))
p.recorder.Eventf(target.Obj, corev1.EventTypeNormal, "Preempted", "Preempted by another workload in the %s", origin)
} else {
log.V(3).Info("Preemption ongoing", "targetWorkload", klog.KObj(target.Obj))
}
atomic.AddInt64(&successfullyPreempted, 1)
})
return int(successfullyPreempted), errCh.ReceiveError()
}
func (p *Preemptor) applyPreemptionWithSSA(ctx context.Context, w *kueue.Workload) error {
w = w.DeepCopy()
workload.SetEvictedCondition(w, kueue.WorkloadEvictedByPreemption, "Preempted to accommodate a higher priority Workload")
return workload.ApplyAdmissionStatus(ctx, p.client, w, false)
}
// minimalPreemptions implements a heuristic to find a minimal set of Workloads
// to preempt.
// The heuristic first removes candidates, in the input order, while their
// ClusterQueues are still borrowing resources and while the incoming Workload
// doesn't fit in the quota.
// Once the Workload fits, the heuristic tries to add Workloads back, in the
// reverse order in which they were removed, while the incoming Workload still
// fits.
func minimalPreemptions(wl *workload.Info, assignment flavorassigner.Assignment, snapshot *cache.Snapshot, resPerFlv resourcesPerFlavor, candidates []*workload.Info, allowBorrowing bool) []*workload.Info {
wlReq := totalRequestsForAssignment(wl, assignment)
cq := snapshot.ClusterQueues[wl.ClusterQueue]
// Simulate removing all candidates from the ClusterQueue and cohort.
var targets []*workload.Info
fits := false
for _, candWl := range candidates {
candCQ := snapshot.ClusterQueues[candWl.ClusterQueue]
if cq != candCQ && !cqIsBorrowing(candCQ, resPerFlv) {
continue
}
snapshot.RemoveWorkload(candWl)
targets = append(targets, candWl)
if workloadFits(wlReq, cq, allowBorrowing) {
fits = true
break
}
}
if !fits {
// Reset changes to the snapshot.
for _, t := range targets {
snapshot.AddWorkload(t)
}
return nil
}
// In the reverse order, check if any of the workloads can be added back.
for i := len(targets) - 2; i >= 0; i-- {
snapshot.AddWorkload(targets[i])
if workloadFits(wlReq, cq, allowBorrowing) {
// O(1) deletion: copy the last element into index i and reduce size.
targets[i] = targets[len(targets)-1]
targets = targets[:len(targets)-1]
} else {
snapshot.RemoveWorkload(targets[i])
}
}
// Reset changes to the snapshot.
for _, t := range targets {
snapshot.AddWorkload(t)
}
return targets
}
type resourcesPerFlavor map[kueue.ResourceFlavorReference]sets.Set[corev1.ResourceName]
func resourcesRequiringPreemption(assignment flavorassigner.Assignment) resourcesPerFlavor {
resPerFlavor := make(resourcesPerFlavor)
for _, ps := range assignment.PodSets {
for res, flvAssignment := range ps.Flavors {
// assignments with NoFit mode wouldn't enter the preemption path.
if flvAssignment.Mode != flavorassigner.Preempt {
continue
}
if resPerFlavor[flvAssignment.Name] == nil {
resPerFlavor[flvAssignment.Name] = sets.New(res)
} else {
resPerFlavor[flvAssignment.Name].Insert(res)
}
}
}
return resPerFlavor
}
// findCandidates obtains candidates for preemption within the ClusterQueue and
// cohort that respect the preemption policy and are using a resource that the
// preempting workload needs.
func findCandidates(wl *kueue.Workload, cq *cache.ClusterQueue, resPerFlv resourcesPerFlavor) []*workload.Info {
var candidates []*workload.Info
wlPriority := priority.Priority(wl)
if cq.Preemption.WithinClusterQueue != kueue.PreemptionPolicyNever {
considerSamePrio := (cq.Preemption.WithinClusterQueue == kueue.PreemptionPolicyLowerOrNewerEqualPriority)
preemptorTS := workload.GetQueueOrderTimestamp(wl)
for _, candidateWl := range cq.Workloads {
candidatePriority := priority.Priority(candidateWl.Obj)
if candidatePriority > wlPriority {
continue
}
if candidatePriority == wlPriority && !(considerSamePrio && preemptorTS.Before(workload.GetQueueOrderTimestamp(candidateWl.Obj))) {
continue
}
if !workloadUsesResources(candidateWl, resPerFlv) {
continue
}
candidates = append(candidates, candidateWl)
}
}
if cq.Cohort != nil && cq.Preemption.ReclaimWithinCohort != kueue.PreemptionPolicyNever {
for cohortCQ := range cq.Cohort.Members {
if cq == cohortCQ || !cqIsBorrowing(cohortCQ, resPerFlv) {
// Can't reclaim quota from itself or ClusterQueues that are not borrowing.
continue
}
onlyLowerPrio := true
if cq.Preemption.ReclaimWithinCohort == kueue.PreemptionPolicyAny {
onlyLowerPrio = false
}
for _, candidateWl := range cohortCQ.Workloads {
if onlyLowerPrio && priority.Priority(candidateWl.Obj) >= priority.Priority(wl) {
continue
}
if !workloadUsesResources(candidateWl, resPerFlv) {
continue
}
candidates = append(candidates, candidateWl)
}
}
}
return candidates
}
func cqIsBorrowing(cq *cache.ClusterQueue, resPerFlv resourcesPerFlavor) bool {
if cq.Cohort == nil {
return false
}
for _, rg := range cq.ResourceGroups {
for _, fQuotas := range rg.Flavors {
fUsage := cq.Usage[fQuotas.Name]
for rName := range resPerFlv[fQuotas.Name] {
if fUsage[rName] > fQuotas.Resources[rName].Nominal {
return true
}
}
}
}
return false
}
func workloadUsesResources(wl *workload.Info, resPerFlv resourcesPerFlavor) bool {
for _, ps := range wl.TotalRequests {
for res, flv := range ps.Flavors {
if resPerFlv[flv].Has(res) {
return true
}
}
}
return false
}
func totalRequestsForAssignment(wl *workload.Info, assignment flavorassigner.Assignment) cache.FlavorResourceQuantities {
usage := make(cache.FlavorResourceQuantities)
for i, ps := range wl.TotalRequests {
for res, q := range ps.Requests {
flv := assignment.PodSets[i].Flavors[res].Name
resUsage := usage[flv]
if resUsage == nil {
resUsage = make(map[corev1.ResourceName]int64)
usage[flv] = resUsage
}
resUsage[res] += q
}
}
return usage
}
// workloadFits determines if the workload requests would fits given the
// requestable resources and simulated usage of the ClusterQueue and its cohort,
// if it belongs to one.
func workloadFits(wlReq cache.FlavorResourceQuantities, cq *cache.ClusterQueue, allowBorrowing bool) bool {
for _, rg := range cq.ResourceGroups {
for _, flvQuotas := range rg.Flavors {
flvReq, found := wlReq[flvQuotas.Name]
if !found {
// Workload doesn't request this flavor.
continue
}
cqResUsage := cq.Usage[flvQuotas.Name]
var cohortResUsage, cohortResRequestable map[corev1.ResourceName]int64
if cq.Cohort != nil {
cohortResUsage = cq.Cohort.Usage[flvQuotas.Name]
cohortResRequestable = cq.Cohort.RequestableResources[flvQuotas.Name]
}
for rName, rReq := range flvReq {
limit := flvQuotas.Resources[rName].Nominal
if flvQuotas.Resources[rName].BorrowingLimit != nil && allowBorrowing {
limit += *flvQuotas.Resources[rName].BorrowingLimit
}
if cqResUsage[rName]+rReq > limit {
return false
}
if cq.Cohort != nil && cohortResUsage[rName]+rReq > cohortResRequestable[rName] {
return false
}
}
}
}
return true
}
// candidatesOrdering criteria:
// 1. Workloads from other ClusterQueues in the cohort before the ones in the
// same ClusterQueue as the preemptor.
// 2. Workloads with lower priority first.
// 3. Workloads admited more recently first.
func candidatesOrdering(candidates []*workload.Info, cq string, now time.Time) func(int, int) bool {
return func(i, j int) bool {
a := candidates[i]
b := candidates[j]
aInCQ := a.ClusterQueue == cq
bInCQ := b.ClusterQueue == cq
if aInCQ != bInCQ {
return !aInCQ
}
pa := priority.Priority(a.Obj)
pb := priority.Priority(b.Obj)
if pa != pb {
return pa < pb
}
return admisionTime(b.Obj, now).Before(admisionTime(a.Obj, now))
}
}
func admisionTime(wl *kueue.Workload, now time.Time) time.Time {
cond := meta.FindStatusCondition(wl.Status.Conditions, kueue.WorkloadAdmitted)
if cond == nil || cond.Status != metav1.ConditionTrue {
// The condition wasn't populated yet, use the current time.
return now
}
return cond.LastTransitionTime.Time
}