docker_api_containers_test.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "os/exec"
  8. "strings"
  9. "time"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/pkg/stringid"
  12. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  13. "github.com/go-check/check"
  14. )
  15. func (s *DockerSuite) TestContainerApiGetAll(c *check.C) {
  16. startCount, err := getContainerCount()
  17. if err != nil {
  18. c.Fatalf("Cannot query container count: %v", err)
  19. }
  20. name := "getall"
  21. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "true")
  22. out, _, err := runCommandWithOutput(runCmd)
  23. if err != nil {
  24. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  25. }
  26. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  27. c.Assert(status, check.Equals, http.StatusOK)
  28. c.Assert(err, check.IsNil)
  29. var inspectJSON []struct {
  30. Names []string
  31. }
  32. if err = json.Unmarshal(body, &inspectJSON); err != nil {
  33. c.Fatalf("unable to unmarshal response body: %v", err)
  34. }
  35. if len(inspectJSON) != startCount+1 {
  36. c.Fatalf("Expected %d container(s), %d found (started with: %d)", startCount+1, len(inspectJSON), startCount)
  37. }
  38. if actual := inspectJSON[0].Names[0]; actual != "/"+name {
  39. c.Fatalf("Container Name mismatch. Expected: %q, received: %q\n", "/"+name, actual)
  40. }
  41. }
  42. func (s *DockerSuite) TestContainerApiGetExport(c *check.C) {
  43. name := "exportcontainer"
  44. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test")
  45. out, _, err := runCommandWithOutput(runCmd)
  46. if err != nil {
  47. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  48. }
  49. status, body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
  50. c.Assert(status, check.Equals, http.StatusOK)
  51. c.Assert(err, check.IsNil)
  52. found := false
  53. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  54. h, err := tarReader.Next()
  55. if err != nil {
  56. if err == io.EOF {
  57. break
  58. }
  59. c.Fatal(err)
  60. }
  61. if h.Name == "test" {
  62. found = true
  63. break
  64. }
  65. }
  66. if !found {
  67. c.Fatalf("The created test file has not been found in the exported image")
  68. }
  69. }
  70. func (s *DockerSuite) TestContainerApiGetChanges(c *check.C) {
  71. name := "changescontainer"
  72. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "rm", "/etc/passwd")
  73. out, _, err := runCommandWithOutput(runCmd)
  74. if err != nil {
  75. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  76. }
  77. status, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
  78. c.Assert(status, check.Equals, http.StatusOK)
  79. c.Assert(err, check.IsNil)
  80. changes := []struct {
  81. Kind int
  82. Path string
  83. }{}
  84. if err = json.Unmarshal(body, &changes); err != nil {
  85. c.Fatalf("unable to unmarshal response body: %v", err)
  86. }
  87. // Check the changelog for removal of /etc/passwd
  88. success := false
  89. for _, elem := range changes {
  90. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  91. success = true
  92. }
  93. }
  94. if !success {
  95. c.Fatalf("/etc/passwd has been removed but is not present in the diff")
  96. }
  97. }
  98. func (s *DockerSuite) TestContainerApiStartVolumeBinds(c *check.C) {
  99. name := "testing"
  100. config := map[string]interface{}{
  101. "Image": "busybox",
  102. "Volumes": map[string]struct{}{"/tmp": {}},
  103. }
  104. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  105. c.Assert(status, check.Equals, http.StatusCreated)
  106. c.Assert(err, check.IsNil)
  107. bindPath := randomUnixTmpDirPath("test")
  108. config = map[string]interface{}{
  109. "Binds": []string{bindPath + ":/tmp"},
  110. }
  111. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  112. c.Assert(status, check.Equals, http.StatusNoContent)
  113. c.Assert(err, check.IsNil)
  114. pth, err := inspectFieldMap(name, "Volumes", "/tmp")
  115. if err != nil {
  116. c.Fatal(err)
  117. }
  118. if pth != bindPath {
  119. c.Fatalf("expected volume host path to be %s, got %s", bindPath, pth)
  120. }
  121. }
  122. // Test for GH#10618
  123. func (s *DockerSuite) TestContainerApiStartDupVolumeBinds(c *check.C) {
  124. name := "testdups"
  125. config := map[string]interface{}{
  126. "Image": "busybox",
  127. "Volumes": map[string]struct{}{"/tmp": {}},
  128. }
  129. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  130. c.Assert(status, check.Equals, http.StatusCreated)
  131. c.Assert(err, check.IsNil)
  132. bindPath1 := randomUnixTmpDirPath("test1")
  133. bindPath2 := randomUnixTmpDirPath("test2")
  134. config = map[string]interface{}{
  135. "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"},
  136. }
  137. status, body, err := sockRequest("POST", "/containers/"+name+"/start", config)
  138. c.Assert(status, check.Equals, http.StatusInternalServerError)
  139. c.Assert(err, check.IsNil)
  140. if !strings.Contains(string(body), "Duplicate volume") {
  141. c.Fatalf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(body), err)
  142. }
  143. }
  144. func (s *DockerSuite) TestContainerApiStartVolumesFrom(c *check.C) {
  145. volName := "voltst"
  146. volPath := "/tmp"
  147. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  148. c.Fatal(out, err)
  149. }
  150. name := "testing"
  151. config := map[string]interface{}{
  152. "Image": "busybox",
  153. "Volumes": map[string]struct{}{volPath: {}},
  154. }
  155. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  156. c.Assert(status, check.Equals, http.StatusCreated)
  157. c.Assert(err, check.IsNil)
  158. config = map[string]interface{}{
  159. "VolumesFrom": []string{volName},
  160. }
  161. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  162. c.Assert(status, check.Equals, http.StatusNoContent)
  163. c.Assert(err, check.IsNil)
  164. pth, err := inspectFieldMap(name, "Volumes", volPath)
  165. if err != nil {
  166. c.Fatal(err)
  167. }
  168. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  169. if err != nil {
  170. c.Fatal(err)
  171. }
  172. if pth != pth2 {
  173. c.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  174. }
  175. }
  176. // Ensure that volumes-from has priority over binds/anything else
  177. // This is pretty much the same as TestRunApplyVolumesFromBeforeVolumes, except with passing the VolumesFrom and the bind on start
  178. func (s *DockerSuite) TestVolumesFromHasPriority(c *check.C) {
  179. volName := "voltst2"
  180. volPath := "/tmp"
  181. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  182. c.Fatal(out, err)
  183. }
  184. name := "testing"
  185. config := map[string]interface{}{
  186. "Image": "busybox",
  187. "Volumes": map[string]struct{}{volPath: {}},
  188. }
  189. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  190. c.Assert(status, check.Equals, http.StatusCreated)
  191. c.Assert(err, check.IsNil)
  192. bindPath := randomUnixTmpDirPath("test")
  193. config = map[string]interface{}{
  194. "VolumesFrom": []string{volName},
  195. "Binds": []string{bindPath + ":/tmp"},
  196. }
  197. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  198. c.Assert(status, check.Equals, http.StatusNoContent)
  199. c.Assert(err, check.IsNil)
  200. pth, err := inspectFieldMap(name, "Volumes", volPath)
  201. if err != nil {
  202. c.Fatal(err)
  203. }
  204. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  205. if err != nil {
  206. c.Fatal(err)
  207. }
  208. if pth != pth2 {
  209. c.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  210. }
  211. }
  212. func (s *DockerSuite) TestGetContainerStats(c *check.C) {
  213. var (
  214. name = "statscontainer"
  215. runCmd = exec.Command(dockerBinary, "run", "-d", "--name", name, "busybox", "top")
  216. )
  217. out, _, err := runCommandWithOutput(runCmd)
  218. if err != nil {
  219. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  220. }
  221. type b struct {
  222. body []byte
  223. err error
  224. }
  225. bc := make(chan b, 1)
  226. go func() {
  227. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  228. c.Assert(status, check.Equals, http.StatusOK)
  229. c.Assert(err, check.IsNil)
  230. bc <- b{body, err}
  231. }()
  232. // allow some time to stream the stats from the container
  233. time.Sleep(4 * time.Second)
  234. if _, err := runCommand(exec.Command(dockerBinary, "rm", "-f", name)); err != nil {
  235. c.Fatal(err)
  236. }
  237. // collect the results from the stats stream or timeout and fail
  238. // if the stream was not disconnected.
  239. select {
  240. case <-time.After(2 * time.Second):
  241. c.Fatal("stream was not closed after container was removed")
  242. case sr := <-bc:
  243. if sr.err != nil {
  244. c.Fatal(sr.err)
  245. }
  246. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  247. var s *types.Stats
  248. // decode only one object from the stream
  249. if err := dec.Decode(&s); err != nil {
  250. c.Fatal(err)
  251. }
  252. }
  253. }
  254. func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) {
  255. var (
  256. name = "statscontainer"
  257. runCmd = exec.Command(dockerBinary, "create", "--name", name, "busybox", "top")
  258. )
  259. out, _, err := runCommandWithOutput(runCmd)
  260. if err != nil {
  261. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  262. }
  263. go func() {
  264. // We'll never get return for GET stats from sockRequest as of now,
  265. // just send request and see if panic or error would happen on daemon side.
  266. status, _, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  267. c.Assert(status, check.Equals, http.StatusOK)
  268. c.Assert(err, check.IsNil)
  269. }()
  270. // allow some time to send request and let daemon deal with it
  271. time.Sleep(1 * time.Second)
  272. }
  273. func (s *DockerSuite) TestBuildApiDockerfilePath(c *check.C) {
  274. // Test to make sure we stop people from trying to leave the
  275. // build context when specifying the path to the dockerfile
  276. buffer := new(bytes.Buffer)
  277. tw := tar.NewWriter(buffer)
  278. defer tw.Close()
  279. dockerfile := []byte("FROM busybox")
  280. if err := tw.WriteHeader(&tar.Header{
  281. Name: "Dockerfile",
  282. Size: int64(len(dockerfile)),
  283. }); err != nil {
  284. c.Fatalf("failed to write tar file header: %v", err)
  285. }
  286. if _, err := tw.Write(dockerfile); err != nil {
  287. c.Fatalf("failed to write tar file content: %v", err)
  288. }
  289. if err := tw.Close(); err != nil {
  290. c.Fatalf("failed to close tar archive: %v", err)
  291. }
  292. status, body, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
  293. c.Assert(status, check.Equals, http.StatusInternalServerError)
  294. c.Assert(err, check.IsNil)
  295. out, err := readBody(body)
  296. if err != nil {
  297. c.Fatal(err)
  298. }
  299. if !strings.Contains(string(out), "must be within the build context") {
  300. c.Fatalf("Didn't complain about leaving build context: %s", out)
  301. }
  302. }
  303. func (s *DockerSuite) TestBuildApiDockerFileRemote(c *check.C) {
  304. server, err := fakeStorage(map[string]string{
  305. "testD": `FROM busybox
  306. COPY * /tmp/
  307. RUN find / -name ba*
  308. RUN find /tmp/`,
  309. })
  310. if err != nil {
  311. c.Fatal(err)
  312. }
  313. defer server.Close()
  314. status, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json")
  315. c.Assert(status, check.Equals, http.StatusOK)
  316. c.Assert(err, check.IsNil)
  317. buf, err := readBody(body)
  318. if err != nil {
  319. c.Fatal(err)
  320. }
  321. // Make sure Dockerfile exists.
  322. // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL
  323. out := string(buf)
  324. if !strings.Contains(out, "/tmp/Dockerfile") ||
  325. strings.Contains(out, "baz") {
  326. c.Fatalf("Incorrect output: %s", out)
  327. }
  328. }
  329. func (s *DockerSuite) TestBuildApiLowerDockerfile(c *check.C) {
  330. git, err := fakeGIT("repo", map[string]string{
  331. "dockerfile": `FROM busybox
  332. RUN echo from dockerfile`,
  333. }, false)
  334. if err != nil {
  335. c.Fatal(err)
  336. }
  337. defer git.Close()
  338. status, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  339. c.Assert(status, check.Equals, http.StatusOK)
  340. c.Assert(err, check.IsNil)
  341. buf, err := readBody(body)
  342. if err != nil {
  343. c.Fatal(err)
  344. }
  345. out := string(buf)
  346. if !strings.Contains(out, "from dockerfile") {
  347. c.Fatalf("Incorrect output: %s", out)
  348. }
  349. }
  350. func (s *DockerSuite) TestBuildApiBuildGitWithF(c *check.C) {
  351. git, err := fakeGIT("repo", map[string]string{
  352. "baz": `FROM busybox
  353. RUN echo from baz`,
  354. "Dockerfile": `FROM busybox
  355. RUN echo from Dockerfile`,
  356. }, false)
  357. if err != nil {
  358. c.Fatal(err)
  359. }
  360. defer git.Close()
  361. // Make sure it tries to 'dockerfile' query param value
  362. status, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
  363. c.Assert(status, check.Equals, http.StatusOK)
  364. c.Assert(err, check.IsNil)
  365. buf, err := readBody(body)
  366. if err != nil {
  367. c.Fatal(err)
  368. }
  369. out := string(buf)
  370. if !strings.Contains(out, "from baz") {
  371. c.Fatalf("Incorrect output: %s", out)
  372. }
  373. }
  374. func (s *DockerSuite) TestBuildApiDoubleDockerfile(c *check.C) {
  375. testRequires(c, UnixCli) // dockerfile overwrites Dockerfile on Windows
  376. git, err := fakeGIT("repo", map[string]string{
  377. "Dockerfile": `FROM busybox
  378. RUN echo from Dockerfile`,
  379. "dockerfile": `FROM busybox
  380. RUN echo from dockerfile`,
  381. }, false)
  382. if err != nil {
  383. c.Fatal(err)
  384. }
  385. defer git.Close()
  386. // Make sure it tries to 'dockerfile' query param value
  387. status, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  388. c.Assert(status, check.Equals, http.StatusOK)
  389. c.Assert(err, check.IsNil)
  390. buf, err := readBody(body)
  391. if err != nil {
  392. c.Fatal(err)
  393. }
  394. out := string(buf)
  395. if !strings.Contains(out, "from Dockerfile") {
  396. c.Fatalf("Incorrect output: %s", out)
  397. }
  398. }
  399. func (s *DockerSuite) TestBuildApiDockerfileSymlink(c *check.C) {
  400. // Test to make sure we stop people from trying to leave the
  401. // build context when specifying a symlink as the path to the dockerfile
  402. buffer := new(bytes.Buffer)
  403. tw := tar.NewWriter(buffer)
  404. defer tw.Close()
  405. if err := tw.WriteHeader(&tar.Header{
  406. Name: "Dockerfile",
  407. Typeflag: tar.TypeSymlink,
  408. Linkname: "/etc/passwd",
  409. }); err != nil {
  410. c.Fatalf("failed to write tar file header: %v", err)
  411. }
  412. if err := tw.Close(); err != nil {
  413. c.Fatalf("failed to close tar archive: %v", err)
  414. }
  415. status, body, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  416. c.Assert(status, check.Equals, http.StatusInternalServerError)
  417. c.Assert(err, check.IsNil)
  418. out, err := readBody(body)
  419. if err != nil {
  420. c.Fatal(err)
  421. }
  422. // The reason the error is "Cannot locate specified Dockerfile" is because
  423. // in the builder, the symlink is resolved within the context, therefore
  424. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  425. // a nonexistent file.
  426. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  427. c.Fatalf("Didn't complain about leaving build context: %s", out)
  428. }
  429. }
  430. // #9981 - Allow a docker created volume (ie, one in /var/lib/docker/volumes) to be used to overwrite (via passing in Binds on api start) an existing volume
  431. func (s *DockerSuite) TestPostContainerBindNormalVolume(c *check.C) {
  432. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=one", "busybox"))
  433. if err != nil {
  434. c.Fatal(err, out)
  435. }
  436. fooDir, err := inspectFieldMap("one", "Volumes", "/foo")
  437. if err != nil {
  438. c.Fatal(err)
  439. }
  440. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=two", "busybox"))
  441. if err != nil {
  442. c.Fatal(err, out)
  443. }
  444. bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
  445. status, _, err := sockRequest("POST", "/containers/two/start", bindSpec)
  446. c.Assert(status, check.Equals, http.StatusNoContent)
  447. c.Assert(err, check.IsNil)
  448. fooDir2, err := inspectFieldMap("two", "Volumes", "/foo")
  449. if err != nil {
  450. c.Fatal(err)
  451. }
  452. if fooDir2 != fooDir {
  453. c.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2)
  454. }
  455. }
  456. func (s *DockerSuite) TestContainerApiPause(c *check.C) {
  457. defer unpauseAllContainers()
  458. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sleep", "30")
  459. out, _, err := runCommandWithOutput(runCmd)
  460. if err != nil {
  461. c.Fatalf("failed to create a container: %s, %v", out, err)
  462. }
  463. ContainerID := strings.TrimSpace(out)
  464. status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil)
  465. c.Assert(status, check.Equals, http.StatusNoContent)
  466. c.Assert(err, check.IsNil)
  467. pausedContainers, err := getSliceOfPausedContainers()
  468. if err != nil {
  469. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  470. }
  471. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  472. c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  473. }
  474. status, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil)
  475. c.Assert(status, check.Equals, http.StatusNoContent)
  476. c.Assert(err, check.IsNil)
  477. pausedContainers, err = getSliceOfPausedContainers()
  478. if err != nil {
  479. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  480. }
  481. if pausedContainers != nil {
  482. c.Fatalf("There should be no paused container.")
  483. }
  484. }
  485. func (s *DockerSuite) TestContainerApiTop(c *check.C) {
  486. out, err := exec.Command(dockerBinary, "run", "-d", "busybox", "/bin/sh", "-c", "top").CombinedOutput()
  487. if err != nil {
  488. c.Fatal(err, out)
  489. }
  490. id := strings.TrimSpace(string(out))
  491. if err := waitRun(id); err != nil {
  492. c.Fatal(err)
  493. }
  494. type topResp struct {
  495. Titles []string
  496. Processes [][]string
  497. }
  498. var top topResp
  499. status, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil)
  500. c.Assert(status, check.Equals, http.StatusOK)
  501. c.Assert(err, check.IsNil)
  502. if err := json.Unmarshal(b, &top); err != nil {
  503. c.Fatal(err)
  504. }
  505. if len(top.Titles) != 11 {
  506. c.Fatalf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles)
  507. }
  508. if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
  509. c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
  510. }
  511. if len(top.Processes) != 2 {
  512. c.Fatalf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes)
  513. }
  514. if top.Processes[0][10] != "/bin/sh -c top" {
  515. c.Fatalf("expected `/bin/sh -c top`, found: %s", top.Processes[0][10])
  516. }
  517. if top.Processes[1][10] != "top" {
  518. c.Fatalf("expected `top`, found: %s", top.Processes[1][10])
  519. }
  520. }
  521. func (s *DockerSuite) TestContainerApiCommit(c *check.C) {
  522. out, err := exec.Command(dockerBinary, "run", "-d", "busybox", "/bin/sh", "-c", "touch /test").CombinedOutput()
  523. if err != nil {
  524. c.Fatal(err, out)
  525. }
  526. id := strings.TrimSpace(string(out))
  527. name := "testcommit" + stringid.GenerateRandomID()
  528. status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+id, nil)
  529. c.Assert(status, check.Equals, http.StatusCreated)
  530. c.Assert(err, check.IsNil)
  531. type resp struct {
  532. Id string
  533. }
  534. var img resp
  535. if err := json.Unmarshal(b, &img); err != nil {
  536. c.Fatal(err)
  537. }
  538. cmd, err := inspectField(img.Id, "Config.Cmd")
  539. if err != nil {
  540. c.Fatal(err)
  541. }
  542. if cmd != "{[/bin/sh -c touch /test]}" {
  543. c.Fatalf("got wrong Cmd from commit: %q", cmd)
  544. }
  545. // sanity check, make sure the image is what we think it is
  546. out, err = exec.Command(dockerBinary, "run", img.Id, "ls", "/test").CombinedOutput()
  547. if err != nil {
  548. c.Fatalf("error checking commited image: %v - %q", err, string(out))
  549. }
  550. }
  551. func (s *DockerSuite) TestContainerApiCreate(c *check.C) {
  552. config := map[string]interface{}{
  553. "Image": "busybox",
  554. "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"},
  555. }
  556. status, b, err := sockRequest("POST", "/containers/create", config)
  557. c.Assert(status, check.Equals, http.StatusCreated)
  558. c.Assert(err, check.IsNil)
  559. type createResp struct {
  560. Id string
  561. }
  562. var container createResp
  563. if err := json.Unmarshal(b, &container); err != nil {
  564. c.Fatal(err)
  565. }
  566. out, err := exec.Command(dockerBinary, "start", "-a", container.Id).CombinedOutput()
  567. if err != nil {
  568. c.Fatal(out, err)
  569. }
  570. if strings.TrimSpace(string(out)) != "/test" {
  571. c.Fatalf("expected output `/test`, got %q", out)
  572. }
  573. }
  574. func (s *DockerSuite) TestContainerApiCreateWithHostName(c *check.C) {
  575. var hostName = "test-host"
  576. config := map[string]interface{}{
  577. "Image": "busybox",
  578. "Hostname": hostName,
  579. }
  580. _, b, err := sockRequest("POST", "/containers/create", config)
  581. if err != nil && !strings.Contains(err.Error(), "200 OK: 201") {
  582. c.Fatal(err)
  583. }
  584. type createResp struct {
  585. Id string
  586. }
  587. var container createResp
  588. if err := json.Unmarshal(b, &container); err != nil {
  589. c.Fatal(err)
  590. }
  591. var id = container.Id
  592. _, bodyGet, err := sockRequest("GET", "/containers/"+id+"/json", nil)
  593. type configLocal struct {
  594. Hostname string
  595. }
  596. type getResponse struct {
  597. Id string
  598. Config configLocal
  599. }
  600. var containerInfo getResponse
  601. if err := json.Unmarshal(bodyGet, &containerInfo); err != nil {
  602. c.Fatal(err)
  603. }
  604. var hostNameActual = containerInfo.Config.Hostname
  605. if hostNameActual != "test-host" {
  606. c.Fatalf("Mismatched Hostname, Expected %v, Actual: %v ", hostName, hostNameActual)
  607. }
  608. }
  609. func (s *DockerSuite) TestContainerApiVerifyHeader(c *check.C) {
  610. config := map[string]interface{}{
  611. "Image": "busybox",
  612. }
  613. create := func(ct string) (int, io.ReadCloser, error) {
  614. jsonData := bytes.NewBuffer(nil)
  615. if err := json.NewEncoder(jsonData).Encode(config); err != nil {
  616. c.Fatal(err)
  617. }
  618. return sockRequestRaw("POST", "/containers/create", jsonData, ct)
  619. }
  620. // Try with no content-type
  621. status, body, err := create("")
  622. c.Assert(status, check.Equals, http.StatusInternalServerError)
  623. c.Assert(err, check.IsNil)
  624. body.Close()
  625. // Try with wrong content-type
  626. status, body, err = create("application/xml")
  627. c.Assert(status, check.Equals, http.StatusInternalServerError)
  628. c.Assert(err, check.IsNil)
  629. body.Close()
  630. // now application/json
  631. status, body, err = create("application/json")
  632. c.Assert(status, check.Equals, http.StatusCreated)
  633. c.Assert(err, check.IsNil)
  634. body.Close()
  635. }
  636. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  637. // W/o this fix a null in JSON would be parsed into a string var as "null"
  638. func (s *DockerSuite) TestContainerApiPostCreateNull(c *check.C) {
  639. config := `{
  640. "Hostname":"",
  641. "Domainname":"",
  642. "Memory":0,
  643. "MemorySwap":0,
  644. "CpuShares":0,
  645. "Cpuset":null,
  646. "AttachStdin":true,
  647. "AttachStdout":true,
  648. "AttachStderr":true,
  649. "PortSpecs":null,
  650. "ExposedPorts":{},
  651. "Tty":true,
  652. "OpenStdin":true,
  653. "StdinOnce":true,
  654. "Env":[],
  655. "Cmd":"ls",
  656. "Image":"busybox",
  657. "Volumes":{},
  658. "WorkingDir":"",
  659. "Entrypoint":null,
  660. "NetworkDisabled":false,
  661. "OnBuild":null}`
  662. status, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  663. c.Assert(status, check.Equals, http.StatusCreated)
  664. c.Assert(err, check.IsNil)
  665. b, err := readBody(body)
  666. if err != nil {
  667. c.Fatal(err)
  668. }
  669. type createResp struct {
  670. Id string
  671. }
  672. var container createResp
  673. if err := json.Unmarshal(b, &container); err != nil {
  674. c.Fatal(err)
  675. }
  676. out, err := inspectField(container.Id, "HostConfig.CpusetCpus")
  677. if err != nil {
  678. c.Fatal(err, out)
  679. }
  680. if out != "" {
  681. c.Fatalf("expected empty string, got %q", out)
  682. }
  683. }
  684. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  685. config := `{
  686. "Image": "busybox",
  687. "Cmd": "ls",
  688. "OpenStdin": true,
  689. "CpuShares": 100,
  690. "Memory": 524287
  691. }`
  692. status, body, _ := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  693. b, err2 := readBody(body)
  694. if err2 != nil {
  695. c.Fatal(err2)
  696. }
  697. c.Assert(status, check.Equals, http.StatusInternalServerError)
  698. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  699. }
  700. func (s *DockerSuite) TestStartWithTooLowMemoryLimit(c *check.C) {
  701. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "busybox"))
  702. if err != nil {
  703. c.Fatal(err, out)
  704. }
  705. containerID := strings.TrimSpace(out)
  706. config := `{
  707. "CpuShares": 100,
  708. "Memory": 524287
  709. }`
  710. status, body, _ := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  711. b, err2 := readBody(body)
  712. if err2 != nil {
  713. c.Fatal(err2)
  714. }
  715. c.Assert(status, check.Equals, http.StatusInternalServerError)
  716. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  717. }