docker_api_containers_test.go 43 KB

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