-
Notifications
You must be signed in to change notification settings - Fork 212
/
queue.go
1991 lines (1816 loc) · 68.2 KB
/
queue.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
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 objects
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/looplab/fsm"
"go.uber.org/zap"
"github.com/apache/yunikorn-core/pkg/common"
"github.com/apache/yunikorn-core/pkg/common/configs"
"github.com/apache/yunikorn-core/pkg/common/resources"
"github.com/apache/yunikorn-core/pkg/common/security"
"github.com/apache/yunikorn-core/pkg/events"
"github.com/apache/yunikorn-core/pkg/locking"
"github.com/apache/yunikorn-core/pkg/log"
"github.com/apache/yunikorn-core/pkg/metrics"
"github.com/apache/yunikorn-core/pkg/scheduler/objects/template"
"github.com/apache/yunikorn-core/pkg/scheduler/policies"
"github.com/apache/yunikorn-core/pkg/scheduler/ugm"
"github.com/apache/yunikorn-core/pkg/webservice/dao"
siCommon "github.com/apache/yunikorn-scheduler-interface/lib/go/common"
)
var (
maxPreemptionsPerQueue = 10 // maximum number of asks to attempt to preempt for in a single queue
)
// Queue structure inside Scheduler
type Queue struct {
QueuePath string // Fully qualified path for the queue
Name string // Queue name as in the config etc.
// Private fields need protection
sortType policies.SortPolicy // How applications (leaf) or queues (parents) are sorted
children map[string]*Queue // Only for direct children, parent queue only
childPriorities map[string]int32 // cached priorities for child queues
applications map[string]*Application // only for leaf queue
appPriorities map[string]int32 // cached priorities for application
reservedApps map[string]int // applications reserved within this queue, with reservation count
parent *Queue // link back to the parent in the scheduler
pending *resources.Resource // pending resource for the apps in the queue
allocatedResource *resources.Resource // allocated resource for the apps in the queue
preemptingResource *resources.Resource // preempting resource for the apps in the queue
prioritySortEnabled bool // whether priority is used for request sorting
priorityPolicy policies.PriorityPolicy // priority policy
priorityOffset int32 // priority offset for this queue relative to others
preemptionPolicy policies.PreemptionPolicy // preemption policy
preemptionDelay time.Duration // time before preemption is considered
currentPriority int32 // the current scheduling priority of this queue
// The queue properties should be treated as immutable the value is a merge of the
// parent properties with the config for this queue only manipulated during creation
// of the queue or via a queue configuration update.
properties map[string]string
adminACL security.ACL // admin ACL
submitACL security.ACL // submit ACL
maxResource *resources.Resource // When not set, max = nil
guaranteedResource *resources.Resource // When not set, Guaranteed == 0
isLeaf bool // this is a leaf queue or not (i.e. parent)
isManaged bool // queue is part of the config, not auto created
stateMachine *fsm.FSM // the state of the queue for scheduling
stateTime time.Time // last time the state was updated (needed for cleanup)
maxRunningApps uint64
runningApps uint64
allocatingAcceptedApps map[string]bool
template *template.Template
queueEvents *queueEvents
locking.RWMutex
}
// newBlankQueue creates a new empty queue objects with all values initialised.
func newBlankQueue() *Queue {
return &Queue{
children: make(map[string]*Queue),
childPriorities: make(map[string]int32),
applications: make(map[string]*Application),
appPriorities: make(map[string]int32),
reservedApps: make(map[string]int),
allocatingAcceptedApps: make(map[string]bool),
properties: make(map[string]string),
stateMachine: NewObjectState(),
allocatedResource: resources.NewResource(),
preemptingResource: resources.NewResource(),
pending: resources.NewResource(),
currentPriority: configs.MinPriority,
prioritySortEnabled: true,
preemptionDelay: configs.DefaultPreemptionDelay,
preemptionPolicy: policies.DefaultPreemptionPolicy,
}
}
// NewConfiguredQueue creates a new queue from scratch based on the configuration
// lock free as it cannot be referenced yet
func NewConfiguredQueue(conf configs.QueueConfig, parent *Queue) (*Queue, error) {
sq := newBlankQueue()
sq.Name = strings.ToLower(conf.Name)
sq.QueuePath = strings.ToLower(conf.Name)
sq.parent = parent
sq.isManaged = true
sq.maxRunningApps = conf.MaxApplications
// update the properties
if err := sq.applyConf(conf); err != nil {
return nil, fmt.Errorf("configured queue creation failed: %w", err)
}
// add to the parent, we might have an overall lock already
// still need to make sure we lock the parent so we do not interfere with scheduling
if parent != nil {
// pull the properties from the parent that should be set on the child
sq.mergeProperties(parent.getProperties(), conf.Properties)
sq.UpdateQueueProperties()
sq.QueuePath = parent.QueuePath + configs.DOT + sq.Name
err := parent.addChildQueue(sq)
if err != nil {
return nil, fmt.Errorf("configured queue creation failed: %w", err)
}
} else {
sq.UpdateQueueProperties()
}
sq.queueEvents = newQueueEvents(events.GetEventSystem())
log.Log(log.SchedQueue).Info("configured queue added to scheduler",
zap.String("queueName", sq.QueuePath))
sq.queueEvents.sendNewQueueEvent(sq.QueuePath, sq.isManaged)
return sq, nil
}
// NewRecoveryQueue creates a recovery queue if it does not exist. The recovery queue
// is a dynamic queue, but has an invalid name so that it cannot be directly referenced.
func NewRecoveryQueue(parent *Queue) (*Queue, error) {
if parent == nil {
return nil, errors.New("recovery queue cannot be created with nil parent")
}
if parent.GetQueuePath() != configs.RootQueue {
return nil, fmt.Errorf("recovery queue cannot be created with non-root parent: %s", parent.GetQueuePath())
}
queue, err := newDynamicQueueInternal(common.RecoveryQueue, true, parent)
if err == nil {
queue.Lock()
defer queue.Unlock()
queue.submitACL = security.ACL{}
queue.sortType = policies.FifoSortPolicy
}
return queue, err
}
// NewDynamicQueue creates a new queue to be added to the system based on the placement rules
// A dynamically added queue can never be the root queue so parent must be set
// lock free as it cannot be referenced yet
func NewDynamicQueue(name string, leaf bool, parent *Queue) (*Queue, error) {
// fail without a parent
if parent == nil {
return nil, fmt.Errorf("dynamic queue can not be added without parent: %s", name)
}
// name might not be checked do it here
if !configs.QueueNameRegExp.MatchString(name) {
return nil, fmt.Errorf("invalid queue name '%s', a name must only have alphanumeric characters, - or _, and be no longer than 64 characters", name)
}
return newDynamicQueueInternal(name, leaf, parent)
}
func newDynamicQueueInternal(name string, leaf bool, parent *Queue) (*Queue, error) {
sq := newBlankQueue()
sq.Name = strings.ToLower(name)
sq.QueuePath = parent.QueuePath + configs.DOT + sq.Name
sq.parent = parent
sq.isManaged = false
sq.isLeaf = leaf
// add to the parent, we might have a partition lock already
// still need to make sure we lock the parent so we do not interfere with scheduling
err := parent.addChildQueue(sq)
if err != nil {
return nil, fmt.Errorf("dynamic queue creation failed: %w", err)
}
sq.UpdateQueueProperties()
sq.queueEvents = newQueueEvents(events.GetEventSystem())
log.Log(log.SchedQueue).Info("dynamic queue added to scheduler",
zap.String("queueName", sq.QueuePath))
sq.queueEvents.sendNewQueueEvent(sq.QueuePath, sq.isManaged)
return sq, nil
}
// applyTemplate uses input template to initialize properties, maxResource, and guaranteedResource
func (sq *Queue) applyTemplate(childTemplate *template.Template) {
sq.maxRunningApps = childTemplate.GetMaxApplications()
sq.properties = childTemplate.GetProperties()
// the resources in template are already checked
sq.guaranteedResource = childTemplate.GetGuaranteedResource()
sq.maxResource = childTemplate.GetMaxResource()
// update metrics for guaranteed and max resource
sq.updateGuaranteedResourceMetrics()
sq.updateMaxResourceMetrics()
}
// getProperties returns a copy of the properties for this queue
// Will never return a nil, can return an empty map.
func (sq *Queue) getProperties() map[string]string {
sq.Lock()
defer sq.Unlock()
props := make(map[string]string)
for key, value := range sq.properties {
props[key] = value
}
return props
}
// mergeProperties merges the properties from the parent queue and the config in the set from new queue
// lock free call
func (sq *Queue) mergeProperties(parent, config map[string]string) {
// clean out all existing values (handles update case)
sq.properties = make(map[string]string)
// Set the parent properties
if len(parent) != 0 {
for key, value := range parent {
sq.properties[key] = filterParentProperty(key, value)
}
}
// merge the config properties
if len(config) > 0 {
for key, value := range config {
sq.properties[key] = value
}
}
}
func preemptionDelay(value string) (time.Duration, error) {
result, err := time.ParseDuration(value)
if err != nil {
return configs.DefaultPreemptionDelay, err
}
if int64(result) <= int64(0) {
return configs.DefaultPreemptionDelay, fmt.Errorf("%s must be positive: %s", configs.PreemptionDelay, value)
}
return result, nil
}
func priorityOffset(value string) (int32, error) {
intValue, err := strconv.ParseInt(value, 10, 32)
if err != nil {
return 0, err
}
return int32(intValue), nil
}
func applicationSortPriorityEnabled(value string) (bool, error) {
switch strings.ToLower(value) {
case configs.ApplicationSortPriorityEnabled:
return true, nil
case configs.ApplicationSortPriorityDisabled:
return false, nil
default:
return true, fmt.Errorf("unknown %s value: %s", configs.ApplicationSortPriority, value)
}
}
// filterParentProperty modifies values from parent queues where necessary
func filterParentProperty(key string, value string) string {
switch key {
case configs.PriorityPolicy:
// default is always used unless explicitly specified
return policies.DefaultPriorityPolicy.String()
case configs.PriorityOffset:
// priority offsets are not inherited as they are additive
return "0"
case configs.PreemptionPolicy:
// only 'disabled' should be allowed to propagate
if pol, err := policies.PreemptionPolicyFromString(value); err != nil || pol != policies.DisabledPreemptionPolicy {
return policies.DefaultPreemptionPolicy.String()
}
}
return value
}
// ApplyConf is the locked version of applyConf
func (sq *Queue) ApplyConf(conf configs.QueueConfig) error {
sq.Lock()
defer sq.Unlock()
return sq.applyConf(conf)
}
// applyConf applies all the properties to the queue from the config.
// lock free call, must be called holding the queue lock or during create only
func (sq *Queue) applyConf(conf configs.QueueConfig) error {
// Set the ACLs
var err error
sq.submitACL, err = security.NewACL(conf.SubmitACL)
if err != nil {
log.Log(log.SchedQueue).Error("parsing submit ACL failed this should not happen",
zap.Error(err))
return err
}
sq.adminACL, err = security.NewACL(conf.AdminACL)
if err != nil {
log.Log(log.SchedQueue).Error("parsing admin ACL failed this should not happen",
zap.Error(err))
return err
}
// Change from unmanaged to managed
if !sq.isManaged {
log.Log(log.SchedQueue).Info("changed dynamic queue to managed",
zap.String("queue", sq.QueuePath))
sq.isManaged = true
}
prevLeaf := sq.isLeaf
sq.isLeaf = !conf.Parent
// Make sure the parent flag is set correctly: config might expect auto parent type creation
if len(conf.Queues) > 0 {
sq.isLeaf = false
}
if prevLeaf != sq.isLeaf && sq.queueEvents != nil {
sq.queueEvents.sendTypeChangedEvent(sq.QueuePath, sq.isLeaf)
}
if !sq.isLeaf {
if err = sq.setTemplate(conf.ChildTemplate); err != nil {
return nil
}
}
// Load the max & guaranteed resources for all but the root queue
if sq.Name != configs.RootQueue {
if err = sq.setResources(conf.Resources); err != nil {
return err
}
}
sq.properties = conf.Properties
return nil
}
// setResources sets the maxResource and guaranteedResource of the queue from the config.
func (sq *Queue) setResources(resource configs.Resources) error {
maxResource, err := resources.NewResourceFromConf(resource.Max)
if err != nil {
log.Log(log.SchedQueue).Error("parsing failed on max resources this should not happen",
zap.String("queue", sq.QueuePath),
zap.Error(err))
return err
}
var guaranteedResource *resources.Resource
guaranteedResource, err = resources.NewResourceFromConf(resource.Guaranteed)
if err != nil {
log.Log(log.SchedQueue).Error("parsing failed on guaranteed resources this should not happen",
zap.String("queue", sq.QueuePath),
zap.Error(err))
return err
}
switch {
case resources.StrictlyGreaterThanZero(maxResource):
log.Log(log.SchedQueue).Debug("setting max resources",
zap.String("queue", sq.QueuePath),
zap.Stringer("current", sq.maxResource),
zap.Stringer("new", maxResource))
if !resources.Equals(sq.maxResource, maxResource) && sq.queueEvents != nil {
sq.queueEvents.sendMaxResourceChangedEvent(sq.QueuePath, maxResource)
}
sq.maxResource = maxResource
sq.updateMaxResourceMetrics()
case sq.maxResource != nil:
log.Log(log.SchedQueue).Debug("setting max resources",
zap.String("queue", sq.QueuePath),
zap.Stringer("current", sq.maxResource),
zap.Stringer("new", maxResource))
if sq.queueEvents != nil {
sq.queueEvents.sendMaxResourceChangedEvent(sq.QueuePath, maxResource)
}
sq.maxResource = nil
sq.updateMaxResourceMetrics()
default:
log.Log(log.SchedQueue).Debug("max resources setting ignored: cannot set zero max resources",
zap.String("queue", sq.QueuePath))
}
switch {
case resources.StrictlyGreaterThanZero(guaranteedResource):
log.Log(log.SchedQueue).Debug("setting guaranteed resources",
zap.String("queue", sq.QueuePath),
zap.Stringer("current", sq.guaranteedResource),
zap.Stringer("new", guaranteedResource))
if !resources.Equals(sq.guaranteedResource, guaranteedResource) && sq.queueEvents != nil {
sq.queueEvents.sendGuaranteedResourceChangedEvent(sq.QueuePath, guaranteedResource)
}
sq.guaranteedResource = guaranteedResource
sq.updateGuaranteedResourceMetrics()
case sq.guaranteedResource != nil:
log.Log(log.SchedQueue).Debug("setting guaranteed resources",
zap.String("queue", sq.QueuePath),
zap.Stringer("current", sq.guaranteedResource),
zap.Stringer("new", guaranteedResource))
if sq.queueEvents != nil {
sq.queueEvents.sendGuaranteedResourceChangedEvent(sq.QueuePath, guaranteedResource)
}
sq.guaranteedResource = nil
sq.updateGuaranteedResourceMetrics()
default:
log.Log(log.SchedQueue).Debug("guaranteed resources setting ignored: cannot set zero guaranteed resources",
zap.String("queue", sq.QueuePath))
}
return nil
}
// setTemplate sets the template on the queue based on the config.
// lock free call, must be called holding the queue lock or during create only
func (sq *Queue) setTemplate(conf configs.ChildTemplate) error {
t, err := template.FromConf(&conf)
if err != nil {
return err
}
sq.template = t
return nil
}
// UpdateQueueProperties updates the queue properties defined as text
func (sq *Queue) UpdateQueueProperties() {
sq.Lock()
defer sq.Unlock()
if common.IsRecoveryQueue(sq.QueuePath) {
// recovery queue properties should never be updated
sq.sortType = policies.FifoSortPolicy
return
}
if !sq.isLeaf {
// set the sorting type for parent queues
sq.sortType = policies.FairSortPolicy
}
// walk over all properties and process
var err error
for key, value := range sq.properties {
switch key {
case configs.ApplicationSortPolicy:
if sq.isLeaf {
sq.sortType, err = policies.SortPolicyFromString(value)
if err != nil {
log.Log(log.SchedQueue).Debug("application sort property configuration error",
zap.Error(err))
}
// if it is not defined default to fifo
if sq.sortType == policies.Undefined {
sq.sortType = policies.FifoSortPolicy
}
}
case configs.ApplicationSortPriority:
sq.prioritySortEnabled, err = applicationSortPriorityEnabled(value)
if err != nil {
log.Log(log.SchedQueue).Debug("queue application sort priority configuration error",
zap.Error(err))
}
case configs.PriorityOffset:
sq.priorityOffset, err = priorityOffset(value)
if err != nil {
log.Log(log.SchedQueue).Debug("queue priority offset configuration error",
zap.Error(err))
}
case configs.PriorityPolicy:
sq.priorityPolicy, err = policies.PriorityPolicyFromString(value)
if err != nil {
log.Log(log.SchedQueue).Debug("queue priority policy configuration error",
zap.Error(err))
}
case configs.PreemptionPolicy:
sq.preemptionPolicy, err = policies.PreemptionPolicyFromString(value)
if err != nil {
log.Log(log.SchedQueue).Debug("queue preemption policy configuration error",
zap.Error(err))
}
case configs.PreemptionDelay:
if sq.isLeaf {
sq.preemptionDelay, err = preemptionDelay(value)
if err != nil {
log.Log(log.SchedQueue).Debug("preemption delay property configuration error",
zap.Error(err))
}
}
default:
// skip unknown properties just log them
log.Log(log.SchedQueue).Debug("queue property skipped",
zap.String("key", key),
zap.String("value", value))
}
}
}
// GetQueuePath returns the fully qualified path of this queue.
func (sq *Queue) GetQueuePath() string {
sq.RLock()
defer sq.RUnlock()
return sq.QueuePath
}
// IsDraining returns true if the queue in Draining state.
// Existing applications will still be scheduled
// No new applications will be accepted.
func (sq *Queue) IsDraining() bool {
return sq.stateMachine.Is(Draining.String())
}
// IsRunning returns true if the queue in Active state.
func (sq *Queue) IsRunning() bool {
return sq.stateMachine.Is(Active.String())
}
// IsStopped returns true if the queue in Stopped state.
// The queue is skipped for scheduling in this state.
func (sq *Queue) IsStopped() bool {
return sq.stateMachine.Is(Stopped.String())
}
// CurrentState returns the current state of the queue in string form.
func (sq *Queue) CurrentState() string {
return sq.stateMachine.Current()
}
// handleQueueEvent processes the state event for the queue.
// The state machine handles the locking.
func (sq *Queue) handleQueueEvent(event ObjectEvent) error {
err := sq.stateMachine.Event(context.Background(), event.String(), sq.QueuePath)
// err is nil the state transition was done
if err == nil {
sq.stateTime = time.Now()
return nil
}
// handle the same state transition not nil error (limit of fsm).
if err.Error() == noTransition {
return nil
}
return err
}
// GetAllocatedResource returns a clone of the allocated resources for this queue.
func (sq *Queue) GetAllocatedResource() *resources.Resource {
sq.RLock()
defer sq.RUnlock()
return sq.allocatedResource.Clone()
}
// GetPreemptingResource returns a clone of the preempting resources for this queue.
func (sq *Queue) GetPreemptingResource() *resources.Resource {
sq.RLock()
defer sq.RUnlock()
return sq.preemptingResource.Clone()
}
// GetGuaranteedResource returns a clone of the guaranteed resource for the queue.
func (sq *Queue) GetGuaranteedResource() *resources.Resource {
sq.RLock()
defer sq.RUnlock()
return sq.guaranteedResource
}
// GetActualGuaranteedResources returns the actual (including parent) guaranteed resources for the queue.
func (sq *Queue) GetActualGuaranteedResource() *resources.Resource {
if sq == nil {
return resources.NewResource()
}
parentGuaranteed := sq.parent.GetActualGuaranteedResource()
sq.RLock()
defer sq.RUnlock()
return resources.ComponentWiseMinPermissive(sq.guaranteedResource, parentGuaranteed)
}
func (sq *Queue) GetPreemptionDelay() time.Duration {
sq.RLock()
defer sq.RUnlock()
return sq.preemptionDelay
}
// CheckSubmitAccess checks if the user has access to the queue to submit an application.
// The check is performed recursively: i.e. access to the parent allows access to this queue.
// This will check both submitACL and adminACL.
func (sq *Queue) CheckSubmitAccess(user security.UserGroup) bool {
if common.IsRecoveryQueue(sq.QueuePath) {
// recovery queue can never pass ACL checks
return false
}
sq.RLock()
allow := sq.submitACL.CheckAccess(user) || sq.adminACL.CheckAccess(user)
sq.RUnlock()
if !allow && sq.parent != nil {
allow = sq.parent.CheckSubmitAccess(user)
}
return allow
}
// CheckAdminAccess checks if the user has access to the queue to perform administrative actions.
// The check is performed recursively: i.e. access to the parent allows access to this queue.
func (sq *Queue) CheckAdminAccess(user security.UserGroup) bool {
sq.RLock()
allow := sq.adminACL.CheckAccess(user)
sq.RUnlock()
if !allow && sq.parent != nil {
allow = sq.parent.CheckAdminAccess(user)
}
return allow
}
// GetPartitionQueueDAOInfo returns the queue hierarchy as an object for a REST call.
// Exclude is true, which means that returns the specified queue object, but does not return the children of the specified queue.
func (sq *Queue) GetPartitionQueueDAOInfo(exclude bool) dao.PartitionQueueDAOInfo {
queueInfo := dao.PartitionQueueDAOInfo{}
children := sq.GetCopyOfChildren()
if !exclude {
queueInfo.Children = make([]dao.PartitionQueueDAOInfo, 0, len(children))
for _, child := range children {
queueInfo.Children = append(queueInfo.Children, child.GetPartitionQueueDAOInfo(false))
}
}
// we have held the read lock so following method should not take lock again.
queueInfo.HeadRoom = sq.getHeadRoom().DAOMap()
sq.RLock()
defer sq.RUnlock()
for _, child := range children {
queueInfo.ChildrenNames = append(queueInfo.ChildrenNames, child.QueuePath)
}
queueInfo.QueueName = sq.QueuePath
queueInfo.Status = sq.stateMachine.Current()
queueInfo.PendingResource = sq.pending.DAOMap()
queueInfo.MaxResource = sq.maxResource.DAOMap()
queueInfo.GuaranteedResource = sq.guaranteedResource.DAOMap()
queueInfo.AllocatedResource = sq.allocatedResource.DAOMap()
queueInfo.PreemptingResource = sq.preemptingResource.DAOMap()
queueInfo.IsLeaf = sq.isLeaf
queueInfo.IsManaged = sq.isManaged
queueInfo.CurrentPriority = sq.getCurrentPriority()
queueInfo.TemplateInfo = sq.template.GetTemplateInfo()
queueInfo.AbsUsedCapacity = resources.CalculateAbsUsedCapacity(
sq.maxResource, sq.allocatedResource).DAOMap()
queueInfo.Properties = make(map[string]string)
for k, v := range sq.properties {
queueInfo.Properties[k] = v
}
if sq.parent == nil {
queueInfo.Parent = ""
} else {
queueInfo.Parent = sq.QueuePath[:strings.LastIndex(sq.QueuePath, configs.DOT)]
}
queueInfo.MaxRunningApps = sq.maxRunningApps
queueInfo.RunningApps = sq.runningApps
queueInfo.AllocatingAcceptedApps = make([]string, 0)
for appID, result := range sq.allocatingAcceptedApps {
if result {
queueInfo.AllocatingAcceptedApps = append(queueInfo.AllocatingAcceptedApps, appID)
}
}
return queueInfo
}
// GetPendingResource returns the pending resources for this queue.
func (sq *Queue) GetPendingResource() *resources.Resource {
sq.RLock()
defer sq.RUnlock()
return sq.pending
}
// incPendingResource increments pending resource of this queue and its parents.
func (sq *Queue) incPendingResource(delta *resources.Resource) {
// update the parent
if sq.parent != nil {
sq.parent.incPendingResource(delta)
}
// update this queue
sq.Lock()
defer sq.Unlock()
sq.pending = resources.Add(sq.pending, delta)
sq.updatePendingResourceMetrics()
}
// decPendingResource decrements pending resource of this queue and its parents.
func (sq *Queue) decPendingResource(delta *resources.Resource) {
if sq == nil {
return
}
// update the parent
if sq.parent != nil {
sq.parent.decPendingResource(delta)
}
// update this queue
sq.Lock()
defer sq.Unlock()
var err error
sq.pending, err = resources.SubErrorNegative(sq.pending, delta)
if err != nil {
log.Log(log.SchedQueue).Warn("Pending resources went negative",
zap.String("queueName", sq.QueuePath),
zap.Error(err))
} else {
sq.updatePendingResourceMetrics()
}
}
// AddApplication adds the application to the queue. All checks are assumed to have passed before we get here.
// No update of pending resource is needed as it should not have any requests yet.
// Replaces the existing application without further checks.
func (sq *Queue) AddApplication(app *Application) {
sq.Lock()
defer sq.Unlock()
appID := app.ApplicationID
sq.applications[appID] = app
sq.queueEvents.sendNewApplicationEvent(sq.QueuePath, appID)
// YUNIKORN-199: update the quota from the namespace
// get the tag with the quota
quota := app.GetTag(siCommon.AppTagNamespaceResourceQuota)
// get the tag with the guaranteed resource
guaranteed := app.GetTag(siCommon.AppTagNamespaceResourceGuaranteed)
if quota == "" && guaranteed == "" {
return
}
var quotaRes, guaranteedRes *resources.Resource
var quotaErr, guaranteedErr error
// need to set a quota: convert json string to resource
if quota != "" {
quotaRes, quotaErr = resources.NewResourceFromString(quota)
if quotaErr != nil {
log.Log(log.SchedQueue).Warn("application resource quota conversion failure",
zap.String("json quota string", quota),
zap.Error(quotaErr))
} else if !resources.StrictlyGreaterThanZero(quotaRes) {
log.Log(log.SchedQueue).Warn("Max resource quantities should be greater than zero: cannot set queue max resource",
zap.Stringer("maxResource", quotaRes))
quotaRes = nil // Skip setting quota if it has a value <= 0
}
}
// need to set guaranteed resource: convert json string to resource
if guaranteed != "" {
guaranteedRes, guaranteedErr = resources.NewResourceFromString(guaranteed)
if guaranteedErr != nil {
log.Log(log.SchedQueue).Warn("application guaranteed resource conversion failure",
zap.String("json guaranteed string", guaranteed),
zap.Error(guaranteedErr))
if quotaErr != nil {
return
}
} else if !resources.StrictlyGreaterThanZero(guaranteedRes) {
log.Log(log.SchedQueue).Warn("Guaranteed resource quantities should be greater than zero: cannot set queue guaranteed resource",
zap.Stringer("guaranteedResource", guaranteedRes))
guaranteedRes = nil // Skip setting guaranteed resource if it has a value <= 0
}
}
// set the quota
if sq.isManaged {
log.Log(log.SchedQueue).Warn("Trying to set max resources on a queue that is not an unmanaged leaf",
zap.String("queueName", sq.QueuePath))
return
}
if quotaRes != nil {
sq.maxResource = quotaRes
}
if guaranteedRes != nil {
sq.guaranteedResource = guaranteedRes
}
}
// RemoveApplication removes the app from the list of tracked applications. Make sure that the app
// is assigned to this queue and not removed yet.
// If not found this call is a noop
func (sq *Queue) RemoveApplication(app *Application) {
// clean up any outstanding pending resources
appID := app.ApplicationID
if !sq.appExists(appID) {
log.Log(log.SchedQueue).Debug("Application not found while removing from queue",
zap.String("queueName", sq.QueuePath),
zap.String("applicationID", appID))
return
}
sq.queueEvents.sendRemoveApplicationEvent(sq.QueuePath, appID)
if appPending := app.GetPendingResource(); !resources.IsZero(appPending) {
sq.decPendingResource(appPending)
}
// clean up the allocated resource
if appAllocated := app.GetAllocatedResource(); !resources.IsZero(appAllocated) {
if err := sq.DecAllocatedResource(appAllocated); err != nil {
log.Log(log.SchedQueue).Warn("failed to release allocated resources from queue",
zap.String("appID", appID),
zap.Error(err))
}
}
// clean up the allocated placeholder resource
if phAllocated := app.GetPlaceholderResource(); !resources.IsZero(phAllocated) {
if err := sq.DecAllocatedResource(phAllocated); err != nil {
log.Log(log.SchedQueue).Warn("failed to release placeholder resources from queue",
zap.String("appID", appID),
zap.Error(err))
}
}
// clean up preempting resources
preempting := resources.NewResource()
for _, alloc := range app.GetAllAllocations() {
if alloc.IsPreempted() {
preempting.AddTo(alloc.GetAllocatedResource())
}
}
if !resources.IsZero(preempting) {
sq.DecPreemptingResource(preempting)
}
sq.Lock()
delete(sq.applications, appID)
delete(sq.appPriorities, appID)
delete(sq.allocatingAcceptedApps, appID)
priority := sq.recalculatePriority()
sq.Unlock()
app.appEvents.sendRemoveApplicationEvent()
sq.parent.UpdateQueuePriority(sq.Name, priority)
log.Log(log.SchedQueue).Info("Application completed and removed from queue",
zap.String("queueName", sq.QueuePath),
zap.String("applicationID", appID))
}
func (sq *Queue) appExists(appID string) bool {
sq.RLock()
defer sq.RUnlock()
_, ok := sq.applications[appID]
return ok
}
// GetCopyOfApps gets a shallow copy of all non-completed apps holding the lock
func (sq *Queue) GetCopyOfApps() map[string]*Application {
sq.RLock()
defer sq.RUnlock()
appsCopy := make(map[string]*Application, len(sq.applications))
for appID, app := range sq.applications {
appsCopy[appID] = app
}
return appsCopy
}
// GetCopyOfChildren return a shallow copy of the child queue map.
// This is used by the partition manager to find all queues to clean however we can not
// guarantee that there is no new child added while we clean up since there is no overall
// lock on the scheduler. We'll need to test just before to make sure the parent is empty
func (sq *Queue) GetCopyOfChildren() map[string]*Queue {
sq.RLock()
defer sq.RUnlock()
childCopy := make(map[string]*Queue)
for k, v := range sq.children {
childCopy[k] = v
}
return childCopy
}
// IsEmpty returns true if a queue is empty based on the following definition:
// A parent queue is empty when it has no children left
// A leaf queue is empty when there are no applications left
func (sq *Queue) IsEmpty() bool {
sq.RLock()
defer sq.RUnlock()
if sq.isLeaf {
return len(sq.applications) == 0
}
return len(sq.children) == 0
}
// removeChildQueue removes a child queue from this queue.
// No checks are performed: if the child has been removed already it is a noop.
// This may only be called by the queue removal itself on the registered parent.
// Queue removal is always a bottom up action: leaves first then the parent.
func (sq *Queue) removeChildQueue(name string) {
sq.Lock()
delete(sq.children, name)
delete(sq.childPriorities, name)
priority := sq.recalculatePriority()
sq.Unlock()
sq.parent.UpdateQueuePriority(sq.Name, priority)
}
// addChildQueue add a child queue to this queue.
// note: both child.isLeaf and child.isManaged must be already configured
func (sq *Queue) addChildQueue(child *Queue) error {
sq.Lock()
defer sq.Unlock()
if sq.isLeaf {
return fmt.Errorf("cannot add a child queue to a leaf queue: %s", sq.QueuePath)
}
if sq.IsDraining() {
return fmt.Errorf("cannot add a child queue when queue is marked for deletion: %s", sq.QueuePath)
}
// no need to lock child as it is a new queue which cannot be accessed yet
sq.children[child.Name] = child
sq.childPriorities[child.Name] = child.getCurrentPriority()
if child.isLeaf {
// managed (configured) leaf queue can't use template
if child.isManaged {
return nil
}
// try to use template if it is not nil
if sq.template != nil {
log.Log(log.SchedQueue).Debug("applying child template to new leaf queue",
zap.String("child queue", child.QueuePath),
zap.String("parent queue", sq.QueuePath),
zap.Any("template", sq.template))
child.applyTemplate(sq.template)
}
return nil
}
// don't override the template of non-leaf queue
if child.template == nil {
child.template = sq.template
log.Log(log.SchedQueue).Debug("new parent queue inheriting template from parent queue",
zap.String("child queue", child.QueuePath),
zap.String("parent queue", sq.QueuePath))
}
return nil
}
// MarkQueueForRemoval marks the managed queue for removal from the system.
// This can be executed multiple times and is only effective the first time.
// This is a noop on an unmanaged queue.
func (sq *Queue) MarkQueueForRemoval() {
if !sq.IsManaged() {
return
}
children := sq.GetCopyOfChildren()
// Mark the managed queue for deletion: it is removed from the config let it drain.
// Also mark all the managed children for deletion.
log.Log(log.SchedQueue).Info("marking managed queue for deletion",
zap.String("queue", sq.QueuePath))
sq.doRemoveQueue()
if len(sq.children) > 0 {
for _, child := range children {
child.MarkQueueForRemoval()
}
}
}
func (sq *Queue) doRemoveQueue() {
sq.Lock()
defer sq.Unlock()
if err := sq.handleQueueEvent(Remove); err != nil {
log.Log(log.SchedQueue).Warn("failed to mark managed queue for deletion",
zap.String("queue", sq.QueuePath),
zap.Error(err))
}
}
// GetChildQueue returns a queue if the name exists in the child map as a key.
func (sq *Queue) GetChildQueue(name string) *Queue {
sq.RLock()
defer sq.RUnlock()
return sq.children[name]
}
// RemoveQueue remove the queue from the structure.
// Since nothing is allocated there shouldn't be anything referencing this queue anymore.
// The real removal is the removal of the queue from the parent's child list.
// Use a read lock on this queue to prevent other changes but allow status checks etc.
func (sq *Queue) RemoveQueue() bool {
sq.RLock()
defer sq.RUnlock()
// cannot remove a managed queue that is running
if sq.isManaged && sq.IsRunning() {
return false
}
// cannot remove a queue that has children or applications assigned
if len(sq.children) > 0 || len(sq.applications) > 0 {
return false