docker_cli_create_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "reflect"
  7. "strings"
  8. "time"
  9. "os/exec"
  10. "io/ioutil"
  11. "github.com/docker/docker/pkg/integration"
  12. "github.com/docker/docker/pkg/integration/checker"
  13. "github.com/docker/docker/pkg/stringid"
  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 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. inspectFieldAndMarshall(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. inspectFieldAndMarshall(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 daemonPlatform == "windows" {
  174. image = WindowsBaseImage
  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. createCmd := exec.Command(dockerBinary, "create", repoName)
  231. s.trustedCmd(createCmd)
  232. out, _, err := runCommandWithOutput(createCmd)
  233. c.Assert(err, check.IsNil)
  234. c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))
  235. dockerCmd(c, "rmi", repoName)
  236. // Try untrusted create to ensure we pushed the tag to the registry
  237. createCmd = exec.Command(dockerBinary, "create", "--disable-content-trust=true", repoName)
  238. s.trustedCmd(createCmd)
  239. out, _, err = runCommandWithOutput(createCmd)
  240. c.Assert(err, check.IsNil)
  241. c.Assert(string(out), checker.Contains, "Status: Downloaded", check.Commentf("Missing expected output on trusted create with --disable-content-trust:\n%s", out))
  242. }
  243. func (s *DockerTrustSuite) TestUntrustedCreate(c *check.C) {
  244. repoName := fmt.Sprintf("%v/dockercliuntrusted/createtest", privateRegistryURL)
  245. withTagName := fmt.Sprintf("%s:latest", repoName)
  246. // tag the image and upload it to the private registry
  247. dockerCmd(c, "tag", "busybox", withTagName)
  248. dockerCmd(c, "push", withTagName)
  249. dockerCmd(c, "rmi", withTagName)
  250. // Try trusted create on untrusted tag
  251. createCmd := exec.Command(dockerBinary, "create", withTagName)
  252. s.trustedCmd(createCmd)
  253. out, _, err := runCommandWithOutput(createCmd)
  254. c.Assert(err, check.Not(check.IsNil))
  255. c.Assert(string(out), checker.Contains, fmt.Sprintf("does not have trust data for %s", repoName), check.Commentf("Missing expected output on trusted create:\n%s", out))
  256. }
  257. func (s *DockerTrustSuite) TestTrustedIsolatedCreate(c *check.C) {
  258. repoName := s.setupTrustedImage(c, "trusted-isolated-create")
  259. // Try create
  260. createCmd := exec.Command(dockerBinary, "--config", "/tmp/docker-isolated-create", "create", repoName)
  261. s.trustedCmd(createCmd)
  262. out, _, err := runCommandWithOutput(createCmd)
  263. c.Assert(err, check.IsNil)
  264. c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))
  265. dockerCmd(c, "rmi", repoName)
  266. }
  267. func (s *DockerTrustSuite) TestCreateWhenCertExpired(c *check.C) {
  268. c.Skip("Currently changes system time, causing instability")
  269. repoName := s.setupTrustedImage(c, "trusted-create-expired")
  270. // Certificates have 10 years of expiration
  271. elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)
  272. integration.RunAtDifferentDate(elevenYearsFromNow, func() {
  273. // Try create
  274. createCmd := exec.Command(dockerBinary, "create", repoName)
  275. s.trustedCmd(createCmd)
  276. out, _, err := runCommandWithOutput(createCmd)
  277. c.Assert(err, check.Not(check.IsNil))
  278. c.Assert(string(out), checker.Contains, "could not validate the path to a trusted root", check.Commentf("Missing expected output on trusted create in the distant future:\n%s", out))
  279. })
  280. integration.RunAtDifferentDate(elevenYearsFromNow, func() {
  281. // Try create
  282. createCmd := exec.Command(dockerBinary, "create", "--disable-content-trust", repoName)
  283. s.trustedCmd(createCmd)
  284. out, _, err := runCommandWithOutput(createCmd)
  285. c.Assert(err, check.Not(check.IsNil))
  286. c.Assert(string(out), checker.Contains, "Status: Downloaded", check.Commentf("Missing expected output on trusted create in the distant future:\n%s", out))
  287. })
  288. }
  289. func (s *DockerTrustSuite) TestTrustedCreateFromBadTrustServer(c *check.C) {
  290. repoName := fmt.Sprintf("%v/dockerclievilcreate/trusted:latest", privateRegistryURL)
  291. evilLocalConfigDir, err := ioutil.TempDir("", "evilcreate-local-config-dir")
  292. c.Assert(err, check.IsNil)
  293. // tag the image and upload it to the private registry
  294. dockerCmd(c, "tag", "busybox", repoName)
  295. pushCmd := exec.Command(dockerBinary, "push", repoName)
  296. s.trustedCmd(pushCmd)
  297. out, _, err := runCommandWithOutput(pushCmd)
  298. c.Assert(err, check.IsNil)
  299. c.Assert(string(out), checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push:\n%s", out))
  300. dockerCmd(c, "rmi", repoName)
  301. // Try create
  302. createCmd := exec.Command(dockerBinary, "create", repoName)
  303. s.trustedCmd(createCmd)
  304. out, _, err = runCommandWithOutput(createCmd)
  305. c.Assert(err, check.IsNil)
  306. c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))
  307. dockerCmd(c, "rmi", repoName)
  308. // Kill the notary server, start a new "evil" one.
  309. s.not.Close()
  310. s.not, err = newTestNotary(c)
  311. c.Assert(err, check.IsNil)
  312. // In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  313. // tag an image and upload it to the private registry
  314. dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  315. // Push up to the new server
  316. pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName)
  317. s.trustedCmd(pushCmd)
  318. out, _, err = runCommandWithOutput(pushCmd)
  319. c.Assert(err, check.IsNil)
  320. c.Assert(string(out), checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push:\n%s", out))
  321. // Now, try creating with the original client from this new trust server. This should fail because the new root is invalid.
  322. createCmd = exec.Command(dockerBinary, "create", repoName)
  323. s.trustedCmd(createCmd)
  324. out, _, err = runCommandWithOutput(createCmd)
  325. if err == nil {
  326. c.Fatalf("Continuing with cached data even though it's an invalid root rotation: %s\n%s", err, out)
  327. }
  328. if !strings.Contains(out, "could not rotate trust to a new trusted root") {
  329. c.Fatalf("Missing expected output on trusted create:\n%s", out)
  330. }
  331. }
  332. func (s *DockerSuite) TestCreateStopSignal(c *check.C) {
  333. name := "test_create_stop_signal"
  334. dockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox")
  335. res := inspectFieldJSON(c, name, "Config.StopSignal")
  336. c.Assert(res, checker.Contains, "9")
  337. }
  338. func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) {
  339. name := "foo"
  340. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  341. dir := prefix + slash + "home" + slash + "foo" + slash + "bar"
  342. dockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
  343. // Windows does not create the workdir until the container is started
  344. if daemonPlatform == "windows" {
  345. dockerCmd(c, "start", name)
  346. }
  347. dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp")
  348. }
  349. func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *check.C) {
  350. name := "test-invalidate-log-opts"
  351. out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox")
  352. c.Assert(err, checker.NotNil)
  353. c.Assert(out, checker.Contains, "unknown log opt")
  354. out, _ = dockerCmd(c, "ps", "-a")
  355. c.Assert(out, checker.Not(checker.Contains), name)
  356. }
  357. // #20972
  358. func (s *DockerSuite) TestCreate64ByteHexID(c *check.C) {
  359. out := inspectField(c, "busybox", "Id")
  360. imageID := strings.TrimPrefix(strings.TrimSpace(string(out)), "sha256:")
  361. dockerCmd(c, "create", imageID)
  362. }
  363. // Test case for #23498
  364. func (s *DockerSuite) TestCreateUnsetEntrypoint(c *check.C) {
  365. name := "test-entrypoint"
  366. dockerfile := `FROM busybox
  367. ADD entrypoint.sh /entrypoint.sh
  368. RUN chmod 755 /entrypoint.sh
  369. ENTRYPOINT ["/entrypoint.sh"]
  370. CMD echo foobar`
  371. ctx, err := fakeContext(dockerfile, map[string]string{
  372. "entrypoint.sh": `#!/bin/sh
  373. echo "I am an entrypoint"
  374. exec "$@"`,
  375. })
  376. c.Assert(err, check.IsNil)
  377. defer ctx.Close()
  378. _, err = buildImageFromContext(name, ctx, true)
  379. c.Assert(err, check.IsNil)
  380. out, _ := dockerCmd(c, "create", "--entrypoint=", name, "echo", "foo")
  381. id := strings.TrimSpace(out)
  382. c.Assert(id, check.Not(check.Equals), "")
  383. out, _ = dockerCmd(c, "start", "-a", id)
  384. c.Assert(strings.TrimSpace(out), check.Equals, "foo")
  385. }
  386. // #22471
  387. func (s *DockerSuite) TestCreateStopTimeout(c *check.C) {
  388. name1 := "test_create_stop_timeout_1"
  389. dockerCmd(c, "create", "--name", name1, "--stop-timeout", "15", "busybox")
  390. res := inspectFieldJSON(c, name1, "Config.StopTimeout")
  391. c.Assert(res, checker.Contains, "15")
  392. name2 := "test_create_stop_timeout_2"
  393. dockerCmd(c, "create", "--name", name2, "busybox")
  394. res = inspectFieldJSON(c, name2, "Config.StopTimeout")
  395. c.Assert(res, checker.Contains, "null")
  396. }