docker_cli_create_test.go 16 KB

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