docker_api_containers_test.go 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941
  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 types.ContainerWaitResponse
  800. c.Assert(json.Unmarshal(body, &waitres), checker.IsNil)
  801. c.Assert(waitres.StatusCode, checker.Equals, 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. name := "test-container-api-copy"
  815. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  816. postData := types.CopyConfig{
  817. Resource: "/test.txt",
  818. }
  819. status, body, err := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
  820. c.Assert(err, checker.IsNil)
  821. c.Assert(status, checker.Equals, http.StatusOK)
  822. found := false
  823. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  824. h, err := tarReader.Next()
  825. if err != nil {
  826. if err == io.EOF {
  827. break
  828. }
  829. c.Fatal(err)
  830. }
  831. if h.Name == "test.txt" {
  832. found = true
  833. break
  834. }
  835. }
  836. c.Assert(found, checker.True)
  837. }
  838. func (s *DockerSuite) TestContainerAPICopyResourcePathEmptyPr124(c *check.C) {
  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 := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
  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. name := "test-container-api-copy-resource-not-found"
  851. dockerCmd(c, "run", "--name", name, "busybox")
  852. postData := types.CopyConfig{
  853. Resource: "/notexist",
  854. }
  855. status, body, err := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
  856. c.Assert(err, checker.IsNil)
  857. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  858. c.Assert(string(body), checker.Matches, "Could not find the file /notexist in container "+name+"\n")
  859. }
  860. func (s *DockerSuite) TestContainerAPICopyContainerNotFoundPr124(c *check.C) {
  861. postData := types.CopyConfig{
  862. Resource: "/something",
  863. }
  864. status, _, err := sockRequest("POST", "/v1.23/containers/notexists/copy", postData)
  865. c.Assert(err, checker.IsNil)
  866. c.Assert(status, checker.Equals, http.StatusNotFound)
  867. }
  868. func (s *DockerSuite) TestContainerAPIDelete(c *check.C) {
  869. out, _ := runSleepingContainer(c)
  870. id := strings.TrimSpace(out)
  871. c.Assert(waitRun(id), checker.IsNil)
  872. dockerCmd(c, "stop", id)
  873. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  874. c.Assert(err, checker.IsNil)
  875. c.Assert(status, checker.Equals, http.StatusNoContent)
  876. }
  877. func (s *DockerSuite) TestContainerAPIDeleteNotExist(c *check.C) {
  878. status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
  879. c.Assert(err, checker.IsNil)
  880. c.Assert(status, checker.Equals, http.StatusNotFound)
  881. c.Assert(getErrorMessage(c, body), checker.Matches, "No such container: doesnotexist")
  882. }
  883. func (s *DockerSuite) TestContainerAPIDeleteForce(c *check.C) {
  884. out, _ := runSleepingContainer(c)
  885. id := strings.TrimSpace(out)
  886. c.Assert(waitRun(id), checker.IsNil)
  887. status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
  888. c.Assert(err, checker.IsNil)
  889. c.Assert(status, checker.Equals, http.StatusNoContent)
  890. }
  891. func (s *DockerSuite) TestContainerAPIDeleteRemoveLinks(c *check.C) {
  892. // Windows does not support links
  893. testRequires(c, DaemonIsLinux)
  894. out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top")
  895. id := strings.TrimSpace(out)
  896. c.Assert(waitRun(id), checker.IsNil)
  897. out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  898. id2 := strings.TrimSpace(out)
  899. c.Assert(waitRun(id2), checker.IsNil)
  900. links := inspectFieldJSON(c, id2, "HostConfig.Links")
  901. c.Assert(links, checker.Equals, "[\"/tlink1:/tlink2/tlink1\"]", check.Commentf("expected to have links between containers"))
  902. status, b, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
  903. c.Assert(err, check.IsNil)
  904. c.Assert(status, check.Equals, http.StatusNoContent, check.Commentf(string(b)))
  905. linksPostRm := inspectFieldJSON(c, id2, "HostConfig.Links")
  906. c.Assert(linksPostRm, checker.Equals, "null", check.Commentf("call to api deleteContainer links should have removed the specified links"))
  907. }
  908. func (s *DockerSuite) TestContainerAPIDeleteConflict(c *check.C) {
  909. out, _ := runSleepingContainer(c)
  910. id := strings.TrimSpace(out)
  911. c.Assert(waitRun(id), checker.IsNil)
  912. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  913. c.Assert(err, checker.IsNil)
  914. c.Assert(status, checker.Equals, http.StatusConflict)
  915. }
  916. func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) {
  917. testRequires(c, SameHostDaemon)
  918. vol := "/testvolume"
  919. if daemonPlatform == "windows" {
  920. vol = `c:\testvolume`
  921. }
  922. out, _ := runSleepingContainer(c, "-v", vol)
  923. id := strings.TrimSpace(out)
  924. c.Assert(waitRun(id), checker.IsNil)
  925. source, err := inspectMountSourceField(id, vol)
  926. _, err = os.Stat(source)
  927. c.Assert(err, checker.IsNil)
  928. status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
  929. c.Assert(err, checker.IsNil)
  930. c.Assert(status, checker.Equals, http.StatusNoContent)
  931. _, err = os.Stat(source)
  932. c.Assert(os.IsNotExist(err), checker.True, check.Commentf("expected to get ErrNotExist error, got %v", err))
  933. }
  934. // Regression test for https://github.com/docker/docker/issues/6231
  935. func (s *DockerSuite) TestContainerAPIChunkedEncoding(c *check.C) {
  936. conn, err := sockConn(time.Duration(10*time.Second), "")
  937. c.Assert(err, checker.IsNil)
  938. client := httputil.NewClientConn(conn, nil)
  939. defer client.Close()
  940. config := map[string]interface{}{
  941. "Image": "busybox",
  942. "Cmd": append([]string{"/bin/sh", "-c"}, sleepCommandForDaemonPlatform()...),
  943. "OpenStdin": true,
  944. }
  945. b, err := json.Marshal(config)
  946. c.Assert(err, checker.IsNil)
  947. req, err := http.NewRequest("POST", "/containers/create", bytes.NewBuffer(b))
  948. c.Assert(err, checker.IsNil)
  949. req.Header.Set("Content-Type", "application/json")
  950. // This is a cheat to make the http request do chunked encoding
  951. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  952. // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
  953. req.ContentLength = -1
  954. resp, err := client.Do(req)
  955. c.Assert(err, checker.IsNil, check.Commentf("error creating container with chunked encoding"))
  956. resp.Body.Close()
  957. c.Assert(resp.StatusCode, checker.Equals, http.StatusCreated)
  958. }
  959. func (s *DockerSuite) TestContainerAPIPostContainerStop(c *check.C) {
  960. out, _ := runSleepingContainer(c)
  961. containerID := strings.TrimSpace(out)
  962. c.Assert(waitRun(containerID), checker.IsNil)
  963. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/stop", nil)
  964. c.Assert(err, checker.IsNil)
  965. // 204 No Content is expected, not 200
  966. c.Assert(statusCode, checker.Equals, http.StatusNoContent)
  967. c.Assert(waitInspect(containerID, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil)
  968. }
  969. // #14170
  970. func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *check.C) {
  971. config := struct {
  972. Image string
  973. Entrypoint string
  974. Cmd []string
  975. }{"busybox", "echo", []string{"hello", "world"}}
  976. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  977. c.Assert(err, checker.IsNil)
  978. out, _ := dockerCmd(c, "start", "-a", "echotest")
  979. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  980. config2 := struct {
  981. Image string
  982. Entrypoint []string
  983. Cmd []string
  984. }{"busybox", []string{"echo"}, []string{"hello", "world"}}
  985. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  986. c.Assert(err, checker.IsNil)
  987. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  988. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  989. }
  990. // #14170
  991. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) {
  992. config := struct {
  993. Image string
  994. Entrypoint string
  995. Cmd string
  996. }{"busybox", "echo", "hello world"}
  997. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  998. c.Assert(err, checker.IsNil)
  999. out, _ := dockerCmd(c, "start", "-a", "echotest")
  1000. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1001. config2 := struct {
  1002. Image string
  1003. Cmd []string
  1004. }{"busybox", []string{"echo", "hello", "world"}}
  1005. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  1006. c.Assert(err, checker.IsNil)
  1007. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  1008. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1009. }
  1010. // regression #14318
  1011. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *check.C) {
  1012. // Windows doesn't support CapAdd/CapDrop
  1013. testRequires(c, DaemonIsLinux)
  1014. config := struct {
  1015. Image string
  1016. CapAdd string
  1017. CapDrop string
  1018. }{"busybox", "NET_ADMIN", "SYS_ADMIN"}
  1019. status, _, err := sockRequest("POST", "/containers/create?name=capaddtest0", config)
  1020. c.Assert(err, checker.IsNil)
  1021. c.Assert(status, checker.Equals, http.StatusCreated)
  1022. config2 := struct {
  1023. Image string
  1024. CapAdd []string
  1025. CapDrop []string
  1026. }{"busybox", []string{"NET_ADMIN", "SYS_ADMIN"}, []string{"SETGID"}}
  1027. status, _, err = sockRequest("POST", "/containers/create?name=capaddtest1", config2)
  1028. c.Assert(err, checker.IsNil)
  1029. c.Assert(status, checker.Equals, http.StatusCreated)
  1030. }
  1031. // #14915
  1032. func (s *DockerSuite) TestContainerAPICreateNoHostConfig118(c *check.C) {
  1033. config := struct {
  1034. Image string
  1035. }{"busybox"}
  1036. status, _, err := sockRequest("POST", "/v1.18/containers/create", config)
  1037. c.Assert(err, checker.IsNil)
  1038. c.Assert(status, checker.Equals, http.StatusCreated)
  1039. }
  1040. // Ensure an error occurs when you have a container read-only rootfs but you
  1041. // extract an archive to a symlink in a writable volume which points to a
  1042. // directory outside of the volume.
  1043. func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(c *check.C) {
  1044. // Windows does not support read-only rootfs
  1045. // Requires local volume mount bind.
  1046. // --read-only + userns has remount issues
  1047. testRequires(c, SameHostDaemon, NotUserNamespace, DaemonIsLinux)
  1048. testVol := getTestDir(c, "test-put-container-archive-err-symlink-in-volume-to-read-only-rootfs-")
  1049. defer os.RemoveAll(testVol)
  1050. makeTestContentInDir(c, testVol)
  1051. cID := makeTestContainer(c, testContainerOptions{
  1052. readOnly: true,
  1053. volumes: defaultVolumes(testVol), // Our bind mount is at /vol2
  1054. })
  1055. defer deleteContainer(cID)
  1056. // Attempt to extract to a symlink in the volume which points to a
  1057. // directory outside the volume. This should cause an error because the
  1058. // rootfs is read-only.
  1059. query := make(url.Values, 1)
  1060. query.Set("path", "/vol2/symlinkToAbsDir")
  1061. urlPath := fmt.Sprintf("/v1.20/containers/%s/archive?%s", cID, query.Encode())
  1062. statusCode, body, err := sockRequest("PUT", urlPath, nil)
  1063. c.Assert(err, checker.IsNil)
  1064. if !isCpCannotCopyReadOnly(fmt.Errorf(string(body))) {
  1065. c.Fatalf("expected ErrContainerRootfsReadonly error, but got %d: %s", statusCode, string(body))
  1066. }
  1067. }
  1068. func (s *DockerSuite) TestContainerAPIGetContainersJSONEmpty(c *check.C) {
  1069. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  1070. c.Assert(err, checker.IsNil)
  1071. c.Assert(status, checker.Equals, http.StatusOK)
  1072. c.Assert(string(body), checker.Equals, "[]\n")
  1073. }
  1074. func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) {
  1075. // Not supported on Windows
  1076. testRequires(c, DaemonIsLinux)
  1077. c1 := struct {
  1078. Image string
  1079. CpusetCpus string
  1080. }{"busybox", "1-42,,"}
  1081. name := "wrong-cpuset-cpus"
  1082. status, body, err := sockRequest("POST", "/containers/create?name="+name, c1)
  1083. c.Assert(err, checker.IsNil)
  1084. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  1085. expected := "Invalid value 1-42,, for cpuset cpus"
  1086. c.Assert(getErrorMessage(c, body), checker.Equals, expected)
  1087. c2 := struct {
  1088. Image string
  1089. CpusetMems string
  1090. }{"busybox", "42-3,1--"}
  1091. name = "wrong-cpuset-mems"
  1092. status, body, err = sockRequest("POST", "/containers/create?name="+name, c2)
  1093. c.Assert(err, checker.IsNil)
  1094. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  1095. expected = "Invalid value 42-3,1-- for cpuset mems"
  1096. c.Assert(getErrorMessage(c, body), checker.Equals, expected)
  1097. }
  1098. func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) {
  1099. // ShmSize is not supported on Windows
  1100. testRequires(c, DaemonIsLinux)
  1101. config := map[string]interface{}{
  1102. "Image": "busybox",
  1103. "HostConfig": map[string]interface{}{"ShmSize": -1},
  1104. }
  1105. status, body, err := sockRequest("POST", "/containers/create", config)
  1106. c.Assert(err, check.IsNil)
  1107. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1108. c.Assert(getErrorMessage(c, body), checker.Contains, "SHM size can not be less than 0")
  1109. }
  1110. func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check.C) {
  1111. // ShmSize is not supported on Windows
  1112. testRequires(c, DaemonIsLinux)
  1113. var defaultSHMSize int64 = 67108864
  1114. config := map[string]interface{}{
  1115. "Image": "busybox",
  1116. "Cmd": "mount",
  1117. }
  1118. status, body, err := sockRequest("POST", "/containers/create", config)
  1119. c.Assert(err, check.IsNil)
  1120. c.Assert(status, check.Equals, http.StatusCreated)
  1121. var container containertypes.ContainerCreateCreatedBody
  1122. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1123. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1124. c.Assert(err, check.IsNil)
  1125. c.Assert(status, check.Equals, http.StatusOK)
  1126. var containerJSON types.ContainerJSON
  1127. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1128. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, defaultSHMSize)
  1129. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1130. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1131. if !shmRegexp.MatchString(out) {
  1132. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1133. }
  1134. }
  1135. func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *check.C) {
  1136. // ShmSize is not supported on Windows
  1137. testRequires(c, DaemonIsLinux)
  1138. config := map[string]interface{}{
  1139. "Image": "busybox",
  1140. "HostConfig": map[string]interface{}{},
  1141. "Cmd": "mount",
  1142. }
  1143. status, body, err := sockRequest("POST", "/containers/create", config)
  1144. c.Assert(err, check.IsNil)
  1145. c.Assert(status, check.Equals, http.StatusCreated)
  1146. var container containertypes.ContainerCreateCreatedBody
  1147. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1148. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1149. c.Assert(err, check.IsNil)
  1150. c.Assert(status, check.Equals, http.StatusOK)
  1151. var containerJSON types.ContainerJSON
  1152. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1153. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(67108864))
  1154. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1155. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1156. if !shmRegexp.MatchString(out) {
  1157. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1158. }
  1159. }
  1160. func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *check.C) {
  1161. // ShmSize is not supported on Windows
  1162. testRequires(c, DaemonIsLinux)
  1163. config := map[string]interface{}{
  1164. "Image": "busybox",
  1165. "Cmd": "mount",
  1166. "HostConfig": map[string]interface{}{"ShmSize": 1073741824},
  1167. }
  1168. status, body, err := sockRequest("POST", "/containers/create", config)
  1169. c.Assert(err, check.IsNil)
  1170. c.Assert(status, check.Equals, http.StatusCreated)
  1171. var container containertypes.ContainerCreateCreatedBody
  1172. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1173. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1174. c.Assert(err, check.IsNil)
  1175. c.Assert(status, check.Equals, http.StatusOK)
  1176. var containerJSON types.ContainerJSON
  1177. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1178. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(1073741824))
  1179. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1180. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  1181. if !shmRegex.MatchString(out) {
  1182. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  1183. }
  1184. }
  1185. func (s *DockerSuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted(c *check.C) {
  1186. // Swappiness is not supported on Windows
  1187. testRequires(c, DaemonIsLinux)
  1188. config := map[string]interface{}{
  1189. "Image": "busybox",
  1190. }
  1191. status, body, err := sockRequest("POST", "/containers/create", config)
  1192. c.Assert(err, check.IsNil)
  1193. c.Assert(status, check.Equals, http.StatusCreated)
  1194. var container containertypes.ContainerCreateCreatedBody
  1195. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1196. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1197. c.Assert(err, check.IsNil)
  1198. c.Assert(status, check.Equals, http.StatusOK)
  1199. var containerJSON types.ContainerJSON
  1200. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1201. c.Assert(*containerJSON.HostConfig.MemorySwappiness, check.Equals, int64(-1))
  1202. }
  1203. // check validation is done daemon side and not only in cli
  1204. func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *check.C) {
  1205. // OomScoreAdj is not supported on Windows
  1206. testRequires(c, DaemonIsLinux)
  1207. config := struct {
  1208. Image string
  1209. OomScoreAdj int
  1210. }{"busybox", 1001}
  1211. name := "oomscoreadj-over"
  1212. status, b, err := sockRequest("POST", "/containers/create?name="+name, config)
  1213. c.Assert(err, check.IsNil)
  1214. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1215. expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]"
  1216. msg := getErrorMessage(c, b)
  1217. if !strings.Contains(msg, expected) {
  1218. c.Fatalf("Expected output to contain %q, got %q", expected, msg)
  1219. }
  1220. config = struct {
  1221. Image string
  1222. OomScoreAdj int
  1223. }{"busybox", -1001}
  1224. name = "oomscoreadj-low"
  1225. status, b, err = sockRequest("POST", "/containers/create?name="+name, config)
  1226. c.Assert(err, check.IsNil)
  1227. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1228. expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]"
  1229. msg = getErrorMessage(c, b)
  1230. if !strings.Contains(msg, expected) {
  1231. c.Fatalf("Expected output to contain %q, got %q", expected, msg)
  1232. }
  1233. }
  1234. // test case for #22210 where an empty container name caused panic.
  1235. func (s *DockerSuite) TestContainerAPIDeleteWithEmptyName(c *check.C) {
  1236. status, out, err := sockRequest("DELETE", "/containers/", nil)
  1237. c.Assert(err, checker.IsNil)
  1238. c.Assert(status, checker.Equals, http.StatusBadRequest)
  1239. c.Assert(string(out), checker.Contains, "No container name or ID supplied")
  1240. }
  1241. func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *check.C) {
  1242. // Problematic on Windows as Windows does not support stats
  1243. testRequires(c, DaemonIsLinux)
  1244. name := "testing-network-disabled"
  1245. config := map[string]interface{}{
  1246. "Image": "busybox",
  1247. "Cmd": []string{"top"},
  1248. "NetworkDisabled": true,
  1249. }
  1250. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  1251. c.Assert(err, checker.IsNil)
  1252. c.Assert(status, checker.Equals, http.StatusCreated)
  1253. status, _, err = sockRequest("POST", "/containers/"+name+"/start", nil)
  1254. c.Assert(err, checker.IsNil)
  1255. c.Assert(status, checker.Equals, http.StatusNoContent)
  1256. c.Assert(waitRun(name), check.IsNil)
  1257. type b struct {
  1258. status int
  1259. body []byte
  1260. err error
  1261. }
  1262. bc := make(chan b, 1)
  1263. go func() {
  1264. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  1265. bc <- b{status, body, err}
  1266. }()
  1267. // allow some time to stream the stats from the container
  1268. time.Sleep(4 * time.Second)
  1269. dockerCmd(c, "rm", "-f", name)
  1270. // collect the results from the stats stream or timeout and fail
  1271. // if the stream was not disconnected.
  1272. select {
  1273. case <-time.After(2 * time.Second):
  1274. c.Fatal("stream was not closed after container was removed")
  1275. case sr := <-bc:
  1276. c.Assert(sr.err, checker.IsNil)
  1277. c.Assert(sr.status, checker.Equals, http.StatusOK)
  1278. // decode only one object from the stream
  1279. var s *types.Stats
  1280. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  1281. c.Assert(dec.Decode(&s), checker.IsNil)
  1282. }
  1283. }
  1284. func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *check.C) {
  1285. type m mounttypes.Mount
  1286. type hc struct{ Mounts []m }
  1287. type cfg struct {
  1288. Image string
  1289. HostConfig hc
  1290. }
  1291. type testCase struct {
  1292. config cfg
  1293. status int
  1294. msg string
  1295. }
  1296. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1297. destPath := prefix + slash + "foo"
  1298. notExistPath := prefix + slash + "notexist"
  1299. cases := []testCase{
  1300. {
  1301. config: cfg{
  1302. Image: "busybox",
  1303. HostConfig: hc{
  1304. Mounts: []m{{
  1305. Type: "notreal",
  1306. Target: destPath}}}},
  1307. status: http.StatusBadRequest,
  1308. msg: "mount type unknown",
  1309. },
  1310. {
  1311. config: cfg{
  1312. Image: "busybox",
  1313. HostConfig: hc{
  1314. Mounts: []m{{
  1315. Type: "bind"}}}},
  1316. status: http.StatusBadRequest,
  1317. msg: "Target must not be empty",
  1318. },
  1319. {
  1320. config: cfg{
  1321. Image: "busybox",
  1322. HostConfig: hc{
  1323. Mounts: []m{{
  1324. Type: "bind",
  1325. Target: destPath}}}},
  1326. status: http.StatusBadRequest,
  1327. msg: "Source must not be empty",
  1328. },
  1329. {
  1330. config: cfg{
  1331. Image: "busybox",
  1332. HostConfig: hc{
  1333. Mounts: []m{{
  1334. Type: "bind",
  1335. Source: notExistPath,
  1336. Target: destPath}}}},
  1337. status: http.StatusBadRequest,
  1338. msg: "bind source path does not exist",
  1339. },
  1340. {
  1341. config: cfg{
  1342. Image: "busybox",
  1343. HostConfig: hc{
  1344. Mounts: []m{{
  1345. Type: "volume"}}}},
  1346. status: http.StatusBadRequest,
  1347. msg: "Target must not be empty",
  1348. },
  1349. {
  1350. config: cfg{
  1351. Image: "busybox",
  1352. HostConfig: hc{
  1353. Mounts: []m{{
  1354. Type: "volume",
  1355. Source: "hello",
  1356. Target: destPath}}}},
  1357. status: http.StatusCreated,
  1358. msg: "",
  1359. },
  1360. {
  1361. config: cfg{
  1362. Image: "busybox",
  1363. HostConfig: hc{
  1364. Mounts: []m{{
  1365. Type: "volume",
  1366. Source: "hello2",
  1367. Target: destPath,
  1368. VolumeOptions: &mounttypes.VolumeOptions{
  1369. DriverConfig: &mounttypes.Driver{
  1370. Name: "local"}}}}}},
  1371. status: http.StatusCreated,
  1372. msg: "",
  1373. },
  1374. }
  1375. if SameHostDaemon.Condition() {
  1376. tmpDir, err := ioutils.TempDir("", "test-mounts-api")
  1377. c.Assert(err, checker.IsNil)
  1378. defer os.RemoveAll(tmpDir)
  1379. cases = append(cases, []testCase{
  1380. {
  1381. config: cfg{
  1382. Image: "busybox",
  1383. HostConfig: hc{
  1384. Mounts: []m{{
  1385. Type: "bind",
  1386. Source: tmpDir,
  1387. Target: destPath}}}},
  1388. status: http.StatusCreated,
  1389. msg: "",
  1390. },
  1391. {
  1392. config: cfg{
  1393. Image: "busybox",
  1394. HostConfig: hc{
  1395. Mounts: []m{{
  1396. Type: "bind",
  1397. Source: tmpDir,
  1398. Target: destPath,
  1399. VolumeOptions: &mounttypes.VolumeOptions{}}}}},
  1400. status: http.StatusBadRequest,
  1401. msg: "VolumeOptions must not be specified",
  1402. },
  1403. }...)
  1404. }
  1405. if DaemonIsLinux.Condition() {
  1406. cases = append(cases, []testCase{
  1407. {
  1408. config: cfg{
  1409. Image: "busybox",
  1410. HostConfig: hc{
  1411. Mounts: []m{{
  1412. Type: "volume",
  1413. Source: "hello3",
  1414. Target: destPath,
  1415. VolumeOptions: &mounttypes.VolumeOptions{
  1416. DriverConfig: &mounttypes.Driver{
  1417. Name: "local",
  1418. Options: map[string]string{"o": "size=1"}}}}}}},
  1419. status: http.StatusCreated,
  1420. msg: "",
  1421. },
  1422. {
  1423. config: cfg{
  1424. Image: "busybox",
  1425. HostConfig: hc{
  1426. Mounts: []m{{
  1427. Type: "tmpfs",
  1428. Target: destPath}}}},
  1429. status: http.StatusCreated,
  1430. msg: "",
  1431. },
  1432. {
  1433. config: cfg{
  1434. Image: "busybox",
  1435. HostConfig: hc{
  1436. Mounts: []m{{
  1437. Type: "tmpfs",
  1438. Target: destPath,
  1439. TmpfsOptions: &mounttypes.TmpfsOptions{
  1440. SizeBytes: 4096 * 1024,
  1441. Mode: 0700,
  1442. }}}}},
  1443. status: http.StatusCreated,
  1444. msg: "",
  1445. },
  1446. {
  1447. config: cfg{
  1448. Image: "busybox",
  1449. HostConfig: hc{
  1450. Mounts: []m{{
  1451. Type: "tmpfs",
  1452. Source: "/shouldnotbespecified",
  1453. Target: destPath}}}},
  1454. status: http.StatusBadRequest,
  1455. msg: "Source must not be specified",
  1456. },
  1457. }...)
  1458. }
  1459. for i, x := range cases {
  1460. c.Logf("case %d", i)
  1461. status, b, err := sockRequest("POST", "/containers/create", x.config)
  1462. c.Assert(err, checker.IsNil)
  1463. c.Assert(status, checker.Equals, x.status, check.Commentf("%s\n%v", string(b), cases[i].config))
  1464. if len(x.msg) > 0 {
  1465. c.Assert(string(b), checker.Contains, x.msg, check.Commentf("%v", cases[i].config))
  1466. }
  1467. }
  1468. }
  1469. func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *check.C) {
  1470. testRequires(c, NotUserNamespace, SameHostDaemon)
  1471. // also with data in the host side
  1472. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1473. destPath := prefix + slash + "foo"
  1474. tmpDir, err := ioutil.TempDir("", "test-mounts-api-bind")
  1475. c.Assert(err, checker.IsNil)
  1476. defer os.RemoveAll(tmpDir)
  1477. err = ioutil.WriteFile(filepath.Join(tmpDir, "bar"), []byte("hello"), 666)
  1478. c.Assert(err, checker.IsNil)
  1479. data := map[string]interface{}{
  1480. "Image": "busybox",
  1481. "Cmd": []string{"/bin/sh", "-c", "cat /foo/bar"},
  1482. "HostConfig": map[string]interface{}{"Mounts": []map[string]interface{}{{"Type": "bind", "Source": tmpDir, "Target": destPath}}},
  1483. }
  1484. status, resp, err := sockRequest("POST", "/containers/create?name=test", data)
  1485. c.Assert(err, checker.IsNil, check.Commentf(string(resp)))
  1486. c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(resp)))
  1487. out, _ := dockerCmd(c, "start", "-a", "test")
  1488. c.Assert(out, checker.Equals, "hello")
  1489. }
  1490. // Test Mounts comes out as expected for the MountPoint
  1491. func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *check.C) {
  1492. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1493. destPath := prefix + slash + "foo"
  1494. var (
  1495. err error
  1496. testImg string
  1497. )
  1498. if daemonPlatform != "windows" {
  1499. testImg, err = buildImage("test-mount-config", `
  1500. FROM busybox
  1501. RUN mkdir `+destPath+` && touch `+destPath+slash+`bar
  1502. CMD cat `+destPath+slash+`bar
  1503. `, true)
  1504. } else {
  1505. testImg = "busybox"
  1506. }
  1507. c.Assert(err, checker.IsNil)
  1508. type testCase struct {
  1509. cfg mounttypes.Mount
  1510. expected types.MountPoint
  1511. }
  1512. cases := []testCase{
  1513. // use literal strings here for `Type` instead of the defined constants in the volume package to keep this honest
  1514. // Validation of the actual `Mount` struct is done in another test is not needed here
  1515. {mounttypes.Mount{Type: "volume", Target: destPath}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1516. {mounttypes.Mount{Type: "volume", Target: destPath + slash}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1517. {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test1"}, types.MountPoint{Type: "volume", Name: "test1", RW: true, Destination: destPath}},
  1518. {mounttypes.Mount{Type: "volume", Target: destPath, ReadOnly: true, Source: "test2"}, types.MountPoint{Type: "volume", Name: "test2", RW: false, Destination: destPath}},
  1519. {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}},
  1520. }
  1521. if SameHostDaemon.Condition() {
  1522. // setup temp dir for testing binds
  1523. tmpDir1, err := ioutil.TempDir("", "test-mounts-api-1")
  1524. c.Assert(err, checker.IsNil)
  1525. defer os.RemoveAll(tmpDir1)
  1526. cases = append(cases, []testCase{
  1527. {mounttypes.Mount{Type: "bind", Source: tmpDir1, Target: destPath}, types.MountPoint{Type: "bind", RW: true, Destination: destPath, Source: tmpDir1}},
  1528. {mounttypes.Mount{Type: "bind", Source: tmpDir1, Target: destPath, ReadOnly: true}, types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir1}},
  1529. }...)
  1530. // for modes only supported on Linux
  1531. if DaemonIsLinux.Condition() {
  1532. tmpDir3, err := ioutils.TempDir("", "test-mounts-api-3")
  1533. c.Assert(err, checker.IsNil)
  1534. defer os.RemoveAll(tmpDir3)
  1535. c.Assert(mount.Mount(tmpDir3, tmpDir3, "none", "bind,rw"), checker.IsNil)
  1536. c.Assert(mount.ForceMount("", tmpDir3, "none", "shared"), checker.IsNil)
  1537. cases = append(cases, []testCase{
  1538. {mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath}, types.MountPoint{Type: "bind", RW: true, Destination: destPath, Source: tmpDir3}},
  1539. {mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true}, types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir3}},
  1540. {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"}},
  1541. }...)
  1542. }
  1543. }
  1544. if daemonPlatform != "windows" { // Windows does not support volume populate
  1545. cases = append(cases, []testCase{
  1546. {mounttypes.Mount{Type: "volume", Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1547. {mounttypes.Mount{Type: "volume", Target: destPath + slash, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1548. {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test4", VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Type: "volume", Name: "test4", RW: true, Destination: destPath}},
  1549. {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}},
  1550. }...)
  1551. }
  1552. type wrapper struct {
  1553. containertypes.Config
  1554. HostConfig containertypes.HostConfig
  1555. }
  1556. type createResp struct {
  1557. ID string `json:"Id"`
  1558. }
  1559. for i, x := range cases {
  1560. c.Logf("case %d - config: %v", i, x.cfg)
  1561. status, data, err := sockRequest("POST", "/containers/create", wrapper{containertypes.Config{Image: testImg}, containertypes.HostConfig{Mounts: []mounttypes.Mount{x.cfg}}})
  1562. c.Assert(err, checker.IsNil, check.Commentf(string(data)))
  1563. c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(data)))
  1564. var resp createResp
  1565. err = json.Unmarshal(data, &resp)
  1566. c.Assert(err, checker.IsNil, check.Commentf(string(data)))
  1567. id := resp.ID
  1568. var mps []types.MountPoint
  1569. err = json.NewDecoder(strings.NewReader(inspectFieldJSON(c, id, "Mounts"))).Decode(&mps)
  1570. c.Assert(err, checker.IsNil)
  1571. c.Assert(mps, checker.HasLen, 1)
  1572. c.Assert(mps[0].Destination, checker.Equals, x.expected.Destination)
  1573. if len(x.expected.Source) > 0 {
  1574. c.Assert(mps[0].Source, checker.Equals, x.expected.Source)
  1575. }
  1576. if len(x.expected.Name) > 0 {
  1577. c.Assert(mps[0].Name, checker.Equals, x.expected.Name)
  1578. }
  1579. if len(x.expected.Driver) > 0 {
  1580. c.Assert(mps[0].Driver, checker.Equals, x.expected.Driver)
  1581. }
  1582. c.Assert(mps[0].RW, checker.Equals, x.expected.RW)
  1583. c.Assert(mps[0].Type, checker.Equals, x.expected.Type)
  1584. c.Assert(mps[0].Mode, checker.Equals, x.expected.Mode)
  1585. if len(x.expected.Propagation) > 0 {
  1586. c.Assert(mps[0].Propagation, checker.Equals, x.expected.Propagation)
  1587. }
  1588. out, _, err := dockerCmdWithError("start", "-a", id)
  1589. if (x.cfg.Type != "volume" || (x.cfg.VolumeOptions != nil && x.cfg.VolumeOptions.NoCopy)) && daemonPlatform != "windows" {
  1590. c.Assert(err, checker.NotNil, check.Commentf("%s\n%v", out, mps[0]))
  1591. } else {
  1592. c.Assert(err, checker.IsNil, check.Commentf("%s\n%v", out, mps[0]))
  1593. }
  1594. dockerCmd(c, "rm", "-fv", id)
  1595. if x.cfg.Type == "volume" && len(x.cfg.Source) > 0 {
  1596. // This should still exist even though we removed the container
  1597. dockerCmd(c, "volume", "inspect", mps[0].Name)
  1598. } else {
  1599. // This should be removed automatically when we removed the container
  1600. out, _, err := dockerCmdWithError("volume", "inspect", mps[0].Name)
  1601. c.Assert(err, checker.NotNil, check.Commentf(out))
  1602. }
  1603. }
  1604. }
  1605. func (s *DockerSuite) TestContainersAPICreateMountsTmpfs(c *check.C) {
  1606. testRequires(c, DaemonIsLinux)
  1607. type testCase struct {
  1608. cfg map[string]interface{}
  1609. expectedOptions []string
  1610. }
  1611. target := "/foo"
  1612. cases := []testCase{
  1613. {
  1614. cfg: map[string]interface{}{
  1615. "Type": "tmpfs",
  1616. "Target": target},
  1617. expectedOptions: []string{"rw", "nosuid", "nodev", "noexec", "relatime"},
  1618. },
  1619. {
  1620. cfg: map[string]interface{}{
  1621. "Type": "tmpfs",
  1622. "Target": target,
  1623. "TmpfsOptions": map[string]interface{}{
  1624. "SizeBytes": 4096 * 1024, "Mode": 0700}},
  1625. expectedOptions: []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=4096k", "mode=700"},
  1626. },
  1627. }
  1628. for i, x := range cases {
  1629. cName := fmt.Sprintf("test-tmpfs-%d", i)
  1630. data := map[string]interface{}{
  1631. "Image": "busybox",
  1632. "Cmd": []string{"/bin/sh", "-c",
  1633. fmt.Sprintf("mount | grep 'tmpfs on %s'", target)},
  1634. "HostConfig": map[string]interface{}{"Mounts": []map[string]interface{}{x.cfg}},
  1635. }
  1636. status, resp, err := sockRequest("POST", "/containers/create?name="+cName, data)
  1637. c.Assert(err, checker.IsNil, check.Commentf(string(resp)))
  1638. c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf(string(resp)))
  1639. out, _ := dockerCmd(c, "start", "-a", cName)
  1640. for _, option := range x.expectedOptions {
  1641. c.Assert(out, checker.Contains, option)
  1642. }
  1643. }
  1644. }