docker_cli_create_test.go 16 KB

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