helpers_test.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package dockershim
  14. import (
  15. "fmt"
  16. "testing"
  17. dockertypes "github.com/docker/docker/api/types"
  18. dockernat "github.com/docker/go-connections/nat"
  19. "github.com/stretchr/testify/assert"
  20. "github.com/stretchr/testify/require"
  21. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  22. "k8s.io/kubernetes/pkg/kubelet/dockershim/libdocker"
  23. "k8s.io/kubernetes/pkg/security/apparmor"
  24. )
  25. func TestLabelsAndAnnotationsRoundTrip(t *testing.T) {
  26. expectedLabels := map[string]string{"foo.123.abc": "baz", "bar.456.xyz": "qwe"}
  27. expectedAnnotations := map[string]string{"uio.ert": "dfs", "jkl": "asd"}
  28. // Merge labels and annotations into docker labels.
  29. dockerLabels := makeLabels(expectedLabels, expectedAnnotations)
  30. // Extract labels and annotations from docker labels.
  31. actualLabels, actualAnnotations := extractLabels(dockerLabels)
  32. assert.Equal(t, expectedLabels, actualLabels)
  33. assert.Equal(t, expectedAnnotations, actualAnnotations)
  34. }
  35. // TestGetApparmorSecurityOpts tests the logic of generating container apparmor options from sandbox annotations.
  36. func TestGetApparmorSecurityOpts(t *testing.T) {
  37. makeConfig := func(profile string) *runtimeapi.LinuxContainerSecurityContext {
  38. return &runtimeapi.LinuxContainerSecurityContext{
  39. ApparmorProfile: profile,
  40. }
  41. }
  42. tests := []struct {
  43. msg string
  44. config *runtimeapi.LinuxContainerSecurityContext
  45. expectedOpts []string
  46. }{{
  47. msg: "No AppArmor options",
  48. config: makeConfig(""),
  49. expectedOpts: nil,
  50. }, {
  51. msg: "AppArmor runtime/default",
  52. config: makeConfig("runtime/default"),
  53. expectedOpts: []string{},
  54. }, {
  55. msg: "AppArmor local profile",
  56. config: makeConfig(apparmor.ProfileNamePrefix + "foo"),
  57. expectedOpts: []string{"apparmor=foo"},
  58. }}
  59. for i, test := range tests {
  60. opts, err := getApparmorSecurityOpts(test.config, '=')
  61. assert.NoError(t, err, "TestCase[%d]: %s", i, test.msg)
  62. assert.Len(t, opts, len(test.expectedOpts), "TestCase[%d]: %s", i, test.msg)
  63. for _, opt := range test.expectedOpts {
  64. assert.Contains(t, opts, opt, "TestCase[%d]: %s", i, test.msg)
  65. }
  66. }
  67. }
  68. // TestGetUserFromImageUser tests the logic of getting image uid or user name of image user.
  69. func TestGetUserFromImageUser(t *testing.T) {
  70. newI64 := func(i int64) *int64 { return &i }
  71. for c, test := range map[string]struct {
  72. user string
  73. uid *int64
  74. name string
  75. }{
  76. "no gid": {
  77. user: "0",
  78. uid: newI64(0),
  79. },
  80. "uid/gid": {
  81. user: "0:1",
  82. uid: newI64(0),
  83. },
  84. "empty user": {
  85. user: "",
  86. },
  87. "multiple spearators": {
  88. user: "1:2:3",
  89. uid: newI64(1),
  90. },
  91. "root username": {
  92. user: "root:root",
  93. name: "root",
  94. },
  95. "username": {
  96. user: "test:test",
  97. name: "test",
  98. },
  99. } {
  100. t.Logf("TestCase - %q", c)
  101. actualUID, actualName := getUserFromImageUser(test.user)
  102. assert.Equal(t, test.uid, actualUID)
  103. assert.Equal(t, test.name, actualName)
  104. }
  105. }
  106. func TestParsingCreationConflictError(t *testing.T) {
  107. // Expected error message from docker.
  108. msgs := []string{
  109. "Conflict. The name \"/k8s_POD_pfpod_e2e-tests-port-forwarding-dlxt2_81a3469e-99e1-11e6-89f2-42010af00002_0\" is already in use by container 24666ab8c814d16f986449e504ea0159468ddf8da01897144a770f66dce0e14e. You have to remove (or rename) that container to be able to reuse that name.",
  110. "Conflict. The name \"/k8s_POD_pfpod_e2e-tests-port-forwarding-dlxt2_81a3469e-99e1-11e6-89f2-42010af00002_0\" is already in use by container \"24666ab8c814d16f986449e504ea0159468ddf8da01897144a770f66dce0e14e\". You have to remove (or rename) that container to be able to reuse that name.",
  111. }
  112. for _, msg := range msgs {
  113. matches := conflictRE.FindStringSubmatch(msg)
  114. require.Len(t, matches, 2)
  115. require.Equal(t, matches[1], "24666ab8c814d16f986449e504ea0159468ddf8da01897144a770f66dce0e14e")
  116. }
  117. }
  118. func TestEnsureSandboxImageExists(t *testing.T) {
  119. sandboxImage := "gcr.io/test/image"
  120. authConfig := dockertypes.AuthConfig{Username: "user", Password: "pass"}
  121. for desc, test := range map[string]struct {
  122. injectImage bool
  123. imgNeedsAuth bool
  124. injectErr error
  125. calls []string
  126. err bool
  127. configJSON string
  128. }{
  129. "should not pull image when it already exists": {
  130. injectImage: true,
  131. injectErr: nil,
  132. calls: []string{"inspect_image"},
  133. },
  134. "should pull image when it doesn't exist": {
  135. injectImage: false,
  136. injectErr: libdocker.ImageNotFoundError{ID: "image_id"},
  137. calls: []string{"inspect_image", "pull"},
  138. },
  139. "should return error when inspect image fails": {
  140. injectImage: false,
  141. injectErr: fmt.Errorf("arbitrary error"),
  142. calls: []string{"inspect_image"},
  143. err: true,
  144. },
  145. "should return error when image pull needs private auth, but none provided": {
  146. injectImage: true,
  147. imgNeedsAuth: true,
  148. injectErr: libdocker.ImageNotFoundError{ID: "image_id"},
  149. calls: []string{"inspect_image", "pull"},
  150. err: true,
  151. },
  152. } {
  153. t.Logf("TestCase: %q", desc)
  154. _, fakeDocker, _ := newTestDockerService()
  155. if test.injectImage {
  156. images := []dockertypes.ImageSummary{{ID: sandboxImage}}
  157. fakeDocker.InjectImages(images)
  158. if test.imgNeedsAuth {
  159. fakeDocker.MakeImagesPrivate(images, authConfig)
  160. }
  161. }
  162. fakeDocker.InjectError("inspect_image", test.injectErr)
  163. err := ensureSandboxImageExists(fakeDocker, sandboxImage)
  164. assert.NoError(t, fakeDocker.AssertCalls(test.calls))
  165. assert.Equal(t, test.err, err != nil)
  166. }
  167. }
  168. func TestMakePortsAndBindings(t *testing.T) {
  169. for desc, test := range map[string]struct {
  170. pm []*runtimeapi.PortMapping
  171. exposedPorts dockernat.PortSet
  172. portmappings map[dockernat.Port][]dockernat.PortBinding
  173. }{
  174. "no port mapping": {
  175. pm: nil,
  176. exposedPorts: map[dockernat.Port]struct{}{},
  177. portmappings: map[dockernat.Port][]dockernat.PortBinding{},
  178. },
  179. "tcp port mapping": {
  180. pm: []*runtimeapi.PortMapping{
  181. {
  182. Protocol: runtimeapi.Protocol_TCP,
  183. ContainerPort: 80,
  184. HostPort: 80,
  185. },
  186. },
  187. exposedPorts: map[dockernat.Port]struct{}{
  188. "80/tcp": {},
  189. },
  190. portmappings: map[dockernat.Port][]dockernat.PortBinding{
  191. "80/tcp": {
  192. {
  193. HostPort: "80",
  194. },
  195. },
  196. },
  197. },
  198. "udp port mapping": {
  199. pm: []*runtimeapi.PortMapping{
  200. {
  201. Protocol: runtimeapi.Protocol_UDP,
  202. ContainerPort: 80,
  203. HostPort: 80,
  204. },
  205. },
  206. exposedPorts: map[dockernat.Port]struct{}{
  207. "80/udp": {},
  208. },
  209. portmappings: map[dockernat.Port][]dockernat.PortBinding{
  210. "80/udp": {
  211. {
  212. HostPort: "80",
  213. },
  214. },
  215. },
  216. },
  217. "multiple port mappings": {
  218. pm: []*runtimeapi.PortMapping{
  219. {
  220. Protocol: runtimeapi.Protocol_TCP,
  221. ContainerPort: 80,
  222. HostPort: 80,
  223. },
  224. {
  225. Protocol: runtimeapi.Protocol_TCP,
  226. ContainerPort: 80,
  227. HostPort: 81,
  228. },
  229. },
  230. exposedPorts: map[dockernat.Port]struct{}{
  231. "80/tcp": {},
  232. },
  233. portmappings: map[dockernat.Port][]dockernat.PortBinding{
  234. "80/tcp": {
  235. {
  236. HostPort: "80",
  237. },
  238. {
  239. HostPort: "81",
  240. },
  241. },
  242. },
  243. },
  244. } {
  245. t.Logf("TestCase: %s", desc)
  246. actualExposedPorts, actualPortMappings := makePortsAndBindings(test.pm)
  247. assert.Equal(t, test.exposedPorts, actualExposedPorts)
  248. assert.Equal(t, test.portmappings, actualPortMappings)
  249. }
  250. }
  251. func TestGenerateMountBindings(t *testing.T) {
  252. mounts := []*runtimeapi.Mount{
  253. // everything default
  254. {
  255. HostPath: "/mnt/1",
  256. ContainerPath: "/var/lib/mysql/1",
  257. },
  258. // readOnly
  259. {
  260. HostPath: "/mnt/2",
  261. ContainerPath: "/var/lib/mysql/2",
  262. Readonly: true,
  263. },
  264. // SELinux
  265. {
  266. HostPath: "/mnt/3",
  267. ContainerPath: "/var/lib/mysql/3",
  268. SelinuxRelabel: true,
  269. },
  270. // Propagation private
  271. {
  272. HostPath: "/mnt/4",
  273. ContainerPath: "/var/lib/mysql/4",
  274. Propagation: runtimeapi.MountPropagation_PROPAGATION_PRIVATE,
  275. },
  276. // Propagation rslave
  277. {
  278. HostPath: "/mnt/5",
  279. ContainerPath: "/var/lib/mysql/5",
  280. Propagation: runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER,
  281. },
  282. // Propagation rshared
  283. {
  284. HostPath: "/mnt/6",
  285. ContainerPath: "/var/lib/mysql/6",
  286. Propagation: runtimeapi.MountPropagation_PROPAGATION_BIDIRECTIONAL,
  287. },
  288. // Propagation unknown (falls back to private)
  289. {
  290. HostPath: "/mnt/7",
  291. ContainerPath: "/var/lib/mysql/7",
  292. Propagation: runtimeapi.MountPropagation(42),
  293. },
  294. // Everything
  295. {
  296. HostPath: "/mnt/8",
  297. ContainerPath: "/var/lib/mysql/8",
  298. Readonly: true,
  299. SelinuxRelabel: true,
  300. Propagation: runtimeapi.MountPropagation_PROPAGATION_BIDIRECTIONAL,
  301. },
  302. }
  303. expectedResult := []string{
  304. "/mnt/1:/var/lib/mysql/1",
  305. "/mnt/2:/var/lib/mysql/2:ro",
  306. "/mnt/3:/var/lib/mysql/3:Z",
  307. "/mnt/4:/var/lib/mysql/4",
  308. "/mnt/5:/var/lib/mysql/5:rslave",
  309. "/mnt/6:/var/lib/mysql/6:rshared",
  310. "/mnt/7:/var/lib/mysql/7",
  311. "/mnt/8:/var/lib/mysql/8:ro,Z,rshared",
  312. }
  313. result := generateMountBindings(mounts)
  314. assert.Equal(t, expectedResult, result)
  315. }