forked from intel/cri-resource-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resources.go
1530 lines (1336 loc) · 45.8 KB
/
resources.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 Intel Corporation. All Rights Reserved.
//
// 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 topologyaware
import (
"fmt"
"strconv"
"time"
v1 "k8s.io/api/core/v1"
"k8s.io/kubernetes/pkg/kubelet/cm/cpuset"
"github.com/intel/cri-resource-manager/pkg/cpuallocator"
"github.com/intel/cri-resource-manager/pkg/cri/resource-manager/cache"
"github.com/intel/cri-resource-manager/pkg/cri/resource-manager/kubernetes"
idset "github.com/intel/goresctrl/pkg/utils"
)
// Supply represents avaialbe CPU and memory capacity of a node.
type Supply interface {
// GetNode returns the node supplying this capacity.
GetNode() Node
// Clone creates a copy of this supply.
Clone() Supply
// IsolatedCPUs returns the isolated cpuset in this supply.
IsolatedCPUs() cpuset.CPUSet
// ReservedCPUs returns the reserved cpuset in this supply.
ReservedCPUs() cpuset.CPUSet
// SharableCPUs returns the sharable cpuset in this supply.
SharableCPUs() cpuset.CPUSet
// GrantedReserved returns the locally granted reserved CPU capacity in this supply.
GrantedReserved() int
// GrantedShared returns the locally granted shared CPU capacity in this supply.
GrantedShared() int
// GrantedMemory returns the locally granted memory capacity in this supply.
GrantedMemory(memoryType) uint64
// Cumulate cumulates the given supply into this one.
Cumulate(Supply)
// AssignMemory adds extra memory to this supply (for extra NUMA nodes assigned to a pool).
AssignMemory(mem memoryMap)
// AccountAllocateCPU accounts for (removes) allocated exclusive capacity from the supply.
AccountAllocateCPU(Grant)
// AccountReleaseCPU accounts for (reinserts) released exclusive capacity into the supply.
AccountReleaseCPU(Grant)
// GetScore calculates how well this supply fits/fulfills the given request.
GetScore(Request) Score
// AllocatableSharedCPU calculates the allocatable amount of shared CPU of this supply.
AllocatableSharedCPU(...bool) int
// Allocate allocates CPU capacity from this supply and returns it as a grant.
Allocate(Request) (Grant, error)
// ReleaseCPU releases a previously allocated CPU grant from this supply.
ReleaseCPU(Grant)
// ReleaseMemory releases a previously allocated memory grant from this supply.
ReleaseMemory(Grant)
// ReallocateMemory updates the Grant to allocate memory from this supply.
ReallocateMemory(Grant) error
// ExtraMemoryReservation returns the memory reservation.
ExtraMemoryReservation(memoryType) uint64
// SetExtraMemroyReservation sets the extra memory reservation based on the granted memory.
SetExtraMemoryReservation(Grant)
// ReleaseExtraMemoryReservation removes the extra memory reservations based on the granted memory.
ReleaseExtraMemoryReservation(Grant)
// MemoryLimit returns the amount of various memory types belonging to this grant.
MemoryLimit() memoryMap
// Reserve accounts for CPU grants after reloading cached allocations.
Reserve(Grant) error
// ReserveMemory accounts for memory grants after reloading cached allocations.
ReserveMemory(Grant) error
// DumpCapacity returns a printable representation of the supply's resource capacity.
DumpCapacity() string
// DumpAllocatable returns a printable representation of the supply's alloctable resources.
DumpAllocatable() string
// DumpMemoryState dumps the state of the available and allocated memory.
DumpMemoryState(string)
}
// Request represents CPU and memory resources requested by a container.
type Request interface {
// GetContainer returns the container requesting CPU capacity.
GetContainer() cache.Container
// String returns a printable representation of this request.
String() string
// CPUType returns the type of requested CPU.
CPUType() cpuClass
// SetCPUType sets the type of requested CPU.
SetCPUType(cpuType cpuClass)
// FullCPUs return the number of full CPUs requested.
FullCPUs() int
// CPUFraction returns the amount of fractional milli-CPU requested.
CPUFraction() int
// Isolate returns whether isolated CPUs are preferred for this request.
Isolate() bool
// MemoryType returns the type(s) of requested memory.
MemoryType() memoryType
// MemAmountToAllocate retuns how much memory we need to reserve for a request.
MemAmountToAllocate() uint64
// ColdStart returns the cold start timeout.
ColdStart() time.Duration
}
// Grant represents CPU and memory capacity allocated to a container from a node.
type Grant interface {
// SetCPUPortion sets the fraction CPU portion for the grant.
SetCPUPortion(fraction int)
// SetMemoryAllocation sets the memory allocation for the grant.
SetMemoryAllocation(memoryType, memoryMap, time.Duration)
// Clone creates a copy of this grant.
Clone() Grant
// RefetchNodes updates the stored cpu and memory nodes of this grant by name.
RefetchNodes() error
// GetContainer returns the container CPU capacity is granted to.
GetContainer() cache.Container
// GetCPUNode returns the node that granted CPU capacity to the container.
GetCPUNode() Node
// GetMemoryNode returns the node which granted memory capacity to
// the container.
GetMemoryNode() Node
// CPUType returns the type of granted CPUs
CPUType() cpuClass
// CPUPortion returns granted milli-CPUs of non-full CPUs of CPUType().
// CPUPortion() == ReservedPortion() + SharedPortion().
CPUPortion() int
// ExclusiveCPUs returns the exclusively granted non-isolated cpuset.
ExclusiveCPUs() cpuset.CPUSet
// ReservedCPUs returns the reserved granted cpuset.
ReservedCPUs() cpuset.CPUSet
// ReservedPortion() returns the amount of CPUs in milli-CPU granted.
ReservedPortion() int
// SharedCPUs returns the shared granted cpuset.
SharedCPUs() cpuset.CPUSet
// SharedPortion returns the amount of CPUs in milli-CPU granted.
SharedPortion() int
// IsolatedCpus returns the exclusively granted isolated cpuset.
IsolatedCPUs() cpuset.CPUSet
// MemoryType returns the type(s) of granted memory.
MemoryType() memoryType
// SetMemoryNode updates the grant memory controllers.
SetMemoryNode(Node)
// Memset returns the granted memory controllers as a string.
Memset() idset.IDSet
// ExpandMemset() makes the memory controller set larger as the grant
// is moved up in the node hierarchy.
ExpandMemset() (bool, error)
// MemLimit returns the amount of memory that the container is
// allowed to use.
MemLimit() memoryMap
// String returns a printable representation of this grant.
String() string
// Release releases the grant from all the Supplys it uses.
Release()
// AccountAllocateCPU accounts for (removes) allocated exclusive capacity for this grant.
AccountAllocateCPU()
// AccountReleaseCPU accounts for (reinserts) released exclusive capacity for this grant.
AccountReleaseCPU()
// UpdateExtraMemoryReservation() updates the reservations in the subtree
// of nodes under the node from which the memory was granted.
UpdateExtraMemoryReservation()
// RestoreMemset restores the granted memory set to node maximum
// and reapplies the grant.
RestoreMemset()
// ColdStart returns the cold start timeout.
ColdStart() time.Duration
// AddTimer adds a cold start timer.
AddTimer(*time.Timer)
// StopTimer stops a cold start timer.
StopTimer()
// ClearTimer clears the cold start timer pointer.
ClearTimer()
}
// Score represents how well a supply can satisfy a request.
type Score interface {
// Calculate the actual score from the collected parameters.
Eval() float64
// Supply returns the supply associated with this score.
Supply() Supply
// Request returns the request associated with this score.
Request() Request
IsolatedCapacity() int
ReservedCapacity() int
SharedCapacity() int
Colocated() int
HintScores() map[string]float64
String() string
}
type memoryMap map[memoryType]uint64
// supply implements our Supply interface.
type supply struct {
node Node // node supplying CPUs and memory
isolated cpuset.CPUSet // isolated CPUs at this node
reserved cpuset.CPUSet // reserved CPUs at this node
sharable cpuset.CPUSet // sharable CPUs at this node
grantedReserved int // amount of reserved CPUs allocated
grantedShared int // amount of shareable CPUs allocated
mem memoryMap // available memory for this node
grantedMem memoryMap // total memory granted
extraMemReservations map[Grant]memoryMap // how much memory each workload above has requested
}
var _ Supply = &supply{}
// request implements our Request interface.
type request struct {
container cache.Container // container for this request
full int // number of full CPUs requested
fraction int // amount of fractional CPU requested
isolate bool // prefer isolated exclusive CPUs
cpuType cpuClass // preferred CPU type (normal, reserved)
memReq uint64 // memory request
memLim uint64 // memory limit
memType memoryType // requested types of memory
// coldStart tells the timeout (in milliseconds) how long to wait until
// a DRAM memory controller should be added to a container asking for a
// mixed DRAM/PMEM memory allocation. This allows for a "cold start" where
// initial memory requests are made to the PMEM memory. A value of 0
// indicates that cold start is not explicitly requested.
coldStart time.Duration
}
var _ Request = &request{}
// grant implements our Grant interface.
type grant struct {
container cache.Container // container CPU is granted to
node Node // node CPU is supplied from
memoryNode Node // node memory is supplied from
exclusive cpuset.CPUSet // exclusive CPUs
cpuType cpuClass // type of CPUs (normal, reserved, ...)
cpuPortion int // milliCPUs granted from CPUs of cpuType
memType memoryType // requested types of memory
memset idset.IDSet // assigned memory nodes
allocatedMem memoryMap // memory limit
coldStart time.Duration // how long until cold start is done
coldStartTimer *time.Timer // timer to trigger cold start timeout
}
var _ Grant = &grant{}
// score implements our Score interface.
type score struct {
supply Supply // CPU supply (node)
req Request // CPU request (container)
isolated int // remaining isolated CPUs
reserved int // remaining reserved CPUs
shared int // remaining shared capacity
colocated int // number of colocated containers
hints map[string]float64 // hint scores
}
var _ Score = &score{}
// newSupply creates CPU supply for the given node, cpusets and existing grant.
func newSupply(n Node, isolated, reserved, sharable cpuset.CPUSet, grantedReserved int, grantedShared int, mem, grantedMem memoryMap) Supply {
if mem == nil {
mem = createMemoryMap(0, 0, 0)
}
if grantedMem == nil {
grantedMem = createMemoryMap(0, 0, 0)
}
return &supply{
node: n,
isolated: isolated.Clone(),
reserved: reserved.Clone(),
sharable: sharable.Clone(),
grantedReserved: grantedReserved,
grantedShared: grantedShared,
mem: mem,
grantedMem: grantedMem,
extraMemReservations: make(map[Grant]memoryMap),
}
}
func createMemoryMap(dram, pmem, hbm uint64) memoryMap {
return memoryMap{
memoryDRAM: dram,
memoryPMEM: pmem,
memoryHBM: hbm,
memoryAll: dram + pmem + hbm,
memoryUnspec: 0,
}
}
func (m memoryMap) Add(dram, pmem, hbm uint64) {
m[memoryDRAM] += dram
m[memoryPMEM] += pmem
m[memoryPMEM] += hbm
m[memoryAll] += dram + pmem + hbm
}
func (m memoryMap) AddDRAM(dram uint64) {
m[memoryDRAM] += dram
m[memoryAll] += dram
}
func (m memoryMap) AddPMEM(pmem uint64) {
m[memoryPMEM] += pmem
m[memoryAll] += pmem
}
func (m memoryMap) AddHBM(hbm uint64) {
m[memoryHBM] += hbm
m[memoryAll] += hbm
}
func (m memoryMap) String() string {
mem, sep := "", ""
dram, pmem, hbm, types := m[memoryDRAM], m[memoryPMEM], m[memoryHBM], 0
if dram > 0 || pmem > 0 || hbm > 0 {
if dram > 0 {
mem += "DRAM " + prettyMem(dram)
sep = ", "
types++
}
if pmem > 0 {
mem += sep + "PMEM " + prettyMem(pmem)
sep = ", "
types++
}
if hbm > 0 {
mem += sep + "HBM " + prettyMem(hbm)
types++
}
if types > 1 {
mem += sep + "total " + prettyMem(pmem+dram+hbm)
}
}
return mem
}
// GetNode returns the node supplying CPU and memory.
func (cs *supply) GetNode() Node {
return cs.node
}
// Clone clones the given CPU supply.
func (cs *supply) Clone() Supply {
// Copy the maps.
mem := make(memoryMap)
for key, value := range cs.mem {
mem[key] = value
}
grantedMem := make(memoryMap)
for key, value := range cs.grantedMem {
grantedMem[key] = value
}
return newSupply(cs.node, cs.isolated, cs.reserved, cs.sharable, cs.grantedReserved, cs.grantedShared, mem, grantedMem)
}
// IsolatedCpus returns the isolated CPUSet of this supply.
func (cs *supply) IsolatedCPUs() cpuset.CPUSet {
return cs.isolated.Clone()
}
// ReservedCpus returns the reserved CPUSet of this supply.
func (cs *supply) ReservedCPUs() cpuset.CPUSet {
return cs.reserved.Clone()
}
// SharableCpus returns the sharable CPUSet of this supply.
func (cs *supply) SharableCPUs() cpuset.CPUSet {
return cs.sharable.Clone()
}
// GrantedReserved returns the locally granted reserved CPU capacity.
func (cs *supply) GrantedReserved() int {
return cs.grantedReserved
}
// GrantedShared returns the locally granted sharable CPU capacity.
func (cs *supply) GrantedShared() int {
return cs.grantedShared
}
func (cs *supply) GrantedMemory(memType memoryType) uint64 {
// Return only granted memory of correct type
return cs.grantedMem[memType]
}
func (cs *supply) MemoryLimit() memoryMap {
return cs.mem
}
// Cumulate more CPU to supply.
func (cs *supply) Cumulate(more Supply) {
mcs := more.(*supply)
cs.isolated = cs.isolated.Union(mcs.isolated)
cs.reserved = cs.reserved.Union(mcs.reserved)
cs.sharable = cs.sharable.Union(mcs.sharable)
cs.grantedReserved += mcs.grantedReserved
cs.grantedShared += mcs.grantedShared
for key, value := range mcs.mem {
cs.mem[key] += value
}
for key, value := range mcs.grantedMem {
cs.grantedMem[key] += value
}
}
// AssignMemory adds memory (for extra NUMA nodes assigned to a pool node).
func (cs *supply) AssignMemory(mem memoryMap) {
for key, value := range mem {
cs.mem[key] += value
}
}
// AccountAllocateCPU accounts for (removes) allocated exclusive capacity from the supply.
func (cs *supply) AccountAllocateCPU(g Grant) {
if cs.node.IsSameNode(g.GetCPUNode()) {
return
}
exclusive := g.ExclusiveCPUs()
cs.isolated = cs.isolated.Difference(exclusive)
cs.sharable = cs.sharable.Difference(exclusive)
}
// AccountReleaseCPU accounts for (reinserts) released exclusive capacity into the supply.
func (cs *supply) AccountReleaseCPU(g Grant) {
if cs.node.IsSameNode(g.GetCPUNode()) {
return
}
ncs := cs.node.GetSupply()
nodecpus := ncs.IsolatedCPUs().Union(ncs.SharableCPUs())
grantcpus := g.ExclusiveCPUs().Intersection(nodecpus)
isolated := grantcpus.Intersection(ncs.IsolatedCPUs())
sharable := grantcpus.Intersection(ncs.SharableCPUs())
cs.isolated = cs.isolated.Union(isolated)
cs.sharable = cs.sharable.Union(sharable)
}
// allocateMemory tries to fulfill the memory allocation part of a request.
func (cs *supply) allocateMemory(r Request) (memoryMap, error) {
reqType := r.MemoryType()
if reqType == memoryUnspec {
reqType = memoryAll
}
allocated := createMemoryMap(0, 0, 0)
requested := r.MemAmountToAllocate()
remaining := requested
//
// Notes:
// We try to allocate PMEM, then DRAM, and finally HBM, honoring
// the types allowed by the request. We don't need to care about
// extra memory reservations for this node as all the nodes with
// insufficient memory have been filtered out before allocation.
//
// However, for cold started containers we do check if there is
// enough PMEM free to accomodate the full request and bail out
// if that check fails.
//
for _, memType := range []memoryType{memoryPMEM, memoryDRAM, memoryHBM} {
if remaining > 0 && (reqType&memType) != 0 {
available := cs.mem[memType]
log.Debug("%s: trying %s %s of %s available",
r.GetContainer().PrettyName(),
prettyMem(remaining), memType.String(), prettyMem(available))
if remaining <= available {
allocated[memType] = remaining
} else {
allocated[memType] = available
}
cs.grantedMem[memType] += allocated[memType]
cs.mem[memType] -= allocated[memType]
remaining -= allocated[memType]
}
if remaining > 0 {
if r.ColdStart() > 0 && memType == memoryPMEM {
return nil, policyError("internal error: "+
"not enough PMEM for cold start at %s", cs.GetNode().Name())
}
} else {
break
}
}
if remaining > 0 {
log.Debug("%s: %s allocation from %s fell short %s",
r.GetContainer().PrettyName(),
reqType.String(), cs.GetNode().Name(), prettyMem(remaining))
for memType, amount := range allocated {
if amount > 0 {
cs.grantedMem[memType] -= amount
cs.mem[memType] += amount
}
}
return nil, policyError("internal error: "+
"not enough memory at %s", cs.node.Name())
}
cs.grantedMem[memoryAll] += requested
cs.mem[memoryAll] -= requested
return allocated, nil
}
// Allocate allocates a grant from the supply.
func (cs *supply) Allocate(r Request) (Grant, error) {
grant, err := cs.AllocateCPU(r)
if err != nil {
return nil, err
}
memory, err := cs.allocateMemory(r)
if err != nil {
cs.ReleaseCPU(grant)
return nil, err
}
grant.SetMemoryAllocation(r.MemoryType(), memory, r.ColdStart())
return grant, nil
}
// AllocateCPU allocates CPU for a grant from the supply.
func (cs *supply) AllocateCPU(r Request) (Grant, error) {
var exclusive cpuset.CPUSet
var err error
cr := r.(*request)
full := cr.full
fraction := cr.fraction
cpuType := cr.cpuType
if cpuType == cpuReserved && full > 0 {
log.Warn("exclusive reserved CPUs not supported, allocating %d full CPUs as fractions", full)
fraction += full * 1000
full = 0
}
if cpuType == cpuReserved && fraction > 0 && cs.AllocatableReservedCPU() < fraction {
log.Warn("possible misconfiguration of reserved resources:")
log.Warn(" %s: allocatable %s", cs.GetNode().Name(), cs.DumpAllocatable())
log.Warn(" %s: needs %d reserved, only %d available",
cr.GetContainer().PrettyName(), fraction, cs.AllocatableReservedCPU())
log.Warn(" falling back to using normal unreserved CPUs instead...")
cpuType = cpuNormal
}
// allocate isolated exclusive CPUs or slice them off the sharable set
switch {
case full > 0 && cs.isolated.Size() >= full && cr.isolate:
exclusive, err = cs.takeCPUs(&cs.isolated, nil, full)
if err != nil {
return nil, policyError("internal error: "+
"%s: can't take %d exclusive isolated CPUs from %s: %v",
cs.node.Name(), full, cs.isolated, err)
}
case full > 0 && cs.AllocatableSharedCPU() > 1000*full:
exclusive, err = cs.takeCPUs(&cs.sharable, nil, full)
if err != nil {
return nil, policyError("internal error: "+
"%s: can't take %d exclusive CPUs from %s: %v",
cs.node.Name(), full, cs.sharable, err)
}
case full > 0:
return nil, policyError("internal error: "+
"%s: can't slice %d exclusive CPUs from %s, %dm available",
cs.node.Name(), full, cs.sharable, cs.AllocatableSharedCPU())
}
grant := newGrant(cs.node, cr.GetContainer(), cpuType, exclusive, 0, 0, nil, 0)
grant.AccountAllocateCPU()
if fraction > 0 {
if cpuType == cpuNormal {
// allocate requested portion of shared CPUs
if cs.AllocatableSharedCPU() < fraction {
cs.ReleaseCPU(grant)
return nil, policyError("internal error: "+
"%s: not enough %dm sharable CPU for %dm, %dm available",
cs.node.Name(), fraction, cs.sharable, cs.AllocatableSharedCPU())
}
cs.grantedShared += fraction
} else if cpuType == cpuReserved {
// allocate requested portion of reserved CPUs
if cs.AllocatableReservedCPU() < fraction {
cs.ReleaseCPU(grant)
return nil, policyError("internal error: "+
"%s: not enough reserved CPU: %dm requested, %dm available",
cs.node.Name(), fraction, cs.AllocatableReservedCPU())
}
cs.grantedReserved += fraction
}
grant.SetCPUPortion(fraction)
}
return grant, nil
}
func (cs *supply) ReallocateMemory(g Grant) error {
log.Debug("%s: reallocating memory (%s) from %s to %s",
g.GetContainer().PrettyName(),
g.MemLimit().String(),
g.GetMemoryNode().Name(),
cs.GetNode().Name())
// The grant has been previously allocated from another supply. Reallocate it here.
g.GetMemoryNode().FreeSupply().ReleaseMemory(g)
mem := uint64(0)
allocatedMemory := g.MemLimit()
for key, value := range allocatedMemory {
if cs.mem[key] < value {
return policyError("internal error: not enough memory for reallocation at %s (released from %s)", cs.GetNode().Name(), g.GetMemoryNode().Name())
}
cs.mem[key] -= value
cs.grantedMem[key] += value
mem += value
}
cs.grantedMem[memoryAll] += mem
cs.mem[memoryAll] -= mem
return nil
}
func (cs *supply) ReleaseCPU(g Grant) {
isolated := g.ExclusiveCPUs().Intersection(cs.node.GetSupply().IsolatedCPUs())
sharable := g.ExclusiveCPUs().Difference(isolated)
cs.isolated = cs.isolated.Union(isolated)
cs.sharable = cs.sharable.Union(sharable)
cs.grantedReserved -= g.ReservedPortion()
cs.grantedShared -= g.SharedPortion()
g.AccountReleaseCPU()
}
// ReleaseMemory returns memory from the given grant to the supply.
func (cs *supply) ReleaseMemory(g Grant) {
releasedMemory := uint64(0)
log.Debug("%s: releasing granted memory (%s) from %s",
g.GetContainer().PrettyName(),
g.MemLimit().String(), cs.GetNode().Name())
for key, value := range g.MemLimit() {
cs.grantedMem[key] -= value
cs.mem[key] += value
releasedMemory += value
}
cs.grantedMem[memoryAll] -= releasedMemory
cs.mem[memoryAll] += releasedMemory
cs.node.DepthFirst(func(n Node) error {
n.FreeSupply().ReleaseExtraMemoryReservation(g)
return nil
})
}
func (cs *supply) ExtraMemoryReservation(memType memoryType) uint64 {
extra := uint64(0)
for _, res := range cs.extraMemReservations {
extra += res[memType]
}
return extra
}
func (cs *supply) ReleaseExtraMemoryReservation(g Grant) {
if mems, ok := cs.extraMemReservations[g]; ok {
log.Debug("%s: releasing extra memory reservation (%s) from %s",
g.GetContainer().PrettyName(), mems.String(),
cs.GetNode().Name())
delete(cs.extraMemReservations, g)
}
}
func (cs *supply) SetExtraMemoryReservation(g Grant) {
res := make(memoryMap)
extraMemory := uint64(0)
for key, value := range g.MemLimit() {
res[key] = value
extraMemory += value
}
res[memoryAll] = extraMemory
cs.extraMemReservations[g] = res
}
func (cs *supply) Reserve(g Grant) error {
if g.CPUType() == cpuNormal {
isolated := g.IsolatedCPUs()
exclusive := g.ExclusiveCPUs().Difference(isolated)
sharedPortion := g.SharedPortion()
if !cs.isolated.Intersection(isolated).Equals(isolated) {
return policyError("can't reserve isolated CPUs (%s) of %s from %s",
isolated.String(), g.String(), cs.DumpAllocatable())
}
if !cs.sharable.Intersection(exclusive).Equals(exclusive) {
return policyError("can't reserve exclusive CPUs (%s) of %s from %s",
exclusive.String(), g.String(), cs.DumpAllocatable())
}
if cs.AllocatableSharedCPU() < 1000*exclusive.Size()+sharedPortion {
return policyError("can't reserve %d shared CPUs of %s from %s",
sharedPortion, g.String(), cs.DumpAllocatable())
}
cs.isolated = cs.isolated.Difference(isolated)
cs.sharable = cs.sharable.Difference(exclusive)
cs.grantedShared += sharedPortion
} else if g.CPUType() == cpuReserved {
sharedPortion := 1000*g.ExclusiveCPUs().Size() + g.SharedPortion()
if sharedPortion > 0 && cs.AllocatableReservedCPU() < sharedPortion {
return policyError("can't reserve %d reserved CPUs of %s from %s",
sharedPortion, g.String(), cs.DumpAllocatable())
}
cs.grantedReserved += sharedPortion
}
g.AccountAllocateCPU()
return nil
}
func (cs *supply) ReserveMemory(g Grant) error {
mem := uint64(0)
allocatedMemory := g.MemLimit()
for key, value := range allocatedMemory {
if cs.mem[key] < value {
return policyError("internal error: not enough memory for allocation at %s", g.GetMemoryNode().Name())
}
cs.mem[key] -= value
cs.grantedMem[key] += value
mem += value
}
cs.grantedMem[memoryAll] += mem
cs.mem[memoryAll] -= mem
g.UpdateExtraMemoryReservation()
return nil
}
// takeCPUs takes up to cnt CPUs from a given CPU set to another.
func (cs *supply) takeCPUs(from, to *cpuset.CPUSet, cnt int) (cpuset.CPUSet, error) {
cset, err := cs.node.Policy().cpuAllocator.AllocateCpus(from, cnt, cpuallocator.PriorityHigh)
if err != nil {
return cset, err
}
if to != nil {
*to = to.Union(cset)
}
return cset, err
}
// DumpCapacity returns a printable representation of the supply's resource capacity.
func (cs *supply) DumpCapacity() string {
cpu, mem, sep := "", cs.mem.String(), ""
if !cs.isolated.IsEmpty() {
cpu = fmt.Sprintf("isolated:%s", kubernetes.ShortCPUSet(cs.isolated))
sep = ", "
}
if !cs.reserved.IsEmpty() {
cpu += sep + fmt.Sprintf("reserved:%s (%dm)", kubernetes.ShortCPUSet(cs.reserved),
1000*cs.reserved.Size())
sep = ", "
}
if !cs.sharable.IsEmpty() {
cpu += sep + fmt.Sprintf("sharable:%s (%dm)", kubernetes.ShortCPUSet(cs.sharable),
1000*cs.sharable.Size())
}
capacity := "<" + cs.node.Name() + " capacity: "
if cpu == "" && mem == "" {
capacity += "-"
} else {
sep = ""
if cpu != "" {
capacity += "CPU: " + cpu
sep = ", "
}
if mem != "" {
capacity += sep + "MemLimit: " + mem
}
}
capacity += ">"
return capacity
}
// DumpAllocatable returns a printable representation of the supply's resource capacity.
func (cs *supply) DumpAllocatable() string {
cpu, mem, sep := "", cs.mem.String(), ""
if !cs.isolated.IsEmpty() {
cpu = fmt.Sprintf("isolated:%s", kubernetes.ShortCPUSet(cs.isolated))
sep = ", "
}
if !cs.reserved.IsEmpty() {
cpu += sep + fmt.Sprintf("reserved:%s (allocatable: %dm)", kubernetes.ShortCPUSet(cs.reserved), cs.AllocatableReservedCPU())
sep = ", "
if cs.grantedReserved > 0 {
cpu += sep + fmt.Sprintf("grantedReserved:%dm", cs.grantedReserved)
}
}
local_grantedShared := cs.grantedShared
total_grantedShared := cs.node.GrantedSharedCPU()
if !cs.sharable.IsEmpty() {
cpu += sep + fmt.Sprintf("sharable:%s (", kubernetes.ShortCPUSet(cs.sharable))
sep = ""
if local_grantedShared > 0 || total_grantedShared > 0 {
cpu += fmt.Sprintf("grantedShared:")
kind := ""
if local_grantedShared > 0 {
cpu += fmt.Sprintf("%dm", local_grantedShared)
kind = "local"
sep = "/"
}
if total_grantedShared > 0 {
cpu += sep + fmt.Sprintf("%dm", total_grantedShared)
kind += sep + "subtree"
}
cpu += " " + kind
sep = ", "
}
cpu += sep + fmt.Sprintf("allocatable:%dm)", cs.AllocatableSharedCPU(true))
}
allocatable := "<" + cs.node.Name() + " allocatable: "
if cpu == "" && mem == "" {
allocatable += "-"
} else {
sep = ""
if cpu != "" {
allocatable += "CPU: " + cpu
sep = ", "
}
if mem != "" {
allocatable += sep + "MemLimit: " + mem
}
}
allocatable += ">"
return allocatable
}
// prettyMem formats the given amount as k, M, G, or T units.
func prettyMem(value uint64) string {
units := []string{"k", "M", "G", "T"}
coeffs := []uint64{1 << 10, 1 << 20, 1 << 30, 1 << 40}
c, u := uint64(1), ""
for i := 0; i < len(units); i++ {
if coeffs[i] > value {
break
}
c, u = coeffs[i], units[i]
}
v := float64(value) / float64(c)
return strconv.FormatFloat(v, 'f', 2, 64) + u
}
// DumpMemoryState dumps the state of the available and allocated memory.
func (cs *supply) DumpMemoryState(prefix string) {
memTypes := []memoryType{memoryDRAM, memoryPMEM, memoryHBM}
totalFree := uint64(0)
totalGranted := uint64(0)
for _, kind := range memTypes {
free := cs.mem[kind]
granted := cs.grantedMem[kind]
if free != 0 || granted != 0 {
log.Debug(prefix+"- %s: free: %s, granted %s",
kind, prettyMem(free), prettyMem(granted))
}
totalFree += free
totalGranted += granted
}
log.Debug(prefix+"- total free: %s, total granted %s",
prettyMem(totalFree), prettyMem(totalGranted))
printHdr := true
if len(cs.extraMemReservations) > 0 {
for g, memMap := range cs.extraMemReservations {
split := ""
sep := ""
total := uint64(0)
if mem := memMap[memoryDRAM]; mem > 0 {
split = "DRAM " + prettyMem(mem)
sep = ", "
total += mem
}
if mem := memMap[memoryPMEM]; mem > 0 {
split += sep + "PMEM " + prettyMem(mem)
sep = ", "
total += mem
}
if mem := memMap[memoryHBM]; mem > 0 {
split += sep + "HBMEM " + prettyMem(mem)
sep = ", "
total += mem
}
if total > 0 {
if printHdr {
log.Debug(prefix + "- extra reservations:")
printHdr = false
}
log.Debug(prefix+" - %s: %s (%s)",
g.GetContainer().PrettyName(), prettyMem(total), split)
}
}
}
}
// newRequest creates a new request for the given container.
func newRequest(container cache.Container) Request {
pod, _ := container.GetPod()
full, fraction, isolate, cpuType := cpuAllocationPreferences(pod, container)
req, lim, mtype := memoryAllocationPreference(pod, container)
coldStart := time.Duration(0)
log.Debug("%s: CPU preferences: cpuType=%s, full=%v, fraction=%v, isolate=%v",
container.PrettyName(), cpuType, full, fraction, isolate)
if mtype == memoryUnspec {
mtype = defaultMemoryType
}
if mtype&memoryPMEM != 0 && mtype&memoryDRAM != 0 {
parsedColdStart, err := coldStartPreference(pod, container)
if err != nil {
log.Error("Failed to parse cold start preference")
} else {
if parsedColdStart.Duration > 0 {
if coldStartOff {
log.Error("coldstart disabled (movable non-DRAM memory zones present)")
} else {
coldStart = time.Duration(parsedColdStart.Duration)
}
}
}
} else if mtype == memoryPMEM {
if coldStartOff {
mtype = mtype | memoryDRAM
log.Error("%s: forced also DRAM usage (movable non-DRAM memory zones present)",
container.PrettyName())
}
}
return &request{
container: container,
full: full,
fraction: fraction,
isolate: isolate,
cpuType: cpuType,
memReq: req,
memLim: lim,
memType: mtype,
coldStart: coldStart,
}
}
// GetContainer returns the container requesting CPU.
func (cr *request) GetContainer() cache.Container {
return cr.container
}
// String returns aprintable representation of the CPU request.
func (cr *request) String() string {
mem := "<Memory request: limit:" + prettyMem(cr.memLim) + ", req:" + prettyMem(cr.memReq) + ">"
isolated := map[bool]string{false: "", true: "isolated "}[cr.isolate]
switch {
case cr.full == 0 && cr.fraction == 0: