docker_api_containers_test.go 44 KB

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