docker_api_containers_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. // Test for GH#10618
  137. func TestContainerApiStartDupVolumeBinds(t *testing.T) {
  138. defer deleteAllContainers()
  139. name := "testdups"
  140. config := map[string]interface{}{
  141. "Image": "busybox",
  142. "Volumes": map[string]struct{}{"/tmp": {}},
  143. }
  144. if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
  145. t.Fatal(err)
  146. }
  147. bindPath1, err := ioutil.TempDir("", "test1")
  148. if err != nil {
  149. t.Fatal(err)
  150. }
  151. defer os.Remove(bindPath1)
  152. bindPath2, err := ioutil.TempDir("", "test2")
  153. if err != nil {
  154. t.Fatal(err)
  155. }
  156. defer os.Remove(bindPath2)
  157. config = map[string]interface{}{
  158. "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"},
  159. }
  160. if body, err := sockRequest("POST", "/containers/"+name+"/start", config); err == nil {
  161. t.Fatal("expected container start to fail when duplicate volume binds to same container path")
  162. } else {
  163. if !strings.Contains(string(body), "Duplicate volume") {
  164. t.Fatalf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(body), err)
  165. }
  166. }
  167. logDone("container REST API - check for duplicate volume binds error on start")
  168. }
  169. func TestContainerApiStartVolumesFrom(t *testing.T) {
  170. defer deleteAllContainers()
  171. volName := "voltst"
  172. volPath := "/tmp"
  173. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  174. t.Fatal(out, err)
  175. }
  176. name := "testing"
  177. config := map[string]interface{}{
  178. "Image": "busybox",
  179. "Volumes": map[string]struct{}{volPath: {}},
  180. }
  181. if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
  182. t.Fatal(err)
  183. }
  184. config = map[string]interface{}{
  185. "VolumesFrom": []string{volName},
  186. }
  187. if _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
  188. t.Fatal(err)
  189. }
  190. pth, err := inspectFieldMap(name, "Volumes", volPath)
  191. if err != nil {
  192. t.Fatal(err)
  193. }
  194. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  195. if err != nil {
  196. t.Fatal(err)
  197. }
  198. if pth != pth2 {
  199. t.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  200. }
  201. logDone("container REST API - check VolumesFrom on start")
  202. }
  203. // Ensure that volumes-from has priority over binds/anything else
  204. // This is pretty much the same as TestRunApplyVolumesFromBeforeVolumes, except with passing the VolumesFrom and the bind on start
  205. func TestVolumesFromHasPriority(t *testing.T) {
  206. defer deleteAllContainers()
  207. volName := "voltst"
  208. volPath := "/tmp"
  209. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  210. t.Fatal(out, err)
  211. }
  212. name := "testing"
  213. config := map[string]interface{}{
  214. "Image": "busybox",
  215. "Volumes": map[string]struct{}{volPath: {}},
  216. }
  217. if _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && !strings.Contains(err.Error(), "201 Created") {
  218. t.Fatal(err)
  219. }
  220. bindPath, err := ioutil.TempDir(os.TempDir(), "test")
  221. if err != nil {
  222. t.Fatal(err)
  223. }
  224. config = map[string]interface{}{
  225. "VolumesFrom": []string{volName},
  226. "Binds": []string{bindPath + ":/tmp"},
  227. }
  228. if _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && !strings.Contains(err.Error(), "204 No Content") {
  229. t.Fatal(err)
  230. }
  231. pth, err := inspectFieldMap(name, "Volumes", volPath)
  232. if err != nil {
  233. t.Fatal(err)
  234. }
  235. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  236. if err != nil {
  237. t.Fatal(err)
  238. }
  239. if pth != pth2 {
  240. t.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  241. }
  242. logDone("container REST API - check VolumesFrom has priority")
  243. }
  244. func TestGetContainerStats(t *testing.T) {
  245. defer deleteAllContainers()
  246. var (
  247. name = "statscontainer"
  248. runCmd = exec.Command(dockerBinary, "run", "-d", "--name", name, "busybox", "top")
  249. )
  250. out, _, err := runCommandWithOutput(runCmd)
  251. if err != nil {
  252. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  253. }
  254. type b struct {
  255. body []byte
  256. err error
  257. }
  258. bc := make(chan b, 1)
  259. go func() {
  260. body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  261. bc <- b{body, err}
  262. }()
  263. // allow some time to stream the stats from the container
  264. time.Sleep(4 * time.Second)
  265. if _, err := runCommand(exec.Command(dockerBinary, "rm", "-f", name)); err != nil {
  266. t.Fatal(err)
  267. }
  268. // collect the results from the stats stream or timeout and fail
  269. // if the stream was not disconnected.
  270. select {
  271. case <-time.After(2 * time.Second):
  272. t.Fatal("stream was not closed after container was removed")
  273. case sr := <-bc:
  274. if sr.err != nil {
  275. t.Fatal(err)
  276. }
  277. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  278. var s *stats.Stats
  279. // decode only one object from the stream
  280. if err := dec.Decode(&s); err != nil {
  281. t.Fatal(err)
  282. }
  283. }
  284. logDone("container REST API - check GET containers/stats")
  285. }
  286. func TestBuildApiDockerfilePath(t *testing.T) {
  287. // Test to make sure we stop people from trying to leave the
  288. // build context when specifying the path to the dockerfile
  289. buffer := new(bytes.Buffer)
  290. tw := tar.NewWriter(buffer)
  291. defer tw.Close()
  292. dockerfile := []byte("FROM busybox")
  293. if err := tw.WriteHeader(&tar.Header{
  294. Name: "Dockerfile",
  295. Size: int64(len(dockerfile)),
  296. }); err != nil {
  297. t.Fatalf("failed to write tar file header: %v", err)
  298. }
  299. if _, err := tw.Write(dockerfile); err != nil {
  300. t.Fatalf("failed to write tar file content: %v", err)
  301. }
  302. if err := tw.Close(); err != nil {
  303. t.Fatalf("failed to close tar archive: %v", err)
  304. }
  305. out, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
  306. if err == nil {
  307. t.Fatalf("Build was supposed to fail: %s", out)
  308. }
  309. if !strings.Contains(string(out), "must be within the build context") {
  310. t.Fatalf("Didn't complain about leaving build context: %s", out)
  311. }
  312. logDone("container REST API - check build w/bad Dockerfile path")
  313. }
  314. func TestBuildApiDockerfileSymlink(t *testing.T) {
  315. // Test to make sure we stop people from trying to leave the
  316. // build context when specifying a symlink as the path to the dockerfile
  317. buffer := new(bytes.Buffer)
  318. tw := tar.NewWriter(buffer)
  319. defer tw.Close()
  320. if err := tw.WriteHeader(&tar.Header{
  321. Name: "Dockerfile",
  322. Typeflag: tar.TypeSymlink,
  323. Linkname: "/etc/passwd",
  324. }); err != nil {
  325. t.Fatalf("failed to write tar file header: %v", err)
  326. }
  327. if err := tw.Close(); err != nil {
  328. t.Fatalf("failed to close tar archive: %v", err)
  329. }
  330. out, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  331. if err == nil {
  332. t.Fatalf("Build was supposed to fail: %s", out)
  333. }
  334. // The reason the error is "Cannot locate specified Dockerfile" is because
  335. // in the builder, the symlink is resolved within the context, therefore
  336. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  337. // a nonexistent file.
  338. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  339. t.Fatalf("Didn't complain about leaving build context: %s", out)
  340. }
  341. logDone("container REST API - check build w/bad Dockerfile symlink path")
  342. }
  343. // #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
  344. func TestPostContainerBindNormalVolume(t *testing.T) {
  345. defer deleteAllContainers()
  346. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=one", "busybox"))
  347. if err != nil {
  348. t.Fatal(err, out)
  349. }
  350. fooDir, err := inspectFieldMap("one", "Volumes", "/foo")
  351. if err != nil {
  352. t.Fatal(err)
  353. }
  354. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=two", "busybox"))
  355. if err != nil {
  356. t.Fatal(err, out)
  357. }
  358. bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
  359. _, err = sockRequest("POST", "/containers/two/start", bindSpec)
  360. if err != nil && !strings.Contains(err.Error(), "204 No Content") {
  361. t.Fatal(err)
  362. }
  363. fooDir2, err := inspectFieldMap("two", "Volumes", "/foo")
  364. if err != nil {
  365. t.Fatal(err)
  366. }
  367. if fooDir2 != fooDir {
  368. t.Fatal("expected volume path to be %s, got: %s", fooDir, fooDir2)
  369. }
  370. logDone("container REST API - can use path from normal volume as bind-mount to overwrite another volume")
  371. }