docker_api_containers_test.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. package main
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "encoding/json"
  6. "io"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "strings"
  11. "time"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/pkg/stringid"
  14. "github.com/go-check/check"
  15. )
  16. func (s *DockerSuite) TestContainerApiGetAll(c *check.C) {
  17. startCount, err := getContainerCount()
  18. if err != nil {
  19. c.Fatalf("Cannot query container count: %v", err)
  20. }
  21. name := "getall"
  22. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "true")
  23. out, _, err := runCommandWithOutput(runCmd)
  24. if err != nil {
  25. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  26. }
  27. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  28. c.Assert(status, check.Equals, http.StatusOK)
  29. c.Assert(err, check.IsNil)
  30. var inspectJSON []struct {
  31. Names []string
  32. }
  33. if err = json.Unmarshal(body, &inspectJSON); err != nil {
  34. c.Fatalf("unable to unmarshal response body: %v", err)
  35. }
  36. if len(inspectJSON) != startCount+1 {
  37. c.Fatalf("Expected %d container(s), %d found (started with: %d)", startCount+1, len(inspectJSON), startCount)
  38. }
  39. if actual := inspectJSON[0].Names[0]; actual != "/"+name {
  40. c.Fatalf("Container Name mismatch. Expected: %q, received: %q\n", "/"+name, actual)
  41. }
  42. }
  43. func (s *DockerSuite) TestContainerApiGetExport(c *check.C) {
  44. name := "exportcontainer"
  45. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test")
  46. out, _, err := runCommandWithOutput(runCmd)
  47. if err != nil {
  48. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  49. }
  50. status, body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
  51. c.Assert(status, check.Equals, http.StatusOK)
  52. c.Assert(err, check.IsNil)
  53. found := false
  54. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  55. h, err := tarReader.Next()
  56. if err != nil {
  57. if err == io.EOF {
  58. break
  59. }
  60. c.Fatal(err)
  61. }
  62. if h.Name == "test" {
  63. found = true
  64. break
  65. }
  66. }
  67. if !found {
  68. c.Fatalf("The created test file has not been found in the exported image")
  69. }
  70. }
  71. func (s *DockerSuite) TestContainerApiGetChanges(c *check.C) {
  72. name := "changescontainer"
  73. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "rm", "/etc/passwd")
  74. out, _, err := runCommandWithOutput(runCmd)
  75. if err != nil {
  76. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  77. }
  78. status, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
  79. c.Assert(status, check.Equals, http.StatusOK)
  80. c.Assert(err, check.IsNil)
  81. changes := []struct {
  82. Kind int
  83. Path string
  84. }{}
  85. if err = json.Unmarshal(body, &changes); err != nil {
  86. c.Fatalf("unable to unmarshal response body: %v", err)
  87. }
  88. // Check the changelog for removal of /etc/passwd
  89. success := false
  90. for _, elem := range changes {
  91. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  92. success = true
  93. }
  94. }
  95. if !success {
  96. c.Fatalf("/etc/passwd has been removed but is not present in the diff")
  97. }
  98. }
  99. func (s *DockerSuite) TestContainerApiStartVolumeBinds(c *check.C) {
  100. name := "testing"
  101. config := map[string]interface{}{
  102. "Image": "busybox",
  103. "Volumes": map[string]struct{}{"/tmp": {}},
  104. }
  105. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  106. c.Assert(status, check.Equals, http.StatusCreated)
  107. c.Assert(err, check.IsNil)
  108. bindPath := randomUnixTmpDirPath("test")
  109. config = map[string]interface{}{
  110. "Binds": []string{bindPath + ":/tmp"},
  111. }
  112. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  113. c.Assert(status, check.Equals, http.StatusNoContent)
  114. c.Assert(err, check.IsNil)
  115. pth, err := inspectFieldMap(name, "Volumes", "/tmp")
  116. if err != nil {
  117. c.Fatal(err)
  118. }
  119. if pth != bindPath {
  120. c.Fatalf("expected volume host path to be %s, got %s", bindPath, pth)
  121. }
  122. }
  123. // Test for GH#10618
  124. func (s *DockerSuite) TestContainerApiStartDupVolumeBinds(c *check.C) {
  125. name := "testdups"
  126. config := map[string]interface{}{
  127. "Image": "busybox",
  128. "Volumes": map[string]struct{}{"/tmp": {}},
  129. }
  130. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  131. c.Assert(status, check.Equals, http.StatusCreated)
  132. c.Assert(err, check.IsNil)
  133. bindPath1 := randomUnixTmpDirPath("test1")
  134. bindPath2 := randomUnixTmpDirPath("test2")
  135. config = map[string]interface{}{
  136. "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"},
  137. }
  138. status, body, err := sockRequest("POST", "/containers/"+name+"/start", config)
  139. c.Assert(status, check.Equals, http.StatusInternalServerError)
  140. c.Assert(err, check.IsNil)
  141. if !strings.Contains(string(body), "Duplicate volume") {
  142. c.Fatalf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(body), err)
  143. }
  144. }
  145. func (s *DockerSuite) TestContainerApiStartVolumesFrom(c *check.C) {
  146. volName := "voltst"
  147. volPath := "/tmp"
  148. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  149. c.Fatal(out, err)
  150. }
  151. name := "TestContainerApiStartDupVolumeBinds"
  152. config := map[string]interface{}{
  153. "Image": "busybox",
  154. "Volumes": map[string]struct{}{volPath: {}},
  155. }
  156. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  157. c.Assert(status, check.Equals, http.StatusCreated)
  158. c.Assert(err, check.IsNil)
  159. config = map[string]interface{}{
  160. "VolumesFrom": []string{volName},
  161. }
  162. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  163. c.Assert(status, check.Equals, http.StatusNoContent)
  164. c.Assert(err, check.IsNil)
  165. pth, err := inspectFieldMap(name, "Volumes", volPath)
  166. if err != nil {
  167. c.Fatal(err)
  168. }
  169. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  170. if err != nil {
  171. c.Fatal(err)
  172. }
  173. if pth != pth2 {
  174. c.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  175. }
  176. }
  177. // Ensure that volumes-from has priority over binds/anything else
  178. // This is pretty much the same as TestRunApplyVolumesFromBeforeVolumes, except with passing the VolumesFrom and the bind on start
  179. func (s *DockerSuite) TestVolumesFromHasPriority(c *check.C) {
  180. volName := "voltst2"
  181. volPath := "/tmp"
  182. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  183. c.Fatal(out, err)
  184. }
  185. name := "testing"
  186. config := map[string]interface{}{
  187. "Image": "busybox",
  188. "Volumes": map[string]struct{}{volPath: {}},
  189. }
  190. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  191. c.Assert(status, check.Equals, http.StatusCreated)
  192. c.Assert(err, check.IsNil)
  193. bindPath := randomUnixTmpDirPath("test")
  194. config = map[string]interface{}{
  195. "VolumesFrom": []string{volName},
  196. "Binds": []string{bindPath + ":/tmp"},
  197. }
  198. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  199. c.Assert(status, check.Equals, http.StatusNoContent)
  200. c.Assert(err, check.IsNil)
  201. pth, err := inspectFieldMap(name, "Volumes", volPath)
  202. if err != nil {
  203. c.Fatal(err)
  204. }
  205. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  206. if err != nil {
  207. c.Fatal(err)
  208. }
  209. if pth != pth2 {
  210. c.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  211. }
  212. }
  213. func (s *DockerSuite) TestGetContainerStats(c *check.C) {
  214. var (
  215. name = "statscontainer"
  216. runCmd = exec.Command(dockerBinary, "run", "-d", "--name", name, "busybox", "top")
  217. )
  218. out, _, err := runCommandWithOutput(runCmd)
  219. if err != nil {
  220. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  221. }
  222. type b struct {
  223. status int
  224. body []byte
  225. err error
  226. }
  227. bc := make(chan b, 1)
  228. go func() {
  229. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  230. bc <- b{status, body, err}
  231. }()
  232. // allow some time to stream the stats from the container
  233. time.Sleep(4 * time.Second)
  234. if _, err := runCommand(exec.Command(dockerBinary, "rm", "-f", name)); err != nil {
  235. c.Fatal(err)
  236. }
  237. // collect the results from the stats stream or timeout and fail
  238. // if the stream was not disconnected.
  239. select {
  240. case <-time.After(2 * time.Second):
  241. c.Fatal("stream was not closed after container was removed")
  242. case sr := <-bc:
  243. c.Assert(sr.err, check.IsNil)
  244. c.Assert(sr.status, check.Equals, http.StatusOK)
  245. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  246. var s *types.Stats
  247. // decode only one object from the stream
  248. if err := dec.Decode(&s); err != nil {
  249. c.Fatal(err)
  250. }
  251. }
  252. }
  253. func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) {
  254. // TODO: this test does nothing because we are c.Assert'ing in goroutine
  255. var (
  256. name = "statscontainer"
  257. runCmd = exec.Command(dockerBinary, "create", "--name", name, "busybox", "top")
  258. )
  259. out, _, err := runCommandWithOutput(runCmd)
  260. if err != nil {
  261. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  262. }
  263. go func() {
  264. // We'll never get return for GET stats from sockRequest as of now,
  265. // just send request and see if panic or error would happen on daemon side.
  266. status, _, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  267. c.Assert(status, check.Equals, http.StatusOK)
  268. c.Assert(err, check.IsNil)
  269. }()
  270. // allow some time to send request and let daemon deal with it
  271. time.Sleep(1 * time.Second)
  272. }
  273. func (s *DockerSuite) TestBuildApiDockerfilePath(c *check.C) {
  274. // Test to make sure we stop people from trying to leave the
  275. // build context when specifying the path to the dockerfile
  276. buffer := new(bytes.Buffer)
  277. tw := tar.NewWriter(buffer)
  278. defer tw.Close()
  279. dockerfile := []byte("FROM busybox")
  280. if err := tw.WriteHeader(&tar.Header{
  281. Name: "Dockerfile",
  282. Size: int64(len(dockerfile)),
  283. }); err != nil {
  284. c.Fatalf("failed to write tar file header: %v", err)
  285. }
  286. if _, err := tw.Write(dockerfile); err != nil {
  287. c.Fatalf("failed to write tar file content: %v", err)
  288. }
  289. if err := tw.Close(); err != nil {
  290. c.Fatalf("failed to close tar archive: %v", err)
  291. }
  292. res, body, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
  293. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  294. c.Assert(err, check.IsNil)
  295. out, err := readBody(body)
  296. if err != nil {
  297. c.Fatal(err)
  298. }
  299. if !strings.Contains(string(out), "must be within the build context") {
  300. c.Fatalf("Didn't complain about leaving build context: %s", out)
  301. }
  302. }
  303. func (s *DockerSuite) TestBuildApiDockerFileRemote(c *check.C) {
  304. server, err := fakeStorage(map[string]string{
  305. "testD": `FROM busybox
  306. COPY * /tmp/
  307. RUN find / -name ba*
  308. RUN find /tmp/`,
  309. })
  310. if err != nil {
  311. c.Fatal(err)
  312. }
  313. defer server.Close()
  314. res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json")
  315. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  316. c.Assert(err, check.IsNil)
  317. buf, err := readBody(body)
  318. if err != nil {
  319. c.Fatal(err)
  320. }
  321. // Make sure Dockerfile exists.
  322. // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL
  323. out := string(buf)
  324. if !strings.Contains(out, "/tmp/Dockerfile") ||
  325. strings.Contains(out, "baz") {
  326. c.Fatalf("Incorrect output: %s", out)
  327. }
  328. }
  329. func (s *DockerSuite) TestBuildApiLowerDockerfile(c *check.C) {
  330. git, err := fakeGIT("repo", map[string]string{
  331. "dockerfile": `FROM busybox
  332. RUN echo from dockerfile`,
  333. }, false)
  334. if err != nil {
  335. c.Fatal(err)
  336. }
  337. defer git.Close()
  338. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  339. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  340. c.Assert(err, check.IsNil)
  341. buf, err := readBody(body)
  342. if err != nil {
  343. c.Fatal(err)
  344. }
  345. out := string(buf)
  346. if !strings.Contains(out, "from dockerfile") {
  347. c.Fatalf("Incorrect output: %s", out)
  348. }
  349. }
  350. func (s *DockerSuite) TestBuildApiBuildGitWithF(c *check.C) {
  351. git, err := fakeGIT("repo", map[string]string{
  352. "baz": `FROM busybox
  353. RUN echo from baz`,
  354. "Dockerfile": `FROM busybox
  355. RUN echo from Dockerfile`,
  356. }, false)
  357. if err != nil {
  358. c.Fatal(err)
  359. }
  360. defer git.Close()
  361. // Make sure it tries to 'dockerfile' query param value
  362. res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
  363. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  364. c.Assert(err, check.IsNil)
  365. buf, err := readBody(body)
  366. if err != nil {
  367. c.Fatal(err)
  368. }
  369. out := string(buf)
  370. if !strings.Contains(out, "from baz") {
  371. c.Fatalf("Incorrect output: %s", out)
  372. }
  373. }
  374. func (s *DockerSuite) TestBuildApiDoubleDockerfile(c *check.C) {
  375. testRequires(c, UnixCli) // dockerfile overwrites Dockerfile on Windows
  376. git, err := fakeGIT("repo", map[string]string{
  377. "Dockerfile": `FROM busybox
  378. RUN echo from Dockerfile`,
  379. "dockerfile": `FROM busybox
  380. RUN echo from dockerfile`,
  381. }, false)
  382. if err != nil {
  383. c.Fatal(err)
  384. }
  385. defer git.Close()
  386. // Make sure it tries to 'dockerfile' query param value
  387. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  388. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  389. c.Assert(err, check.IsNil)
  390. buf, err := readBody(body)
  391. if err != nil {
  392. c.Fatal(err)
  393. }
  394. out := string(buf)
  395. if !strings.Contains(out, "from Dockerfile") {
  396. c.Fatalf("Incorrect output: %s", out)
  397. }
  398. }
  399. func (s *DockerSuite) TestBuildApiDockerfileSymlink(c *check.C) {
  400. // Test to make sure we stop people from trying to leave the
  401. // build context when specifying a symlink as the path to the dockerfile
  402. buffer := new(bytes.Buffer)
  403. tw := tar.NewWriter(buffer)
  404. defer tw.Close()
  405. if err := tw.WriteHeader(&tar.Header{
  406. Name: "Dockerfile",
  407. Typeflag: tar.TypeSymlink,
  408. Linkname: "/etc/passwd",
  409. }); err != nil {
  410. c.Fatalf("failed to write tar file header: %v", err)
  411. }
  412. if err := tw.Close(); err != nil {
  413. c.Fatalf("failed to close tar archive: %v", err)
  414. }
  415. res, body, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  416. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  417. c.Assert(err, check.IsNil)
  418. out, err := readBody(body)
  419. if err != nil {
  420. c.Fatal(err)
  421. }
  422. // The reason the error is "Cannot locate specified Dockerfile" is because
  423. // in the builder, the symlink is resolved within the context, therefore
  424. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  425. // a nonexistent file.
  426. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  427. c.Fatalf("Didn't complain about leaving build context: %s", out)
  428. }
  429. }
  430. // #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
  431. func (s *DockerSuite) TestPostContainerBindNormalVolume(c *check.C) {
  432. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=one", "busybox"))
  433. if err != nil {
  434. c.Fatal(err, out)
  435. }
  436. fooDir, err := inspectFieldMap("one", "Volumes", "/foo")
  437. if err != nil {
  438. c.Fatal(err)
  439. }
  440. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=two", "busybox"))
  441. if err != nil {
  442. c.Fatal(err, out)
  443. }
  444. bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
  445. status, _, err := sockRequest("POST", "/containers/two/start", bindSpec)
  446. c.Assert(status, check.Equals, http.StatusNoContent)
  447. c.Assert(err, check.IsNil)
  448. fooDir2, err := inspectFieldMap("two", "Volumes", "/foo")
  449. if err != nil {
  450. c.Fatal(err)
  451. }
  452. if fooDir2 != fooDir {
  453. c.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2)
  454. }
  455. }
  456. func (s *DockerSuite) TestContainerApiPause(c *check.C) {
  457. defer unpauseAllContainers()
  458. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sleep", "30")
  459. out, _, err := runCommandWithOutput(runCmd)
  460. if err != nil {
  461. c.Fatalf("failed to create a container: %s, %v", out, err)
  462. }
  463. ContainerID := strings.TrimSpace(out)
  464. status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil)
  465. c.Assert(status, check.Equals, http.StatusNoContent)
  466. c.Assert(err, check.IsNil)
  467. pausedContainers, err := getSliceOfPausedContainers()
  468. if err != nil {
  469. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  470. }
  471. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  472. c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  473. }
  474. status, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil)
  475. c.Assert(status, check.Equals, http.StatusNoContent)
  476. c.Assert(err, check.IsNil)
  477. pausedContainers, err = getSliceOfPausedContainers()
  478. if err != nil {
  479. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  480. }
  481. if pausedContainers != nil {
  482. c.Fatalf("There should be no paused container.")
  483. }
  484. }
  485. func (s *DockerSuite) TestContainerApiTop(c *check.C) {
  486. out, err := exec.Command(dockerBinary, "run", "-d", "busybox", "/bin/sh", "-c", "top").CombinedOutput()
  487. if err != nil {
  488. c.Fatal(err, out)
  489. }
  490. id := strings.TrimSpace(string(out))
  491. if err := waitRun(id); err != nil {
  492. c.Fatal(err)
  493. }
  494. type topResp struct {
  495. Titles []string
  496. Processes [][]string
  497. }
  498. var top topResp
  499. status, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil)
  500. c.Assert(status, check.Equals, http.StatusOK)
  501. c.Assert(err, check.IsNil)
  502. if err := json.Unmarshal(b, &top); err != nil {
  503. c.Fatal(err)
  504. }
  505. if len(top.Titles) != 11 {
  506. c.Fatalf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles)
  507. }
  508. if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
  509. c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
  510. }
  511. if len(top.Processes) != 2 {
  512. c.Fatalf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes)
  513. }
  514. if top.Processes[0][10] != "/bin/sh -c top" {
  515. c.Fatalf("expected `/bin/sh -c top`, found: %s", top.Processes[0][10])
  516. }
  517. if top.Processes[1][10] != "top" {
  518. c.Fatalf("expected `top`, found: %s", top.Processes[1][10])
  519. }
  520. }
  521. func (s *DockerSuite) TestContainerApiCommit(c *check.C) {
  522. cName := "testapicommit"
  523. out, err := exec.Command(dockerBinary, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test").CombinedOutput()
  524. if err != nil {
  525. c.Fatal(err, out)
  526. }
  527. name := "TestContainerApiCommit"
  528. status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil)
  529. c.Assert(status, check.Equals, http.StatusCreated)
  530. c.Assert(err, check.IsNil)
  531. type resp struct {
  532. Id string
  533. }
  534. var img resp
  535. if err := json.Unmarshal(b, &img); err != nil {
  536. c.Fatal(err)
  537. }
  538. cmd, err := inspectField(img.Id, "Config.Cmd")
  539. if err != nil {
  540. c.Fatal(err)
  541. }
  542. if cmd != "{[/bin/sh -c touch /test]}" {
  543. c.Fatalf("got wrong Cmd from commit: %q", cmd)
  544. }
  545. // sanity check, make sure the image is what we think it is
  546. out, err = exec.Command(dockerBinary, "run", img.Id, "ls", "/test").CombinedOutput()
  547. if err != nil {
  548. c.Fatalf("error checking committed image: %v - %q", err, string(out))
  549. }
  550. }
  551. func (s *DockerSuite) TestContainerApiCreate(c *check.C) {
  552. config := map[string]interface{}{
  553. "Image": "busybox",
  554. "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"},
  555. }
  556. status, b, err := sockRequest("POST", "/containers/create", config)
  557. c.Assert(status, check.Equals, http.StatusCreated)
  558. c.Assert(err, check.IsNil)
  559. type createResp struct {
  560. Id string
  561. }
  562. var container createResp
  563. if err := json.Unmarshal(b, &container); err != nil {
  564. c.Fatal(err)
  565. }
  566. out, err := exec.Command(dockerBinary, "start", "-a", container.Id).CombinedOutput()
  567. if err != nil {
  568. c.Fatal(out, err)
  569. }
  570. if strings.TrimSpace(string(out)) != "/test" {
  571. c.Fatalf("expected output `/test`, got %q", out)
  572. }
  573. }
  574. func (s *DockerSuite) TestContainerApiCreateWithHostName(c *check.C) {
  575. var hostName = "test-host"
  576. config := map[string]interface{}{
  577. "Image": "busybox",
  578. "Hostname": hostName,
  579. }
  580. _, b, err := sockRequest("POST", "/containers/create", config)
  581. if err != nil && !strings.Contains(err.Error(), "200 OK: 201") {
  582. c.Fatal(err)
  583. }
  584. type createResp struct {
  585. Id string
  586. }
  587. var container createResp
  588. if err := json.Unmarshal(b, &container); err != nil {
  589. c.Fatal(err)
  590. }
  591. var id = container.Id
  592. _, bodyGet, err := sockRequest("GET", "/containers/"+id+"/json", nil)
  593. type configLocal struct {
  594. Hostname string
  595. }
  596. type getResponse struct {
  597. Id string
  598. Config configLocal
  599. }
  600. var containerInfo getResponse
  601. if err := json.Unmarshal(bodyGet, &containerInfo); err != nil {
  602. c.Fatal(err)
  603. }
  604. var hostNameActual = containerInfo.Config.Hostname
  605. if hostNameActual != "test-host" {
  606. c.Fatalf("Mismatched Hostname, Expected %v, Actual: %v ", hostName, hostNameActual)
  607. }
  608. }
  609. func (s *DockerSuite) TestContainerApiVerifyHeader(c *check.C) {
  610. config := map[string]interface{}{
  611. "Image": "busybox",
  612. }
  613. create := func(ct string) (*http.Response, io.ReadCloser, error) {
  614. jsonData := bytes.NewBuffer(nil)
  615. if err := json.NewEncoder(jsonData).Encode(config); err != nil {
  616. c.Fatal(err)
  617. }
  618. return sockRequestRaw("POST", "/containers/create", jsonData, ct)
  619. }
  620. // Try with no content-type
  621. res, body, err := create("")
  622. c.Assert(err, check.IsNil)
  623. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  624. body.Close()
  625. // Try with wrong content-type
  626. res, body, err = create("application/xml")
  627. c.Assert(err, check.IsNil)
  628. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  629. body.Close()
  630. // now application/json
  631. res, body, err = create("application/json")
  632. c.Assert(err, check.IsNil)
  633. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  634. body.Close()
  635. }
  636. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  637. // W/o this fix a null in JSON would be parsed into a string var as "null"
  638. func (s *DockerSuite) TestContainerApiPostCreateNull(c *check.C) {
  639. config := `{
  640. "Hostname":"",
  641. "Domainname":"",
  642. "Memory":0,
  643. "MemorySwap":0,
  644. "CpuShares":0,
  645. "Cpuset":null,
  646. "AttachStdin":true,
  647. "AttachStdout":true,
  648. "AttachStderr":true,
  649. "PortSpecs":null,
  650. "ExposedPorts":{},
  651. "Tty":true,
  652. "OpenStdin":true,
  653. "StdinOnce":true,
  654. "Env":[],
  655. "Cmd":"ls",
  656. "Image":"busybox",
  657. "Volumes":{},
  658. "WorkingDir":"",
  659. "Entrypoint":null,
  660. "NetworkDisabled":false,
  661. "OnBuild":null}`
  662. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  663. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  664. c.Assert(err, check.IsNil)
  665. b, err := readBody(body)
  666. if err != nil {
  667. c.Fatal(err)
  668. }
  669. type createResp struct {
  670. Id string
  671. }
  672. var container createResp
  673. if err := json.Unmarshal(b, &container); err != nil {
  674. c.Fatal(err)
  675. }
  676. out, err := inspectField(container.Id, "HostConfig.CpusetCpus")
  677. if err != nil {
  678. c.Fatal(err, out)
  679. }
  680. if out != "" {
  681. c.Fatalf("expected empty string, got %q", out)
  682. }
  683. }
  684. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  685. config := `{
  686. "Image": "busybox",
  687. "Cmd": "ls",
  688. "OpenStdin": true,
  689. "CpuShares": 100,
  690. "Memory": 524287
  691. }`
  692. res, body, _ := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  693. b, err2 := readBody(body)
  694. if err2 != nil {
  695. c.Fatal(err2)
  696. }
  697. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  698. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  699. }
  700. func (s *DockerSuite) TestStartWithTooLowMemoryLimit(c *check.C) {
  701. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "busybox"))
  702. if err != nil {
  703. c.Fatal(err, out)
  704. }
  705. containerID := strings.TrimSpace(out)
  706. config := `{
  707. "CpuShares": 100,
  708. "Memory": 524287
  709. }`
  710. res, body, _ := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  711. b, err2 := readBody(body)
  712. if err2 != nil {
  713. c.Fatal(err2)
  714. }
  715. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  716. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  717. }
  718. func (s *DockerSuite) TestContainerApiRename(c *check.C) {
  719. runCmd := exec.Command(dockerBinary, "run", "--name", "TestContainerApiRename", "-d", "busybox", "sh")
  720. out, _, err := runCommandWithOutput(runCmd)
  721. c.Assert(err, check.IsNil)
  722. containerID := strings.TrimSpace(out)
  723. newName := "TestContainerApiRenameNew"
  724. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
  725. // 204 No Content is expected, not 200
  726. c.Assert(statusCode, check.Equals, http.StatusNoContent)
  727. c.Assert(err, check.IsNil)
  728. name, err := inspectField(containerID, "Name")
  729. if name != "/"+newName {
  730. c.Fatalf("Failed to rename container, expected %v, got %v. Container rename API failed", newName, name)
  731. }
  732. }
  733. func (s *DockerSuite) TestContainerApiKill(c *check.C) {
  734. name := "test-api-kill"
  735. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  736. out, _, err := runCommandWithOutput(runCmd)
  737. if err != nil {
  738. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  739. }
  740. status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil)
  741. c.Assert(status, check.Equals, http.StatusNoContent)
  742. c.Assert(err, check.IsNil)
  743. state, err := inspectField(name, "State.Running")
  744. if err != nil {
  745. c.Fatal(err)
  746. }
  747. if state != "false" {
  748. c.Fatalf("got wrong State from container %s: %q", name, state)
  749. }
  750. }
  751. func (s *DockerSuite) TestContainerApiRestart(c *check.C) {
  752. name := "test-api-restart"
  753. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  754. out, _, err := runCommandWithOutput(runCmd)
  755. if err != nil {
  756. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  757. }
  758. status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil)
  759. c.Assert(status, check.Equals, http.StatusNoContent)
  760. c.Assert(err, check.IsNil)
  761. if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil {
  762. c.Fatal(err)
  763. }
  764. }
  765. func (s *DockerSuite) TestContainerApiStart(c *check.C) {
  766. name := "testing-start"
  767. config := map[string]interface{}{
  768. "Image": "busybox",
  769. "Cmd": []string{"/bin/sh", "-c", "/bin/top"},
  770. "OpenStdin": true,
  771. }
  772. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  773. c.Assert(status, check.Equals, http.StatusCreated)
  774. c.Assert(err, check.IsNil)
  775. conf := make(map[string]interface{})
  776. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  777. c.Assert(status, check.Equals, http.StatusNoContent)
  778. c.Assert(err, check.IsNil)
  779. // second call to start should give 304
  780. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  781. c.Assert(status, check.Equals, http.StatusNotModified)
  782. c.Assert(err, check.IsNil)
  783. }
  784. func (s *DockerSuite) TestContainerApiStop(c *check.C) {
  785. name := "test-api-stop"
  786. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  787. out, _, err := runCommandWithOutput(runCmd)
  788. if err != nil {
  789. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  790. }
  791. status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  792. c.Assert(status, check.Equals, http.StatusNoContent)
  793. c.Assert(err, check.IsNil)
  794. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  795. c.Fatal(err)
  796. }
  797. // second call to start should give 304
  798. status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  799. c.Assert(status, check.Equals, http.StatusNotModified)
  800. c.Assert(err, check.IsNil)
  801. }
  802. func (s *DockerSuite) TestContainerApiWait(c *check.C) {
  803. name := "test-api-wait"
  804. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sleep", "5")
  805. out, _, err := runCommandWithOutput(runCmd)
  806. if err != nil {
  807. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  808. }
  809. status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil)
  810. c.Assert(status, check.Equals, http.StatusOK)
  811. c.Assert(err, check.IsNil)
  812. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  813. c.Fatal(err)
  814. }
  815. var waitres types.ContainerWaitResponse
  816. if err := json.Unmarshal(body, &waitres); err != nil {
  817. c.Fatalf("unable to unmarshal response body: %v", err)
  818. }
  819. if waitres.StatusCode != 0 {
  820. c.Fatalf("Expected wait response StatusCode to be 0, got %d", waitres.StatusCode)
  821. }
  822. }
  823. func (s *DockerSuite) TestContainerApiCopy(c *check.C) {
  824. name := "test-container-api-copy"
  825. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test.txt")
  826. _, err := runCommand(runCmd)
  827. c.Assert(err, check.IsNil)
  828. postData := types.CopyConfig{
  829. Resource: "/test.txt",
  830. }
  831. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  832. c.Assert(err, check.IsNil)
  833. c.Assert(status, check.Equals, http.StatusOK)
  834. found := false
  835. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  836. h, err := tarReader.Next()
  837. if err != nil {
  838. if err == io.EOF {
  839. break
  840. }
  841. c.Fatal(err)
  842. }
  843. if h.Name == "test.txt" {
  844. found = true
  845. break
  846. }
  847. }
  848. c.Assert(found, check.Equals, true)
  849. }
  850. func (s *DockerSuite) TestContainerApiCopyResourcePathEmpty(c *check.C) {
  851. name := "test-container-api-copy-resource-empty"
  852. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test.txt")
  853. _, err := runCommand(runCmd)
  854. c.Assert(err, check.IsNil)
  855. postData := types.CopyConfig{
  856. Resource: "",
  857. }
  858. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  859. c.Assert(err, check.IsNil)
  860. c.Assert(status, check.Equals, http.StatusInternalServerError)
  861. c.Assert(string(body), check.Matches, "Path cannot be empty\n")
  862. }
  863. func (s *DockerSuite) TestContainerApiCopyResourcePathNotFound(c *check.C) {
  864. name := "test-container-api-copy-resource-not-found"
  865. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox")
  866. _, err := runCommand(runCmd)
  867. c.Assert(err, check.IsNil)
  868. postData := types.CopyConfig{
  869. Resource: "/notexist",
  870. }
  871. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  872. c.Assert(err, check.IsNil)
  873. c.Assert(status, check.Equals, http.StatusInternalServerError)
  874. c.Assert(string(body), check.Matches, "Could not find the file /notexist in container "+name+"\n")
  875. }
  876. func (s *DockerSuite) TestContainerApiCopyContainerNotFound(c *check.C) {
  877. postData := types.CopyConfig{
  878. Resource: "/something",
  879. }
  880. status, _, err := sockRequest("POST", "/containers/notexists/copy", postData)
  881. c.Assert(err, check.IsNil)
  882. c.Assert(status, check.Equals, http.StatusNotFound)
  883. }
  884. func (s *DockerSuite) TestContainerApiDelete(c *check.C) {
  885. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  886. out, _, err := runCommandWithOutput(runCmd)
  887. c.Assert(err, check.IsNil)
  888. id := strings.TrimSpace(out)
  889. c.Assert(waitRun(id), check.IsNil)
  890. stopCmd := exec.Command(dockerBinary, "stop", id)
  891. _, err = runCommand(stopCmd)
  892. c.Assert(err, check.IsNil)
  893. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  894. c.Assert(err, check.IsNil)
  895. c.Assert(status, check.Equals, http.StatusNoContent)
  896. }
  897. func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) {
  898. status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
  899. c.Assert(err, check.IsNil)
  900. c.Assert(status, check.Equals, http.StatusNotFound)
  901. c.Assert(string(body), check.Matches, "no such id: doesnotexist\n")
  902. }
  903. func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) {
  904. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  905. out, _, err := runCommandWithOutput(runCmd)
  906. c.Assert(err, check.IsNil)
  907. id := strings.TrimSpace(out)
  908. c.Assert(waitRun(id), check.IsNil)
  909. status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
  910. c.Assert(err, check.IsNil)
  911. c.Assert(status, check.Equals, http.StatusNoContent)
  912. }
  913. func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) {
  914. runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "tlink1", "busybox", "top")
  915. out, _, err := runCommandWithOutput(runCmd)
  916. c.Assert(err, check.IsNil)
  917. id := strings.TrimSpace(out)
  918. c.Assert(waitRun(id), check.IsNil)
  919. runCmd = exec.Command(dockerBinary, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  920. out, _, err = runCommandWithOutput(runCmd)
  921. c.Assert(err, check.IsNil)
  922. id2 := strings.TrimSpace(out)
  923. c.Assert(waitRun(id2), check.IsNil)
  924. links, err := inspectFieldJSON(id2, "HostConfig.Links")
  925. c.Assert(err, check.IsNil)
  926. if links != "[\"/tlink1:/tlink2/tlink1\"]" {
  927. c.Fatal("expected to have links between containers")
  928. }
  929. status, _, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
  930. c.Assert(err, check.IsNil)
  931. c.Assert(status, check.Equals, http.StatusNoContent)
  932. linksPostRm, err := inspectFieldJSON(id2, "HostConfig.Links")
  933. c.Assert(err, check.IsNil)
  934. if linksPostRm != "null" {
  935. c.Fatal("call to api deleteContainer links should have removed the specified links")
  936. }
  937. }
  938. func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) {
  939. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  940. out, _, err := runCommandWithOutput(runCmd)
  941. c.Assert(err, check.IsNil)
  942. id := strings.TrimSpace(out)
  943. c.Assert(waitRun(id), check.IsNil)
  944. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  945. c.Assert(status, check.Equals, http.StatusConflict)
  946. c.Assert(err, check.IsNil)
  947. }
  948. func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) {
  949. testRequires(c, SameHostDaemon)
  950. runCmd := exec.Command(dockerBinary, "run", "-d", "-v", "/testvolume", "busybox", "top")
  951. out, _, err := runCommandWithOutput(runCmd)
  952. c.Assert(err, check.IsNil)
  953. id := strings.TrimSpace(out)
  954. c.Assert(waitRun(id), check.IsNil)
  955. vol, err := inspectFieldMap(id, "Volumes", "/testvolume")
  956. c.Assert(err, check.IsNil)
  957. _, err = os.Stat(vol)
  958. c.Assert(err, check.IsNil)
  959. status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
  960. c.Assert(status, check.Equals, http.StatusNoContent)
  961. c.Assert(err, check.IsNil)
  962. if _, err := os.Stat(vol); !os.IsNotExist(err) {
  963. c.Fatalf("expected to get ErrNotExist error, got %v", err)
  964. }
  965. }