docker_cli_create_test.go 16 KB

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