Skip to content

Commit

Permalink
feat(fragmem): unified solution for memory compaction
Browse files Browse the repository at this point in the history
Signed-off-by: Robin Lu <robin.lu@bytedance.com>
  • Loading branch information
lubinszARM committed Aug 8, 2024
1 parent 7d9189e commit 847528c
Show file tree
Hide file tree
Showing 8 changed files with 564 additions and 0 deletions.
18 changes: 18 additions & 0 deletions cmd/katalyst-agent/app/options/qrm/memory_plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ type MemoryOptions struct {
OOMPriorityPinnedMapAbsPath string

SockMemOptions
FragMemOptions
}

type SockMemOptions struct {
Expand All @@ -43,6 +44,13 @@ type SockMemOptions struct {
SetCgroupTCPMemRatio int
}

type FragMemOptions struct {
EnableSettingFragMem bool
// SetMemFragScoreAsync sets the threashold of frag score for async memory compaction.
// The async compaction behavior will be triggered while exceeding this score.
SetMemFragScoreAsync int
}

func NewMemoryOptions() *MemoryOptions {
return &MemoryOptions{
PolicyName: "dynamic",
Expand All @@ -56,6 +64,10 @@ func NewMemoryOptions() *MemoryOptions {
SetGlobalTCPMemRatio: 20, // default: 20% * {host total memory}
SetCgroupTCPMemRatio: 100, // default: 100% * {cgroup memory}
},
FragMemOptions: FragMemOptions{
EnableSettingFragMem: false,
SetMemFragScoreAsync: 800,
},
}
}

Expand Down Expand Up @@ -84,6 +96,10 @@ func (o *MemoryOptions) AddFlags(fss *cliflag.NamedFlagSets) {
o.SetGlobalTCPMemRatio, "limit global max tcp memory usage")
fs.IntVar(&o.SetCgroupTCPMemRatio, "qrm-memory-cgroup-tcpmem-ratio",
o.SetCgroupTCPMemRatio, "limit cgroup max tcp memory usage")
fs.BoolVar(&o.EnableSettingFragMem, "enable-setting-mem-compaction",
o.EnableSettingFragMem, "if set true, we will enable memory compaction related features")
fs.IntVar(&o.SetMemFragScoreAsync, "qrm-memory-frag-score-async",
o.SetMemFragScoreAsync, "set the threshold of frag score for async memory compaction")
}

