docker_api_containers_test.go 38 KB

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