docker_cli_create_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. // TODO Windows. This requires further investigation for porting to
  19. // Windows CI. Currently fails.
  20. if daemonPlatform == "windows" {
  21. c.Skip("Fails on Windows CI")
  22. }
  23. out, _ := dockerCmd(c, "create", "busybox", "command", "arg1", "arg2", "arg with space", "-c", "flags")
  24. cleanedContainerID := strings.TrimSpace(out)
  25. out, _ = dockerCmd(c, "inspect", cleanedContainerID)
  26. containers := []struct {
  27. ID string
  28. Created time.Time
  29. Path string
  30. Args []string
  31. Image string
  32. }{}
  33. err := json.Unmarshal([]byte(out), &containers)
  34. c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
  35. c.Assert(containers, checker.HasLen, 1)
  36. cont := containers[0]
  37. c.Assert(string(cont.Path), checker.Equals, "command", check.Commentf("Unexpected container path. Expected command, received: %s", cont.Path))
  38. b := false
  39. expected := []string{"arg1", "arg2", "arg with space", "-c", "flags"}
  40. for i, arg := range expected {
  41. if arg != cont.Args[i] {
  42. b = true
  43. break
  44. }
  45. }
  46. if len(cont.Args) != len(expected) || b {
  47. c.Fatalf("Unexpected args. Expected %v, received: %v", expected, cont.Args)
  48. }
  49. }
  50. // Make sure we can grow the container's rootfs at creation time.
  51. func (s *DockerSuite) TestCreateGrowRootfs(c *check.C) {
  52. testRequires(c, Devicemapper)
  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 := "/"
  133. if daemonPlatform == "windows" {
  134. prefix = `c:\`
  135. }
  136. name := "test_create_volume"
  137. dockerCmd(c, "create", "--name", name, "-v", prefix+"foo", "busybox")
  138. dir, err := inspectMountSourceField(name, prefix+"foo")
  139. c.Assert(err, check.IsNil, check.Commentf("Error getting volume host path: %q", err))
  140. if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
  141. c.Fatalf("Volume was not created")
  142. }
  143. if err != nil {
  144. c.Fatalf("Error statting volume host path: %q", err)
  145. }
  146. }
  147. func (s *DockerSuite) TestCreateLabels(c *check.C) {
  148. name := "test_create_labels"
  149. expected := map[string]string{"k1": "v1", "k2": "v2"}
  150. dockerCmd(c, "create", "--name", name, "-l", "k1=v1", "--label", "k2=v2", "busybox")
  151. actual := make(map[string]string)
  152. inspectFieldAndMarshall(c, name, "Config.Labels", &actual)
  153. if !reflect.DeepEqual(expected, actual) {
  154. c.Fatalf("Expected %s got %s", expected, actual)
  155. }
  156. }
  157. func (s *DockerSuite) TestCreateLabelFromImage(c *check.C) {
  158. imageName := "testcreatebuildlabel"
  159. _, err := buildImage(imageName,
  160. `FROM busybox
  161. LABEL k1=v1 k2=v2`,
  162. true)
  163. c.Assert(err, check.IsNil)
  164. name := "test_create_labels_from_image"
  165. expected := map[string]string{"k2": "x", "k3": "v3", "k1": "v1"}
  166. dockerCmd(c, "create", "--name", name, "-l", "k2=x", "--label", "k3=v3", imageName)
  167. actual := make(map[string]string)
  168. inspectFieldAndMarshall(c, name, "Config.Labels", &actual)
  169. if !reflect.DeepEqual(expected, actual) {
  170. c.Fatalf("Expected %s got %s", expected, actual)
  171. }
  172. }
  173. func (s *DockerSuite) TestCreateHostnameWithNumber(c *check.C) {
  174. // TODO Windows. Consider enabling this in TP5 timeframe if Windows support
  175. // is fully hooked up. The hostname is passed through, but only to the
  176. // environment variable "COMPUTERNAME". It is not hooked up to hostname.exe
  177. // or returned in ipconfig. Needs platform support in networking.
  178. testRequires(c, DaemonIsLinux)
  179. out, _ := dockerCmd(c, "run", "-h", "web.0", "busybox", "hostname")
  180. c.Assert(strings.TrimSpace(out), checker.Equals, "web.0", check.Commentf("hostname not set, expected `web.0`, got: %s", out))
  181. }
  182. func (s *DockerSuite) TestCreateRM(c *check.C) {
  183. // Test to make sure we can 'rm' a new container that is in
  184. // "Created" state, and has ever been run. Test "rm -f" too.
  185. // create a container
  186. out, _ := dockerCmd(c, "create", "busybox")
  187. cID := strings.TrimSpace(out)
  188. dockerCmd(c, "rm", cID)
  189. // Now do it again so we can "rm -f" this time
  190. out, _ = dockerCmd(c, "create", "busybox")
  191. cID = strings.TrimSpace(out)
  192. dockerCmd(c, "rm", "-f", cID)
  193. }
  194. func (s *DockerSuite) TestCreateModeIpcContainer(c *check.C) {
  195. // Uses Linux specific functionality (--ipc)
  196. testRequires(c, DaemonIsLinux, SameHostDaemon)
  197. out, _ := dockerCmd(c, "create", "busybox")
  198. id := strings.TrimSpace(out)
  199. dockerCmd(c, "create", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  200. }
  201. func (s *DockerSuite) TestCreateByImageID(c *check.C) {
  202. imageName := "testcreatebyimageid"
  203. imageID, err := buildImage(imageName,
  204. `FROM busybox
  205. MAINTAINER dockerio`,
  206. true)
  207. if err != nil {
  208. c.Fatal(err)
  209. }
  210. truncatedImageID := stringid.TruncateID(imageID)
  211. dockerCmd(c, "create", imageID)
  212. dockerCmd(c, "create", truncatedImageID)
  213. dockerCmd(c, "create", fmt.Sprintf("%s:%s", imageName, truncatedImageID))
  214. // Ensure this fails
  215. out, exit, _ := dockerCmdWithError("create", fmt.Sprintf("%s:%s", imageName, imageID))
  216. if exit == 0 {
  217. c.Fatalf("expected non-zero exit code; received %d", exit)
  218. }
  219. if expected := "Error parsing reference"; !strings.Contains(out, expected) {
  220. c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  221. }
  222. out, exit, _ = dockerCmdWithError("create", fmt.Sprintf("%s:%s", "wrongimage", truncatedImageID))
  223. if exit == 0 {
  224. c.Fatalf("expected non-zero exit code; received %d", exit)
  225. }
  226. if expected := "Unable to find image"; !strings.Contains(out, expected) {
  227. c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  228. }
  229. }
  230. func (s *DockerTrustSuite) TestTrustedCreate(c *check.C) {
  231. repoName := s.setupTrustedImage(c, "trusted-create")
  232. // Try create
  233. createCmd := exec.Command(dockerBinary, "create", repoName)
  234. s.trustedCmd(createCmd)
  235. out, _, err := runCommandWithOutput(createCmd)
  236. c.Assert(err, check.IsNil)
  237. c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))
  238. dockerCmd(c, "rmi", repoName)
  239. // Try untrusted create to ensure we pushed the tag to the registry
  240. createCmd = exec.Command(dockerBinary, "create", "--disable-content-trust=true", repoName)
  241. s.trustedCmd(createCmd)
  242. out, _, err = runCommandWithOutput(createCmd)
  243. c.Assert(err, check.IsNil)
  244. c.Assert(string(out), checker.Contains, "Status: Downloaded", check.Commentf("Missing expected output on trusted create with --disable-content-trust:\n%s", out))
  245. }
  246. func (s *DockerTrustSuite) TestUntrustedCreate(c *check.C) {
  247. repoName := fmt.Sprintf("%v/dockercliuntrusted/createtest", privateRegistryURL)
  248. withTagName := fmt.Sprintf("%s:latest", repoName)
  249. // tag the image and upload it to the private registry
  250. dockerCmd(c, "tag", "busybox", withTagName)
  251. dockerCmd(c, "push", withTagName)
  252. dockerCmd(c, "rmi", withTagName)
  253. // Try trusted create on untrusted tag
  254. createCmd := exec.Command(dockerBinary, "create", withTagName)
  255. s.trustedCmd(createCmd)
  256. out, _, err := runCommandWithOutput(createCmd)
  257. c.Assert(err, check.Not(check.IsNil))
  258. 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))
  259. }
  260. func (s *DockerTrustSuite) TestTrustedIsolatedCreate(c *check.C) {
  261. repoName := s.setupTrustedImage(c, "trusted-isolated-create")
  262. // Try create
  263. createCmd := exec.Command(dockerBinary, "--config", "/tmp/docker-isolated-create", "create", repoName)
  264. s.trustedCmd(createCmd)
  265. out, _, err := runCommandWithOutput(createCmd)
  266. c.Assert(err, check.IsNil)
  267. c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))
  268. dockerCmd(c, "rmi", repoName)
  269. }
  270. func (s *DockerTrustSuite) TestCreateWhenCertExpired(c *check.C) {
  271. c.Skip("Currently changes system time, causing instability")
  272. repoName := s.setupTrustedImage(c, "trusted-create-expired")
  273. // Certificates have 10 years of expiration
  274. elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)
  275. runAtDifferentDate(elevenYearsFromNow, func() {
  276. // Try create
  277. createCmd := exec.Command(dockerBinary, "create", repoName)
  278. s.trustedCmd(createCmd)
  279. out, _, err := runCommandWithOutput(createCmd)
  280. c.Assert(err, check.Not(check.IsNil))
  281. 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))
  282. })
  283. runAtDifferentDate(elevenYearsFromNow, func() {
  284. // Try create
  285. createCmd := exec.Command(dockerBinary, "create", "--disable-content-trust", repoName)
  286. s.trustedCmd(createCmd)
  287. out, _, err := runCommandWithOutput(createCmd)
  288. c.Assert(err, check.Not(check.IsNil))
  289. c.Assert(string(out), checker.Contains, "Status: Downloaded", check.Commentf("Missing expected output on trusted create in the distant future:\n%s", out))
  290. })
  291. }
  292. func (s *DockerTrustSuite) TestTrustedCreateFromBadTrustServer(c *check.C) {
  293. repoName := fmt.Sprintf("%v/dockerclievilcreate/trusted:latest", privateRegistryURL)
  294. evilLocalConfigDir, err := ioutil.TempDir("", "evilcreate-local-config-dir")
  295. c.Assert(err, check.IsNil)
  296. // tag the image and upload it to the private registry
  297. dockerCmd(c, "tag", "busybox", repoName)
  298. pushCmd := exec.Command(dockerBinary, "push", repoName)
  299. s.trustedCmd(pushCmd)
  300. out, _, err := runCommandWithOutput(pushCmd)
  301. c.Assert(err, check.IsNil)
  302. c.Assert(string(out), checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push:\n%s", out))
  303. dockerCmd(c, "rmi", repoName)
  304. // Try create
  305. createCmd := exec.Command(dockerBinary, "create", repoName)
  306. s.trustedCmd(createCmd)
  307. out, _, err = runCommandWithOutput(createCmd)
  308. c.Assert(err, check.IsNil)
  309. c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))
  310. dockerCmd(c, "rmi", repoName)
  311. // Kill the notary server, start a new "evil" one.
  312. s.not.Close()
  313. s.not, err = newTestNotary(c)
  314. c.Assert(err, check.IsNil)
  315. // In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  316. // tag an image and upload it to the private registry
  317. dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  318. // Push up to the new server
  319. pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName)
  320. s.trustedCmd(pushCmd)
  321. out, _, err = runCommandWithOutput(pushCmd)
  322. c.Assert(err, check.IsNil)
  323. c.Assert(string(out), checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push:\n%s", out))
  324. // Now, try creating with the original client from this new trust server. This should fallback to our cached timestamp and metadata.
  325. createCmd = exec.Command(dockerBinary, "create", repoName)
  326. s.trustedCmd(createCmd)
  327. out, _, err = runCommandWithOutput(createCmd)
  328. if err != nil {
  329. c.Fatalf("Error falling back to cached trust data: %s\n%s", err, out)
  330. }
  331. if !strings.Contains(string(out), "Error while downloading remote metadata, using cached timestamp") {
  332. c.Fatalf("Missing expected output on trusted create:\n%s", out)
  333. }
  334. }
  335. func (s *DockerSuite) TestCreateStopSignal(c *check.C) {
  336. name := "test_create_stop_signal"
  337. dockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox")
  338. res := inspectFieldJSON(c, name, "Config.StopSignal")
  339. c.Assert(res, checker.Contains, "9")
  340. }
  341. func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) {
  342. // TODO Windows. This requires further investigation for porting to
  343. // Windows CI. Currently fails.
  344. if daemonPlatform == "windows" {
  345. c.Skip("Fails on Windows CI")
  346. }
  347. name := "foo"
  348. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  349. dir := prefix + slash + "home" + slash + "foo" + slash + "bar"
  350. dockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
  351. dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp")
  352. }
  353. func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *check.C) {
  354. name := "test-invalidate-log-opts"
  355. out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox")
  356. c.Assert(err, checker.NotNil)
  357. c.Assert(out, checker.Contains, "unknown log opt")
  358. out, _ = dockerCmd(c, "ps", "-a")
  359. c.Assert(out, checker.Not(checker.Contains), name)
  360. }
  361. // #20972
  362. func (s *DockerSuite) TestCreate64ByteHexID(c *check.C) {
  363. out := inspectField(c, "busybox", "Id")
  364. imageID := strings.TrimPrefix(strings.TrimSpace(string(out)), "sha256:")
  365. dockerCmd(c, "create", imageID)
  366. }
  367. // Test case for #23498
  368. func (s *DockerSuite) TestCreateUnsetEntrypoint(c *check.C) {
  369. name := "test-entrypoint"
  370. dockerfile := `FROM busybox
  371. ADD entrypoint.sh /entrypoint.sh
  372. RUN chmod 755 /entrypoint.sh
  373. ENTRYPOINT ["/entrypoint.sh"]
  374. CMD echo foobar`
  375. ctx, err := fakeContext(dockerfile, map[string]string{
  376. "entrypoint.sh": `#!/bin/sh
  377. echo "I am an entrypoint"
  378. exec "$@"`,
  379. })
  380. c.Assert(err, check.IsNil)
  381. defer ctx.Close()
  382. _, err = buildImageFromContext(name, ctx, true)
  383. c.Assert(err, check.IsNil)
  384. out, _ := dockerCmd(c, "create", "--entrypoint=", name, "echo", "foo")
  385. id := strings.TrimSpace(out)
  386. c.Assert(id, check.Not(check.Equals), "")
  387. out, _ = dockerCmd(c, "start", "-a", id)
  388. c.Assert(strings.TrimSpace(out), check.Equals, "foo")
  389. }