-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathpolicy.go
More file actions
1296 lines (1128 loc) · 50.6 KB
/
policy.go
File metadata and controls
1296 lines (1128 loc) · 50.6 KB
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 2022 The Katalyst 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 dynamicpolicy
import (
"context"
"errors"
"fmt"
"strconv"
"sync"
"time"
"github.com/cilium/ebpf"
"google.golang.org/grpc"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/wait"
pluginapi "k8s.io/kubelet/pkg/apis/resourceplugin/v1alpha1"
maputil "k8s.io/kubernetes/pkg/util/maps"
"k8s.io/utils/clock"
apiconsts "github.com/kubewharf/katalyst-api/pkg/consts"
"github.com/kubewharf/katalyst-api/pkg/plugins/skeleton"
"github.com/kubewharf/katalyst-core/cmd/katalyst-agent/app/agent"
"github.com/kubewharf/katalyst-core/cmd/katalyst-agent/app/agent/qrm"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/advisorsvc"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/commonstate"
memconsts "github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/memory/consts"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/memory/dynamicpolicy/memoryadvisor"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/memory/dynamicpolicy/oom"
memoryreactor "github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/memory/dynamicpolicy/reactor"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/memory/dynamicpolicy/state"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/memory/handlers/fragmem"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/memory/handlers/logcache"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/memory/handlers/sockmem"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/util"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/util/reactor"
"github.com/kubewharf/katalyst-core/pkg/agent/utilcomponent/featuregatenegotiation"
"github.com/kubewharf/katalyst-core/pkg/agent/utilcomponent/periodicalhandler"
"github.com/kubewharf/katalyst-core/pkg/config"
dynamicconfig "github.com/kubewharf/katalyst-core/pkg/config/agent/dynamic"
"github.com/kubewharf/katalyst-core/pkg/config/generic"
"github.com/kubewharf/katalyst-core/pkg/metaserver"
"github.com/kubewharf/katalyst-core/pkg/metrics"
"github.com/kubewharf/katalyst-core/pkg/util/asyncworker"
"github.com/kubewharf/katalyst-core/pkg/util/general"
"github.com/kubewharf/katalyst-core/pkg/util/machine"
"github.com/kubewharf/katalyst-core/pkg/util/metric"
"github.com/kubewharf/katalyst-core/pkg/util/native"
"github.com/kubewharf/katalyst-core/pkg/util/process"
"github.com/kubewharf/katalyst-core/pkg/util/timemonitor"
)
const (
MemoryResourcePluginPolicyNameDynamic = string(apiconsts.ResourcePluginPolicyNameDynamic)
memoryPluginStateFileName = "memory_plugin_state"
memoryPluginAsyncWorkersName = "qrm_memory_plugin_async_workers"
memoryPluginAsyncWorkTopicDropCache = "qrm_memory_plugin_drop_cache"
memoryPluginAsyncWorkTopicSetExtraCGMemLimit = "qrm_memory_plugin_set_extra_mem_limit"
memoryPluginAsyncWorkTopicMovePage = "qrm_memory_plugin_move_page"
memoryPluginAsyncWorkTopicMemoryOffloading = "qrm_memory_plugin_mem_offload"
dropCacheTimeoutSeconds = 30
setExtraCGMemLimitTimeoutSeconds = 60
)
const (
memsetCheckPeriod = 10 * time.Second
stateCheckPeriod = 30 * time.Second
maxResidualTime = 5 * time.Minute
setMemoryMigratePeriod = 5 * time.Second
applyCgroupPeriod = 5 * time.Second
setExtraControlKnobsPeriod = 5 * time.Second
clearOOMPriorityPeriod = 1 * time.Hour
syncOOMPriorityPeriod = 5 * time.Second
healthCheckTolerationTimes = 3
defaultAsyncWorkLimit = 8
movePagesWorkLimit = 2
)
type DynamicPolicy struct {
sync.RWMutex
stopCh chan struct{}
started bool
dynamicConf *dynamicconfig.DynamicAgentConfiguration
qosConfig *generic.QoSConfiguration
extraControlKnobConfigs commonstate.ExtraControlKnobConfigs
// emitter is used to emit metrics.
// metaServer is used to collect metadata universal metaServer.
emitter metrics.MetricEmitter
metaServer *metaserver.MetaServer
advisorClient advisorsvc.AdvisorServiceClient
advisorConn *grpc.ClientConn
advisorMonitor *timemonitor.TimeMonitor
featureGateManager featuregatenegotiation.FeatureGateManager
// resctrlHinter is in charge of resctrl FS hints for mon group layout customizations
resctrlHinter ResctrlHinter
topology *machine.CPUTopology
state state.State
migrateMemoryLock sync.Mutex
migratingMemory map[string]map[string]bool
residualHitMap map[string]int64
allocationHandlers map[string]util.AllocationHandler
hintHandlers map[string]util.HintHandler
enhancementHandlers util.ResourceEnhancementHandlerMap
extraStateFileAbsPath string
name string
podDebugAnnoKeys []string
podAnnotationKeptKeys []string
podLabelKeptKeys []string
asyncWorkers *asyncworker.AsyncWorkers
// defaultAsyncLimitedWorkers is general workers with default limit.
// asyncLimitedWorkersMap is workers map for plugin can define its own limit.
defaultAsyncLimitedWorkers *asyncworker.AsyncLimitedWorkers
asyncLimitedWorkersMap map[string]*asyncworker.AsyncLimitedWorkers
enableSettingMemoryMigrate bool
enableSettingSockMem bool
enableSettingFragMem bool
enableMemoryAdvisor bool
getAdviceInterval time.Duration
memoryAdvisorSocketAbsPath string
memoryPluginSocketAbsPath string
enableOOMPriority bool
oomPriorityMapPinnedPath string
oomPriorityMapLock sync.Mutex
oomPriorityMap *ebpf.Map
enableEvictingLogCache bool
logCacheEvictionManager logcache.Manager
enableReclaimNUMABinding bool
enableSNBHighNumaPreference bool
enableNonBindingShareCoresMemoryResourceCheck bool
numaAllocationReactor reactor.AllocationReactor
numaBindResultResourceAllocationAnnotationKey string
}
func NewDynamicPolicy(agentCtx *agent.GenericContext, conf *config.Configuration,
_ interface{}, agentName string,
) (bool, agent.Component, error) {
reservedMemory, err := getReservedMemory(conf, agentCtx.MetaServer, agentCtx.MachineInfo)
if err != nil {
return false, agent.ComponentStub{}, fmt.Errorf("getReservedMemoryFromOptions failed with error: %v", err)
}
wrappedEmitter := agentCtx.EmitterPool.GetDefaultMetricsEmitter().WithTags(agentName, metrics.MetricTag{
Key: util.QRMPluginPolicyTagName,
Val: memconsts.MemoryResourcePluginPolicyNameDynamic,
})
resourcesReservedMemory := map[v1.ResourceName]map[int]uint64{
v1.ResourceMemory: reservedMemory,
}
stateImpl, err := state.NewCheckpointState(conf.StateDirectoryConfiguration, memoryPluginStateFileName,
memconsts.MemoryResourcePluginPolicyNameDynamic, agentCtx.CPUTopology, agentCtx.MachineInfo, resourcesReservedMemory, conf.SkipMemoryStateCorruption, wrappedEmitter)
if err != nil {
return false, agent.ComponentStub{}, fmt.Errorf("NewCheckpointState failed with error: %v", err)
}
extraControlKnobConfigs := make(commonstate.ExtraControlKnobConfigs)
if len(conf.ExtraControlKnobConfigFile) > 0 {
extraControlKnobConfigs, err = commonstate.LoadExtraControlKnobConfigs(conf.ExtraControlKnobConfigFile)
if err != nil {
return false, agent.ComponentStub{}, fmt.Errorf("loadExtraControlKnobConfigs failed with error: %v", err)
}
} else {
general.Infof("empty ExtraControlKnobConfigFile, initialize empty extraControlKnobConfigs")
}
state.SetReadonlyState(stateImpl)
state.SetReadWriteState(stateImpl)
policyImplement := &DynamicPolicy{
topology: agentCtx.CPUTopology,
dynamicConf: conf.DynamicAgentConfiguration,
qosConfig: conf.QoSConfiguration,
emitter: wrappedEmitter,
metaServer: agentCtx.MetaServer,
state: stateImpl,
stopCh: make(chan struct{}),
migratingMemory: make(map[string]map[string]bool),
residualHitMap: make(map[string]int64),
featureGateManager: featuregatenegotiation.NewFeatureGateManager(conf),
enhancementHandlers: make(util.ResourceEnhancementHandlerMap),
extraStateFileAbsPath: conf.ExtraStateFileAbsPath,
name: fmt.Sprintf("%s_%s", agentName, memconsts.MemoryResourcePluginPolicyNameDynamic),
podDebugAnnoKeys: conf.PodDebugAnnoKeys,
podAnnotationKeptKeys: conf.PodAnnotationKeptKeys,
podLabelKeptKeys: conf.PodLabelKeptKeys,
asyncWorkers: asyncworker.NewAsyncWorkers(memoryPluginAsyncWorkersName, wrappedEmitter),
defaultAsyncLimitedWorkers: asyncworker.NewAsyncLimitedWorkers(memoryPluginAsyncWorkersName, defaultAsyncWorkLimit, wrappedEmitter),
enableSettingMemoryMigrate: conf.EnableSettingMemoryMigrate,
enableSettingSockMem: conf.EnableSettingSockMem,
enableSettingFragMem: conf.EnableSettingFragMem,
enableMemoryAdvisor: conf.EnableMemoryAdvisor,
getAdviceInterval: conf.GetAdviceInterval,
memoryAdvisorSocketAbsPath: conf.MemoryAdvisorSocketAbsPath,
memoryPluginSocketAbsPath: conf.MemoryPluginSocketAbsPath,
extraControlKnobConfigs: extraControlKnobConfigs, // [TODO]: support modifying extraControlKnobConfigs by KCC
enableOOMPriority: conf.EnableOOMPriority,
oomPriorityMapPinnedPath: conf.OOMPriorityPinnedMapAbsPath,
enableEvictingLogCache: conf.EnableEvictingLogCache,
enableReclaimNUMABinding: conf.EnableReclaimNUMABinding,
enableSNBHighNumaPreference: conf.EnableSNBHighNumaPreference,
resctrlHinter: newResctrlHinter(&conf.ResctrlConfig, wrappedEmitter, stateImpl),
enableNonBindingShareCoresMemoryResourceCheck: conf.EnableNonBindingShareCoresMemoryResourceCheck,
numaBindResultResourceAllocationAnnotationKey: conf.NUMABindResultResourceAllocationAnnotationKey,
}
policyImplement.allocationHandlers = map[string]util.AllocationHandler{
apiconsts.PodAnnotationQoSLevelSharedCores: policyImplement.sharedCoresAllocationHandler,
apiconsts.PodAnnotationQoSLevelDedicatedCores: policyImplement.dedicatedCoresAllocationHandler,
apiconsts.PodAnnotationQoSLevelReclaimedCores: policyImplement.reclaimedCoresAllocationHandler,
apiconsts.PodAnnotationQoSLevelSystemCores: policyImplement.systemCoresAllocationHandler,
}
policyImplement.hintHandlers = map[string]util.HintHandler{
apiconsts.PodAnnotationQoSLevelSharedCores: policyImplement.sharedCoresHintHandler,
apiconsts.PodAnnotationQoSLevelDedicatedCores: policyImplement.dedicatedCoresHintHandler,
apiconsts.PodAnnotationQoSLevelReclaimedCores: policyImplement.reclaimedCoresHintHandler,
apiconsts.PodAnnotationQoSLevelSystemCores: policyImplement.systemCoresHintHandler,
}
policyImplement.asyncLimitedWorkersMap = map[string]*asyncworker.AsyncLimitedWorkers{
memoryPluginAsyncWorkTopicMovePage: asyncworker.NewAsyncLimitedWorkers(memoryPluginAsyncWorkTopicMovePage, movePagesWorkLimit, wrappedEmitter),
}
if policyImplement.enableOOMPriority {
policyImplement.enhancementHandlers.Register(apiconsts.QRMPhaseRemovePod,
apiconsts.PodAnnotationMemoryEnhancementOOMPriority, policyImplement.clearOOMPriority)
}
pluginWrapper, err := skeleton.NewRegistrationPluginWrapper(policyImplement, conf.QRMPluginSocketDirs,
func(key string, value int64) {
_ = wrappedEmitter.StoreInt64(key, value, metrics.MetricTypeNameRaw)
})
if err != nil {
return false, agent.ComponentStub{}, fmt.Errorf("dynamic policy new plugin wrapper failed with error: %v", err)
}
memoryadvisor.RegisterControlKnobHandler(memoryadvisor.ControlKnobKeyMemoryLimitInBytes,
memoryadvisor.ControlKnobHandlerWithChecker(policyImplement.handleAdvisorMemoryLimitInBytes))
memoryadvisor.RegisterControlKnobHandler(memoryadvisor.ControlKnobKeyCPUSetMems,
memoryadvisor.ControlKnobHandlerWithChecker(policyImplement.handleAdvisorCPUSetMems))
memoryadvisor.RegisterControlKnobHandler(memoryadvisor.ControlKnobKeyDropCache,
memoryadvisor.ControlKnobHandlerWithChecker(policyImplement.handleAdvisorDropCache))
memoryadvisor.RegisterControlKnobHandler(memoryadvisor.ControlKnobReclaimedMemorySize,
memoryadvisor.ControlKnobHandlerWithChecker(policyImplement.handleAdvisorMemoryProvisions))
memoryadvisor.RegisterControlKnobHandler(memoryadvisor.ControlKnobKeyBalanceNumaMemory,
memoryadvisor.ControlKnobHandlerWithChecker(policyImplement.handleNumaMemoryBalance))
memoryadvisor.RegisterControlKnobHandler(memoryadvisor.ControlKnowKeyMemoryOffloading,
memoryadvisor.ControlKnobHandlerWithChecker(policyImplement.handleAdvisorMemoryOffloading))
memoryadvisor.RegisterControlKnobHandler(memoryadvisor.ControlKnobKeyMemoryNUMAHeadroom,
memoryadvisor.ControlKnobHandlerWithChecker(policyImplement.handleAdvisorMemoryNUMAHeadroom))
if policyImplement.enableEvictingLogCache {
policyImplement.logCacheEvictionManager = logcache.NewManager(conf, agentCtx.MetaServer)
}
policyImplement.numaAllocationReactor = reactor.DummyAllocationReactor{}
if conf.EnableNUMAAllocationReactor {
policyImplement.numaAllocationReactor = memoryreactor.NewNUMAPodAllocationReactor(
reactor.NewPodAllocationReactor(
agentCtx.MetaServer.PodFetcher,
agentCtx.Client.KubeClient,
))
}
return true, &agent.PluginWrapper{GenericPlugin: pluginWrapper}, nil
}
func (p *DynamicPolicy) registerControlKnobHandlerCheckRules() {
general.RegisterReportCheck(memconsts.DropCache, 0, general.HealthzCheckStateReady)
}
func (p *DynamicPolicy) Start() (err error) {
general.Infof("called")
p.Lock()
defer func() {
if !p.started {
if err == nil {
p.started = true
} else {
close(p.stopCh)
}
}
p.Unlock()
}()
if p.started {
general.Infof("already started")
return nil
}
p.stopCh = make(chan struct{})
p.registerControlKnobHandlerCheckRules()
go wait.Until(func() {
_ = p.emitter.StoreInt64(util.MetricNameHeartBeat, 1, metrics.MetricTypeNameRaw)
}, time.Second*30, p.stopCh)
err = periodicalhandler.RegisterPeriodicalHandlerWithHealthz(memconsts.ClearResidualState,
general.HealthzCheckStateNotReady, qrm.QRMMemoryPluginPeriodicalHandlerGroupName,
p.clearResidualState, stateCheckPeriod, healthCheckTolerationTimes)
if err != nil {
general.Errorf("start %v failed, err: %v", memconsts.ClearResidualState, err)
}
// TODO: we should remove this healthy check when we support inplace update resize in all clusters.
syncMemoryStatusFromSpec := func(_ *config.Configuration,
_ interface{},
_ *dynamicconfig.DynamicAgentConfiguration,
_ metrics.MetricEmitter,
_ *metaserver.MetaServer,
) {
p.Lock()
defer func() {
p.Unlock()
}()
if err := p.adjustAllocationEntries(true); err != nil {
general.Warningf("failed to sync memory state from pod spec: %q", err)
} else {
general.Warningf("sync memory state from pod spec successfully")
}
}
err = periodicalhandler.RegisterPeriodicalHandler(qrm.QRMMemoryPluginPeriodicalHandlerGroupName, memconsts.SyncMemoryStateFromSpec,
syncMemoryStatusFromSpec, stateCheckPeriod)
if err != nil {
general.Errorf("start %v failed, err: %v", memconsts.SyncMemoryStateFromSpec, err)
}
err = periodicalhandler.RegisterPeriodicalHandlerWithHealthz(memconsts.CheckMemSet, general.HealthzCheckStateNotReady,
qrm.QRMMemoryPluginPeriodicalHandlerGroupName, p.checkMemorySet, memsetCheckPeriod, healthCheckTolerationTimes)
if err != nil {
general.Errorf("start %v failed, err: %v", memconsts.CheckMemSet, err)
}
err = periodicalhandler.RegisterPeriodicalHandlerWithHealthz(memconsts.ApplyExternalCGParams, general.HealthzCheckStateNotReady,
qrm.QRMMemoryPluginPeriodicalHandlerGroupName, p.applyExternalCgroupParams, applyCgroupPeriod, healthCheckTolerationTimes)
if err != nil {
general.Errorf("start %v failed, err: %v", memconsts.ApplyExternalCGParams, err)
}
err = periodicalhandler.RegisterPeriodicalHandlerWithHealthz(memconsts.SetExtraControlKnob, general.HealthzCheckStateNotReady,
qrm.QRMMemoryPluginPeriodicalHandlerGroupName, p.setExtraControlKnobByConfigs, setExtraControlKnobsPeriod, healthCheckTolerationTimes)
if err != nil {
general.Errorf("start %v failed, err: %v", memconsts.SetExtraControlKnob, err)
}
err = p.asyncWorkers.Start(p.stopCh)
if err != nil {
general.Errorf("start async worker failed, err: %v", err)
}
err = p.defaultAsyncLimitedWorkers.Start(p.stopCh)
if err != nil {
general.Errorf("start async limited worker failed, err: %v", err)
}
for name, workers := range p.asyncLimitedWorkersMap {
err = workers.Start(p.stopCh)
if err != nil {
general.Errorf("start async limited worker for plugin %s failed, err: %v", name, err)
}
}
if p.enableSettingMemoryMigrate {
general.Infof("setMemoryMigrate enabled")
go wait.Until(p.setMemoryMigrate, setMemoryMigratePeriod, p.stopCh)
}
if p.enableOOMPriority {
general.Infof("OOM priority enabled")
go p.PollOOMBPFInit(p.stopCh)
err := periodicalhandler.RegisterPeriodicalHandler(qrm.QRMMemoryPluginPeriodicalHandlerGroupName,
oom.ClearResidualOOMPriorityPeriodicalHandlerName, p.clearResidualOOMPriority, clearOOMPriorityPeriod)
if err != nil {
general.Infof("register clearResidualOOMPriority failed, err=%v", err)
}
err = periodicalhandler.RegisterPeriodicalHandlerWithHealthz(memconsts.OOMPriority, general.HealthzCheckStateNotReady,
qrm.QRMMemoryPluginPeriodicalHandlerGroupName, p.syncOOMPriority, syncOOMPriorityPeriod, healthCheckTolerationTimes)
if err != nil {
general.Infof("register syncOOMPriority failed, err=%v", err)
}
}
if p.enableSettingSockMem {
general.Infof("setSockMem enabled")
err := periodicalhandler.RegisterPeriodicalHandlerWithHealthz(memconsts.SetSockMem,
general.HealthzCheckStateNotReady, qrm.QRMMemoryPluginPeriodicalHandlerGroupName,
sockmem.SetSockMemLimit, 240*time.Second, healthCheckTolerationTimes)
if err != nil {
general.Infof("setSockMem failed, err=%v", err)
}
}
if p.enableEvictingLogCache {
general.Infof("evictLogCache enabled")
err := periodicalhandler.RegisterPeriodicalHandlerWithHealthz(memconsts.EvictLogCache,
general.HealthzCheckStateNotReady, qrm.QRMMemoryPluginPeriodicalHandlerGroupName,
p.logCacheEvictionManager.EvictLogCache, 600*time.Second, healthCheckTolerationTimes)
if err != nil {
general.Errorf("evictLogCache failed, err=%v", err)
}
}
if p.enableSettingFragMem {
general.Infof("setFragMem enabled")
err := periodicalhandler.RegisterPeriodicalHandlerWithHealthz(memconsts.SetMemCompact,
general.HealthzCheckStateNotReady, qrm.QRMMemoryPluginPeriodicalHandlerGroupName,
fragmem.SetMemCompact, 1800*time.Second, healthCheckTolerationTimes)
if err != nil {
general.Infof("setFragMem failed, err=%v", err)
}
}
go wait.Until(func() {
periodicalhandler.ReadyToStartHandlersByGroup(qrm.QRMMemoryPluginPeriodicalHandlerGroupName)
}, 5*time.Second, p.stopCh)
if p.resctrlHinter != nil {
go p.resctrlHinter.Run(p.stopCh)
}
if !p.enableMemoryAdvisor {
general.Infof("start dynamic policy memory plugin without memory advisor")
return nil
} else if p.memoryAdvisorSocketAbsPath == "" {
return fmt.Errorf("invalid memoryAdvisorSocketAbsPath: %s", p.memoryAdvisorSocketAbsPath)
}
general.Infof("start dynamic policy memory plugin with memory advisor")
general.RegisterHeartbeatCheck(memconsts.CommunicateWithAdvisor, 2*time.Minute, general.HealthzCheckStateNotReady,
2*time.Minute)
err = p.initAdvisorClientConn()
if err != nil {
general.Errorf("initAdvisorClientConn failed with error: %v", err)
return
}
p.advisorMonitor, err = timemonitor.NewTimeMonitor(memoryAdvisorHealthMonitorName, memoryAdvisorHealthMonitorInterval,
memoryAdvisorUnhealthyThreshold, memoryAdvisorHealthyThreshold,
util.MetricNameAdvisorUnhealthy, p.emitter, memoryAdvisorHealthyCount, true)
if err != nil {
general.Errorf("initialize memory advisor monitor failed with error: %v", err)
return
}
go p.advisorMonitor.Run(p.stopCh)
go wait.BackoffUntil(func() { p.serveForAdvisor(p.stopCh) }, wait.NewExponentialBackoffManager(
800*time.Millisecond, 30*time.Second, 2*time.Minute, 2.0, 0, &clock.RealClock{}), true, p.stopCh)
communicateWithMemoryAdvisorServer := func() {
general.Infof("waiting memory plugin checkpoint server serving confirmation")
if conn, err := process.Dial(p.memoryPluginSocketAbsPath, 5*time.Second); err != nil {
general.Errorf("dial check at socket: %s failed with err: %v", p.memoryPluginSocketAbsPath, err)
return
} else {
_ = conn.Close()
}
general.Infof("memory plugin checkpoint server serving confirmed")
p.getAdviceFromAdvisorLoop(p.stopCh)
select {
case <-p.stopCh:
// stopCh closed, no need to fall back to ListAndWatch.
return
default:
}
general.Infof("advisor does not implement GetAdvice, fall back to ListAndWatch")
// keep compatible to old version sys advisor not supporting list containers from memory plugin
if err := p.pushMemoryAdvisor(); err != nil {
general.Errorf("sync existing containers to memory advisor failed with error: %v", err)
return
}
// call lw of MemoryAdvisorServer and do allocation
if err := p.lwMemoryAdvisorServer(p.stopCh); err != nil {
general.Errorf("lwMemoryAdvisorServer failed with error: %v", err)
} else {
general.Infof("lwMemoryAdvisorServer finished")
}
}
go wait.BackoffUntil(communicateWithMemoryAdvisorServer, wait.NewExponentialBackoffManager(800*time.Millisecond,
30*time.Second, 2*time.Minute, 2.0, 0, &clock.RealClock{}), true, p.stopCh)
return nil
}
func (p *DynamicPolicy) Stop() error {
p.Lock()
defer func() {
p.oomPriorityMap.Close()
p.started = false
p.Unlock()
general.Warningf("stopped")
}()
if !p.started {
general.Warningf("already stopped")
return nil
}
close(p.stopCh)
periodicalhandler.StopHandlersByGroup(qrm.QRMMemoryPluginPeriodicalHandlerGroupName)
return nil
}
func (p *DynamicPolicy) Name() string {
return p.name
}
func (p *DynamicPolicy) ResourceName() string {
return string(v1.ResourceMemory)
}
// GetTopologyHints returns hints of corresponding resources
func (p *DynamicPolicy) GetTopologyHints(ctx context.Context,
req *pluginapi.ResourceRequest,
) (resp *pluginapi.ResourceHintsResponse, err error) {
if req == nil {
return nil, fmt.Errorf("GetTopologyHints got nil req")
}
// identify if the pod is a debug pod,
// if so, apply specific strategy to it.
// since GetKatalystQoSLevelFromResourceReq function will filter annotations,
// we should do it before GetKatalystQoSLevelFromResourceReq.
isDebugPod := util.IsDebugPod(req.Annotations, p.podDebugAnnoKeys)
qosLevel, err := util.GetKatalystQoSLevelFromResourceReq(p.qosConfig, req, p.podAnnotationKeptKeys, p.podLabelKeptKeys)
if err != nil {
err = fmt.Errorf("GetKatalystQoSLevelFromResourceReq for pod: %s/%s, container: %s failed with error: %v",
req.PodNamespace, req.PodName, req.ContainerName, err)
general.Errorf("%s", err.Error())
return nil, err
}
reqInt, _, err := util.GetQuantityFromResourceReq(req)
if err != nil {
return nil, fmt.Errorf("getReqQuantityFromResourceReq failed with error: %v", err)
}
general.InfoS("called",
"podNamespace", req.PodNamespace,
"podName", req.PodName,
"containerName", req.ContainerName,
"podType", req.PodType,
"podRole", req.PodRole,
"containerType", req.ContainerType,
"qosLevel", qosLevel,
"memoryReq(bytes)", reqInt,
"isDebugPod", isDebugPod)
if req.ContainerType == pluginapi.ContainerType_INIT || isDebugPod {
general.Infof("there is no NUMA preference, return nil hint")
return util.PackResourceHintsResponse(req, string(v1.ResourceMemory),
map[string]*pluginapi.ListOfTopologyHints{
string(v1.ResourceMemory): nil,
})
}
startTime := time.Now()
p.RLock()
defer func() {
p.RUnlock()
if err != nil {
inplaceUpdateResizing := util.PodInplaceUpdateResizing(req)
_ = p.emitter.StoreInt64(util.MetricNameGetTopologyHintsFailed, 1, metrics.MetricTypeNameRaw,
metrics.MetricTag{Key: "error_message", Val: metric.MetricTagValueFormat(err)},
metrics.MetricTag{Key: util.MetricTagNameInplaceUpdateResizing, Val: strconv.FormatBool(inplaceUpdateResizing)})
general.ErrorS(err, "GetTopologyHints failed",
"podNamespace", req.PodNamespace,
"podName", req.PodName,
"containerName", req.ContainerName,
"inplaceUpdateResizing", inplaceUpdateResizing,
)
}
general.InfoS("finished",
"duration", time.Since(startTime),
"podNamespace", req.PodNamespace,
"podName", req.PodName,
"containerName", req.ContainerName,
)
}()
if p.hintHandlers[qosLevel] == nil {
return nil, fmt.Errorf("katalyst QoS level: %s is not supported yet", qosLevel)
}
return p.hintHandlers[qosLevel](ctx, req)
}
// GetPodTopologyHints returns hints of corresponding resources for pod
func (p *DynamicPolicy) GetPodTopologyHints(ctx context.Context,
req *pluginapi.PodResourceRequest,
) (*pluginapi.PodResourceHintsResponse, error) {
return nil, util.ErrNotImplemented
}
func (p *DynamicPolicy) RemovePod(ctx context.Context,
req *pluginapi.RemovePodRequest,
) (resp *pluginapi.RemovePodResponse, err error) {
if req == nil {
return nil, fmt.Errorf("RemovePod got nil req")
}
general.InfoS("called", "podUID", req.PodUid)
startTime := time.Now()
p.Lock()
defer func() {
p.Unlock()
if err != nil {
_ = p.emitter.StoreInt64(util.MetricNameRemovePodFailed, 1, metrics.MetricTypeNameRaw,
metrics.MetricTag{Key: "error_message", Val: metric.MetricTagValueFormat(err)})
general.ErrorS(err, "RemovePod failed", "podUID", req.PodUid)
}
general.InfoS("finished", "duration", time.Since(startTime), "podUID", req.PodUid)
}()
for lastLevelEnhancementKey, handler := range p.enhancementHandlers[apiconsts.QRMPhaseRemovePod] {
if p.hasLastLevelEnhancementKey(lastLevelEnhancementKey, req.PodUid) {
herr := handler(ctx, p.emitter, p.metaServer, req,
p.state.GetPodResourceEntries())
if herr != nil {
return &pluginapi.RemovePodResponse{}, herr
}
}
}
if p.enableMemoryAdvisor {
if p.advisorClient == nil {
return nil, fmt.Errorf("memory advisor client is nil")
}
_, err = p.advisorClient.RemovePod(ctx, &advisorsvc.RemovePodRequest{PodUid: req.PodUid})
if err != nil {
return nil, fmt.Errorf("remove pod in QoS aware server failed with error: %v", err)
}
}
err = p.removePod(req.PodUid, false)
if err != nil {
general.ErrorS(err, "remove pod failed with error", "podUID", req.PodUid)
_ = p.emitter.StoreInt64(util.MetricNameRemovePodFailed, 1, metrics.MetricTypeNameRaw,
metrics.MetricTag{Key: "error_message", Val: metric.MetricTagValueFormat(err)})
return nil, err
}
aErr := p.adjustAllocationEntries(false)
if aErr != nil {
general.ErrorS(aErr, "adjustAllocationEntries failed", "podUID", req.PodUid)
}
if err := p.state.StoreState(); err != nil {
general.ErrorS(err, "store state failed", "podUID", req.PodUid)
}
return &pluginapi.RemovePodResponse{}, nil
}
// GetResourcesAllocation returns allocation results of corresponding resources
func (p *DynamicPolicy) GetResourcesAllocation(_ context.Context,
req *pluginapi.GetResourcesAllocationRequest,
) (*pluginapi.GetResourcesAllocationResponse, error) {
if req == nil {
return nil, fmt.Errorf("GetResourcesAllocation got nil req")
}
p.RLock()
defer p.RUnlock()
podResources := make(map[string]*pluginapi.ContainerResources)
podEntries := p.state.GetPodResourceEntries()[v1.ResourceMemory]
needUpdateMachineState := false
for podUID, containerEntries := range podEntries {
if podResources[podUID] == nil {
podResources[podUID] = &pluginapi.ContainerResources{}
}
mainContainerAllocationInfo, _ := podEntries.GetMainContainerAllocation(podUID)
for containerName, allocationInfo := range containerEntries {
if allocationInfo == nil {
continue
}
if allocationInfo.CheckSideCar() && mainContainerAllocationInfo != nil {
if applySidecarAllocationInfoFromMainContainer(allocationInfo, mainContainerAllocationInfo) {
general.Infof("pod: %s/%s sidecar container: %s update its allocation",
allocationInfo.PodNamespace, allocationInfo.PodName, allocationInfo.ContainerName)
p.state.SetAllocationInfo(v1.ResourceMemory, podUID, containerName, allocationInfo, true)
needUpdateMachineState = true
}
}
if podResources[podUID].ContainerResources == nil {
podResources[podUID].ContainerResources = make(map[string]*pluginapi.ResourceAllocation)
}
resourceAllocation, err := allocationInfo.GetResourceAllocation()
if err != nil {
errMsg := "allocationInfo.GetResourceAllocation failed"
general.ErrorS(err, errMsg,
"podNamespace", allocationInfo.PodNamespace,
"podName", allocationInfo.PodName,
"containerName", allocationInfo.ContainerName)
return nil, fmt.Errorf(errMsg)
}
if p.resctrlHinter != nil {
p.resctrlHinter.HintResourceAllocation(allocationInfo.AllocationMeta, resourceAllocation)
}
podResources[podUID].ContainerResources[containerName] = resourceAllocation
}
}
if needUpdateMachineState {
general.Infof("GetResourcesAllocation update machine state")
podResourceEntries := p.state.GetPodResourceEntries()
resourcesState, err := state.GenerateMachineStateFromPodEntries(p.state.GetMachineInfo(), podResourceEntries, p.state.GetMachineState(), p.state.GetReservedMemory())
if err != nil {
general.Infof("GetResourcesAllocation GenerateMachineStateFromPodEntries failed with error: %v", err)
return nil, fmt.Errorf("calculate machineState by updated pod entries failed with error: %v", err)
}
p.state.SetMachineState(resourcesState, true)
}
return &pluginapi.GetResourcesAllocationResponse{
PodResources: podResources,
}, nil
}
// GetTopologyAwareResources returns allocation results of corresponding resources as topology aware format
func (p *DynamicPolicy) GetTopologyAwareResources(_ context.Context,
req *pluginapi.GetTopologyAwareResourcesRequest,
) (*pluginapi.GetTopologyAwareResourcesResponse, error) {
if req == nil {
return nil, fmt.Errorf("GetTopologyAwareResources got nil req")
}
p.RLock()
defer p.RUnlock()
allocationInfo := p.state.GetAllocationInfo(v1.ResourceMemory, req.PodUid, req.ContainerName)
if allocationInfo == nil {
return nil, fmt.Errorf("pod: %s, container: %s is not show up in memory plugin state", req.PodUid, req.ContainerName)
}
topologyAwareQuantityList := util.GetTopologyAwareQuantityFromAssignmentsSize(allocationInfo.TopologyAwareAllocations)
resp := &pluginapi.GetTopologyAwareResourcesResponse{
PodUid: allocationInfo.PodUid,
PodName: allocationInfo.PodName,
PodNamespace: allocationInfo.PodNamespace,
ContainerTopologyAwareResources: &pluginapi.ContainerTopologyAwareResources{
ContainerName: allocationInfo.ContainerName,
},
}
if allocationInfo.CheckSideCar() {
resp.ContainerTopologyAwareResources.AllocatedResources = map[string]*pluginapi.TopologyAwareResource{
string(v1.ResourceMemory): {
IsNodeResource: false,
IsScalarResource: true,
AggregatedQuantity: 0,
OriginalAggregatedQuantity: 0,
TopologyAwareQuantityList: nil,
OriginalTopologyAwareQuantityList: nil,
},
}
} else {
resp.ContainerTopologyAwareResources.AllocatedResources = map[string]*pluginapi.TopologyAwareResource{
string(v1.ResourceMemory): {
IsNodeResource: false,
IsScalarResource: true,
AggregatedQuantity: float64(allocationInfo.AggregatedQuantity),
OriginalAggregatedQuantity: float64(allocationInfo.AggregatedQuantity),
TopologyAwareQuantityList: topologyAwareQuantityList,
OriginalTopologyAwareQuantityList: topologyAwareQuantityList,
},
}
}
return resp, nil
}
// GetTopologyAwareAllocatableResources returns corresponding allocatable resources as topology aware format
func (p *DynamicPolicy) GetTopologyAwareAllocatableResources(context.Context,
*pluginapi.GetTopologyAwareAllocatableResourcesRequest,
) (*pluginapi.GetTopologyAwareAllocatableResourcesResponse, error) {
p.RLock()
defer p.RUnlock()
machineState := p.state.GetMachineState()[v1.ResourceMemory]
numaNodes := p.topology.CPUDetails.NUMANodes().ToSliceInt()
topologyAwareAllocatableQuantityList := make([]*pluginapi.TopologyAwareQuantity, 0, len(machineState))
topologyAwareCapacityQuantityList := make([]*pluginapi.TopologyAwareQuantity, 0, len(machineState))
var aggregatedAllocatableQuantity, aggregatedCapacityQuantity uint64 = 0, 0
for _, numaNode := range numaNodes {
numaNodeState := machineState[numaNode]
if numaNodeState == nil {
return nil, fmt.Errorf("nil numaNodeState for NUMA: %d", numaNode)
}
topologyAwareAllocatableQuantityList = append(topologyAwareAllocatableQuantityList, &pluginapi.TopologyAwareQuantity{
ResourceValue: float64(numaNodeState.Allocatable),
Node: uint64(numaNode),
})
topologyAwareCapacityQuantityList = append(topologyAwareCapacityQuantityList, &pluginapi.TopologyAwareQuantity{
ResourceValue: float64(numaNodeState.TotalMemSize),
Node: uint64(numaNode),
})
aggregatedAllocatableQuantity += numaNodeState.Allocatable
aggregatedCapacityQuantity += numaNodeState.TotalMemSize
}
return &pluginapi.GetTopologyAwareAllocatableResourcesResponse{
AllocatableResources: map[string]*pluginapi.AllocatableTopologyAwareResource{
string(v1.ResourceMemory): {
IsNodeResource: false,
IsScalarResource: true,
AggregatedAllocatableQuantity: float64(aggregatedAllocatableQuantity),
TopologyAwareAllocatableQuantityList: topologyAwareAllocatableQuantityList,
AggregatedCapacityQuantity: float64(aggregatedCapacityQuantity),
TopologyAwareCapacityQuantityList: topologyAwareCapacityQuantityList,
},
},
}, nil
}
// GetResourcePluginOptions returns options to be communicated with Resource Manager
func (p *DynamicPolicy) GetResourcePluginOptions(context.Context,
*pluginapi.Empty,
) (*pluginapi.ResourcePluginOptions, error) {
return &pluginapi.ResourcePluginOptions{
PreStartRequired: false,
WithTopologyAlignment: true,
NeedReconcile: true,
}, nil
}
// postAllocateForResctrl makes applicable changes to response's annotations
// as hint to kubelet about resctrl FS related settings
func (p *DynamicPolicy) postAllocateForResctrl(qosLevel string, req *pluginapi.ResourceRequest, resp *pluginapi.ResourceAllocationResponse) {
if p.resctrlHinter == nil {
return
}
meta := state.GenerateMemoryContainerAllocationMeta(req, qosLevel)
p.resctrlHinter.Allocate(meta, resp.AllocationResult)
}
// Allocate is called during pod admit so that the resource
// plugin can allocate corresponding resource for the container
// according to resource request
func (p *DynamicPolicy) Allocate(ctx context.Context,
req *pluginapi.ResourceRequest,
) (resp *pluginapi.ResourceAllocationResponse, respErr error) {
if req == nil {
return nil, fmt.Errorf("Allocate got nil req")
}
// identify if the pod is a debug pod,
// if so, apply specific strategy to it.
// since GetKatalystQoSLevelFromResourceReq function will filter annotations,
// we should do it before GetKatalystQoSLevelFromResourceReq.
isDebugPod := util.IsDebugPod(req.Annotations, p.podDebugAnnoKeys)
existReallocAnno, isReallocation := util.IsReallocation(req.Annotations)
qosLevel, err := util.GetKatalystQoSLevelFromResourceReq(p.qosConfig, req, p.podAnnotationKeptKeys, p.podLabelKeptKeys)
if err != nil {
err = fmt.Errorf("GetKatalystQoSLevelFromResourceReq for pod: %s/%s, container: %s failed with error: %v",
req.PodNamespace, req.PodName, req.ContainerName, err)
general.Errorf("%s", err.Error())
return nil, err
}
// register post-process to inject applicable resp annotation as kubelet pod admit hint
defer func() {
if respErr == nil {
p.postAllocateForResctrl(qosLevel, req, resp)
}
}()
reqInt, _, err := util.GetQuantityFromResourceReq(req)
if err != nil {
return nil, fmt.Errorf("getReqQuantityFromResourceReq failed with error: %v", err)
}
general.InfoS("called",
"podNamespace", req.PodNamespace,
"podName", req.PodName,
"containerName", req.ContainerName,
"podType", req.PodType,
"podRole", req.PodRole,
"qosLevel", qosLevel,
"memoryReq(bytes)", reqInt,
"hint", req.Hint)
if req.ContainerType == pluginapi.ContainerType_INIT {
return &pluginapi.ResourceAllocationResponse{
PodUid: req.PodUid,
PodNamespace: req.PodNamespace,
PodName: req.PodName,
ContainerName: req.ContainerName,
ContainerType: req.ContainerType,
ContainerIndex: req.ContainerIndex,
PodRole: req.PodRole,
PodType: req.PodType,
ResourceName: string(v1.ResourceMemory),
Labels: general.DeepCopyMap(req.Labels),
Annotations: general.DeepCopyMap(req.Annotations),
}, nil
} else if isDebugPod {
return &pluginapi.ResourceAllocationResponse{
PodUid: req.PodUid,
PodNamespace: req.PodNamespace,
PodName: req.PodName,
ContainerName: req.ContainerName,
ContainerType: req.ContainerType,
ContainerIndex: req.ContainerIndex,
PodRole: req.PodRole,
PodType: req.PodType,
ResourceName: string(v1.ResourceMemory),
AllocationResult: &pluginapi.ResourceAllocation{
ResourceAllocation: map[string]*pluginapi.ResourceAllocationInfo{
string(v1.ResourceMemory): {
// return ResourceAllocation with empty OciPropertyName, AllocatedQuantity, AllocationResult for containers in debug pod,
// it won't influence oci spec properties of the container
IsNodeResource: false,
IsScalarResource: true,
},
},
},
Labels: general.DeepCopyMap(req.Labels),
Annotations: general.DeepCopyMap(req.Annotations),
}, nil
}
startTime := time.Now()
p.Lock()
defer func() {
// calls sys-advisor to inform the latest container
if p.enableMemoryAdvisor && respErr == nil && req.ContainerType != pluginapi.ContainerType_INIT {
_, err := p.advisorClient.AddContainer(ctx, &advisorsvc.ContainerMetadata{
PodUid: req.PodUid,
PodNamespace: req.PodNamespace,
PodName: req.PodName,
ContainerName: req.ContainerName,
ContainerType: req.ContainerType,
ContainerIndex: req.ContainerIndex,
Labels: maputil.CopySS(req.Labels),
Annotations: maputil.CopySS(req.Annotations),
QosLevel: qosLevel,
RequestQuantity: uint64(reqInt),
})
if err != nil {
resp = nil
respErr = fmt.Errorf("add container to qos aware server failed with error: %v", err)
_ = p.removeContainer(req.PodUid, req.ContainerName, false)
}
} else if respErr != nil {
inplaceUpdateResizing := util.PodInplaceUpdateResizing(req)
if !inplaceUpdateResizing {
_ = p.removeContainer(req.PodUid, req.ContainerName, false)
}