docker_cli_create_test.go 17 KB

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