docker_cli_create_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "reflect"
  8. "strings"
  9. "time"
  10. "github.com/docker/docker/integration-cli/checker"
  11. "github.com/docker/docker/integration-cli/cli"
  12. "github.com/docker/docker/integration-cli/cli/build"
  13. "github.com/docker/docker/integration-cli/cli/build/fakecontext"
  14. "github.com/docker/docker/pkg/stringid"
  15. "github.com/docker/go-connections/nat"
  16. "github.com/go-check/check"
  17. "github.com/gotestyourself/gotestyourself/icmd"
  18. )
  19. // Make sure we can create a simple container with some args
  20. func (s *DockerSuite) TestCreateArgs(c *check.C) {
  21. // Intentionally clear entrypoint, as the Windows busybox image needs an entrypoint, which breaks this test
  22. out, _ := dockerCmd(c, "create", "--entrypoint=", "busybox", "command", "arg1", "arg2", "arg with space", "-c", "flags")
  23. cleanedContainerID := strings.TrimSpace(out)
  24. out, _ = dockerCmd(c, "inspect", cleanedContainerID)
  25. containers := []struct {
  26. ID string
  27. Created time.Time
  28. Path string
  29. Args []string
  30. Image string
  31. }{}
  32. err := json.Unmarshal([]byte(out), &containers)
  33. c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
  34. c.Assert(containers, checker.HasLen, 1)
  35. cont := containers[0]
  36. c.Assert(string(cont.Path), checker.Equals, "command", check.Commentf("Unexpected container path. Expected command, received: %s", cont.Path))
  37. b := false
  38. expected := []string{"arg1", "arg2", "arg with space", "-c", "flags"}
  39. for i, arg := range expected {
  40. if arg != cont.Args[i] {
  41. b = true
  42. break
  43. }
  44. }
  45. if len(cont.Args) != len(expected) || b {
  46. c.Fatalf("Unexpected args. Expected %v, received: %v", expected, cont.Args)
  47. }
  48. }
  49. // Make sure we can grow the container's rootfs at creation time.
  50. func (s *DockerSuite) TestCreateGrowRootfs(c *check.C) {
  51. // Windows and Devicemapper support growing the rootfs
  52. if testEnv.DaemonPlatform() != "windows" {
  53. testRequires(c, Devicemapper)
  54. }
  55. out, _ := dockerCmd(c, "create", "--storage-opt", "size=120G", "busybox")
  56. cleanedContainerID := strings.TrimSpace(out)
  57. inspectOut := inspectField(c, cleanedContainerID, "HostConfig.StorageOpt")
  58. c.Assert(inspectOut, checker.Equals, "map[size:120G]")
  59. }
  60. // Make sure we cannot shrink the container's rootfs at creation time.
  61. func (s *DockerSuite) TestCreateShrinkRootfs(c *check.C) {
  62. testRequires(c, Devicemapper)
  63. // Ensure this fails because of the defaultBaseFsSize is 10G
  64. out, _, err := dockerCmdWithError("create", "--storage-opt", "size=5G", "busybox")
  65. c.Assert(err, check.NotNil, check.Commentf(out))
  66. c.Assert(out, checker.Contains, "Container size cannot be smaller than")
  67. }
  68. // Make sure we can set hostconfig options too
  69. func (s *DockerSuite) TestCreateHostConfig(c *check.C) {
  70. out, _ := dockerCmd(c, "create", "-P", "busybox", "echo")
  71. cleanedContainerID := strings.TrimSpace(out)
  72. out, _ = dockerCmd(c, "inspect", cleanedContainerID)
  73. containers := []struct {
  74. HostConfig *struct {
  75. PublishAllPorts bool
  76. }
  77. }{}
  78. err := json.Unmarshal([]byte(out), &containers)
  79. c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
  80. c.Assert(containers, checker.HasLen, 1)
  81. cont := containers[0]
  82. c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
  83. c.Assert(cont.HostConfig.PublishAllPorts, check.NotNil, check.Commentf("Expected PublishAllPorts, got false"))
  84. }
  85. func (s *DockerSuite) TestCreateWithPortRange(c *check.C) {
  86. out, _ := dockerCmd(c, "create", "-p", "3300-3303:3300-3303/tcp", "busybox", "echo")
  87. cleanedContainerID := strings.TrimSpace(out)
  88. out, _ = dockerCmd(c, "inspect", cleanedContainerID)
  89. containers := []struct {
  90. HostConfig *struct {
  91. PortBindings map[nat.Port][]nat.PortBinding
  92. }
  93. }{}
  94. err := json.Unmarshal([]byte(out), &containers)
  95. c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
  96. c.Assert(containers, checker.HasLen, 1)
  97. cont := containers[0]
  98. c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
  99. c.Assert(cont.HostConfig.PortBindings, checker.HasLen, 4, check.Commentf("Expected 4 ports bindings, got %d", len(cont.HostConfig.PortBindings)))
  100. for k, v := range cont.HostConfig.PortBindings {
  101. c.Assert(v, checker.HasLen, 1, check.Commentf("Expected 1 ports binding, for the port %s but found %s", k, v))
  102. c.Assert(k.Port(), checker.Equals, v[0].HostPort, check.Commentf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort))
  103. }
  104. }
  105. func (s *DockerSuite) TestCreateWithLargePortRange(c *check.C) {
  106. out, _ := dockerCmd(c, "create", "-p", "1-65535:1-65535/tcp", "busybox", "echo")
  107. cleanedContainerID := strings.TrimSpace(out)
  108. out, _ = dockerCmd(c, "inspect", cleanedContainerID)
  109. containers := []struct {
  110. HostConfig *struct {
  111. PortBindings map[nat.Port][]nat.PortBinding
  112. }
  113. }{}
  114. err := json.Unmarshal([]byte(out), &containers)
  115. c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
  116. c.Assert(containers, checker.HasLen, 1)
  117. cont := containers[0]
  118. c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
  119. c.Assert(cont.HostConfig.PortBindings, checker.HasLen, 65535)
  120. for k, v := range cont.HostConfig.PortBindings {
  121. c.Assert(v, checker.HasLen, 1)
  122. c.Assert(k.Port(), checker.Equals, v[0].HostPort, check.Commentf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort))
  123. }
  124. }
  125. // "test123" should be printed by docker create + start
  126. func (s *DockerSuite) TestCreateEchoStdout(c *check.C) {
  127. out, _ := dockerCmd(c, "create", "busybox", "echo", "test123")
  128. cleanedContainerID := strings.TrimSpace(out)
  129. out, _ = dockerCmd(c, "start", "-ai", cleanedContainerID)
  130. c.Assert(out, checker.Equals, "test123\n", check.Commentf("container should've printed 'test123', got %q", out))
  131. }
  132. func (s *DockerSuite) TestCreateVolumesCreated(c *check.C) {
  133. testRequires(c, SameHostDaemon)
  134. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  135. name := "test_create_volume"
  136. dockerCmd(c, "create", "--name", name, "-v", prefix+slash+"foo", "busybox")
  137. dir, err := inspectMountSourceField(name, prefix+slash+"foo")
  138. c.Assert(err, check.IsNil, check.Commentf("Error getting volume host path: %q", err))
  139. if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
  140. c.Fatalf("Volume was not created")
  141. }
  142. if err != nil {
  143. c.Fatalf("Error statting volume host path: %q", err)
  144. }
  145. }
  146. func (s *DockerSuite) TestCreateLabels(c *check.C) {
  147. name := "test_create_labels"
  148. expected := map[string]string{"k1": "v1", "k2": "v2"}
  149. dockerCmd(c, "create", "--name", name, "-l", "k1=v1", "--label", "k2=v2", "busybox")
  150. actual := make(map[string]string)
  151. inspectFieldAndUnmarshall(c, name, "Config.Labels", &actual)
  152. if !reflect.DeepEqual(expected, actual) {
  153. c.Fatalf("Expected %s got %s", expected, actual)
  154. }
  155. }
  156. func (s *DockerSuite) TestCreateLabelFromImage(c *check.C) {
  157. imageName := "testcreatebuildlabel"
  158. buildImageSuccessfully(c, imageName, build.WithDockerfile(`FROM busybox
  159. LABEL k1=v1 k2=v2`))
  160. name := "test_create_labels_from_image"
  161. expected := map[string]string{"k2": "x", "k3": "v3", "k1": "v1"}
  162. dockerCmd(c, "create", "--name", name, "-l", "k2=x", "--label", "k3=v3", imageName)
  163. actual := make(map[string]string)
  164. inspectFieldAndUnmarshall(c, name, "Config.Labels", &actual)
  165. if !reflect.DeepEqual(expected, actual) {
  166. c.Fatalf("Expected %s got %s", expected, actual)
  167. }
  168. }
  169. func (s *DockerSuite) TestCreateHostnameWithNumber(c *check.C) {
  170. image := "busybox"
  171. // Busybox on Windows does not implement hostname command
  172. if testEnv.DaemonPlatform() == "windows" {
  173. image = testEnv.MinimalBaseImage()
  174. }
  175. out, _ := dockerCmd(c, "run", "-h", "web.0", image, "hostname")
  176. c.Assert(strings.TrimSpace(out), checker.Equals, "web.0", check.Commentf("hostname not set, expected `web.0`, got: %s", out))
  177. }
  178. func (s *DockerSuite) TestCreateRM(c *check.C) {
  179. // Test to make sure we can 'rm' a new container that is in
  180. // "Created" state, and has ever been run. Test "rm -f" too.
  181. // create a container
  182. out, _ := dockerCmd(c, "create", "busybox")
  183. cID := strings.TrimSpace(out)
  184. dockerCmd(c, "rm", cID)
  185. // Now do it again so we can "rm -f" this time
  186. out, _ = dockerCmd(c, "create", "busybox")
  187. cID = strings.TrimSpace(out)
  188. dockerCmd(c, "rm", "-f", cID)
  189. }
  190. func (s *DockerSuite) TestCreateModeIpcContainer(c *check.C) {
  191. // Uses Linux specific functionality (--ipc)
  192. testRequires(c, DaemonIsLinux, SameHostDaemon)
  193. out, _ := dockerCmd(c, "create", "busybox")
  194. id := strings.TrimSpace(out)
  195. dockerCmd(c, "create", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  196. }
  197. func (s *DockerSuite) TestCreateByImageID(c *check.C) {
  198. imageName := "testcreatebyimageid"
  199. buildImageSuccessfully(c, imageName, build.WithDockerfile(`FROM busybox
  200. MAINTAINER dockerio`))
  201. imageID := getIDByName(c, imageName)
  202. truncatedImageID := stringid.TruncateID(imageID)
  203. dockerCmd(c, "create", imageID)
  204. dockerCmd(c, "create", truncatedImageID)
  205. // Ensure this fails
  206. out, exit, _ := dockerCmdWithError("create", fmt.Sprintf("%s:%s", imageName, imageID))
  207. if exit == 0 {
  208. c.Fatalf("expected non-zero exit code; received %d", exit)
  209. }
  210. if expected := "invalid reference format"; !strings.Contains(out, expected) {
  211. c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  212. }
  213. if i := strings.IndexRune(imageID, ':'); i >= 0 {
  214. imageID = imageID[i+1:]
  215. }
  216. out, exit, _ = dockerCmdWithError("create", fmt.Sprintf("%s:%s", "wrongimage", imageID))
  217. if exit == 0 {
  218. c.Fatalf("expected non-zero exit code; received %d", exit)
  219. }
  220. if expected := "Unable to find image"; !strings.Contains(out, expected) {
  221. c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  222. }
  223. }
  224. func (s *DockerTrustSuite) TestTrustedCreate(c *check.C) {
  225. repoName := s.setupTrustedImage(c, "trusted-create")
  226. // Try create
  227. cli.Docker(cli.Args("create", repoName), trustedCmd).Assert(c, SuccessTagging)
  228. cli.DockerCmd(c, "rmi", repoName)
  229. // Try untrusted create to ensure we pushed the tag to the registry
  230. cli.Docker(cli.Args("create", "--disable-content-trust=true", repoName)).Assert(c, SuccessDownloadedOnStderr)
  231. }
  232. func (s *DockerTrustSuite) TestUntrustedCreate(c *check.C) {
  233. repoName := fmt.Sprintf("%v/dockercliuntrusted/createtest", privateRegistryURL)
  234. withTagName := fmt.Sprintf("%s:latest", repoName)
  235. // tag the image and upload it to the private registry
  236. cli.DockerCmd(c, "tag", "busybox", withTagName)
  237. cli.DockerCmd(c, "push", withTagName)
  238. cli.DockerCmd(c, "rmi", withTagName)
  239. // Try trusted create on untrusted tag
  240. cli.Docker(cli.Args("create", withTagName), trustedCmd).Assert(c, icmd.Expected{
  241. ExitCode: 1,
  242. Err: fmt.Sprintf("does not have trust data for %s", repoName),
  243. })
  244. }
  245. func (s *DockerTrustSuite) TestTrustedIsolatedCreate(c *check.C) {
  246. repoName := s.setupTrustedImage(c, "trusted-isolated-create")
  247. // Try create
  248. cli.Docker(cli.Args("--config", "/tmp/docker-isolated-create", "create", repoName), trustedCmd).Assert(c, SuccessTagging)
  249. defer os.RemoveAll("/tmp/docker-isolated-create")
  250. cli.DockerCmd(c, "rmi", repoName)
  251. }
  252. func (s *DockerTrustSuite) TestTrustedCreateFromBadTrustServer(c *check.C) {
  253. repoName := fmt.Sprintf("%v/dockerclievilcreate/trusted:latest", privateRegistryURL)
  254. evilLocalConfigDir, err := ioutil.TempDir("", "evilcreate-local-config-dir")
  255. c.Assert(err, check.IsNil)
  256. // tag the image and upload it to the private registry
  257. cli.DockerCmd(c, "tag", "busybox", repoName)
  258. cli.Docker(cli.Args("push", repoName), trustedCmd).Assert(c, SuccessSigningAndPushing)
  259. cli.DockerCmd(c, "rmi", repoName)
  260. // Try create
  261. cli.Docker(cli.Args("create", repoName), trustedCmd).Assert(c, SuccessTagging)
  262. cli.DockerCmd(c, "rmi", repoName)
  263. // Kill the notary server, start a new "evil" one.
  264. s.not.Close()
  265. s.not, err = newTestNotary(c)
  266. c.Assert(err, check.IsNil)
  267. // In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  268. // tag an image and upload it to the private registry
  269. cli.DockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  270. // Push up to the new server
  271. cli.Docker(cli.Args("--config", evilLocalConfigDir, "push", repoName), trustedCmd).Assert(c, SuccessSigningAndPushing)
  272. // Now, try creating with the original client from this new trust server. This should fail because the new root is invalid.
  273. cli.Docker(cli.Args("create", repoName), trustedCmd).Assert(c, icmd.Expected{
  274. ExitCode: 1,
  275. Err: "could not rotate trust to a new trusted root",
  276. })
  277. }
  278. func (s *DockerSuite) TestCreateStopSignal(c *check.C) {
  279. name := "test_create_stop_signal"
  280. dockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox")
  281. res := inspectFieldJSON(c, name, "Config.StopSignal")
  282. c.Assert(res, checker.Contains, "9")
  283. }
  284. func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) {
  285. name := "foo"
  286. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  287. dir := prefix + slash + "home" + slash + "foo" + slash + "bar"
  288. dockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
  289. // Windows does not create the workdir until the container is started
  290. if testEnv.DaemonPlatform() == "windows" {
  291. dockerCmd(c, "start", name)
  292. }
  293. dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp")
  294. }
  295. func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *check.C) {
  296. name := "test-invalidate-log-opts"
  297. out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox")
  298. c.Assert(err, checker.NotNil)
  299. c.Assert(out, checker.Contains, "unknown log opt")
  300. out, _ = dockerCmd(c, "ps", "-a")
  301. c.Assert(out, checker.Not(checker.Contains), name)
  302. }
  303. // #20972
  304. func (s *DockerSuite) TestCreate64ByteHexID(c *check.C) {
  305. out := inspectField(c, "busybox", "Id")
  306. imageID := strings.TrimPrefix(strings.TrimSpace(string(out)), "sha256:")
  307. dockerCmd(c, "create", imageID)
  308. }
  309. // Test case for #23498
  310. func (s *DockerSuite) TestCreateUnsetEntrypoint(c *check.C) {
  311. name := "test-entrypoint"
  312. dockerfile := `FROM busybox
  313. ADD entrypoint.sh /entrypoint.sh
  314. RUN chmod 755 /entrypoint.sh
  315. ENTRYPOINT ["/entrypoint.sh"]
  316. CMD echo foobar`
  317. ctx := fakecontext.New(c, "",
  318. fakecontext.WithDockerfile(dockerfile),
  319. fakecontext.WithFiles(map[string]string{
  320. "entrypoint.sh": `#!/bin/sh
  321. echo "I am an entrypoint"
  322. exec "$@"`,
  323. }))
  324. defer ctx.Close()
  325. cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  326. out := cli.DockerCmd(c, "create", "--entrypoint=", name, "echo", "foo").Combined()
  327. id := strings.TrimSpace(out)
  328. c.Assert(id, check.Not(check.Equals), "")
  329. out = cli.DockerCmd(c, "start", "-a", id).Combined()
  330. c.Assert(strings.TrimSpace(out), check.Equals, "foo")
  331. }
  332. // #22471
  333. func (s *DockerSuite) TestCreateStopTimeout(c *check.C) {
  334. name1 := "test_create_stop_timeout_1"
  335. dockerCmd(c, "create", "--name", name1, "--stop-timeout", "15", "busybox")
  336. res := inspectFieldJSON(c, name1, "Config.StopTimeout")
  337. c.Assert(res, checker.Contains, "15")
  338. name2 := "test_create_stop_timeout_2"
  339. dockerCmd(c, "create", "--name", name2, "busybox")
  340. res = inspectFieldJSON(c, name2, "Config.StopTimeout")
  341. c.Assert(res, checker.Contains, "null")
  342. }