docker_api_containers_test.go 64 KB

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