create_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. specs "github.com/opencontainers/image-spec/specs-go/v1"
  19. "gotest.tools/v3/assert"
  20. is "gotest.tools/v3/assert/cmp"
  21. "gotest.tools/v3/poll"
  22. "gotest.tools/v3/skip"
  23. )
  24. func TestCreateFailsWhenIdentifierDoesNotExist(t *testing.T) {
  25. defer setupTest(t)()
  26. client := testEnv.APIClient()
  27. testCases := []struct {
  28. doc string
  29. image string
  30. expectedError string
  31. }{
  32. {
  33. doc: "image and tag",
  34. image: "test456:v1",
  35. expectedError: "No such image: test456:v1",
  36. },
  37. {
  38. doc: "image no tag",
  39. image: "test456",
  40. expectedError: "No such image: test456",
  41. },
  42. {
  43. doc: "digest",
  44. image: "sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa",
  45. expectedError: "No such image: sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efeaaaa",
  46. },
  47. }
  48. for _, tc := range testCases {
  49. tc := tc
  50. t.Run(tc.doc, func(t *testing.T) {
  51. t.Parallel()
  52. _, err := client.ContainerCreate(context.Background(),
  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. defer setupTest(t)()
  70. c := testEnv.APIClient()
  71. _, err := c.ContainerCreate(context.Background(),
  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. defer 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. _, err := client.ContainerCreate(context.Background(),
  110. &container.Config{
  111. Image: "busybox",
  112. Env: []string{tc.env},
  113. },
  114. &container.HostConfig{},
  115. &network.NetworkingConfig{},
  116. nil,
  117. "",
  118. )
  119. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  120. assert.Check(t, errdefs.IsInvalidParameter(err))
  121. })
  122. }
  123. }
  124. // Test case for #30166 (target was not validated)
  125. func TestCreateTmpfsMountsTarget(t *testing.T) {
  126. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  127. defer setupTest(t)()
  128. client := testEnv.APIClient()
  129. testCases := []struct {
  130. target string
  131. expectedError string
  132. }{
  133. {
  134. target: ".",
  135. expectedError: "mount path must be absolute",
  136. },
  137. {
  138. target: "foo",
  139. expectedError: "mount path must be absolute",
  140. },
  141. {
  142. target: "/",
  143. expectedError: "destination can't be '/'",
  144. },
  145. {
  146. target: "//",
  147. expectedError: "destination can't be '/'",
  148. },
  149. }
  150. for _, tc := range testCases {
  151. _, err := client.ContainerCreate(context.Background(),
  152. &container.Config{
  153. Image: "busybox",
  154. },
  155. &container.HostConfig{
  156. Tmpfs: map[string]string{tc.target: ""},
  157. },
  158. &network.NetworkingConfig{},
  159. nil,
  160. "",
  161. )
  162. assert.Check(t, is.ErrorContains(err, tc.expectedError))
  163. assert.Check(t, errdefs.IsInvalidParameter(err))
  164. }
  165. }
  166. func TestCreateWithCustomMaskedPaths(t *testing.T) {
  167. skip.If(t, testEnv.DaemonInfo.OSType != "linux")
  168. defer setupTest(t)()
  169. client := testEnv.APIClient()
  170. ctx := context.Background()
  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 := client.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. for i, tc := range testCases {
  205. name := fmt.Sprintf("create-masked-paths-%d", i)
  206. config := container.Config{
  207. Image: "busybox",
  208. Cmd: []string{"true"},
  209. }
  210. hc := container.HostConfig{}
  211. if tc.maskedPaths != nil {
  212. hc.MaskedPaths = tc.maskedPaths
  213. }
  214. // Create the container.
  215. c, err := client.ContainerCreate(context.Background(),
  216. &config,
  217. &hc,
  218. &network.NetworkingConfig{},
  219. nil,
  220. name,
  221. )
  222. assert.NilError(t, err)
  223. checkInspect(t, ctx, name, tc.expected)
  224. // Start the container.
  225. err = client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{})
  226. assert.NilError(t, err)
  227. poll.WaitOn(t, ctr.IsInState(ctx, client, c.ID, "exited"), poll.WithDelay(100*time.Millisecond))
  228. checkInspect(t, ctx, name, tc.expected)
  229. }
  230. }
  231. func TestCreateWithCustomReadonlyPaths(t *testing.T) {
  232. skip.If(t, testEnv.DaemonInfo.OSType != "linux")
  233. defer setupTest(t)()
  234. client := testEnv.APIClient()
  235. ctx := context.Background()
  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 := client.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 := client.ContainerCreate(context.Background(),
  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 = client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{})
  291. assert.NilError(t, err)
  292. poll.WaitOn(t, ctr.IsInState(ctx, client, c.ID, "exited"), poll.WithDelay(100*time.Millisecond))
  293. checkInspect(t, ctx, name, tc.expected)
  294. }
  295. }
  296. func TestCreateWithInvalidHealthcheckParams(t *testing.T) {
  297. defer setupTest(t)()
  298. client := testEnv.APIClient()
  299. ctx := context.Background()
  300. testCases := []struct {
  301. doc string
  302. interval time.Duration
  303. timeout time.Duration
  304. retries int
  305. startPeriod 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. for _, tc := range testCases {
  346. tc := tc
  347. t.Run(tc.doc, func(t *testing.T) {
  348. t.Parallel()
  349. cfg := container.Config{
  350. Image: "busybox",
  351. Healthcheck: &container.HealthConfig{
  352. Interval: tc.interval,
  353. Timeout: tc.timeout,
  354. Retries: tc.retries,
  355. },
  356. }
  357. if tc.startPeriod != 0 {
  358. cfg.Healthcheck.StartPeriod = tc.startPeriod
  359. }
  360. resp, err := client.ContainerCreate(ctx, &cfg, &container.HostConfig{}, nil, nil, "")
  361. assert.Check(t, is.Equal(len(resp.Warnings), 0))
  362. if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") {
  363. assert.Check(t, errdefs.IsSystem(err))
  364. } else {
  365. assert.Check(t, errdefs.IsInvalidParameter(err))
  366. }
  367. assert.ErrorContains(t, err, tc.expectedErr)
  368. })
  369. }
  370. }
  371. // Make sure that anonymous volumes can be overritten by tmpfs
  372. // https://github.com/moby/moby/issues/40446
  373. func TestCreateTmpfsOverrideAnonymousVolume(t *testing.T) {
  374. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "windows does not support tmpfs")
  375. defer setupTest(t)()
  376. client := testEnv.APIClient()
  377. ctx := context.Background()
  378. id := ctr.Create(ctx, t, client,
  379. ctr.WithVolume("/foo"),
  380. ctr.WithTmpfs("/foo"),
  381. ctr.WithVolume("/bar"),
  382. ctr.WithTmpfs("/bar:size=999"),
  383. ctr.WithCmd("/bin/sh", "-c", "mount | grep '/foo' | grep tmpfs && mount | grep '/bar' | grep tmpfs"),
  384. )
  385. defer func() {
  386. err := client.ContainerRemove(ctx, id, types.ContainerRemoveOptions{Force: true})
  387. assert.NilError(t, err)
  388. }()
  389. inspect, err := client.ContainerInspect(ctx, id)
  390. assert.NilError(t, err)
  391. // tmpfs do not currently get added to inspect.Mounts
  392. // Normally an anonymous volume would, except now tmpfs should prevent that.
  393. assert.Assert(t, is.Len(inspect.Mounts, 0))
  394. chWait, chErr := client.ContainerWait(ctx, id, container.WaitConditionNextExit)
  395. assert.NilError(t, client.ContainerStart(ctx, id, types.ContainerStartOptions{}))
  396. timeout := time.NewTimer(30 * time.Second)
  397. defer timeout.Stop()
  398. select {
  399. case <-timeout.C:
  400. t.Fatal("timeout waiting for container to exit")
  401. case status := <-chWait:
  402. var errMsg string
  403. if status.Error != nil {
  404. errMsg = status.Error.Message
  405. }
  406. assert.Equal(t, int(status.StatusCode), 0, errMsg)
  407. case err := <-chErr:
  408. assert.NilError(t, err)
  409. }
  410. }
  411. // Test that if the referenced image platform does not match the requested platform on container create that we get an
  412. // error.
  413. func TestCreateDifferentPlatform(t *testing.T) {
  414. defer setupTest(t)()
  415. c := testEnv.APIClient()
  416. ctx := context.Background()
  417. img, _, err := c.ImageInspectWithRaw(ctx, "busybox:latest")
  418. assert.NilError(t, err)
  419. assert.Assert(t, img.Architecture != "")
  420. t.Run("different os", func(t *testing.T) {
  421. p := specs.Platform{
  422. OS: img.Os + "DifferentOS",
  423. Architecture: img.Architecture,
  424. Variant: img.Variant,
  425. }
  426. _, err := c.ContainerCreate(ctx, &containertypes.Config{Image: "busybox:latest"}, &containertypes.HostConfig{}, nil, &p, "")
  427. assert.Assert(t, client.IsErrNotFound(err), err)
  428. })
  429. t.Run("different cpu arch", func(t *testing.T) {
  430. p := specs.Platform{
  431. OS: img.Os,
  432. Architecture: img.Architecture + "DifferentArch",
  433. Variant: img.Variant,
  434. }
  435. _, err := c.ContainerCreate(ctx, &containertypes.Config{Image: "busybox:latest"}, &containertypes.HostConfig{}, nil, &p, "")
  436. assert.Assert(t, client.IsErrNotFound(err), err)
  437. })
  438. }
  439. func TestCreateVolumesFromNonExistingContainer(t *testing.T) {
  440. defer setupTest(t)()
  441. cli := testEnv.APIClient()
  442. _, err := cli.ContainerCreate(
  443. context.Background(),
  444. &container.Config{Image: "busybox"},
  445. &container.HostConfig{VolumesFrom: []string{"nosuchcontainer"}},
  446. nil,
  447. nil,
  448. "",
  449. )
  450. assert.Check(t, errdefs.IsInvalidParameter(err))
  451. }
  452. // Test that we can create a container from an image that is for a different platform even if a platform was not specified
  453. // This is for the regression detailed here: https://github.com/moby/moby/issues/41552
  454. func TestCreatePlatformSpecificImageNoPlatform(t *testing.T) {
  455. defer setupTest(t)()
  456. skip.If(t, testEnv.DaemonInfo.Architecture == "arm", "test only makes sense to run on non-arm systems")
  457. skip.If(t, testEnv.OSType != "linux", "test image is only available on linux")
  458. cli := testEnv.APIClient()
  459. _, err := cli.ContainerCreate(
  460. context.Background(),
  461. &container.Config{Image: "arm32v7/hello-world"},
  462. &container.HostConfig{},
  463. nil,
  464. nil,
  465. "",
  466. )
  467. assert.NilError(t, err)
  468. }