docker_api_containers_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "github.com/docker/docker/api/types"
  6. "github.com/docker/docker/pkg/stringid"
  7. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  8. "io"
  9. "os/exec"
  10. "strings"
  11. "testing"
  12. "time"
  13. )
  14. func TestContainerApiGetAll(t *testing.T) {
  15. defer deleteAllContainers()
  16. startCount, err := getContainerCount()
  17. if err != nil {
  18. t.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. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  25. }
  26. body, err := sockRequest("GET", "/containers/json?all=1", nil)
  27. if err != nil {
  28. t.Fatalf("GET all containers sockRequest failed: %v", err)
  29. }
  30. var inspectJSON []struct {
  31. Names []string
  32. }
  33. if err = json.Unmarshal(body, &inspectJSON); err != nil {
  34. t.Fatalf("unable to unmarshal response body: %v", err)
  35. }
  36. if len(inspectJSON) != startCount+1 {
  37. t.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. t.Fatalf("Container Name mismatch. Expected: %q, received: %q\n", "/"+name, actual)
  41. }
  42. logDone("container REST API - check GET json/all=1")
  43. }
  44. func TestContainerApiGetExport(t *testing.T) {
  45. defer deleteAllContainers()
  46. name := "exportcontainer"
  47. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test")
  48. out, _, err := runCommandWithOutput(runCmd)
  49. if err != nil {
  50. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  51. }
  52. body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
  53. if err != nil {
  54. t.Fatalf("GET containers/export sockRequest failed: %v", err)
  55. }
  56. found := false
  57. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  58. h, err := tarReader.Next()
  59. if err != nil {
  60. if err == io.EOF {
  61. break
  62. }
  63. t.Fatal(err)
  64. }
  65. if h.Name == "test" {
  66. found = true
  67. break
  68. }
  69. }
  70. if !found {
  71. t.Fatalf("The created test file has not been found in the exported image")
  72. }
  73. logDone("container REST API - check GET containers/export")
  74. }
  75. func TestContainerApiGetChanges(t *testing.T) {
  76. defer deleteAllContainers()
  77. name := "changescontainer"
  78. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "rm", "/etc/passwd")
  79. out, _, err := runCommandWithOutput(runCmd)
  80. if err != nil {
  81. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  82. }
  83. body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
  84. if err != nil {
  85. t.Fatalf("GET containers/changes sockRequest failed: %v", err)
  86. }
  87. changes := []struct {
  88. Kind int
  89. Path string
  90. }{}
  91. if err = json.Unmarshal(body, &changes); err != nil {
  92. t.Fatalf("unable to unmarshal response body: %v", err)
  93. }
  94. // Check the changelog for removal of /etc/passwd
  95. success := false
  96. for _, elem := range changes {
  97. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  98. success = true
  99. }
  100. }
  101. if !success {
  102. t.Fatalf("/etc/passwd has been removed but is not present in the diff")
  103. }
  104. logDone("container REST API - check GET containers/changes")
  105. }
  106. func TestContainerApiStartVolumeBinds(t *testing.T) {
  107. defer deleteAllContainers()
  108. name := "testing"
  109. config := map[string]interface{}{
  110. "Image": "busybox",
  111. "Volumes": map[string]struct{}{"/tmp": {}},
  112. }
  113. if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
  114. t.Fatal(err)
  115. }
  116. bindPath := randomUnixTmpDirPath("test")
  117. config = map[string]interface{}{
  118. "Binds": []string{bindPath + ":/tmp"},
  119. }
  120. if _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
  121. t.Fatal(err)
  122. }
  123. pth, err := inspectFieldMap(name, "Volumes", "/tmp")
  124. if err != nil {
  125. t.Fatal(err)
  126. }
  127. if pth != bindPath {
  128. t.Fatalf("expected volume host path to be %s, got %s", bindPath, pth)
  129. }
  130. logDone("container REST API - check volume binds on start")
  131. }
  132. // Test for GH#10618
  133. func TestContainerApiStartDupVolumeBinds(t *testing.T) {
  134. defer deleteAllContainers()
  135. name := "testdups"
  136. config := map[string]interface{}{
  137. "Image": "busybox",
  138. "Volumes": map[string]struct{}{"/tmp": {}},
  139. }
  140. if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
  141. t.Fatal(err)
  142. }
  143. bindPath1 := randomUnixTmpDirPath("test1")
  144. bindPath2 := randomUnixTmpDirPath("test2")
  145. config = map[string]interface{}{
  146. "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"},
  147. }
  148. if body, err := sockRequest("POST", "/containers/"+name+"/start", config); err == nil {
  149. t.Fatal("expected container start to fail when duplicate volume binds to same container path")
  150. } else {
  151. if !strings.Contains(string(body), "Duplicate volume") {
  152. t.Fatalf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(body), err)
  153. }
  154. }
  155. logDone("container REST API - check for duplicate volume binds error on start")
  156. }
  157. func TestContainerApiStartVolumesFrom(t *testing.T) {
  158. defer deleteAllContainers()
  159. volName := "voltst"
  160. volPath := "/tmp"
  161. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  162. t.Fatal(out, err)
  163. }
  164. name := "testing"
  165. config := map[string]interface{}{
  166. "Image": "busybox",
  167. "Volumes": map[string]struct{}{volPath: {}},
  168. }
  169. if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
  170. t.Fatal(err)
  171. }
  172. config = map[string]interface{}{
  173. "VolumesFrom": []string{volName},
  174. }
  175. if _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
  176. t.Fatal(err)
  177. }
  178. pth, err := inspectFieldMap(name, "Volumes", volPath)
  179. if err != nil {
  180. t.Fatal(err)
  181. }
  182. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  183. if err != nil {
  184. t.Fatal(err)
  185. }
  186. if pth != pth2 {
  187. t.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  188. }
  189. logDone("container REST API - check VolumesFrom on start")
  190. }
  191. // Ensure that volumes-from has priority over binds/anything else
  192. // This is pretty much the same as TestRunApplyVolumesFromBeforeVolumes, except with passing the VolumesFrom and the bind on start
  193. func TestVolumesFromHasPriority(t *testing.T) {
  194. defer deleteAllContainers()
  195. volName := "voltst2"
  196. volPath := "/tmp"
  197. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  198. t.Fatal(out, err)
  199. }
  200. name := "testing"
  201. config := map[string]interface{}{
  202. "Image": "busybox",
  203. "Volumes": map[string]struct{}{volPath: {}},
  204. }
  205. if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
  206. t.Fatal(err)
  207. }
  208. bindPath := randomUnixTmpDirPath("test")
  209. config = map[string]interface{}{
  210. "VolumesFrom": []string{volName},
  211. "Binds": []string{bindPath + ":/tmp"},
  212. }
  213. if _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
  214. t.Fatal(err)
  215. }
  216. pth, err := inspectFieldMap(name, "Volumes", volPath)
  217. if err != nil {
  218. t.Fatal(err)
  219. }
  220. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  221. if err != nil {
  222. t.Fatal(err)
  223. }
  224. if pth != pth2 {
  225. t.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  226. }
  227. logDone("container REST API - check VolumesFrom has priority")
  228. }
  229. func TestGetContainerStats(t *testing.T) {
  230. defer deleteAllContainers()
  231. var (
  232. name = "statscontainer"
  233. runCmd = exec.Command(dockerBinary, "run", "-d", "--name", name, "busybox", "top")
  234. )
  235. out, _, err := runCommandWithOutput(runCmd)
  236. if err != nil {
  237. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  238. }
  239. type b struct {
  240. body []byte
  241. err error
  242. }
  243. bc := make(chan b, 1)
  244. go func() {
  245. body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  246. bc <- b{body, err}
  247. }()
  248. // allow some time to stream the stats from the container
  249. time.Sleep(4 * time.Second)
  250. if _, err := runCommand(exec.Command(dockerBinary, "rm", "-f", name)); err != nil {
  251. t.Fatal(err)
  252. }
  253. // collect the results from the stats stream or timeout and fail
  254. // if the stream was not disconnected.
  255. select {
  256. case <-time.After(2 * time.Second):
  257. t.Fatal("stream was not closed after container was removed")
  258. case sr := <-bc:
  259. if sr.err != nil {
  260. t.Fatal(sr.err)
  261. }
  262. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  263. var s *types.Stats
  264. // decode only one object from the stream
  265. if err := dec.Decode(&s); err != nil {
  266. t.Fatal(err)
  267. }
  268. }
  269. logDone("container REST API - check GET containers/stats")
  270. }
  271. func TestGetStoppedContainerStats(t *testing.T) {
  272. defer deleteAllContainers()
  273. var (
  274. name = "statscontainer"
  275. runCmd = exec.Command(dockerBinary, "create", "--name", name, "busybox", "top")
  276. )
  277. out, _, err := runCommandWithOutput(runCmd)
  278. if err != nil {
  279. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  280. }
  281. go func() {
  282. // We'll never get return for GET stats from sockRequest as of now,
  283. // just send request and see if panic or error would happen on daemon side.
  284. _, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  285. if err != nil {
  286. t.Fatal(err)
  287. }
  288. }()
  289. // allow some time to send request and let daemon deal with it
  290. time.Sleep(1 * time.Second)
  291. logDone("container REST API - check GET stopped containers/stats")
  292. }
  293. func TestBuildApiDockerfilePath(t *testing.T) {
  294. // Test to make sure we stop people from trying to leave the
  295. // build context when specifying the path to the dockerfile
  296. buffer := new(bytes.Buffer)
  297. tw := tar.NewWriter(buffer)
  298. defer tw.Close()
  299. dockerfile := []byte("FROM busybox")
  300. if err := tw.WriteHeader(&tar.Header{
  301. Name: "Dockerfile",
  302. Size: int64(len(dockerfile)),
  303. }); err != nil {
  304. t.Fatalf("failed to write tar file header: %v", err)
  305. }
  306. if _, err := tw.Write(dockerfile); err != nil {
  307. t.Fatalf("failed to write tar file content: %v", err)
  308. }
  309. if err := tw.Close(); err != nil {
  310. t.Fatalf("failed to close tar archive: %v", err)
  311. }
  312. out, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
  313. if err == nil {
  314. t.Fatalf("Build was supposed to fail: %s", out)
  315. }
  316. if !strings.Contains(string(out), "must be within the build context") {
  317. t.Fatalf("Didn't complain about leaving build context: %s", out)
  318. }
  319. logDone("container REST API - check build w/bad Dockerfile path")
  320. }
  321. func TestBuildApiDockerFileRemote(t *testing.T) {
  322. server, err := fakeStorage(map[string]string{
  323. "testD": `FROM busybox
  324. COPY * /tmp/
  325. RUN find / -name ba*
  326. RUN find /tmp/`,
  327. })
  328. if err != nil {
  329. t.Fatal(err)
  330. }
  331. defer server.Close()
  332. buf, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json")
  333. if err != nil {
  334. t.Fatalf("Build failed: %s", err)
  335. }
  336. // Make sure Dockerfile exists.
  337. // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL
  338. out := string(buf)
  339. if !strings.Contains(out, "/tmp/Dockerfile") ||
  340. strings.Contains(out, "baz") {
  341. t.Fatalf("Incorrect output: %s", out)
  342. }
  343. logDone("container REST API - check build with -f from remote")
  344. }
  345. func TestBuildApiLowerDockerfile(t *testing.T) {
  346. git, err := fakeGIT("repo", map[string]string{
  347. "dockerfile": `FROM busybox
  348. RUN echo from dockerfile`,
  349. }, false)
  350. if err != nil {
  351. t.Fatal(err)
  352. }
  353. defer git.Close()
  354. buf, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  355. if err != nil {
  356. t.Fatalf("Build failed: %s\n%q", err, buf)
  357. }
  358. out := string(buf)
  359. if !strings.Contains(out, "from dockerfile") {
  360. t.Fatalf("Incorrect output: %s", out)
  361. }
  362. logDone("container REST API - check build with lower dockerfile")
  363. }
  364. func TestBuildApiBuildGitWithF(t *testing.T) {
  365. git, err := fakeGIT("repo", map[string]string{
  366. "baz": `FROM busybox
  367. RUN echo from baz`,
  368. "Dockerfile": `FROM busybox
  369. RUN echo from Dockerfile`,
  370. }, false)
  371. if err != nil {
  372. t.Fatal(err)
  373. }
  374. defer git.Close()
  375. // Make sure it tries to 'dockerfile' query param value
  376. buf, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
  377. if err != nil {
  378. t.Fatalf("Build failed: %s\n%q", err, buf)
  379. }
  380. out := string(buf)
  381. if !strings.Contains(out, "from baz") {
  382. t.Fatalf("Incorrect output: %s", out)
  383. }
  384. logDone("container REST API - check build from git w/F")
  385. }
  386. func TestBuildApiDoubleDockerfile(t *testing.T) {
  387. testRequires(t, UnixCli) // dockerfile overwrites Dockerfile on Windows
  388. git, err := fakeGIT("repo", map[string]string{
  389. "Dockerfile": `FROM busybox
  390. RUN echo from Dockerfile`,
  391. "dockerfile": `FROM busybox
  392. RUN echo from dockerfile`,
  393. }, false)
  394. if err != nil {
  395. t.Fatal(err)
  396. }
  397. defer git.Close()
  398. // Make sure it tries to 'dockerfile' query param value
  399. buf, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  400. if err != nil {
  401. t.Fatalf("Build failed: %s", err)
  402. }
  403. out := string(buf)
  404. if !strings.Contains(out, "from Dockerfile") {
  405. t.Fatalf("Incorrect output: %s", out)
  406. }
  407. logDone("container REST API - check build with two dockerfiles")
  408. }
  409. func TestBuildApiDockerfileSymlink(t *testing.T) {
  410. // Test to make sure we stop people from trying to leave the
  411. // build context when specifying a symlink as the path to the dockerfile
  412. buffer := new(bytes.Buffer)
  413. tw := tar.NewWriter(buffer)
  414. defer tw.Close()
  415. if err := tw.WriteHeader(&tar.Header{
  416. Name: "Dockerfile",
  417. Typeflag: tar.TypeSymlink,
  418. Linkname: "/etc/passwd",
  419. }); err != nil {
  420. t.Fatalf("failed to write tar file header: %v", err)
  421. }
  422. if err := tw.Close(); err != nil {
  423. t.Fatalf("failed to close tar archive: %v", err)
  424. }
  425. out, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  426. if err == nil {
  427. t.Fatalf("Build was supposed to fail: %s", out)
  428. }
  429. // The reason the error is "Cannot locate specified Dockerfile" is because
  430. // in the builder, the symlink is resolved within the context, therefore
  431. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  432. // a nonexistent file.
  433. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  434. t.Fatalf("Didn't complain about leaving build context: %s", out)
  435. }
  436. logDone("container REST API - check build w/bad Dockerfile symlink path")
  437. }
  438. // #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
  439. func TestPostContainerBindNormalVolume(t *testing.T) {
  440. defer deleteAllContainers()
  441. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=one", "busybox"))
  442. if err != nil {
  443. t.Fatal(err, out)
  444. }
  445. fooDir, err := inspectFieldMap("one", "Volumes", "/foo")
  446. if err != nil {
  447. t.Fatal(err)
  448. }
  449. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=two", "busybox"))
  450. if err != nil {
  451. t.Fatal(err, out)
  452. }
  453. bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
  454. _, err = sockRequest("POST", "/containers/two/start", bindSpec)
  455. if err != nil && !strings.Contains(err.Error(), "204 No Content") {
  456. t.Fatal(err)
  457. }
  458. fooDir2, err := inspectFieldMap("two", "Volumes", "/foo")
  459. if err != nil {
  460. t.Fatal(err)
  461. }
  462. if fooDir2 != fooDir {
  463. t.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2)
  464. }
  465. logDone("container REST API - can use path from normal volume as bind-mount to overwrite another volume")
  466. }
  467. func TestContainerApiPause(t *testing.T) {
  468. defer deleteAllContainers()
  469. defer unpauseAllContainers()
  470. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sleep", "30")
  471. out, _, err := runCommandWithOutput(runCmd)
  472. if err != nil {
  473. t.Fatalf("failed to create a container: %s, %v", out, err)
  474. }
  475. ContainerID := strings.TrimSpace(out)
  476. if _, err = sockRequest("POST", "/containers/"+ContainerID+"/pause", nil); err != nil && !strings.Contains(err.Error(), "204 No Content") {
  477. t.Fatalf("POST a container pause: sockRequest failed: %v", err)
  478. }
  479. pausedContainers, err := getSliceOfPausedContainers()
  480. if err != nil {
  481. t.Fatalf("error thrown while checking if containers were paused: %v", err)
  482. }
  483. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  484. t.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  485. }
  486. if _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil); err != nil && !strings.Contains(err.Error(), "204 No Content") {
  487. t.Fatalf("POST a container pause: sockRequest failed: %v", err)
  488. }
  489. pausedContainers, err = getSliceOfPausedContainers()
  490. if err != nil {
  491. t.Fatalf("error thrown while checking if containers were paused: %v", err)
  492. }
  493. if pausedContainers != nil {
  494. t.Fatalf("There should be no paused container.")
  495. }
  496. logDone("container REST API - check POST containers/pause and unpause")
  497. }