kuberuntime_container_linux_test.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. // +build linux
  2. /*
  3. Copyright 2018 The Kubernetes Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package kuberuntime
  15. import (
  16. "reflect"
  17. "testing"
  18. cgroupfs "github.com/opencontainers/runc/libcontainer/cgroups/fs"
  19. "github.com/stretchr/testify/assert"
  20. v1 "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  23. "k8s.io/apimachinery/pkg/api/resource"
  24. )
  25. func makeExpectedConfig(m *kubeGenericRuntimeManager, pod *v1.Pod, containerIndex int) *runtimeapi.ContainerConfig {
  26. container := &pod.Spec.Containers[containerIndex]
  27. podIP := ""
  28. restartCount := 0
  29. opts, _, _ := m.runtimeHelper.GenerateRunContainerOptions(pod, container, podIP, []string{podIP})
  30. containerLogsPath := buildContainerLogsPath(container.Name, restartCount)
  31. restartCountUint32 := uint32(restartCount)
  32. envs := make([]*runtimeapi.KeyValue, len(opts.Envs))
  33. expectedConfig := &runtimeapi.ContainerConfig{
  34. Metadata: &runtimeapi.ContainerMetadata{
  35. Name: container.Name,
  36. Attempt: restartCountUint32,
  37. },
  38. Image: &runtimeapi.ImageSpec{Image: container.Image},
  39. Command: container.Command,
  40. Args: []string(nil),
  41. WorkingDir: container.WorkingDir,
  42. Labels: newContainerLabels(container, pod),
  43. Annotations: newContainerAnnotations(container, pod, restartCount, opts),
  44. Devices: makeDevices(opts),
  45. Mounts: m.makeMounts(opts, container),
  46. LogPath: containerLogsPath,
  47. Stdin: container.Stdin,
  48. StdinOnce: container.StdinOnce,
  49. Tty: container.TTY,
  50. Linux: m.generateLinuxContainerConfig(container, pod, new(int64), ""),
  51. Envs: envs,
  52. }
  53. return expectedConfig
  54. }
  55. func TestGenerateContainerConfig(t *testing.T) {
  56. _, imageService, m, err := createTestRuntimeManager()
  57. assert.NoError(t, err)
  58. runAsUser := int64(1000)
  59. runAsGroup := int64(2000)
  60. pod := &v1.Pod{
  61. ObjectMeta: metav1.ObjectMeta{
  62. UID: "12345678",
  63. Name: "bar",
  64. Namespace: "new",
  65. },
  66. Spec: v1.PodSpec{
  67. Containers: []v1.Container{
  68. {
  69. Name: "foo",
  70. Image: "busybox",
  71. ImagePullPolicy: v1.PullIfNotPresent,
  72. Command: []string{"testCommand"},
  73. WorkingDir: "testWorkingDir",
  74. SecurityContext: &v1.SecurityContext{
  75. RunAsUser: &runAsUser,
  76. RunAsGroup: &runAsGroup,
  77. },
  78. },
  79. },
  80. },
  81. }
  82. expectedConfig := makeExpectedConfig(m, pod, 0)
  83. containerConfig, _, err := m.generateContainerConfig(&pod.Spec.Containers[0], pod, 0, "", pod.Spec.Containers[0].Image, []string{})
  84. assert.NoError(t, err)
  85. assert.Equal(t, expectedConfig, containerConfig, "generate container config for kubelet runtime v1.")
  86. assert.Equal(t, runAsUser, containerConfig.GetLinux().GetSecurityContext().GetRunAsUser().GetValue(), "RunAsUser should be set")
  87. assert.Equal(t, runAsGroup, containerConfig.GetLinux().GetSecurityContext().GetRunAsGroup().GetValue(), "RunAsGroup should be set")
  88. runAsRoot := int64(0)
  89. runAsNonRootTrue := true
  90. podWithContainerSecurityContext := &v1.Pod{
  91. ObjectMeta: metav1.ObjectMeta{
  92. UID: "12345678",
  93. Name: "bar",
  94. Namespace: "new",
  95. },
  96. Spec: v1.PodSpec{
  97. Containers: []v1.Container{
  98. {
  99. Name: "foo",
  100. Image: "busybox",
  101. ImagePullPolicy: v1.PullIfNotPresent,
  102. Command: []string{"testCommand"},
  103. WorkingDir: "testWorkingDir",
  104. SecurityContext: &v1.SecurityContext{
  105. RunAsNonRoot: &runAsNonRootTrue,
  106. RunAsUser: &runAsRoot,
  107. },
  108. },
  109. },
  110. },
  111. }
  112. _, _, err = m.generateContainerConfig(&podWithContainerSecurityContext.Spec.Containers[0], podWithContainerSecurityContext, 0, "", podWithContainerSecurityContext.Spec.Containers[0].Image, []string{})
  113. assert.Error(t, err)
  114. imageID, _ := imageService.PullImage(&runtimeapi.ImageSpec{Image: "busybox"}, nil, nil)
  115. image, _ := imageService.ImageStatus(&runtimeapi.ImageSpec{Image: imageID})
  116. image.Uid = nil
  117. image.Username = "test"
  118. podWithContainerSecurityContext.Spec.Containers[0].SecurityContext.RunAsUser = nil
  119. podWithContainerSecurityContext.Spec.Containers[0].SecurityContext.RunAsNonRoot = &runAsNonRootTrue
  120. _, _, err = m.generateContainerConfig(&podWithContainerSecurityContext.Spec.Containers[0], podWithContainerSecurityContext, 0, "", podWithContainerSecurityContext.Spec.Containers[0].Image, []string{})
  121. assert.Error(t, err, "RunAsNonRoot should fail for non-numeric username")
  122. }
  123. func TestGetHugepageLimitsFromResources(t *testing.T) {
  124. var baseHugepage []*runtimeapi.HugepageLimit
  125. // For each page size, limit to 0.
  126. for _, pageSize := range cgroupfs.HugePageSizes {
  127. baseHugepage = append(baseHugepage, &runtimeapi.HugepageLimit{
  128. PageSize: pageSize,
  129. Limit: uint64(0),
  130. })
  131. }
  132. tests := []struct {
  133. name string
  134. resources v1.ResourceRequirements
  135. expected []*runtimeapi.HugepageLimit
  136. }{
  137. {
  138. name: "Success2MB",
  139. resources: v1.ResourceRequirements{
  140. Limits: v1.ResourceList{
  141. "hugepages-2Mi": resource.MustParse("2Mi"),
  142. },
  143. },
  144. expected: []*runtimeapi.HugepageLimit{
  145. {
  146. PageSize: "2MB",
  147. Limit: 2097152,
  148. },
  149. },
  150. },
  151. {
  152. name: "Success1GB",
  153. resources: v1.ResourceRequirements{
  154. Limits: v1.ResourceList{
  155. "hugepages-1Gi": resource.MustParse("2Gi"),
  156. },
  157. },
  158. expected: []*runtimeapi.HugepageLimit{
  159. {
  160. PageSize: "1GB",
  161. Limit: 2147483648,
  162. },
  163. },
  164. },
  165. {
  166. name: "Skip2MB",
  167. resources: v1.ResourceRequirements{
  168. Limits: v1.ResourceList{
  169. "hugepages-2MB": resource.MustParse("2Mi"),
  170. },
  171. },
  172. expected: []*runtimeapi.HugepageLimit{
  173. {
  174. PageSize: "2MB",
  175. Limit: 0,
  176. },
  177. },
  178. },
  179. {
  180. name: "Skip1GB",
  181. resources: v1.ResourceRequirements{
  182. Limits: v1.ResourceList{
  183. "hugepages-1GB": resource.MustParse("2Gi"),
  184. },
  185. },
  186. expected: []*runtimeapi.HugepageLimit{
  187. {
  188. PageSize: "1GB",
  189. Limit: 0,
  190. },
  191. },
  192. },
  193. {
  194. name: "Success2MBand1GB",
  195. resources: v1.ResourceRequirements{
  196. Limits: v1.ResourceList{
  197. v1.ResourceName(v1.ResourceCPU): resource.MustParse("0"),
  198. "hugepages-2Mi": resource.MustParse("2Mi"),
  199. "hugepages-1Gi": resource.MustParse("2Gi"),
  200. },
  201. },
  202. expected: []*runtimeapi.HugepageLimit{
  203. {
  204. PageSize: "2MB",
  205. Limit: 2097152,
  206. },
  207. {
  208. PageSize: "1GB",
  209. Limit: 2147483648,
  210. },
  211. },
  212. },
  213. {
  214. name: "Skip2MBand1GB",
  215. resources: v1.ResourceRequirements{
  216. Limits: v1.ResourceList{
  217. v1.ResourceName(v1.ResourceCPU): resource.MustParse("0"),
  218. "hugepages-2MB": resource.MustParse("2Mi"),
  219. "hugepages-1GB": resource.MustParse("2Gi"),
  220. },
  221. },
  222. expected: []*runtimeapi.HugepageLimit{
  223. {
  224. PageSize: "2MB",
  225. Limit: 0,
  226. },
  227. {
  228. PageSize: "1GB",
  229. Limit: 0,
  230. },
  231. },
  232. },
  233. }
  234. for _, test := range tests {
  235. // Validate if machine supports hugepage size that used in test case.
  236. machineHugepageSupport := true
  237. for _, hugepageLimit := range test.expected {
  238. hugepageSupport := false
  239. for _, pageSize := range cgroupfs.HugePageSizes {
  240. if pageSize == hugepageLimit.PageSize {
  241. hugepageSupport = true
  242. break
  243. }
  244. }
  245. if !hugepageSupport {
  246. machineHugepageSupport = false
  247. break
  248. }
  249. }
  250. // Case of machine can't support hugepage size
  251. if !machineHugepageSupport {
  252. continue
  253. }
  254. expectedHugepages := baseHugepage
  255. for _, hugepage := range test.expected {
  256. for _, expectedHugepage := range expectedHugepages {
  257. if expectedHugepage.PageSize == hugepage.PageSize {
  258. expectedHugepage.Limit = hugepage.Limit
  259. }
  260. }
  261. }
  262. results := GetHugepageLimitsFromResources(test.resources)
  263. if !reflect.DeepEqual(expectedHugepages, results) {
  264. t.Errorf("%s test failed. Expected %v but got %v", test.name, expectedHugepages, results)
  265. }
  266. for _, hugepage := range baseHugepage {
  267. hugepage.Limit = uint64(0)
  268. }
  269. }
  270. }