create_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. package container // import "github.com/docker/docker/integration/container"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strconv"
  7. "testing"
  8. "time"
  9. "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/api/types/container"
  11. containertypes "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/api/types/network"
  13. "github.com/docker/docker/api/types/versions"
  14. "github.com/docker/docker/client"
  15. "github.com/docker/docker/errdefs"
  16. ctr "github.com/docker/docker/integration/internal/container"
  17. "github.com/docker/docker/oci"
  18. "github.com/docker/docker/testutil/request"
  19. specs "github.com/opencontainers/image-spec/specs-go/v1"
  20. "gotest.tools/v3/assert"
  21. is "gotest.tools/v3/assert/cmp"
  22. "gotest.tools/v3/poll"
  23. "gotest.tools/v3/skip"
  24. )
  25. func TestCreateFailsWhenIdentifierDoesNotExist(t *testing.T) {
  26. defer setupTest(t)()
  27. client := testEnv.APIClient()
  28. testCases := []struct {
  29. doc string
  30. image string
  31. expectedError string
  32. }{
  33. {
  34. doc: "image and tag",
  35. image: "test456:v1",
  36. expectedError: "No such image: test456:v1",
  37. },
  38. {
  39. doc: "image no tag",
  40. image: "test456",
  41. expectedError: "No such image: test456",
  42. },
  43. {
  44. doc: "digest",
  45. image: "sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa",
  46. expectedError: "No such image: sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa",
  47. },
  48. }
  49. for _, tc := range testCases {
  50. tc := tc
  51. t.Run(tc.doc, func(t *testing.T) {
  52. t.Parallel()
  53. _, err := client.ContainerCreate(context.Background(),
  54. &container.Config{Image: tc.image},
  55. &container.HostConfig{},
  56. &network.NetworkingConfig{},
  57. nil,
  58. "",
  59. )
  60. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  61. assert.Check(t, errdefs.IsNotFound(err))
  62. })
  63. }
  64. }
  65. // TestCreateLinkToNonExistingContainer verifies that linking to a non-existing
  66. // container returns an "invalid parameter" (400) status, and not the underlying
  67. // "non exists" (404).
  68. func TestCreateLinkToNonExistingContainer(t *testing.T) {
  69. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "legacy links are not supported on windows")
  70. defer setupTest(t)()
  71. c := testEnv.APIClient()
  72. _, err := c.ContainerCreate(context.Background(),
  73. &container.Config{
  74. Image: "busybox",
  75. },
  76. &container.HostConfig{
  77. Links: []string{"no-such-container"},
  78. },
  79. &network.NetworkingConfig{},
  80. nil,
  81. "",
  82. )
  83. assert.Check(t, is.ErrorContains(err, "could not get container for no-such-container"))
  84. assert.Check(t, errdefs.IsInvalidParameter(err))
  85. }
  86. func TestCreateWithInvalidEnv(t *testing.T) {
  87. defer setupTest(t)()
  88. client := testEnv.APIClient()
  89. testCases := []struct {
  90. env string
  91. expectedError string
  92. }{
  93. {
  94. env: "",
  95. expectedError: "invalid environment variable:",
  96. },
  97. {
  98. env: "=",
  99. expectedError: "invalid environment variable: =",
  100. },
  101. {
  102. env: "=foo",
  103. expectedError: "invalid environment variable: =foo",
  104. },
  105. }
  106. for index, tc := range testCases {
  107. tc := tc
  108. t.Run(strconv.Itoa(index), func(t *testing.T) {
  109. t.Parallel()
  110. _, err := client.ContainerCreate(context.Background(),
  111. &container.Config{
  112. Image: "busybox",
  113. Env: []string{tc.env},
  114. },
  115. &container.HostConfig{},
  116. &network.NetworkingConfig{},
  117. nil,
  118. "",
  119. )
  120. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  121. assert.Check(t, errdefs.IsInvalidParameter(err))
  122. })
  123. }
  124. }
  125. // Test case for #30166 (target was not validated)
  126. func TestCreateTmpfsMountsTarget(t *testing.T) {
  127. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  128. defer setupTest(t)()
  129. client := testEnv.APIClient()
  130. testCases := []struct {
  131. target string
  132. expectedError string
  133. }{
  134. {
  135. target: ".",
  136. expectedError: "mount path must be absolute",
  137. },
  138. {
  139. target: "foo",
  140. expectedError: "mount path must be absolute",
  141. },
  142. {
  143. target: "/",
  144. expectedError: "destination can't be '/'",
  145. },
  146. {
  147. target: "//",
  148. expectedError: "destination can't be '/'",
  149. },
  150. }
  151. for _, tc := range testCases {
  152. _, err := client.ContainerCreate(context.Background(),
  153. &container.Config{
  154. Image: "busybox",
  155. },
  156. &container.HostConfig{
  157. Tmpfs: map[string]string{tc.target: ""},
  158. },
  159. &network.NetworkingConfig{},
  160. nil,
  161. "",
  162. )
  163. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  164. assert.Check(t, errdefs.IsInvalidParameter(err))
  165. }
  166. }
  167. func TestCreateWithCustomMaskedPaths(t *testing.T) {
  168. skip.If(t, testEnv.DaemonInfo.OSType != "linux")
  169. defer setupTest(t)()
  170. client := testEnv.APIClient()
  171. ctx := context.Background()
  172. testCases := []struct {
  173. maskedPaths []string
  174. expected []string
  175. }{
  176. {
  177. maskedPaths: []string{},
  178. expected: []string{},
  179. },
  180. {
  181. maskedPaths: nil,
  182. expected: oci.DefaultSpec().Linux.MaskedPaths,
  183. },
  184. {
  185. maskedPaths: []string{"/proc/kcore", "/proc/keys"},
  186. expected: []string{"/proc/kcore", "/proc/keys"},
  187. },
  188. }
  189. checkInspect := func(t *testing.T, ctx context.Context, name string, expected []string) {
  190. _, b, err := client.ContainerInspectWithRaw(ctx, name, false)
  191. assert.NilError(t, err)
  192. var inspectJSON map[string]interface{}
  193. err = json.Unmarshal(b, &inspectJSON)
  194. assert.NilError(t, err)
  195. cfg, ok := inspectJSON["HostConfig"].(map[string]interface{})
  196. assert.Check(t, is.Equal(true, ok), name)
  197. maskedPaths, ok := cfg["MaskedPaths"].([]interface{})
  198. assert.Check(t, is.Equal(true, ok), name)
  199. mps := []string{}
  200. for _, mp := range maskedPaths {
  201. mps = append(mps, mp.(string))
  202. }
  203. assert.DeepEqual(t, expected, mps)
  204. }
  205. for i, tc := range testCases {
  206. name := fmt.Sprintf("create-masked-paths-%d", i)
  207. config := container.Config{
  208. Image: "busybox",
  209. Cmd: []string{"true"},
  210. }
  211. hc := container.HostConfig{}
  212. if tc.maskedPaths != nil {
  213. hc.MaskedPaths = tc.maskedPaths
  214. }
  215. // Create the container.
  216. c, err := client.ContainerCreate(context.Background(),
  217. &config,
  218. &hc,
  219. &network.NetworkingConfig{},
  220. nil,
  221. name,
  222. )
  223. assert.NilError(t, err)
  224. checkInspect(t, ctx, name, tc.expected)
  225. // Start the container.
  226. err = client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{})
  227. assert.NilError(t, err)
  228. poll.WaitOn(t, ctr.IsInState(ctx, client, c.ID, "exited"), poll.WithDelay(100*time.Millisecond))
  229. checkInspect(t, ctx, name, tc.expected)
  230. }
  231. }
  232. func TestCreateWithCapabilities(t *testing.T) {
  233. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME: test should be able to run on LCOW")
  234. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "Capabilities was added in API v1.40")
  235. defer setupTest(t)()
  236. ctx := context.Background()
  237. clientNew := request.NewAPIClient(t)
  238. clientOld := request.NewAPIClient(t, client.WithVersion("1.39"))
  239. testCases := []struct {
  240. doc string
  241. hostConfig container.HostConfig
  242. expected []string
  243. expectedError string
  244. oldClient bool
  245. }{
  246. {
  247. doc: "no capabilities",
  248. hostConfig: container.HostConfig{},
  249. },
  250. {
  251. doc: "empty capabilities",
  252. hostConfig: container.HostConfig{
  253. Capabilities: []string{},
  254. },
  255. expected: []string{},
  256. },
  257. {
  258. doc: "valid capabilities",
  259. hostConfig: container.HostConfig{
  260. Capabilities: []string{"CAP_NET_RAW", "CAP_SYS_CHROOT"},
  261. },
  262. expected: []string{"CAP_NET_RAW", "CAP_SYS_CHROOT"},
  263. },
  264. {
  265. doc: "invalid capabilities",
  266. hostConfig: container.HostConfig{
  267. Capabilities: []string{"NET_RAW"},
  268. },
  269. expectedError: `invalid Capabilities: unknown capability: "NET_RAW"`,
  270. },
  271. {
  272. doc: "duplicate capabilities",
  273. hostConfig: container.HostConfig{
  274. Capabilities: []string{"CAP_SYS_NICE", "CAP_SYS_NICE"},
  275. },
  276. expected: []string{"CAP_SYS_NICE", "CAP_SYS_NICE"},
  277. },
  278. {
  279. doc: "capabilities API v1.39",
  280. hostConfig: container.HostConfig{
  281. Capabilities: []string{"CAP_NET_RAW", "CAP_SYS_CHROOT"},
  282. },
  283. expected: nil,
  284. oldClient: true,
  285. },
  286. {
  287. doc: "empty capadd",
  288. hostConfig: container.HostConfig{
  289. Capabilities: []string{"CAP_NET_ADMIN"},
  290. CapAdd: []string{},
  291. },
  292. expected: []string{"CAP_NET_ADMIN"},
  293. },
  294. {
  295. doc: "empty capdrop",
  296. hostConfig: container.HostConfig{
  297. Capabilities: []string{"CAP_NET_ADMIN"},
  298. CapDrop: []string{},
  299. },
  300. expected: []string{"CAP_NET_ADMIN"},
  301. },
  302. {
  303. doc: "capadd capdrop",
  304. hostConfig: container.HostConfig{
  305. CapAdd: []string{"SYS_NICE", "CAP_SYS_NICE"},
  306. CapDrop: []string{"SYS_NICE", "CAP_SYS_NICE"},
  307. },
  308. },
  309. {
  310. doc: "conflict with capadd",
  311. hostConfig: container.HostConfig{
  312. Capabilities: []string{"CAP_NET_ADMIN"},
  313. CapAdd: []string{"SYS_NICE"},
  314. },
  315. expectedError: `conflicting options: Capabilities and CapAdd`,
  316. },
  317. {
  318. doc: "conflict with capdrop",
  319. hostConfig: container.HostConfig{
  320. Capabilities: []string{"CAP_NET_ADMIN"},
  321. CapDrop: []string{"NET_RAW"},
  322. },
  323. expectedError: `conflicting options: Capabilities and CapDrop`,
  324. },
  325. }
  326. for _, tc := range testCases {
  327. tc := tc
  328. t.Run(tc.doc, func(t *testing.T) {
  329. t.Parallel()
  330. client := clientNew
  331. if tc.oldClient {
  332. client = clientOld
  333. }
  334. c, err := client.ContainerCreate(context.Background(),
  335. &container.Config{Image: "busybox"},
  336. &tc.hostConfig,
  337. &network.NetworkingConfig{},
  338. nil,
  339. "",
  340. )
  341. if tc.expectedError == "" {
  342. assert.NilError(t, err)
  343. ci, err := client.ContainerInspect(ctx, c.ID)
  344. assert.NilError(t, err)
  345. assert.Check(t, ci.HostConfig != nil)
  346. assert.DeepEqual(t, tc.expected, ci.HostConfig.Capabilities)
  347. } else {
  348. assert.ErrorContains(t, err, tc.expectedError)
  349. assert.Check(t, errdefs.IsInvalidParameter(err))
  350. }
  351. })
  352. }
  353. }
  354. func TestCreateWithCustomReadonlyPaths(t *testing.T) {
  355. skip.If(t, testEnv.DaemonInfo.OSType != "linux")
  356. defer setupTest(t)()
  357. client := testEnv.APIClient()
  358. ctx := context.Background()
  359. testCases := []struct {
  360. readonlyPaths []string
  361. expected []string
  362. }{
  363. {
  364. readonlyPaths: []string{},
  365. expected: []string{},
  366. },
  367. {
  368. readonlyPaths: nil,
  369. expected: oci.DefaultSpec().Linux.ReadonlyPaths,
  370. },
  371. {
  372. readonlyPaths: []string{"/proc/asound", "/proc/bus"},
  373. expected: []string{"/proc/asound", "/proc/bus"},
  374. },
  375. }
  376. checkInspect := func(t *testing.T, ctx context.Context, name string, expected []string) {
  377. _, b, err := client.ContainerInspectWithRaw(ctx, name, false)
  378. assert.NilError(t, err)
  379. var inspectJSON map[string]interface{}
  380. err = json.Unmarshal(b, &inspectJSON)
  381. assert.NilError(t, err)
  382. cfg, ok := inspectJSON["HostConfig"].(map[string]interface{})
  383. assert.Check(t, is.Equal(true, ok), name)
  384. readonlyPaths, ok := cfg["ReadonlyPaths"].([]interface{})
  385. assert.Check(t, is.Equal(true, ok), name)
  386. rops := []string{}
  387. for _, rop := range readonlyPaths {
  388. rops = append(rops, rop.(string))
  389. }
  390. assert.DeepEqual(t, expected, rops)
  391. }
  392. for i, tc := range testCases {
  393. name := fmt.Sprintf("create-readonly-paths-%d", i)
  394. config := container.Config{
  395. Image: "busybox",
  396. Cmd: []string{"true"},
  397. }
  398. hc := container.HostConfig{}
  399. if tc.readonlyPaths != nil {
  400. hc.ReadonlyPaths = tc.readonlyPaths
  401. }
  402. // Create the container.
  403. c, err := client.ContainerCreate(context.Background(),
  404. &config,
  405. &hc,
  406. &network.NetworkingConfig{},
  407. nil,
  408. name,
  409. )
  410. assert.NilError(t, err)
  411. checkInspect(t, ctx, name, tc.expected)
  412. // Start the container.
  413. err = client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{})
  414. assert.NilError(t, err)
  415. poll.WaitOn(t, ctr.IsInState(ctx, client, c.ID, "exited"), poll.WithDelay(100*time.Millisecond))
  416. checkInspect(t, ctx, name, tc.expected)
  417. }
  418. }
  419. func TestCreateWithInvalidHealthcheckParams(t *testing.T) {
  420. defer setupTest(t)()
  421. client := testEnv.APIClient()
  422. ctx := context.Background()
  423. testCases := []struct {
  424. doc string
  425. interval time.Duration
  426. timeout time.Duration
  427. retries int
  428. startPeriod time.Duration
  429. expectedErr string
  430. }{
  431. {
  432. doc: "test invalid Interval in Healthcheck: less than 0s",
  433. interval: -10 * time.Millisecond,
  434. timeout: time.Second,
  435. retries: 1000,
  436. expectedErr: fmt.Sprintf("Interval in Healthcheck cannot be less than %s", container.MinimumDuration),
  437. },
  438. {
  439. doc: "test invalid Interval in Healthcheck: larger than 0s but less than 1ms",
  440. interval: 500 * time.Microsecond,
  441. timeout: time.Second,
  442. retries: 1000,
  443. expectedErr: fmt.Sprintf("Interval in Healthcheck cannot be less than %s", container.MinimumDuration),
  444. },
  445. {
  446. doc: "test invalid Timeout in Healthcheck: less than 1ms",
  447. interval: time.Second,
  448. timeout: -100 * time.Millisecond,
  449. retries: 1000,
  450. expectedErr: fmt.Sprintf("Timeout in Healthcheck cannot be less than %s", container.MinimumDuration),
  451. },
  452. {
  453. doc: "test invalid Retries in Healthcheck: less than 0",
  454. interval: time.Second,
  455. timeout: time.Second,
  456. retries: -10,
  457. expectedErr: "Retries in Healthcheck cannot be negative",
  458. },
  459. {
  460. doc: "test invalid StartPeriod in Healthcheck: not 0 and less than 1ms",
  461. interval: time.Second,
  462. timeout: time.Second,
  463. retries: 1000,
  464. startPeriod: 100 * time.Microsecond,
  465. expectedErr: fmt.Sprintf("StartPeriod in Healthcheck cannot be less than %s", container.MinimumDuration),
  466. },
  467. }
  468. for _, tc := range testCases {
  469. tc := tc
  470. t.Run(tc.doc, func(t *testing.T) {
  471. t.Parallel()
  472. cfg := container.Config{
  473. Image: "busybox",
  474. Healthcheck: &container.HealthConfig{
  475. Interval: tc.interval,
  476. Timeout: tc.timeout,
  477. Retries: tc.retries,
  478. },
  479. }
  480. if tc.startPeriod != 0 {
  481. cfg.Healthcheck.StartPeriod = tc.startPeriod
  482. }
  483. resp, err := client.ContainerCreate(ctx, &cfg, &container.HostConfig{}, nil, nil, "")
  484. assert.Check(t, is.Equal(len(resp.Warnings), 0))
  485. if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") {
  486. assert.Check(t, errdefs.IsSystem(err))
  487. } else {
  488. assert.Check(t, errdefs.IsInvalidParameter(err))
  489. }
  490. assert.ErrorContains(t, err, tc.expectedErr)
  491. })
  492. }
  493. }
  494. // Make sure that anonymous volumes can be overritten by tmpfs
  495. // https://github.com/moby/moby/issues/40446
  496. func TestCreateTmpfsOverrideAnonymousVolume(t *testing.T) {
  497. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "windows does not support tmpfs")
  498. defer setupTest(t)()
  499. client := testEnv.APIClient()
  500. ctx := context.Background()
  501. id := ctr.Create(ctx, t, client,
  502. ctr.WithVolume("/foo"),
  503. ctr.WithTmpfs("/foo"),
  504. ctr.WithVolume("/bar"),
  505. ctr.WithTmpfs("/bar:size=999"),
  506. ctr.WithCmd("/bin/sh", "-c", "mount | grep '/foo' | grep tmpfs && mount | grep '/bar' | grep tmpfs"),
  507. )
  508. defer func() {
  509. err := client.ContainerRemove(ctx, id, types.ContainerRemoveOptions{Force: true})
  510. assert.NilError(t, err)
  511. }()
  512. inspect, err := client.ContainerInspect(ctx, id)
  513. assert.NilError(t, err)
  514. // tmpfs do not currently get added to inspect.Mounts
  515. // Normally an anonymous volume would, except now tmpfs should prevent that.
  516. assert.Assert(t, is.Len(inspect.Mounts, 0))
  517. chWait, chErr := client.ContainerWait(ctx, id, container.WaitConditionNextExit)
  518. assert.NilError(t, client.ContainerStart(ctx, id, types.ContainerStartOptions{}))
  519. timeout := time.NewTimer(30 * time.Second)
  520. defer timeout.Stop()
  521. select {
  522. case <-timeout.C:
  523. t.Fatal("timeout waiting for container to exit")
  524. case status := <-chWait:
  525. var errMsg string
  526. if status.Error != nil {
  527. errMsg = status.Error.Message
  528. }
  529. assert.Equal(t, int(status.StatusCode), 0, errMsg)
  530. case err := <-chErr:
  531. assert.NilError(t, err)
  532. }
  533. }
  534. // Test that if the referenced image platform does not match the requested platform on container create that we get an
  535. // error.
  536. func TestCreateDifferentPlatform(t *testing.T) {
  537. defer setupTest(t)()
  538. c := testEnv.APIClient()
  539. ctx := context.Background()
  540. img, _, err := c.ImageInspectWithRaw(ctx, "busybox:latest")
  541. assert.NilError(t, err)
  542. assert.Assert(t, img.Architecture != "")
  543. t.Run("different os", func(t *testing.T) {
  544. p := specs.Platform{
  545. OS: img.Os + "DifferentOS",
  546. Architecture: img.Architecture,
  547. Variant: img.Variant,
  548. }
  549. _, err := c.ContainerCreate(ctx, &containertypes.Config{Image: "busybox:latest"}, &containertypes.HostConfig{}, nil, &p, "")
  550. assert.Assert(t, client.IsErrNotFound(err), err)
  551. })
  552. t.Run("different cpu arch", func(t *testing.T) {
  553. p := specs.Platform{
  554. OS: img.Os,
  555. Architecture: img.Architecture + "DifferentArch",
  556. Variant: img.Variant,
  557. }
  558. _, err := c.ContainerCreate(ctx, &containertypes.Config{Image: "busybox:latest"}, &containertypes.HostConfig{}, nil, &p, "")
  559. assert.Assert(t, client.IsErrNotFound(err), err)
  560. })
  561. }
  562. func TestCreateVolumesFromNonExistingContainer(t *testing.T) {
  563. defer setupTest(t)()
  564. cli := testEnv.APIClient()
  565. _, err := cli.ContainerCreate(
  566. context.Background(),
  567. &container.Config{Image: "busybox"},
  568. &container.HostConfig{VolumesFrom: []string{"nosuchcontainer"}},
  569. nil,
  570. nil,
  571. "",
  572. )
  573. assert.Check(t, errdefs.IsInvalidParameter(err))
  574. }