docker_api_containers_test.go 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732
  1. package main
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "net/http/httputil"
  11. "net/url"
  12. "os"
  13. "path/filepath"
  14. "regexp"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/docker/docker/api/types"
  19. containertypes "github.com/docker/docker/api/types/container"
  20. mounttypes "github.com/docker/docker/api/types/mount"
  21. networktypes "github.com/docker/docker/api/types/network"
  22. "github.com/docker/docker/pkg/integration"
  23. "github.com/docker/docker/pkg/integration/checker"
  24. "github.com/docker/docker/pkg/ioutils"
  25. "github.com/docker/docker/pkg/mount"
  26. "github.com/docker/docker/pkg/stringid"
  27. "github.com/docker/docker/volume"
  28. "github.com/go-check/check"
  29. )
  30. func (s *DockerSuite) TestContainerAPIGetAll(c *check.C) {
  31. startCount, err := getContainerCount()
  32. c.Assert(err, checker.IsNil, check.Commentf("Cannot query container count"))
  33. name := "getall"
  34. dockerCmd(c, "run", "--name", name, "busybox", "true")
  35. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  36. c.Assert(err, checker.IsNil)
  37. c.Assert(status, checker.Equals, http.StatusOK)
  38. var inspectJSON []struct {
  39. Names []string
  40. }
  41. err = json.Unmarshal(body, &inspectJSON)
  42. c.Assert(err, checker.IsNil, check.Commentf("unable to unmarshal response body"))
  43. c.Assert(inspectJSON, checker.HasLen, startCount+1)
  44. actual := inspectJSON[0].Names[0]
  45. c.Assert(actual, checker.Equals, "/"+name)
  46. }
  47. // regression test for empty json field being omitted #13691
  48. func (s *DockerSuite) TestContainerAPIGetJSONNoFieldsOmitted(c *check.C) {
  49. dockerCmd(c, "run", "busybox", "true")
  50. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  51. c.Assert(err, checker.IsNil)
  52. c.Assert(status, checker.Equals, http.StatusOK)
  53. // empty Labels field triggered this bug, make sense to check for everything
  54. // cause even Ports for instance can trigger this bug
  55. // better safe than sorry..
  56. fields := []string{
  57. "Id",
  58. "Names",
  59. "Image",
  60. "Command",
  61. "Created",
  62. "Ports",
  63. "Labels",
  64. "Status",
  65. "NetworkSettings",
  66. }
  67. // decoding into types.Container do not work since it eventually unmarshal
  68. // and empty field to an empty go map, so we just check for a string
  69. for _, f := range fields {
  70. if !strings.Contains(string(body), f) {
  71. c.Fatalf("Field %s is missing and it shouldn't", f)
  72. }
  73. }
  74. }
  75. type containerPs struct {
  76. Names []string
  77. Ports []map[string]interface{}
  78. }
  79. // regression test for non-empty fields from #13901
  80. func (s *DockerSuite) TestContainerAPIPsOmitFields(c *check.C) {
  81. // Problematic for Windows porting due to networking not yet being passed back
  82. testRequires(c, DaemonIsLinux)
  83. name := "pstest"
  84. port := 80
  85. runSleepingContainer(c, "--name", name, "--expose", strconv.Itoa(port))
  86. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  87. c.Assert(err, checker.IsNil)
  88. c.Assert(status, checker.Equals, http.StatusOK)
  89. var resp []containerPs
  90. err = json.Unmarshal(body, &resp)
  91. c.Assert(err, checker.IsNil)
  92. var foundContainer *containerPs
  93. for _, container := range resp {
  94. for _, testName := range container.Names {
  95. if "/"+name == testName {
  96. foundContainer = &container
  97. break
  98. }
  99. }
  100. }
  101. c.Assert(foundContainer.Ports, checker.HasLen, 1)
  102. c.Assert(foundContainer.Ports[0]["PrivatePort"], checker.Equals, float64(port))
  103. _, ok := foundContainer.Ports[0]["PublicPort"]
  104. c.Assert(ok, checker.Not(checker.Equals), true)
  105. _, ok = foundContainer.Ports[0]["IP"]
  106. c.Assert(ok, checker.Not(checker.Equals), true)
  107. }
  108. func (s *DockerSuite) TestContainerAPIGetExport(c *check.C) {
  109. // TODO: Investigate why this fails on Windows to Windows CI
  110. testRequires(c, DaemonIsLinux)
  111. name := "exportcontainer"
  112. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test")
  113. status, body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
  114. c.Assert(err, checker.IsNil)
  115. c.Assert(status, checker.Equals, http.StatusOK)
  116. found := false
  117. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  118. h, err := tarReader.Next()
  119. if err != nil && err == io.EOF {
  120. break
  121. }
  122. if h.Name == "test" {
  123. found = true
  124. break
  125. }
  126. }
  127. c.Assert(found, checker.True, check.Commentf("The created test file has not been found in the exported image"))
  128. }
  129. func (s *DockerSuite) TestContainerAPIGetChanges(c *check.C) {
  130. // Not supported on Windows as Windows does not support docker diff (/containers/name/changes)
  131. testRequires(c, DaemonIsLinux)
  132. name := "changescontainer"
  133. dockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd")
  134. status, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
  135. c.Assert(err, checker.IsNil)
  136. c.Assert(status, checker.Equals, http.StatusOK)
  137. changes := []struct {
  138. Kind int
  139. Path string
  140. }{}
  141. c.Assert(json.Unmarshal(body, &changes), checker.IsNil, check.Commentf("unable to unmarshal response body"))
  142. // Check the changelog for removal of /etc/passwd
  143. success := false
  144. for _, elem := range changes {
  145. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  146. success = true
  147. }
  148. }
  149. c.Assert(success, checker.True, check.Commentf("/etc/passwd has been removed but is not present in the diff"))
  150. }
  151. func (s *DockerSuite) TestGetContainerStats(c *check.C) {
  152. var (
  153. name = "statscontainer"
  154. )
  155. runSleepingContainer(c, "--name", name)
  156. type b struct {
  157. status int
  158. body []byte
  159. err error
  160. }
  161. bc := make(chan b, 1)
  162. go func() {
  163. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  164. bc <- b{status, body, err}
  165. }()
  166. // allow some time to stream the stats from the container
  167. time.Sleep(4 * time.Second)
  168. dockerCmd(c, "rm", "-f", name)
  169. // collect the results from the stats stream or timeout and fail
  170. // if the stream was not disconnected.
  171. select {
  172. case <-time.After(2 * time.Second):
  173. c.Fatal("stream was not closed after container was removed")
  174. case sr := <-bc:
  175. c.Assert(sr.err, checker.IsNil)
  176. c.Assert(sr.status, checker.Equals, http.StatusOK)
  177. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  178. var s *types.Stats
  179. // decode only one object from the stream
  180. c.Assert(dec.Decode(&s), checker.IsNil)
  181. }
  182. }
  183. func (s *DockerSuite) TestGetContainerStatsRmRunning(c *check.C) {
  184. out, _ := runSleepingContainer(c)
  185. id := strings.TrimSpace(out)
  186. buf := &integration.ChannelBuffer{make(chan []byte, 1)}
  187. defer buf.Close()
  188. _, body, err := sockRequestRaw("GET", "/containers/"+id+"/stats?stream=1", nil, "application/json")
  189. c.Assert(err, checker.IsNil)
  190. defer body.Close()
  191. chErr := make(chan error, 1)
  192. go func() {
  193. _, err = io.Copy(buf, body)
  194. chErr <- err
  195. }()
  196. b := make([]byte, 32)
  197. // make sure we've got some stats
  198. _, err = buf.ReadTimeout(b, 2*time.Second)
  199. c.Assert(err, checker.IsNil)
  200. // Now remove without `-f` and make sure we are still pulling stats
  201. _, _, err = dockerCmdWithError("rm", id)
  202. c.Assert(err, checker.Not(checker.IsNil), check.Commentf("rm should have failed but didn't"))
  203. _, err = buf.ReadTimeout(b, 2*time.Second)
  204. c.Assert(err, checker.IsNil)
  205. dockerCmd(c, "rm", "-f", id)
  206. c.Assert(<-chErr, checker.IsNil)
  207. }
  208. // regression test for gh13421
  209. // previous test was just checking one stat entry so it didn't fail (stats with
  210. // stream false always return one stat)
  211. func (s *DockerSuite) TestGetContainerStatsStream(c *check.C) {
  212. name := "statscontainer"
  213. runSleepingContainer(c, "--name", name)
  214. type b struct {
  215. status int
  216. body []byte
  217. err error
  218. }
  219. bc := make(chan b, 1)
  220. go func() {
  221. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  222. bc <- b{status, body, err}
  223. }()
  224. // allow some time to stream the stats from the container
  225. time.Sleep(4 * time.Second)
  226. dockerCmd(c, "rm", "-f", name)
  227. // collect the results from the stats stream or timeout and fail
  228. // if the stream was not disconnected.
  229. select {
  230. case <-time.After(2 * time.Second):
  231. c.Fatal("stream was not closed after container was removed")
  232. case sr := <-bc:
  233. c.Assert(sr.err, checker.IsNil)
  234. c.Assert(sr.status, checker.Equals, http.StatusOK)
  235. s := string(sr.body)
  236. // count occurrences of "read" of types.Stats
  237. if l := strings.Count(s, "read"); l < 2 {
  238. c.Fatalf("Expected more than one stat streamed, got %d", l)
  239. }
  240. }
  241. }
  242. func (s *DockerSuite) TestGetContainerStatsNoStream(c *check.C) {
  243. name := "statscontainer"
  244. runSleepingContainer(c, "--name", name)
  245. type b struct {
  246. status int
  247. body []byte
  248. err error
  249. }
  250. bc := make(chan b, 1)
  251. go func() {
  252. status, body, err := sockRequest("GET", "/containers/"+name+"/stats?stream=0", nil)
  253. bc <- b{status, body, err}
  254. }()
  255. // allow some time to stream the stats from the container
  256. time.Sleep(4 * time.Second)
  257. dockerCmd(c, "rm", "-f", name)
  258. // collect the results from the stats stream or timeout and fail
  259. // if the stream was not disconnected.
  260. select {
  261. case <-time.After(2 * time.Second):
  262. c.Fatal("stream was not closed after container was removed")
  263. case sr := <-bc:
  264. c.Assert(sr.err, checker.IsNil)
  265. c.Assert(sr.status, checker.Equals, http.StatusOK)
  266. s := string(sr.body)
  267. // count occurrences of `"read"` of types.Stats
  268. c.Assert(strings.Count(s, `"read"`), checker.Equals, 1, check.Commentf("Expected only one stat streamed, got %d", strings.Count(s, `"read"`)))
  269. }
  270. }
  271. func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) {
  272. name := "statscontainer"
  273. dockerCmd(c, "create", "--name", name, "busybox", "ps")
  274. type stats struct {
  275. status int
  276. err error
  277. }
  278. chResp := make(chan stats)
  279. // We expect an immediate response, but if it's not immediate, the test would hang, so put it in a goroutine
  280. // below we'll check this on a timeout.
  281. go func() {
  282. resp, body, err := sockRequestRaw("GET", "/containers/"+name+"/stats", nil, "")
  283. body.Close()
  284. chResp <- stats{resp.StatusCode, err}
  285. }()
  286. select {
  287. case r := <-chResp:
  288. c.Assert(r.err, checker.IsNil)
  289. c.Assert(r.status, checker.Equals, http.StatusOK)
  290. case <-time.After(10 * time.Second):
  291. c.Fatal("timeout waiting for stats response for stopped container")
  292. }
  293. }
  294. func (s *DockerSuite) TestContainerAPIPause(c *check.C) {
  295. // Problematic on Windows as Windows does not support pause
  296. testRequires(c, DaemonIsLinux)
  297. defer unpauseAllContainers()
  298. out, _ := dockerCmd(c, "run", "-d", "busybox", "sleep", "30")
  299. ContainerID := strings.TrimSpace(out)
  300. status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil)
  301. c.Assert(err, checker.IsNil)
  302. c.Assert(status, checker.Equals, http.StatusNoContent)
  303. pausedContainers, err := getSliceOfPausedContainers()
  304. c.Assert(err, checker.IsNil, check.Commentf("error thrown while checking if containers were paused"))
  305. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  306. c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  307. }
  308. status, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil)
  309. c.Assert(err, checker.IsNil)
  310. c.Assert(status, checker.Equals, http.StatusNoContent)
  311. pausedContainers, err = getSliceOfPausedContainers()
  312. c.Assert(err, checker.IsNil, check.Commentf("error thrown while checking if containers were paused"))
  313. c.Assert(pausedContainers, checker.IsNil, check.Commentf("There should be no paused container."))
  314. }
  315. func (s *DockerSuite) TestContainerAPITop(c *check.C) {
  316. // Problematic on Windows as Windows does not support top
  317. testRequires(c, DaemonIsLinux)
  318. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top")
  319. id := strings.TrimSpace(string(out))
  320. c.Assert(waitRun(id), checker.IsNil)
  321. type topResp struct {
  322. Titles []string
  323. Processes [][]string
  324. }
  325. var top topResp
  326. status, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil)
  327. c.Assert(err, checker.IsNil)
  328. c.Assert(status, checker.Equals, http.StatusOK)
  329. c.Assert(json.Unmarshal(b, &top), checker.IsNil)
  330. c.Assert(top.Titles, checker.HasLen, 11, check.Commentf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles))
  331. if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
  332. c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
  333. }
  334. c.Assert(top.Processes, checker.HasLen, 2, check.Commentf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes))
  335. c.Assert(top.Processes[0][10], checker.Equals, "/bin/sh -c top")
  336. c.Assert(top.Processes[1][10], checker.Equals, "top")
  337. }
  338. func (s *DockerSuite) TestContainerAPICommit(c *check.C) {
  339. cName := "testapicommit"
  340. dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
  341. name := "testcontainerapicommit"
  342. status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil)
  343. c.Assert(err, checker.IsNil)
  344. c.Assert(status, checker.Equals, http.StatusCreated)
  345. type resp struct {
  346. ID string
  347. }
  348. var img resp
  349. c.Assert(json.Unmarshal(b, &img), checker.IsNil)
  350. cmd := inspectField(c, img.ID, "Config.Cmd")
  351. c.Assert(cmd, checker.Equals, "[/bin/sh -c touch /test]", check.Commentf("got wrong Cmd from commit: %q", cmd))
  352. // sanity check, make sure the image is what we think it is
  353. dockerCmd(c, "run", img.ID, "ls", "/test")
  354. }
  355. func (s *DockerSuite) TestContainerAPICommitWithLabelInConfig(c *check.C) {
  356. cName := "testapicommitwithconfig"
  357. dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
  358. config := map[string]interface{}{
  359. "Labels": map[string]string{"key1": "value1", "key2": "value2"},
  360. }
  361. name := "testcontainerapicommitwithconfig"
  362. status, b, err := sockRequest("POST", "/commit?repo="+name+"&container="+cName, config)
  363. c.Assert(err, checker.IsNil)
  364. c.Assert(status, checker.Equals, http.StatusCreated)
  365. type resp struct {
  366. ID string
  367. }
  368. var img resp
  369. c.Assert(json.Unmarshal(b, &img), checker.IsNil)
  370. label1 := inspectFieldMap(c, img.ID, "Config.Labels", "key1")
  371. c.Assert(label1, checker.Equals, "value1")
  372. label2 := inspectFieldMap(c, img.ID, "Config.Labels", "key2")
  373. c.Assert(label2, checker.Equals, "value2")
  374. cmd := inspectField(c, img.ID, "Config.Cmd")
  375. c.Assert(cmd, checker.Equals, "[/bin/sh -c touch /test]", check.Commentf("got wrong Cmd from commit: %q", cmd))
  376. // sanity check, make sure the image is what we think it is
  377. dockerCmd(c, "run", img.ID, "ls", "/test")
  378. }
  379. func (s *DockerSuite) TestContainerAPIBadPort(c *check.C) {
  380. // TODO Windows to Windows CI - Port this test
  381. testRequires(c, DaemonIsLinux)
  382. config := map[string]interface{}{
  383. "Image": "busybox",
  384. "Cmd": []string{"/bin/sh", "-c", "echo test"},
  385. "PortBindings": map[string]interface{}{
  386. "8080/tcp": []map[string]interface{}{
  387. {
  388. "HostIP": "",
  389. "HostPort": "aa80",
  390. },
  391. },
  392. },
  393. }
  394. jsonData := bytes.NewBuffer(nil)
  395. json.NewEncoder(jsonData).Encode(config)
  396. status, body, err := sockRequest("POST", "/containers/create", config)
  397. c.Assert(err, checker.IsNil)
  398. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  399. c.Assert(getErrorMessage(c, body), checker.Equals, `invalid port specification: "aa80"`, check.Commentf("Incorrect error msg: %s", body))
  400. }
  401. func (s *DockerSuite) TestContainerAPICreate(c *check.C) {
  402. config := map[string]interface{}{
  403. "Image": "busybox",
  404. "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"},
  405. }
  406. status, b, err := sockRequest("POST", "/containers/create", config)
  407. c.Assert(err, checker.IsNil)
  408. c.Assert(status, checker.Equals, http.StatusCreated)
  409. type createResp struct {
  410. ID string
  411. }
  412. var container createResp
  413. c.Assert(json.Unmarshal(b, &container), checker.IsNil)
  414. out, _ := dockerCmd(c, "start", "-a", container.ID)
  415. c.Assert(strings.TrimSpace(out), checker.Equals, "/test")
  416. }
  417. func (s *DockerSuite) TestContainerAPICreateEmptyConfig(c *check.C) {
  418. config := map[string]interface{}{}
  419. status, body, err := sockRequest("POST", "/containers/create", config)
  420. c.Assert(err, checker.IsNil)
  421. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  422. expected := "Config cannot be empty in order to create a container"
  423. c.Assert(getErrorMessage(c, body), checker.Equals, expected)
  424. }
  425. func (s *DockerSuite) TestContainerAPICreateMultipleNetworksConfig(c *check.C) {
  426. // Container creation must fail if client specified configurations for more than one network
  427. config := map[string]interface{}{
  428. "Image": "busybox",
  429. "NetworkingConfig": networktypes.NetworkingConfig{
  430. EndpointsConfig: map[string]*networktypes.EndpointSettings{
  431. "net1": {},
  432. "net2": {},
  433. "net3": {},
  434. },
  435. },
  436. }
  437. status, body, err := sockRequest("POST", "/containers/create", config)
  438. c.Assert(err, checker.IsNil)
  439. c.Assert(status, checker.Equals, http.StatusBadRequest)
  440. msg := getErrorMessage(c, body)
  441. // network name order in error message is not deterministic
  442. c.Assert(msg, checker.Contains, "Container cannot be connected to network endpoints")
  443. c.Assert(msg, checker.Contains, "net1")
  444. c.Assert(msg, checker.Contains, "net2")
  445. c.Assert(msg, checker.Contains, "net3")
  446. }
  447. func (s *DockerSuite) TestContainerAPICreateWithHostName(c *check.C) {
  448. hostName := "test-host"
  449. config := map[string]interface{}{
  450. "Image": "busybox",
  451. "Hostname": hostName,
  452. }
  453. status, body, err := sockRequest("POST", "/containers/create", config)
  454. c.Assert(err, checker.IsNil)
  455. c.Assert(status, checker.Equals, http.StatusCreated)
  456. var container types.ContainerCreateResponse
  457. c.Assert(json.Unmarshal(body, &container), checker.IsNil)
  458. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  459. c.Assert(err, checker.IsNil)
  460. c.Assert(status, checker.Equals, http.StatusOK)
  461. var containerJSON types.ContainerJSON
  462. c.Assert(json.Unmarshal(body, &containerJSON), checker.IsNil)
  463. c.Assert(containerJSON.Config.Hostname, checker.Equals, hostName, check.Commentf("Mismatched Hostname"))
  464. }
  465. func (s *DockerSuite) TestContainerAPICreateWithDomainName(c *check.C) {
  466. domainName := "test-domain"
  467. config := map[string]interface{}{
  468. "Image": "busybox",
  469. "Domainname": domainName,
  470. }
  471. status, body, err := sockRequest("POST", "/containers/create", config)
  472. c.Assert(err, checker.IsNil)
  473. c.Assert(status, checker.Equals, http.StatusCreated)
  474. var container types.ContainerCreateResponse
  475. c.Assert(json.Unmarshal(body, &container), checker.IsNil)
  476. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  477. c.Assert(err, checker.IsNil)
  478. c.Assert(status, checker.Equals, http.StatusOK)
  479. var containerJSON types.ContainerJSON
  480. c.Assert(json.Unmarshal(body, &containerJSON), checker.IsNil)
  481. c.Assert(containerJSON.Config.Domainname, checker.Equals, domainName, check.Commentf("Mismatched Domainname"))
  482. }
  483. func (s *DockerSuite) TestContainerAPICreateBridgeNetworkMode(c *check.C) {
  484. // Windows does not support bridge
  485. testRequires(c, DaemonIsLinux)
  486. UtilCreateNetworkMode(c, "bridge")
  487. }
  488. func (s *DockerSuite) TestContainerAPICreateOtherNetworkModes(c *check.C) {
  489. // Windows does not support these network modes
  490. testRequires(c, DaemonIsLinux, NotUserNamespace)
  491. UtilCreateNetworkMode(c, "host")
  492. UtilCreateNetworkMode(c, "container:web1")
  493. }
  494. func UtilCreateNetworkMode(c *check.C, networkMode string) {
  495. config := map[string]interface{}{
  496. "Image": "busybox",
  497. "HostConfig": map[string]interface{}{"NetworkMode": networkMode},
  498. }
  499. status, body, err := sockRequest("POST", "/containers/create", config)
  500. c.Assert(err, checker.IsNil)
  501. c.Assert(status, checker.Equals, http.StatusCreated)
  502. var container types.ContainerCreateResponse
  503. c.Assert(json.Unmarshal(body, &container), checker.IsNil)
  504. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  505. c.Assert(err, checker.IsNil)
  506. c.Assert(status, checker.Equals, http.StatusOK)
  507. var containerJSON types.ContainerJSON
  508. c.Assert(json.Unmarshal(body, &containerJSON), checker.IsNil)
  509. c.Assert(containerJSON.HostConfig.NetworkMode, checker.Equals, containertypes.NetworkMode(networkMode), check.Commentf("Mismatched NetworkMode"))
  510. }
  511. func (s *DockerSuite) TestContainerAPICreateWithCpuSharesCpuset(c *check.C) {
  512. // TODO Windows to Windows CI. The CpuShares part could be ported.
  513. testRequires(c, DaemonIsLinux)
  514. config := map[string]interface{}{
  515. "Image": "busybox",
  516. "CpuShares": 512,
  517. "CpusetCpus": "0",
  518. }
  519. status, body, err := sockRequest("POST", "/containers/create", config)
  520. c.Assert(err, checker.IsNil)
  521. c.Assert(status, checker.Equals, http.StatusCreated)
  522. var container types.ContainerCreateResponse
  523. c.Assert(json.Unmarshal(body, &container), checker.IsNil)
  524. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  525. c.Assert(err, checker.IsNil)
  526. c.Assert(status, checker.Equals, http.StatusOK)
  527. var containerJSON types.ContainerJSON
  528. c.Assert(json.Unmarshal(body, &containerJSON), checker.IsNil)
  529. out := inspectField(c, containerJSON.ID, "HostConfig.CpuShares")
  530. c.Assert(out, checker.Equals, "512")
  531. outCpuset := inspectField(c, containerJSON.ID, "HostConfig.CpusetCpus")
  532. c.Assert(outCpuset, checker.Equals, "0")
  533. }
  534. func (s *DockerSuite) TestContainerAPIVerifyHeader(c *check.C) {
  535. config := map[string]interface{}{
  536. "Image": "busybox",
  537. }
  538. create := func(ct string) (*http.Response, io.ReadCloser, error) {
  539. jsonData := bytes.NewBuffer(nil)
  540. c.Assert(json.NewEncoder(jsonData).Encode(config), checker.IsNil)
  541. return sockRequestRaw("POST", "/containers/create", jsonData, ct)
  542. }
  543. // Try with no content-type
  544. res, body, err := create("")
  545. c.Assert(err, checker.IsNil)
  546. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  547. body.Close()
  548. // Try with wrong content-type
  549. res, body, err = create("application/xml")
  550. c.Assert(err, checker.IsNil)
  551. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  552. body.Close()
  553. // now application/json
  554. res, body, err = create("application/json")
  555. c.Assert(err, checker.IsNil)
  556. c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
  557. body.Close()
  558. }
  559. //Issue 14230. daemon should return 500 for invalid port syntax
  560. func (s *DockerSuite) TestContainerAPIInvalidPortSyntax(c *check.C) {
  561. config := `{
  562. "Image": "busybox",
  563. "HostConfig": {
  564. "NetworkMode": "default",
  565. "PortBindings": {
  566. "19039;1230": [
  567. {}
  568. ]
  569. }
  570. }
  571. }`
  572. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  573. c.Assert(err, checker.IsNil)
  574. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  575. b, err := readBody(body)
  576. c.Assert(err, checker.IsNil)
  577. c.Assert(string(b[:]), checker.Contains, "invalid port")
  578. }
  579. func (s *DockerSuite) TestContainerAPIInvalidRestartPolicyName(c *check.C) {
  580. config := `{
  581. "Image": "busybox",
  582. "HostConfig": {
  583. "RestartPolicy": {
  584. "Name": "something",
  585. "MaximumRetryCount": 0
  586. }
  587. }
  588. }`
  589. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  590. c.Assert(err, checker.IsNil)
  591. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  592. b, err := readBody(body)
  593. c.Assert(err, checker.IsNil)
  594. c.Assert(string(b[:]), checker.Contains, "invalid restart policy")
  595. }
  596. func (s *DockerSuite) TestContainerAPIInvalidRestartPolicyRetryMismatch(c *check.C) {
  597. config := `{
  598. "Image": "busybox",
  599. "HostConfig": {
  600. "RestartPolicy": {
  601. "Name": "always",
  602. "MaximumRetryCount": 2
  603. }
  604. }
  605. }`
  606. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  607. c.Assert(err, checker.IsNil)
  608. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  609. b, err := readBody(body)
  610. c.Assert(err, checker.IsNil)
  611. c.Assert(string(b[:]), checker.Contains, "maximum restart count not valid with restart policy")
  612. }
  613. func (s *DockerSuite) TestContainerAPIInvalidRestartPolicyPositiveRetryCount(c *check.C) {
  614. config := `{
  615. "Image": "busybox",
  616. "HostConfig": {
  617. "RestartPolicy": {
  618. "Name": "on-failure",
  619. "MaximumRetryCount": -2
  620. }
  621. }
  622. }`
  623. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  624. c.Assert(err, checker.IsNil)
  625. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  626. b, err := readBody(body)
  627. c.Assert(err, checker.IsNil)
  628. c.Assert(string(b[:]), checker.Contains, "maximum restart count must be a positive integer")
  629. }
  630. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  631. // W/o this fix a null in JSON would be parsed into a string var as "null"
  632. func (s *DockerSuite) TestContainerAPIPostCreateNull(c *check.C) {
  633. config := `{
  634. "Hostname":"",
  635. "Domainname":"",
  636. "Memory":0,
  637. "MemorySwap":0,
  638. "CpuShares":0,
  639. "Cpuset":null,
  640. "AttachStdin":true,
  641. "AttachStdout":true,
  642. "AttachStderr":true,
  643. "ExposedPorts":{},
  644. "Tty":true,
  645. "OpenStdin":true,
  646. "StdinOnce":true,
  647. "Env":[],
  648. "Cmd":"ls",
  649. "Image":"busybox",
  650. "Volumes":{},
  651. "WorkingDir":"",
  652. "Entrypoint":null,
  653. "NetworkDisabled":false,
  654. "OnBuild":null}`
  655. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  656. c.Assert(err, checker.IsNil)
  657. c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
  658. b, err := readBody(body)
  659. c.Assert(err, checker.IsNil)
  660. type createResp struct {
  661. ID string
  662. }
  663. var container createResp
  664. c.Assert(json.Unmarshal(b, &container), checker.IsNil)
  665. out := inspectField(c, container.ID, "HostConfig.CpusetCpus")
  666. c.Assert(out, checker.Equals, "")
  667. outMemory := inspectField(c, container.ID, "HostConfig.Memory")
  668. c.Assert(outMemory, checker.Equals, "0")
  669. outMemorySwap := inspectField(c, container.ID, "HostConfig.MemorySwap")
  670. c.Assert(outMemorySwap, checker.Equals, "0")
  671. }
  672. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  673. // TODO Windows: Port once memory is supported
  674. testRequires(c, DaemonIsLinux)
  675. config := `{
  676. "Image": "busybox",
  677. "Cmd": "ls",
  678. "OpenStdin": true,
  679. "CpuShares": 100,
  680. "Memory": 524287
  681. }`
  682. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  683. c.Assert(err, checker.IsNil)
  684. b, err2 := readBody(body)
  685. c.Assert(err2, checker.IsNil)
  686. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  687. c.Assert(string(b), checker.Contains, "Minimum memory limit allowed is 4MB")
  688. }
  689. func (s *DockerSuite) TestContainerAPIRename(c *check.C) {
  690. out, _ := dockerCmd(c, "run", "--name", "TestContainerAPIRename", "-d", "busybox", "sh")
  691. containerID := strings.TrimSpace(out)
  692. newName := "TestContainerAPIRenameNew"
  693. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
  694. c.Assert(err, checker.IsNil)
  695. // 204 No Content is expected, not 200
  696. c.Assert(statusCode, checker.Equals, http.StatusNoContent)
  697. name := inspectField(c, containerID, "Name")
  698. c.Assert(name, checker.Equals, "/"+newName, check.Commentf("Failed to rename container"))
  699. }
  700. func (s *DockerSuite) TestContainerAPIKill(c *check.C) {
  701. name := "test-api-kill"
  702. runSleepingContainer(c, "-i", "--name", name)
  703. status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil)
  704. c.Assert(err, checker.IsNil)
  705. c.Assert(status, checker.Equals, http.StatusNoContent)
  706. state := inspectField(c, name, "State.Running")
  707. c.Assert(state, checker.Equals, "false", check.Commentf("got wrong State from container %s: %q", name, state))
  708. }
  709. func (s *DockerSuite) TestContainerAPIRestart(c *check.C) {
  710. // TODO Windows to Windows CI. This is flaky due to the timing
  711. testRequires(c, DaemonIsLinux)
  712. name := "test-api-restart"
  713. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  714. status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil)
  715. c.Assert(err, checker.IsNil)
  716. c.Assert(status, checker.Equals, http.StatusNoContent)
  717. c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5*time.Second), checker.IsNil)
  718. }
  719. func (s *DockerSuite) TestContainerAPIRestartNotimeoutParam(c *check.C) {
  720. // TODO Windows to Windows CI. This is flaky due to the timing
  721. testRequires(c, DaemonIsLinux)
  722. name := "test-api-restart-no-timeout-param"
  723. out, _ := dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  724. id := strings.TrimSpace(out)
  725. c.Assert(waitRun(id), checker.IsNil)
  726. status, _, err := sockRequest("POST", "/containers/"+name+"/restart", nil)
  727. c.Assert(err, checker.IsNil)
  728. c.Assert(status, checker.Equals, http.StatusNoContent)
  729. c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5*time.Second), checker.IsNil)
  730. }
  731. func (s *DockerSuite) TestContainerAPIStart(c *check.C) {
  732. name := "testing-start"
  733. config := map[string]interface{}{
  734. "Image": "busybox",
  735. "Cmd": append([]string{"/bin/sh", "-c"}, sleepCommandForDaemonPlatform()...),
  736. "OpenStdin": true,
  737. }
  738. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  739. c.Assert(err, checker.IsNil)
  740. c.Assert(status, checker.Equals, http.StatusCreated)
  741. status, _, err = sockRequest("POST", "/containers/"+name+"/start", nil)
  742. c.Assert(err, checker.IsNil)
  743. c.Assert(status, checker.Equals, http.StatusNoContent)
  744. // second call to start should give 304
  745. status, _, err = sockRequest("POST", "/containers/"+name+"/start", nil)
  746. c.Assert(err, checker.IsNil)
  747. // TODO(tibor): figure out why this doesn't work on windows
  748. if isLocalDaemon {
  749. c.Assert(status, checker.Equals, http.StatusNotModified)
  750. }
  751. }
  752. func (s *DockerSuite) TestContainerAPIStop(c *check.C) {
  753. name := "test-api-stop"
  754. runSleepingContainer(c, "-i", "--name", name)
  755. status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=30", nil)
  756. c.Assert(err, checker.IsNil)
  757. c.Assert(status, checker.Equals, http.StatusNoContent)
  758. c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil)
  759. // second call to start should give 304
  760. status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=30", nil)
  761. c.Assert(err, checker.IsNil)
  762. c.Assert(status, checker.Equals, http.StatusNotModified)
  763. }
  764. func (s *DockerSuite) TestContainerAPIWait(c *check.C) {
  765. name := "test-api-wait"
  766. sleepCmd := "/bin/sleep"
  767. if daemonPlatform == "windows" {
  768. sleepCmd = "sleep"
  769. }
  770. dockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "2")
  771. status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil)
  772. c.Assert(err, checker.IsNil)
  773. c.Assert(status, checker.Equals, http.StatusOK)
  774. c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil)
  775. var waitres types.ContainerWaitResponse
  776. c.Assert(json.Unmarshal(body, &waitres), checker.IsNil)
  777. c.Assert(waitres.StatusCode, checker.Equals, 0)
  778. }
  779. func (s *DockerSuite) TestContainerAPICopyNotExistsAnyMore(c *check.C) {
  780. name := "test-container-api-copy"
  781. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  782. postData := types.CopyConfig{
  783. Resource: "/test.txt",
  784. }
  785. status, _, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  786. c.Assert(err, checker.IsNil)
  787. c.Assert(status, checker.Equals, http.StatusNotFound)
  788. }
  789. func (s *DockerSuite) TestContainerAPICopyPre124(c *check.C) {
  790. name := "test-container-api-copy"
  791. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  792. postData := types.CopyConfig{
  793. Resource: "/test.txt",
  794. }
  795. status, body, err := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
  796. c.Assert(err, checker.IsNil)
  797. c.Assert(status, checker.Equals, http.StatusOK)
  798. found := false
  799. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  800. h, err := tarReader.Next()
  801. if err != nil {
  802. if err == io.EOF {
  803. break
  804. }
  805. c.Fatal(err)
  806. }
  807. if h.Name == "test.txt" {
  808. found = true
  809. break
  810. }
  811. }
  812. c.Assert(found, checker.True)
  813. }
  814. func (s *DockerSuite) TestContainerAPICopyResourcePathEmptyPr124(c *check.C) {
  815. name := "test-container-api-copy-resource-empty"
  816. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  817. postData := types.CopyConfig{
  818. Resource: "",
  819. }
  820. status, body, err := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
  821. c.Assert(err, checker.IsNil)
  822. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  823. c.Assert(string(body), checker.Matches, "Path cannot be empty\n")
  824. }
  825. func (s *DockerSuite) TestContainerAPICopyResourcePathNotFoundPre124(c *check.C) {
  826. name := "test-container-api-copy-resource-not-found"
  827. dockerCmd(c, "run", "--name", name, "busybox")
  828. postData := types.CopyConfig{
  829. Resource: "/notexist",
  830. }
  831. status, body, err := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
  832. c.Assert(err, checker.IsNil)
  833. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  834. c.Assert(string(body), checker.Matches, "Could not find the file /notexist in container "+name+"\n")
  835. }
  836. func (s *DockerSuite) TestContainerAPICopyContainerNotFoundPr124(c *check.C) {
  837. postData := types.CopyConfig{
  838. Resource: "/something",
  839. }
  840. status, _, err := sockRequest("POST", "/v1.23/containers/notexists/copy", postData)
  841. c.Assert(err, checker.IsNil)
  842. c.Assert(status, checker.Equals, http.StatusNotFound)
  843. }
  844. func (s *DockerSuite) TestContainerAPIDelete(c *check.C) {
  845. out, _ := runSleepingContainer(c)
  846. id := strings.TrimSpace(out)
  847. c.Assert(waitRun(id), checker.IsNil)
  848. dockerCmd(c, "stop", id)
  849. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  850. c.Assert(err, checker.IsNil)
  851. c.Assert(status, checker.Equals, http.StatusNoContent)
  852. }
  853. func (s *DockerSuite) TestContainerAPIDeleteNotExist(c *check.C) {
  854. status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
  855. c.Assert(err, checker.IsNil)
  856. c.Assert(status, checker.Equals, http.StatusNotFound)
  857. c.Assert(getErrorMessage(c, body), checker.Matches, "No such container: doesnotexist")
  858. }
  859. func (s *DockerSuite) TestContainerAPIDeleteForce(c *check.C) {
  860. out, _ := runSleepingContainer(c)
  861. id := strings.TrimSpace(out)
  862. c.Assert(waitRun(id), checker.IsNil)
  863. status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
  864. c.Assert(err, checker.IsNil)
  865. c.Assert(status, checker.Equals, http.StatusNoContent)
  866. }
  867. func (s *DockerSuite) TestContainerAPIDeleteRemoveLinks(c *check.C) {
  868. // Windows does not support links
  869. testRequires(c, DaemonIsLinux)
  870. out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top")
  871. id := strings.TrimSpace(out)
  872. c.Assert(waitRun(id), checker.IsNil)
  873. out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  874. id2 := strings.TrimSpace(out)
  875. c.Assert(waitRun(id2), checker.IsNil)
  876. links := inspectFieldJSON(c, id2, "HostConfig.Links")
  877. c.Assert(links, checker.Equals, "[\"/tlink1:/tlink2/tlink1\"]", check.Commentf("expected to have links between containers"))
  878. status, b, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
  879. c.Assert(err, check.IsNil)
  880. c.Assert(status, check.Equals, http.StatusNoContent, check.Commentf(string(b)))
  881. linksPostRm := inspectFieldJSON(c, id2, "HostConfig.Links")
  882. c.Assert(linksPostRm, checker.Equals, "null", check.Commentf("call to api deleteContainer links should have removed the specified links"))
  883. }
  884. func (s *DockerSuite) TestContainerAPIDeleteConflict(c *check.C) {
  885. out, _ := runSleepingContainer(c)
  886. id := strings.TrimSpace(out)
  887. c.Assert(waitRun(id), checker.IsNil)
  888. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  889. c.Assert(err, checker.IsNil)
  890. c.Assert(status, checker.Equals, http.StatusConflict)
  891. }
  892. func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) {
  893. testRequires(c, SameHostDaemon)
  894. vol := "/testvolume"
  895. if daemonPlatform == "windows" {
  896. vol = `c:\testvolume`
  897. }
  898. out, _ := runSleepingContainer(c, "-v", vol)
  899. id := strings.TrimSpace(out)
  900. c.Assert(waitRun(id), checker.IsNil)
  901. source, err := inspectMountSourceField(id, vol)
  902. _, err = os.Stat(source)
  903. c.Assert(err, checker.IsNil)
  904. status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
  905. c.Assert(err, checker.IsNil)
  906. c.Assert(status, checker.Equals, http.StatusNoContent)
  907. _, err = os.Stat(source)
  908. c.Assert(os.IsNotExist(err), checker.True, check.Commentf("expected to get ErrNotExist error, got %v", err))
  909. }
  910. // Regression test for https://github.com/docker/docker/issues/6231
  911. func (s *DockerSuite) TestContainerAPIChunkedEncoding(c *check.C) {
  912. conn, err := sockConn(time.Duration(10*time.Second), "")
  913. c.Assert(err, checker.IsNil)
  914. client := httputil.NewClientConn(conn, nil)
  915. defer client.Close()
  916. config := map[string]interface{}{
  917. "Image": "busybox",
  918. "Cmd": append([]string{"/bin/sh", "-c"}, sleepCommandForDaemonPlatform()...),
  919. "OpenStdin": true,
  920. }
  921. b, err := json.Marshal(config)
  922. c.Assert(err, checker.IsNil)
  923. req, err := http.NewRequest("POST", "/containers/create", bytes.NewBuffer(b))
  924. c.Assert(err, checker.IsNil)
  925. req.Header.Set("Content-Type", "application/json")
  926. // This is a cheat to make the http request do chunked encoding
  927. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  928. // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
  929. req.ContentLength = -1
  930. resp, err := client.Do(req)
  931. c.Assert(err, checker.IsNil, check.Commentf("error creating container with chunked encoding"))
  932. resp.Body.Close()
  933. c.Assert(resp.StatusCode, checker.Equals, http.StatusCreated)
  934. }
  935. func (s *DockerSuite) TestContainerAPIPostContainerStop(c *check.C) {
  936. out, _ := runSleepingContainer(c)
  937. containerID := strings.TrimSpace(out)
  938. c.Assert(waitRun(containerID), checker.IsNil)
  939. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/stop", nil)
  940. c.Assert(err, checker.IsNil)
  941. // 204 No Content is expected, not 200
  942. c.Assert(statusCode, checker.Equals, http.StatusNoContent)
  943. c.Assert(waitInspect(containerID, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil)
  944. }
  945. // #14170
  946. func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *check.C) {
  947. config := struct {
  948. Image string
  949. Entrypoint string
  950. Cmd []string
  951. }{"busybox", "echo", []string{"hello", "world"}}
  952. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  953. c.Assert(err, checker.IsNil)
  954. out, _ := dockerCmd(c, "start", "-a", "echotest")
  955. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  956. config2 := struct {
  957. Image string
  958. Entrypoint []string
  959. Cmd []string
  960. }{"busybox", []string{"echo"}, []string{"hello", "world"}}
  961. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  962. c.Assert(err, checker.IsNil)
  963. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  964. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  965. }
  966. // #14170
  967. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) {
  968. config := struct {
  969. Image string
  970. Entrypoint string
  971. Cmd string
  972. }{"busybox", "echo", "hello world"}
  973. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  974. c.Assert(err, checker.IsNil)
  975. out, _ := dockerCmd(c, "start", "-a", "echotest")
  976. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  977. config2 := struct {
  978. Image string
  979. Cmd []string
  980. }{"busybox", []string{"echo", "hello", "world"}}
  981. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  982. c.Assert(err, checker.IsNil)
  983. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  984. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  985. }
  986. // regression #14318
  987. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *check.C) {
  988. // Windows doesn't support CapAdd/CapDrop
  989. testRequires(c, DaemonIsLinux)
  990. config := struct {
  991. Image string
  992. CapAdd string
  993. CapDrop string
  994. }{"busybox", "NET_ADMIN", "SYS_ADMIN"}
  995. status, _, err := sockRequest("POST", "/containers/create?name=capaddtest0", config)
  996. c.Assert(err, checker.IsNil)
  997. c.Assert(status, checker.Equals, http.StatusCreated)
  998. config2 := struct {
  999. Image string
  1000. CapAdd []string
  1001. CapDrop []string
  1002. }{"busybox", []string{"NET_ADMIN", "SYS_ADMIN"}, []string{"SETGID"}}
  1003. status, _, err = sockRequest("POST", "/containers/create?name=capaddtest1", config2)
  1004. c.Assert(err, checker.IsNil)
  1005. c.Assert(status, checker.Equals, http.StatusCreated)
  1006. }
  1007. // #14915
  1008. func (s *DockerSuite) TestContainerAPICreateNoHostConfig118(c *check.C) {
  1009. config := struct {
  1010. Image string
  1011. }{"busybox"}
  1012. status, _, err := sockRequest("POST", "/v1.18/containers/create", config)
  1013. c.Assert(err, checker.IsNil)
  1014. c.Assert(status, checker.Equals, http.StatusCreated)
  1015. }
  1016. // Ensure an error occurs when you have a container read-only rootfs but you
  1017. // extract an archive to a symlink in a writable volume which points to a
  1018. // directory outside of the volume.
  1019. func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(c *check.C) {
  1020. // Windows does not support read-only rootfs
  1021. // Requires local volume mount bind.
  1022. // --read-only + userns has remount issues
  1023. testRequires(c, SameHostDaemon, NotUserNamespace, DaemonIsLinux)
  1024. testVol := getTestDir(c, "test-put-container-archive-err-symlink-in-volume-to-read-only-rootfs-")
  1025. defer os.RemoveAll(testVol)
  1026. makeTestContentInDir(c, testVol)
  1027. cID := makeTestContainer(c, testContainerOptions{
  1028. readOnly: true,
  1029. volumes: defaultVolumes(testVol), // Our bind mount is at /vol2
  1030. })
  1031. defer deleteContainer(cID)
  1032. // Attempt to extract to a symlink in the volume which points to a
  1033. // directory outside the volume. This should cause an error because the
  1034. // rootfs is read-only.
  1035. query := make(url.Values, 1)
  1036. query.Set("path", "/vol2/symlinkToAbsDir")
  1037. urlPath := fmt.Sprintf("/v1.20/containers/%s/archive?%s", cID, query.Encode())
  1038. statusCode, body, err := sockRequest("PUT", urlPath, nil)
  1039. c.Assert(err, checker.IsNil)
  1040. if !isCpCannotCopyReadOnly(fmt.Errorf(string(body))) {
  1041. c.Fatalf("expected ErrContainerRootfsReadonly error, but got %d: %s", statusCode, string(body))
  1042. }
  1043. }
  1044. func (s *DockerSuite) TestContainerAPIGetContainersJSONEmpty(c *check.C) {
  1045. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  1046. c.Assert(err, checker.IsNil)
  1047. c.Assert(status, checker.Equals, http.StatusOK)
  1048. c.Assert(string(body), checker.Equals, "[]\n")
  1049. }
  1050. func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) {
  1051. // Not supported on Windows
  1052. testRequires(c, DaemonIsLinux)
  1053. c1 := struct {
  1054. Image string
  1055. CpusetCpus string
  1056. }{"busybox", "1-42,,"}
  1057. name := "wrong-cpuset-cpus"
  1058. status, body, err := sockRequest("POST", "/containers/create?name="+name, c1)
  1059. c.Assert(err, checker.IsNil)
  1060. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  1061. expected := "Invalid value 1-42,, for cpuset cpus"
  1062. c.Assert(getErrorMessage(c, body), checker.Equals, expected)
  1063. c2 := struct {
  1064. Image string
  1065. CpusetMems string
  1066. }{"busybox", "42-3,1--"}
  1067. name = "wrong-cpuset-mems"
  1068. status, body, err = sockRequest("POST", "/containers/create?name="+name, c2)
  1069. c.Assert(err, checker.IsNil)
  1070. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  1071. expected = "Invalid value 42-3,1-- for cpuset mems"
  1072. c.Assert(getErrorMessage(c, body), checker.Equals, expected)
  1073. }
  1074. func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) {
  1075. // ShmSize is not supported on Windows
  1076. testRequires(c, DaemonIsLinux)
  1077. config := map[string]interface{}{
  1078. "Image": "busybox",
  1079. "HostConfig": map[string]interface{}{"ShmSize": -1},
  1080. }
  1081. status, body, err := sockRequest("POST", "/containers/create", config)
  1082. c.Assert(err, check.IsNil)
  1083. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1084. c.Assert(getErrorMessage(c, body), checker.Contains, "SHM size can not be less than 0")
  1085. }
  1086. func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check.C) {
  1087. // ShmSize is not supported on Windows
  1088. testRequires(c, DaemonIsLinux)
  1089. var defaultSHMSize int64 = 67108864
  1090. config := map[string]interface{}{
  1091. "Image": "busybox",
  1092. "Cmd": "mount",
  1093. }
  1094. status, body, err := sockRequest("POST", "/containers/create", config)
  1095. c.Assert(err, check.IsNil)
  1096. c.Assert(status, check.Equals, http.StatusCreated)
  1097. var container types.ContainerCreateResponse
  1098. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1099. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1100. c.Assert(err, check.IsNil)
  1101. c.Assert(status, check.Equals, http.StatusOK)
  1102. var containerJSON types.ContainerJSON
  1103. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1104. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, defaultSHMSize)
  1105. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1106. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1107. if !shmRegexp.MatchString(out) {
  1108. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1109. }
  1110. }
  1111. func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *check.C) {
  1112. // ShmSize is not supported on Windows
  1113. testRequires(c, DaemonIsLinux)
  1114. config := map[string]interface{}{
  1115. "Image": "busybox",
  1116. "HostConfig": map[string]interface{}{},
  1117. "Cmd": "mount",
  1118. }
  1119. status, body, err := sockRequest("POST", "/containers/create", config)
  1120. c.Assert(err, check.IsNil)
  1121. c.Assert(status, check.Equals, http.StatusCreated)
  1122. var container types.ContainerCreateResponse
  1123. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1124. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1125. c.Assert(err, check.IsNil)
  1126. c.Assert(status, check.Equals, http.StatusOK)
  1127. var containerJSON types.ContainerJSON
  1128. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1129. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(67108864))
  1130. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1131. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1132. if !shmRegexp.MatchString(out) {
  1133. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1134. }
  1135. }
  1136. func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *check.C) {
  1137. // ShmSize is not supported on Windows
  1138. testRequires(c, DaemonIsLinux)
  1139. config := map[string]interface{}{
  1140. "Image": "busybox",
  1141. "Cmd": "mount",
  1142. "HostConfig": map[string]interface{}{"ShmSize": 1073741824},
  1143. }
  1144. status, body, err := sockRequest("POST", "/containers/create", config)
  1145. c.Assert(err, check.IsNil)
  1146. c.Assert(status, check.Equals, http.StatusCreated)
  1147. var container types.ContainerCreateResponse
  1148. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1149. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1150. c.Assert(err, check.IsNil)
  1151. c.Assert(status, check.Equals, http.StatusOK)
  1152. var containerJSON types.ContainerJSON
  1153. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1154. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(1073741824))
  1155. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1156. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  1157. if !shmRegex.MatchString(out) {
  1158. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  1159. }
  1160. }
  1161. func (s *DockerSuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted(c *check.C) {
  1162. // Swappiness is not supported on Windows
  1163. testRequires(c, DaemonIsLinux)
  1164. config := map[string]interface{}{
  1165. "Image": "busybox",
  1166. }
  1167. status, body, err := sockRequest("POST", "/containers/create", config)
  1168. c.Assert(err, check.IsNil)
  1169. c.Assert(status, check.Equals, http.StatusCreated)
  1170. var container types.ContainerCreateResponse
  1171. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1172. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1173. c.Assert(err, check.IsNil)
  1174. c.Assert(status, check.Equals, http.StatusOK)
  1175. var containerJSON types.ContainerJSON
  1176. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1177. c.Assert(*containerJSON.HostConfig.MemorySwappiness, check.Equals, int64(-1))
  1178. }
  1179. // check validation is done daemon side and not only in cli
  1180. func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *check.C) {
  1181. // OomScoreAdj is not supported on Windows
  1182. testRequires(c, DaemonIsLinux)
  1183. config := struct {
  1184. Image string
  1185. OomScoreAdj int
  1186. }{"busybox", 1001}
  1187. name := "oomscoreadj-over"
  1188. status, b, err := sockRequest("POST", "/containers/create?name="+name, config)
  1189. c.Assert(err, check.IsNil)
  1190. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1191. expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]"
  1192. msg := getErrorMessage(c, b)
  1193. if !strings.Contains(msg, expected) {
  1194. c.Fatalf("Expected output to contain %q, got %q", expected, msg)
  1195. }
  1196. config = struct {
  1197. Image string
  1198. OomScoreAdj int
  1199. }{"busybox", -1001}
  1200. name = "oomscoreadj-low"
  1201. status, b, err = sockRequest("POST", "/containers/create?name="+name, config)
  1202. c.Assert(err, check.IsNil)
  1203. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1204. expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]"
  1205. msg = getErrorMessage(c, b)
  1206. if !strings.Contains(msg, expected) {
  1207. c.Fatalf("Expected output to contain %q, got %q", expected, msg)
  1208. }
  1209. }
  1210. // test case for #22210 where an empty container name caused panic.
  1211. func (s *DockerSuite) TestContainerAPIDeleteWithEmptyName(c *check.C) {
  1212. status, out, err := sockRequest("DELETE", "/containers/", nil)
  1213. c.Assert(err, checker.IsNil)
  1214. c.Assert(status, checker.Equals, http.StatusBadRequest)
  1215. c.Assert(string(out), checker.Contains, "No container name or ID supplied")
  1216. }
  1217. func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *check.C) {
  1218. // Problematic on Windows as Windows does not support stats
  1219. testRequires(c, DaemonIsLinux)
  1220. name := "testing-network-disabled"
  1221. config := map[string]interface{}{
  1222. "Image": "busybox",
  1223. "Cmd": []string{"top"},
  1224. "NetworkDisabled": true,
  1225. }
  1226. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  1227. c.Assert(err, checker.IsNil)
  1228. c.Assert(status, checker.Equals, http.StatusCreated)
  1229. status, _, err = sockRequest("POST", "/containers/"+name+"/start", nil)
  1230. c.Assert(err, checker.IsNil)
  1231. c.Assert(status, checker.Equals, http.StatusNoContent)
  1232. c.Assert(waitRun(name), check.IsNil)
  1233. type b struct {
  1234. status int
  1235. body []byte
  1236. err error
  1237. }
  1238. bc := make(chan b, 1)
  1239. go func() {
  1240. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  1241. bc <- b{status, body, err}
  1242. }()
  1243. // allow some time to stream the stats from the container
  1244. time.Sleep(4 * time.Second)
  1245. dockerCmd(c, "rm", "-f", name)
  1246. // collect the results from the stats stream or timeout and fail
  1247. // if the stream was not disconnected.
  1248. select {
  1249. case <-time.After(2 * time.Second):
  1250. c.Fatal("stream was not closed after container was removed")
  1251. case sr := <-bc:
  1252. c.Assert(sr.err, checker.IsNil)
  1253. c.Assert(sr.status, checker.Equals, http.StatusOK)
  1254. // decode only one object from the stream
  1255. var s *types.Stats
  1256. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  1257. c.Assert(dec.Decode(&s), checker.IsNil)
  1258. }
  1259. }
  1260. func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *check.C) {
  1261. type m mounttypes.Mount
  1262. type hc struct{ Mounts []m }
  1263. type cfg struct {
  1264. Image string
  1265. HostConfig hc
  1266. }
  1267. type testCase struct {
  1268. config cfg
  1269. status int
  1270. msg string
  1271. }
  1272. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1273. destPath := prefix + slash + "foo"
  1274. notExistPath := prefix + slash + "notexist"
  1275. cases := []testCase{
  1276. {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "notreal", Target: destPath}}}}, http.StatusBadRequest, "mount type unknown"},
  1277. {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "bind"}}}}, http.StatusBadRequest, "Target must not be empty"},
  1278. {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "bind", Target: destPath}}}}, http.StatusBadRequest, "Source must not be empty"},
  1279. {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "bind", Source: notExistPath, Target: destPath}}}}, http.StatusBadRequest, "bind source path does not exist"},
  1280. {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "volume"}}}}, http.StatusBadRequest, "Target must not be empty"},
  1281. {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "volume", Source: "hello", Target: destPath}}}}, http.StatusCreated, ""},
  1282. {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "volume", Source: "hello2", Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{DriverConfig: &mounttypes.Driver{Name: "local"}}}}}}, http.StatusCreated, ""},
  1283. }
  1284. if SameHostDaemon.Condition() {
  1285. tmpDir, err := ioutils.TempDir("", "test-mounts-api")
  1286. c.Assert(err, checker.IsNil)
  1287. defer os.RemoveAll(tmpDir)
  1288. cases = append(cases, []testCase{
  1289. {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "bind", Source: tmpDir, Target: destPath}}}}, http.StatusCreated, ""},
  1290. {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "bind", Source: tmpDir, Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{}}}}}, http.StatusBadRequest, "VolumeOptions must not be specified"},
  1291. }...)
  1292. }
  1293. if DaemonIsLinux.Condition() {
  1294. cases = append(cases, []testCase{
  1295. {cfg{Image: "busybox", HostConfig: hc{Mounts: []m{{Type: "volume", Source: "hello3", Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{DriverConfig: &mounttypes.Driver{Name: "local", Options: map[string]string{"o": "size=1"}}}}}}}, http.StatusCreated, ""},
  1296. }...)
  1297. }
  1298. for i, x := range cases {
  1299. c.Logf("case %d", i)
  1300. status, b, err := sockRequest("POST", "/containers/create", x.config)
  1301. c.Assert(err, checker.IsNil)
  1302. c.Assert(status, checker.Equals, x.status, check.Commentf("%s\n%v", string(b), cases[i].config))
  1303. if len(x.msg) > 0 {
  1304. c.Assert(string(b), checker.Contains, x.msg, check.Commentf("%v", cases[i].config))
  1305. }
  1306. }
  1307. }
  1308. func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *check.C) {
  1309. testRequires(c, NotUserNamespace, SameHostDaemon)
  1310. // also with data in the host side
  1311. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1312. destPath := prefix + slash + "foo"
  1313. tmpDir, err := ioutil.TempDir("", "test-mounts-api-bind")
  1314. c.Assert(err, checker.IsNil)
  1315. defer os.RemoveAll(tmpDir)
  1316. err = ioutil.WriteFile(filepath.Join(tmpDir, "bar"), []byte("hello"), 666)
  1317. c.Assert(err, checker.IsNil)
  1318. data := map[string]interface{}{
  1319. "Image": "busybox",
  1320. "Cmd": []string{"/bin/sh", "-c", "cat /foo/bar"},
  1321. "HostConfig": map[string]interface{}{"Mounts": []map[string]interface{}{{"Type": "bind", "Source": tmpDir, "Target": destPath}}},
  1322. }
  1323. status, resp, err := sockRequest("POST", "/containers/create?name=test", data)
  1324. c.Assert(err, checker.IsNil, check.Commentf(string(resp)))
  1325. c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(resp)))
  1326. out, _ := dockerCmd(c, "start", "-a", "test")
  1327. c.Assert(out, checker.Equals, "hello")
  1328. }
  1329. // Test Mounts comes out as expected for the MountPoint
  1330. func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *check.C) {
  1331. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1332. destPath := prefix + slash + "foo"
  1333. var (
  1334. err error
  1335. testImg string
  1336. )
  1337. if daemonPlatform != "windows" {
  1338. testImg, err = buildImage("test-mount-config", `
  1339. FROM busybox
  1340. RUN mkdir `+destPath+` && touch `+destPath+slash+`bar
  1341. CMD cat `+destPath+slash+`bar
  1342. `, true)
  1343. } else {
  1344. testImg = "busybox"
  1345. }
  1346. c.Assert(err, checker.IsNil)
  1347. type testCase struct {
  1348. cfg mounttypes.Mount
  1349. expected types.MountPoint
  1350. }
  1351. cases := []testCase{
  1352. // use literal strings here for `Type` instead of the defined constants in the volume package to keep this honest
  1353. // Validation of the actual `Mount` struct is done in another test is not needed here
  1354. {mounttypes.Mount{Type: "volume", Target: destPath}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1355. {mounttypes.Mount{Type: "volume", Target: destPath + slash}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1356. {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test1"}, types.MountPoint{Type: "volume", Name: "test1", RW: true, Destination: destPath}},
  1357. {mounttypes.Mount{Type: "volume", Target: destPath, ReadOnly: true, Source: "test2"}, types.MountPoint{Type: "volume", Name: "test2", RW: false, Destination: destPath}},
  1358. {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test3", VolumeOptions: &mounttypes.VolumeOptions{DriverConfig: &mounttypes.Driver{Name: volume.DefaultDriverName}}}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", Name: "test3", RW: true, Destination: destPath}},
  1359. }
  1360. if SameHostDaemon.Condition() {
  1361. // setup temp dir for testing binds
  1362. tmpDir1, err := ioutil.TempDir("", "test-mounts-api-1")
  1363. c.Assert(err, checker.IsNil)
  1364. defer os.RemoveAll(tmpDir1)
  1365. cases = append(cases, []testCase{
  1366. {mounttypes.Mount{Type: "bind", Source: tmpDir1, Target: destPath}, types.MountPoint{Type: "bind", RW: true, Destination: destPath, Source: tmpDir1}},
  1367. {mounttypes.Mount{Type: "bind", Source: tmpDir1, Target: destPath, ReadOnly: true}, types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir1}},
  1368. }...)
  1369. // for modes only supported on Linux
  1370. if DaemonIsLinux.Condition() {
  1371. tmpDir3, err := ioutils.TempDir("", "test-mounts-api-3")
  1372. c.Assert(err, checker.IsNil)
  1373. defer os.RemoveAll(tmpDir3)
  1374. c.Assert(mount.Mount(tmpDir3, tmpDir3, "none", "bind,rw"), checker.IsNil)
  1375. c.Assert(mount.ForceMount("", tmpDir3, "none", "shared"), checker.IsNil)
  1376. cases = append(cases, []testCase{
  1377. {mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath}, types.MountPoint{Type: "bind", RW: true, Destination: destPath, Source: tmpDir3}},
  1378. {mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true}, types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir3}},
  1379. {mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true, BindOptions: &mounttypes.BindOptions{Propagation: "shared"}}, types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir3, Propagation: "shared"}},
  1380. }...)
  1381. }
  1382. }
  1383. if daemonPlatform != "windows" { // Windows does not support volume populate
  1384. cases = append(cases, []testCase{
  1385. {mounttypes.Mount{Type: "volume", Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1386. {mounttypes.Mount{Type: "volume", Target: destPath + slash, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1387. {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test4", VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Type: "volume", Name: "test4", RW: true, Destination: destPath}},
  1388. {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test5", ReadOnly: true, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Type: "volume", Name: "test5", RW: false, Destination: destPath}},
  1389. }...)
  1390. }
  1391. type wrapper struct {
  1392. containertypes.Config
  1393. HostConfig containertypes.HostConfig
  1394. }
  1395. type createResp struct {
  1396. ID string `json:"Id"`
  1397. }
  1398. for i, x := range cases {
  1399. c.Logf("case %d - config: %v", i, x.cfg)
  1400. status, data, err := sockRequest("POST", "/containers/create", wrapper{containertypes.Config{Image: testImg}, containertypes.HostConfig{Mounts: []mounttypes.Mount{x.cfg}}})
  1401. c.Assert(err, checker.IsNil, check.Commentf(string(data)))
  1402. c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(data)))
  1403. var resp createResp
  1404. err = json.Unmarshal(data, &resp)
  1405. c.Assert(err, checker.IsNil, check.Commentf(string(data)))
  1406. id := resp.ID
  1407. var mps []types.MountPoint
  1408. err = json.NewDecoder(strings.NewReader(inspectFieldJSON(c, id, "Mounts"))).Decode(&mps)
  1409. c.Assert(err, checker.IsNil)
  1410. c.Assert(mps, checker.HasLen, 1)
  1411. c.Assert(mps[0].Destination, checker.Equals, x.expected.Destination)
  1412. if len(x.expected.Source) > 0 {
  1413. c.Assert(mps[0].Source, checker.Equals, x.expected.Source)
  1414. }
  1415. if len(x.expected.Name) > 0 {
  1416. c.Assert(mps[0].Name, checker.Equals, x.expected.Name)
  1417. }
  1418. if len(x.expected.Driver) > 0 {
  1419. c.Assert(mps[0].Driver, checker.Equals, x.expected.Driver)
  1420. }
  1421. c.Assert(mps[0].RW, checker.Equals, x.expected.RW)
  1422. c.Assert(mps[0].Type, checker.Equals, x.expected.Type)
  1423. c.Assert(mps[0].Mode, checker.Equals, x.expected.Mode)
  1424. if len(x.expected.Propagation) > 0 {
  1425. c.Assert(mps[0].Propagation, checker.Equals, x.expected.Propagation)
  1426. }
  1427. out, _, err := dockerCmdWithError("start", "-a", id)
  1428. if (x.cfg.Type != "volume" || (x.cfg.VolumeOptions != nil && x.cfg.VolumeOptions.NoCopy)) && daemonPlatform != "windows" {
  1429. c.Assert(err, checker.NotNil, check.Commentf("%s\n%v", out, mps[0]))
  1430. } else {
  1431. c.Assert(err, checker.IsNil, check.Commentf("%s\n%v", out, mps[0]))
  1432. }
  1433. dockerCmd(c, "rm", "-fv", id)
  1434. if x.cfg.Type == "volume" && len(x.cfg.Source) > 0 {
  1435. // This should still exist even though we removed the container
  1436. dockerCmd(c, "volume", "inspect", mps[0].Name)
  1437. } else {
  1438. // This should be removed automatically when we removed the container
  1439. out, _, err := dockerCmdWithError("volume", "inspect", mps[0].Name)
  1440. c.Assert(err, checker.NotNil, check.Commentf(out))
  1441. }
  1442. }
  1443. }