docker_api_containers_test.go 30 KB

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