docker_api_containers_test.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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. "ExposedPorts":{},
  713. "Tty":true,
  714. "OpenStdin":true,
  715. "StdinOnce":true,
  716. "Env":[],
  717. "Cmd":"ls",
  718. "Image":"busybox",
  719. "Volumes":{},
  720. "WorkingDir":"",
  721. "Entrypoint":null,
  722. "NetworkDisabled":false,
  723. "OnBuild":null}`
  724. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  725. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  726. c.Assert(err, check.IsNil)
  727. b, err := readBody(body)
  728. if err != nil {
  729. c.Fatal(err)
  730. }
  731. type createResp struct {
  732. Id string
  733. }
  734. var container createResp
  735. if err := json.Unmarshal(b, &container); err != nil {
  736. c.Fatal(err)
  737. }
  738. out, err := inspectField(container.Id, "HostConfig.CpusetCpus")
  739. if err != nil {
  740. c.Fatal(err, out)
  741. }
  742. if out != "" {
  743. c.Fatalf("expected empty string, got %q", out)
  744. }
  745. outMemory, errMemory := inspectField(container.Id, "HostConfig.Memory")
  746. c.Assert(outMemory, check.Equals, "0")
  747. if errMemory != nil {
  748. c.Fatal(errMemory, outMemory)
  749. }
  750. outMemorySwap, errMemorySwap := inspectField(container.Id, "HostConfig.MemorySwap")
  751. c.Assert(outMemorySwap, check.Equals, "0")
  752. if errMemorySwap != nil {
  753. c.Fatal(errMemorySwap, outMemorySwap)
  754. }
  755. }
  756. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  757. config := `{
  758. "Image": "busybox",
  759. "Cmd": "ls",
  760. "OpenStdin": true,
  761. "CpuShares": 100,
  762. "Memory": 524287
  763. }`
  764. res, body, _ := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  765. b, err2 := readBody(body)
  766. if err2 != nil {
  767. c.Fatal(err2)
  768. }
  769. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  770. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  771. }
  772. func (s *DockerSuite) TestStartWithTooLowMemoryLimit(c *check.C) {
  773. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "busybox"))
  774. if err != nil {
  775. c.Fatal(err, out)
  776. }
  777. containerID := strings.TrimSpace(out)
  778. config := `{
  779. "CpuShares": 100,
  780. "Memory": 524287
  781. }`
  782. res, body, _ := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  783. b, err2 := readBody(body)
  784. if err2 != nil {
  785. c.Fatal(err2)
  786. }
  787. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  788. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  789. }
  790. func (s *DockerSuite) TestContainerApiRename(c *check.C) {
  791. runCmd := exec.Command(dockerBinary, "run", "--name", "TestContainerApiRename", "-d", "busybox", "sh")
  792. out, _, err := runCommandWithOutput(runCmd)
  793. c.Assert(err, check.IsNil)
  794. containerID := strings.TrimSpace(out)
  795. newName := "TestContainerApiRenameNew"
  796. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
  797. // 204 No Content is expected, not 200
  798. c.Assert(statusCode, check.Equals, http.StatusNoContent)
  799. c.Assert(err, check.IsNil)
  800. name, err := inspectField(containerID, "Name")
  801. if name != "/"+newName {
  802. c.Fatalf("Failed to rename container, expected %v, got %v. Container rename API failed", newName, name)
  803. }
  804. }
  805. func (s *DockerSuite) TestContainerApiKill(c *check.C) {
  806. name := "test-api-kill"
  807. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  808. out, _, err := runCommandWithOutput(runCmd)
  809. if err != nil {
  810. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  811. }
  812. status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil)
  813. c.Assert(status, check.Equals, http.StatusNoContent)
  814. c.Assert(err, check.IsNil)
  815. state, err := inspectField(name, "State.Running")
  816. if err != nil {
  817. c.Fatal(err)
  818. }
  819. if state != "false" {
  820. c.Fatalf("got wrong State from container %s: %q", name, state)
  821. }
  822. }
  823. func (s *DockerSuite) TestContainerApiRestart(c *check.C) {
  824. name := "test-api-restart"
  825. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  826. out, _, err := runCommandWithOutput(runCmd)
  827. if err != nil {
  828. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  829. }
  830. status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil)
  831. c.Assert(status, check.Equals, http.StatusNoContent)
  832. c.Assert(err, check.IsNil)
  833. if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil {
  834. c.Fatal(err)
  835. }
  836. }
  837. func (s *DockerSuite) TestContainerApiRestartNotimeoutParam(c *check.C) {
  838. name := "test-api-restart-no-timeout-param"
  839. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  840. out, _, err := runCommandWithOutput(runCmd)
  841. if err != nil {
  842. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  843. }
  844. id := strings.TrimSpace(out)
  845. c.Assert(waitRun(id), check.IsNil)
  846. status, _, err := sockRequest("POST", "/containers/"+name+"/restart", nil)
  847. c.Assert(status, check.Equals, http.StatusNoContent)
  848. c.Assert(err, check.IsNil)
  849. if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil {
  850. c.Fatal(err)
  851. }
  852. }
  853. func (s *DockerSuite) TestContainerApiStart(c *check.C) {
  854. name := "testing-start"
  855. config := map[string]interface{}{
  856. "Image": "busybox",
  857. "Cmd": []string{"/bin/sh", "-c", "/bin/top"},
  858. "OpenStdin": true,
  859. }
  860. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  861. c.Assert(status, check.Equals, http.StatusCreated)
  862. c.Assert(err, check.IsNil)
  863. conf := make(map[string]interface{})
  864. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  865. c.Assert(status, check.Equals, http.StatusNoContent)
  866. c.Assert(err, check.IsNil)
  867. // second call to start should give 304
  868. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  869. c.Assert(status, check.Equals, http.StatusNotModified)
  870. c.Assert(err, check.IsNil)
  871. }
  872. func (s *DockerSuite) TestContainerApiStop(c *check.C) {
  873. name := "test-api-stop"
  874. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  875. out, _, err := runCommandWithOutput(runCmd)
  876. if err != nil {
  877. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  878. }
  879. status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  880. c.Assert(status, check.Equals, http.StatusNoContent)
  881. c.Assert(err, check.IsNil)
  882. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  883. c.Fatal(err)
  884. }
  885. // second call to start should give 304
  886. status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  887. c.Assert(status, check.Equals, http.StatusNotModified)
  888. c.Assert(err, check.IsNil)
  889. }
  890. func (s *DockerSuite) TestContainerApiWait(c *check.C) {
  891. name := "test-api-wait"
  892. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sleep", "5")
  893. out, _, err := runCommandWithOutput(runCmd)
  894. if err != nil {
  895. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  896. }
  897. status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil)
  898. c.Assert(status, check.Equals, http.StatusOK)
  899. c.Assert(err, check.IsNil)
  900. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  901. c.Fatal(err)
  902. }
  903. var waitres types.ContainerWaitResponse
  904. if err := json.Unmarshal(body, &waitres); err != nil {
  905. c.Fatalf("unable to unmarshal response body: %v", err)
  906. }
  907. if waitres.StatusCode != 0 {
  908. c.Fatalf("Expected wait response StatusCode to be 0, got %d", waitres.StatusCode)
  909. }
  910. }
  911. func (s *DockerSuite) TestContainerApiCopy(c *check.C) {
  912. name := "test-container-api-copy"
  913. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test.txt")
  914. _, err := runCommand(runCmd)
  915. c.Assert(err, check.IsNil)
  916. postData := types.CopyConfig{
  917. Resource: "/test.txt",
  918. }
  919. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  920. c.Assert(err, check.IsNil)
  921. c.Assert(status, check.Equals, http.StatusOK)
  922. found := false
  923. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  924. h, err := tarReader.Next()
  925. if err != nil {
  926. if err == io.EOF {
  927. break
  928. }
  929. c.Fatal(err)
  930. }
  931. if h.Name == "test.txt" {
  932. found = true
  933. break
  934. }
  935. }
  936. c.Assert(found, check.Equals, true)
  937. }
  938. func (s *DockerSuite) TestContainerApiCopyResourcePathEmpty(c *check.C) {
  939. name := "test-container-api-copy-resource-empty"
  940. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test.txt")
  941. _, err := runCommand(runCmd)
  942. c.Assert(err, check.IsNil)
  943. postData := types.CopyConfig{
  944. Resource: "",
  945. }
  946. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  947. c.Assert(err, check.IsNil)
  948. c.Assert(status, check.Equals, http.StatusInternalServerError)
  949. c.Assert(string(body), check.Matches, "Path cannot be empty\n")
  950. }
  951. func (s *DockerSuite) TestContainerApiCopyResourcePathNotFound(c *check.C) {
  952. name := "test-container-api-copy-resource-not-found"
  953. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox")
  954. _, err := runCommand(runCmd)
  955. c.Assert(err, check.IsNil)
  956. postData := types.CopyConfig{
  957. Resource: "/notexist",
  958. }
  959. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  960. c.Assert(err, check.IsNil)
  961. c.Assert(status, check.Equals, http.StatusInternalServerError)
  962. c.Assert(string(body), check.Matches, "Could not find the file /notexist in container "+name+"\n")
  963. }
  964. func (s *DockerSuite) TestContainerApiCopyContainerNotFound(c *check.C) {
  965. postData := types.CopyConfig{
  966. Resource: "/something",
  967. }
  968. status, _, err := sockRequest("POST", "/containers/notexists/copy", postData)
  969. c.Assert(err, check.IsNil)
  970. c.Assert(status, check.Equals, http.StatusNotFound)
  971. }
  972. func (s *DockerSuite) TestContainerApiDelete(c *check.C) {
  973. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  974. out, _, err := runCommandWithOutput(runCmd)
  975. c.Assert(err, check.IsNil)
  976. id := strings.TrimSpace(out)
  977. c.Assert(waitRun(id), check.IsNil)
  978. stopCmd := exec.Command(dockerBinary, "stop", id)
  979. _, err = runCommand(stopCmd)
  980. c.Assert(err, check.IsNil)
  981. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  982. c.Assert(err, check.IsNil)
  983. c.Assert(status, check.Equals, http.StatusNoContent)
  984. }
  985. func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) {
  986. status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
  987. c.Assert(err, check.IsNil)
  988. c.Assert(status, check.Equals, http.StatusNotFound)
  989. c.Assert(string(body), check.Matches, "no such id: doesnotexist\n")
  990. }
  991. func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) {
  992. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  993. out, _, err := runCommandWithOutput(runCmd)
  994. c.Assert(err, check.IsNil)
  995. id := strings.TrimSpace(out)
  996. c.Assert(waitRun(id), check.IsNil)
  997. status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
  998. c.Assert(err, check.IsNil)
  999. c.Assert(status, check.Equals, http.StatusNoContent)
  1000. }
  1001. func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) {
  1002. runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "tlink1", "busybox", "top")
  1003. out, _, err := runCommandWithOutput(runCmd)
  1004. c.Assert(err, check.IsNil)
  1005. id := strings.TrimSpace(out)
  1006. c.Assert(waitRun(id), check.IsNil)
  1007. runCmd = exec.Command(dockerBinary, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  1008. out, _, err = runCommandWithOutput(runCmd)
  1009. c.Assert(err, check.IsNil)
  1010. id2 := strings.TrimSpace(out)
  1011. c.Assert(waitRun(id2), check.IsNil)
  1012. links, err := inspectFieldJSON(id2, "HostConfig.Links")
  1013. c.Assert(err, check.IsNil)
  1014. if links != "[\"/tlink1:/tlink2/tlink1\"]" {
  1015. c.Fatal("expected to have links between containers")
  1016. }
  1017. status, _, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
  1018. c.Assert(err, check.IsNil)
  1019. c.Assert(status, check.Equals, http.StatusNoContent)
  1020. linksPostRm, err := inspectFieldJSON(id2, "HostConfig.Links")
  1021. c.Assert(err, check.IsNil)
  1022. if linksPostRm != "null" {
  1023. c.Fatal("call to api deleteContainer links should have removed the specified links")
  1024. }
  1025. }
  1026. func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) {
  1027. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1028. out, _, err := runCommandWithOutput(runCmd)
  1029. c.Assert(err, check.IsNil)
  1030. id := strings.TrimSpace(out)
  1031. c.Assert(waitRun(id), check.IsNil)
  1032. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  1033. c.Assert(status, check.Equals, http.StatusConflict)
  1034. c.Assert(err, check.IsNil)
  1035. }
  1036. func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) {
  1037. testRequires(c, SameHostDaemon)
  1038. runCmd := exec.Command(dockerBinary, "run", "-d", "-v", "/testvolume", "busybox", "top")
  1039. out, _, err := runCommandWithOutput(runCmd)
  1040. c.Assert(err, check.IsNil)
  1041. id := strings.TrimSpace(out)
  1042. c.Assert(waitRun(id), check.IsNil)
  1043. vol, err := inspectFieldMap(id, "Volumes", "/testvolume")
  1044. c.Assert(err, check.IsNil)
  1045. _, err = os.Stat(vol)
  1046. c.Assert(err, check.IsNil)
  1047. status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
  1048. c.Assert(status, check.Equals, http.StatusNoContent)
  1049. c.Assert(err, check.IsNil)
  1050. if _, err := os.Stat(vol); !os.IsNotExist(err) {
  1051. c.Fatalf("expected to get ErrNotExist error, got %v", err)
  1052. }
  1053. }
  1054. // Regression test for https://github.com/docker/docker/issues/6231
  1055. func (s *DockerSuite) TestContainersApiChunkedEncoding(c *check.C) {
  1056. out, _ := dockerCmd(c, "create", "-v", "/foo", "busybox", "true")
  1057. id := strings.TrimSpace(out)
  1058. conn, err := sockConn(time.Duration(10 * time.Second))
  1059. if err != nil {
  1060. c.Fatal(err)
  1061. }
  1062. client := httputil.NewClientConn(conn, nil)
  1063. defer client.Close()
  1064. bindCfg := strings.NewReader(`{"Binds": ["/tmp:/foo"]}`)
  1065. req, err := http.NewRequest("POST", "/containers/"+id+"/start", bindCfg)
  1066. if err != nil {
  1067. c.Fatal(err)
  1068. }
  1069. req.Header.Set("Content-Type", "application/json")
  1070. // This is a cheat to make the http request do chunked encoding
  1071. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  1072. // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
  1073. req.ContentLength = -1
  1074. resp, err := client.Do(req)
  1075. if err != nil {
  1076. c.Fatalf("error starting container with chunked encoding: %v", err)
  1077. }
  1078. resp.Body.Close()
  1079. if resp.StatusCode != 204 {
  1080. c.Fatalf("expected status code 204, got %d", resp.StatusCode)
  1081. }
  1082. out, err = inspectFieldJSON(id, "HostConfig.Binds")
  1083. if err != nil {
  1084. c.Fatal(err)
  1085. }
  1086. var binds []string
  1087. if err := json.NewDecoder(strings.NewReader(out)).Decode(&binds); err != nil {
  1088. c.Fatal(err)
  1089. }
  1090. if len(binds) != 1 {
  1091. c.Fatalf("got unexpected binds: %v", binds)
  1092. }
  1093. expected := "/tmp:/foo"
  1094. if binds[0] != expected {
  1095. c.Fatalf("got incorrect bind spec, wanted %s, got: %s", expected, binds[0])
  1096. }
  1097. }
  1098. func (s *DockerSuite) TestPostContainerStop(c *check.C) {
  1099. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1100. out, _, err := runCommandWithOutput(runCmd)
  1101. c.Assert(err, check.IsNil)
  1102. containerID := strings.TrimSpace(out)
  1103. c.Assert(waitRun(containerID), check.IsNil)
  1104. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/stop", nil)
  1105. // 204 No Content is expected, not 200
  1106. c.Assert(statusCode, check.Equals, http.StatusNoContent)
  1107. c.Assert(err, check.IsNil)
  1108. if err := waitInspect(containerID, "{{ .State.Running }}", "false", 5); err != nil {
  1109. c.Fatal(err)
  1110. }
  1111. }