docker_api_containers_test.go 22 KB

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