docker_cli_create_test.go 16 KB

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