docker_api_containers_test.go 39 KB

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