docker_api_containers_test.go 65 KB

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