docker_api_containers_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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/stats"
  11. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  12. )
  13. func TestContainerApiGetAll(t *testing.T) {
  14. startCount, err := getContainerCount()
  15. if err != nil {
  16. t.Fatalf("Cannot query container count: %v", err)
  17. }
  18. name := "getall"
  19. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "true")
  20. out, _, err := runCommandWithOutput(runCmd)
  21. if err != nil {
  22. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  23. }
  24. body, err := sockRequest("GET", "/containers/json?all=1", nil)
  25. if err != nil {
  26. t.Fatalf("GET all containers sockRequest failed: %v", err)
  27. }
  28. var inspectJSON []struct {
  29. Names []string
  30. }
  31. if err = json.Unmarshal(body, &inspectJSON); err != nil {
  32. t.Fatalf("unable to unmarshal response body: %v", err)
  33. }
  34. if len(inspectJSON) != startCount+1 {
  35. t.Fatalf("Expected %d container(s), %d found (started with: %d)", startCount+1, len(inspectJSON), startCount)
  36. }
  37. if actual := inspectJSON[0].Names[0]; actual != "/"+name {
  38. t.Fatalf("Container Name mismatch. Expected: %q, received: %q\n", "/"+name, actual)
  39. }
  40. deleteAllContainers()
  41. logDone("container REST API - check GET json/all=1")
  42. }
  43. func TestContainerApiGetExport(t *testing.T) {
  44. name := "exportcontainer"
  45. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test")
  46. out, _, err := runCommandWithOutput(runCmd)
  47. if err != nil {
  48. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  49. }
  50. body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
  51. if err != nil {
  52. t.Fatalf("GET containers/export sockRequest failed: %v", err)
  53. }
  54. found := false
  55. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  56. h, err := tarReader.Next()
  57. if err != nil {
  58. if err == io.EOF {
  59. break
  60. }
  61. t.Fatal(err)
  62. }
  63. if h.Name == "test" {
  64. found = true
  65. break
  66. }
  67. }
  68. if !found {
  69. t.Fatalf("The created test file has not been found in the exported image")
  70. }
  71. deleteAllContainers()
  72. logDone("container REST API - check GET containers/export")
  73. }
  74. func TestContainerApiGetChanges(t *testing.T) {
  75. name := "changescontainer"
  76. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "rm", "/etc/passwd")
  77. out, _, err := runCommandWithOutput(runCmd)
  78. if err != nil {
  79. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  80. }
  81. body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
  82. if err != nil {
  83. t.Fatalf("GET containers/changes sockRequest failed: %v", err)
  84. }
  85. changes := []struct {
  86. Kind int
  87. Path string
  88. }{}
  89. if err = json.Unmarshal(body, &changes); err != nil {
  90. t.Fatalf("unable to unmarshal response body: %v", err)
  91. }
  92. // Check the changelog for removal of /etc/passwd
  93. success := false
  94. for _, elem := range changes {
  95. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  96. success = true
  97. }
  98. }
  99. if !success {
  100. t.Fatalf("/etc/passwd has been removed but is not present in the diff")
  101. }
  102. deleteAllContainers()
  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 *stats.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 TestBuildApiDockerfileSymlink(t *testing.T) {
  299. // Test to make sure we stop people from trying to leave the
  300. // build context when specifying a symlink as the path to the dockerfile
  301. buffer := new(bytes.Buffer)
  302. tw := tar.NewWriter(buffer)
  303. defer tw.Close()
  304. if err := tw.WriteHeader(&tar.Header{
  305. Name: "Dockerfile",
  306. Typeflag: tar.TypeSymlink,
  307. Linkname: "/etc/passwd",
  308. }); err != nil {
  309. t.Fatalf("failed to write tar file header: %v", err)
  310. }
  311. if err := tw.Close(); err != nil {
  312. t.Fatalf("failed to close tar archive: %v", err)
  313. }
  314. out, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  315. if err == nil {
  316. t.Fatalf("Build was supposed to fail: %s", out)
  317. }
  318. // The reason the error is "Cannot locate specified Dockerfile" is because
  319. // in the builder, the symlink is resolved within the context, therefore
  320. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  321. // a nonexistent file.
  322. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  323. t.Fatalf("Didn't complain about leaving build context: %s", out)
  324. }
  325. logDone("container REST API - check build w/bad Dockerfile symlink path")
  326. }