Skip to content

Commit 3e97504

Browse files
authored
Merge pull request #270 from dcantah/cg-type
cg2: Add ability to set type
2 parents 8c10986 + 2e7ce7f commit 3e97504

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

cgroup2/manager.go

+30
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ const (
4242
subtreeControl = "cgroup.subtree_control"
4343
controllersFile = "cgroup.controllers"
4444
killFile = "cgroup.kill"
45+
typeFile = "cgroup.type"
4546
defaultCgroup2Path = "/sys/fs/cgroup"
4647
defaultSlice = "system.slice"
4748
)
@@ -235,6 +236,35 @@ func setResources(path string, resources *Resources) error {
235236
return nil
236237
}
237238

239+
// CgroupType represents the types a cgroup can be.
240+
type CgroupType string
241+
242+
const (
243+
Domain CgroupType = "domain"
244+
Threaded CgroupType = "threaded"
245+
)
246+
247+
func (c *Manager) GetType() (CgroupType, error) {
248+
val, err := os.ReadFile(filepath.Join(c.path, typeFile))
249+
if err != nil {
250+
return "", err
251+
}
252+
trimmed := strings.TrimSpace(string(val))
253+
return CgroupType(trimmed), nil
254+
}
255+
256+
func (c *Manager) SetType(cgType CgroupType) error {
257+
// NOTE: We could abort if cgType != Threaded here as currently
258+
// it's not possible to revert back to domain, but not sure
259+
// it's worth being that opinionated, especially if that may
260+
// ever change.
261+
v := Value{
262+
filename: typeFile,
263+
value: string(cgType),
264+
}
265+
return writeValues(c.path, []Value{v})
266+
}
267+
238268
func (c *Manager) RootControllers() ([]string, error) {
239269
b, err := os.ReadFile(filepath.Join(c.unifiedMountpoint, controllersFile))
240270
if err != nil {

cgroup2/manager_test.go

+18
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525

2626
"github.com/opencontainers/runtime-spec/specs-go"
2727
"github.com/stretchr/testify/assert"
28+
"github.com/stretchr/testify/require"
2829
"go.uber.org/goleak"
2930
)
3031

@@ -221,3 +222,20 @@ func TestMoveTo(t *testing.T) {
221222
return
222223
}
223224
}
225+
226+
func TestCgroupType(t *testing.T) {
227+
checkCgroupMode(t)
228+
manager, err := NewManager(defaultCgroup2Path, "/test1", ToResources(&specs.LinuxResources{}))
229+
require.NoError(t, err)
230+
231+
cgType, err := manager.GetType()
232+
require.NoError(t, err)
233+
require.Equal(t, cgType, Domain)
234+
235+
// Swap to threaded
236+
require.NoError(t, manager.SetType(Threaded))
237+
238+
cgType, err = manager.GetType()
239+
require.NoError(t, err)
240+
require.Equal(t, cgType, Threaded)
241+
}

0 commit comments

Comments
 (0)