func (o *MemoryOptions) ApplyTo(conf *qrmconfig.MemoryQRMPluginConfig) error {
Expand All @@ -98,5 +114,7 @@ func (o *MemoryOptions) ApplyTo(conf *qrmconfig.MemoryQRMPluginConfig) error {
conf.EnableSettingSockMem = o.EnableSettingSockMem
conf.SetGlobalTCPMemRatio = o.SetGlobalTCPMemRatio
conf.SetCgroupTCPMemRatio = o.SetCgroupTCPMemRatio
conf.EnableSettingFragMem = o.EnableSettingFragMem
conf.SetMemFragScoreAsync = o.SetMemFragScoreAsync
return nil
}
12 changes: 12 additions & 0 deletions pkg/agent/qrm-plugins/memory/dynamicpolicy/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import (
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/memory/dynamicpolicy/memoryadvisor"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/memory/dynamicpolicy/oom"
"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/sockmem"
"github.com/kubewharf/katalyst-core/pkg/agent/qrm-plugins/util"
"github.com/kubewharf/katalyst-core/pkg/agent/utilcomponent/periodicalhandler"
Expand Down Expand Up @@ -146,6 +147,7 @@ type DynamicPolicy struct {

enableSettingMemoryMigrate bool
enableSettingSockMem bool
enableSettingFragMem bool
enableMemoryAdvisor bool
memoryAdvisorSocketAbsPath string
memoryPluginSocketAbsPath string
Expand Down Expand Up @@ -211,6 +213,7 @@ func NewDynamicPolicy(agentCtx *agent.GenericContext, conf *config.Configuration
defaultAsyncLimitedWorkers: asyncworker.NewAsyncLimitedWorkers(memoryPluginAsyncWorkersName, defaultAsyncWorkLimit, wrappedEmitter),
enableSettingMemoryMigrate: conf.EnableSettingMemoryMigrate,
enableSettingSockMem: conf.EnableSettingSockMem,
enableSettingFragMem: conf.EnableSettingFragMem,
enableMemoryAdvisor: conf.EnableMemoryAdvisor,
memoryAdvisorSocketAbsPath: conf.MemoryAdvisorSocketAbsPath,
memoryPluginSocketAbsPath: conf.MemoryPluginSocketAbsPath,
Expand Down Expand Up @@ -367,6 +370,15 @@ func (p *DynamicPolicy) Start() (err error) {
}
}

if p.enableSettingFragMem {
general.Infof("setFragMem enabled")
err := periodicalhandler.RegisterPeriodicalHandler(qrm.QRMMemoryPluginPeriodicalHandlerGroupName,
fragmem.EnableSetFragMemPeriodicalHandlerName, fragmem.SetMemCompact, 1500*time.Second)
if err != nil {
general.Infof("setFragMem failed, err=%v", err)
}
}

go wait.Until(func() {
periodicalhandler.ReadyToStartHandlersByGroup(qrm.QRMMemoryPluginPeriodicalHandlerGroupName)
}, 5*time.Second, p.stopCh)
Expand Down
36 changes: 36 additions & 0 deletions pkg/agent/qrm-plugins/memory/handlers/fragmem/const.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
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 fragmem

const EnableSetFragMemPeriodicalHandlerName = "SetFragMem"

const (
// Constants for fragmem related kernel features
hostFragScoreFile = "/sys/kernel/debug/extfrag/unusable_index"
hostCompactProactivenessFile = "/proc/sys/vm/compaction_proactiveness"
hostMemNodePath = "/sys/devices/system/node/node"

fragScoreMin = 500.0
fragScoreMax = 900.0
minFragScoreGap = 50
delayCompactTimes = 10
minHostLoad = 120
)

const (
metricNameMemoryCompaction = "async_handler_memory_compaction"
)
138 changes: 138 additions & 0 deletions pkg/agent/qrm-plugins/memory/handlers/fragmem/fragmem_linux.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
//go:build linux
// +build linux

/*
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 fragmem

import (
"sync"

coreconfig "github.com/kubewharf/katalyst-core/pkg/config"
dynamicconfig "github.com/kubewharf/katalyst-core/pkg/config/agent/dynamic"
"github.com/kubewharf/katalyst-core/pkg/consts"
"github.com/kubewharf/katalyst-core/pkg/metaserver"
"github.com/kubewharf/katalyst-core/pkg/metaserver/agent/metric/helper"
"github.com/kubewharf/katalyst-core/pkg/metrics"
"github.com/kubewharf/katalyst-core/pkg/util/general"
)

var (
delayTimes int
mu sync.RWMutex
)

// SetDelayValue sets the value of the global delayTimes
func SetDelayTimes(value int) {
mu.Lock()
defer mu.Unlock()
delayTimes = value
}

// GetDelayValue returns the value of the global delayTimes
func GetDelayTimes() int {
mu.RLock()
defer mu.RUnlock()
return delayTimes
}

/* SetMemCompact is the unified solution for memory compaction.
* it includes 3 parts:
* 1, set the threshold of fragmentation score that triggers synchronous memory compaction in the memory slow path.
* 2, if has proactive compaction feature, then set the threshold of fragmentation score for asynchronous memory compaction through compaction_proactiveness.
* 3, if no proactive compaction feature, then use the async threshold of fragmentation score to trigger manually memory compaction.
*/
func SetMemCompact(conf *coreconfig.Configuration,
_ interface{}, _ *dynamicconfig.DynamicAgentConfiguration,
emitter metrics.MetricEmitter, metaServer *metaserver.MetaServer,
) {
general.Infof("called")

if conf == nil {
general.Errorf("nil extraConf")
return
} else if emitter == nil {
general.Errorf("nil emitter")
return
} else if metaServer == nil {
general.Errorf("nil metaServer")
return
}

delay := GetDelayTimes()
if delay > 0 {
general.Infof("No memory fragmentation in this node, skip this scanning cycle, delay=%d", delay)
delay--
SetDelayTimes(delay)
return
}

// EnableSettingMemCompact featuregate.
if !conf.EnableSettingFragMem {
general.Infof("EnableSettingFragMem disabled")
return
}

// Step1, check proactive compaction.
// if proactive compaction feature enabled, then return.
if !checkCompactionProactivenessDisabled(hostCompactProactivenessFile) {
general.Infof("proactive compaction enabled, then return")
return
}

// Step2, if proactive compaction feature was disabled, then a user space solution for memory compaction will be triggered.
// Step2.0, avoid too much system pressure.
load, err := helper.GetNodeMetricWithTime(metaServer.MetricsFetcher, emitter, consts.MetricLoad5MinSystem)
if err != nil {
return
}
numCPU := metaServer.CPUTopology.NumCPUs
loadPerCPU := int(load.Value) * 100 / numCPU
general.Infof("Host load info: load:%v, numCPU:%v, loadPerCPU:%v", load.Value, numCPU, loadPerCPU)
if loadPerCPU > minHostLoad {
return
}
// Step2.1, get the fragmentation score.
asyncWatermark := uint64(general.Clamp(float64(conf.SetMemFragScoreAsync), fragScoreMin, fragScoreMax))
fragScores, err := GetNumaFragScore(hostFragScoreFile)
if err != nil {
general.Errorf("gatherFragScore failed:%v.\n", err)
return
}
// Step2.2, async user space memory compaction will be trigger while exceeding the conf.SetMemFragScoreAsync.
for _, scoreInfo := range fragScores {
general.Infof("Node fragScore info: node:%d, fragScore:%d, fragScoreGate:%d", scoreInfo.Node, scoreInfo.Score, asyncWatermark)
if scoreInfo.Score < int(asyncWatermark) {
continue
}
nodeId := scoreInfo.Node

_ = emitter.StoreInt64(metricNameMemoryCompaction, 1, metrics.MetricTypeNameRaw)
setHostMemCompact(nodeId)

newScores, err := GetNumaFragScore(hostFragScoreFile)
if err != nil {
return
}
general.Infof("Node fragScore new info: node:%d, fragScore:%d", scoreInfo.Node, newScores[nodeId].Score)
// compare the new and old average fragmentation core to avoid ineffective compaction.
if newScores[nodeId].Score >= int(asyncWatermark-minFragScoreGap) {
general.Infof("No memory fragmentation in this node, increase the scanning cycle")
SetDelayTimes(delayCompactTimes)
}
}
}
Loading

0 comments on commit 847528c

Please sign in to comment.