1717package opts
1818
1919import (
20+ "context"
2021 "testing"
2122
23+ "github.com/containerd/containerd/v2/core/mount"
24+ ostesting "github.com/containerd/containerd/v2/pkg/os/testing"
25+ runtimespec "github.com/opencontainers/runtime-spec/specs-go"
2226 "github.com/stretchr/testify/assert"
2327 "github.com/stretchr/testify/require"
28+ runtime "k8s.io/cri-api/pkg/apis/runtime/v1"
2429)
2530
2631func TestMergeGids (t * testing.T ) {
@@ -45,3 +50,73 @@ func TestRestrictOOMScoreAdj(t *testing.T) {
4550 require .NoError (t , err )
4651 assert .Equal (t , got , current + 1 )
4752}
53+
54+ func TestWithMountsCgroupNamespaceOptions (t * testing.T ) {
55+ tests := []struct {
56+ name string
57+ hasCgroupNS bool
58+ hostMountOpts string
59+ expectedOpts []string
60+ }{
61+ {
62+ name : "has cgroupns, should use default options" ,
63+ hasCgroupNS : true ,
64+ hostMountOpts : "rw,nosuid,nodev,noexec,relatime,nsdelegate,memory_recursiveprot" ,
65+ expectedOpts : []string {"nosuid" , "noexec" , "nodev" , "relatime" , "ro" },
66+ },
67+ {
68+ name : "no cgroupns, with host options present" ,
69+ hasCgroupNS : false ,
70+ hostMountOpts : "rw,nosuid,nodev,noexec,relatime,nsdelegate,memory_recursiveprot" ,
71+ expectedOpts : []string {"nosuid" , "noexec" , "nodev" , "relatime" , "ro" , "nsdelegate" , "memory_recursiveprot" },
72+ },
73+ {
74+ name : "no cgroupns, with host missing nsdelegate" ,
75+ hasCgroupNS : false ,
76+ hostMountOpts : "rw,nosuid,nodev,noexec,relatime,memory_recursiveprot" ,
77+ expectedOpts : []string {"nosuid" , "noexec" , "nodev" , "relatime" , "ro" , "memory_recursiveprot" },
78+ },
79+ {
80+ name : "no cgroupns, with host missing all extra options" ,
81+ hasCgroupNS : false ,
82+ hostMountOpts : "rw,nosuid,nodev,noexec,relatime" ,
83+ expectedOpts : []string {"nosuid" , "noexec" , "nodev" , "relatime" , "ro" },
84+ },
85+ }
86+
87+ for _ , tt := range tests {
88+ t .Run (tt .name , func (t * testing.T ) {
89+ fakeOS := ostesting .NewFakeOS ()
90+ fakeOS .LookupMountFn = func (path string ) (mount.Info , error ) {
91+ if path == "/sys/fs/cgroup" {
92+ return mount.Info {VFSOptions : tt .hostMountOpts }, nil
93+ }
94+ return mount.Info {}, nil
95+ }
96+
97+ config := & runtime.ContainerConfig {
98+ Linux : & runtime.LinuxContainerConfig {},
99+ }
100+
101+ spec := & runtimespec.Spec {}
102+ if tt .hasCgroupNS {
103+ spec .Linux = & runtimespec.Linux {Namespaces : []runtimespec.LinuxNamespace {{Type : runtimespec .CgroupNamespace }}}
104+ }
105+
106+ opt := withMounts (fakeOS , config , nil , "" , nil , false )
107+ err := opt (context .Background (), nil , nil , spec )
108+ require .NoError (t , err )
109+
110+ var cgroupMount * runtimespec.Mount
111+ for _ , m := range spec .Mounts {
112+ if m .Destination == "/sys/fs/cgroup" {
113+ cgroupMount = & m
114+ break
115+ }
116+ }
117+
118+ require .NotNil (t , cgroupMount )
119+ assert .ElementsMatch (t , tt .expectedOpts , cgroupMount .Options )
120+ })
121+ }
122+ }
0 commit comments