Skip to content

Commit 3bb9611

Browse files
committed
Add memory policy support
Implement support for Linux memory policy in OCI spec PR: opencontainers/runtime-spec#1282 TODO: - remove the replace from go.mod Signed-off-by: Antti Kervinen <antti.kervinen@intel.com>
1 parent 2b96aa2 commit 3bb9611

File tree

16 files changed

+477
-4
lines changed

16 files changed

+477
-4
lines changed

features.go

+4
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ var featuresCommand = cli.Command{
5858
IntelRdt: &features.IntelRdt{
5959
Enabled: &t,
6060
},
61+
MemoryPolicy: &features.MemoryPolicy{
62+
Modes: specconv.KnownMemoryPolicyModes(),
63+
Flags: specconv.KnownMemoryPolicyFlags(),
64+
},
6165
MountExtensions: &features.MountExtensions{
6266
IDMap: &features.IDMap{
6367
Enabled: &t,

go.mod

+2
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,5 @@ require (
3939
github.com/russross/blackfriday/v2 v2.1.0 // indirect
4040
github.com/vishvananda/netns v0.0.4 // indirect
4141
)
42+
43+
replace github.com/opencontainers/runtime-spec => github.com/askervin/runtime-spec v1.0.3-0.20250423073229-57c949588e88

go.sum

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
2+
github.com/askervin/runtime-spec v1.0.3-0.20250423073229-57c949588e88 h1:Rs1b8ssNo+RX0wq0ROF+OGpQ4aks2gmi9906a5tNBZk=
3+
github.com/askervin/runtime-spec v1.0.3-0.20250423073229-57c949588e88/go.mod h1:0ccwhiCQXxLwvWvVsdVdxTe+IFfXyJTjr/wNue5fNJY=
24
github.com/checkpoint-restore/go-criu/v7 v7.2.0 h1:qGiWA4App1gGlEfIJ68WR9jbezV9J7yZdjzglezcqKo=
35
github.com/checkpoint-restore/go-criu/v7 v7.2.0/go.mod h1:u0LCWLg0w4yqqu14aXhiB4YD3a1qd8EcCEg7vda5dwo=
46
github.com/cilium/ebpf v0.17.3 h1:FnP4r16PWYSE4ux6zN+//jMcW4nMVRvuTLVTvCjyyjg=
@@ -47,8 +49,6 @@ github.com/mrunalp/fileutils v0.5.1 h1:F+S7ZlNKnrwHfSwdlgNSkKo67ReVf8o9fel6C3dkm
4749
github.com/mrunalp/fileutils v0.5.1/go.mod h1:M1WthSahJixYnrXQl/DFQuteStB1weuxD2QJNHXfbSQ=
4850
github.com/opencontainers/cgroups v0.0.1 h1:MXjMkkFpKv6kpuirUa4USFBas573sSAY082B4CiHEVA=
4951
github.com/opencontainers/cgroups v0.0.1/go.mod h1:s8lktyhlGUqM7OSRL5P7eAW6Wb+kWPNvt4qvVfzA5vs=
50-
github.com/opencontainers/runtime-spec v1.2.1 h1:S4k4ryNgEpxW1dzyqffOmhI1BHYcjzU8lpJfSlR0xww=
51-
github.com/opencontainers/runtime-spec v1.2.1/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0=
5252
github.com/opencontainers/selinux v1.12.0 h1:6n5JV4Cf+4y0KNXW48TLj5DwfXpvWlxXplUkdTrmPb8=
5353
github.com/opencontainers/selinux v1.12.0/go.mod h1:BTPX+bjVbWGXw7ZZWUbdENt8w0htPSrlgOOysQaU62U=
5454
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=

libcontainer/configs/config.go

+3
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,9 @@ type Config struct {
210210
// to limit the resources (e.g., L3 cache, memory bandwidth) the container has available
211211
IntelRdt *IntelRdt `json:"intel_rdt,omitempty"`
212212

213+
// MemoryPolicy specifies NUMA memory policy for the container.
214+
MemoryPolicy *LinuxMemoryPolicy `json:"memoryPolicy,omitempty"`
215+
213216
// RootlessEUID is set when the runc was launched with non-zero EUID.
214217
// Note that RootlessEUID is set to false when launched with EUID=0 in userns.
215218
// When RootlessEUID is set, runc creates a new userns for the container.

libcontainer/configs/memorypolicy.go

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package configs
2+
3+
// LinuxMemoryPolicy contains memory policy configuration.
4+
type LinuxMemoryPolicy struct {
5+
// Mode combines memory poliy mode and mode flags. Refer to
6+
// set_mempolicy() documentation for details.
7+
Mode uint
8+
// Contains NUMA nodes to which the mode applies.
9+
Nodes []int
10+
}

libcontainer/init_linux.go

+4
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,10 @@ func setupIOPriority(config *initConfig) error {
659659
return nil
660660
}
661661

662+
func setupMemoryPolicy(config *configs.Config) error {
663+
return system.SetMempolicy(config.MemoryPolicy.Mode, config.MemoryPolicy.Nodes)
664+
}
665+
662666
func setupPersonality(config *configs.Config) error {
663667
return system.SetLinuxPersonality(config.Personality.Domain)
664668
}

libcontainer/setns_init_linux.go

+5
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,11 @@ func (l *linuxSetnsInit) Init() error {
110110
if err := apparmor.ApplyProfile(l.config.AppArmorProfile); err != nil {
111111
return err
112112
}
113+
if l.config.Config.MemoryPolicy != nil {
114+
if err := setupMemoryPolicy(l.config.Config); err != nil {
115+
return err
116+
}
117+
}
113118
if l.config.Config.Personality != nil {
114119
if err := setupPersonality(l.config.Config); err != nil {
115120
return err

libcontainer/specconv/spec_linux.go

+113
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"os"
1010
"path/filepath"
1111
"sort"
12+
"strconv"
1213
"strings"
1314
"sync"
1415
"time"
@@ -41,6 +42,15 @@ var (
4142
flag int
4243
}
4344
complexFlags map[string]func(*configs.Mount)
45+
mpolModeMap map[specs.MemoryPolicyModeType]uint
46+
mpolModeFMap map[specs.MemoryPolicyFlagType]uint
47+
)
48+
49+
const (
50+
// maxNumaNode for a sensibility check to user-provided node
51+
// values and ranges. It does not reflect currently onlined nodes.
52+
// set_mempolicy() accepts call-time non-existent nodes, so do we.
53+
maxNumaNode = 1023
4454
)
4555

4656
func initMaps() {
@@ -148,6 +158,22 @@ func initMaps() {
148158
m.IDMapping.Recursive = true
149159
},
150160
}
161+
162+
mpolModeMap = map[specs.MemoryPolicyModeType]uint{
163+
specs.MpolDefault: 0,
164+
specs.MpolPreferred: 1,
165+
specs.MpolBind: 2,
166+
specs.MpolInterleave: 3,
167+
specs.MpolLocal: 4,
168+
specs.MpolPreferredMany: 5,
169+
specs.MpolWeightedInterleave: 6,
170+
}
171+
172+
mpolModeFMap = map[specs.MemoryPolicyFlagType]uint{
173+
specs.MpolFStaticNodes: 1 << 15,
174+
specs.MpolFRelativeNodes: 1 << 14,
175+
specs.MpolFNumaBalancing: 1 << 13,
176+
}
151177
})
152178
}
153179

@@ -184,6 +210,27 @@ func KnownMountOptions() []string {
184210
return res
185211
}
186212

213+
func KnownMemoryPolicyModes() []string {
214+
initMaps()
215+
var res []string
216+
for k := range mpolModeMap {
217+
res = append(res, string(k))
218+
}
219+
sort.Strings(res)
220+
return res
221+
}
222+
223+
func KnownMemoryPolicyFlags() []string {
224+
initMaps()
225+
var res []string
226+
for k := range mpolModeFMap {
227+
res = append(res, string(k))
228+
}
229+
sort.Strings(res)
230+
return res
231+
}
232+
233+
187234
// AllowedDevices is the set of devices which are automatically included for
188235
// all containers.
189236
//
@@ -467,6 +514,28 @@ func CreateLibcontainerConfig(opts *CreateOpts) (*configs.Config, error) {
467514
MemBwSchema: spec.Linux.IntelRdt.MemBwSchema,
468515
}
469516
}
517+
if spec.Linux.MemoryPolicy != nil &&
518+
(spec.Linux.MemoryPolicy.Mode != "" ||
519+
spec.Linux.MemoryPolicy.Nodes != "" ||
520+
len(spec.Linux.MemoryPolicy.Flags) > 0) {
521+
var ok bool
522+
specMp := spec.Linux.MemoryPolicy
523+
confMp := &configs.LinuxMemoryPolicy{}
524+
if confMp.Mode, ok = mpolModeMap[specMp.Mode]; !ok {
525+
return nil, fmt.Errorf("invalid memory policy mode %q", specMp.Mode)
526+
}
527+
if confMp.Nodes, err = parseListSet(specMp.Nodes, 0, maxNumaNode); err != nil {
528+
return nil, fmt.Errorf("invalid memory policy nodes %q: %w", specMp.Nodes, err)
529+
}
530+
for _, specFlag := range specMp.Flags {
531+
confModeFlag, ok := mpolModeFMap[specFlag]
532+
if !ok {
533+
return nil, fmt.Errorf("invalid memory policy flag %q", specFlag)
534+
}
535+
confMp.Mode |= confModeFlag
536+
}
537+
config.MemoryPolicy = confMp
538+
}
470539
if spec.Linux.Personality != nil {
471540
if len(spec.Linux.Personality.Flags) > 0 {
472541
logrus.Warnf("ignoring unsupported personality flags: %+v because personality flag has not supported at this time", spec.Linux.Personality.Flags)
@@ -1127,6 +1196,50 @@ func parseMountOptions(options []string) *configs.Mount {
11271196
return &m
11281197
}
11291198

1199+
// parseListSet parses "list set" syntax ("0,61-63,2") into a list ([0, 61, 62, 63, 2]).
1200+
func parseListSet(listSet string, minValue, maxValue int) ([]int, error) {
1201+
var result []int
1202+
parts := strings.Split(listSet, ",")
1203+
for _, part := range parts {
1204+
switch {
1205+
case part == "":
1206+
continue
1207+
case strings.Contains(part, "-"):
1208+
rangeParts := strings.Split(part, "-")
1209+
if len(rangeParts) != 2 {
1210+
return nil, fmt.Errorf("invalid range: %s", part)
1211+
}
1212+
start, err := strconv.Atoi(rangeParts[0])
1213+
if err != nil {
1214+
return nil, err
1215+
}
1216+
end, err := strconv.Atoi(rangeParts[1])
1217+
if err != nil {
1218+
return nil, err
1219+
}
1220+
if start > end {
1221+
return nil, fmt.Errorf("invalid range %s: start > end", part)
1222+
}
1223+
if start < minValue || end > maxValue {
1224+
return nil, fmt.Errorf("invalid range %s: out of range %d-%d", part, minValue, maxValue)
1225+
}
1226+
for i := start; i <= end; i++ {
1227+
result = append(result, i)
1228+
}
1229+
default:
1230+
num, err := strconv.Atoi(part)
1231+
if err != nil {
1232+
return nil, err
1233+
}
1234+
if num < minValue || num > maxValue {
1235+
return nil, fmt.Errorf("invalid value %d: out of range %d-%d", num, minValue, maxValue)
1236+
}
1237+
result = append(result, num)
1238+
}
1239+
}
1240+
return result, nil
1241+
}
1242+
11301243
func SetupSeccomp(config *specs.LinuxSeccomp) (*configs.Seccomp, error) {
11311244
if config == nil {
11321245
return nil, nil

libcontainer/specconv/spec_linux_test.go

+105
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,111 @@ func TestSetupSeccomp(t *testing.T) {
338338
}
339339
}
340340

341+
func TestParseListSet(t *testing.T) {
342+
testCases := []struct {
343+
name string
344+
listSet string
345+
minValue, maxValue int
346+
expectedInts []int
347+
expectedErr string
348+
}{
349+
{
350+
name: "empty string",
351+
listSet: "",
352+
},
353+
{
354+
name: "single value at max",
355+
listSet: "42",
356+
expectedInts: []int{42},
357+
maxValue: 42,
358+
},
359+
{
360+
name: "full range from min to max",
361+
listSet: "0-7",
362+
expectedInts: []int{0, 1, 2, 3, 4, 5, 6, 7},
363+
maxValue: 7,
364+
},
365+
{
366+
name: "comma separated values",
367+
listSet: "1,3",
368+
expectedInts: []int{1, 3},
369+
maxValue: 5,
370+
},
371+
{
372+
name: "comma separated values and overlapping ranges",
373+
listSet: "3-5,1,4-6",
374+
expectedInts: []int{3, 4, 5, 1, 4, 5, 6},
375+
maxValue: 10,
376+
},
377+
{
378+
name: "empty ranges, single number ranges",
379+
listSet: ",2,,4-4,",
380+
expectedInts: []int{2, 4},
381+
maxValue: 4,
382+
},
383+
{
384+
name: "value out of range",
385+
listSet: "2-4,0",
386+
minValue: 1,
387+
maxValue: 4,
388+
expectedErr: "invalid value",
389+
},
390+
{
391+
name: "end of range out of range",
392+
listSet: "2-4,0",
393+
maxValue: 3,
394+
expectedErr: "invalid range",
395+
},
396+
{
397+
name: "start is greater than end",
398+
listSet: "4-3,0",
399+
maxValue: 1024,
400+
expectedErr: "invalid range",
401+
},
402+
{
403+
name: "syntax error in value",
404+
listSet: "a",
405+
maxValue: 1024,
406+
expectedErr: "invalid syntax",
407+
},
408+
{
409+
name: "syntax error at range start",
410+
listSet: "0,?-4",
411+
maxValue: 1024,
412+
expectedErr: "invalid syntax",
413+
},
414+
{
415+
name: "syntax error at range end",
416+
listSet: "0,4-,2",
417+
maxValue: 1024,
418+
expectedErr: "invalid syntax",
419+
},
420+
}
421+
for _, tc := range testCases {
422+
t.Run(tc.name, func(t *testing.T) {
423+
obsInts, obsErr := parseListSet(tc.listSet, tc.minValue, tc.maxValue)
424+
if len(obsInts) != len(tc.expectedInts) {
425+
t.Errorf("Expected %d ints, got %d (%v)", len(tc.expectedInts), len(obsInts), obsInts)
426+
}
427+
for i, v := range obsInts {
428+
if len(tc.expectedInts) > i && v != tc.expectedInts[i] {
429+
t.Errorf("Expected at index %d value %d, got %d", i, tc.expectedInts[i], v)
430+
}
431+
}
432+
switch {
433+
case tc.expectedErr == "" && obsErr != nil:
434+
t.Errorf("Expected no error, got %v", obsErr)
435+
case tc.expectedErr != "" && obsErr == nil:
436+
t.Errorf("Expected error %v, got nil", tc.expectedErr)
437+
case tc.expectedErr != "" && obsErr != nil:
438+
if !strings.Contains(obsErr.Error(), tc.expectedErr) {
439+
t.Errorf("Expected error containing %q, got %v", tc.expectedErr, obsErr)
440+
}
441+
}
442+
})
443+
}
444+
}
445+
341446
func TestLinuxCgroupWithMemoryResource(t *testing.T) {
342447
cgroupsPath := "/user/cgroups/path/id"
343448

libcontainer/standard_init_linux.go

+7
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,13 @@ func (l *linuxStandardInit) Init() error {
238238
}
239239
}
240240

241+
// Set memory policy if specified.
242+
if l.config.Config.MemoryPolicy != nil {
243+
if err := setupMemoryPolicy(l.config.Config); err != nil {
244+
return err
245+
}
246+
}
247+
241248
// Set personality if specified.
242249
if l.config.Config.Personality != nil {
243250
if err := setupPersonality(l.config.Config); err != nil {

libcontainer/system/linux.go

+25
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,31 @@ fallback:
151151
return io.Copy(dst, src)
152152
}
153153

154+
func bitmaskFromInts(bits []int) []uint64 {
155+
maxBit := 0
156+
for _, bit := range bits {
157+
if bit > maxBit {
158+
maxBit = bit
159+
}
160+
}
161+
mask := make([]uint64, (maxBit/64)+1)
162+
for _, bit := range bits {
163+
mask[bit/64] |= (1 << (bit % 64))
164+
}
165+
return mask
166+
}
167+
168+
// SetMempolicy sets the NUMA memory policy. For more information see the set_mempolicy syscall documentation.
169+
func SetMempolicy(mode uint, nodes []int) error {
170+
nodemask := bitmaskFromInts(nodes)
171+
nodemaskPtr := unsafe.Pointer(&nodemask[0])
172+
_, _, errno := unix.Syscall(unix.SYS_SET_MEMPOLICY, uintptr(mode), uintptr(nodemaskPtr), uintptr(len(nodemask)*64))
173+
if errno != 0 {
174+
return &os.SyscallError{Syscall: "set_mempolicy", Err: errno}
175+
}
176+
return nil
177+
}
178+
154179
// SetLinuxPersonality sets the Linux execution personality. For more information see the personality syscall documentation.
155180
// checkout getLinuxPersonalityFromStr() from libcontainer/specconv/spec_linux.go for type conversion.
156181
func SetLinuxPersonality(personality int) error {

0 commit comments

Comments
 (0)