docker_api_containers_test.go 17 KB

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