Skip to content

Commit 2e7ce7f

Browse files
committed
cg2: Add ability to set type
This adds in some simple functionality to be able to set the cgroup type (threaded or domain). Signed-off-by: Danny Canter <danny@dcantah.dev>
1 parent 157c4da commit 2e7ce7f

2 files changed

Lines changed: 48 additions & 0 deletions

File tree

cgroup2/manager.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ const (
4343
subtreeControl = "cgroup.subtree_control"
4444
controllersFile = "cgroup.controllers"
4545
killFile = "cgroup.kill"
46+
typeFile = "cgroup.type"
4647
defaultCgroup2Path = "/sys/fs/cgroup"
4748
defaultSlice = "system.slice"
4849
)
@@ -236,6 +237,35 @@ func setResources(path string, resources *Resources) error {
236237
return nil
237238
}
238239

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

cgroup2/manager_test.go

Lines changed: 18 additions & 0 deletions
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)