-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathqueuejob_controller_ex.go
2210 lines (1986 loc) · 101 KB
/
queuejob_controller_ex.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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2019, 2021, 2022 The Multi-Cluster App Dispatcher 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 queuejob
import (
"context"
jsons "encoding/json"
"errors"
"fmt"
"math"
"math/rand"
"reflect"
"runtime/debug"
"sort"
"strings"
"sync"
"time"
"github.com/eapache/go-resiliency/retrier"
"github.com/gogo/protobuf/proto"
"github.com/hashicorp/go-multierror"
qmutils "github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/quotaplugins/util"
"github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/controller/quota/quotaforestmanager"
dto "github.com/prometheus/client_model/go"
"github.com/project-codeflare/multi-cluster-app-dispatcher/cmd/kar-controllers/app/options"
"github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/controller/metrics/adapter"
"github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/controller/quota"
"k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/klog/v2"
v1 "k8s.io/api/core/v1"
"github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/controller/queuejobresources"
"github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/controller/queuejobresources/genericresource"
respod "github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/controller/queuejobresources/pod"
"k8s.io/apimachinery/pkg/labels"
arbv1 "github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/apis/controller/v1beta1"
clientset "github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/client/clientset/versioned"
informerFactory "github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/client/informers/externalversions"
arbinformers "github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/client/informers/externalversions/controller/v1beta1"
arblisters "github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/client/listers/controller/v1beta1"
"github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/controller/queuejobdispatch"
clusterstateapi "github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/controller/clusterstate/api"
clusterstatecache "github.com/project-codeflare/multi-cluster-app-dispatcher/pkg/controller/clusterstate/cache"
)
// XController the AppWrapper Controller type
type XController struct {
config *rest.Config
serverOption *options.ServerOption
appwrapperInformer arbinformers.AppWrapperInformer
// resources registered for the AppWrapper
qjobRegisteredResources queuejobresources.RegisteredResources
// controllers for these resources
qjobResControls map[arbv1.ResourceType]queuejobresources.Interface
// Captures all available resources in the cluster
genericresources *genericresource.GenericResources
clients *kubernetes.Clientset
arbclients *clientset.Clientset
// A store of jobs
appWrapperLister arblisters.AppWrapperLister
appWrapperSynced func() bool
// QueueJobs that need to be initialized
// Add labels and selectors to AppWrapper
initQueue *cache.FIFO
// QueueJobs that need to sync up after initialization
updateQueue *cache.FIFO
// eventQueue that need to sync up
eventQueue *cache.FIFO
// QJ queue that needs to be allocated
qjqueue SchedulingQueue
// our own local cache, used for computing total amount of resources
cache clusterstatecache.Cache
// is dispatcher or deployer?
isDispatcher bool
// Agent map: agentID -> JobClusterAgent
agentMap map[string]*queuejobdispatch.JobClusterAgent
agentList []string
// Map for AppWrapper -> JobClusterAgent
dispatchMap map[string]string
// Metrics API Server
metricsAdapter *adapter.MetricsAdapter
// EventQueueforAgent
agentEventQueue *cache.FIFO
// Quota Manager
quotaManager quota.QuotaManagerInterface
// Active Scheduling AppWrapper
schedulingAW *arbv1.AppWrapper
schedulingMutex sync.RWMutex
}
type JobAndClusterAgent struct {
queueJobKey string
queueJobAgentKey string
}
// RegisterAllQueueJobResourceTypes - registers all resources
func RegisterAllQueueJobResourceTypes(regs *queuejobresources.RegisteredResources) {
respod.Register(regs)
}
func GetQueueJobKey(obj interface{}) (string, error) {
qj, ok := obj.(*arbv1.AppWrapper)
if !ok {
return "", fmt.Errorf("not a AppWrapper")
}
return fmt.Sprintf("%s/%s", qj.Namespace, qj.Name), nil
}
// NewJobController create new AppWrapper Controller
func NewJobController(config *rest.Config, serverOption *options.ServerOption) *XController {
cc := &XController{
config: config,
serverOption: serverOption,
clients: kubernetes.NewForConfigOrDie(config),
arbclients: clientset.NewForConfigOrDie(config),
eventQueue: cache.NewFIFO(GetQueueJobKey),
agentEventQueue: cache.NewFIFO(GetQueueJobKey),
initQueue: cache.NewFIFO(GetQueueJobKey),
updateQueue: cache.NewFIFO(GetQueueJobKey),
qjqueue: NewSchedulingQueue(),
cache: clusterstatecache.New(config),
schedulingAW: nil,
}
cc.metricsAdapter = adapter.New(serverOption, config, cc.cache)
cc.genericresources = genericresource.NewAppWrapperGenericResource(config)
cc.qjobResControls = map[arbv1.ResourceType]queuejobresources.Interface{}
RegisterAllQueueJobResourceTypes(&cc.qjobRegisteredResources)
// initialize pod sub-resource control
resControlPod, found, err := cc.qjobRegisteredResources.InitQueueJobResource(arbv1.ResourceTypePod, config)
if err != nil {
klog.Errorf("fail to create queuejob resource control")
return nil
}
if !found {
klog.Errorf("queuejob resource type Pod not found")
return nil
}
cc.qjobResControls[arbv1.ResourceTypePod] = resControlPod
appWrapperClient, err := clientset.NewForConfig(cc.config)
if err != nil {
klog.Fatalf("Could not instantiate k8s client, err=%v", err)
}
cc.appwrapperInformer = informerFactory.NewSharedInformerFactory(appWrapperClient, 0).Mcad().V1beta1().AppWrappers()
cc.appwrapperInformer.Informer().AddEventHandler(
cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
switch t := obj.(type) {
case *arbv1.AppWrapper:
klog.V(10).Infof("[Informer] Filter Name=%s Version=%s Local=%t FilterIgnore=%t Sender=%s &qj=%p qj=%+v", t.Name, t.ResourceVersion, t.Status.Local, t.Status.FilterIgnore, t.Status.Sender, t, t)
// todo: This is a current workaround for duplicate message bug.
// if t.Status.Local == true { // ignore duplicate message from cache
// return false
// }
// t.Status.Local = true // another copy of this will be recognized as duplicate
return true
// return !t.Status.FilterIgnore // ignore update messages
default:
return false
}
},
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: cc.addQueueJob,
UpdateFunc: cc.updateQueueJob,
DeleteFunc: cc.deleteQueueJob,
},
})
cc.appWrapperLister = cc.appwrapperInformer.Lister()
cc.appWrapperSynced = cc.appwrapperInformer.Informer().HasSynced
// Setup Quota
if serverOption.QuotaEnabled {
dispatchedAWDemands, dispatchedAWs := cc.getDispatchedAppWrappers()
cc.quotaManager, err = quotaforestmanager.NewQuotaManager(dispatchedAWDemands, dispatchedAWs, cc.appWrapperLister,
config, serverOption)
if err != nil {
klog.Error("Failed to instantiate quota manager: %#v", err)
return nil
}
} else {
cc.quotaManager = nil
}
// Set dispatcher mode or agent mode
cc.isDispatcher = serverOption.Dispatcher
if cc.isDispatcher {
klog.Infof("[Controller] Dispatcher mode")
} else {
klog.Infof("[Controller] Agent mode")
}
// create agents and agentMap
cc.agentMap = map[string]*queuejobdispatch.JobClusterAgent{}
cc.agentList = []string{}
for _, agentconfig := range strings.Split(serverOption.AgentConfigs, ",") {
agentData := strings.Split(agentconfig, ":")
cc.agentMap["/root/kubernetes/"+agentData[0]] = queuejobdispatch.NewJobClusterAgent(agentconfig, cc.agentEventQueue)
cc.agentList = append(cc.agentList, "/root/kubernetes/"+agentData[0])
}
if cc.isDispatcher && len(cc.agentMap) == 0 {
klog.Errorf("Dispatcher mode: no agent information")
return nil
}
// create (empty) dispatchMap
cc.dispatchMap = map[string]string{}
return cc
}
func (qjm *XController) PreemptQueueJobs() {
ctx := context.Background()
qjobs := qjm.GetQueueJobsEligibleForPreemption()
for _, aw := range qjobs {
if aw.Status.State == arbv1.AppWrapperStateCompleted || aw.Status.State == arbv1.AppWrapperStateDeleted || aw.Status.State == arbv1.AppWrapperStateFailed {
continue
}
var updateNewJob *arbv1.AppWrapper
var message string
newjob, err := qjm.getAppWrapper(aw.Namespace, aw.Name, "[PreemptQueueJobs] get fresh app wrapper")
if err != nil {
klog.Warningf("[PreemptQueueJobs] failed in retrieving a fresh copy of the app wrapper '%s/%s', err=%v. Will try to preempt on the next run.", aw.Namespace, aw.Name, err)
continue
}
newjob.Status.CanRun = false
newjob.Status.FilterIgnore = true // update QueueJobState only
cleanAppWrapper := false
// If dispatch deadline is exceeded no matter what the state of AW, kill the job and set status as Failed.
if (aw.Status.State == arbv1.AppWrapperStateActive) && (aw.Spec.SchedSpec.DispatchDuration.Limit > 0) {
if aw.Spec.SchedSpec.DispatchDuration.Overrun {
index := getIndexOfMatchedCondition(aw, arbv1.AppWrapperCondPreemptCandidate, "DispatchDeadlineExceeded")
if index < 0 {
message = fmt.Sprintf("Dispatch deadline exceeded. allowed to run for %v seconds", aw.Spec.SchedSpec.DispatchDuration.Limit)
cond := GenerateAppWrapperCondition(arbv1.AppWrapperCondPreemptCandidate, v1.ConditionTrue, "DispatchDeadlineExceeded", message)
newjob.Status.Conditions = append(newjob.Status.Conditions, cond)
} else {
cond := GenerateAppWrapperCondition(arbv1.AppWrapperCondPreemptCandidate, v1.ConditionTrue, "DispatchDeadlineExceeded", "")
newjob.Status.Conditions[index] = *cond.DeepCopy()
}
// should the AW state be set in this method??
newjob.Status.State = arbv1.AppWrapperStateFailed
newjob.Status.QueueJobState = arbv1.AppWrapperCondFailed
newjob.Status.Running = 0
updateNewJob = newjob.DeepCopy()
err := qjm.updateStatusInEtcdWithRetry(ctx, updateNewJob, "PreemptQueueJobs - CanRun: false -- DispatchDeadlineExceeded")
if err != nil {
klog.Warningf("[PreemptQueueJobs] status update CanRun: false -- DispatchDeadlineExceeded for '%s/%s' failed", aw.Namespace, aw.Name)
continue
}
// cannot use cleanup AW, since it puts AW back in running state
qjm.qjqueue.AddUnschedulableIfNotPresent(updateNewJob)
// Move to next AW
continue
}
}
if ((aw.Status.Running + aw.Status.Succeeded) < int32(aw.Spec.SchedSpec.MinAvailable)) && aw.Status.State == arbv1.AppWrapperStateActive {
index := getIndexOfMatchedCondition(aw, arbv1.AppWrapperCondPreemptCandidate, "MinPodsNotRunning")
if index < 0 {
message = fmt.Sprintf("Insufficient number of Running and Completed pods, minimum=%d, running=%d, completed=%d.", aw.Spec.SchedSpec.MinAvailable, aw.Status.Running, aw.Status.Succeeded)
cond := GenerateAppWrapperCondition(arbv1.AppWrapperCondPreemptCandidate, v1.ConditionTrue, "MinPodsNotRunning", message)
newjob.Status.Conditions = append(newjob.Status.Conditions, cond)
} else {
cond := GenerateAppWrapperCondition(arbv1.AppWrapperCondPreemptCandidate, v1.ConditionTrue, "MinPodsNotRunning", "")
newjob.Status.Conditions[index] = *cond.DeepCopy()
}
if aw.Spec.SchedSpec.Requeuing.InitialTimeInSeconds == 0 {
aw.Spec.SchedSpec.Requeuing.InitialTimeInSeconds = aw.Spec.SchedSpec.Requeuing.TimeInSeconds
}
if aw.Spec.SchedSpec.Requeuing.GrowthType == "exponential" {
if newjob.Status.RequeueingTimeInSeconds == 0 {
newjob.Status.RequeueingTimeInSeconds += aw.Spec.SchedSpec.Requeuing.TimeInSeconds
} else {
newjob.Status.RequeueingTimeInSeconds += newjob.Status.RequeueingTimeInSeconds
}
} else if aw.Spec.SchedSpec.Requeuing.GrowthType == "linear" {
newjob.Status.RequeueingTimeInSeconds += aw.Spec.SchedSpec.Requeuing.InitialTimeInSeconds
}
if aw.Spec.SchedSpec.Requeuing.MaxTimeInSeconds > 0 {
if aw.Spec.SchedSpec.Requeuing.MaxTimeInSeconds <= newjob.Status.RequeueingTimeInSeconds {
newjob.Status.RequeueingTimeInSeconds = aw.Spec.SchedSpec.Requeuing.MaxTimeInSeconds
}
}
if newjob.Spec.SchedSpec.Requeuing.MaxNumRequeuings > 0 && newjob.Spec.SchedSpec.Requeuing.NumRequeuings == newjob.Spec.SchedSpec.Requeuing.MaxNumRequeuings {
newjob.Status.State = arbv1.AppWrapperStateDeleted
cleanAppWrapper = true
} else {
newjob.Status.NumberOfRequeueings += 1
}
updateNewJob = newjob.DeepCopy()
} else {
// If pods failed scheduling generate new preempt condition
message = fmt.Sprintf("Pods failed scheduling failed=%v, running=%v.", len(aw.Status.PendingPodConditions), aw.Status.Running)
index := getIndexOfMatchedCondition(newjob, arbv1.AppWrapperCondPreemptCandidate, "PodsFailedScheduling")
// ignore co-scheduler failed scheduling events. This is a temp
// work-around until co-scheduler version 0.22.X perf issues are resolved.
if index < 0 {
cond := GenerateAppWrapperCondition(arbv1.AppWrapperCondPreemptCandidate, v1.ConditionTrue, "PodsFailedScheduling", message)
newjob.Status.Conditions = append(newjob.Status.Conditions, cond)
} else {
cond := GenerateAppWrapperCondition(arbv1.AppWrapperCondPreemptCandidate, v1.ConditionTrue, "PodsFailedScheduling", message)
newjob.Status.Conditions[index] = *cond.DeepCopy()
}
updateNewJob = newjob.DeepCopy()
}
err = qjm.updateStatusInEtcdWithRetry(ctx, updateNewJob, "PreemptQueueJobs - CanRun: false -- MinPodsNotRunning")
if err != nil {
klog.Warningf("[PreemptQueueJobs] status update for '%s/%s' failed, skipping app wrapper err =%v", aw.Namespace, aw.Name, err)
continue
}
if cleanAppWrapper {
klog.V(4).Infof("[PreemptQueueJobs] Deleting AppWrapper %s/%s due to maximum number of re-queueing(s) exceeded.", aw.Name, aw.Namespace)
go qjm.Cleanup(ctx, updateNewJob)
} else {
// Only back-off AWs that are in state running and not in state Failed
if updateNewJob.Status.State != arbv1.AppWrapperStateFailed {
klog.Infof("[PreemptQueueJobs] Adding preempted AppWrapper %s/%s to back off queue.", aw.Name, aw.Namespace)
go qjm.backoff(ctx, updateNewJob, "PreemptionTriggered", string(message))
}
}
}
}
func (qjm *XController) preemptAWJobs(ctx context.Context, preemptAWs []*arbv1.AppWrapper) {
if preemptAWs == nil {
return
}
for _, aw := range preemptAWs {
apiCacheAWJob, err := qjm.getAppWrapper(aw.Namespace, aw.Name, "[preemptAWJobs] get fresh app wrapper")
if err != nil {
if apierrors.IsNotFound(err) {
klog.Warningf("[preemptAWJobs] App wrapper '%s/%s' was not found when getting a fresh copy. ", aw.Namespace, aw.Name)
continue
}
klog.Errorf("[preemptAWJobs] Failed to get AppWrapper to from API Cache %s/%s: err = %v",
aw.Namespace, aw.Name, err)
continue
}
apiCacheAWJob.Status.CanRun = false
err = qjm.updateStatusInEtcdWithRetry(ctx, apiCacheAWJob, "preemptAWJobs - CanRun: false")
if err != nil {
if apierrors.IsNotFound(err) {
klog.Warningf("[preemptAWJobs] App wrapper '%s/%s' was not found when updating status. ", aw.Namespace, aw.Name)
continue
}
klog.Warningf("[preemptAWJobs] status update for '%s/%s' failed, err=%v", aw.Namespace, aw.Name, err)
}
}
}
func (qjm *XController) GetQueueJobsEligibleForPreemption() []*arbv1.AppWrapper {
qjobs := make([]*arbv1.AppWrapper, 0)
queueJobs, err := qjm.appWrapperLister.AppWrappers("").List(labels.Everything())
if err != nil {
klog.Errorf("List of queueJobs %+v", qjobs)
return qjobs
}
if !qjm.isDispatcher { // Agent Mode
for _, value := range queueJobs {
// Skip if AW Pending or just entering the system and does not have a state yet.
if (value.Status.State == arbv1.AppWrapperStateEnqueued) || (value.Status.State == "") {
continue
}
if value.Status.State == arbv1.AppWrapperStateActive && value.Spec.SchedSpec.DispatchDuration.Limit > 0 {
awDispatchDurationLimit := value.Spec.SchedSpec.DispatchDuration.Limit
dispatchDuration := value.Status.ControllerFirstDispatchTimestamp.Add(time.Duration(awDispatchDurationLimit) * time.Second)
currentTime := time.Now()
hasDispatchTimeNotExceeded := currentTime.Before(dispatchDuration)
if !hasDispatchTimeNotExceeded {
klog.V(8).Infof("Appwrapper Dispatch limit exceeded, currentTime %v, dispatchTimeInSeconds %v", currentTime, dispatchDuration)
value.Spec.SchedSpec.DispatchDuration.Overrun = true
qjobs = append(qjobs, value)
// Got AW which exceeded dispatch runtime limit, move to next AW
continue
}
}
replicas := value.Spec.SchedSpec.MinAvailable
if (int(value.Status.Running) + int(value.Status.Succeeded)) < replicas {
// Find the dispatched condition if there is any
numConditions := len(value.Status.Conditions)
var dispatchedCondition arbv1.AppWrapperCondition
dispatchedConditionExists := false
for i := numConditions - 1; i > 0; i-- {
dispatchedCondition = value.Status.Conditions[i]
if dispatchedCondition.Type != arbv1.AppWrapperCondDispatched {
continue
}
dispatchedConditionExists = true
break
}
// Check for the minimum age and then skip preempt if current time is not beyond minimum age
// The minimum age is controlled by the requeuing.TimeInSeconds stanza
// For preemption, the time is compared to the last condition or the dispatched condition in the AppWrapper, whichever happened later
lastCondition := value.Status.Conditions[numConditions-1]
var condition arbv1.AppWrapperCondition
if dispatchedConditionExists && dispatchedCondition.LastTransitionMicroTime.After(lastCondition.LastTransitionMicroTime.Time) {
condition = dispatchedCondition
} else {
condition = lastCondition
}
var requeuingTimeInSeconds int
if value.Status.RequeueingTimeInSeconds > 0 {
requeuingTimeInSeconds = value.Status.RequeueingTimeInSeconds
} else if value.Spec.SchedSpec.Requeuing.InitialTimeInSeconds == 0 {
requeuingTimeInSeconds = value.Spec.SchedSpec.Requeuing.TimeInSeconds
} else {
requeuingTimeInSeconds = value.Spec.SchedSpec.Requeuing.InitialTimeInSeconds
}
minAge := condition.LastTransitionMicroTime.Add(time.Duration(requeuingTimeInSeconds) * time.Second)
currentTime := time.Now()
if currentTime.Before(minAge) {
continue
}
if replicas > 0 {
klog.V(3).Infof("AppWrapper '%s/%s' is eligible for preemption Running: %d - minAvailable: %d , Succeeded: %d !!!", value.Namespace, value.Name, value.Status.Running, replicas, value.Status.Succeeded)
qjobs = append(qjobs, value)
}
} else {
// Preempt when schedulingSpec stanza is not set but pods fails scheduling.
// ignore co-scheduler pods
if len(value.Status.PendingPodConditions) > 0 {
klog.V(3).Infof("AppWrapper '%s/%s' is eligible for preemption Running: %d , Succeeded: %d due to failed scheduling !!!", value.Namespace, value.Status.Running, value.Status.Succeeded)
qjobs = append(qjobs, value)
}
}
}
}
return qjobs
}
func (qjm *XController) GetAggregatedResourcesPerGenericItem(cqj *arbv1.AppWrapper) []*clusterstateapi.Resource {
var retVal []*clusterstateapi.Resource
// Get all pods and related resources
for _, genericItem := range cqj.Spec.AggrResources.GenericItems {
itemsList, _ := genericresource.GetListOfPodResourcesFromOneGenericItem(&genericItem)
for i := 0; i < len(itemsList); i++ {
retVal = append(retVal, itemsList[i])
}
}
return retVal
}
// Gets all objects owned by AW from API server, check user supplied status and set whole AW status
func (qjm *XController) getAppWrapperCompletionStatus(caw *arbv1.AppWrapper) arbv1.AppWrapperState {
// Count how many generic items specify a 'completionstatus'. For those that do specify it, check to see if the
// generic item reached any of the condition states provided in the YAML
totalCompletionsRequired := 0
countCompletionRequired := 0
for i, genericItem := range caw.Spec.AggrResources.GenericItems {
if len(genericItem.CompletionStatus) > 0 {
totalCompletionsRequired += 1
objectName := genericItem.GenericTemplate
var unstruct unstructured.Unstructured
unstruct.Object = make(map[string]interface{})
var blob interface{}
if err := jsons.Unmarshal(objectName.Raw, &blob); err != nil {
klog.Errorf("[getAppWrapperCompletionStatus] Error unmarshalling, err=%#v", err)
}
unstruct.Object = blob.(map[string]interface{}) // set object to the content of the blob after Unmarshalling
name := ""
if md, ok := unstruct.Object["metadata"]; ok {
metadata := md.(map[string]interface{})
if objectName, ok := metadata["name"]; ok {
name = objectName.(string)
}
}
if len(name) == 0 {
klog.Warningf("[getAppWrapperCompletionStatus] object name not present for appwrapper: '%s/%s", caw.Namespace, caw.Name)
}
klog.V(4).Infof("[getAppWrapperCompletionStatus] Checking if item %d named %s completed for appwrapper: '%s/%s'...", i+1, name, caw.Namespace, caw.Name)
status := qjm.genericresources.IsItemCompleted(&genericItem, caw.Namespace, caw.Name, name)
if !status {
klog.V(4).Infof("[getAppWrapperCompletionStatus] Item %d named %s not completed for appwrapper: '%s/%s'", i+1, name, caw.Namespace, caw.Name)
// early termination because a required item is not completed
continue
}
// only consider count completion required for valid items
countCompletionRequired = countCompletionRequired + 1
}
}
klog.V(4).Infof("[getAppWrapperCompletionStatus] App wrapper '%s/%s' countCompletionRequired %d, podsRunning %d, podsPending %d", caw.Namespace, caw.Name, countCompletionRequired, caw.Status.Running, caw.Status.Pending)
// Set new status only when completion required flag is present in genericitems array
if countCompletionRequired > 0 {
if caw.Status.Running == 0 && caw.Status.Pending == 0 || countCompletionRequired == totalCompletionsRequired {
return arbv1.AppWrapperStateCompleted
}
if caw.Status.Running > 0 || caw.Status.Pending > 0 {
return arbv1.AppWrapperStateRunningHoldCompletion
}
}
// return previous condition
return caw.Status.State
}
func (qjm *XController) GetAggregatedResources(cqj *arbv1.AppWrapper) *clusterstateapi.Resource {
allocated := clusterstateapi.EmptyResource()
for _, genericItem := range cqj.Spec.AggrResources.GenericItems {
qjv, err := genericresource.GetResources(&genericItem)
if err != nil {
klog.V(8).Infof("[GetAggregatedResources] Failure aggregating resources for %s/%s, err=%#v, genericItem=%#v",
cqj.Namespace, cqj.Name, err, genericItem)
}
allocated = allocated.Add(qjv)
}
return allocated
}
func (qjm *XController) getProposedPreemptions(requestingJob *arbv1.AppWrapper, availableResourcesWithoutPreemption *clusterstateapi.Resource,
preemptableAWs map[float64][]string, preemptableAWsMap map[string]*arbv1.AppWrapper) []*arbv1.AppWrapper {
if requestingJob == nil {
klog.Warning("[getProposedPreemptions] Invalid job to evaluate. Job is set to nil.")
return nil
}
aggJobReq := qjm.GetAggregatedResources(requestingJob)
if aggJobReq.LessEqual(availableResourcesWithoutPreemption) {
klog.V(10).Infof("[getProposedPreemptions] Job fits without preemption.")
return nil
}
if preemptableAWs == nil || len(preemptableAWs) < 1 {
klog.V(10).Infof("[getProposedPreemptions] No preemptable jobs.")
return nil
} else {
klog.V(10).Infof("[getProposedPreemptions] Processing %v candidate jobs for preemption.", len(preemptableAWs))
}
// Sort keys of map
priorityKeyValues := make([]float64, len(preemptableAWs))
i := 0
for key := range preemptableAWs {
priorityKeyValues[i] = key
i++
}
sort.Float64s(priorityKeyValues)
// Get list of proposed preemptions
var proposedPreemptions []*arbv1.AppWrapper
foundEnoughResources := false
preemptable := clusterstateapi.EmptyResource()
for _, priorityKey := range priorityKeyValues {
if foundEnoughResources {
break
}
appWrapperIds := preemptableAWs[priorityKey]
for _, awId := range appWrapperIds {
aggaw := qjm.GetAggregatedResources(preemptableAWsMap[awId])
preemptable.Add(aggaw)
klog.V(4).Infof("[getProposedPreemptions] Adding %s to proposed preemption list on order to dispatch: %s.", awId, requestingJob.Name)
proposedPreemptions = append(proposedPreemptions, preemptableAWsMap[awId])
if aggJobReq.LessEqual(preemptable) {
foundEnoughResources = true
break
}
}
}
if !foundEnoughResources {
klog.V(10).Infof("[getProposedPreemptions] Not enought preemptable jobs to dispatch %s.", requestingJob.Name)
}
return proposedPreemptions
}
func (qjm *XController) getDispatchedAppWrappers() (map[string]*clusterstateapi.Resource, map[string]*arbv1.AppWrapper) {
awrRetVal := make(map[string]*clusterstateapi.Resource)
awsRetVal := make(map[string]*arbv1.AppWrapper)
// Setup and break down an informer to get a list of appwrappers bofore controllerinitialization completes
appWrapperClient, err := clientset.NewForConfig(qjm.config)
if err != nil {
klog.Errorf("[getDispatchedAppWrappers] Failure creating client for initialization informer err=%#v", err)
return awrRetVal, awsRetVal
}
queueJobInformer := informerFactory.NewSharedInformerFactory(appWrapperClient, 0).Mcad().V1beta1().AppWrappers()
queueJobInformer.Informer().AddEventHandler(
cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
switch t := obj.(type) {
case *arbv1.AppWrapper:
klog.V(10).Infof("[getDispatchedAppWrappers] Filtered name=%s/%s",
t.Namespace, t.Name)
return true
default:
return false
}
},
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: qjm.addQueueJob,
UpdateFunc: qjm.updateQueueJob,
DeleteFunc: qjm.deleteQueueJob,
},
})
queueJobLister := queueJobInformer.Lister()
queueJobSynced := queueJobInformer.Informer().HasSynced
stopCh := make(chan struct{})
defer close(stopCh)
go queueJobInformer.Informer().Run(stopCh)
cache.WaitForCacheSync(stopCh, queueJobSynced)
appwrappers, err := queueJobLister.AppWrappers("").List(labels.Everything())
if err != nil {
klog.Errorf("[getDispatchedAppWrappers] List of AppWrappers err=%+v", err)
return awrRetVal, awsRetVal
}
for _, aw := range appwrappers {
// Get dispatched jobs
if aw.Status.CanRun {
id := qmutils.CreateId(aw.Namespace, aw.Name)
awrRetVal[id] = qjm.GetAggregatedResources(aw)
awsRetVal[id] = aw
}
}
klog.V(10).Infof("[getDispatchedAppWrappers] List of runnable AppWrappers dispatched or to be dispatched: %+v",
awrRetVal)
return awrRetVal, awsRetVal
}
func (qjm *XController) addTotalSnapshotResourcesConsumedByAw(totalgpu int32, totalcpu int32, totalmemory int32) *clusterstateapi.Resource {
totalResource := clusterstateapi.EmptyResource()
totalResource.GPU = int64(totalgpu)
totalResource.MilliCPU = float64(totalcpu)
totalResource.Memory = float64(totalmemory)
return totalResource
}
func (qjm *XController) getAggregatedAvailableResourcesPriority(unallocatedClusterResources *clusterstateapi.
Resource, targetpr float64, requestingJob *arbv1.AppWrapper, agentId string) (*clusterstateapi.Resource, []*arbv1.AppWrapper) {
//get available free resources in the cluster.
r := unallocatedClusterResources.Clone()
// Track preemption resources
preemptable := clusterstateapi.EmptyResource()
preemptableAWs := make(map[float64][]string)
preemptableAWsMap := make(map[string]*arbv1.AppWrapper)
// Resources that can fit but have not dispatched.
pending := clusterstateapi.EmptyResource()
klog.V(3).Infof("[getAggAvaiResPri] Idle cluster resources %+v", r)
queueJobs, err := qjm.appWrapperLister.AppWrappers("").List(labels.Everything())
if err != nil {
klog.Errorf("[getAggAvaiResPri] Unable to obtain the list of queueJobs %+v", err)
return r, nil
}
//for all AWs that have canRun status are true
//in non-preemption mode, we reserve resources for AWs
//reserving is done by subtracting total AW resources from pods owned by AW that are running or completed.
// AW can be running but items owned by it can be completed or there might be new set of pods yet to be spawned
for _, value := range queueJobs {
klog.V(10).Infof("[getAggAvaiResPri] %s: Evaluating job: %s to calculate aggregated resources.", time.Now().String(), value.Name)
if value.Name == requestingJob.Name {
klog.V(11).Infof("[getAggAvaiResPri] %s: Skipping adjustments for %s since it is the job being processed.", time.Now().String(), value.Name)
continue
} else if !value.Status.CanRun {
// canRun is false when AW completes or it is preempted
// when preempted AW is cleanedup and resources will be released by preempt thread
// when AW is completed cluster state will reflect available resources
// in both cases we do not account for resources.
klog.V(6).Infof("[getAggAvaiResPri] %s: AW %s cannot run, so not accounting resoources", time.Now().String(), value.Name)
continue
} else if value.Status.SystemPriority < targetpr {
// Dispatcher Mode: Ensure this job is part of the target cluster
if qjm.isDispatcher {
// Get the job key
klog.V(10).Infof("[getAggAvaiResPri] %s: Getting job key for: %s.", time.Now().String(), value.Name)
queueJobKey, _ := GetQueueJobKey(value)
klog.V(10).Infof("[getAggAvaiResPri] %s: Getting dispatchid for: %s.", time.Now().String(), queueJobKey)
dispatchedAgentId := qjm.dispatchMap[queueJobKey]
// If this is not in the same cluster then skip
if strings.Compare(dispatchedAgentId, agentId) != 0 {
klog.V(10).Infof("[getAggAvaiResPri] %s: Skipping adjustments for %s since it is in cluster %s which is not in the same cluster under evaluation: %s.",
time.Now().String(), value.Name, dispatchedAgentId, agentId)
continue
}
}
err := qjm.qjobResControls[arbv1.ResourceTypePod].UpdateQueueJobStatus(value)
if err != nil {
klog.Warningf("[getAggAvaiResPri] Error updating pod status counts for AppWrapper job: %s, err=%+v", value.Name, err)
}
totalResource := qjm.addTotalSnapshotResourcesConsumedByAw(value.Status.TotalGPU, value.Status.TotalCPU, value.Status.TotalMemory)
klog.V(10).Infof("[getAggAvaiResPri] total resources consumed by Appwrapper %v when lower priority compared to target are %v", value.Name, totalResource)
preemptable = preemptable.Add(totalResource)
klog.V(6).Infof("[getAggAvaiResPri] %s proirity %v is lower target priority %v reclaiming total preemptable resources %v", value.Name, value.Status.SystemPriority, targetpr, totalResource)
queueJobKey, _ := GetQueueJobKey(value)
addPreemptableAWs(preemptableAWs, value, queueJobKey, preemptableAWsMap)
continue
} else if qjm.isDispatcher {
// Dispatcher job does not currently track pod states. This is
// a workaround until implementation of pod state is complete.
// Currently calculation for available resources only considers priority.
klog.V(10).Infof("[getAggAvaiResPri] %s: Skipping adjustments for %s since priority %f is >= %f of requesting job: %s.", time.Now().String(),
value.Name, value.Status.SystemPriority, targetpr, requestingJob.Name)
continue
} else if value.Status.CanRun {
qjv := clusterstateapi.EmptyResource()
for _, genericItem := range value.Spec.AggrResources.GenericItems {
res, _ := genericresource.GetResources(&genericItem)
qjv.Add(res)
klog.V(10).Infof("[getAggAvaiResPri] Subtract all resources %+v in genericItem=%T for job %s which can-run is set to: %v but state is still pending.", qjv, genericItem, value.Name, value.Status.CanRun)
}
err := qjm.qjobResControls[arbv1.ResourceTypePod].UpdateQueueJobStatus(value)
if err != nil {
klog.Warningf("[getAggAvaiResPri] Error updating pod status counts for AppWrapper job: %s, err=%+v", value.Name, err)
}
totalResource := qjm.addTotalSnapshotResourcesConsumedByAw(value.Status.TotalGPU, value.Status.TotalCPU, value.Status.TotalMemory)
klog.V(6).Infof("[getAggAvaiResPri] total resources consumed by Appwrapper %v when CanRun are %v", value.Name, totalResource)
delta, err := qjv.NonNegSub(totalResource)
pending = pending.Add(delta)
if err != nil {
klog.Warningf("[getAggAvaiResPri] Subtraction of resources failed, adding entire appwrapper resoources %v, %v", qjv, err)
pending = pending.Add(qjv)
}
klog.V(6).Infof("[getAggAvaiResPri] The value of pending is %v", pending)
continue
}
}
proposedPremptions := qjm.getProposedPreemptions(requestingJob, r, preemptableAWs, preemptableAWsMap)
klog.V(6).Infof("[getAggAvaiResPri] Schedulable idle cluster resources: %+v, subtracting dispatched resources: %+v and adding preemptable cluster resources: %+v", r, pending, preemptable)
r = r.Add(preemptable)
r, _ = r.NonNegSub(pending)
klog.V(3).Infof("[getAggAvaiResPri] %+v available resources to schedule", r)
return r, proposedPremptions
}
func addPreemptableAWs(preemptableAWs map[float64][]string, value *arbv1.AppWrapper, queueJobKey string, preemptableAWsMap map[string]*arbv1.AppWrapper) {
preemptableAWs[value.Status.SystemPriority] = append(preemptableAWs[value.Status.SystemPriority], queueJobKey)
preemptableAWsMap[queueJobKey] = value
klog.V(10).Infof("[getAggAvaiResPri] %s: Added %s to candidate preemptable job with priority %f.", time.Now().String(), value.Name, value.Status.SystemPriority)
}
func (qjm *XController) chooseAgent(ctx context.Context, qj *arbv1.AppWrapper) string {
qjAggrResources := qjm.GetAggregatedResources(qj)
klog.V(2).Infof("[chooseAgent] Aggregated Resources of XQJ %s: %v\n", qj.Name, qjAggrResources)
agentId := qjm.agentList[rand.Int()%len(qjm.agentList)]
klog.V(2).Infof("[chooseAgent] Agent %s is chosen randomly\n", agentId)
unallocatedResources := qjm.agentMap[agentId].AggrResources
priorityindex := qj.Status.SystemPriority
resources, proposedPreemptions := qjm.getAggregatedAvailableResourcesPriority(unallocatedResources, priorityindex, qj, agentId)
klog.V(2).Infof("[chooseAgent] Aggr Resources of Agent %s: %v\n", agentId, resources)
if qjAggrResources.LessEqual(resources) {
klog.V(2).Infof("[chooseAgent] Agent %s has enough resources\n", agentId)
// Now evaluate quota
if qjm.serverOption.QuotaEnabled {
if qjm.quotaManager != nil {
if fits, preemptAWs, _ := qjm.quotaManager.Fits(qj, qjAggrResources, proposedPreemptions); fits {
klog.V(2).Infof("[chooseAgent] AppWrapper %s has enough quota.\n", qj.Name)
qjm.preemptAWJobs(ctx, preemptAWs)
return agentId
} else {
klog.V(2).Infof("[chooseAgent] AppWrapper %s does not have enough quota\n", qj.Name)
}
} else {
klog.Errorf("[chooseAgent] Quota evaluation is enable but not initialize. AppWrapper %s/%s does not have enough quota\n", qj.Name, qj.Namespace)
}
} else {
// Quota is not enabled to return selected agent
return agentId
}
} else {
klog.V(2).Infof("[chooseAgent] Agent %s does not have enough resources\n", agentId)
}
return ""
}
func (qjm *XController) nodeChecks(histograms map[string]*dto.Metric, aw *arbv1.AppWrapper) bool {
ok := true
allPods := qjm.GetAggregatedResourcesPerGenericItem(aw)
// Check only GPUs at this time
var podsToCheck []*clusterstateapi.Resource
for _, pod := range allPods {
if pod.GPU > 0 {
podsToCheck = append(podsToCheck, pod)
}
}
gpuHistogram := histograms["gpu"]
if gpuHistogram != nil {
buckets := gpuHistogram.Histogram.Bucket
// Go through pods needing checking
for _, gpuPod := range podsToCheck {
// Go through each bucket of the histogram to find a valid bucket
bucketFound := false
for _, bucket := range buckets {
ub := bucket.UpperBound
if ub == nil {
klog.Errorf("Unable to get upperbound of histogram bucket.")
continue
}
c := bucket.GetCumulativeCount()
var fGPU float64 = float64(gpuPod.GPU)
if fGPU < *ub && c > 1 {
// Found a valid node
bucketFound = true
break
}
}
if !bucketFound {
ok = false
break
}
}
}
return ok
}
// Thread to find queue-job(QJ) for next schedule
func (qjm *XController) ScheduleNext() {
ctx := context.Background()
// get next QJ from the queue
// check if we have enough compute resources for it
// if we have enough compute resources then we set the AllocatedReplicas to the total
// amount of resources asked by the job
qj, err := qjm.qjqueue.Pop()
if err != nil {
klog.Errorf("[ScheduleNext] Cannot pop QueueJob from qjqueue! err=%#v", err)
return // Try to pop qjqueue again
}
qjm.schedulingMutex.Lock()
qjm.schedulingAW = qj
qjm.schedulingMutex.Unlock()
// ensure that current active appwrapper is reset at the end of this function, to prevent
// the appwrapper from being added in syncjob
defer qjm.schedulingAWAtomicSet(nil)
scheduleNextRetrier := retrier.New(retrier.ExponentialBackoff(1, 100*time.Millisecond), &EtcdErrorClassifier{})
scheduleNextRetrier.SetJitter(0.05)
// Retry the execution
err = scheduleNextRetrier.Run(func() error {
klog.Infof("[ScheduleNext] activeQ.Pop %s *Delay=%.6f seconds RemainingLength=%d &qj=%p Version=%s Status=%+v", qj.Name, time.Now().Sub(qj.Status.ControllerFirstTimestamp.Time).Seconds(), qjm.qjqueue.Length(), qj,
qj.ResourceVersion, qj.Status)
apiCacheAWJob, retryErr := qjm.getAppWrapper(qj.Namespace, qj.Name, "[ScheduleNext] -- get fresh copy after queue pop")
if retryErr != nil {
if apierrors.IsNotFound(retryErr) {
klog.Warningf("[ScheduleNext] app wrapper '%s/%s' not found skiping dispatch", qj.Namespace, qj.Name)
return nil
}
klog.Errorf("[ScheduleNext] Unable to get AW %s from API cache &aw=%p Version=%s Status=%+v err=%#v", qj.Name, qj, qj.ResourceVersion, qj.Status, retryErr)
return retryErr
}
// make sure qj has the latest information
if larger(apiCacheAWJob.ResourceVersion, qj.ResourceVersion) {
klog.V(10).Infof("[ScheduleNext] '%s/%s' found more recent copy from cache &qj=%p qj=%+v", qj.Namespace, qj.Name, qj, qj)
klog.V(10).Infof("[ScheduleNext] '%s/%s' found more recent copy from cache &apiQueueJob=%p apiQueueJob=%+v", apiCacheAWJob.Namespace, apiCacheAWJob.Name, apiCacheAWJob, apiCacheAWJob)
apiCacheAWJob.DeepCopyInto(qj)
}
if qj.Status.CanRun {
klog.V(4).Infof("[ScheduleNext] AppWrapper '%s/%s' from priority queue is already scheduled. Ignoring request: Status=%+v", qj.Namespace, qj.Name, qj.Status)
return nil
}
// Re-compute SystemPriority for DynamicPriority policy
if qjm.serverOption.DynamicPriority {
klog.V(4).Info("[ScheduleNext] dynamic priority enabled")
// Create newHeap to temporarily store qjqueue jobs for updating SystemPriority
tempQ := newHeap(cache.MetaNamespaceKeyFunc, HigherSystemPriorityQJ)
qj.Status.SystemPriority = float64(qj.Spec.Priority) + qj.Spec.PrioritySlope*(time.Now().Sub(qj.Status.ControllerFirstTimestamp.Time)).Seconds()
tempQ.Add(qj)
for qjm.qjqueue.Length() > 0 {
qjtemp, _ := qjm.qjqueue.Pop()
qjtemp.Status.SystemPriority = float64(qjtemp.Spec.Priority) + qjtemp.Spec.PrioritySlope*(time.Now().Sub(qjtemp.Status.ControllerFirstTimestamp.Time)).Seconds()
tempQ.Add(qjtemp)
}
// move AppWrappers back to activeQ and sort based on SystemPriority
for tempQ.data.Len() > 0 {
qjtemp, _ := tempQ.Pop()
qjm.qjqueue.AddIfNotPresent(qjtemp.(*arbv1.AppWrapper))
}
// Print qjqueue.ativeQ for debugging
if klog.V(4).Enabled() {
pq := qjm.qjqueue.(*PriorityQueue)
if qjm.qjqueue.Length() > 0 {
for key, element := range pq.activeQ.data.items {
qjtemp := element.obj
klog.V(4).Infof("[ScheduleNext] AfterCalc: qjqLength=%d Key=%s index=%d Priority=%.1f SystemPriority=%.1f QueueJobState=%s",
qjm.qjqueue.Length(), key, element.index, float64(qjtemp.Spec.Priority), qjtemp.Status.SystemPriority, qjtemp.Status.QueueJobState)
}
}
}
// Retrieve HeadOfLine after priority update
qj, retryErr = qjm.qjqueue.Pop()
if retryErr != nil {
klog.V(3).Infof("[ScheduleNext] Cannot pop QueueJob from qjqueue! err=%#v", retryErr)
return err
}
klog.V(3).Infof("[ScheduleNext] activeQ.Pop_afterPriorityUpdate %s *Delay=%.6f seconds RemainingLength=%d &qj=%p Version=%s Status=%+v", qj.Name, time.Now().Sub(qj.Status.ControllerFirstTimestamp.Time).Seconds(), qjm.qjqueue.Length(), qj, qj.ResourceVersion, qj.Status)