docker_api_containers_test.go 41 KB

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