docker_cli_create_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. // Windows does not currently support port ranges.
  85. testRequires(c, DaemonIsLinux)
  86. out, _ := dockerCmd(c, "create", "-p", "3300-3303:3300-3303/tcp", "busybox", "echo")
  87. cleanedContainerID := strings.TrimSpace(out)
  88. out, _ = dockerCmd(c, "inspect", cleanedContainerID)
  89. containers := []struct {
  90. HostConfig *struct {
  91. PortBindings map[nat.Port][]nat.PortBinding
  92. }
  93. }{}
  94. err := json.Unmarshal([]byte(out), &containers)
  95. c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
  96. c.Assert(containers, checker.HasLen, 1)
  97. cont := containers[0]
  98. c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
  99. c.Assert(cont.HostConfig.PortBindings, checker.HasLen, 4, check.Commentf("Expected 4 ports bindings, got %d", len(cont.HostConfig.PortBindings)))
  100. for k, v := range cont.HostConfig.PortBindings {
  101. c.Assert(v, checker.HasLen, 1, check.Commentf("Expected 1 ports binding, for the port %s but found %s", k, v))
  102. 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))
  103. }
  104. }
  105. func (s *DockerSuite) TestCreateWithLargePortRange(c *check.C) {
  106. // Windows does not currently support port ranges.
  107. testRequires(c, DaemonIsLinux)
  108. out, _ := dockerCmd(c, "create", "-p", "1-65535:1-65535/tcp", "busybox", "echo")
  109. cleanedContainerID := strings.TrimSpace(out)
  110. out, _ = dockerCmd(c, "inspect", cleanedContainerID)
  111. containers := []struct {
  112. HostConfig *struct {
  113. PortBindings map[nat.Port][]nat.PortBinding
  114. }
  115. }{}
  116. err := json.Unmarshal([]byte(out), &containers)
  117. c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
  118. c.Assert(containers, checker.HasLen, 1)
  119. cont := containers[0]
  120. c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
  121. c.Assert(cont.HostConfig.PortBindings, checker.HasLen, 65535)
  122. for k, v := range cont.HostConfig.PortBindings {
  123. c.Assert(v, checker.HasLen, 1)
  124. 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))
  125. }
  126. }
  127. // "test123" should be printed by docker create + start
  128. func (s *DockerSuite) TestCreateEchoStdout(c *check.C) {
  129. out, _ := dockerCmd(c, "create", "busybox", "echo", "test123")
  130. cleanedContainerID := strings.TrimSpace(out)
  131. out, _ = dockerCmd(c, "start", "-ai", cleanedContainerID)
  132. c.Assert(out, checker.Equals, "test123\n", check.Commentf("container should've printed 'test123', got %q", out))
  133. }
  134. func (s *DockerSuite) TestCreateVolumesCreated(c *check.C) {
  135. testRequires(c, SameHostDaemon)
  136. prefix := "/"
  137. if daemonPlatform == "windows" {
  138. prefix = `c:\`
  139. }
  140. name := "test_create_volume"
  141. dockerCmd(c, "create", "--name", name, "-v", prefix+"foo", "busybox")
  142. dir, err := inspectMountSourceField(name, prefix+"foo")
  143. c.Assert(err, check.IsNil, check.Commentf("Error getting volume host path: %q", err))
  144. if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
  145. c.Fatalf("Volume was not created")
  146. }
  147. if err != nil {
  148. c.Fatalf("Error statting volume host path: %q", err)
  149. }
  150. }
  151. func (s *DockerSuite) TestCreateLabels(c *check.C) {
  152. name := "test_create_labels"
  153. expected := map[string]string{"k1": "v1", "k2": "v2"}
  154. dockerCmd(c, "create", "--name", name, "-l", "k1=v1", "--label", "k2=v2", "busybox")
  155. actual := make(map[string]string)
  156. inspectFieldAndMarshall(c, name, "Config.Labels", &actual)
  157. if !reflect.DeepEqual(expected, actual) {
  158. c.Fatalf("Expected %s got %s", expected, actual)
  159. }
  160. }
  161. func (s *DockerSuite) TestCreateLabelFromImage(c *check.C) {
  162. imageName := "testcreatebuildlabel"
  163. _, err := buildImage(imageName,
  164. `FROM busybox
  165. LABEL k1=v1 k2=v2`,
  166. true)
  167. c.Assert(err, check.IsNil)
  168. name := "test_create_labels_from_image"
  169. expected := map[string]string{"k2": "x", "k3": "v3", "k1": "v1"}
  170. dockerCmd(c, "create", "--name", name, "-l", "k2=x", "--label", "k3=v3", imageName)
  171. actual := make(map[string]string)
  172. inspectFieldAndMarshall(c, name, "Config.Labels", &actual)
  173. if !reflect.DeepEqual(expected, actual) {
  174. c.Fatalf("Expected %s got %s", expected, actual)
  175. }
  176. }
  177. func (s *DockerSuite) TestCreateHostnameWithNumber(c *check.C) {
  178. // TODO Windows. Consider enabling this in TP5 timeframe if Windows support
  179. // is fully hooked up. The hostname is passed through, but only to the
  180. // environment variable "COMPUTERNAME". It is not hooked up to hostname.exe
  181. // or returned in ipconfig. Needs platform support in networking.
  182. testRequires(c, DaemonIsLinux)
  183. out, _ := dockerCmd(c, "run", "-h", "web.0", "busybox", "hostname")
  184. c.Assert(strings.TrimSpace(out), checker.Equals, "web.0", check.Commentf("hostname not set, expected `web.0`, got: %s", out))
  185. }
  186. func (s *DockerSuite) TestCreateRM(c *check.C) {
  187. // Test to make sure we can 'rm' a new container that is in
  188. // "Created" state, and has ever been run. Test "rm -f" too.
  189. // create a container
  190. out, _ := dockerCmd(c, "create", "busybox")
  191. cID := strings.TrimSpace(out)
  192. dockerCmd(c, "rm", cID)
  193. // Now do it again so we can "rm -f" this time
  194. out, _ = dockerCmd(c, "create", "busybox")
  195. cID = strings.TrimSpace(out)
  196. dockerCmd(c, "rm", "-f", cID)
  197. }
  198. func (s *DockerSuite) TestCreateModeIpcContainer(c *check.C) {
  199. // Uses Linux specific functionality (--ipc)
  200. testRequires(c, DaemonIsLinux, SameHostDaemon)
  201. out, _ := dockerCmd(c, "create", "busybox")
  202. id := strings.TrimSpace(out)
  203. dockerCmd(c, "create", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  204. }
  205. func (s *DockerSuite) TestCreateByImageID(c *check.C) {
  206. imageName := "testcreatebyimageid"
  207. imageID, err := buildImage(imageName,
  208. `FROM busybox
  209. MAINTAINER dockerio`,
  210. true)
  211. if err != nil {
  212. c.Fatal(err)
  213. }
  214. truncatedImageID := stringid.TruncateID(imageID)
  215. dockerCmd(c, "create", imageID)
  216. dockerCmd(c, "create", truncatedImageID)
  217. dockerCmd(c, "create", fmt.Sprintf("%s:%s", imageName, truncatedImageID))
  218. // Ensure this fails
  219. out, exit, _ := dockerCmdWithError("create", fmt.Sprintf("%s:%s", imageName, imageID))
  220. if exit == 0 {
  221. c.Fatalf("expected non-zero exit code; received %d", exit)
  222. }
  223. if expected := "Error parsing reference"; !strings.Contains(out, expected) {
  224. c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  225. }
  226. out, exit, _ = dockerCmdWithError("create", fmt.Sprintf("%s:%s", "wrongimage", truncatedImageID))
  227. if exit == 0 {
  228. c.Fatalf("expected non-zero exit code; received %d", exit)
  229. }
  230. if expected := "Unable to find image"; !strings.Contains(out, expected) {
  231. c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  232. }
  233. }
  234. func (s *DockerTrustSuite) TestTrustedCreate(c *check.C) {
  235. repoName := s.setupTrustedImage(c, "trusted-create")
  236. // Try create
  237. createCmd := exec.Command(dockerBinary, "create", repoName)
  238. s.trustedCmd(createCmd)
  239. out, _, err := runCommandWithOutput(createCmd)
  240. c.Assert(err, check.IsNil)
  241. c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))
  242. dockerCmd(c, "rmi", repoName)
  243. // Try untrusted create to ensure we pushed the tag to the registry
  244. createCmd = exec.Command(dockerBinary, "create", "--disable-content-trust=true", repoName)
  245. s.trustedCmd(createCmd)
  246. out, _, err = runCommandWithOutput(createCmd)
  247. c.Assert(err, check.IsNil)
  248. c.Assert(string(out), checker.Contains, "Status: Downloaded", check.Commentf("Missing expected output on trusted create with --disable-content-trust:\n%s", out))
  249. }
  250. func (s *DockerTrustSuite) TestUntrustedCreate(c *check.C) {
  251. repoName := fmt.Sprintf("%v/dockercliuntrusted/createtest", privateRegistryURL)
  252. withTagName := fmt.Sprintf("%s:latest", repoName)
  253. // tag the image and upload it to the private registry
  254. dockerCmd(c, "tag", "busybox", withTagName)
  255. dockerCmd(c, "push", withTagName)
  256. dockerCmd(c, "rmi", withTagName)
  257. // Try trusted create on untrusted tag
  258. createCmd := exec.Command(dockerBinary, "create", withTagName)
  259. s.trustedCmd(createCmd)
  260. out, _, err := runCommandWithOutput(createCmd)
  261. c.Assert(err, check.Not(check.IsNil))
  262. 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))
  263. }
  264. func (s *DockerTrustSuite) TestTrustedIsolatedCreate(c *check.C) {
  265. repoName := s.setupTrustedImage(c, "trusted-isolated-create")
  266. // Try create
  267. createCmd := exec.Command(dockerBinary, "--config", "/tmp/docker-isolated-create", "create", repoName)
  268. s.trustedCmd(createCmd)
  269. out, _, err := runCommandWithOutput(createCmd)
  270. c.Assert(err, check.IsNil)
  271. c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))
  272. dockerCmd(c, "rmi", repoName)
  273. }
  274. func (s *DockerTrustSuite) TestCreateWhenCertExpired(c *check.C) {
  275. c.Skip("Currently changes system time, causing instability")
  276. repoName := s.setupTrustedImage(c, "trusted-create-expired")
  277. // Certificates have 10 years of expiration
  278. elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)
  279. runAtDifferentDate(elevenYearsFromNow, func() {
  280. // Try create
  281. createCmd := exec.Command(dockerBinary, "create", 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, "could not validate the path to a trusted root", check.Commentf("Missing expected output on trusted create in the distant future:\n%s", out))
  286. })
  287. runAtDifferentDate(elevenYearsFromNow, func() {
  288. // Try create
  289. createCmd := exec.Command(dockerBinary, "create", "--disable-content-trust", repoName)
  290. s.trustedCmd(createCmd)
  291. out, _, err := runCommandWithOutput(createCmd)
  292. c.Assert(err, check.Not(check.IsNil))
  293. c.Assert(string(out), checker.Contains, "Status: Downloaded", check.Commentf("Missing expected output on trusted create in the distant future:\n%s", out))
  294. })
  295. }
  296. func (s *DockerTrustSuite) TestTrustedCreateFromBadTrustServer(c *check.C) {
  297. repoName := fmt.Sprintf("%v/dockerclievilcreate/trusted:latest", privateRegistryURL)
  298. evilLocalConfigDir, err := ioutil.TempDir("", "evilcreate-local-config-dir")
  299. c.Assert(err, check.IsNil)
  300. // tag the image and upload it to the private registry
  301. dockerCmd(c, "tag", "busybox", repoName)
  302. pushCmd := exec.Command(dockerBinary, "push", repoName)
  303. s.trustedCmd(pushCmd)
  304. out, _, err := runCommandWithOutput(pushCmd)
  305. c.Assert(err, check.IsNil)
  306. c.Assert(string(out), checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push:\n%s", out))
  307. dockerCmd(c, "rmi", repoName)
  308. // Try create
  309. createCmd := exec.Command(dockerBinary, "create", repoName)
  310. s.trustedCmd(createCmd)
  311. out, _, err = runCommandWithOutput(createCmd)
  312. c.Assert(err, check.IsNil)
  313. c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))
  314. dockerCmd(c, "rmi", repoName)
  315. // Kill the notary server, start a new "evil" one.
  316. s.not.Close()
  317. s.not, err = newTestNotary(c)
  318. c.Assert(err, check.IsNil)
  319. // In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  320. // tag an image and upload it to the private registry
  321. dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  322. // Push up to the new server
  323. pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName)
  324. s.trustedCmd(pushCmd)
  325. out, _, err = runCommandWithOutput(pushCmd)
  326. c.Assert(err, check.IsNil)
  327. c.Assert(string(out), checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push:\n%s", out))
  328. // Now, try creating with the original client from this new trust server. This should fallback to our cached timestamp and metadata.
  329. createCmd = exec.Command(dockerBinary, "create", repoName)
  330. s.trustedCmd(createCmd)
  331. out, _, err = runCommandWithOutput(createCmd)
  332. if err != nil {
  333. c.Fatalf("Error falling back to cached trust data: %s\n%s", err, out)
  334. }
  335. if !strings.Contains(string(out), "Error while downloading remote metadata, using cached timestamp") {
  336. c.Fatalf("Missing expected output on trusted create:\n%s", out)
  337. }
  338. }
  339. func (s *DockerSuite) TestCreateStopSignal(c *check.C) {
  340. name := "test_create_stop_signal"
  341. dockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox")
  342. res := inspectFieldJSON(c, name, "Config.StopSignal")
  343. c.Assert(res, checker.Contains, "9")
  344. }
  345. func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) {
  346. // TODO Windows. This requires further investigation for porting to
  347. // Windows CI. Currently fails.
  348. if daemonPlatform == "windows" {
  349. c.Skip("Fails on Windows CI")
  350. }
  351. name := "foo"
  352. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  353. dir := prefix + slash + "home" + slash + "foo" + slash + "bar"
  354. dockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
  355. dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp")
  356. }
  357. func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *check.C) {
  358. name := "test-invalidate-log-opts"
  359. out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox")
  360. c.Assert(err, checker.NotNil)
  361. c.Assert(out, checker.Contains, "unknown log opt")
  362. out, _ = dockerCmd(c, "ps", "-a")
  363. c.Assert(out, checker.Not(checker.Contains), name)
  364. }
  365. // #20972
  366. func (s *DockerSuite) TestCreate64ByteHexID(c *check.C) {
  367. out := inspectField(c, "busybox", "Id")
  368. imageID := strings.TrimPrefix(strings.TrimSpace(string(out)), "sha256:")
  369. dockerCmd(c, "create", imageID)
  370. }