docker_api_containers_test.go 38 KB

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