docker_api_containers_test.go 52 KB

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