generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 262
/
scheduler.go
630 lines (567 loc) · 22.6 KB
/
scheduler.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/*
Copyright 2022 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 scheduler
import (
"context"
"fmt"
"maps"
"sort"
"strings"
"time"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/tools/record"
"k8s.io/klog/v2"
"k8s.io/utils/field"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
config "sigs.k8s.io/kueue/apis/config/v1beta1"
kueue "sigs.k8s.io/kueue/apis/kueue/v1beta1"
"sigs.k8s.io/kueue/pkg/cache"
"sigs.k8s.io/kueue/pkg/features"
"sigs.k8s.io/kueue/pkg/metrics"
"sigs.k8s.io/kueue/pkg/queue"
"sigs.k8s.io/kueue/pkg/scheduler/flavorassigner"
"sigs.k8s.io/kueue/pkg/scheduler/preemption"
"sigs.k8s.io/kueue/pkg/util/api"
"sigs.k8s.io/kueue/pkg/util/limitrange"
utilmaps "sigs.k8s.io/kueue/pkg/util/maps"
"sigs.k8s.io/kueue/pkg/util/priority"
"sigs.k8s.io/kueue/pkg/util/resource"
"sigs.k8s.io/kueue/pkg/util/routine"
"sigs.k8s.io/kueue/pkg/util/wait"
"sigs.k8s.io/kueue/pkg/workload"
)
const (
errCouldNotAdmitWL = "Could not admit Workload and assign flavors in apiserver"
)
type Scheduler struct {
queues *queue.Manager
cache *cache.Cache
client client.Client
recorder record.EventRecorder
admissionRoutineWrapper routine.Wrapper
preemptor *preemption.Preemptor
workloadOrdering workload.Ordering
fairSharing config.FairSharing
// Stubs.
applyAdmission func(context.Context, *kueue.Workload) error
}
type options struct {
podsReadyRequeuingTimestamp config.RequeuingTimestamp
fairSharing config.FairSharing
}
// Option configures the reconciler.
type Option func(*options)
var defaultOptions = options{
podsReadyRequeuingTimestamp: config.EvictionTimestamp,
}
// WithPodsReadyRequeuingTimestamp sets the timestamp that is used for ordering
// workloads that have been requeued due to the PodsReady condition.
func WithPodsReadyRequeuingTimestamp(ts config.RequeuingTimestamp) Option {
return func(o *options) {
o.podsReadyRequeuingTimestamp = ts
}
}
func WithFairSharing(fs *config.FairSharing) Option {
return func(o *options) {
if fs != nil {
o.fairSharing = *fs
}
}
}
func New(queues *queue.Manager, cache *cache.Cache, cl client.Client, recorder record.EventRecorder, opts ...Option) *Scheduler {
options := defaultOptions
for _, opt := range opts {
opt(&options)
}
wo := workload.Ordering{
PodsReadyRequeuingTimestamp: options.podsReadyRequeuingTimestamp,
}
s := &Scheduler{
fairSharing: options.fairSharing,
queues: queues,
cache: cache,
client: cl,
recorder: recorder,
preemptor: preemption.New(cl, wo, recorder, options.fairSharing),
admissionRoutineWrapper: routine.DefaultWrapper,
workloadOrdering: wo,
}
s.applyAdmission = s.applyAdmissionWithSSA
return s
}
// Start implements the Runnable interface to run scheduler as a controller.
func (s *Scheduler) Start(ctx context.Context) error {
log := ctrl.LoggerFrom(ctx).WithName("scheduler")
ctx = ctrl.LoggerInto(ctx, log)
go wait.UntilWithBackoff(ctx, s.schedule)
return nil
}
// NeedLeaderElection Implements LeaderElectionRunnable interface to make scheduler
// run in leader election mode
func (s *Scheduler) NeedLeaderElection() bool {
return true
}
func (s *Scheduler) setAdmissionRoutineWrapper(wrapper routine.Wrapper) {
s.admissionRoutineWrapper = wrapper
}
type cohortsUsage map[string]cache.FlavorResourceQuantities
func (cu *cohortsUsage) add(cohort string, assignment cache.FlavorResourceQuantities) {
cohortUsage := (*cu)[cohort]
if cohortUsage == nil {
cohortUsage = make(cache.FlavorResourceQuantities, len(assignment))
}
for flavor, resources := range assignment {
if _, found := cohortUsage[flavor]; found {
cohortUsage[flavor] = utilmaps.Merge(cohortUsage[flavor], resources, func(a, b int64) int64 { return a + b })
} else {
cohortUsage[flavor] = maps.Clone(resources)
}
}
(*cu)[cohort] = cohortUsage
}
func (cu *cohortsUsage) totalUsageForCommonFlavorResources(cohort string, assignment cache.FlavorResourceQuantities) cache.FlavorResourceQuantities {
return utilmaps.Intersect((*cu)[cohort], assignment, func(a, b workload.Requests) workload.Requests {
return utilmaps.Intersect(a, b, func(a, b int64) int64 { return a + b })
})
}
func (cu *cohortsUsage) hasCommonFlavorResources(cohort string, assignment cache.FlavorResourceQuantities) bool {
cohortUsage, cohortFound := (*cu)[cohort]
if !cohortFound {
return false
}
for flavor, assignmentResources := range assignment {
if cohortResources, found := cohortUsage[flavor]; found {
for resName := range assignmentResources {
if _, found := cohortResources[resName]; found {
return true
}
}
}
}
return false
}
func (s *Scheduler) schedule(ctx context.Context) wait.SpeedSignal {
log := ctrl.LoggerFrom(ctx)
// 1. Get the heads from the queues, including their desired clusterQueue.
// This operation blocks while the queues are empty.
headWorkloads := s.queues.Heads(ctx)
// If there are no elements, it means that the program is finishing.
if len(headWorkloads) == 0 {
return wait.KeepGoing
}
startTime := time.Now()
// 2. Take a snapshot of the cache.
snapshot := s.cache.Snapshot()
logSnapshotIfVerbose(log, &snapshot)
// 3. Calculate requirements (resource flavors, borrowing) for admitting workloads.
entries := s.nominate(ctx, headWorkloads, snapshot)
// 4. Sort entries based on borrowing, priorities (if enabled) and timestamps.
sort.Sort(entryOrdering{
enableFairSharing: s.fairSharing.Enable,
entries: entries,
workloadOrdering: s.workloadOrdering,
})
// 5. Admit entries, ensuring that no more than one workload gets
// admitted by a cohort (if borrowing).
// This is because there can be other workloads deeper in a clusterQueue whose
// head got admitted that should be scheduled in the cohort before the heads
// of other clusterQueues.
cycleCohortsUsage := cohortsUsage{}
cycleCohortsSkipPreemption := sets.New[string]()
for i := range entries {
e := &entries[i]
mode := e.assignment.RepresentativeMode()
if mode == flavorassigner.NoFit {
continue
}
cq := snapshot.ClusterQueues[e.ClusterQueue]
if cq.Cohort != nil {
sum := cycleCohortsUsage.totalUsageForCommonFlavorResources(cq.Cohort.Name, e.assignment.Usage)
// Check whether there was an assignment in this cycle that could render the next assignments invalid:
// - If the workload no longer fits in the cohort.
// - If there was another assignment in the cohort, then the preemption calculation is no longer valid.
if cycleCohortsUsage.hasCommonFlavorResources(cq.Cohort.Name, e.assignment.Usage) &&
((mode == flavorassigner.Fit && !cq.FitInCohort(sum)) ||
(mode == flavorassigner.Preempt && cycleCohortsSkipPreemption.Has(cq.Cohort.Name))) {
e.status = skipped
e.inadmissibleMsg = "other workloads in the cohort were prioritized"
// When the workload needs borrowing and there is another workload in cohort doesn't
// need borrowing, the workload needborrowing will come again. In this case we should
// not skip the previous flavors.
e.LastAssignment = nil
continue
}
// Even if the workload will not be admitted after this point, due to preemption pending or other failures,
// we should still account for its usage.
cycleCohortsUsage.add(cq.Cohort.Name, resourcesToReserve(e, cq))
}
log := log.WithValues("workload", klog.KObj(e.Obj), "clusterQueue", klog.KRef("", e.ClusterQueue))
ctx := ctrl.LoggerInto(ctx, log)
if e.assignment.RepresentativeMode() != flavorassigner.Fit {
if len(e.preemptionTargets) != 0 {
// If preemptions are issued, the next attempt should try all the flavors.
e.LastAssignment = nil
preempted, err := s.preemptor.IssuePreemptions(ctx, &e.Info, e.preemptionTargets, cq)
if err != nil {
log.Error(err, "Failed to preempt workloads")
}
if preempted != 0 {
e.inadmissibleMsg += fmt.Sprintf(". Pending the preemption of %d workload(s)", preempted)
e.requeueReason = queue.RequeueReasonPendingPreemption
}
if cq.Cohort != nil {
cycleCohortsSkipPreemption.Insert(cq.Cohort.Name)
}
} else {
log.V(2).Info("Workload requires preemption, but there are no candidate workloads allowed for preemption", "preemption", cq.Preemption)
}
continue
}
if !s.cache.PodsReadyForAllAdmittedWorkloads(log) {
log.V(5).Info("Waiting for all admitted workloads to be in the PodsReady condition")
// If WaitForPodsReady is enabled and WaitForPodsReady.BlockAdmission is true
// Block admission until all currently admitted workloads are in
// PodsReady condition if the waitForPodsReady is enabled
workload.UnsetQuotaReservationWithCondition(e.Obj, "Waiting", "waiting for all admitted workloads to be in PodsReady condition")
if err := workload.ApplyAdmissionStatus(ctx, s.client, e.Obj, false); err != nil {
log.Error(err, "Could not update Workload status")
}
s.cache.WaitForPodsReady(ctx)
log.V(5).Info("Finished waiting for all admitted workloads to be in the PodsReady condition")
}
e.status = nominated
if err := s.admit(ctx, e, cq); err != nil {
e.inadmissibleMsg = fmt.Sprintf("Failed to admit workload: %v", err)
}
if cq.Cohort != nil {
cycleCohortsSkipPreemption.Insert(cq.Cohort.Name)
}
}
// 6. Requeue the heads that were not scheduled.
result := metrics.AdmissionResultInadmissible
for _, e := range entries {
logAdmissionAttemptIfVerbose(log, &e)
if e.status != assumed {
s.requeueAndUpdate(log, ctx, e)
} else {
result = metrics.AdmissionResultSuccess
}
}
metrics.AdmissionAttempt(result, time.Since(startTime))
if result != metrics.AdmissionResultSuccess {
return wait.SlowDown
}
return wait.KeepGoing
}
type entryStatus string
const (
// indicates if the workload was nominated for admission.
nominated entryStatus = "nominated"
// indicates if the workload was skipped in this cycle.
skipped entryStatus = "skipped"
// indicates if the workload was assumed to have been admitted.
assumed entryStatus = "assumed"
// indicates that the workload was never nominated for admission.
notNominated entryStatus = ""
)
// entry holds requirements for a workload to be admitted by a clusterQueue.
type entry struct {
// workload.Info holds the workload from the API as well as resource usage
// and flavors assigned.
workload.Info
dominantResourceShare int
dominantResourceName corev1.ResourceName
assignment flavorassigner.Assignment
status entryStatus
inadmissibleMsg string
requeueReason queue.RequeueReason
preemptionTargets []*workload.Info
}
// nominate returns the workloads with their requirements (resource flavors, borrowing) if
// they were admitted by the clusterQueues in the snapshot.
func (s *Scheduler) nominate(ctx context.Context, workloads []workload.Info, snap cache.Snapshot) []entry {
log := ctrl.LoggerFrom(ctx)
entries := make([]entry, 0, len(workloads))
for _, w := range workloads {
log := log.WithValues("workload", klog.KObj(w.Obj), "clusterQueue", klog.KRef("", w.ClusterQueue))
cq := snap.ClusterQueues[w.ClusterQueue]
ns := corev1.Namespace{}
e := entry{Info: w}
if s.cache.IsAssumedOrAdmittedWorkload(w) {
log.Info("Workload skipped from admission because it's already assumed or admitted", "workload", klog.KObj(w.Obj))
continue
} else if workload.HasRetryChecks(w.Obj) || workload.HasRejectedChecks(w.Obj) {
e.inadmissibleMsg = "The workload has failed admission checks"
} else if snap.InactiveClusterQueueSets.Has(w.ClusterQueue) {
e.inadmissibleMsg = fmt.Sprintf("ClusterQueue %s is inactive", w.ClusterQueue)
} else if cq == nil {
e.inadmissibleMsg = fmt.Sprintf("ClusterQueue %s not found", w.ClusterQueue)
} else if err := s.client.Get(ctx, types.NamespacedName{Name: w.Obj.Namespace}, &ns); err != nil {
e.inadmissibleMsg = fmt.Sprintf("Could not obtain workload namespace: %v", err)
} else if !cq.NamespaceSelector.Matches(labels.Set(ns.Labels)) {
e.inadmissibleMsg = "Workload namespace doesn't match ClusterQueue selector"
e.requeueReason = queue.RequeueReasonNamespaceMismatch
} else if err := s.validateResources(&w); err != nil {
e.inadmissibleMsg = err.Error()
} else if err := s.validateLimitRange(ctx, &w); err != nil {
e.inadmissibleMsg = err.Error()
} else {
e.assignment, e.preemptionTargets = s.getAssignments(log, &e.Info, &snap)
e.inadmissibleMsg = e.assignment.Message()
e.Info.LastAssignment = &e.assignment.LastState
if s.fairSharing.Enable {
e.dominantResourceShare, e.dominantResourceName = cq.DominantResourceShareWith(e.assignment.TotalRequestsFor(&w))
}
}
entries = append(entries, e)
}
return entries
}
// resourcesToReserve calculates how much of the available resources in cq/cohort assignment should be reserved.
func resourcesToReserve(e *entry, cq *cache.ClusterQueue) cache.FlavorResourceQuantities {
if e.assignment.RepresentativeMode() != flavorassigner.Preempt {
return e.assignment.Usage
}
reservedUsage := make(cache.FlavorResourceQuantities)
for flavor, resourceUsage := range e.assignment.Usage {
reservedUsage[flavor] = make(map[corev1.ResourceName]int64)
for resource, usage := range resourceUsage {
rg := cq.RGByResource[resource]
cqQuota := cache.ResourceQuota{}
for _, cqFlavor := range rg.Flavors {
if cqFlavor.Name == flavor {
cqQuota = *cqFlavor.Resources[resource]
break
}
}
if !e.assignment.Borrowing {
reservedUsage[flavor][resource] = max(0, min(usage, cqQuota.Nominal-cq.Usage[flavor][resource]))
} else {
if cqQuota.BorrowingLimit == nil {
reservedUsage[flavor][resource] = usage
} else {
reservedUsage[flavor][resource] = min(usage, cqQuota.Nominal+*cqQuota.BorrowingLimit-cq.Usage[flavor][resource])
}
}
}
}
return reservedUsage
}
type partialAssignment struct {
assignment flavorassigner.Assignment
preemptionTargets []*workload.Info
}
func (s *Scheduler) getAssignments(log logr.Logger, wl *workload.Info, snap *cache.Snapshot) (flavorassigner.Assignment, []*workload.Info) {
cq := snap.ClusterQueues[wl.ClusterQueue]
flvAssigner := flavorassigner.New(wl, cq, snap.ResourceFlavors, s.fairSharing.Enable)
fullAssignment := flvAssigner.Assign(log, nil)
var faPreemtionTargets []*workload.Info
arm := fullAssignment.RepresentativeMode()
if arm == flavorassigner.Fit {
return fullAssignment, nil
}
if arm == flavorassigner.Preempt {
faPreemtionTargets = s.preemptor.GetTargets(*wl, fullAssignment, snap)
}
// if the feature gate is not enabled or we can preempt
if !features.Enabled(features.PartialAdmission) || len(faPreemtionTargets) > 0 {
return fullAssignment, faPreemtionTargets
}
if wl.CanBePartiallyAdmitted() {
reducer := flavorassigner.NewPodSetReducer(wl.Obj.Spec.PodSets, func(nextCounts []int32) (*partialAssignment, bool) {
assignment := flvAssigner.Assign(log, nextCounts)
if assignment.RepresentativeMode() == flavorassigner.Fit {
return &partialAssignment{assignment: assignment}, true
}
preemptionTargets := s.preemptor.GetTargets(*wl, assignment, snap)
if len(preemptionTargets) > 0 {
return &partialAssignment{assignment: assignment, preemptionTargets: preemptionTargets}, true
}
return nil, false
})
if pa, found := reducer.Search(); found {
return pa.assignment, pa.preemptionTargets
}
}
return fullAssignment, nil
}
// validateResources validates that requested resources are less or equal
// to limits.
func (s *Scheduler) validateResources(wi *workload.Info) error {
podsetsPath := field.NewPath("podSets")
// requests should be less than limits.
allReasons := []string{}
for i := range wi.Obj.Spec.PodSets {
ps := &wi.Obj.Spec.PodSets[i]
psPath := podsetsPath.Child(ps.Name)
for i := range ps.Template.Spec.InitContainers {
c := ps.Template.Spec.InitContainers[i]
if list := resource.GetGreaterKeys(c.Resources.Requests, c.Resources.Limits); len(list) > 0 {
allReasons = append(allReasons, fmt.Sprintf("%s[%s] requests exceed it's limits",
psPath.Child("initContainers").Index(i).String(),
strings.Join(list, ", ")))
}
}
for i := range ps.Template.Spec.Containers {
c := ps.Template.Spec.Containers[i]
if list := resource.GetGreaterKeys(c.Resources.Requests, c.Resources.Limits); len(list) > 0 {
allReasons = append(allReasons, fmt.Sprintf("%s[%s] requests exceed it's limits",
psPath.Child("containers").Index(i).String(),
strings.Join(list, ", ")))
}
}
}
if len(allReasons) > 0 {
return fmt.Errorf("resource validation failed: %s", strings.Join(allReasons, "; "))
}
return nil
}
// validateLimitRange validates that the requested resources fit into the namespace defined
// limitRanges.
func (s *Scheduler) validateLimitRange(ctx context.Context, wi *workload.Info) error {
podsetsPath := field.NewPath("podSets")
// get the range summary from the namespace.
list := corev1.LimitRangeList{}
if err := s.client.List(ctx, &list, &client.ListOptions{Namespace: wi.Obj.Namespace}); err != nil {
return err
}
if len(list.Items) == 0 {
return nil
}
summary := limitrange.Summarize(list.Items...)
// verify
allReasons := []string{}
for i := range wi.Obj.Spec.PodSets {
ps := &wi.Obj.Spec.PodSets[i]
allReasons = append(allReasons, summary.ValidatePodSpec(&ps.Template.Spec, podsetsPath.Child(ps.Name))...)
}
if len(allReasons) > 0 {
return fmt.Errorf("didn't satisfy LimitRange constraints: %s", strings.Join(allReasons, "; "))
}
return nil
}
// admit sets the admitting clusterQueue and flavors into the workload of
// the entry, and asynchronously updates the object in the apiserver after
// assuming it in the cache.
func (s *Scheduler) admit(ctx context.Context, e *entry, cq *cache.ClusterQueue) error {
log := ctrl.LoggerFrom(ctx)
newWorkload := e.Obj.DeepCopy()
admission := &kueue.Admission{
ClusterQueue: kueue.ClusterQueueReference(e.ClusterQueue),
PodSetAssignments: e.assignment.ToAPI(),
}
workload.SetQuotaReservation(newWorkload, admission)
if workload.HasAllChecks(newWorkload, workload.AdmissionChecksForWorkload(log, newWorkload, cq.AdmissionChecks)) {
// sync Admitted, ignore the result since an API update is always done.
_ = workload.SyncAdmittedCondition(newWorkload)
}
if err := s.cache.AssumeWorkload(newWorkload); err != nil {
return err
}
e.status = assumed
log.V(2).Info("Workload assumed in the cache")
s.admissionRoutineWrapper.Run(func() {
err := s.applyAdmission(ctx, newWorkload)
if err == nil {
waitTime := workload.QueuedWaitTime(newWorkload)
s.recorder.Eventf(newWorkload, corev1.EventTypeNormal, "QuotaReserved", "Quota reserved in ClusterQueue %v, wait time since queued was %.0fs", admission.ClusterQueue, waitTime.Seconds())
metrics.QuotaReservedWorkload(admission.ClusterQueue, waitTime)
if workload.IsAdmitted(newWorkload) {
s.recorder.Eventf(newWorkload, corev1.EventTypeNormal, "Admitted", "Admitted by ClusterQueue %v, wait time since reservation was 0s", admission.ClusterQueue)
metrics.AdmittedWorkload(admission.ClusterQueue, waitTime)
if len(newWorkload.Status.AdmissionChecks) > 0 {
metrics.AdmissionChecksWaitTime(admission.ClusterQueue, 0)
}
}
log.V(2).Info("Workload successfully admitted and assigned flavors", "assignments", admission.PodSetAssignments)
return
}
// Ignore errors because the workload or clusterQueue could have been deleted
// by an event.
_ = s.cache.ForgetWorkload(newWorkload)
if errors.IsNotFound(err) {
log.V(2).Info("Workload not admitted because it was deleted")
return
}
log.Error(err, errCouldNotAdmitWL)
s.requeueAndUpdate(log, ctx, *e)
})
return nil
}
func (s *Scheduler) applyAdmissionWithSSA(ctx context.Context, w *kueue.Workload) error {
return workload.ApplyAdmissionStatus(ctx, s.client, w, false)
}
type entryOrdering struct {
enableFairSharing bool
entries []entry
workloadOrdering workload.Ordering
}
func (e entryOrdering) Len() int {
return len(e.entries)
}
func (e entryOrdering) Swap(i, j int) {
e.entries[i], e.entries[j] = e.entries[j], e.entries[i]
}
// Less is the ordering criteria:
// 1. request under nominal quota before borrowing.
// 2. higher priority first.
// 3. FIFO on eviction or creation timestamp.
func (e entryOrdering) Less(i, j int) bool {
a := e.entries[i]
b := e.entries[j]
// 1. Request under nominal quota.
aBorrows := a.assignment.Borrows()
bBorrows := b.assignment.Borrows()
if aBorrows != bBorrows {
return !aBorrows
}
// 2. Fair share, if enabled.
if e.enableFairSharing && a.dominantResourceShare != b.dominantResourceShare {
return a.dominantResourceShare < b.dominantResourceShare
}
// 3. Higher priority first if not disabled.
if features.Enabled(features.PrioritySortingWithinCohort) {
p1 := priority.Priority(a.Obj)
p2 := priority.Priority(b.Obj)
if p1 != p2 {
return p1 > p2
}
}
// 4. FIFO.
aComparisonTimestamp := e.workloadOrdering.GetQueueOrderTimestamp(a.Obj)
bComparisonTimestamp := e.workloadOrdering.GetQueueOrderTimestamp(b.Obj)
return aComparisonTimestamp.Before(bComparisonTimestamp)
}
func (s *Scheduler) requeueAndUpdate(log logr.Logger, ctx context.Context, e entry) {
if e.status != notNominated && e.requeueReason == queue.RequeueReasonGeneric {
// Failed after nomination is the only reason why a workload would be requeued downstream.
e.requeueReason = queue.RequeueReasonFailedAfterNomination
}
added := s.queues.RequeueWorkload(ctx, &e.Info, e.requeueReason)
log.V(2).Info("Workload re-queued", "workload", klog.KObj(e.Obj), "clusterQueue", klog.KRef("", e.ClusterQueue), "queue", klog.KRef(e.Obj.Namespace, e.Obj.Spec.QueueName), "requeueReason", e.requeueReason, "added", added)
if e.status == notNominated || e.status == skipped {
if workload.UnsetQuotaReservationWithCondition(e.Obj, "Pending", e.inadmissibleMsg) {
err := workload.ApplyAdmissionStatus(ctx, s.client, e.Obj, true)
if err != nil {
log.Error(err, "Could not update Workload status")
}
}
s.recorder.Eventf(e.Obj, corev1.EventTypeNormal, "Pending", api.TruncateEventMessage(e.inadmissibleMsg))
}
}