docker_api_containers_test.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. package main
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "encoding/json"
  6. "io"
  7. "net/http"
  8. "net/http/httputil"
  9. "os"
  10. "os/exec"
  11. "strings"
  12. "time"
  13. "github.com/docker/docker/api/types"
  14. "github.com/docker/docker/pkg/stringid"
  15. "github.com/docker/docker/runconfig"
  16. "github.com/go-check/check"
  17. )
  18. func (s *DockerSuite) TestContainerApiGetAll(c *check.C) {
  19. startCount, err := getContainerCount()
  20. if err != nil {
  21. c.Fatalf("Cannot query container count: %v", err)
  22. }
  23. name := "getall"
  24. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "true")
  25. out, _, err := runCommandWithOutput(runCmd)
  26. if err != nil {
  27. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  28. }
  29. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  30. c.Assert(status, check.Equals, http.StatusOK)
  31. c.Assert(err, check.IsNil)
  32. var inspectJSON []struct {
  33. Names []string
  34. }
  35. if err = json.Unmarshal(body, &inspectJSON); err != nil {
  36. c.Fatalf("unable to unmarshal response body: %v", err)
  37. }
  38. if len(inspectJSON) != startCount+1 {
  39. c.Fatalf("Expected %d container(s), %d found (started with: %d)", startCount+1, len(inspectJSON), startCount)
  40. }
  41. if actual := inspectJSON[0].Names[0]; actual != "/"+name {
  42. c.Fatalf("Container Name mismatch. Expected: %q, received: %q\n", "/"+name, actual)
  43. }
  44. }
  45. func (s *DockerSuite) TestContainerApiGetExport(c *check.C) {
  46. name := "exportcontainer"
  47. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test")
  48. out, _, err := runCommandWithOutput(runCmd)
  49. if err != nil {
  50. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  51. }
  52. status, body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
  53. c.Assert(status, check.Equals, http.StatusOK)
  54. c.Assert(err, check.IsNil)
  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. c.Fatal(err)
  63. }
  64. if h.Name == "test" {
  65. found = true
  66. break
  67. }
  68. }
  69. if !found {
  70. c.Fatalf("The created test file has not been found in the exported image")
  71. }
  72. }
  73. func (s *DockerSuite) TestContainerApiGetChanges(c *check.C) {
  74. name := "changescontainer"
  75. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "rm", "/etc/passwd")
  76. out, _, err := runCommandWithOutput(runCmd)
  77. if err != nil {
  78. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  79. }
  80. status, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
  81. c.Assert(status, check.Equals, http.StatusOK)
  82. c.Assert(err, check.IsNil)
  83. changes := []struct {
  84. Kind int
  85. Path string
  86. }{}
  87. if err = json.Unmarshal(body, &changes); err != nil {
  88. c.Fatalf("unable to unmarshal response body: %v", err)
  89. }
  90. // Check the changelog for removal of /etc/passwd
  91. success := false
  92. for _, elem := range changes {
  93. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  94. success = true
  95. }
  96. }
  97. if !success {
  98. c.Fatalf("/etc/passwd has been removed but is not present in the diff")
  99. }
  100. }
  101. func (s *DockerSuite) TestContainerApiStartVolumeBinds(c *check.C) {
  102. name := "testing"
  103. config := map[string]interface{}{
  104. "Image": "busybox",
  105. "Volumes": map[string]struct{}{"/tmp": {}},
  106. }
  107. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  108. c.Assert(status, check.Equals, http.StatusCreated)
  109. c.Assert(err, check.IsNil)
  110. bindPath := randomUnixTmpDirPath("test")
  111. config = map[string]interface{}{
  112. "Binds": []string{bindPath + ":/tmp"},
  113. }
  114. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  115. c.Assert(status, check.Equals, http.StatusNoContent)
  116. c.Assert(err, check.IsNil)
  117. pth, err := inspectFieldMap(name, "Volumes", "/tmp")
  118. if err != nil {
  119. c.Fatal(err)
  120. }
  121. if pth != bindPath {
  122. c.Fatalf("expected volume host path to be %s, got %s", bindPath, pth)
  123. }
  124. }
  125. // Test for GH#10618
  126. func (s *DockerSuite) TestContainerApiStartDupVolumeBinds(c *check.C) {
  127. name := "testdups"
  128. config := map[string]interface{}{
  129. "Image": "busybox",
  130. "Volumes": map[string]struct{}{"/tmp": {}},
  131. }
  132. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  133. c.Assert(status, check.Equals, http.StatusCreated)
  134. c.Assert(err, check.IsNil)
  135. bindPath1 := randomUnixTmpDirPath("test1")
  136. bindPath2 := randomUnixTmpDirPath("test2")
  137. config = map[string]interface{}{
  138. "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"},
  139. }
  140. status, body, err := sockRequest("POST", "/containers/"+name+"/start", config)
  141. c.Assert(status, check.Equals, http.StatusInternalServerError)
  142. c.Assert(err, check.IsNil)
  143. if !strings.Contains(string(body), "Duplicate bind") {
  144. c.Fatalf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(body), err)
  145. }
  146. }
  147. func (s *DockerSuite) TestContainerApiStartVolumesFrom(c *check.C) {
  148. volName := "voltst"
  149. volPath := "/tmp"
  150. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  151. c.Fatal(out, err)
  152. }
  153. name := "TestContainerApiStartDupVolumeBinds"
  154. config := map[string]interface{}{
  155. "Image": "busybox",
  156. "Volumes": map[string]struct{}{volPath: {}},
  157. }
  158. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  159. c.Assert(status, check.Equals, http.StatusCreated)
  160. c.Assert(err, check.IsNil)
  161. config = map[string]interface{}{
  162. "VolumesFrom": []string{volName},
  163. }
  164. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  165. c.Assert(status, check.Equals, http.StatusNoContent)
  166. c.Assert(err, check.IsNil)
  167. pth, err := inspectFieldMap(name, "Volumes", volPath)
  168. if err != nil {
  169. c.Fatal(err)
  170. }
  171. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  172. if err != nil {
  173. c.Fatal(err)
  174. }
  175. if pth != pth2 {
  176. c.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  177. }
  178. }
  179. func (s *DockerSuite) TestGetContainerStats(c *check.C) {
  180. var (
  181. name = "statscontainer"
  182. runCmd = exec.Command(dockerBinary, "run", "-d", "--name", name, "busybox", "top")
  183. )
  184. out, _, err := runCommandWithOutput(runCmd)
  185. if err != nil {
  186. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  187. }
  188. type b struct {
  189. status int
  190. body []byte
  191. err error
  192. }
  193. bc := make(chan b, 1)
  194. go func() {
  195. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  196. bc <- b{status, body, err}
  197. }()
  198. // allow some time to stream the stats from the container
  199. time.Sleep(4 * time.Second)
  200. if _, err := runCommand(exec.Command(dockerBinary, "rm", "-f", name)); err != nil {
  201. c.Fatal(err)
  202. }
  203. // collect the results from the stats stream or timeout and fail
  204. // if the stream was not disconnected.
  205. select {
  206. case <-time.After(2 * time.Second):
  207. c.Fatal("stream was not closed after container was removed")
  208. case sr := <-bc:
  209. c.Assert(sr.err, check.IsNil)
  210. c.Assert(sr.status, check.Equals, http.StatusOK)
  211. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  212. var s *types.Stats
  213. // decode only one object from the stream
  214. if err := dec.Decode(&s); err != nil {
  215. c.Fatal(err)
  216. }
  217. }
  218. }
  219. func (s *DockerSuite) TestGetContainerStatsRmRunning(c *check.C) {
  220. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  221. id := strings.TrimSpace(out)
  222. buf := &channelBuffer{make(chan []byte, 1)}
  223. defer buf.Close()
  224. chErr := make(chan error)
  225. go func() {
  226. _, body, err := sockRequestRaw("GET", "/containers/"+id+"/stats?stream=1", nil, "application/json")
  227. if err != nil {
  228. chErr <- err
  229. }
  230. defer body.Close()
  231. _, err = io.Copy(buf, body)
  232. chErr <- err
  233. }()
  234. defer func() {
  235. c.Assert(<-chErr, check.IsNil)
  236. }()
  237. b := make([]byte, 32)
  238. // make sure we've got some stats
  239. _, err := buf.ReadTimeout(b, 2*time.Second)
  240. c.Assert(err, check.IsNil)
  241. // Now remove without `-f` and make sure we are still pulling stats
  242. _, err = runCommand(exec.Command(dockerBinary, "rm", id))
  243. c.Assert(err, check.Not(check.IsNil), check.Commentf("rm should have failed but didn't"))
  244. _, err = buf.ReadTimeout(b, 2*time.Second)
  245. c.Assert(err, check.IsNil)
  246. dockerCmd(c, "rm", "-f", id)
  247. _, err = buf.ReadTimeout(b, 2*time.Second)
  248. c.Assert(err, check.Not(check.IsNil))
  249. }
  250. // regression test for gh13421
  251. // previous test was just checking one stat entry so it didn't fail (stats with
  252. // stream false always return one stat)
  253. func (s *DockerSuite) TestGetContainerStatsStream(c *check.C) {
  254. name := "statscontainer"
  255. runCmd := exec.Command(dockerBinary, "run", "-d", "--name", name, "busybox", "top")
  256. _, err := runCommand(runCmd)
  257. c.Assert(err, check.IsNil)
  258. type b struct {
  259. status int
  260. body []byte
  261. err error
  262. }
  263. bc := make(chan b, 1)
  264. go func() {
  265. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  266. bc <- b{status, body, err}
  267. }()
  268. // allow some time to stream the stats from the container
  269. time.Sleep(4 * time.Second)
  270. if _, err := runCommand(exec.Command(dockerBinary, "rm", "-f", name)); err != nil {
  271. c.Fatal(err)
  272. }
  273. // collect the results from the stats stream or timeout and fail
  274. // if the stream was not disconnected.
  275. select {
  276. case <-time.After(2 * time.Second):
  277. c.Fatal("stream was not closed after container was removed")
  278. case sr := <-bc:
  279. c.Assert(sr.err, check.IsNil)
  280. c.Assert(sr.status, check.Equals, http.StatusOK)
  281. s := string(sr.body)
  282. // count occurrences of "read" of types.Stats
  283. if l := strings.Count(s, "read"); l < 2 {
  284. c.Fatalf("Expected more than one stat streamed, got %d", l)
  285. }
  286. }
  287. }
  288. func (s *DockerSuite) TestGetContainerStatsNoStream(c *check.C) {
  289. name := "statscontainer"
  290. runCmd := exec.Command(dockerBinary, "run", "-d", "--name", name, "busybox", "top")
  291. _, err := runCommand(runCmd)
  292. c.Assert(err, check.IsNil)
  293. type b struct {
  294. status int
  295. body []byte
  296. err error
  297. }
  298. bc := make(chan b, 1)
  299. go func() {
  300. status, body, err := sockRequest("GET", "/containers/"+name+"/stats?stream=0", nil)
  301. bc <- b{status, body, err}
  302. }()
  303. // allow some time to stream the stats from the container
  304. time.Sleep(4 * time.Second)
  305. if _, err := runCommand(exec.Command(dockerBinary, "rm", "-f", name)); err != nil {
  306. c.Fatal(err)
  307. }
  308. // collect the results from the stats stream or timeout and fail
  309. // if the stream was not disconnected.
  310. select {
  311. case <-time.After(2 * time.Second):
  312. c.Fatal("stream was not closed after container was removed")
  313. case sr := <-bc:
  314. c.Assert(sr.err, check.IsNil)
  315. c.Assert(sr.status, check.Equals, http.StatusOK)
  316. s := string(sr.body)
  317. // count occurrences of "read" of types.Stats
  318. if l := strings.Count(s, "read"); l != 1 {
  319. c.Fatalf("Expected only one stat streamed, got %d", l)
  320. }
  321. }
  322. }
  323. func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) {
  324. // TODO: this test does nothing because we are c.Assert'ing in goroutine
  325. var (
  326. name = "statscontainer"
  327. runCmd = exec.Command(dockerBinary, "create", "--name", name, "busybox", "top")
  328. )
  329. out, _, err := runCommandWithOutput(runCmd)
  330. if err != nil {
  331. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  332. }
  333. go func() {
  334. // We'll never get return for GET stats from sockRequest as of now,
  335. // just send request and see if panic or error would happen on daemon side.
  336. status, _, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  337. c.Assert(status, check.Equals, http.StatusOK)
  338. c.Assert(err, check.IsNil)
  339. }()
  340. // allow some time to send request and let daemon deal with it
  341. time.Sleep(1 * time.Second)
  342. }
  343. func (s *DockerSuite) TestBuildApiDockerfilePath(c *check.C) {
  344. // Test to make sure we stop people from trying to leave the
  345. // build context when specifying the path to the dockerfile
  346. buffer := new(bytes.Buffer)
  347. tw := tar.NewWriter(buffer)
  348. defer tw.Close()
  349. dockerfile := []byte("FROM busybox")
  350. if err := tw.WriteHeader(&tar.Header{
  351. Name: "Dockerfile",
  352. Size: int64(len(dockerfile)),
  353. }); err != nil {
  354. c.Fatalf("failed to write tar file header: %v", err)
  355. }
  356. if _, err := tw.Write(dockerfile); err != nil {
  357. c.Fatalf("failed to write tar file content: %v", err)
  358. }
  359. if err := tw.Close(); err != nil {
  360. c.Fatalf("failed to close tar archive: %v", err)
  361. }
  362. res, body, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
  363. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  364. c.Assert(err, check.IsNil)
  365. out, err := readBody(body)
  366. if err != nil {
  367. c.Fatal(err)
  368. }
  369. if !strings.Contains(string(out), "must be within the build context") {
  370. c.Fatalf("Didn't complain about leaving build context: %s", out)
  371. }
  372. }
  373. func (s *DockerSuite) TestBuildApiDockerFileRemote(c *check.C) {
  374. server, err := fakeStorage(map[string]string{
  375. "testD": `FROM busybox
  376. COPY * /tmp/
  377. RUN find / -name ba*
  378. RUN find /tmp/`,
  379. })
  380. if err != nil {
  381. c.Fatal(err)
  382. }
  383. defer server.Close()
  384. res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json")
  385. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  386. c.Assert(err, check.IsNil)
  387. buf, err := readBody(body)
  388. if err != nil {
  389. c.Fatal(err)
  390. }
  391. // Make sure Dockerfile exists.
  392. // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL
  393. out := string(buf)
  394. if !strings.Contains(out, "/tmp/Dockerfile") ||
  395. strings.Contains(out, "baz") {
  396. c.Fatalf("Incorrect output: %s", out)
  397. }
  398. }
  399. func (s *DockerSuite) TestBuildApiLowerDockerfile(c *check.C) {
  400. git, err := fakeGIT("repo", map[string]string{
  401. "dockerfile": `FROM busybox
  402. RUN echo from dockerfile`,
  403. }, false)
  404. if err != nil {
  405. c.Fatal(err)
  406. }
  407. defer git.Close()
  408. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  409. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  410. c.Assert(err, check.IsNil)
  411. buf, err := readBody(body)
  412. if err != nil {
  413. c.Fatal(err)
  414. }
  415. out := string(buf)
  416. if !strings.Contains(out, "from dockerfile") {
  417. c.Fatalf("Incorrect output: %s", out)
  418. }
  419. }
  420. func (s *DockerSuite) TestBuildApiBuildGitWithF(c *check.C) {
  421. git, err := fakeGIT("repo", map[string]string{
  422. "baz": `FROM busybox
  423. RUN echo from baz`,
  424. "Dockerfile": `FROM busybox
  425. RUN echo from Dockerfile`,
  426. }, false)
  427. if err != nil {
  428. c.Fatal(err)
  429. }
  430. defer git.Close()
  431. // Make sure it tries to 'dockerfile' query param value
  432. res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
  433. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  434. c.Assert(err, check.IsNil)
  435. buf, err := readBody(body)
  436. if err != nil {
  437. c.Fatal(err)
  438. }
  439. out := string(buf)
  440. if !strings.Contains(out, "from baz") {
  441. c.Fatalf("Incorrect output: %s", out)
  442. }
  443. }
  444. func (s *DockerSuite) TestBuildApiDoubleDockerfile(c *check.C) {
  445. testRequires(c, UnixCli) // dockerfile overwrites Dockerfile on Windows
  446. git, err := fakeGIT("repo", map[string]string{
  447. "Dockerfile": `FROM busybox
  448. RUN echo from Dockerfile`,
  449. "dockerfile": `FROM busybox
  450. RUN echo from dockerfile`,
  451. }, false)
  452. if err != nil {
  453. c.Fatal(err)
  454. }
  455. defer git.Close()
  456. // Make sure it tries to 'dockerfile' query param value
  457. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  458. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  459. c.Assert(err, check.IsNil)
  460. buf, err := readBody(body)
  461. if err != nil {
  462. c.Fatal(err)
  463. }
  464. out := string(buf)
  465. if !strings.Contains(out, "from Dockerfile") {
  466. c.Fatalf("Incorrect output: %s", out)
  467. }
  468. }
  469. func (s *DockerSuite) TestBuildApiDockerfileSymlink(c *check.C) {
  470. // Test to make sure we stop people from trying to leave the
  471. // build context when specifying a symlink as the path to the dockerfile
  472. buffer := new(bytes.Buffer)
  473. tw := tar.NewWriter(buffer)
  474. defer tw.Close()
  475. if err := tw.WriteHeader(&tar.Header{
  476. Name: "Dockerfile",
  477. Typeflag: tar.TypeSymlink,
  478. Linkname: "/etc/passwd",
  479. }); err != nil {
  480. c.Fatalf("failed to write tar file header: %v", err)
  481. }
  482. if err := tw.Close(); err != nil {
  483. c.Fatalf("failed to close tar archive: %v", err)
  484. }
  485. res, body, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  486. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  487. c.Assert(err, check.IsNil)
  488. out, err := readBody(body)
  489. if err != nil {
  490. c.Fatal(err)
  491. }
  492. // The reason the error is "Cannot locate specified Dockerfile" is because
  493. // in the builder, the symlink is resolved within the context, therefore
  494. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  495. // a nonexistent file.
  496. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  497. c.Fatalf("Didn't complain about leaving build context: %s", out)
  498. }
  499. }
  500. // #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
  501. func (s *DockerSuite) TestPostContainerBindNormalVolume(c *check.C) {
  502. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=one", "busybox"))
  503. if err != nil {
  504. c.Fatal(err, out)
  505. }
  506. fooDir, err := inspectFieldMap("one", "Volumes", "/foo")
  507. if err != nil {
  508. c.Fatal(err)
  509. }
  510. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=two", "busybox"))
  511. if err != nil {
  512. c.Fatal(err, out)
  513. }
  514. bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
  515. status, _, err := sockRequest("POST", "/containers/two/start", bindSpec)
  516. c.Assert(status, check.Equals, http.StatusNoContent)
  517. c.Assert(err, check.IsNil)
  518. fooDir2, err := inspectFieldMap("two", "Volumes", "/foo")
  519. if err != nil {
  520. c.Fatal(err)
  521. }
  522. if fooDir2 != fooDir {
  523. c.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2)
  524. }
  525. }
  526. func (s *DockerSuite) TestContainerApiPause(c *check.C) {
  527. defer unpauseAllContainers()
  528. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sleep", "30")
  529. out, _, err := runCommandWithOutput(runCmd)
  530. if err != nil {
  531. c.Fatalf("failed to create a container: %s, %v", out, err)
  532. }
  533. ContainerID := strings.TrimSpace(out)
  534. status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil)
  535. c.Assert(status, check.Equals, http.StatusNoContent)
  536. c.Assert(err, check.IsNil)
  537. pausedContainers, err := getSliceOfPausedContainers()
  538. if err != nil {
  539. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  540. }
  541. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  542. c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  543. }
  544. status, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil)
  545. c.Assert(status, check.Equals, http.StatusNoContent)
  546. c.Assert(err, check.IsNil)
  547. pausedContainers, err = getSliceOfPausedContainers()
  548. if err != nil {
  549. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  550. }
  551. if pausedContainers != nil {
  552. c.Fatalf("There should be no paused container.")
  553. }
  554. }
  555. func (s *DockerSuite) TestContainerApiTop(c *check.C) {
  556. out, err := exec.Command(dockerBinary, "run", "-d", "busybox", "/bin/sh", "-c", "top").CombinedOutput()
  557. if err != nil {
  558. c.Fatal(err, out)
  559. }
  560. id := strings.TrimSpace(string(out))
  561. if err := waitRun(id); err != nil {
  562. c.Fatal(err)
  563. }
  564. type topResp struct {
  565. Titles []string
  566. Processes [][]string
  567. }
  568. var top topResp
  569. status, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil)
  570. c.Assert(status, check.Equals, http.StatusOK)
  571. c.Assert(err, check.IsNil)
  572. if err := json.Unmarshal(b, &top); err != nil {
  573. c.Fatal(err)
  574. }
  575. if len(top.Titles) != 11 {
  576. c.Fatalf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles)
  577. }
  578. if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
  579. c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
  580. }
  581. if len(top.Processes) != 2 {
  582. c.Fatalf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes)
  583. }
  584. if top.Processes[0][10] != "/bin/sh -c top" {
  585. c.Fatalf("expected `/bin/sh -c top`, found: %s", top.Processes[0][10])
  586. }
  587. if top.Processes[1][10] != "top" {
  588. c.Fatalf("expected `top`, found: %s", top.Processes[1][10])
  589. }
  590. }
  591. func (s *DockerSuite) TestContainerApiCommit(c *check.C) {
  592. cName := "testapicommit"
  593. out, err := exec.Command(dockerBinary, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test").CombinedOutput()
  594. if err != nil {
  595. c.Fatal(err, out)
  596. }
  597. name := "TestContainerApiCommit"
  598. status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil)
  599. c.Assert(status, check.Equals, http.StatusCreated)
  600. c.Assert(err, check.IsNil)
  601. type resp struct {
  602. Id string
  603. }
  604. var img resp
  605. if err := json.Unmarshal(b, &img); err != nil {
  606. c.Fatal(err)
  607. }
  608. cmd, err := inspectField(img.Id, "Config.Cmd")
  609. if err != nil {
  610. c.Fatal(err)
  611. }
  612. if cmd != "{[/bin/sh -c touch /test]}" {
  613. c.Fatalf("got wrong Cmd from commit: %q", cmd)
  614. }
  615. // sanity check, make sure the image is what we think it is
  616. out, err = exec.Command(dockerBinary, "run", img.Id, "ls", "/test").CombinedOutput()
  617. if err != nil {
  618. c.Fatalf("error checking committed image: %v - %q", err, string(out))
  619. }
  620. }
  621. func (s *DockerSuite) TestContainerApiCreate(c *check.C) {
  622. config := map[string]interface{}{
  623. "Image": "busybox",
  624. "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"},
  625. }
  626. status, b, err := sockRequest("POST", "/containers/create", config)
  627. c.Assert(status, check.Equals, http.StatusCreated)
  628. c.Assert(err, check.IsNil)
  629. type createResp struct {
  630. Id string
  631. }
  632. var container createResp
  633. if err := json.Unmarshal(b, &container); err != nil {
  634. c.Fatal(err)
  635. }
  636. out, err := exec.Command(dockerBinary, "start", "-a", container.Id).CombinedOutput()
  637. if err != nil {
  638. c.Fatal(out, err)
  639. }
  640. if strings.TrimSpace(string(out)) != "/test" {
  641. c.Fatalf("expected output `/test`, got %q", out)
  642. }
  643. }
  644. func (s *DockerSuite) TestContainerApiCreateWithHostName(c *check.C) {
  645. hostName := "test-host"
  646. config := map[string]interface{}{
  647. "Image": "busybox",
  648. "Hostname": hostName,
  649. }
  650. status, body, err := sockRequest("POST", "/containers/create", config)
  651. c.Assert(err, check.IsNil)
  652. c.Assert(status, check.Equals, http.StatusCreated)
  653. var container types.ContainerCreateResponse
  654. if err := json.Unmarshal(body, &container); err != nil {
  655. c.Fatal(err)
  656. }
  657. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  658. c.Assert(err, check.IsNil)
  659. c.Assert(status, check.Equals, http.StatusOK)
  660. var containerJSON types.ContainerJSON
  661. if err := json.Unmarshal(body, &containerJSON); err != nil {
  662. c.Fatal(err)
  663. }
  664. if containerJSON.Config.Hostname != hostName {
  665. c.Fatalf("Mismatched Hostname, Expected %s, Actual: %s ", hostName, containerJSON.Config.Hostname)
  666. }
  667. }
  668. func (s *DockerSuite) TestContainerApiCreateWithDomainName(c *check.C) {
  669. domainName := "test-domain"
  670. config := map[string]interface{}{
  671. "Image": "busybox",
  672. "Domainname": domainName,
  673. }
  674. status, body, err := sockRequest("POST", "/containers/create", config)
  675. c.Assert(err, check.IsNil)
  676. c.Assert(status, check.Equals, http.StatusCreated)
  677. var container types.ContainerCreateResponse
  678. if err := json.Unmarshal(body, &container); err != nil {
  679. c.Fatal(err)
  680. }
  681. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  682. c.Assert(err, check.IsNil)
  683. c.Assert(status, check.Equals, http.StatusOK)
  684. var containerJSON types.ContainerJSON
  685. if err := json.Unmarshal(body, &containerJSON); err != nil {
  686. c.Fatal(err)
  687. }
  688. if containerJSON.Config.Domainname != domainName {
  689. c.Fatalf("Mismatched Domainname, Expected %s, Actual: %s ", domainName, containerJSON.Config.Domainname)
  690. }
  691. }
  692. func (s *DockerSuite) TestContainerApiCreateNetworkMode(c *check.C) {
  693. UtilCreateNetworkMode(c, "host")
  694. UtilCreateNetworkMode(c, "bridge")
  695. UtilCreateNetworkMode(c, "container:web1")
  696. }
  697. func UtilCreateNetworkMode(c *check.C, networkMode string) {
  698. config := map[string]interface{}{
  699. "Image": "busybox",
  700. "HostConfig": map[string]interface{}{"NetworkMode": networkMode},
  701. }
  702. status, body, err := sockRequest("POST", "/containers/create", config)
  703. c.Assert(err, check.IsNil)
  704. c.Assert(status, check.Equals, http.StatusCreated)
  705. var container types.ContainerCreateResponse
  706. if err := json.Unmarshal(body, &container); err != nil {
  707. c.Fatal(err)
  708. }
  709. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  710. c.Assert(err, check.IsNil)
  711. c.Assert(status, check.Equals, http.StatusOK)
  712. var containerJSON types.ContainerJSON
  713. if err := json.Unmarshal(body, &containerJSON); err != nil {
  714. c.Fatal(err)
  715. }
  716. if containerJSON.HostConfig.NetworkMode != runconfig.NetworkMode(networkMode) {
  717. c.Fatalf("Mismatched NetworkMode, Expected %s, Actual: %s ", networkMode, containerJSON.HostConfig.NetworkMode)
  718. }
  719. }
  720. func (s *DockerSuite) TestContainerApiCreateWithCpuSharesCpuset(c *check.C) {
  721. config := map[string]interface{}{
  722. "Image": "busybox",
  723. "CpuShares": 512,
  724. "CpusetCpus": "0,1",
  725. }
  726. status, body, err := sockRequest("POST", "/containers/create", config)
  727. c.Assert(err, check.IsNil)
  728. c.Assert(status, check.Equals, http.StatusCreated)
  729. var container types.ContainerCreateResponse
  730. if err := json.Unmarshal(body, &container); err != nil {
  731. c.Fatal(err)
  732. }
  733. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  734. c.Assert(err, check.IsNil)
  735. c.Assert(status, check.Equals, http.StatusOK)
  736. var containerJson types.ContainerJSON
  737. c.Assert(json.Unmarshal(body, &containerJson), check.IsNil)
  738. out, err := inspectField(containerJson.Id, "HostConfig.CpuShares")
  739. c.Assert(err, check.IsNil)
  740. c.Assert(out, check.Equals, "512")
  741. outCpuset, errCpuset := inspectField(containerJson.Id, "HostConfig.CpusetCpus")
  742. c.Assert(errCpuset, check.IsNil, check.Commentf("Output: %s", outCpuset))
  743. c.Assert(outCpuset, check.Equals, "0,1")
  744. }
  745. func (s *DockerSuite) TestContainerApiVerifyHeader(c *check.C) {
  746. config := map[string]interface{}{
  747. "Image": "busybox",
  748. }
  749. create := func(ct string) (*http.Response, io.ReadCloser, error) {
  750. jsonData := bytes.NewBuffer(nil)
  751. if err := json.NewEncoder(jsonData).Encode(config); err != nil {
  752. c.Fatal(err)
  753. }
  754. return sockRequestRaw("POST", "/containers/create", jsonData, ct)
  755. }
  756. // Try with no content-type
  757. res, body, err := create("")
  758. c.Assert(err, check.IsNil)
  759. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  760. body.Close()
  761. // Try with wrong content-type
  762. res, body, err = create("application/xml")
  763. c.Assert(err, check.IsNil)
  764. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  765. body.Close()
  766. // now application/json
  767. res, body, err = create("application/json")
  768. c.Assert(err, check.IsNil)
  769. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  770. body.Close()
  771. }
  772. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  773. // W/o this fix a null in JSON would be parsed into a string var as "null"
  774. func (s *DockerSuite) TestContainerApiPostCreateNull(c *check.C) {
  775. config := `{
  776. "Hostname":"",
  777. "Domainname":"",
  778. "Memory":0,
  779. "MemorySwap":0,
  780. "CpuShares":0,
  781. "Cpuset":null,
  782. "AttachStdin":true,
  783. "AttachStdout":true,
  784. "AttachStderr":true,
  785. "PortSpecs":null,
  786. "ExposedPorts":{},
  787. "Tty":true,
  788. "OpenStdin":true,
  789. "StdinOnce":true,
  790. "Env":[],
  791. "Cmd":"ls",
  792. "Image":"busybox",
  793. "Volumes":{},
  794. "WorkingDir":"",
  795. "Entrypoint":null,
  796. "NetworkDisabled":false,
  797. "OnBuild":null}`
  798. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  799. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  800. c.Assert(err, check.IsNil)
  801. b, err := readBody(body)
  802. if err != nil {
  803. c.Fatal(err)
  804. }
  805. type createResp struct {
  806. Id string
  807. }
  808. var container createResp
  809. if err := json.Unmarshal(b, &container); err != nil {
  810. c.Fatal(err)
  811. }
  812. out, err := inspectField(container.Id, "HostConfig.CpusetCpus")
  813. if err != nil {
  814. c.Fatal(err, out)
  815. }
  816. if out != "" {
  817. c.Fatalf("expected empty string, got %q", out)
  818. }
  819. outMemory, errMemory := inspectField(container.Id, "HostConfig.Memory")
  820. c.Assert(outMemory, check.Equals, "0")
  821. if errMemory != nil {
  822. c.Fatal(errMemory, outMemory)
  823. }
  824. outMemorySwap, errMemorySwap := inspectField(container.Id, "HostConfig.MemorySwap")
  825. c.Assert(outMemorySwap, check.Equals, "0")
  826. if errMemorySwap != nil {
  827. c.Fatal(errMemorySwap, outMemorySwap)
  828. }
  829. }
  830. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  831. config := `{
  832. "Image": "busybox",
  833. "Cmd": "ls",
  834. "OpenStdin": true,
  835. "CpuShares": 100,
  836. "Memory": 524287
  837. }`
  838. res, body, _ := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  839. b, err2 := readBody(body)
  840. if err2 != nil {
  841. c.Fatal(err2)
  842. }
  843. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  844. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  845. }
  846. func (s *DockerSuite) TestStartWithTooLowMemoryLimit(c *check.C) {
  847. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "busybox"))
  848. if err != nil {
  849. c.Fatal(err, out)
  850. }
  851. containerID := strings.TrimSpace(out)
  852. config := `{
  853. "CpuShares": 100,
  854. "Memory": 524287
  855. }`
  856. res, body, _ := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  857. b, err2 := readBody(body)
  858. if err2 != nil {
  859. c.Fatal(err2)
  860. }
  861. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  862. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  863. }
  864. func (s *DockerSuite) TestContainerApiRename(c *check.C) {
  865. runCmd := exec.Command(dockerBinary, "run", "--name", "TestContainerApiRename", "-d", "busybox", "sh")
  866. out, _, err := runCommandWithOutput(runCmd)
  867. c.Assert(err, check.IsNil)
  868. containerID := strings.TrimSpace(out)
  869. newName := "TestContainerApiRenameNew"
  870. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
  871. // 204 No Content is expected, not 200
  872. c.Assert(statusCode, check.Equals, http.StatusNoContent)
  873. c.Assert(err, check.IsNil)
  874. name, err := inspectField(containerID, "Name")
  875. if name != "/"+newName {
  876. c.Fatalf("Failed to rename container, expected %v, got %v. Container rename API failed", newName, name)
  877. }
  878. }
  879. func (s *DockerSuite) TestContainerApiKill(c *check.C) {
  880. name := "test-api-kill"
  881. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  882. out, _, err := runCommandWithOutput(runCmd)
  883. if err != nil {
  884. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  885. }
  886. status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil)
  887. c.Assert(status, check.Equals, http.StatusNoContent)
  888. c.Assert(err, check.IsNil)
  889. state, err := inspectField(name, "State.Running")
  890. if err != nil {
  891. c.Fatal(err)
  892. }
  893. if state != "false" {
  894. c.Fatalf("got wrong State from container %s: %q", name, state)
  895. }
  896. }
  897. func (s *DockerSuite) TestContainerApiRestart(c *check.C) {
  898. name := "test-api-restart"
  899. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  900. out, _, err := runCommandWithOutput(runCmd)
  901. if err != nil {
  902. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  903. }
  904. status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil)
  905. c.Assert(status, check.Equals, http.StatusNoContent)
  906. c.Assert(err, check.IsNil)
  907. if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil {
  908. c.Fatal(err)
  909. }
  910. }
  911. func (s *DockerSuite) TestContainerApiRestartNotimeoutParam(c *check.C) {
  912. name := "test-api-restart-no-timeout-param"
  913. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  914. out, _, err := runCommandWithOutput(runCmd)
  915. if err != nil {
  916. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  917. }
  918. id := strings.TrimSpace(out)
  919. c.Assert(waitRun(id), check.IsNil)
  920. status, _, err := sockRequest("POST", "/containers/"+name+"/restart", nil)
  921. c.Assert(status, check.Equals, http.StatusNoContent)
  922. c.Assert(err, check.IsNil)
  923. if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil {
  924. c.Fatal(err)
  925. }
  926. }
  927. func (s *DockerSuite) TestContainerApiStart(c *check.C) {
  928. name := "testing-start"
  929. config := map[string]interface{}{
  930. "Image": "busybox",
  931. "Cmd": []string{"/bin/sh", "-c", "/bin/top"},
  932. "OpenStdin": true,
  933. }
  934. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  935. c.Assert(status, check.Equals, http.StatusCreated)
  936. c.Assert(err, check.IsNil)
  937. conf := make(map[string]interface{})
  938. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  939. c.Assert(status, check.Equals, http.StatusNoContent)
  940. c.Assert(err, check.IsNil)
  941. // second call to start should give 304
  942. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  943. c.Assert(status, check.Equals, http.StatusNotModified)
  944. c.Assert(err, check.IsNil)
  945. }
  946. func (s *DockerSuite) TestContainerApiStop(c *check.C) {
  947. name := "test-api-stop"
  948. runCmd := exec.Command(dockerBinary, "run", "-di", "--name", name, "busybox", "top")
  949. out, _, err := runCommandWithOutput(runCmd)
  950. if err != nil {
  951. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  952. }
  953. status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  954. c.Assert(status, check.Equals, http.StatusNoContent)
  955. c.Assert(err, check.IsNil)
  956. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  957. c.Fatal(err)
  958. }
  959. // second call to start should give 304
  960. status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  961. c.Assert(status, check.Equals, http.StatusNotModified)
  962. c.Assert(err, check.IsNil)
  963. }
  964. func (s *DockerSuite) TestContainerApiWait(c *check.C) {
  965. name := "test-api-wait"
  966. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sleep", "5")
  967. out, _, err := runCommandWithOutput(runCmd)
  968. if err != nil {
  969. c.Fatalf("Error on container creation: %v, output: %q", err, out)
  970. }
  971. status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil)
  972. c.Assert(status, check.Equals, http.StatusOK)
  973. c.Assert(err, check.IsNil)
  974. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  975. c.Fatal(err)
  976. }
  977. var waitres types.ContainerWaitResponse
  978. if err := json.Unmarshal(body, &waitres); err != nil {
  979. c.Fatalf("unable to unmarshal response body: %v", err)
  980. }
  981. if waitres.StatusCode != 0 {
  982. c.Fatalf("Expected wait response StatusCode to be 0, got %d", waitres.StatusCode)
  983. }
  984. }
  985. func (s *DockerSuite) TestContainerApiCopy(c *check.C) {
  986. name := "test-container-api-copy"
  987. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test.txt")
  988. _, err := runCommand(runCmd)
  989. c.Assert(err, check.IsNil)
  990. postData := types.CopyConfig{
  991. Resource: "/test.txt",
  992. }
  993. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  994. c.Assert(err, check.IsNil)
  995. c.Assert(status, check.Equals, http.StatusOK)
  996. found := false
  997. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  998. h, err := tarReader.Next()
  999. if err != nil {
  1000. if err == io.EOF {
  1001. break
  1002. }
  1003. c.Fatal(err)
  1004. }
  1005. if h.Name == "test.txt" {
  1006. found = true
  1007. break
  1008. }
  1009. }
  1010. c.Assert(found, check.Equals, true)
  1011. }
  1012. func (s *DockerSuite) TestContainerApiCopyResourcePathEmpty(c *check.C) {
  1013. name := "test-container-api-copy-resource-empty"
  1014. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test.txt")
  1015. _, err := runCommand(runCmd)
  1016. c.Assert(err, check.IsNil)
  1017. postData := types.CopyConfig{
  1018. Resource: "",
  1019. }
  1020. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  1021. c.Assert(err, check.IsNil)
  1022. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1023. c.Assert(string(body), check.Matches, "Path cannot be empty\n")
  1024. }
  1025. func (s *DockerSuite) TestContainerApiCopyResourcePathNotFound(c *check.C) {
  1026. name := "test-container-api-copy-resource-not-found"
  1027. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox")
  1028. _, err := runCommand(runCmd)
  1029. c.Assert(err, check.IsNil)
  1030. postData := types.CopyConfig{
  1031. Resource: "/notexist",
  1032. }
  1033. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  1034. c.Assert(err, check.IsNil)
  1035. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1036. c.Assert(string(body), check.Matches, "Could not find the file /notexist in container "+name+"\n")
  1037. }
  1038. func (s *DockerSuite) TestContainerApiCopyContainerNotFound(c *check.C) {
  1039. postData := types.CopyConfig{
  1040. Resource: "/something",
  1041. }
  1042. status, _, err := sockRequest("POST", "/containers/notexists/copy", postData)
  1043. c.Assert(err, check.IsNil)
  1044. c.Assert(status, check.Equals, http.StatusNotFound)
  1045. }
  1046. func (s *DockerSuite) TestContainerApiDelete(c *check.C) {
  1047. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1048. out, _, err := runCommandWithOutput(runCmd)
  1049. c.Assert(err, check.IsNil)
  1050. id := strings.TrimSpace(out)
  1051. c.Assert(waitRun(id), check.IsNil)
  1052. stopCmd := exec.Command(dockerBinary, "stop", id)
  1053. _, err = runCommand(stopCmd)
  1054. c.Assert(err, check.IsNil)
  1055. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  1056. c.Assert(err, check.IsNil)
  1057. c.Assert(status, check.Equals, http.StatusNoContent)
  1058. }
  1059. func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) {
  1060. status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
  1061. c.Assert(err, check.IsNil)
  1062. c.Assert(status, check.Equals, http.StatusNotFound)
  1063. c.Assert(string(body), check.Matches, "no such id: doesnotexist\n")
  1064. }
  1065. func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) {
  1066. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1067. out, _, err := runCommandWithOutput(runCmd)
  1068. c.Assert(err, check.IsNil)
  1069. id := strings.TrimSpace(out)
  1070. c.Assert(waitRun(id), check.IsNil)
  1071. status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
  1072. c.Assert(err, check.IsNil)
  1073. c.Assert(status, check.Equals, http.StatusNoContent)
  1074. }
  1075. func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) {
  1076. runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "tlink1", "busybox", "top")
  1077. out, _, err := runCommandWithOutput(runCmd)
  1078. c.Assert(err, check.IsNil)
  1079. id := strings.TrimSpace(out)
  1080. c.Assert(waitRun(id), check.IsNil)
  1081. runCmd = exec.Command(dockerBinary, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  1082. out, _, err = runCommandWithOutput(runCmd)
  1083. c.Assert(err, check.IsNil)
  1084. id2 := strings.TrimSpace(out)
  1085. c.Assert(waitRun(id2), check.IsNil)
  1086. links, err := inspectFieldJSON(id2, "HostConfig.Links")
  1087. c.Assert(err, check.IsNil)
  1088. if links != "[\"/tlink1:/tlink2/tlink1\"]" {
  1089. c.Fatal("expected to have links between containers")
  1090. }
  1091. status, _, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
  1092. c.Assert(err, check.IsNil)
  1093. c.Assert(status, check.Equals, http.StatusNoContent)
  1094. linksPostRm, err := inspectFieldJSON(id2, "HostConfig.Links")
  1095. c.Assert(err, check.IsNil)
  1096. if linksPostRm != "null" {
  1097. c.Fatal("call to api deleteContainer links should have removed the specified links")
  1098. }
  1099. }
  1100. func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) {
  1101. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1102. out, _, err := runCommandWithOutput(runCmd)
  1103. c.Assert(err, check.IsNil)
  1104. id := strings.TrimSpace(out)
  1105. c.Assert(waitRun(id), check.IsNil)
  1106. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  1107. c.Assert(status, check.Equals, http.StatusConflict)
  1108. c.Assert(err, check.IsNil)
  1109. }
  1110. func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) {
  1111. testRequires(c, SameHostDaemon)
  1112. runCmd := exec.Command(dockerBinary, "run", "-d", "-v", "/testvolume", "busybox", "top")
  1113. out, _, err := runCommandWithOutput(runCmd)
  1114. c.Assert(err, check.IsNil)
  1115. id := strings.TrimSpace(out)
  1116. c.Assert(waitRun(id), check.IsNil)
  1117. vol, err := inspectFieldMap(id, "Volumes", "/testvolume")
  1118. c.Assert(err, check.IsNil)
  1119. _, err = os.Stat(vol)
  1120. c.Assert(err, check.IsNil)
  1121. status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
  1122. c.Assert(status, check.Equals, http.StatusNoContent)
  1123. c.Assert(err, check.IsNil)
  1124. if _, err := os.Stat(vol); !os.IsNotExist(err) {
  1125. c.Fatalf("expected to get ErrNotExist error, got %v", err)
  1126. }
  1127. }
  1128. // Regression test for https://github.com/docker/docker/issues/6231
  1129. func (s *DockerSuite) TestContainersApiChunkedEncoding(c *check.C) {
  1130. out, _ := dockerCmd(c, "create", "-v", "/foo", "busybox", "true")
  1131. id := strings.TrimSpace(out)
  1132. conn, err := sockConn(time.Duration(10 * time.Second))
  1133. if err != nil {
  1134. c.Fatal(err)
  1135. }
  1136. client := httputil.NewClientConn(conn, nil)
  1137. defer client.Close()
  1138. bindCfg := strings.NewReader(`{"Binds": ["/tmp:/foo"]}`)
  1139. req, err := http.NewRequest("POST", "/containers/"+id+"/start", bindCfg)
  1140. if err != nil {
  1141. c.Fatal(err)
  1142. }
  1143. req.Header.Set("Content-Type", "application/json")
  1144. // This is a cheat to make the http request do chunked encoding
  1145. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  1146. // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
  1147. req.ContentLength = -1
  1148. resp, err := client.Do(req)
  1149. if err != nil {
  1150. c.Fatalf("error starting container with chunked encoding: %v", err)
  1151. }
  1152. resp.Body.Close()
  1153. if resp.StatusCode != 204 {
  1154. c.Fatalf("expected status code 204, got %d", resp.StatusCode)
  1155. }
  1156. out, err = inspectFieldJSON(id, "HostConfig.Binds")
  1157. if err != nil {
  1158. c.Fatal(err)
  1159. }
  1160. var binds []string
  1161. if err := json.NewDecoder(strings.NewReader(out)).Decode(&binds); err != nil {
  1162. c.Fatal(err)
  1163. }
  1164. if len(binds) != 1 {
  1165. c.Fatalf("got unexpected binds: %v", binds)
  1166. }
  1167. expected := "/tmp:/foo"
  1168. if binds[0] != expected {
  1169. c.Fatalf("got incorrect bind spec, wanted %s, got: %s", expected, binds[0])
  1170. }
  1171. }
  1172. func (s *DockerSuite) TestPostContainerStop(c *check.C) {
  1173. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1174. out, _, err := runCommandWithOutput(runCmd)
  1175. c.Assert(err, check.IsNil)
  1176. containerID := strings.TrimSpace(out)
  1177. c.Assert(waitRun(containerID), check.IsNil)
  1178. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/stop", nil)
  1179. // 204 No Content is expected, not 200
  1180. c.Assert(statusCode, check.Equals, http.StatusNoContent)
  1181. c.Assert(err, check.IsNil)
  1182. if err := waitInspect(containerID, "{{ .State.Running }}", "false", 5); err != nil {
  1183. c.Fatal(err)
  1184. }
  1185. }