helpers_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. "bytes"
  16. "errors"
  17. "fmt"
  18. "sync"
  19. "testing"
  20. dockertypes "github.com/docker/docker/api/types"
  21. dockernat "github.com/docker/go-connections/nat"
  22. "github.com/stretchr/testify/assert"
  23. "github.com/stretchr/testify/require"
  24. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  25. "k8s.io/kubernetes/pkg/kubelet/dockershim/libdocker"
  26. "k8s.io/kubernetes/pkg/security/apparmor"
  27. )
  28. func TestLabelsAndAnnotationsRoundTrip(t *testing.T) {
  29. expectedLabels := map[string]string{"foo.123.abc": "baz", "bar.456.xyz": "qwe"}
  30. expectedAnnotations := map[string]string{"uio.ert": "dfs", "jkl": "asd"}
  31. // Merge labels and annotations into docker labels.
  32. dockerLabels := makeLabels(expectedLabels, expectedAnnotations)
  33. // Extract labels and annotations from docker labels.
  34. actualLabels, actualAnnotations := extractLabels(dockerLabels)
  35. assert.Equal(t, expectedLabels, actualLabels)
  36. assert.Equal(t, expectedAnnotations, actualAnnotations)
  37. }
  38. // TestGetApparmorSecurityOpts tests the logic of generating container apparmor options from sandbox annotations.
  39. func TestGetApparmorSecurityOpts(t *testing.T) {
  40. makeConfig := func(profile string) *runtimeapi.LinuxContainerSecurityContext {
  41. return &runtimeapi.LinuxContainerSecurityContext{
  42. ApparmorProfile: profile,
  43. }
  44. }
  45. tests := []struct {
  46. msg string
  47. config *runtimeapi.LinuxContainerSecurityContext
  48. expectedOpts []string
  49. }{{
  50. msg: "No AppArmor options",
  51. config: makeConfig(""),
  52. expectedOpts: nil,
  53. }, {
  54. msg: "AppArmor runtime/default",
  55. config: makeConfig("runtime/default"),
  56. expectedOpts: []string{},
  57. }, {
  58. msg: "AppArmor local profile",
  59. config: makeConfig(apparmor.ProfileNamePrefix + "foo"),
  60. expectedOpts: []string{"apparmor=foo"},
  61. }}
  62. for i, test := range tests {
  63. opts, err := getApparmorSecurityOpts(test.config, '=')
  64. assert.NoError(t, err, "TestCase[%d]: %s", i, test.msg)
  65. assert.Len(t, opts, len(test.expectedOpts), "TestCase[%d]: %s", i, test.msg)
  66. for _, opt := range test.expectedOpts {
  67. assert.Contains(t, opts, opt, "TestCase[%d]: %s", i, test.msg)
  68. }
  69. }
  70. }
  71. // TestGetUserFromImageUser tests the logic of getting image uid or user name of image user.
  72. func TestGetUserFromImageUser(t *testing.T) {
  73. newI64 := func(i int64) *int64 { return &i }
  74. for c, test := range map[string]struct {
  75. user string
  76. uid *int64
  77. name string
  78. }{
  79. "no gid": {
  80. user: "0",
  81. uid: newI64(0),
  82. },
  83. "uid/gid": {
  84. user: "0:1",
  85. uid: newI64(0),
  86. },
  87. "empty user": {
  88. user: "",
  89. },
  90. "multiple spearators": {
  91. user: "1:2:3",
  92. uid: newI64(1),
  93. },
  94. "root username": {
  95. user: "root:root",
  96. name: "root",
  97. },
  98. "username": {
  99. user: "test:test",
  100. name: "test",
  101. },
  102. } {
  103. t.Logf("TestCase - %q", c)
  104. actualUID, actualName := getUserFromImageUser(test.user)
  105. assert.Equal(t, test.uid, actualUID)
  106. assert.Equal(t, test.name, actualName)
  107. }
  108. }
  109. func TestParsingCreationConflictError(t *testing.T) {
  110. // Expected error message from docker.
  111. msgs := []string{
  112. "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.",
  113. "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.",
  114. }
  115. for _, msg := range msgs {
  116. matches := conflictRE.FindStringSubmatch(msg)
  117. require.Len(t, matches, 2)
  118. require.Equal(t, matches[1], "24666ab8c814d16f986449e504ea0159468ddf8da01897144a770f66dce0e14e")
  119. }
  120. }
  121. func TestEnsureSandboxImageExists(t *testing.T) {
  122. sandboxImage := "gcr.io/test/image"
  123. authConfig := dockertypes.AuthConfig{Username: "user", Password: "pass"}
  124. for desc, test := range map[string]struct {
  125. injectImage bool
  126. imgNeedsAuth bool
  127. injectErr error
  128. calls []string
  129. err bool
  130. configJSON string
  131. }{
  132. "should not pull image when it already exists": {
  133. injectImage: true,
  134. injectErr: nil,
  135. calls: []string{"inspect_image"},
  136. },
  137. "should pull image when it doesn't exist": {
  138. injectImage: false,
  139. injectErr: libdocker.ImageNotFoundError{ID: "image_id"},
  140. calls: []string{"inspect_image", "pull"},
  141. },
  142. "should return error when inspect image fails": {
  143. injectImage: false,
  144. injectErr: fmt.Errorf("arbitrary error"),
  145. calls: []string{"inspect_image"},
  146. err: true,
  147. },
  148. "should return error when image pull needs private auth, but none provided": {
  149. injectImage: true,
  150. imgNeedsAuth: true,
  151. injectErr: libdocker.ImageNotFoundError{ID: "image_id"},
  152. calls: []string{"inspect_image", "pull"},
  153. err: true,
  154. },
  155. } {
  156. t.Logf("TestCase: %q", desc)
  157. _, fakeDocker, _ := newTestDockerService()
  158. if test.injectImage {
  159. images := []dockertypes.ImageSummary{{ID: sandboxImage}}
  160. fakeDocker.InjectImages(images)
  161. if test.imgNeedsAuth {
  162. fakeDocker.MakeImagesPrivate(images, authConfig)
  163. }
  164. }
  165. fakeDocker.InjectError("inspect_image", test.injectErr)
  166. err := ensureSandboxImageExists(fakeDocker, sandboxImage)
  167. assert.NoError(t, fakeDocker.AssertCalls(test.calls))
  168. assert.Equal(t, test.err, err != nil)
  169. }
  170. }
  171. func TestMakePortsAndBindings(t *testing.T) {
  172. for desc, test := range map[string]struct {
  173. pm []*runtimeapi.PortMapping
  174. exposedPorts dockernat.PortSet
  175. portmappings map[dockernat.Port][]dockernat.PortBinding
  176. }{
  177. "no port mapping": {
  178. pm: nil,
  179. exposedPorts: map[dockernat.Port]struct{}{},
  180. portmappings: map[dockernat.Port][]dockernat.PortBinding{},
  181. },
  182. "tcp port mapping": {
  183. pm: []*runtimeapi.PortMapping{
  184. {
  185. Protocol: runtimeapi.Protocol_TCP,
  186. ContainerPort: 80,
  187. HostPort: 80,
  188. },
  189. },
  190. exposedPorts: map[dockernat.Port]struct{}{
  191. "80/tcp": {},
  192. },
  193. portmappings: map[dockernat.Port][]dockernat.PortBinding{
  194. "80/tcp": {
  195. {
  196. HostPort: "80",
  197. },
  198. },
  199. },
  200. },
  201. "udp port mapping": {
  202. pm: []*runtimeapi.PortMapping{
  203. {
  204. Protocol: runtimeapi.Protocol_UDP,
  205. ContainerPort: 80,
  206. HostPort: 80,
  207. },
  208. },
  209. exposedPorts: map[dockernat.Port]struct{}{
  210. "80/udp": {},
  211. },
  212. portmappings: map[dockernat.Port][]dockernat.PortBinding{
  213. "80/udp": {
  214. {
  215. HostPort: "80",
  216. },
  217. },
  218. },
  219. },
  220. "multiple port mappings": {
  221. pm: []*runtimeapi.PortMapping{
  222. {
  223. Protocol: runtimeapi.Protocol_TCP,
  224. ContainerPort: 80,
  225. HostPort: 80,
  226. },
  227. {
  228. Protocol: runtimeapi.Protocol_TCP,
  229. ContainerPort: 80,
  230. HostPort: 81,
  231. },
  232. },
  233. exposedPorts: map[dockernat.Port]struct{}{
  234. "80/tcp": {},
  235. },
  236. portmappings: map[dockernat.Port][]dockernat.PortBinding{
  237. "80/tcp": {
  238. {
  239. HostPort: "80",
  240. },
  241. {
  242. HostPort: "81",
  243. },
  244. },
  245. },
  246. },
  247. } {
  248. t.Logf("TestCase: %s", desc)
  249. actualExposedPorts, actualPortMappings := makePortsAndBindings(test.pm)
  250. assert.Equal(t, test.exposedPorts, actualExposedPorts)
  251. assert.Equal(t, test.portmappings, actualPortMappings)
  252. }
  253. }
  254. func TestGenerateMountBindings(t *testing.T) {
  255. mounts := []*runtimeapi.Mount{
  256. // everything default
  257. {
  258. HostPath: "/mnt/1",
  259. ContainerPath: "/var/lib/mysql/1",
  260. },
  261. // readOnly
  262. {
  263. HostPath: "/mnt/2",
  264. ContainerPath: "/var/lib/mysql/2",
  265. Readonly: true,
  266. },
  267. // SELinux
  268. {
  269. HostPath: "/mnt/3",
  270. ContainerPath: "/var/lib/mysql/3",
  271. SelinuxRelabel: true,
  272. },
  273. // Propagation private
  274. {
  275. HostPath: "/mnt/4",
  276. ContainerPath: "/var/lib/mysql/4",
  277. Propagation: runtimeapi.MountPropagation_PROPAGATION_PRIVATE,
  278. },
  279. // Propagation rslave
  280. {
  281. HostPath: "/mnt/5",
  282. ContainerPath: "/var/lib/mysql/5",
  283. Propagation: runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER,
  284. },
  285. // Propagation rshared
  286. {
  287. HostPath: "/mnt/6",
  288. ContainerPath: "/var/lib/mysql/6",
  289. Propagation: runtimeapi.MountPropagation_PROPAGATION_BIDIRECTIONAL,
  290. },
  291. // Propagation unknown (falls back to private)
  292. {
  293. HostPath: "/mnt/7",
  294. ContainerPath: "/var/lib/mysql/7",
  295. Propagation: runtimeapi.MountPropagation(42),
  296. },
  297. // Everything
  298. {
  299. HostPath: "/mnt/8",
  300. ContainerPath: "/var/lib/mysql/8",
  301. Readonly: true,
  302. SelinuxRelabel: true,
  303. Propagation: runtimeapi.MountPropagation_PROPAGATION_BIDIRECTIONAL,
  304. },
  305. }
  306. expectedResult := []string{
  307. "/mnt/1:/var/lib/mysql/1",
  308. "/mnt/2:/var/lib/mysql/2:ro",
  309. "/mnt/3:/var/lib/mysql/3:Z",
  310. "/mnt/4:/var/lib/mysql/4",
  311. "/mnt/5:/var/lib/mysql/5:rslave",
  312. "/mnt/6:/var/lib/mysql/6:rshared",
  313. "/mnt/7:/var/lib/mysql/7",
  314. "/mnt/8:/var/lib/mysql/8:ro,Z,rshared",
  315. }
  316. result := generateMountBindings(mounts)
  317. assert.Equal(t, expectedResult, result)
  318. }
  319. func TestLimitedWriter(t *testing.T) {
  320. max := func(x, y int64) int64 {
  321. if x > y {
  322. return x
  323. }
  324. return y
  325. }
  326. for name, tc := range map[string]struct {
  327. w bytes.Buffer
  328. toWrite string
  329. limit int64
  330. wants string
  331. wantsErr error
  332. }{
  333. "nil": {},
  334. "neg": {
  335. toWrite: "a",
  336. wantsErr: errMaximumWrite,
  337. limit: -1,
  338. },
  339. "1byte-over": {
  340. toWrite: "a",
  341. wantsErr: errMaximumWrite,
  342. },
  343. "1byte-maxed": {
  344. toWrite: "a",
  345. wants: "a",
  346. limit: 1,
  347. },
  348. "1byte-under": {
  349. toWrite: "a",
  350. wants: "a",
  351. limit: 2,
  352. },
  353. "6byte-over": {
  354. toWrite: "foobar",
  355. wants: "foo",
  356. limit: 3,
  357. wantsErr: errMaximumWrite,
  358. },
  359. "6byte-maxed": {
  360. toWrite: "foobar",
  361. wants: "foobar",
  362. limit: 6,
  363. },
  364. "6byte-under": {
  365. toWrite: "foobar",
  366. wants: "foobar",
  367. limit: 20,
  368. },
  369. } {
  370. t.Run(name, func(t *testing.T) {
  371. limit := tc.limit
  372. w := sharedLimitWriter(&tc.w, &limit)
  373. n, err := w.Write([]byte(tc.toWrite))
  374. if int64(n) > max(0, tc.limit) {
  375. t.Fatalf("bytes written (%d) exceeds limit (%d)", n, tc.limit)
  376. }
  377. if (err != nil) != (tc.wantsErr != nil) {
  378. if err != nil {
  379. t.Fatal("unexpected error:", err)
  380. }
  381. t.Fatal("expected error:", err)
  382. }
  383. if err != nil {
  384. if !errors.Is(err, tc.wantsErr) {
  385. t.Fatal("expected error: ", tc.wantsErr, " instead of: ", err)
  386. }
  387. if !errors.Is(err, errMaximumWrite) {
  388. return
  389. }
  390. // check contents for errMaximumWrite
  391. }
  392. if s := tc.w.String(); s != tc.wants {
  393. t.Fatalf("expected %q instead of %q", tc.wants, s)
  394. }
  395. })
  396. }
  397. // test concurrency. run this test a bunch of times to attempt to flush
  398. // out any data races or concurrency issues.
  399. for i := 0; i < 1000; i++ {
  400. var (
  401. b1, b2 bytes.Buffer
  402. limit = int64(10)
  403. w1 = sharedLimitWriter(&b1, &limit)
  404. w2 = sharedLimitWriter(&b2, &limit)
  405. ch = make(chan struct{})
  406. wg sync.WaitGroup
  407. )
  408. wg.Add(2)
  409. go func() { defer wg.Done(); <-ch; w1.Write([]byte("hello")) }()
  410. go func() { defer wg.Done(); <-ch; w2.Write([]byte("world")) }()
  411. close(ch)
  412. wg.Wait()
  413. if limit != 0 {
  414. t.Fatalf("expected max limit to be reached, instead of %d", limit)
  415. }
  416. }
  417. }