create_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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/container"
  10. "github.com/docker/docker/api/types/network"
  11. "github.com/docker/docker/api/types/versions"
  12. "github.com/docker/docker/client"
  13. "github.com/docker/docker/errdefs"
  14. ctr "github.com/docker/docker/integration/internal/container"
  15. "github.com/docker/docker/oci"
  16. "github.com/docker/docker/testutil"
  17. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  18. "gotest.tools/v3/assert"
  19. is "gotest.tools/v3/assert/cmp"
  20. "gotest.tools/v3/poll"
  21. "gotest.tools/v3/skip"
  22. )
  23. func TestCreateFailsWhenIdentifierDoesNotExist(t *testing.T) {
  24. ctx := setupTest(t)
  25. client := testEnv.APIClient()
  26. testCases := []struct {
  27. doc string
  28. image string
  29. expectedError string
  30. }{
  31. {
  32. doc: "image and tag",
  33. image: "test456:v1",
  34. expectedError: "No such image: test456:v1",
  35. },
  36. {
  37. doc: "image no tag",
  38. image: "test456",
  39. expectedError: "No such image: test456",
  40. },
  41. {
  42. doc: "digest",
  43. image: "sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa",
  44. expectedError: "No such image: sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa",
  45. },
  46. }
  47. for _, tc := range testCases {
  48. tc := tc
  49. t.Run(tc.doc, func(t *testing.T) {
  50. t.Parallel()
  51. ctx := testutil.StartSpan(ctx, t)
  52. _, err := client.ContainerCreate(ctx,
  53. &container.Config{Image: tc.image},
  54. &container.HostConfig{},
  55. &network.NetworkingConfig{},
  56. nil,
  57. "",
  58. )
  59. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  60. assert.Check(t, errdefs.IsNotFound(err))
  61. })
  62. }
  63. }
  64. // TestCreateLinkToNonExistingContainer verifies that linking to a non-existing
  65. // container returns an "invalid parameter" (400) status, and not the underlying
  66. // "non exists" (404).
  67. func TestCreateLinkToNonExistingContainer(t *testing.T) {
  68. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "legacy links are not supported on windows")
  69. ctx := setupTest(t)
  70. c := testEnv.APIClient()
  71. _, err := c.ContainerCreate(ctx,
  72. &container.Config{
  73. Image: "busybox",
  74. },
  75. &container.HostConfig{
  76. Links: []string{"no-such-container"},
  77. },
  78. &network.NetworkingConfig{},
  79. nil,
  80. "",
  81. )
  82. assert.Check(t, is.ErrorContains(err, "could not get container for no-such-container"))
  83. assert.Check(t, errdefs.IsInvalidParameter(err))
  84. }
  85. func TestCreateWithInvalidEnv(t *testing.T) {
  86. ctx := setupTest(t)
  87. client := testEnv.APIClient()
  88. testCases := []struct {
  89. env string
  90. expectedError string
  91. }{
  92. {
  93. env: "",
  94. expectedError: "invalid environment variable:",
  95. },
  96. {
  97. env: "=",
  98. expectedError: "invalid environment variable: =",
  99. },
  100. {
  101. env: "=foo",
  102. expectedError: "invalid environment variable: =foo",
  103. },
  104. }
  105. for index, tc := range testCases {
  106. tc := tc
  107. t.Run(strconv.Itoa(index), func(t *testing.T) {
  108. t.Parallel()
  109. ctx := testutil.StartSpan(ctx, t)
  110. _, err := client.ContainerCreate(ctx,
  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. ctx := 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(ctx,
  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. ctx := setupTest(t)
  170. apiClient := testEnv.APIClient()
  171. testCases := []struct {
  172. maskedPaths []string
  173. expected []string
  174. }{
  175. {
  176. maskedPaths: []string{},
  177. expected: []string{},
  178. },
  179. {
  180. maskedPaths: nil,
  181. expected: oci.DefaultSpec().Linux.MaskedPaths,
  182. },
  183. {
  184. maskedPaths: []string{"/proc/kcore", "/proc/keys"},
  185. expected: []string{"/proc/kcore", "/proc/keys"},
  186. },
  187. }
  188. checkInspect := func(t *testing.T, ctx context.Context, name string, expected []string) {
  189. _, b, err := apiClient.ContainerInspectWithRaw(ctx, name, false)
  190. assert.NilError(t, err)
  191. var inspectJSON map[string]interface{}
  192. err = json.Unmarshal(b, &inspectJSON)
  193. assert.NilError(t, err)
  194. cfg, ok := inspectJSON["HostConfig"].(map[string]interface{})
  195. assert.Check(t, is.Equal(true, ok), name)
  196. maskedPaths, ok := cfg["MaskedPaths"].([]interface{})
  197. assert.Check(t, is.Equal(true, ok), name)
  198. mps := []string{}
  199. for _, mp := range maskedPaths {
  200. mps = append(mps, mp.(string))
  201. }
  202. assert.DeepEqual(t, expected, mps)
  203. }
  204. // TODO: This should be using subtests
  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 := apiClient.ContainerCreate(ctx,
  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 = apiClient.ContainerStart(ctx, c.ID, container.StartOptions{})
  227. assert.NilError(t, err)
  228. poll.WaitOn(t, ctr.IsInState(ctx, apiClient, c.ID, "exited"), poll.WithDelay(100*time.Millisecond))
  229. checkInspect(t, ctx, name, tc.expected)
  230. }
  231. }
  232. func TestCreateWithCustomReadonlyPaths(t *testing.T) {
  233. skip.If(t, testEnv.DaemonInfo.OSType != "linux")
  234. ctx := setupTest(t)
  235. apiClient := testEnv.APIClient()
  236. testCases := []struct {
  237. readonlyPaths []string
  238. expected []string
  239. }{
  240. {
  241. readonlyPaths: []string{},
  242. expected: []string{},
  243. },
  244. {
  245. readonlyPaths: nil,
  246. expected: oci.DefaultSpec().Linux.ReadonlyPaths,
  247. },
  248. {
  249. readonlyPaths: []string{"/proc/asound", "/proc/bus"},
  250. expected: []string{"/proc/asound", "/proc/bus"},
  251. },
  252. }
  253. checkInspect := func(t *testing.T, ctx context.Context, name string, expected []string) {
  254. _, b, err := apiClient.ContainerInspectWithRaw(ctx, name, false)
  255. assert.NilError(t, err)
  256. var inspectJSON map[string]interface{}
  257. err = json.Unmarshal(b, &inspectJSON)
  258. assert.NilError(t, err)
  259. cfg, ok := inspectJSON["HostConfig"].(map[string]interface{})
  260. assert.Check(t, is.Equal(true, ok), name)
  261. readonlyPaths, ok := cfg["ReadonlyPaths"].([]interface{})
  262. assert.Check(t, is.Equal(true, ok), name)
  263. rops := []string{}
  264. for _, rop := range readonlyPaths {
  265. rops = append(rops, rop.(string))
  266. }
  267. assert.DeepEqual(t, expected, rops)
  268. }
  269. for i, tc := range testCases {
  270. name := fmt.Sprintf("create-readonly-paths-%d", i)
  271. config := container.Config{
  272. Image: "busybox",
  273. Cmd: []string{"true"},
  274. }
  275. hc := container.HostConfig{}
  276. if tc.readonlyPaths != nil {
  277. hc.ReadonlyPaths = tc.readonlyPaths
  278. }
  279. // Create the container.
  280. c, err := apiClient.ContainerCreate(ctx,
  281. &config,
  282. &hc,
  283. &network.NetworkingConfig{},
  284. nil,
  285. name,
  286. )
  287. assert.NilError(t, err)
  288. checkInspect(t, ctx, name, tc.expected)
  289. // Start the container.
  290. err = apiClient.ContainerStart(ctx, c.ID, container.StartOptions{})
  291. assert.NilError(t, err)
  292. poll.WaitOn(t, ctr.IsInState(ctx, apiClient, c.ID, "exited"), poll.WithDelay(100*time.Millisecond))
  293. checkInspect(t, ctx, name, tc.expected)
  294. }
  295. }
  296. func TestCreateWithInvalidHealthcheckParams(t *testing.T) {
  297. ctx := setupTest(t)
  298. apiClient := testEnv.APIClient()
  299. testCases := []struct {
  300. doc string
  301. interval time.Duration
  302. timeout time.Duration
  303. retries int
  304. startPeriod time.Duration
  305. startInterval time.Duration
  306. expectedErr string
  307. }{
  308. {
  309. doc: "test invalid Interval in Healthcheck: less than 0s",
  310. interval: -10 * time.Millisecond,
  311. timeout: time.Second,
  312. retries: 1000,
  313. expectedErr: fmt.Sprintf("Interval in Healthcheck cannot be less than %s", container.MinimumDuration),
  314. },
  315. {
  316. doc: "test invalid Interval in Healthcheck: larger than 0s but less than 1ms",
  317. interval: 500 * time.Microsecond,
  318. timeout: time.Second,
  319. retries: 1000,
  320. expectedErr: fmt.Sprintf("Interval in Healthcheck cannot be less than %s", container.MinimumDuration),
  321. },
  322. {
  323. doc: "test invalid Timeout in Healthcheck: less than 1ms",
  324. interval: time.Second,
  325. timeout: -100 * time.Millisecond,
  326. retries: 1000,
  327. expectedErr: fmt.Sprintf("Timeout in Healthcheck cannot be less than %s", container.MinimumDuration),
  328. },
  329. {
  330. doc: "test invalid Retries in Healthcheck: less than 0",
  331. interval: time.Second,
  332. timeout: time.Second,
  333. retries: -10,
  334. expectedErr: "Retries in Healthcheck cannot be negative",
  335. },
  336. {
  337. doc: "test invalid StartPeriod in Healthcheck: not 0 and less than 1ms",
  338. interval: time.Second,
  339. timeout: time.Second,
  340. retries: 1000,
  341. startPeriod: 100 * time.Microsecond,
  342. expectedErr: fmt.Sprintf("StartPeriod in Healthcheck cannot be less than %s", container.MinimumDuration),
  343. },
  344. {
  345. doc: "test invalid StartInterval in Healthcheck: not 0 and less than 1ms",
  346. interval: time.Second,
  347. timeout: time.Second,
  348. retries: 1000,
  349. startPeriod: time.Second,
  350. startInterval: 100 * time.Microsecond,
  351. expectedErr: fmt.Sprintf("StartInterval in Healthcheck cannot be less than %s", container.MinimumDuration),
  352. },
  353. }
  354. for _, tc := range testCases {
  355. tc := tc
  356. t.Run(tc.doc, func(t *testing.T) {
  357. t.Parallel()
  358. ctx := testutil.StartSpan(ctx, t)
  359. cfg := container.Config{
  360. Image: "busybox",
  361. Healthcheck: &container.HealthConfig{
  362. Interval: tc.interval,
  363. Timeout: tc.timeout,
  364. Retries: tc.retries,
  365. StartInterval: tc.startInterval,
  366. },
  367. }
  368. if tc.startPeriod != 0 {
  369. cfg.Healthcheck.StartPeriod = tc.startPeriod
  370. }
  371. resp, err := apiClient.ContainerCreate(ctx, &cfg, &container.HostConfig{}, nil, nil, "")
  372. assert.Check(t, is.Equal(len(resp.Warnings), 0))
  373. if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") {
  374. assert.Check(t, errdefs.IsSystem(err))
  375. } else {
  376. assert.Check(t, errdefs.IsInvalidParameter(err))
  377. }
  378. assert.ErrorContains(t, err, tc.expectedErr)
  379. })
  380. }
  381. }
  382. // Make sure that anonymous volumes can be overritten by tmpfs
  383. // https://github.com/moby/moby/issues/40446
  384. func TestCreateTmpfsOverrideAnonymousVolume(t *testing.T) {
  385. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "windows does not support tmpfs")
  386. ctx := setupTest(t)
  387. apiClient := testEnv.APIClient()
  388. id := ctr.Create(ctx, t, apiClient,
  389. ctr.WithVolume("/foo"),
  390. ctr.WithTmpfs("/foo"),
  391. ctr.WithVolume("/bar"),
  392. ctr.WithTmpfs("/bar:size=999"),
  393. ctr.WithCmd("/bin/sh", "-c", "mount | grep '/foo' | grep tmpfs && mount | grep '/bar' | grep tmpfs"),
  394. )
  395. defer func() {
  396. err := apiClient.ContainerRemove(ctx, id, container.RemoveOptions{Force: true})
  397. assert.NilError(t, err)
  398. }()
  399. inspect, err := apiClient.ContainerInspect(ctx, id)
  400. assert.NilError(t, err)
  401. // tmpfs do not currently get added to inspect.Mounts
  402. // Normally an anonymous volume would, except now tmpfs should prevent that.
  403. assert.Assert(t, is.Len(inspect.Mounts, 0))
  404. chWait, chErr := apiClient.ContainerWait(ctx, id, container.WaitConditionNextExit)
  405. assert.NilError(t, apiClient.ContainerStart(ctx, id, container.StartOptions{}))
  406. timeout := time.NewTimer(30 * time.Second)
  407. defer timeout.Stop()
  408. select {
  409. case <-timeout.C:
  410. t.Fatal("timeout waiting for container to exit")
  411. case status := <-chWait:
  412. var errMsg string
  413. if status.Error != nil {
  414. errMsg = status.Error.Message
  415. }
  416. assert.Equal(t, int(status.StatusCode), 0, errMsg)
  417. case err := <-chErr:
  418. assert.NilError(t, err)
  419. }
  420. }
  421. // Test that if the referenced image platform does not match the requested platform on container create that we get an
  422. // error.
  423. func TestCreateDifferentPlatform(t *testing.T) {
  424. ctx := setupTest(t)
  425. apiClient := testEnv.APIClient()
  426. img, _, err := apiClient.ImageInspectWithRaw(ctx, "busybox:latest")
  427. assert.NilError(t, err)
  428. assert.Assert(t, img.Architecture != "")
  429. t.Run("different os", func(t *testing.T) {
  430. ctx := testutil.StartSpan(ctx, t)
  431. p := ocispec.Platform{
  432. OS: img.Os + "DifferentOS",
  433. Architecture: img.Architecture,
  434. Variant: img.Variant,
  435. }
  436. _, err := apiClient.ContainerCreate(ctx, &container.Config{Image: "busybox:latest"}, &container.HostConfig{}, nil, &p, "")
  437. assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
  438. })
  439. t.Run("different cpu arch", func(t *testing.T) {
  440. ctx := testutil.StartSpan(ctx, t)
  441. p := ocispec.Platform{
  442. OS: img.Os,
  443. Architecture: img.Architecture + "DifferentArch",
  444. Variant: img.Variant,
  445. }
  446. _, err := apiClient.ContainerCreate(ctx, &container.Config{Image: "busybox:latest"}, &container.HostConfig{}, nil, &p, "")
  447. assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
  448. })
  449. }
  450. func TestCreateVolumesFromNonExistingContainer(t *testing.T) {
  451. ctx := setupTest(t)
  452. cli := testEnv.APIClient()
  453. _, err := cli.ContainerCreate(
  454. ctx,
  455. &container.Config{Image: "busybox"},
  456. &container.HostConfig{VolumesFrom: []string{"nosuchcontainer"}},
  457. nil,
  458. nil,
  459. "",
  460. )
  461. assert.Check(t, errdefs.IsInvalidParameter(err))
  462. }
  463. // Test that we can create a container from an image that is for a different platform even if a platform was not specified
  464. // This is for the regression detailed here: https://github.com/moby/moby/issues/41552
  465. func TestCreatePlatformSpecificImageNoPlatform(t *testing.T) {
  466. ctx := setupTest(t)
  467. skip.If(t, testEnv.DaemonInfo.Architecture == "arm", "test only makes sense to run on non-arm systems")
  468. skip.If(t, testEnv.DaemonInfo.OSType != "linux", "test image is only available on linux")
  469. cli := testEnv.APIClient()
  470. _, err := cli.ContainerCreate(
  471. ctx,
  472. &container.Config{Image: "arm32v7/hello-world"},
  473. &container.HostConfig{},
  474. nil,
  475. nil,
  476. "",
  477. )
  478. assert.NilError(t, err)
  479. }
  480. func TestCreateInvalidHostConfig(t *testing.T) {
  481. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  482. ctx := setupTest(t)
  483. apiClient := testEnv.APIClient()
  484. testCases := []struct {
  485. doc string
  486. hc container.HostConfig
  487. expectedErr string
  488. }{
  489. {
  490. doc: "invalid IpcMode",
  491. hc: container.HostConfig{IpcMode: "invalid"},
  492. expectedErr: "Error response from daemon: invalid IPC mode: invalid",
  493. },
  494. {
  495. doc: "invalid PidMode",
  496. hc: container.HostConfig{PidMode: "invalid"},
  497. expectedErr: "Error response from daemon: invalid PID mode: invalid",
  498. },
  499. {
  500. doc: "invalid PidMode without container ID",
  501. hc: container.HostConfig{PidMode: "container"},
  502. expectedErr: "Error response from daemon: invalid PID mode: container",
  503. },
  504. {
  505. doc: "invalid UTSMode",
  506. hc: container.HostConfig{UTSMode: "invalid"},
  507. expectedErr: "Error response from daemon: invalid UTS mode: invalid",
  508. },
  509. {
  510. doc: "invalid Annotations",
  511. hc: container.HostConfig{Annotations: map[string]string{"": "a"}},
  512. expectedErr: "Error response from daemon: invalid Annotations: the empty string is not permitted as an annotation key",
  513. },
  514. }
  515. for _, tc := range testCases {
  516. tc := tc
  517. t.Run(tc.doc, func(t *testing.T) {
  518. t.Parallel()
  519. ctx := testutil.StartSpan(ctx, t)
  520. cfg := container.Config{
  521. Image: "busybox",
  522. }
  523. resp, err := apiClient.ContainerCreate(ctx, &cfg, &tc.hc, nil, nil, "")
  524. assert.Check(t, is.Equal(len(resp.Warnings), 0))
  525. assert.Check(t, errdefs.IsInvalidParameter(err), "got: %T", err)
  526. assert.Error(t, err, tc.expectedErr)
  527. })
  528. }
  529. }
  530. func TestCreateWithMultipleEndpointSettings(t *testing.T) {
  531. ctx := setupTest(t)
  532. testcases := []struct {
  533. apiVersion string
  534. expectedErr string
  535. }{
  536. {apiVersion: "1.44"},
  537. {apiVersion: "1.43", expectedErr: "Container cannot be created with multiple network endpoints"},
  538. }
  539. for _, tc := range testcases {
  540. t.Run("with API v"+tc.apiVersion, func(t *testing.T) {
  541. apiClient, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion(tc.apiVersion))
  542. assert.NilError(t, err)
  543. config := container.Config{
  544. Image: "busybox",
  545. }
  546. networkingConfig := network.NetworkingConfig{
  547. EndpointsConfig: map[string]*network.EndpointSettings{
  548. "net1": {},
  549. "net2": {},
  550. "net3": {},
  551. },
  552. }
  553. _, err = apiClient.ContainerCreate(ctx, &config, &container.HostConfig{}, &networkingConfig, nil, "")
  554. if tc.expectedErr == "" {
  555. assert.NilError(t, err)
  556. } else {
  557. assert.ErrorContains(t, err, tc.expectedErr)
  558. }
  559. })
  560. }
  561. }