docker_api_containers_test.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334
  1. package main
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "encoding/json"
  6. "io"
  7. "net/http"
  8. "net/http/httputil"
  9. "os"
  10. "os/exec"
  11. "strings"
  12. "time"
  13. "github.com/docker/docker/api/types"
  14. "github.com/docker/docker/pkg/stringid"
  15. "github.com/docker/docker/runconfig"
  16. "github.com/go-check/check"
  17. )
  18. func (s *DockerSuite) TestContainerApiGetAll(c *check.C) {
  19. startCount, err := getContainerCount()
  20. if err != nil {
  21. c.Fatalf("Cannot query container count: %v", err)
  22. }
  23. name := "getall"
  24. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "true")
  25. out, _, err := runCommandWithOutput(runCmd)
  26. if err != nil {
  27. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  28. }
  29. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  30. c.Assert(status, check.Equals, http.StatusOK)
  31. c.Assert(err, check.IsNil)
  32. var inspectJSON []struct {
  33. Names []string
  34. }
  35. if err = json.Unmarshal(body, &inspectJSON); err != nil {
  36. c.Fatalf("unable to unmarshal response body: %v", err)
  37. }
  38. if len(inspectJSON) != startCount+1 {
  39. c.Fatalf("Expected %d container(s), %d found (started with: %d)", startCount+1, len(inspectJSON), startCount)
  40. }
  41. if actual := inspectJSON[0].Names[0]; actual != "/"+name {
  42. c.Fatalf("Container Name mismatch. Expected: %q, received: %q\n", "/"+name, actual)
  43. }
  44. }
  45. func (s *DockerSuite) TestContainerApiGetExport(c *check.C) {
  46. name := "exportcontainer"
  47. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test")
  48. out, _, err := runCommandWithOutput(runCmd)
  49. if err != nil {
  50. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  51. }
  52. status, body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
  53. c.Assert(status, check.Equals, http.StatusOK)
  54. c.Assert(err, check.IsNil)
  55. found := false
  56. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  57. h, err := tarReader.Next()
  58. if err != nil {
  59. if err == io.EOF {
  60. break
  61. }
  62. c.Fatal(err)
  63. }
  64. if h.Name == "test" {
  65. found = true
  66. break
  67. }
  68. }
  69. if !found {
  70. c.Fatalf("The created test file has not been found in the exported image")
  71. }
  72. }
  73. func (s *DockerSuite) TestContainerApiGetChanges(c *check.C) {
  74. name := "changescontainer"
  75. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "rm", "/etc/passwd")
  76. out, _, err := runCommandWithOutput(runCmd)
  77. if err != nil {
  78. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  79. }
  80. status, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
  81. c.Assert(status, check.Equals, http.StatusOK)
  82. c.Assert(err, check.IsNil)
  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. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  108. c.Assert(status, check.Equals, http.StatusCreated)
  109. c.Assert(err, check.IsNil)
  110. bindPath := randomUnixTmpDirPath("test")
  111. config = map[string]interface{}{
  112. "Binds": []string{bindPath + ":/tmp"},
  113. }
  114. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  115. c.Assert(status, check.Equals, http.StatusNoContent)
  116. c.Assert(err, check.IsNil)
  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. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  133. c.Assert(status, check.Equals, http.StatusCreated)
  134. c.Assert(err, check.IsNil)
  135. bindPath1 := randomUnixTmpDirPath("test1")
  136. bindPath2 := randomUnixTmpDirPath("test2")
  137. config = map[string]interface{}{
  138. "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"},
  139. }
  140. status, body, err := sockRequest("POST", "/containers/"+name+"/start", config)
  141. c.Assert(status, check.Equals, http.StatusInternalServerError)
  142. c.Assert(err, check.IsNil)
  143. if !strings.Contains(string(body), "Duplicate bind") {
  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. func (s *DockerSuite) TestContainerApiStartVolumesFrom(c *check.C) {
  148. volName := "voltst"
  149. volPath := "/tmp"
  150. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  151. c.Fatal(out, err)
  152. }
  153. name := "TestContainerApiStartDupVolumeBinds"
  154. config := map[string]interface{}{
  155. "Image": "busybox",
  156. "Volumes": map[string]struct{}{volPath: {}},
  157. }
  158. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  159. c.Assert(status, check.Equals, http.StatusCreated)
  160. c.Assert(err, check.IsNil)
  161. config = map[string]interface{}{
  162. "VolumesFrom": []string{volName},
  163. }
  164. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  165. c.Assert(status, check.Equals, http.StatusNoContent)
  166. c.Assert(err, check.IsNil)
  167. pth, err := inspectFieldMap(name, "Volumes", volPath)
  168. if err != nil {
  169. c.Fatal(err)
  170. }
  171. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  172. if err != nil {
  173. c.Fatal(err)
  174. }
  175. if pth != pth2 {
  176. c.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  177. }
  178. }
  179. func (s *DockerSuite) TestGetContainerStats(c *check.C) {
  180. var (
  181. name = "statscontainer"
  182. runCmd = exec.Command(dockerBinary, "run", "-d", "--name", name, "busybox", "top")
  183. )
  184. out, _, err := runCommandWithOutput(runCmd)
  185. if err != nil {
  186. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  187. }
  188. type b struct {
  189. status int
  190. body []byte
  191. err error
  192. }
  193. bc := make(chan b, 1)
  194. go func() {
  195. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  196. bc <- b{status, body, err}
  197. }()
  198. // allow some time to stream the stats from the container
  199. time.Sleep(4 * time.Second)
  200. if _, err := runCommand(exec.Command(dockerBinary, "rm", "-f", name)); err != nil {
  201. c.Fatal(err)
  202. }
  203. // collect the results from the stats stream or timeout and fail
  204. // if the stream was not disconnected.
  205. select {
  206. case <-time.After(2 * time.Second):
  207. c.Fatal("stream was not closed after container was removed")
  208. case sr := <-bc:
  209. c.Assert(sr.err, check.IsNil)
  210. c.Assert(sr.status, check.Equals, http.StatusOK)
  211. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  212. var s *types.Stats
  213. // decode only one object from the stream
  214. if err := dec.Decode(&s); err != nil {
  215. c.Fatal(err)
  216. }
  217. }
  218. }
  219. func (s *DockerSuite) TestContainerStatsRmRunning(c *check.C) {
  220. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  221. id := strings.TrimSpace(out)
  222. buf := &channelBuffer{make(chan []byte, 1)}
  223. defer buf.Close()
  224. chErr := make(chan error)
  225. go func() {
  226. _, body, err := sockRequestRaw("GET", "/containers/"+id+"/stats?stream=1", nil, "application/json")
  227. if err != nil {
  228. chErr <- err
  229. }
  230. defer body.Close()
  231. _, err = io.Copy(buf, body)
  232. chErr <- err
  233. }()
  234. defer func() {
  235. c.Assert(<-chErr, check.IsNil)
  236. }()
  237. b := make([]byte, 32)
  238. // make sure we've got some stats
  239. _, err := buf.ReadTimeout(b, 2*time.Second)
  240. c.Assert(err, check.IsNil)
  241. // Now remove without `-f` and make sure we are still pulling stats
  242. _, err = runCommand(exec.Command(dockerBinary, "rm", id))
  243. c.Assert(err, check.Not(check.IsNil), check.Commentf("rm should have failed but didn't"))
  244. _, err = buf.ReadTimeout(b, 2*time.Second)
  245. c.Assert(err, check.IsNil)
  246. dockerCmd(c, "rm", "-f", id)
  247. _, err = buf.ReadTimeout(b, 2*time.Second)
  248. c.Assert(err, check.Not(check.IsNil))
  249. }
  250. func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) {
  251. // TODO: this test does nothing because we are c.Assert'ing in goroutine
  252. var (
  253. name = "statscontainer"
  254. runCmd = exec.Command(dockerBinary, "create", "--name", name, "busybox", "top")
  255. )
  256. out, _, err := runCommandWithOutput(runCmd)
  257. if err != nil {
  258. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  259. }
  260. go func() {
  261. // We'll never get return for GET stats from sockRequest as of now,
  262. // just send request and see if panic or error would happen on daemon side.
  263. status, _, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  264. c.Assert(status, check.Equals, http.StatusOK)
  265. c.Assert(err, check.IsNil)
  266. }()
  267. // allow some time to send request and let daemon deal with it
  268. time.Sleep(1 * time.Second)
  269. }
  270. func (s *DockerSuite) TestBuildApiDockerfilePath(c *check.C) {
  271. // Test to make sure we stop people from trying to leave the
  272. // build context when specifying the path to the dockerfile
  273. buffer := new(bytes.Buffer)
  274. tw := tar.NewWriter(buffer)
  275. defer tw.Close()
  276. dockerfile := []byte("FROM busybox")
  277. if err := tw.WriteHeader(&tar.Header{
  278. Name: "Dockerfile",
  279. Size: int64(len(dockerfile)),
  280. }); err != nil {
  281. c.Fatalf("failed to write tar file header: %v", err)
  282. }
  283. if _, err := tw.Write(dockerfile); err != nil {
  284. c.Fatalf("failed to write tar file content: %v", err)
  285. }
  286. if err := tw.Close(); err != nil {
  287. c.Fatalf("failed to close tar archive: %v", err)
  288. }
  289. res, body, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
  290. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  291. c.Assert(err, check.IsNil)
  292. out, err := readBody(body)
  293. if err != nil {
  294. c.Fatal(err)
  295. }
  296. if !strings.Contains(string(out), "must be within the build context") {
  297. c.Fatalf("Didn't complain about leaving build context: %s", out)
  298. }
  299. }
  300. func (s *DockerSuite) TestBuildApiDockerFileRemote(c *check.C) {
  301. server, err := fakeStorage(map[string]string{
  302. "testD": `FROM busybox
  303. COPY * /tmp/
  304. RUN find / -name ba*
  305. RUN find /tmp/`,
  306. })
  307. if err != nil {
  308. c.Fatal(err)
  309. }
  310. defer server.Close()
  311. res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json")
  312. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  313. c.Assert(err, check.IsNil)
  314. buf, err := readBody(body)
  315. if err != nil {
  316. c.Fatal(err)
  317. }
  318. // Make sure Dockerfile exists.
  319. // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL
  320. out := string(buf)
  321. if !strings.Contains(out, "/tmp/Dockerfile") ||
  322. strings.Contains(out, "baz") {
  323. c.Fatalf("Incorrect output: %s", out)
  324. }
  325. }
  326. func (s *DockerSuite) TestBuildApiLowerDockerfile(c *check.C) {
  327. git, err := fakeGIT("repo", map[string]string{
  328. "dockerfile": `FROM busybox
  329. RUN echo from dockerfile`,
  330. }, false)
  331. if err != nil {
  332. c.Fatal(err)
  333. }
  334. defer git.Close()
  335. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  336. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  337. c.Assert(err, check.IsNil)
  338. buf, err := readBody(body)
  339. if err != nil {
  340. c.Fatal(err)
  341. }
  342. out := string(buf)
  343. if !strings.Contains(out, "from dockerfile") {
  344. c.Fatalf("Incorrect output: %s", out)
  345. }
  346. }
  347. func (s *DockerSuite) TestBuildApiBuildGitWithF(c *check.C) {
  348. git, err := fakeGIT("repo", map[string]string{
  349. "baz": `FROM busybox
  350. RUN echo from baz`,
  351. "Dockerfile": `FROM busybox
  352. RUN echo from Dockerfile`,
  353. }, false)
  354. if err != nil {
  355. c.Fatal(err)
  356. }
  357. defer git.Close()
  358. // Make sure it tries to 'dockerfile' query param value
  359. res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
  360. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  361. c.Assert(err, check.IsNil)
  362. buf, err := readBody(body)
  363. if err != nil {
  364. c.Fatal(err)
  365. }
  366. out := string(buf)
  367. if !strings.Contains(out, "from baz") {
  368. c.Fatalf("Incorrect output: %s", out)
  369. }
  370. }
  371. func (s *DockerSuite) TestBuildApiDoubleDockerfile(c *check.C) {
  372. testRequires(c, UnixCli) // dockerfile overwrites Dockerfile on Windows
  373. git, err := fakeGIT("repo", map[string]string{
  374. "Dockerfile": `FROM busybox
  375. RUN echo from Dockerfile`,
  376. "dockerfile": `FROM busybox
  377. RUN echo from dockerfile`,
  378. }, false)
  379. if err != nil {
  380. c.Fatal(err)
  381. }
  382. defer git.Close()
  383. // Make sure it tries to 'dockerfile' query param value
  384. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  385. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  386. c.Assert(err, check.IsNil)
  387. buf, err := readBody(body)
  388. if err != nil {
  389. c.Fatal(err)
  390. }
  391. out := string(buf)
  392. if !strings.Contains(out, "from Dockerfile") {
  393. c.Fatalf("Incorrect output: %s", out)
  394. }
  395. }
  396. func (s *DockerSuite) TestBuildApiDockerfileSymlink(c *check.C) {
  397. // Test to make sure we stop people from trying to leave the
  398. // build context when specifying a symlink as the path to the dockerfile
  399. buffer := new(bytes.Buffer)
  400. tw := tar.NewWriter(buffer)
  401. defer tw.Close()
  402. if err := tw.WriteHeader(&tar.Header{
  403. Name: "Dockerfile",
  404. Typeflag: tar.TypeSymlink,
  405. Linkname: "/etc/passwd",
  406. }); err != nil {
  407. c.Fatalf("failed to write tar file header: %v", err)
  408. }
  409. if err := tw.Close(); err != nil {
  410. c.Fatalf("failed to close tar archive: %v", err)
  411. }
  412. res, body, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  413. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  414. c.Assert(err, check.IsNil)
  415. out, err := readBody(body)
  416. if err != nil {
  417. c.Fatal(err)
  418. }
  419. // The reason the error is "Cannot locate specified Dockerfile" is because
  420. // in the builder, the symlink is resolved within the context, therefore
  421. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  422. // a nonexistent file.
  423. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  424. c.Fatalf("Didn't complain about leaving build context: %s", out)
  425. }
  426. }
  427. // #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
  428. func (s *DockerSuite) TestPostContainerBindNormalVolume(c *check.C) {
  429. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=one", "busybox"))
  430. if err != nil {
  431. c.Fatal(err, out)
  432. }
  433. fooDir, err := inspectFieldMap("one", "Volumes", "/foo")
  434. if err != nil {
  435. c.Fatal(err)
  436. }
  437. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=two", "busybox"))
  438. if err != nil {
  439. c.Fatal(err, out)
  440. }
  441. bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
  442. status, _, err := sockRequest("POST", "/containers/two/start", bindSpec)
  443. c.Assert(status, check.Equals, http.StatusNoContent)
  444. c.Assert(err, check.IsNil)
  445. fooDir2, err := inspectFieldMap("two", "Volumes", "/foo")
  446. if err != nil {
  447. c.Fatal(err)
  448. }
  449. if fooDir2 != fooDir {
  450. c.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2)
  451. }
  452. }
  453. func (s *DockerSuite) TestContainerApiPause(c *check.C) {
  454. defer unpauseAllContainers()
  455. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sleep", "30")
  456. out, _, err := runCommandWithOutput(runCmd)
  457. if err != nil {
  458. c.Fatalf("failed to create a container: %s, %v", out, err)
  459. }
  460. ContainerID := strings.TrimSpace(out)
  461. status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil)
  462. c.Assert(status, check.Equals, http.StatusNoContent)
  463. c.Assert(err, check.IsNil)
  464. pausedContainers, err := getSliceOfPausedContainers()
  465. if err != nil {
  466. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  467. }
  468. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  469. c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  470. }
  471. status, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil)
  472. c.Assert(status, check.Equals, http.StatusNoContent)
  473. c.Assert(err, check.IsNil)
  474. pausedContainers, err = getSliceOfPausedContainers()
  475. if err != nil {
  476. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  477. }
  478. if pausedContainers != nil {
  479. c.Fatalf("There should be no paused container.")
  480. }
  481. }
  482. func (s *DockerSuite) TestContainerApiTop(c *check.C) {
  483. out, err := exec.Command(dockerBinary, "run", "-d", "busybox", "/bin/sh", "-c", "top").CombinedOutput()
  484. if err != nil {
  485. c.Fatal(err, out)
  486. }
  487. id := strings.TrimSpace(string(out))
  488. if err := waitRun(id); err != nil {
  489. c.Fatal(err)
  490. }
  491. type topResp struct {
  492. Titles []string
  493. Processes [][]string
  494. }
  495. var top topResp
  496. status, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil)
  497. c.Assert(status, check.Equals, http.StatusOK)
  498. c.Assert(err, check.IsNil)
  499. if err := json.Unmarshal(b, &top); err != nil {
  500. c.Fatal(err)
  501. }
  502. if len(top.Titles) != 11 {
  503. c.Fatalf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles)
  504. }
  505. if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
  506. c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
  507. }
  508. if len(top.Processes) != 2 {
  509. c.Fatalf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes)
  510. }
  511. if top.Processes[0][10] != "/bin/sh -c top" {
  512. c.Fatalf("expected `/bin/sh -c top`, found: %s", top.Processes[0][10])
  513. }
  514. if top.Processes[1][10] != "top" {
  515. c.Fatalf("expected `top`, found: %s", top.Processes[1][10])
  516. }
  517. }
  518. func (s *DockerSuite) TestContainerApiCommit(c *check.C) {
  519. cName := "testapicommit"
  520. out, err := exec.Command(dockerBinary, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test").CombinedOutput()
  521. if err != nil {
  522. c.Fatal(err, out)
  523. }
  524. name := "TestContainerApiCommit"
  525. status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil)
  526. c.Assert(status, check.Equals, http.StatusCreated)
  527. c.Assert(err, check.IsNil)
  528. type resp struct {
  529. Id string
  530. }
  531. var img resp
  532. if err := json.Unmarshal(b, &img); err != nil {
  533. c.Fatal(err)
  534. }
  535. cmd, err := inspectField(img.Id, "Config.Cmd")
  536. if err != nil {
  537. c.Fatal(err)
  538. }
  539. if cmd != "{[/bin/sh -c touch /test]}" {
  540. c.Fatalf("got wrong Cmd from commit: %q", cmd)
  541. }
  542. // sanity check, make sure the image is what we think it is
  543. out, err = exec.Command(dockerBinary, "run", img.Id, "ls", "/test").CombinedOutput()
  544. if err != nil {
  545. c.Fatalf("error checking committed image: %v - %q", err, string(out))
  546. }
  547. }
  548. func (s *DockerSuite) TestContainerApiCreate(c *check.C) {
  549. config := map[string]interface{}{
  550. "Image": "busybox",
  551. "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"},
  552. }
  553. status, b, err := sockRequest("POST", "/containers/create", config)
  554. c.Assert(status, check.Equals, http.StatusCreated)
  555. c.Assert(err, check.IsNil)
  556. type createResp struct {
  557. Id string
  558. }
  559. var container createResp
  560. if err := json.Unmarshal(b, &container); err != nil {
  561. c.Fatal(err)
  562. }
  563. out, err := exec.Command(dockerBinary, "start", "-a", container.Id).CombinedOutput()
  564. if err != nil {
  565. c.Fatal(out, err)
  566. }
  567. if strings.TrimSpace(string(out)) != "/test" {
  568. c.Fatalf("expected output `/test`, got %q", out)
  569. }
  570. }
  571. func (s *DockerSuite) TestContainerApiCreateWithHostName(c *check.C) {
  572. hostName := "test-host"
  573. config := map[string]interface{}{
  574. "Image": "busybox",
  575. "Hostname": hostName,
  576. }
  577. status, body, err := sockRequest("POST", "/containers/create", config)
  578. c.Assert(err, check.IsNil)
  579. c.Assert(status, check.Equals, http.StatusCreated)
  580. var container types.ContainerCreateResponse
  581. if err := json.Unmarshal(body, &container); err != nil {
  582. c.Fatal(err)
  583. }
  584. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  585. c.Assert(err, check.IsNil)
  586. c.Assert(status, check.Equals, http.StatusOK)
  587. var containerJSON types.ContainerJSON
  588. if err := json.Unmarshal(body, &containerJSON); err != nil {
  589. c.Fatal(err)
  590. }
  591. if containerJSON.Config.Hostname != hostName {
  592. c.Fatalf("Mismatched Hostname, Expected %s, Actual: %s ", hostName, containerJSON.Config.Hostname)
  593. }
  594. }
  595. func (s *DockerSuite) TestContainerApiCreateWithDomainName(c *check.C) {
  596. domainName := "test-domain"
  597. config := map[string]interface{}{
  598. "Image": "busybox",
  599. "Domainname": domainName,
  600. }
  601. status, body, err := sockRequest("POST", "/containers/create", config)
  602. c.Assert(err, check.IsNil)
  603. c.Assert(status, check.Equals, http.StatusCreated)
  604. var container types.ContainerCreateResponse
  605. if err := json.Unmarshal(body, &container); err != nil {
  606. c.Fatal(err)
  607. }
  608. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  609. c.Assert(err, check.IsNil)
  610. c.Assert(status, check.Equals, http.StatusOK)
  611. var containerJSON types.ContainerJSON
  612. if err := json.Unmarshal(body, &containerJSON); err != nil {
  613. c.Fatal(err)
  614. }
  615. if containerJSON.Config.Domainname != domainName {
  616. c.Fatalf("Mismatched Domainname, Expected %s, Actual: %s ", domainName, containerJSON.Config.Domainname)
  617. }
  618. }
  619. func (s *DockerSuite) TestContainerApiCreateNetworkMode(c *check.C) {
  620. UtilCreateNetworkMode(c, "host")
  621. UtilCreateNetworkMode(c, "bridge")
  622. UtilCreateNetworkMode(c, "container:web1")
  623. }
  624. func UtilCreateNetworkMode(c *check.C, networkMode string) {
  625. config := map[string]interface{}{
  626. "Image": "busybox",
  627. "HostConfig": map[string]interface{}{"NetworkMode": networkMode},
  628. }
  629. status, body, err := sockRequest("POST", "/containers/create", config)
  630. c.Assert(err, check.IsNil)
  631. c.Assert(status, check.Equals, http.StatusCreated)
  632. var container types.ContainerCreateResponse
  633. if err := json.Unmarshal(body, &container); err != nil {
  634. c.Fatal(err)
  635. }
  636. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  637. c.Assert(err, check.IsNil)
  638. c.Assert(status, check.Equals, http.StatusOK)
  639. var containerJSON types.ContainerJSON
  640. if err := json.Unmarshal(body, &containerJSON); err != nil {
  641. c.Fatal(err)
  642. }
  643. if containerJSON.HostConfig.NetworkMode != runconfig.NetworkMode(networkMode) {
  644. c.Fatalf("Mismatched NetworkMode, Expected %s, Actual: %s ", networkMode, containerJSON.HostConfig.NetworkMode)
  645. }
  646. }
  647. func (s *DockerSuite) TestContainerApiCreateWithCpuSharesCpuset(c *check.C) {
  648. config := map[string]interface{}{
  649. "Image": "busybox",
  650. "CpuShares": 512,
  651. "CpusetCpus": "0,1",
  652. }
  653. status, body, err := sockRequest("POST", "/containers/create", config)
  654. c.Assert(err, check.IsNil)
  655. c.Assert(status, check.Equals, http.StatusCreated)
  656. var container types.ContainerCreateResponse
  657. if err := json.Unmarshal(body, &container); err != nil {
  658. c.Fatal(err)
  659. }
  660. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  661. c.Assert(err, check.IsNil)
  662. c.Assert(status, check.Equals, http.StatusOK)
  663. var containerJson types.ContainerJSON
  664. c.Assert(json.Unmarshal(body, &containerJson), check.IsNil)
  665. out, err := inspectField(containerJson.Id, "HostConfig.CpuShares")
  666. c.Assert(err, check.IsNil)
  667. c.Assert(out, check.Equals, "512")
  668. outCpuset, errCpuset := inspectField(containerJson.Id, "HostConfig.CpusetCpus")
  669. c.Assert(errCpuset, check.IsNil, check.Commentf("Output: %s", outCpuset))
  670. c.Assert(outCpuset, check.Equals, "0,1")
  671. }
  672. func (s *DockerSuite) TestContainerApiVerifyHeader(c *check.C) {
  673. config := map[string]interface{}{
  674. "Image": "busybox",
  675. }
  676. create := func(ct string) (*http.Response, io.ReadCloser, error) {
  677. jsonData := bytes.NewBuffer(nil)
  678. if err := json.NewEncoder(jsonData).Encode(config); err != nil {
  679. c.Fatal(err)
  680. }
  681. return sockRequestRaw("POST", "/containers/create", jsonData, ct)
  682. }
  683. // Try with no content-type
  684. res, body, err := create("")
  685. c.Assert(err, check.IsNil)
  686. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  687. body.Close()
  688. // Try with wrong content-type
  689. res, body, err = create("application/xml")
  690. c.Assert(err, check.IsNil)
  691. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  692. body.Close()
  693. // now application/json
  694. res, body, err = create("application/json")
  695. c.Assert(err, check.IsNil)
  696. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  697. body.Close()
  698. }
  699. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  700. // W/o this fix a null in JSON would be parsed into a string var as "null"
  701. func (s *DockerSuite) TestContainerApiPostCreateNull(c *check.C) {
  702. config := `{
  703. "Hostname":"",
  704. "Domainname":"",
  705. "Memory":0,
  706. "MemorySwap":0,
  707. "CpuShares":0,
  708. "Cpuset":null,
  709. "AttachStdin":true,
  710. "AttachStdout":true,
  711. "AttachStderr":true,
  712. "PortSpecs":null,
  713. "ExposedPorts":{},
  714. "Tty":true,
  715. "OpenStdin":true,
  716. "StdinOnce":true,
  717. "Env":[],
  718. "Cmd":"ls",
  719. "Image":"busybox",
  720. "Volumes":{},
  721. "WorkingDir":"",
  722. "Entrypoint":null,
  723. "NetworkDisabled":false,
  724. "OnBuild":null}`
  725. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  726. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  727. c.Assert(err, check.IsNil)
  728. b, err := readBody(body)
  729. if err != nil {
  730. c.Fatal(err)
  731. }
  732. type createResp struct {
  733. Id string
  734. }
  735. var container createResp
  736. if err := json.Unmarshal(b, &container); err != nil {
  737. c.Fatal(err)
  738. }
  739. out, err := inspectField(container.Id, "HostConfig.CpusetCpus")
  740. if err != nil {
  741. c.Fatal(err, out)
  742. }
  743. if out != "" {
  744. c.Fatalf("expected empty string, got %q", out)
  745. }
  746. outMemory, errMemory := inspectField(container.Id, "HostConfig.Memory")
  747. c.Assert(outMemory, check.Equals, "0")
  748. if errMemory != nil {
  749. c.Fatal(errMemory, outMemory)
  750. }
  751. outMemorySwap, errMemorySwap := inspectField(container.Id, "HostConfig.MemorySwap")
  752. c.Assert(outMemorySwap, check.Equals, "0")
  753. if errMemorySwap != nil {
  754. c.Fatal(errMemorySwap, outMemorySwap)
  755. }
  756. }
  757. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  758. config := `{
  759. "Image": "busybox",
  760. "Cmd": "ls",
  761. "OpenStdin": true,
  762. "CpuShares": 100,
  763. "Memory": 524287
  764. }`
  765. res, body, _ := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  766. b, err2 := readBody(body)
  767. if err2 != nil {
  768. c.Fatal(err2)
  769. }
  770. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  771. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  772. }
  773. func (s *DockerSuite) TestStartWithTooLowMemoryLimit(c *check.C) {
  774. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "busybox"))
  775. if err != nil {
  776. c.Fatal(err, out)
  777. }
  778. containerID := strings.TrimSpace(out)
  779. config := `{
  780. "CpuShares": 100,
  781. "Memory": 524287
  782. }`
  783. res, body, _ := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  784. b, err2 := readBody(body)
  785. if err2 != nil {
  786. c.Fatal(err2)
  787. }
  788. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  789. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  790. }
  791. func (s *DockerSuite) TestContainerApiRename(c *check.C) {
  792. runCmd := exec.Command(dockerBinary, "run", "--name", "TestContainerApiRename", "-d", "busybox", "sh")
  793. out, _, err := runCommandWithOutput(runCmd)
  794. c.Assert(err, check.IsNil)
  795. containerID := strings.TrimSpace(out)
  796. newName := "TestContainerApiRenameNew"
  797. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
  798. // 204 No Content is expected, not 200
  799. c.Assert(statusCode, check.Equals, http.StatusNoContent)
  800. c.Assert(err, check.IsNil)
  801. name, err := inspectField(containerID, "Name")
  802. if name != "/"+newName {
  803. c.Fatalf("Failed to rename container, expected %v, got %v. Container rename API failed", newName, name)
  804. }
  805. }
  806. func (s *DockerSuite) TestContainerApiKill(c *check.C) {
  807. name := "test-api-kill"
  808. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  809. out, _, err := runCommandWithOutput(runCmd)
  810. if err != nil {
  811. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  812. }
  813. status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil)
  814. c.Assert(status, check.Equals, http.StatusNoContent)
  815. c.Assert(err, check.IsNil)
  816. state, err := inspectField(name, "State.Running")
  817. if err != nil {
  818. c.Fatal(err)
  819. }
  820. if state != "false" {
  821. c.Fatalf("got wrong State from container %s: %q", name, state)
  822. }
  823. }
  824. func (s *DockerSuite) TestContainerApiRestart(c *check.C) {
  825. name := "test-api-restart"
  826. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  827. out, _, err := runCommandWithOutput(runCmd)
  828. if err != nil {
  829. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  830. }
  831. status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil)
  832. c.Assert(status, check.Equals, http.StatusNoContent)
  833. c.Assert(err, check.IsNil)
  834. if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil {
  835. c.Fatal(err)
  836. }
  837. }
  838. func (s *DockerSuite) TestContainerApiRestartNotimeoutParam(c *check.C) {
  839. name := "test-api-restart-no-timeout-param"
  840. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  841. out, _, err := runCommandWithOutput(runCmd)
  842. if err != nil {
  843. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  844. }
  845. id := strings.TrimSpace(out)
  846. c.Assert(waitRun(id), check.IsNil)
  847. status, _, err := sockRequest("POST", "/containers/"+name+"/restart", nil)
  848. c.Assert(status, check.Equals, http.StatusNoContent)
  849. c.Assert(err, check.IsNil)
  850. if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil {
  851. c.Fatal(err)
  852. }
  853. }
  854. func (s *DockerSuite) TestContainerApiStart(c *check.C) {
  855. name := "testing-start"
  856. config := map[string]interface{}{
  857. "Image": "busybox",
  858. "Cmd": []string{"/bin/sh", "-c", "/bin/top"},
  859. "OpenStdin": true,
  860. }
  861. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  862. c.Assert(status, check.Equals, http.StatusCreated)
  863. c.Assert(err, check.IsNil)
  864. conf := make(map[string]interface{})
  865. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  866. c.Assert(status, check.Equals, http.StatusNoContent)
  867. c.Assert(err, check.IsNil)
  868. // second call to start should give 304
  869. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  870. c.Assert(status, check.Equals, http.StatusNotModified)
  871. c.Assert(err, check.IsNil)
  872. }
  873. func (s *DockerSuite) TestContainerApiStop(c *check.C) {
  874. name := "test-api-stop"
  875. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  876. out, _, err := runCommandWithOutput(runCmd)
  877. if err != nil {
  878. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  879. }
  880. status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  881. c.Assert(status, check.Equals, http.StatusNoContent)
  882. c.Assert(err, check.IsNil)
  883. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  884. c.Fatal(err)
  885. }
  886. // second call to start should give 304
  887. status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  888. c.Assert(status, check.Equals, http.StatusNotModified)
  889. c.Assert(err, check.IsNil)
  890. }
  891. func (s *DockerSuite) TestContainerApiWait(c *check.C) {
  892. name := "test-api-wait"
  893. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sleep", "5")
  894. out, _, err := runCommandWithOutput(runCmd)
  895. if err != nil {
  896. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  897. }
  898. status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil)
  899. c.Assert(status, check.Equals, http.StatusOK)
  900. c.Assert(err, check.IsNil)
  901. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  902. c.Fatal(err)
  903. }
  904. var waitres types.ContainerWaitResponse
  905. if err := json.Unmarshal(body, &waitres); err != nil {
  906. c.Fatalf("unable to unmarshal response body: %v", err)
  907. }
  908. if waitres.StatusCode != 0 {
  909. c.Fatalf("Expected wait response StatusCode to be 0, got %d", waitres.StatusCode)
  910. }
  911. }
  912. func (s *DockerSuite) TestContainerApiCopy(c *check.C) {
  913. name := "test-container-api-copy"
  914. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test.txt")
  915. _, err := runCommand(runCmd)
  916. c.Assert(err, check.IsNil)
  917. postData := types.CopyConfig{
  918. Resource: "/test.txt",
  919. }
  920. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  921. c.Assert(err, check.IsNil)
  922. c.Assert(status, check.Equals, http.StatusOK)
  923. found := false
  924. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  925. h, err := tarReader.Next()
  926. if err != nil {
  927. if err == io.EOF {
  928. break
  929. }
  930. c.Fatal(err)
  931. }
  932. if h.Name == "test.txt" {
  933. found = true
  934. break
  935. }
  936. }
  937. c.Assert(found, check.Equals, true)
  938. }
  939. func (s *DockerSuite) TestContainerApiCopyResourcePathEmpty(c *check.C) {
  940. name := "test-container-api-copy-resource-empty"
  941. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test.txt")
  942. _, err := runCommand(runCmd)
  943. c.Assert(err, check.IsNil)
  944. postData := types.CopyConfig{
  945. Resource: "",
  946. }
  947. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  948. c.Assert(err, check.IsNil)
  949. c.Assert(status, check.Equals, http.StatusInternalServerError)
  950. c.Assert(string(body), check.Matches, "Path cannot be empty\n")
  951. }
  952. func (s *DockerSuite) TestContainerApiCopyResourcePathNotFound(c *check.C) {
  953. name := "test-container-api-copy-resource-not-found"
  954. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox")
  955. _, err := runCommand(runCmd)
  956. c.Assert(err, check.IsNil)
  957. postData := types.CopyConfig{
  958. Resource: "/notexist",
  959. }
  960. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  961. c.Assert(err, check.IsNil)
  962. c.Assert(status, check.Equals, http.StatusInternalServerError)
  963. c.Assert(string(body), check.Matches, "Could not find the file /notexist in container "+name+"\n")
  964. }
  965. func (s *DockerSuite) TestContainerApiCopyContainerNotFound(c *check.C) {
  966. postData := types.CopyConfig{
  967. Resource: "/something",
  968. }
  969. status, _, err := sockRequest("POST", "/containers/notexists/copy", postData)
  970. c.Assert(err, check.IsNil)
  971. c.Assert(status, check.Equals, http.StatusNotFound)
  972. }
  973. func (s *DockerSuite) TestContainerApiDelete(c *check.C) {
  974. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  975. out, _, err := runCommandWithOutput(runCmd)
  976. c.Assert(err, check.IsNil)
  977. id := strings.TrimSpace(out)
  978. c.Assert(waitRun(id), check.IsNil)
  979. stopCmd := exec.Command(dockerBinary, "stop", id)
  980. _, err = runCommand(stopCmd)
  981. c.Assert(err, check.IsNil)
  982. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  983. c.Assert(err, check.IsNil)
  984. c.Assert(status, check.Equals, http.StatusNoContent)
  985. }
  986. func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) {
  987. status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
  988. c.Assert(err, check.IsNil)
  989. c.Assert(status, check.Equals, http.StatusNotFound)
  990. c.Assert(string(body), check.Matches, "no such id: doesnotexist\n")
  991. }
  992. func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) {
  993. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  994. out, _, err := runCommandWithOutput(runCmd)
  995. c.Assert(err, check.IsNil)
  996. id := strings.TrimSpace(out)
  997. c.Assert(waitRun(id), check.IsNil)
  998. status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
  999. c.Assert(err, check.IsNil)
  1000. c.Assert(status, check.Equals, http.StatusNoContent)
  1001. }
  1002. func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) {
  1003. runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "tlink1", "busybox", "top")
  1004. out, _, err := runCommandWithOutput(runCmd)
  1005. c.Assert(err, check.IsNil)
  1006. id := strings.TrimSpace(out)
  1007. c.Assert(waitRun(id), check.IsNil)
  1008. runCmd = exec.Command(dockerBinary, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  1009. out, _, err = runCommandWithOutput(runCmd)
  1010. c.Assert(err, check.IsNil)
  1011. id2 := strings.TrimSpace(out)
  1012. c.Assert(waitRun(id2), check.IsNil)
  1013. links, err := inspectFieldJSON(id2, "HostConfig.Links")
  1014. c.Assert(err, check.IsNil)
  1015. if links != "[\"/tlink1:/tlink2/tlink1\"]" {
  1016. c.Fatal("expected to have links between containers")
  1017. }
  1018. status, _, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
  1019. c.Assert(err, check.IsNil)
  1020. c.Assert(status, check.Equals, http.StatusNoContent)
  1021. linksPostRm, err := inspectFieldJSON(id2, "HostConfig.Links")
  1022. c.Assert(err, check.IsNil)
  1023. if linksPostRm != "null" {
  1024. c.Fatal("call to api deleteContainer links should have removed the specified links")
  1025. }
  1026. }
  1027. func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) {
  1028. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1029. out, _, err := runCommandWithOutput(runCmd)
  1030. c.Assert(err, check.IsNil)
  1031. id := strings.TrimSpace(out)
  1032. c.Assert(waitRun(id), check.IsNil)
  1033. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  1034. c.Assert(status, check.Equals, http.StatusConflict)
  1035. c.Assert(err, check.IsNil)
  1036. }
  1037. func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) {
  1038. testRequires(c, SameHostDaemon)
  1039. runCmd := exec.Command(dockerBinary, "run", "-d", "-v", "/testvolume", "busybox", "top")
  1040. out, _, err := runCommandWithOutput(runCmd)
  1041. c.Assert(err, check.IsNil)
  1042. id := strings.TrimSpace(out)
  1043. c.Assert(waitRun(id), check.IsNil)
  1044. vol, err := inspectFieldMap(id, "Volumes", "/testvolume")
  1045. c.Assert(err, check.IsNil)
  1046. _, err = os.Stat(vol)
  1047. c.Assert(err, check.IsNil)
  1048. status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
  1049. c.Assert(status, check.Equals, http.StatusNoContent)
  1050. c.Assert(err, check.IsNil)
  1051. if _, err := os.Stat(vol); !os.IsNotExist(err) {
  1052. c.Fatalf("expected to get ErrNotExist error, got %v", err)
  1053. }
  1054. }
  1055. // Regression test for https://github.com/docker/docker/issues/6231
  1056. func (s *DockerSuite) TestContainersApiChunkedEncoding(c *check.C) {
  1057. out, _ := dockerCmd(c, "create", "-v", "/foo", "busybox", "true")
  1058. id := strings.TrimSpace(out)
  1059. conn, err := sockConn(time.Duration(10 * time.Second))
  1060. if err != nil {
  1061. c.Fatal(err)
  1062. }
  1063. client := httputil.NewClientConn(conn, nil)
  1064. defer client.Close()
  1065. bindCfg := strings.NewReader(`{"Binds": ["/tmp:/foo"]}`)
  1066. req, err := http.NewRequest("POST", "/containers/"+id+"/start", bindCfg)
  1067. if err != nil {
  1068. c.Fatal(err)
  1069. }
  1070. req.Header.Set("Content-Type", "application/json")
  1071. // This is a cheat to make the http request do chunked encoding
  1072. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  1073. // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
  1074. req.ContentLength = -1
  1075. resp, err := client.Do(req)
  1076. if err != nil {
  1077. c.Fatalf("error starting container with chunked encoding: %v", err)
  1078. }
  1079. resp.Body.Close()
  1080. if resp.StatusCode != 204 {
  1081. c.Fatalf("expected status code 204, got %d", resp.StatusCode)
  1082. }
  1083. out, err = inspectFieldJSON(id, "HostConfig.Binds")
  1084. if err != nil {
  1085. c.Fatal(err)
  1086. }
  1087. var binds []string
  1088. if err := json.NewDecoder(strings.NewReader(out)).Decode(&binds); err != nil {
  1089. c.Fatal(err)
  1090. }
  1091. if len(binds) != 1 {
  1092. c.Fatalf("got unexpected binds: %v", binds)
  1093. }
  1094. expected := "/tmp:/foo"
  1095. if binds[0] != expected {
  1096. c.Fatalf("got incorrect bind spec, wanted %s, got: %s", expected, binds[0])
  1097. }
  1098. }
  1099. func (s *DockerSuite) TestPostContainerStop(c *check.C) {
  1100. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1101. out, _, err := runCommandWithOutput(runCmd)
  1102. c.Assert(err, check.IsNil)
  1103. containerID := strings.TrimSpace(out)
  1104. c.Assert(waitRun(containerID), check.IsNil)
  1105. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/stop", nil)
  1106. // 204 No Content is expected, not 200
  1107. c.Assert(statusCode, check.Equals, http.StatusNoContent)
  1108. c.Assert(err, check.IsNil)
  1109. if err := waitInspect(containerID, "{{ .State.Running }}", "false", 5); err != nil {
  1110. c.Fatal(err)
  1111. }
  1112. }