docker_api_containers_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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 := "TestContainerApiStartDupVolumeBinds"
  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. status int
  223. body []byte
  224. err error
  225. }
  226. bc := make(chan b, 1)
  227. go func() {
  228. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  229. bc <- b{status, body, err}
  230. }()
  231. // allow some time to stream the stats from the container
  232. time.Sleep(4 * time.Second)
  233. if _, err := runCommand(exec.Command(dockerBinary, "rm", "-f", name)); err != nil {
  234. c.Fatal(err)
  235. }
  236. // collect the results from the stats stream or timeout and fail
  237. // if the stream was not disconnected.
  238. select {
  239. case <-time.After(2 * time.Second):
  240. c.Fatal("stream was not closed after container was removed")
  241. case sr := <-bc:
  242. c.Assert(sr.err, check.IsNil)
  243. c.Assert(sr.status, check.Equals, http.StatusOK)
  244. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  245. var s *types.Stats
  246. // decode only one object from the stream
  247. if err := dec.Decode(&s); err != nil {
  248. c.Fatal(err)
  249. }
  250. }
  251. }
  252. func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) {
  253. // TODO: this test does nothing because we are c.Assert'ing in goroutine
  254. var (
  255. name = "statscontainer"
  256. runCmd = exec.Command(dockerBinary, "create", "--name", name, "busybox", "top")
  257. )
  258. out, _, err := runCommandWithOutput(runCmd)
  259. if err != nil {
  260. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  261. }
  262. go func() {
  263. // We'll never get return for GET stats from sockRequest as of now,
  264. // just send request and see if panic or error would happen on daemon side.
  265. status, _, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  266. c.Assert(status, check.Equals, http.StatusOK)
  267. c.Assert(err, check.IsNil)
  268. }()
  269. // allow some time to send request and let daemon deal with it
  270. time.Sleep(1 * time.Second)
  271. }
  272. func (s *DockerSuite) TestBuildApiDockerfilePath(c *check.C) {
  273. // Test to make sure we stop people from trying to leave the
  274. // build context when specifying the path to the dockerfile
  275. buffer := new(bytes.Buffer)
  276. tw := tar.NewWriter(buffer)
  277. defer tw.Close()
  278. dockerfile := []byte("FROM busybox")
  279. if err := tw.WriteHeader(&tar.Header{
  280. Name: "Dockerfile",
  281. Size: int64(len(dockerfile)),
  282. }); err != nil {
  283. c.Fatalf("failed to write tar file header: %v", err)
  284. }
  285. if _, err := tw.Write(dockerfile); err != nil {
  286. c.Fatalf("failed to write tar file content: %v", err)
  287. }
  288. if err := tw.Close(); err != nil {
  289. c.Fatalf("failed to close tar archive: %v", err)
  290. }
  291. res, body, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
  292. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  293. c.Assert(err, check.IsNil)
  294. out, err := readBody(body)
  295. if err != nil {
  296. c.Fatal(err)
  297. }
  298. if !strings.Contains(string(out), "must be within the build context") {
  299. c.Fatalf("Didn't complain about leaving build context: %s", out)
  300. }
  301. }
  302. func (s *DockerSuite) TestBuildApiDockerFileRemote(c *check.C) {
  303. server, err := fakeStorage(map[string]string{
  304. "testD": `FROM busybox
  305. COPY * /tmp/
  306. RUN find / -name ba*
  307. RUN find /tmp/`,
  308. })
  309. if err != nil {
  310. c.Fatal(err)
  311. }
  312. defer server.Close()
  313. res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json")
  314. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  315. c.Assert(err, check.IsNil)
  316. buf, err := readBody(body)
  317. if err != nil {
  318. c.Fatal(err)
  319. }
  320. // Make sure Dockerfile exists.
  321. // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL
  322. out := string(buf)
  323. if !strings.Contains(out, "/tmp/Dockerfile") ||
  324. strings.Contains(out, "baz") {
  325. c.Fatalf("Incorrect output: %s", out)
  326. }
  327. }
  328. func (s *DockerSuite) TestBuildApiLowerDockerfile(c *check.C) {
  329. git, err := fakeGIT("repo", map[string]string{
  330. "dockerfile": `FROM busybox
  331. RUN echo from dockerfile`,
  332. }, false)
  333. if err != nil {
  334. c.Fatal(err)
  335. }
  336. defer git.Close()
  337. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  338. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  339. c.Assert(err, check.IsNil)
  340. buf, err := readBody(body)
  341. if err != nil {
  342. c.Fatal(err)
  343. }
  344. out := string(buf)
  345. if !strings.Contains(out, "from dockerfile") {
  346. c.Fatalf("Incorrect output: %s", out)
  347. }
  348. }
  349. func (s *DockerSuite) TestBuildApiBuildGitWithF(c *check.C) {
  350. git, err := fakeGIT("repo", map[string]string{
  351. "baz": `FROM busybox
  352. RUN echo from baz`,
  353. "Dockerfile": `FROM busybox
  354. RUN echo from Dockerfile`,
  355. }, false)
  356. if err != nil {
  357. c.Fatal(err)
  358. }
  359. defer git.Close()
  360. // Make sure it tries to 'dockerfile' query param value
  361. res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
  362. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  363. c.Assert(err, check.IsNil)
  364. buf, err := readBody(body)
  365. if err != nil {
  366. c.Fatal(err)
  367. }
  368. out := string(buf)
  369. if !strings.Contains(out, "from baz") {
  370. c.Fatalf("Incorrect output: %s", out)
  371. }
  372. }
  373. func (s *DockerSuite) TestBuildApiDoubleDockerfile(c *check.C) {
  374. testRequires(c, UnixCli) // dockerfile overwrites Dockerfile on Windows
  375. git, err := fakeGIT("repo", map[string]string{
  376. "Dockerfile": `FROM busybox
  377. RUN echo from Dockerfile`,
  378. "dockerfile": `FROM busybox
  379. RUN echo from dockerfile`,
  380. }, false)
  381. if err != nil {
  382. c.Fatal(err)
  383. }
  384. defer git.Close()
  385. // Make sure it tries to 'dockerfile' query param value
  386. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  387. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  388. c.Assert(err, check.IsNil)
  389. buf, err := readBody(body)
  390. if err != nil {
  391. c.Fatal(err)
  392. }
  393. out := string(buf)
  394. if !strings.Contains(out, "from Dockerfile") {
  395. c.Fatalf("Incorrect output: %s", out)
  396. }
  397. }
  398. func (s *DockerSuite) TestBuildApiDockerfileSymlink(c *check.C) {
  399. // Test to make sure we stop people from trying to leave the
  400. // build context when specifying a symlink as the path to the dockerfile
  401. buffer := new(bytes.Buffer)
  402. tw := tar.NewWriter(buffer)
  403. defer tw.Close()
  404. if err := tw.WriteHeader(&tar.Header{
  405. Name: "Dockerfile",
  406. Typeflag: tar.TypeSymlink,
  407. Linkname: "/etc/passwd",
  408. }); err != nil {
  409. c.Fatalf("failed to write tar file header: %v", err)
  410. }
  411. if err := tw.Close(); err != nil {
  412. c.Fatalf("failed to close tar archive: %v", err)
  413. }
  414. res, body, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  415. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  416. c.Assert(err, check.IsNil)
  417. out, err := readBody(body)
  418. if err != nil {
  419. c.Fatal(err)
  420. }
  421. // The reason the error is "Cannot locate specified Dockerfile" is because
  422. // in the builder, the symlink is resolved within the context, therefore
  423. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  424. // a nonexistent file.
  425. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  426. c.Fatalf("Didn't complain about leaving build context: %s", out)
  427. }
  428. }
  429. // #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
  430. func (s *DockerSuite) TestPostContainerBindNormalVolume(c *check.C) {
  431. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=one", "busybox"))
  432. if err != nil {
  433. c.Fatal(err, out)
  434. }
  435. fooDir, err := inspectFieldMap("one", "Volumes", "/foo")
  436. if err != nil {
  437. c.Fatal(err)
  438. }
  439. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=two", "busybox"))
  440. if err != nil {
  441. c.Fatal(err, out)
  442. }
  443. bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
  444. status, _, err := sockRequest("POST", "/containers/two/start", bindSpec)
  445. c.Assert(status, check.Equals, http.StatusNoContent)
  446. c.Assert(err, check.IsNil)
  447. fooDir2, err := inspectFieldMap("two", "Volumes", "/foo")
  448. if err != nil {
  449. c.Fatal(err)
  450. }
  451. if fooDir2 != fooDir {
  452. c.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2)
  453. }
  454. }
  455. func (s *DockerSuite) TestContainerApiPause(c *check.C) {
  456. defer unpauseAllContainers()
  457. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sleep", "30")
  458. out, _, err := runCommandWithOutput(runCmd)
  459. if err != nil {
  460. c.Fatalf("failed to create a container: %s, %v", out, err)
  461. }
  462. ContainerID := strings.TrimSpace(out)
  463. status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil)
  464. c.Assert(status, check.Equals, http.StatusNoContent)
  465. c.Assert(err, check.IsNil)
  466. pausedContainers, err := getSliceOfPausedContainers()
  467. if err != nil {
  468. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  469. }
  470. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  471. c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  472. }
  473. status, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil)
  474. c.Assert(status, check.Equals, http.StatusNoContent)
  475. c.Assert(err, check.IsNil)
  476. pausedContainers, err = getSliceOfPausedContainers()
  477. if err != nil {
  478. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  479. }
  480. if pausedContainers != nil {
  481. c.Fatalf("There should be no paused container.")
  482. }
  483. }
  484. func (s *DockerSuite) TestContainerApiTop(c *check.C) {
  485. out, err := exec.Command(dockerBinary, "run", "-d", "busybox", "/bin/sh", "-c", "top").CombinedOutput()
  486. if err != nil {
  487. c.Fatal(err, out)
  488. }
  489. id := strings.TrimSpace(string(out))
  490. if err := waitRun(id); err != nil {
  491. c.Fatal(err)
  492. }
  493. type topResp struct {
  494. Titles []string
  495. Processes [][]string
  496. }
  497. var top topResp
  498. status, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil)
  499. c.Assert(status, check.Equals, http.StatusOK)
  500. c.Assert(err, check.IsNil)
  501. if err := json.Unmarshal(b, &top); err != nil {
  502. c.Fatal(err)
  503. }
  504. if len(top.Titles) != 11 {
  505. c.Fatalf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles)
  506. }
  507. if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
  508. c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
  509. }
  510. if len(top.Processes) != 2 {
  511. c.Fatalf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes)
  512. }
  513. if top.Processes[0][10] != "/bin/sh -c top" {
  514. c.Fatalf("expected `/bin/sh -c top`, found: %s", top.Processes[0][10])
  515. }
  516. if top.Processes[1][10] != "top" {
  517. c.Fatalf("expected `top`, found: %s", top.Processes[1][10])
  518. }
  519. }
  520. func (s *DockerSuite) TestContainerApiCommit(c *check.C) {
  521. cName := "testapicommit"
  522. out, err := exec.Command(dockerBinary, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test").CombinedOutput()
  523. if err != nil {
  524. c.Fatal(err, out)
  525. }
  526. name := "TestContainerApiCommit"
  527. status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil)
  528. c.Assert(status, check.Equals, http.StatusCreated)
  529. c.Assert(err, check.IsNil)
  530. type resp struct {
  531. Id string
  532. }
  533. var img resp
  534. if err := json.Unmarshal(b, &img); err != nil {
  535. c.Fatal(err)
  536. }
  537. cmd, err := inspectField(img.Id, "Config.Cmd")
  538. if err != nil {
  539. c.Fatal(err)
  540. }
  541. if cmd != "{[/bin/sh -c touch /test]}" {
  542. c.Fatalf("got wrong Cmd from commit: %q", cmd)
  543. }
  544. // sanity check, make sure the image is what we think it is
  545. out, err = exec.Command(dockerBinary, "run", img.Id, "ls", "/test").CombinedOutput()
  546. if err != nil {
  547. c.Fatalf("error checking committed image: %v - %q", err, string(out))
  548. }
  549. }
  550. func (s *DockerSuite) TestContainerApiCreate(c *check.C) {
  551. config := map[string]interface{}{
  552. "Image": "busybox",
  553. "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"},
  554. }
  555. status, b, err := sockRequest("POST", "/containers/create", config)
  556. c.Assert(status, check.Equals, http.StatusCreated)
  557. c.Assert(err, check.IsNil)
  558. type createResp struct {
  559. Id string
  560. }
  561. var container createResp
  562. if err := json.Unmarshal(b, &container); err != nil {
  563. c.Fatal(err)
  564. }
  565. out, err := exec.Command(dockerBinary, "start", "-a", container.Id).CombinedOutput()
  566. if err != nil {
  567. c.Fatal(out, err)
  568. }
  569. if strings.TrimSpace(string(out)) != "/test" {
  570. c.Fatalf("expected output `/test`, got %q", out)
  571. }
  572. }
  573. func (s *DockerSuite) TestContainerApiCreateWithHostName(c *check.C) {
  574. var hostName = "test-host"
  575. config := map[string]interface{}{
  576. "Image": "busybox",
  577. "Hostname": hostName,
  578. }
  579. _, b, err := sockRequest("POST", "/containers/create", config)
  580. if err != nil && !strings.Contains(err.Error(), "200 OK: 201") {
  581. c.Fatal(err)
  582. }
  583. type createResp struct {
  584. Id string
  585. }
  586. var container createResp
  587. if err := json.Unmarshal(b, &container); err != nil {
  588. c.Fatal(err)
  589. }
  590. var id = container.Id
  591. _, bodyGet, err := sockRequest("GET", "/containers/"+id+"/json", nil)
  592. type configLocal struct {
  593. Hostname string
  594. }
  595. type getResponse struct {
  596. Id string
  597. Config configLocal
  598. }
  599. var containerInfo getResponse
  600. if err := json.Unmarshal(bodyGet, &containerInfo); err != nil {
  601. c.Fatal(err)
  602. }
  603. var hostNameActual = containerInfo.Config.Hostname
  604. if hostNameActual != "test-host" {
  605. c.Fatalf("Mismatched Hostname, Expected %v, Actual: %v ", hostName, hostNameActual)
  606. }
  607. }
  608. func (s *DockerSuite) TestContainerApiVerifyHeader(c *check.C) {
  609. config := map[string]interface{}{
  610. "Image": "busybox",
  611. }
  612. create := func(ct string) (*http.Response, io.ReadCloser, error) {
  613. jsonData := bytes.NewBuffer(nil)
  614. if err := json.NewEncoder(jsonData).Encode(config); err != nil {
  615. c.Fatal(err)
  616. }
  617. return sockRequestRaw("POST", "/containers/create", jsonData, ct)
  618. }
  619. // Try with no content-type
  620. res, body, err := create("")
  621. c.Assert(err, check.IsNil)
  622. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  623. body.Close()
  624. // Try with wrong content-type
  625. res, body, err = create("application/xml")
  626. c.Assert(err, check.IsNil)
  627. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  628. body.Close()
  629. // now application/json
  630. res, body, err = create("application/json")
  631. c.Assert(err, check.IsNil)
  632. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  633. body.Close()
  634. }
  635. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  636. // W/o this fix a null in JSON would be parsed into a string var as "null"
  637. func (s *DockerSuite) TestContainerApiPostCreateNull(c *check.C) {
  638. config := `{
  639. "Hostname":"",
  640. "Domainname":"",
  641. "Memory":0,
  642. "MemorySwap":0,
  643. "CpuShares":0,
  644. "Cpuset":null,
  645. "AttachStdin":true,
  646. "AttachStdout":true,
  647. "AttachStderr":true,
  648. "PortSpecs":null,
  649. "ExposedPorts":{},
  650. "Tty":true,
  651. "OpenStdin":true,
  652. "StdinOnce":true,
  653. "Env":[],
  654. "Cmd":"ls",
  655. "Image":"busybox",
  656. "Volumes":{},
  657. "WorkingDir":"",
  658. "Entrypoint":null,
  659. "NetworkDisabled":false,
  660. "OnBuild":null}`
  661. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  662. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  663. c.Assert(err, check.IsNil)
  664. b, err := readBody(body)
  665. if err != nil {
  666. c.Fatal(err)
  667. }
  668. type createResp struct {
  669. Id string
  670. }
  671. var container createResp
  672. if err := json.Unmarshal(b, &container); err != nil {
  673. c.Fatal(err)
  674. }
  675. out, err := inspectField(container.Id, "HostConfig.CpusetCpus")
  676. if err != nil {
  677. c.Fatal(err, out)
  678. }
  679. if out != "" {
  680. c.Fatalf("expected empty string, got %q", out)
  681. }
  682. }
  683. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  684. config := `{
  685. "Image": "busybox",
  686. "Cmd": "ls",
  687. "OpenStdin": true,
  688. "CpuShares": 100,
  689. "Memory": 524287
  690. }`
  691. res, body, _ := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  692. b, err2 := readBody(body)
  693. if err2 != nil {
  694. c.Fatal(err2)
  695. }
  696. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  697. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  698. }
  699. func (s *DockerSuite) TestStartWithTooLowMemoryLimit(c *check.C) {
  700. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "busybox"))
  701. if err != nil {
  702. c.Fatal(err, out)
  703. }
  704. containerID := strings.TrimSpace(out)
  705. config := `{
  706. "CpuShares": 100,
  707. "Memory": 524287
  708. }`
  709. res, body, _ := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  710. b, err2 := readBody(body)
  711. if err2 != nil {
  712. c.Fatal(err2)
  713. }
  714. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  715. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  716. }
  717. func (s *DockerSuite) TestContainerApiRename(c *check.C) {
  718. runCmd := exec.Command(dockerBinary, "run", "--name", "TestContainerApiRename", "-d", "busybox", "sh")
  719. out, _, err := runCommandWithOutput(runCmd)
  720. c.Assert(err, check.IsNil)
  721. containerID := strings.TrimSpace(out)
  722. newName := "TestContainerApiRenameNew"
  723. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
  724. // 204 No Content is expected, not 200
  725. c.Assert(statusCode, check.Equals, http.StatusNoContent)
  726. c.Assert(err, check.IsNil)
  727. name, err := inspectField(containerID, "Name")
  728. if name != "/"+newName {
  729. c.Fatalf("Failed to rename container, expected %v, got %v. Container rename API failed", newName, name)
  730. }
  731. }