docker_api_containers_test.go 66 KB

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