docker_api_containers_test.go 64 KB

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