docker_api_containers_test.go 13 KB

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