docker_cli_create_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. buildImageSuccessfully(c, imageName, withDockerfile(`FROM busybox
  157. LABEL k1=v1 k2=v2`))
  158. name := "test_create_labels_from_image"
  159. expected := map[string]string{"k2": "x", "k3": "v3", "k1": "v1"}
  160. dockerCmd(c, "create", "--name", name, "-l", "k2=x", "--label", "k3=v3", imageName)
  161. actual := make(map[string]string)
  162. inspectFieldAndUnmarshall(c, name, "Config.Labels", &actual)
  163. if !reflect.DeepEqual(expected, actual) {
  164. c.Fatalf("Expected %s got %s", expected, actual)
  165. }
  166. }
  167. func (s *DockerSuite) TestCreateHostnameWithNumber(c *check.C) {
  168. image := "busybox"
  169. // Busybox on Windows does not implement hostname command
  170. if testEnv.DaemonPlatform() == "windows" {
  171. image = testEnv.MinimalBaseImage()
  172. }
  173. out, _ := dockerCmd(c, "run", "-h", "web.0", image, "hostname")
  174. c.Assert(strings.TrimSpace(out), checker.Equals, "web.0", check.Commentf("hostname not set, expected `web.0`, got: %s", out))
  175. }
  176. func (s *DockerSuite) TestCreateRM(c *check.C) {
  177. // Test to make sure we can 'rm' a new container that is in
  178. // "Created" state, and has ever been run. Test "rm -f" too.
  179. // create a container
  180. out, _ := dockerCmd(c, "create", "busybox")
  181. cID := strings.TrimSpace(out)
  182. dockerCmd(c, "rm", cID)
  183. // Now do it again so we can "rm -f" this time
  184. out, _ = dockerCmd(c, "create", "busybox")
  185. cID = strings.TrimSpace(out)
  186. dockerCmd(c, "rm", "-f", cID)
  187. }
  188. func (s *DockerSuite) TestCreateModeIpcContainer(c *check.C) {
  189. // Uses Linux specific functionality (--ipc)
  190. testRequires(c, DaemonIsLinux, SameHostDaemon)
  191. out, _ := dockerCmd(c, "create", "busybox")
  192. id := strings.TrimSpace(out)
  193. dockerCmd(c, "create", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  194. }
  195. func (s *DockerSuite) TestCreateByImageID(c *check.C) {
  196. imageName := "testcreatebyimageid"
  197. buildImageSuccessfully(c, imageName, withDockerfile(`FROM busybox
  198. MAINTAINER dockerio`))
  199. imageID := getIDByName(c, imageName)
  200. truncatedImageID := stringid.TruncateID(imageID)
  201. dockerCmd(c, "create", imageID)
  202. dockerCmd(c, "create", truncatedImageID)
  203. dockerCmd(c, "create", fmt.Sprintf("%s:%s", imageName, truncatedImageID))
  204. // Ensure this fails
  205. out, exit, _ := dockerCmdWithError("create", fmt.Sprintf("%s:%s", imageName, imageID))
  206. if exit == 0 {
  207. c.Fatalf("expected non-zero exit code; received %d", exit)
  208. }
  209. if expected := "invalid reference format"; !strings.Contains(out, expected) {
  210. c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  211. }
  212. out, exit, _ = dockerCmdWithError("create", fmt.Sprintf("%s:%s", "wrongimage", truncatedImageID))
  213. if exit == 0 {
  214. c.Fatalf("expected non-zero exit code; received %d", exit)
  215. }
  216. if expected := "Unable to find image"; !strings.Contains(out, expected) {
  217. c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  218. }
  219. }
  220. func (s *DockerTrustSuite) TestTrustedCreate(c *check.C) {
  221. repoName := s.setupTrustedImage(c, "trusted-create")
  222. // Try create
  223. icmd.RunCmd(icmd.Command(dockerBinary, "create", repoName), trustedCmd).Assert(c, SuccessTagging)
  224. dockerCmd(c, "rmi", repoName)
  225. // Try untrusted create to ensure we pushed the tag to the registry
  226. icmd.RunCmd(icmd.Command(dockerBinary, "create", "--disable-content-trust=true", repoName), trustedCmd).Assert(c, SuccessDownloadedOnStderr)
  227. }
  228. func (s *DockerTrustSuite) TestUntrustedCreate(c *check.C) {
  229. repoName := fmt.Sprintf("%v/dockercliuntrusted/createtest", privateRegistryURL)
  230. withTagName := fmt.Sprintf("%s:latest", repoName)
  231. // tag the image and upload it to the private registry
  232. dockerCmd(c, "tag", "busybox", withTagName)
  233. dockerCmd(c, "push", withTagName)
  234. dockerCmd(c, "rmi", withTagName)
  235. // Try trusted create on untrusted tag
  236. icmd.RunCmd(icmd.Command(dockerBinary, "create", withTagName), trustedCmd).Assert(c, icmd.Expected{
  237. ExitCode: 1,
  238. Err: fmt.Sprintf("does not have trust data for %s", repoName),
  239. })
  240. }
  241. func (s *DockerTrustSuite) TestTrustedIsolatedCreate(c *check.C) {
  242. repoName := s.setupTrustedImage(c, "trusted-isolated-create")
  243. // Try create
  244. icmd.RunCmd(icmd.Command(dockerBinary, "--config", "/tmp/docker-isolated-create", "create", repoName), trustedCmd).Assert(c, SuccessTagging)
  245. dockerCmd(c, "rmi", repoName)
  246. }
  247. func (s *DockerTrustSuite) TestCreateWhenCertExpired(c *check.C) {
  248. c.Skip("Currently changes system time, causing instability")
  249. repoName := s.setupTrustedImage(c, "trusted-create-expired")
  250. // Certificates have 10 years of expiration
  251. elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)
  252. testutil.RunAtDifferentDate(elevenYearsFromNow, func() {
  253. // Try create
  254. icmd.RunCmd(icmd.Cmd{
  255. Command: []string{dockerBinary, "create", repoName},
  256. }, trustedCmd).Assert(c, icmd.Expected{
  257. ExitCode: 1,
  258. Err: "could not validate the path to a trusted root",
  259. })
  260. })
  261. testutil.RunAtDifferentDate(elevenYearsFromNow, func() {
  262. // Try create
  263. result := icmd.RunCmd(icmd.Command(dockerBinary, "create", "--disable-content-trust", repoName), trustedCmd)
  264. c.Assert(result.Error, check.Not(check.IsNil))
  265. 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()))
  266. })
  267. }
  268. func (s *DockerTrustSuite) TestTrustedCreateFromBadTrustServer(c *check.C) {
  269. repoName := fmt.Sprintf("%v/dockerclievilcreate/trusted:latest", privateRegistryURL)
  270. evilLocalConfigDir, err := ioutil.TempDir("", "evilcreate-local-config-dir")
  271. c.Assert(err, check.IsNil)
  272. // tag the image and upload it to the private registry
  273. dockerCmd(c, "tag", "busybox", repoName)
  274. icmd.RunCmd(icmd.Command(dockerBinary, "push", repoName), trustedCmd).Assert(c, SuccessSigningAndPushing)
  275. dockerCmd(c, "rmi", repoName)
  276. // Try create
  277. icmd.RunCmd(icmd.Command(dockerBinary, "create", repoName), trustedCmd).Assert(c, SuccessTagging)
  278. dockerCmd(c, "rmi", repoName)
  279. // Kill the notary server, start a new "evil" one.
  280. s.not.Close()
  281. s.not, err = newTestNotary(c)
  282. c.Assert(err, check.IsNil)
  283. // In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  284. // tag an image and upload it to the private registry
  285. dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  286. // Push up to the new server
  287. icmd.RunCmd(icmd.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName), trustedCmd).Assert(c, SuccessSigningAndPushing)
  288. // Now, try creating with the original client from this new trust server. This should fail because the new root is invalid.
  289. icmd.RunCmd(icmd.Command(dockerBinary, "create", repoName), trustedCmd).Assert(c, icmd.Expected{
  290. ExitCode: 1,
  291. Err: "could not rotate trust to a new trusted root",
  292. })
  293. }
  294. func (s *DockerSuite) TestCreateStopSignal(c *check.C) {
  295. name := "test_create_stop_signal"
  296. dockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox")
  297. res := inspectFieldJSON(c, name, "Config.StopSignal")
  298. c.Assert(res, checker.Contains, "9")
  299. }
  300. func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) {
  301. name := "foo"
  302. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  303. dir := prefix + slash + "home" + slash + "foo" + slash + "bar"
  304. dockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
  305. // Windows does not create the workdir until the container is started
  306. if testEnv.DaemonPlatform() == "windows" {
  307. dockerCmd(c, "start", name)
  308. }
  309. dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp")
  310. }
  311. func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *check.C) {
  312. name := "test-invalidate-log-opts"
  313. out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox")
  314. c.Assert(err, checker.NotNil)
  315. c.Assert(out, checker.Contains, "unknown log opt")
  316. out, _ = dockerCmd(c, "ps", "-a")
  317. c.Assert(out, checker.Not(checker.Contains), name)
  318. }
  319. // #20972
  320. func (s *DockerSuite) TestCreate64ByteHexID(c *check.C) {
  321. out := inspectField(c, "busybox", "Id")
  322. imageID := strings.TrimPrefix(strings.TrimSpace(string(out)), "sha256:")
  323. dockerCmd(c, "create", imageID)
  324. }
  325. // Test case for #23498
  326. func (s *DockerSuite) TestCreateUnsetEntrypoint(c *check.C) {
  327. name := "test-entrypoint"
  328. dockerfile := `FROM busybox
  329. ADD entrypoint.sh /entrypoint.sh
  330. RUN chmod 755 /entrypoint.sh
  331. ENTRYPOINT ["/entrypoint.sh"]
  332. CMD echo foobar`
  333. ctx := fakeContext(c, dockerfile, map[string]string{
  334. "entrypoint.sh": `#!/bin/sh
  335. echo "I am an entrypoint"
  336. exec "$@"`,
  337. })
  338. defer ctx.Close()
  339. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  340. out, _ := dockerCmd(c, "create", "--entrypoint=", name, "echo", "foo")
  341. id := strings.TrimSpace(out)
  342. c.Assert(id, check.Not(check.Equals), "")
  343. out, _ = dockerCmd(c, "start", "-a", id)
  344. c.Assert(strings.TrimSpace(out), check.Equals, "foo")
  345. }
  346. // #22471
  347. func (s *DockerSuite) TestCreateStopTimeout(c *check.C) {
  348. name1 := "test_create_stop_timeout_1"
  349. dockerCmd(c, "create", "--name", name1, "--stop-timeout", "15", "busybox")
  350. res := inspectFieldJSON(c, name1, "Config.StopTimeout")
  351. c.Assert(res, checker.Contains, "15")
  352. name2 := "test_create_stop_timeout_2"
  353. dockerCmd(c, "create", "--name", name2, "busybox")
  354. res = inspectFieldJSON(c, name2, "Config.StopTimeout")
  355. c.Assert(res, checker.Contains, "null")
  356. }