docker_api_containers_test.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/docker/docker/api/stats"
  13. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  14. )
  15. func TestContainerApiGetAll(t *testing.T) {
  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. deleteAllContainers()
  43. logDone("container REST API - check GET json/all=1")
  44. }
  45. func TestContainerApiGetExport(t *testing.T) {
  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. deleteAllContainers()
  74. logDone("container REST API - check GET containers/export")
  75. }
  76. func TestContainerApiGetChanges(t *testing.T) {
  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. deleteAllContainers()
  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 _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
  115. t.Fatal(err)
  116. }
  117. bindPath, err := ioutil.TempDir(os.TempDir(), "test")
  118. if err != nil {
  119. t.Fatal(err)
  120. }
  121. config = map[string]interface{}{
  122. "Binds": []string{bindPath + ":/tmp"},
  123. }
  124. if _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
  125. t.Fatal(err)
  126. }
  127. pth, err := inspectFieldMap(name, "Volumes", "/tmp")
  128. if err != nil {
  129. t.Fatal(err)
  130. }
  131. if pth != bindPath {
  132. t.Fatalf("expected volume host path to be %s, got %s", bindPath, pth)
  133. }
  134. logDone("container REST API - check volume binds on start")
  135. }
  136. func TestContainerApiStartVolumesFrom(t *testing.T) {
  137. defer deleteAllContainers()
  138. volName := "voltst"
  139. volPath := "/tmp"
  140. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  141. t.Fatal(out, err)
  142. }
  143. name := "testing"
  144. config := map[string]interface{}{
  145. "Image": "busybox",
  146. "Volumes": map[string]struct{}{volPath: {}},
  147. }
  148. if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
  149. t.Fatal(err)
  150. }
  151. config = map[string]interface{}{
  152. "VolumesFrom": []string{volName},
  153. }
  154. if _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
  155. t.Fatal(err)
  156. }
  157. pth, err := inspectFieldMap(name, "Volumes", volPath)
  158. if err != nil {
  159. t.Fatal(err)
  160. }
  161. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  162. if err != nil {
  163. t.Fatal(err)
  164. }
  165. if pth != pth2 {
  166. t.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  167. }
  168. logDone("container REST API - check VolumesFrom on start")
  169. }
  170. // Ensure that volumes-from has priority over binds/anything else
  171. // This is pretty much the same as TestRunApplyVolumesFromBeforeVolumes, except with passing the VolumesFrom and the bind on start
  172. func TestVolumesFromHasPriority(t *testing.T) {
  173. defer deleteAllContainers()
  174. volName := "voltst"
  175. volPath := "/tmp"
  176. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  177. t.Fatal(out, err)
  178. }
  179. name := "testing"
  180. config := map[string]interface{}{
  181. "Image": "busybox",
  182. "Volumes": map[string]struct{}{volPath: {}},
  183. }
  184. if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
  185. t.Fatal(err)
  186. }
  187. bindPath, err := ioutil.TempDir(os.TempDir(), "test")
  188. if err != nil {
  189. t.Fatal(err)
  190. }
  191. config = map[string]interface{}{
  192. "VolumesFrom": []string{volName},
  193. "Binds": []string{bindPath + ":/tmp"},
  194. }
  195. if _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
  196. t.Fatal(err)
  197. }
  198. pth, err := inspectFieldMap(name, "Volumes", volPath)
  199. if err != nil {
  200. t.Fatal(err)
  201. }
  202. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  203. if err != nil {
  204. t.Fatal(err)
  205. }
  206. if pth != pth2 {
  207. t.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  208. }
  209. logDone("container REST API - check VolumesFrom has priority")
  210. }
  211. func TestGetContainerStats(t *testing.T) {
  212. defer deleteAllContainers()
  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. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  220. }
  221. type b struct {
  222. body []byte
  223. err error
  224. }
  225. bc := make(chan b, 1)
  226. go func() {
  227. body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  228. bc <- b{body, err}
  229. }()
  230. // allow some time to stream the stats from the container
  231. time.Sleep(4 * time.Second)
  232. if _, err := runCommand(exec.Command(dockerBinary, "rm", "-f", name)); err != nil {
  233. t.Fatal(err)
  234. }
  235. // collect the results from the stats stream or timeout and fail
  236. // if the stream was not disconnected.
  237. select {
  238. case <-time.After(2 * time.Second):
  239. t.Fatal("stream was not closed after container was removed")
  240. case sr := <-bc:
  241. if sr.err != nil {
  242. t.Fatal(err)
  243. }
  244. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  245. var s *stats.Stats
  246. // decode only one object from the stream
  247. if err := dec.Decode(&s); err != nil {
  248. t.Fatal(err)
  249. }
  250. }
  251. logDone("container REST API - check GET containers/stats")
  252. }
  253. func TestBuildApiDockerfilePath(t *testing.T) {
  254. // Test to make sure we stop people from trying to leave the
  255. // build context when specifying the path to the dockerfile
  256. buffer := new(bytes.Buffer)
  257. tw := tar.NewWriter(buffer)
  258. defer tw.Close()
  259. dockerfile := []byte("FROM busybox")
  260. if err := tw.WriteHeader(&tar.Header{
  261. Name: "Dockerfile",
  262. Size: int64(len(dockerfile)),
  263. }); err != nil {
  264. t.Fatalf("failed to write tar file header: %v", err)
  265. }
  266. if _, err := tw.Write(dockerfile); err != nil {
  267. t.Fatalf("failed to write tar file content: %v", err)
  268. }
  269. if err := tw.Close(); err != nil {
  270. t.Fatalf("failed to close tar archive: %v", err)
  271. }
  272. out, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
  273. if err == nil {
  274. t.Fatalf("Build was supposed to fail: %s", out)
  275. }
  276. if !strings.Contains(string(out), "must be within the build context") {
  277. t.Fatalf("Didn't complain about leaving build context: %s", out)
  278. }
  279. logDone("container REST API - check build w/bad Dockerfile path")
  280. }
  281. func TestBuildApiDockerfileSymlink(t *testing.T) {
  282. // Test to make sure we stop people from trying to leave the
  283. // build context when specifying a symlink as the path to the dockerfile
  284. buffer := new(bytes.Buffer)
  285. tw := tar.NewWriter(buffer)
  286. defer tw.Close()
  287. if err := tw.WriteHeader(&tar.Header{
  288. Name: "Dockerfile",
  289. Typeflag: tar.TypeSymlink,
  290. Linkname: "/etc/passwd",
  291. }); err != nil {
  292. t.Fatalf("failed to write tar file header: %v", err)
  293. }
  294. if err := tw.Close(); err != nil {
  295. t.Fatalf("failed to close tar archive: %v", err)
  296. }
  297. out, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  298. if err == nil {
  299. t.Fatalf("Build was supposed to fail: %s", out)
  300. }
  301. // The reason the error is "Cannot locate specified Dockerfile" is because
  302. // in the builder, the symlink is resolved within the context, therefore
  303. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  304. // a nonexistent file.
  305. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  306. t.Fatalf("Didn't complain about leaving build context: %s", out)
  307. }
  308. logDone("container REST API - check build w/bad Dockerfile symlink path")
  309. }