docker_api_containers_test.go 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526
  1. package main
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/http/httputil"
  10. "net/url"
  11. "os"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/docker/docker/api/types"
  17. "github.com/docker/docker/pkg/integration"
  18. "github.com/docker/docker/pkg/integration/checker"
  19. "github.com/docker/docker/pkg/stringid"
  20. "github.com/docker/docker/runconfig"
  21. "github.com/go-check/check"
  22. )
  23. func (s *DockerSuite) TestContainerApiGetAll(c *check.C) {
  24. testRequires(c, DaemonIsLinux)
  25. startCount, err := getContainerCount()
  26. c.Assert(err, checker.IsNil, check.Commentf("Cannot query container count"))
  27. name := "getall"
  28. dockerCmd(c, "run", "--name", name, "busybox", "true")
  29. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  30. c.Assert(err, checker.IsNil)
  31. c.Assert(status, checker.Equals, http.StatusOK)
  32. var inspectJSON []struct {
  33. Names []string
  34. }
  35. err = json.Unmarshal(body, &inspectJSON)
  36. c.Assert(err, checker.IsNil, check.Commentf("unable to unmarshal response body"))
  37. c.Assert(inspectJSON, checker.HasLen, startCount+1)
  38. actual := inspectJSON[0].Names[0]
  39. c.Assert(actual, checker.Equals, "/"+name)
  40. }
  41. // regression test for empty json field being omitted #13691
  42. func (s *DockerSuite) TestContainerApiGetJSONNoFieldsOmitted(c *check.C) {
  43. testRequires(c, DaemonIsLinux)
  44. dockerCmd(c, "run", "busybox", "true")
  45. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  46. c.Assert(err, checker.IsNil)
  47. c.Assert(status, checker.Equals, http.StatusOK)
  48. // empty Labels field triggered this bug, make sense to check for everything
  49. // cause even Ports for instance can trigger this bug
  50. // better safe than sorry..
  51. fields := []string{
  52. "Id",
  53. "Names",
  54. "Image",
  55. "Command",
  56. "Created",
  57. "Ports",
  58. "Labels",
  59. "Status",
  60. }
  61. // decoding into types.Container do not work since it eventually unmarshal
  62. // and empty field to an empty go map, so we just check for a string
  63. for _, f := range fields {
  64. if !strings.Contains(string(body), f) {
  65. c.Fatalf("Field %s is missing and it shouldn't", f)
  66. }
  67. }
  68. }
  69. type containerPs struct {
  70. Names []string
  71. Ports []map[string]interface{}
  72. }
  73. // regression test for non-empty fields from #13901
  74. func (s *DockerSuite) TestContainerPsOmitFields(c *check.C) {
  75. testRequires(c, DaemonIsLinux)
  76. name := "pstest"
  77. port := 80
  78. dockerCmd(c, "run", "-d", "--name", name, "--expose", strconv.Itoa(port), "busybox", "top")
  79. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  80. c.Assert(err, checker.IsNil)
  81. c.Assert(status, checker.Equals, http.StatusOK)
  82. var resp []containerPs
  83. err = json.Unmarshal(body, &resp)
  84. c.Assert(err, checker.IsNil)
  85. var foundContainer *containerPs
  86. for _, container := range resp {
  87. for _, testName := range container.Names {
  88. if "/"+name == testName {
  89. foundContainer = &container
  90. break
  91. }
  92. }
  93. }
  94. c.Assert(foundContainer.Ports, checker.HasLen, 1)
  95. c.Assert(foundContainer.Ports[0]["PrivatePort"], checker.Equals, float64(port))
  96. _, ok := foundContainer.Ports[0]["PublicPort"]
  97. c.Assert(ok, checker.Not(checker.Equals), true)
  98. _, ok = foundContainer.Ports[0]["IP"]
  99. c.Assert(ok, checker.Not(checker.Equals), true)
  100. }
  101. func (s *DockerSuite) TestContainerApiGetExport(c *check.C) {
  102. testRequires(c, DaemonIsLinux)
  103. name := "exportcontainer"
  104. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test")
  105. status, body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
  106. c.Assert(err, checker.IsNil)
  107. c.Assert(status, checker.Equals, http.StatusOK)
  108. found := false
  109. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  110. h, err := tarReader.Next()
  111. if err != nil && err == io.EOF {
  112. break
  113. }
  114. if h.Name == "test" {
  115. found = true
  116. break
  117. }
  118. }
  119. c.Assert(found, checker.True, check.Commentf("The created test file has not been found in the exported image"))
  120. }
  121. func (s *DockerSuite) TestContainerApiGetChanges(c *check.C) {
  122. testRequires(c, DaemonIsLinux)
  123. name := "changescontainer"
  124. dockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd")
  125. status, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
  126. c.Assert(err, checker.IsNil)
  127. c.Assert(status, checker.Equals, http.StatusOK)
  128. changes := []struct {
  129. Kind int
  130. Path string
  131. }{}
  132. c.Assert(json.Unmarshal(body, &changes), checker.IsNil, check.Commentf("unable to unmarshal response body"))
  133. // Check the changelog for removal of /etc/passwd
  134. success := false
  135. for _, elem := range changes {
  136. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  137. success = true
  138. }
  139. }
  140. c.Assert(success, checker.True, check.Commentf("/etc/passwd has been removed but is not present in the diff"))
  141. }
  142. func (s *DockerSuite) TestContainerApiStartVolumeBinds(c *check.C) {
  143. testRequires(c, DaemonIsLinux)
  144. name := "testing"
  145. config := map[string]interface{}{
  146. "Image": "busybox",
  147. "Volumes": map[string]struct{}{"/tmp": {}},
  148. }
  149. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  150. c.Assert(err, checker.IsNil)
  151. c.Assert(status, checker.Equals, http.StatusCreated)
  152. bindPath := randomTmpDirPath("test", daemonPlatform)
  153. config = map[string]interface{}{
  154. "Binds": []string{bindPath + ":/tmp"},
  155. }
  156. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  157. c.Assert(err, checker.IsNil)
  158. c.Assert(status, checker.Equals, http.StatusNoContent)
  159. pth, err := inspectMountSourceField(name, "/tmp")
  160. c.Assert(err, checker.IsNil)
  161. c.Assert(pth, checker.Equals, bindPath, check.Commentf("expected volume host path to be %s, got %s", bindPath, pth))
  162. }
  163. // Test for GH#10618
  164. func (s *DockerSuite) TestContainerApiStartDupVolumeBinds(c *check.C) {
  165. testRequires(c, DaemonIsLinux)
  166. name := "testdups"
  167. config := map[string]interface{}{
  168. "Image": "busybox",
  169. "Volumes": map[string]struct{}{"/tmp": {}},
  170. }
  171. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  172. c.Assert(err, checker.IsNil)
  173. c.Assert(status, checker.Equals, http.StatusCreated)
  174. bindPath1 := randomTmpDirPath("test1", daemonPlatform)
  175. bindPath2 := randomTmpDirPath("test2", daemonPlatform)
  176. config = map[string]interface{}{
  177. "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"},
  178. }
  179. status, body, err := sockRequest("POST", "/containers/"+name+"/start", config)
  180. c.Assert(err, checker.IsNil)
  181. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  182. c.Assert(string(body), checker.Contains, "Duplicate mount point", check.Commentf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(body), err))
  183. }
  184. func (s *DockerSuite) TestContainerApiStartVolumesFrom(c *check.C) {
  185. testRequires(c, DaemonIsLinux)
  186. volName := "voltst"
  187. volPath := "/tmp"
  188. dockerCmd(c, "run", "-d", "--name", volName, "-v", volPath, "busybox")
  189. name := "TestContainerApiStartVolumesFrom"
  190. config := map[string]interface{}{
  191. "Image": "busybox",
  192. "Volumes": map[string]struct{}{volPath: {}},
  193. }
  194. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  195. c.Assert(err, checker.IsNil)
  196. c.Assert(status, checker.Equals, http.StatusCreated)
  197. config = map[string]interface{}{
  198. "VolumesFrom": []string{volName},
  199. }
  200. status, _, err = sockRequest("POST", "/containers/"+name+"/start", config)
  201. c.Assert(err, checker.IsNil)
  202. c.Assert(status, checker.Equals, http.StatusNoContent)
  203. pth, err := inspectMountSourceField(name, volPath)
  204. c.Assert(err, checker.IsNil)
  205. pth2, err := inspectMountSourceField(volName, volPath)
  206. c.Assert(err, checker.IsNil)
  207. c.Assert(pth, checker.Equals, pth2, check.Commentf("expected volume host path to be %s, got %s", pth, pth2))
  208. }
  209. func (s *DockerSuite) TestGetContainerStats(c *check.C) {
  210. testRequires(c, DaemonIsLinux)
  211. var (
  212. name = "statscontainer"
  213. )
  214. dockerCmd(c, "run", "-d", "--name", name, "busybox", "top")
  215. type b struct {
  216. status int
  217. body []byte
  218. err error
  219. }
  220. bc := make(chan b, 1)
  221. go func() {
  222. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  223. bc <- b{status, body, err}
  224. }()
  225. // allow some time to stream the stats from the container
  226. time.Sleep(4 * time.Second)
  227. dockerCmd(c, "rm", "-f", name)
  228. // collect the results from the stats stream or timeout and fail
  229. // if the stream was not disconnected.
  230. select {
  231. case <-time.After(2 * time.Second):
  232. c.Fatal("stream was not closed after container was removed")
  233. case sr := <-bc:
  234. c.Assert(sr.err, checker.IsNil)
  235. c.Assert(sr.status, checker.Equals, http.StatusOK)
  236. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  237. var s *types.Stats
  238. // decode only one object from the stream
  239. c.Assert(dec.Decode(&s), checker.IsNil)
  240. }
  241. }
  242. func (s *DockerSuite) TestGetContainerStatsRmRunning(c *check.C) {
  243. testRequires(c, DaemonIsLinux)
  244. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  245. id := strings.TrimSpace(out)
  246. buf := &integration.ChannelBuffer{make(chan []byte, 1)}
  247. defer buf.Close()
  248. chErr := make(chan error)
  249. go func() {
  250. _, body, err := sockRequestRaw("GET", "/containers/"+id+"/stats?stream=1", nil, "application/json")
  251. if err != nil {
  252. chErr <- err
  253. }
  254. defer body.Close()
  255. _, err = io.Copy(buf, body)
  256. chErr <- err
  257. }()
  258. defer func() {
  259. c.Assert(<-chErr, checker.IsNil)
  260. }()
  261. b := make([]byte, 32)
  262. // make sure we've got some stats
  263. _, err := buf.ReadTimeout(b, 2*time.Second)
  264. c.Assert(err, checker.IsNil)
  265. // Now remove without `-f` and make sure we are still pulling stats
  266. _, _, err = dockerCmdWithError("rm", id)
  267. c.Assert(err, checker.Not(checker.IsNil), check.Commentf("rm should have failed but didn't"))
  268. _, err = buf.ReadTimeout(b, 2*time.Second)
  269. c.Assert(err, checker.IsNil)
  270. dockerCmd(c, "rm", "-f", id)
  271. _, err = buf.ReadTimeout(b, 2*time.Second)
  272. c.Assert(err, checker.Not(checker.IsNil))
  273. }
  274. // regression test for gh13421
  275. // previous test was just checking one stat entry so it didn't fail (stats with
  276. // stream false always return one stat)
  277. func (s *DockerSuite) TestGetContainerStatsStream(c *check.C) {
  278. testRequires(c, DaemonIsLinux)
  279. name := "statscontainer"
  280. dockerCmd(c, "run", "-d", "--name", name, "busybox", "top")
  281. type b struct {
  282. status int
  283. body []byte
  284. err error
  285. }
  286. bc := make(chan b, 1)
  287. go func() {
  288. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  289. bc <- b{status, body, err}
  290. }()
  291. // allow some time to stream the stats from the container
  292. time.Sleep(4 * time.Second)
  293. dockerCmd(c, "rm", "-f", name)
  294. // collect the results from the stats stream or timeout and fail
  295. // if the stream was not disconnected.
  296. select {
  297. case <-time.After(2 * time.Second):
  298. c.Fatal("stream was not closed after container was removed")
  299. case sr := <-bc:
  300. c.Assert(sr.err, checker.IsNil)
  301. c.Assert(sr.status, checker.Equals, http.StatusOK)
  302. s := string(sr.body)
  303. // count occurrences of "read" of types.Stats
  304. if l := strings.Count(s, "read"); l < 2 {
  305. c.Fatalf("Expected more than one stat streamed, got %d", l)
  306. }
  307. }
  308. }
  309. func (s *DockerSuite) TestGetContainerStatsNoStream(c *check.C) {
  310. testRequires(c, DaemonIsLinux)
  311. name := "statscontainer"
  312. dockerCmd(c, "run", "-d", "--name", name, "busybox", "top")
  313. type b struct {
  314. status int
  315. body []byte
  316. err error
  317. }
  318. bc := make(chan b, 1)
  319. go func() {
  320. status, body, err := sockRequest("GET", "/containers/"+name+"/stats?stream=0", nil)
  321. bc <- b{status, body, err}
  322. }()
  323. // allow some time to stream the stats from the container
  324. time.Sleep(4 * time.Second)
  325. dockerCmd(c, "rm", "-f", name)
  326. // collect the results from the stats stream or timeout and fail
  327. // if the stream was not disconnected.
  328. select {
  329. case <-time.After(2 * time.Second):
  330. c.Fatal("stream was not closed after container was removed")
  331. case sr := <-bc:
  332. c.Assert(sr.err, checker.IsNil)
  333. c.Assert(sr.status, checker.Equals, http.StatusOK)
  334. s := string(sr.body)
  335. // count occurrences of "read" of types.Stats
  336. c.Assert(strings.Count(s, "read"), checker.Equals, 1, check.Commentf("Expected only one stat streamed, got %d", strings.Count(s, "read")))
  337. }
  338. }
  339. func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) {
  340. testRequires(c, DaemonIsLinux)
  341. // TODO: this test does nothing because we are c.Assert'ing in goroutine
  342. var (
  343. name = "statscontainer"
  344. )
  345. dockerCmd(c, "create", "--name", name, "busybox", "top")
  346. go func() {
  347. // We'll never get return for GET stats from sockRequest as of now,
  348. // just send request and see if panic or error would happen on daemon side.
  349. status, _, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  350. c.Assert(err, checker.IsNil)
  351. c.Assert(status, checker.Equals, http.StatusOK)
  352. }()
  353. // allow some time to send request and let daemon deal with it
  354. time.Sleep(1 * time.Second)
  355. }
  356. // #9981 - Allow a docker created volume (ie, one in /var/lib/docker/volumes) to be used to overwrite (via passing in Binds on api start) an existing volume
  357. func (s *DockerSuite) TestPostContainerBindNormalVolume(c *check.C) {
  358. testRequires(c, DaemonIsLinux)
  359. dockerCmd(c, "create", "-v", "/foo", "--name=one", "busybox")
  360. fooDir, err := inspectMountSourceField("one", "/foo")
  361. c.Assert(err, checker.IsNil)
  362. dockerCmd(c, "create", "-v", "/foo", "--name=two", "busybox")
  363. bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
  364. status, _, err := sockRequest("POST", "/containers/two/start", bindSpec)
  365. c.Assert(err, checker.IsNil)
  366. c.Assert(status, checker.Equals, http.StatusNoContent)
  367. fooDir2, err := inspectMountSourceField("two", "/foo")
  368. c.Assert(err, checker.IsNil)
  369. c.Assert(fooDir2, checker.Equals, fooDir, check.Commentf("expected volume path to be %s, got: %s", fooDir, fooDir2))
  370. }
  371. func (s *DockerSuite) TestContainerApiPause(c *check.C) {
  372. testRequires(c, DaemonIsLinux)
  373. defer unpauseAllContainers()
  374. out, _ := dockerCmd(c, "run", "-d", "busybox", "sleep", "30")
  375. ContainerID := strings.TrimSpace(out)
  376. status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil)
  377. c.Assert(err, checker.IsNil)
  378. c.Assert(status, checker.Equals, http.StatusNoContent)
  379. pausedContainers, err := getSliceOfPausedContainers()
  380. c.Assert(err, checker.IsNil, check.Commentf("error thrown while checking if containers were paused"))
  381. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  382. c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  383. }
  384. status, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil)
  385. c.Assert(err, checker.IsNil)
  386. c.Assert(status, checker.Equals, http.StatusNoContent)
  387. pausedContainers, err = getSliceOfPausedContainers()
  388. c.Assert(err, checker.IsNil, check.Commentf("error thrown while checking if containers were paused"))
  389. c.Assert(pausedContainers, checker.IsNil, check.Commentf("There should be no paused container."))
  390. }
  391. func (s *DockerSuite) TestContainerApiTop(c *check.C) {
  392. testRequires(c, DaemonIsLinux)
  393. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top")
  394. id := strings.TrimSpace(string(out))
  395. c.Assert(waitRun(id), checker.IsNil)
  396. type topResp struct {
  397. Titles []string
  398. Processes [][]string
  399. }
  400. var top topResp
  401. status, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil)
  402. c.Assert(err, checker.IsNil)
  403. c.Assert(status, checker.Equals, http.StatusOK)
  404. c.Assert(json.Unmarshal(b, &top), checker.IsNil)
  405. c.Assert(top.Titles, checker.HasLen, 11, check.Commentf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles))
  406. if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
  407. c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
  408. }
  409. c.Assert(top.Processes, checker.HasLen, 2, check.Commentf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes))
  410. c.Assert(top.Processes[0][10], checker.Equals, "/bin/sh -c top")
  411. c.Assert(top.Processes[1][10], checker.Equals, "top")
  412. }
  413. func (s *DockerSuite) TestContainerApiCommit(c *check.C) {
  414. testRequires(c, DaemonIsLinux)
  415. cName := "testapicommit"
  416. dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
  417. name := "testcontainerapicommit"
  418. status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil)
  419. c.Assert(err, checker.IsNil)
  420. c.Assert(status, checker.Equals, http.StatusCreated)
  421. type resp struct {
  422. ID string
  423. }
  424. var img resp
  425. c.Assert(json.Unmarshal(b, &img), checker.IsNil)
  426. cmd, err := inspectField(img.ID, "Config.Cmd")
  427. c.Assert(err, checker.IsNil)
  428. c.Assert(cmd, checker.Equals, "{[/bin/sh -c touch /test]}", check.Commentf("got wrong Cmd from commit: %q", cmd))
  429. // sanity check, make sure the image is what we think it is
  430. dockerCmd(c, "run", img.ID, "ls", "/test")
  431. }
  432. func (s *DockerSuite) TestContainerApiCommitWithLabelInConfig(c *check.C) {
  433. testRequires(c, DaemonIsLinux)
  434. cName := "testapicommitwithconfig"
  435. dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
  436. config := map[string]interface{}{
  437. "Labels": map[string]string{"key1": "value1", "key2": "value2"},
  438. }
  439. name := "testcontainerapicommitwithconfig"
  440. status, b, err := sockRequest("POST", "/commit?repo="+name+"&container="+cName, config)
  441. c.Assert(err, checker.IsNil)
  442. c.Assert(status, checker.Equals, http.StatusCreated)
  443. type resp struct {
  444. ID string
  445. }
  446. var img resp
  447. c.Assert(json.Unmarshal(b, &img), checker.IsNil)
  448. label1, err := inspectFieldMap(img.ID, "Config.Labels", "key1")
  449. c.Assert(err, checker.IsNil)
  450. c.Assert(label1, checker.Equals, "value1")
  451. label2, err := inspectFieldMap(img.ID, "Config.Labels", "key2")
  452. c.Assert(err, checker.IsNil)
  453. c.Assert(label2, checker.Equals, "value2")
  454. cmd, err := inspectField(img.ID, "Config.Cmd")
  455. c.Assert(err, checker.IsNil)
  456. c.Assert(cmd, checker.Equals, "{[/bin/sh -c touch /test]}", check.Commentf("got wrong Cmd from commit: %q", cmd))
  457. // sanity check, make sure the image is what we think it is
  458. dockerCmd(c, "run", img.ID, "ls", "/test")
  459. }
  460. func (s *DockerSuite) TestContainerApiBadPort(c *check.C) {
  461. testRequires(c, DaemonIsLinux)
  462. config := map[string]interface{}{
  463. "Image": "busybox",
  464. "Cmd": []string{"/bin/sh", "-c", "echo test"},
  465. "PortBindings": map[string]interface{}{
  466. "8080/tcp": []map[string]interface{}{
  467. {
  468. "HostIP": "",
  469. "HostPort": "aa80",
  470. },
  471. },
  472. },
  473. }
  474. jsonData := bytes.NewBuffer(nil)
  475. json.NewEncoder(jsonData).Encode(config)
  476. status, b, err := sockRequest("POST", "/containers/create", config)
  477. c.Assert(err, checker.IsNil)
  478. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  479. c.Assert(strings.TrimSpace(string(b)), checker.Equals, `Invalid port specification: "aa80"`, check.Commentf("Incorrect error msg: %s", string(b)))
  480. }
  481. func (s *DockerSuite) TestContainerApiCreate(c *check.C) {
  482. testRequires(c, DaemonIsLinux)
  483. config := map[string]interface{}{
  484. "Image": "busybox",
  485. "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"},
  486. }
  487. status, b, err := sockRequest("POST", "/containers/create", config)
  488. c.Assert(err, checker.IsNil)
  489. c.Assert(status, checker.Equals, http.StatusCreated)
  490. type createResp struct {
  491. ID string
  492. }
  493. var container createResp
  494. c.Assert(json.Unmarshal(b, &container), checker.IsNil)
  495. out, _ := dockerCmd(c, "start", "-a", container.ID)
  496. c.Assert(strings.TrimSpace(out), checker.Equals, "/test")
  497. }
  498. func (s *DockerSuite) TestContainerApiCreateEmptyConfig(c *check.C) {
  499. config := map[string]interface{}{}
  500. status, b, err := sockRequest("POST", "/containers/create", config)
  501. c.Assert(err, checker.IsNil)
  502. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  503. expected := "Config cannot be empty in order to create a container\n"
  504. c.Assert(string(b), checker.Equals, expected)
  505. }
  506. func (s *DockerSuite) TestContainerApiCreateWithHostName(c *check.C) {
  507. testRequires(c, DaemonIsLinux)
  508. hostName := "test-host"
  509. config := map[string]interface{}{
  510. "Image": "busybox",
  511. "Hostname": hostName,
  512. }
  513. status, body, err := sockRequest("POST", "/containers/create", config)
  514. c.Assert(err, checker.IsNil)
  515. c.Assert(status, checker.Equals, http.StatusCreated)
  516. var container types.ContainerCreateResponse
  517. c.Assert(json.Unmarshal(body, &container), checker.IsNil)
  518. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  519. c.Assert(err, checker.IsNil)
  520. c.Assert(status, checker.Equals, http.StatusOK)
  521. var containerJSON types.ContainerJSON
  522. c.Assert(json.Unmarshal(body, &containerJSON), checker.IsNil)
  523. c.Assert(containerJSON.Config.Hostname, checker.Equals, hostName, check.Commentf("Mismatched Hostname"))
  524. }
  525. func (s *DockerSuite) TestContainerApiCreateWithDomainName(c *check.C) {
  526. testRequires(c, DaemonIsLinux)
  527. domainName := "test-domain"
  528. config := map[string]interface{}{
  529. "Image": "busybox",
  530. "Domainname": domainName,
  531. }
  532. status, body, err := sockRequest("POST", "/containers/create", config)
  533. c.Assert(err, checker.IsNil)
  534. c.Assert(status, checker.Equals, http.StatusCreated)
  535. var container types.ContainerCreateResponse
  536. c.Assert(json.Unmarshal(body, &container), checker.IsNil)
  537. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  538. c.Assert(err, checker.IsNil)
  539. c.Assert(status, checker.Equals, http.StatusOK)
  540. var containerJSON types.ContainerJSON
  541. c.Assert(json.Unmarshal(body, &containerJSON), checker.IsNil)
  542. c.Assert(containerJSON.Config.Domainname, checker.Equals, domainName, check.Commentf("Mismatched Domainname"))
  543. }
  544. func (s *DockerSuite) TestContainerApiCreateNetworkMode(c *check.C) {
  545. testRequires(c, DaemonIsLinux)
  546. UtilCreateNetworkMode(c, "host")
  547. UtilCreateNetworkMode(c, "bridge")
  548. UtilCreateNetworkMode(c, "container:web1")
  549. }
  550. func UtilCreateNetworkMode(c *check.C, networkMode string) {
  551. config := map[string]interface{}{
  552. "Image": "busybox",
  553. "HostConfig": map[string]interface{}{"NetworkMode": networkMode},
  554. }
  555. status, body, err := sockRequest("POST", "/containers/create", config)
  556. c.Assert(err, checker.IsNil)
  557. c.Assert(status, checker.Equals, http.StatusCreated)
  558. var container types.ContainerCreateResponse
  559. c.Assert(json.Unmarshal(body, &container), checker.IsNil)
  560. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  561. c.Assert(err, checker.IsNil)
  562. c.Assert(status, checker.Equals, http.StatusOK)
  563. var containerJSON types.ContainerJSON
  564. c.Assert(json.Unmarshal(body, &containerJSON), checker.IsNil)
  565. c.Assert(containerJSON.HostConfig.NetworkMode, checker.Equals, runconfig.NetworkMode(networkMode), check.Commentf("Mismatched NetworkMode"))
  566. }
  567. func (s *DockerSuite) TestContainerApiCreateWithCpuSharesCpuset(c *check.C) {
  568. testRequires(c, DaemonIsLinux)
  569. config := map[string]interface{}{
  570. "Image": "busybox",
  571. "CpuShares": 512,
  572. "CpusetCpus": "0",
  573. }
  574. status, body, err := sockRequest("POST", "/containers/create", config)
  575. c.Assert(err, checker.IsNil)
  576. c.Assert(status, checker.Equals, http.StatusCreated)
  577. var container types.ContainerCreateResponse
  578. c.Assert(json.Unmarshal(body, &container), checker.IsNil)
  579. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  580. c.Assert(err, checker.IsNil)
  581. c.Assert(status, checker.Equals, http.StatusOK)
  582. var containerJSON types.ContainerJSON
  583. c.Assert(json.Unmarshal(body, &containerJSON), checker.IsNil)
  584. out, err := inspectField(containerJSON.ID, "HostConfig.CpuShares")
  585. c.Assert(err, checker.IsNil)
  586. c.Assert(out, checker.Equals, "512")
  587. outCpuset, errCpuset := inspectField(containerJSON.ID, "HostConfig.CpusetCpus")
  588. c.Assert(errCpuset, checker.IsNil, check.Commentf("Output: %s", outCpuset))
  589. c.Assert(outCpuset, checker.Equals, "0")
  590. }
  591. func (s *DockerSuite) TestContainerApiVerifyHeader(c *check.C) {
  592. testRequires(c, DaemonIsLinux)
  593. config := map[string]interface{}{
  594. "Image": "busybox",
  595. }
  596. create := func(ct string) (*http.Response, io.ReadCloser, error) {
  597. jsonData := bytes.NewBuffer(nil)
  598. c.Assert(json.NewEncoder(jsonData).Encode(config), checker.IsNil)
  599. return sockRequestRaw("POST", "/containers/create", jsonData, ct)
  600. }
  601. // Try with no content-type
  602. res, body, err := create("")
  603. c.Assert(err, checker.IsNil)
  604. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  605. body.Close()
  606. // Try with wrong content-type
  607. res, body, err = create("application/xml")
  608. c.Assert(err, checker.IsNil)
  609. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  610. body.Close()
  611. // now application/json
  612. res, body, err = create("application/json")
  613. c.Assert(err, checker.IsNil)
  614. c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
  615. body.Close()
  616. }
  617. //Issue 14230. daemon should return 500 for invalid port syntax
  618. func (s *DockerSuite) TestContainerApiInvalidPortSyntax(c *check.C) {
  619. testRequires(c, DaemonIsLinux)
  620. config := `{
  621. "Image": "busybox",
  622. "HostConfig": {
  623. "PortBindings": {
  624. "19039;1230": [
  625. {}
  626. ]
  627. }
  628. }
  629. }`
  630. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  631. c.Assert(err, checker.IsNil)
  632. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  633. b, err := readBody(body)
  634. c.Assert(err, checker.IsNil)
  635. c.Assert(string(b[:]), checker.Contains, "Invalid port")
  636. }
  637. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  638. // W/o this fix a null in JSON would be parsed into a string var as "null"
  639. func (s *DockerSuite) TestContainerApiPostCreateNull(c *check.C) {
  640. testRequires(c, DaemonIsLinux)
  641. config := `{
  642. "Hostname":"",
  643. "Domainname":"",
  644. "Memory":0,
  645. "MemorySwap":0,
  646. "CpuShares":0,
  647. "Cpuset":null,
  648. "AttachStdin":true,
  649. "AttachStdout":true,
  650. "AttachStderr":true,
  651. "ExposedPorts":{},
  652. "Tty":true,
  653. "OpenStdin":true,
  654. "StdinOnce":true,
  655. "Env":[],
  656. "Cmd":"ls",
  657. "Image":"busybox",
  658. "Volumes":{},
  659. "WorkingDir":"",
  660. "Entrypoint":null,
  661. "NetworkDisabled":false,
  662. "OnBuild":null}`
  663. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  664. c.Assert(err, checker.IsNil)
  665. c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
  666. b, err := readBody(body)
  667. c.Assert(err, checker.IsNil)
  668. type createResp struct {
  669. ID string
  670. }
  671. var container createResp
  672. c.Assert(json.Unmarshal(b, &container), checker.IsNil)
  673. out, err := inspectField(container.ID, "HostConfig.CpusetCpus")
  674. c.Assert(err, checker.IsNil)
  675. c.Assert(out, checker.Equals, "")
  676. outMemory, errMemory := inspectField(container.ID, "HostConfig.Memory")
  677. c.Assert(outMemory, checker.Equals, "0")
  678. c.Assert(errMemory, checker.IsNil)
  679. outMemorySwap, errMemorySwap := inspectField(container.ID, "HostConfig.MemorySwap")
  680. c.Assert(outMemorySwap, checker.Equals, "0")
  681. c.Assert(errMemorySwap, checker.IsNil)
  682. }
  683. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  684. testRequires(c, DaemonIsLinux)
  685. config := `{
  686. "Image": "busybox",
  687. "Cmd": "ls",
  688. "OpenStdin": true,
  689. "CpuShares": 100,
  690. "Memory": 524287
  691. }`
  692. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  693. c.Assert(err, checker.IsNil)
  694. b, err2 := readBody(body)
  695. c.Assert(err2, checker.IsNil)
  696. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  697. c.Assert(string(b), checker.Contains, "Minimum memory limit allowed is 4MB")
  698. }
  699. func (s *DockerSuite) TestStartWithTooLowMemoryLimit(c *check.C) {
  700. testRequires(c, DaemonIsLinux)
  701. out, _ := dockerCmd(c, "create", "busybox")
  702. containerID := strings.TrimSpace(out)
  703. config := `{
  704. "CpuShares": 100,
  705. "Memory": 524287
  706. }`
  707. res, body, err := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  708. c.Assert(err, checker.IsNil)
  709. b, err2 := readBody(body)
  710. c.Assert(err2, checker.IsNil)
  711. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  712. c.Assert(string(b), checker.Contains, "Minimum memory limit allowed is 4MB")
  713. }
  714. func (s *DockerSuite) TestContainerApiRename(c *check.C) {
  715. testRequires(c, DaemonIsLinux)
  716. out, _ := dockerCmd(c, "run", "--name", "TestContainerApiRename", "-d", "busybox", "sh")
  717. containerID := strings.TrimSpace(out)
  718. newName := "TestContainerApiRenameNew"
  719. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
  720. c.Assert(err, checker.IsNil)
  721. // 204 No Content is expected, not 200
  722. c.Assert(statusCode, checker.Equals, http.StatusNoContent)
  723. name, err := inspectField(containerID, "Name")
  724. c.Assert(name, checker.Equals, "/"+newName, check.Commentf("Failed to rename container"))
  725. }
  726. func (s *DockerSuite) TestContainerApiKill(c *check.C) {
  727. testRequires(c, DaemonIsLinux)
  728. name := "test-api-kill"
  729. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  730. status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil)
  731. c.Assert(err, checker.IsNil)
  732. c.Assert(status, checker.Equals, http.StatusNoContent)
  733. state, err := inspectField(name, "State.Running")
  734. c.Assert(err, checker.IsNil)
  735. c.Assert(state, checker.Equals, "false", check.Commentf("got wrong State from container %s: %q", name, state))
  736. }
  737. func (s *DockerSuite) TestContainerApiRestart(c *check.C) {
  738. testRequires(c, DaemonIsLinux)
  739. name := "test-api-restart"
  740. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  741. status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil)
  742. c.Assert(err, checker.IsNil)
  743. c.Assert(status, checker.Equals, http.StatusNoContent)
  744. c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5*time.Second), checker.IsNil)
  745. }
  746. func (s *DockerSuite) TestContainerApiRestartNotimeoutParam(c *check.C) {
  747. testRequires(c, DaemonIsLinux)
  748. name := "test-api-restart-no-timeout-param"
  749. out, _ := dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  750. id := strings.TrimSpace(out)
  751. c.Assert(waitRun(id), checker.IsNil)
  752. status, _, err := sockRequest("POST", "/containers/"+name+"/restart", nil)
  753. c.Assert(err, checker.IsNil)
  754. c.Assert(status, checker.Equals, http.StatusNoContent)
  755. c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5*time.Second), checker.IsNil)
  756. }
  757. func (s *DockerSuite) TestContainerApiStart(c *check.C) {
  758. testRequires(c, DaemonIsLinux)
  759. name := "testing-start"
  760. config := map[string]interface{}{
  761. "Image": "busybox",
  762. "Cmd": []string{"/bin/sh", "-c", "/bin/top"},
  763. "OpenStdin": true,
  764. }
  765. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  766. c.Assert(err, checker.IsNil)
  767. c.Assert(status, checker.Equals, http.StatusCreated)
  768. conf := make(map[string]interface{})
  769. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  770. c.Assert(err, checker.IsNil)
  771. c.Assert(status, checker.Equals, http.StatusNoContent)
  772. // second call to start should give 304
  773. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  774. c.Assert(err, checker.IsNil)
  775. c.Assert(status, checker.Equals, http.StatusNotModified)
  776. }
  777. func (s *DockerSuite) TestContainerApiStop(c *check.C) {
  778. testRequires(c, DaemonIsLinux)
  779. name := "test-api-stop"
  780. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  781. status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  782. c.Assert(err, checker.IsNil)
  783. c.Assert(status, checker.Equals, http.StatusNoContent)
  784. c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 5*time.Second), checker.IsNil)
  785. // second call to start should give 304
  786. status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  787. c.Assert(err, checker.IsNil)
  788. c.Assert(status, checker.Equals, http.StatusNotModified)
  789. }
  790. func (s *DockerSuite) TestContainerApiWait(c *check.C) {
  791. testRequires(c, DaemonIsLinux)
  792. name := "test-api-wait"
  793. dockerCmd(c, "run", "--name", name, "busybox", "sleep", "5")
  794. status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil)
  795. c.Assert(err, checker.IsNil)
  796. c.Assert(status, checker.Equals, http.StatusOK)
  797. c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 5*time.Second), checker.IsNil)
  798. var waitres types.ContainerWaitResponse
  799. c.Assert(json.Unmarshal(body, &waitres), checker.IsNil)
  800. c.Assert(waitres.StatusCode, checker.Equals, 0)
  801. }
  802. func (s *DockerSuite) TestContainerApiCopy(c *check.C) {
  803. testRequires(c, DaemonIsLinux)
  804. name := "test-container-api-copy"
  805. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  806. postData := types.CopyConfig{
  807. Resource: "/test.txt",
  808. }
  809. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  810. c.Assert(err, checker.IsNil)
  811. c.Assert(status, checker.Equals, http.StatusOK)
  812. found := false
  813. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  814. h, err := tarReader.Next()
  815. if err != nil {
  816. if err == io.EOF {
  817. break
  818. }
  819. c.Fatal(err)
  820. }
  821. if h.Name == "test.txt" {
  822. found = true
  823. break
  824. }
  825. }
  826. c.Assert(found, checker.True)
  827. }
  828. func (s *DockerSuite) TestContainerApiCopyResourcePathEmpty(c *check.C) {
  829. testRequires(c, DaemonIsLinux)
  830. name := "test-container-api-copy-resource-empty"
  831. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  832. postData := types.CopyConfig{
  833. Resource: "",
  834. }
  835. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  836. c.Assert(err, checker.IsNil)
  837. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  838. c.Assert(string(body), checker.Matches, "Path cannot be empty\n")
  839. }
  840. func (s *DockerSuite) TestContainerApiCopyResourcePathNotFound(c *check.C) {
  841. testRequires(c, DaemonIsLinux)
  842. name := "test-container-api-copy-resource-not-found"
  843. dockerCmd(c, "run", "--name", name, "busybox")
  844. postData := types.CopyConfig{
  845. Resource: "/notexist",
  846. }
  847. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  848. c.Assert(err, checker.IsNil)
  849. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  850. c.Assert(string(body), checker.Matches, "Could not find the file /notexist in container "+name+"\n")
  851. }
  852. func (s *DockerSuite) TestContainerApiCopyContainerNotFound(c *check.C) {
  853. postData := types.CopyConfig{
  854. Resource: "/something",
  855. }
  856. status, _, err := sockRequest("POST", "/containers/notexists/copy", postData)
  857. c.Assert(err, checker.IsNil)
  858. c.Assert(status, checker.Equals, http.StatusNotFound)
  859. }
  860. func (s *DockerSuite) TestContainerApiDelete(c *check.C) {
  861. testRequires(c, DaemonIsLinux)
  862. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  863. id := strings.TrimSpace(out)
  864. c.Assert(waitRun(id), checker.IsNil)
  865. dockerCmd(c, "stop", id)
  866. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  867. c.Assert(err, checker.IsNil)
  868. c.Assert(status, checker.Equals, http.StatusNoContent)
  869. }
  870. func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) {
  871. status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
  872. c.Assert(err, checker.IsNil)
  873. c.Assert(status, checker.Equals, http.StatusNotFound)
  874. c.Assert(string(body), checker.Matches, "no such id: doesnotexist\n")
  875. }
  876. func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) {
  877. testRequires(c, DaemonIsLinux)
  878. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  879. id := strings.TrimSpace(out)
  880. c.Assert(waitRun(id), checker.IsNil)
  881. status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
  882. c.Assert(err, checker.IsNil)
  883. c.Assert(status, checker.Equals, http.StatusNoContent)
  884. }
  885. func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) {
  886. testRequires(c, DaemonIsLinux)
  887. out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top")
  888. id := strings.TrimSpace(out)
  889. c.Assert(waitRun(id), checker.IsNil)
  890. out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  891. id2 := strings.TrimSpace(out)
  892. c.Assert(waitRun(id2), checker.IsNil)
  893. links, err := inspectFieldJSON(id2, "HostConfig.Links")
  894. c.Assert(err, checker.IsNil)
  895. c.Assert(links, checker.Equals, "[\"/tlink1:/tlink2/tlink1\"]", check.Commentf("expected to have links between containers"))
  896. status, _, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
  897. c.Assert(err, checker.IsNil)
  898. c.Assert(status, checker.Equals, http.StatusNoContent)
  899. linksPostRm, err := inspectFieldJSON(id2, "HostConfig.Links")
  900. c.Assert(err, checker.IsNil)
  901. c.Assert(linksPostRm, checker.Equals, "null", check.Commentf("call to api deleteContainer links should have removed the specified links"))
  902. }
  903. func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) {
  904. testRequires(c, DaemonIsLinux)
  905. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  906. id := strings.TrimSpace(out)
  907. c.Assert(waitRun(id), checker.IsNil)
  908. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  909. c.Assert(err, checker.IsNil)
  910. c.Assert(status, checker.Equals, http.StatusConflict)
  911. }
  912. func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) {
  913. testRequires(c, DaemonIsLinux)
  914. testRequires(c, SameHostDaemon)
  915. out, _ := dockerCmd(c, "run", "-d", "-v", "/testvolume", "busybox", "top")
  916. id := strings.TrimSpace(out)
  917. c.Assert(waitRun(id), checker.IsNil)
  918. source, err := inspectMountSourceField(id, "/testvolume")
  919. _, err = os.Stat(source)
  920. c.Assert(err, checker.IsNil)
  921. status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
  922. c.Assert(err, checker.IsNil)
  923. c.Assert(status, checker.Equals, http.StatusNoContent)
  924. _, err = os.Stat(source)
  925. c.Assert(os.IsNotExist(err), checker.True, check.Commentf("expected to get ErrNotExist error, got %v", err))
  926. }
  927. // Regression test for https://github.com/docker/docker/issues/6231
  928. func (s *DockerSuite) TestContainersApiChunkedEncoding(c *check.C) {
  929. testRequires(c, DaemonIsLinux)
  930. out, _ := dockerCmd(c, "create", "-v", "/foo", "busybox", "true")
  931. id := strings.TrimSpace(out)
  932. conn, err := sockConn(time.Duration(10 * time.Second))
  933. c.Assert(err, checker.IsNil)
  934. client := httputil.NewClientConn(conn, nil)
  935. defer client.Close()
  936. bindCfg := strings.NewReader(`{"Binds": ["/tmp:/foo"]}`)
  937. req, err := http.NewRequest("POST", "/containers/"+id+"/start", bindCfg)
  938. c.Assert(err, checker.IsNil)
  939. req.Header.Set("Content-Type", "application/json")
  940. // This is a cheat to make the http request do chunked encoding
  941. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  942. // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
  943. req.ContentLength = -1
  944. resp, err := client.Do(req)
  945. c.Assert(err, checker.IsNil, check.Commentf("error starting container with chunked encoding"))
  946. resp.Body.Close()
  947. c.Assert(resp.StatusCode, checker.Equals, 204)
  948. out, err = inspectFieldJSON(id, "HostConfig.Binds")
  949. c.Assert(err, checker.IsNil)
  950. var binds []string
  951. c.Assert(json.NewDecoder(strings.NewReader(out)).Decode(&binds), checker.IsNil)
  952. c.Assert(binds, checker.HasLen, 1, check.Commentf("Got unexpected binds: %v", binds))
  953. expected := "/tmp:/foo"
  954. c.Assert(binds[0], checker.Equals, expected, check.Commentf("got incorrect bind spec"))
  955. }
  956. func (s *DockerSuite) TestPostContainerStop(c *check.C) {
  957. testRequires(c, DaemonIsLinux)
  958. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  959. containerID := strings.TrimSpace(out)
  960. c.Assert(waitRun(containerID), checker.IsNil)
  961. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/stop", nil)
  962. c.Assert(err, checker.IsNil)
  963. // 204 No Content is expected, not 200
  964. c.Assert(statusCode, checker.Equals, http.StatusNoContent)
  965. c.Assert(waitInspect(containerID, "{{ .State.Running }}", "false", 5*time.Second), checker.IsNil)
  966. }
  967. // #14170
  968. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceEntrypoint(c *check.C) {
  969. testRequires(c, DaemonIsLinux)
  970. config := struct {
  971. Image string
  972. Entrypoint string
  973. Cmd []string
  974. }{"busybox", "echo", []string{"hello", "world"}}
  975. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  976. c.Assert(err, checker.IsNil)
  977. out, _ := dockerCmd(c, "start", "-a", "echotest")
  978. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  979. config2 := struct {
  980. Image string
  981. Entrypoint []string
  982. Cmd []string
  983. }{"busybox", []string{"echo"}, []string{"hello", "world"}}
  984. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  985. c.Assert(err, checker.IsNil)
  986. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  987. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  988. }
  989. // #14170
  990. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) {
  991. testRequires(c, DaemonIsLinux)
  992. config := struct {
  993. Image string
  994. Entrypoint string
  995. Cmd string
  996. }{"busybox", "echo", "hello world"}
  997. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  998. c.Assert(err, checker.IsNil)
  999. out, _ := dockerCmd(c, "start", "-a", "echotest")
  1000. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1001. config2 := struct {
  1002. Image string
  1003. Cmd []string
  1004. }{"busybox", []string{"echo", "hello", "world"}}
  1005. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  1006. c.Assert(err, checker.IsNil)
  1007. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  1008. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1009. }
  1010. // regression #14318
  1011. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *check.C) {
  1012. testRequires(c, DaemonIsLinux)
  1013. config := struct {
  1014. Image string
  1015. CapAdd string
  1016. CapDrop string
  1017. }{"busybox", "NET_ADMIN", "SYS_ADMIN"}
  1018. status, _, err := sockRequest("POST", "/containers/create?name=capaddtest0", config)
  1019. c.Assert(err, checker.IsNil)
  1020. c.Assert(status, checker.Equals, http.StatusCreated)
  1021. config2 := struct {
  1022. Image string
  1023. CapAdd []string
  1024. CapDrop []string
  1025. }{"busybox", []string{"NET_ADMIN", "SYS_ADMIN"}, []string{"SETGID"}}
  1026. status, _, err = sockRequest("POST", "/containers/create?name=capaddtest1", config2)
  1027. c.Assert(err, checker.IsNil)
  1028. c.Assert(status, checker.Equals, http.StatusCreated)
  1029. }
  1030. // #14640
  1031. func (s *DockerSuite) TestPostContainersStartWithoutLinksInHostConfig(c *check.C) {
  1032. testRequires(c, DaemonIsLinux)
  1033. name := "test-host-config-links"
  1034. dockerCmd(c, "create", "--name", name, "busybox", "top")
  1035. hc, err := inspectFieldJSON(name, "HostConfig")
  1036. c.Assert(err, checker.IsNil)
  1037. config := `{"HostConfig":` + hc + `}`
  1038. res, b, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json")
  1039. c.Assert(err, checker.IsNil)
  1040. c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
  1041. b.Close()
  1042. }
  1043. // #14640
  1044. func (s *DockerSuite) TestPostContainersStartWithLinksInHostConfig(c *check.C) {
  1045. testRequires(c, DaemonIsLinux)
  1046. name := "test-host-config-links"
  1047. dockerCmd(c, "run", "--name", "foo", "-d", "busybox", "top")
  1048. dockerCmd(c, "create", "--name", name, "--link", "foo:bar", "busybox", "top")
  1049. hc, err := inspectFieldJSON(name, "HostConfig")
  1050. c.Assert(err, checker.IsNil)
  1051. config := `{"HostConfig":` + hc + `}`
  1052. res, b, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json")
  1053. c.Assert(err, checker.IsNil)
  1054. c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
  1055. b.Close()
  1056. }
  1057. // #14640
  1058. func (s *DockerSuite) TestPostContainersStartWithLinksInHostConfigIdLinked(c *check.C) {
  1059. testRequires(c, DaemonIsLinux)
  1060. name := "test-host-config-links"
  1061. out, _ := dockerCmd(c, "run", "--name", "link0", "-d", "busybox", "top")
  1062. id := strings.TrimSpace(out)
  1063. dockerCmd(c, "create", "--name", name, "--link", id, "busybox", "top")
  1064. hc, err := inspectFieldJSON(name, "HostConfig")
  1065. c.Assert(err, checker.IsNil)
  1066. config := `{"HostConfig":` + hc + `}`
  1067. res, b, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json")
  1068. c.Assert(err, checker.IsNil)
  1069. c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
  1070. b.Close()
  1071. }
  1072. // #14915
  1073. func (s *DockerSuite) TestContainersApiCreateNoHostConfig118(c *check.C) {
  1074. testRequires(c, DaemonIsLinux)
  1075. config := struct {
  1076. Image string
  1077. }{"busybox"}
  1078. status, _, err := sockRequest("POST", "/v1.18/containers/create", config)
  1079. c.Assert(err, checker.IsNil)
  1080. c.Assert(status, checker.Equals, http.StatusCreated)
  1081. }
  1082. // Ensure an error occurs when you have a container read-only rootfs but you
  1083. // extract an archive to a symlink in a writable volume which points to a
  1084. // directory outside of the volume.
  1085. func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(c *check.C) {
  1086. // Requires local volume mount bind.
  1087. // --read-only + userns has remount issues
  1088. testRequires(c, SameHostDaemon, NotUserNamespace)
  1089. testVol := getTestDir(c, "test-put-container-archive-err-symlink-in-volume-to-read-only-rootfs-")
  1090. defer os.RemoveAll(testVol)
  1091. makeTestContentInDir(c, testVol)
  1092. cID := makeTestContainer(c, testContainerOptions{
  1093. readOnly: true,
  1094. volumes: defaultVolumes(testVol), // Our bind mount is at /vol2
  1095. })
  1096. defer deleteContainer(cID)
  1097. // Attempt to extract to a symlink in the volume which points to a
  1098. // directory outside the volume. This should cause an error because the
  1099. // rootfs is read-only.
  1100. query := make(url.Values, 1)
  1101. query.Set("path", "/vol2/symlinkToAbsDir")
  1102. urlPath := fmt.Sprintf("/v1.20/containers/%s/archive?%s", cID, query.Encode())
  1103. statusCode, body, err := sockRequest("PUT", urlPath, nil)
  1104. c.Assert(err, checker.IsNil)
  1105. if !isCpCannotCopyReadOnly(fmt.Errorf(string(body))) {
  1106. c.Fatalf("expected ErrContainerRootfsReadonly error, but got %d: %s", statusCode, string(body))
  1107. }
  1108. }
  1109. func (s *DockerSuite) TestContainersApiGetContainersJSONEmpty(c *check.C) {
  1110. testRequires(c, DaemonIsLinux)
  1111. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  1112. c.Assert(err, checker.IsNil)
  1113. c.Assert(status, checker.Equals, http.StatusOK)
  1114. c.Assert(string(body), checker.Equals, "[]\n")
  1115. }
  1116. func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) {
  1117. testRequires(c, DaemonIsLinux)
  1118. c1 := struct {
  1119. Image string
  1120. CpusetCpus string
  1121. }{"busybox", "1-42,,"}
  1122. name := "wrong-cpuset-cpus"
  1123. status, body, err := sockRequest("POST", "/containers/create?name="+name, c1)
  1124. c.Assert(err, checker.IsNil)
  1125. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  1126. expected := "Invalid value 1-42,, for cpuset cpus.\n"
  1127. c.Assert(string(body), checker.Equals, expected)
  1128. c2 := struct {
  1129. Image string
  1130. CpusetMems string
  1131. }{"busybox", "42-3,1--"}
  1132. name = "wrong-cpuset-mems"
  1133. status, body, err = sockRequest("POST", "/containers/create?name="+name, c2)
  1134. c.Assert(err, checker.IsNil)
  1135. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  1136. expected = "Invalid value 42-3,1-- for cpuset mems.\n"
  1137. c.Assert(string(body), checker.Equals, expected)
  1138. }
  1139. func (s *DockerSuite) TestStartWithNilDNS(c *check.C) {
  1140. testRequires(c, DaemonIsLinux)
  1141. out, _ := dockerCmd(c, "create", "busybox")
  1142. containerID := strings.TrimSpace(out)
  1143. config := `{"HostConfig": {"Dns": null}}`
  1144. res, b, err := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  1145. c.Assert(err, checker.IsNil)
  1146. c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
  1147. b.Close()
  1148. dns, err := inspectFieldJSON(containerID, "HostConfig.Dns")
  1149. c.Assert(err, checker.IsNil)
  1150. c.Assert(dns, checker.Equals, "[]")
  1151. }
  1152. func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) {
  1153. config := map[string]interface{}{
  1154. "Image": "busybox",
  1155. "HostConfig": map[string]interface{}{"ShmSize": -1},
  1156. }
  1157. status, body, err := sockRequest("POST", "/containers/create", config)
  1158. c.Assert(err, check.IsNil)
  1159. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1160. c.Assert(string(body), checker.Contains, "SHM size must be greater then 0")
  1161. }
  1162. func (s *DockerSuite) TestPostContainersCreateShmSizeZero(c *check.C) {
  1163. config := map[string]interface{}{
  1164. "Image": "busybox",
  1165. "HostConfig": map[string]interface{}{"ShmSize": 0},
  1166. }
  1167. status, body, err := sockRequest("POST", "/containers/create", config)
  1168. c.Assert(err, check.IsNil)
  1169. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1170. c.Assert(string(body), checker.Contains, "SHM size must be greater then 0")
  1171. }
  1172. func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check.C) {
  1173. config := map[string]interface{}{
  1174. "Image": "busybox",
  1175. "Cmd": "mount",
  1176. }
  1177. status, body, err := sockRequest("POST", "/containers/create", config)
  1178. c.Assert(err, check.IsNil)
  1179. c.Assert(status, check.Equals, http.StatusCreated)
  1180. var container types.ContainerCreateResponse
  1181. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1182. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1183. c.Assert(err, check.IsNil)
  1184. c.Assert(status, check.Equals, http.StatusOK)
  1185. var containerJSON types.ContainerJSON
  1186. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1187. c.Assert(*containerJSON.HostConfig.ShmSize, check.Equals, runconfig.DefaultSHMSize)
  1188. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1189. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1190. if !shmRegexp.MatchString(out) {
  1191. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1192. }
  1193. }
  1194. func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *check.C) {
  1195. config := map[string]interface{}{
  1196. "Image": "busybox",
  1197. "HostConfig": map[string]interface{}{},
  1198. "Cmd": "mount",
  1199. }
  1200. status, body, err := sockRequest("POST", "/containers/create", config)
  1201. c.Assert(err, check.IsNil)
  1202. c.Assert(status, check.Equals, http.StatusCreated)
  1203. var container types.ContainerCreateResponse
  1204. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1205. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1206. c.Assert(err, check.IsNil)
  1207. c.Assert(status, check.Equals, http.StatusOK)
  1208. var containerJSON types.ContainerJSON
  1209. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1210. c.Assert(*containerJSON.HostConfig.ShmSize, check.Equals, int64(67108864))
  1211. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1212. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1213. if !shmRegexp.MatchString(out) {
  1214. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1215. }
  1216. }
  1217. func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *check.C) {
  1218. config := map[string]interface{}{
  1219. "Image": "busybox",
  1220. "Cmd": "mount",
  1221. "HostConfig": map[string]interface{}{"ShmSize": 1073741824},
  1222. }
  1223. status, body, err := sockRequest("POST", "/containers/create", config)
  1224. c.Assert(err, check.IsNil)
  1225. c.Assert(status, check.Equals, http.StatusCreated)
  1226. var container types.ContainerCreateResponse
  1227. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1228. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1229. c.Assert(err, check.IsNil)
  1230. c.Assert(status, check.Equals, http.StatusOK)
  1231. var containerJSON types.ContainerJSON
  1232. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1233. c.Assert(*containerJSON.HostConfig.ShmSize, check.Equals, int64(1073741824))
  1234. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1235. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  1236. if !shmRegex.MatchString(out) {
  1237. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  1238. }
  1239. }
  1240. func (s *DockerSuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted(c *check.C) {
  1241. config := map[string]interface{}{
  1242. "Image": "busybox",
  1243. }
  1244. status, body, err := sockRequest("POST", "/containers/create", config)
  1245. c.Assert(err, check.IsNil)
  1246. c.Assert(status, check.Equals, http.StatusCreated)
  1247. var container types.ContainerCreateResponse
  1248. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1249. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1250. c.Assert(err, check.IsNil)
  1251. c.Assert(status, check.Equals, http.StatusOK)
  1252. var containerJSON types.ContainerJSON
  1253. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1254. c.Assert(*containerJSON.HostConfig.MemorySwappiness, check.Equals, int64(-1))
  1255. }