docker_api_containers_test.go 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  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/pkg/integration"
  17. "github.com/docker/docker/pkg/integration/checker"
  18. "github.com/docker/docker/pkg/stringid"
  19. "github.com/docker/engine-api/types"
  20. containertypes "github.com/docker/engine-api/types/container"
  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) TestContainerApiCreateBridgeNetworkMode(c *check.C) {
  546. testRequires(c, DaemonIsLinux)
  547. UtilCreateNetworkMode(c, "bridge")
  548. }
  549. func (s *DockerSuite) TestContainerApiCreateOtherNetworkModes(c *check.C) {
  550. testRequires(c, DaemonIsLinux, NotUserNamespace)
  551. UtilCreateNetworkMode(c, "host")
  552. UtilCreateNetworkMode(c, "container:web1")
  553. }
  554. func UtilCreateNetworkMode(c *check.C, networkMode string) {
  555. config := map[string]interface{}{
  556. "Image": "busybox",
  557. "HostConfig": map[string]interface{}{"NetworkMode": networkMode},
  558. }
  559. status, body, err := sockRequest("POST", "/containers/create", config)
  560. c.Assert(err, checker.IsNil)
  561. c.Assert(status, checker.Equals, http.StatusCreated)
  562. var container types.ContainerCreateResponse
  563. c.Assert(json.Unmarshal(body, &container), checker.IsNil)
  564. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  565. c.Assert(err, checker.IsNil)
  566. c.Assert(status, checker.Equals, http.StatusOK)
  567. var containerJSON types.ContainerJSON
  568. c.Assert(json.Unmarshal(body, &containerJSON), checker.IsNil)
  569. c.Assert(containerJSON.HostConfig.NetworkMode, checker.Equals, containertypes.NetworkMode(networkMode), check.Commentf("Mismatched NetworkMode"))
  570. }
  571. func (s *DockerSuite) TestContainerApiCreateWithCpuSharesCpuset(c *check.C) {
  572. testRequires(c, DaemonIsLinux)
  573. config := map[string]interface{}{
  574. "Image": "busybox",
  575. "CpuShares": 512,
  576. "CpusetCpus": "0",
  577. }
  578. status, body, err := sockRequest("POST", "/containers/create", config)
  579. c.Assert(err, checker.IsNil)
  580. c.Assert(status, checker.Equals, http.StatusCreated)
  581. var container types.ContainerCreateResponse
  582. c.Assert(json.Unmarshal(body, &container), checker.IsNil)
  583. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  584. c.Assert(err, checker.IsNil)
  585. c.Assert(status, checker.Equals, http.StatusOK)
  586. var containerJSON types.ContainerJSON
  587. c.Assert(json.Unmarshal(body, &containerJSON), checker.IsNil)
  588. out, err := inspectField(containerJSON.ID, "HostConfig.CpuShares")
  589. c.Assert(err, checker.IsNil)
  590. c.Assert(out, checker.Equals, "512")
  591. outCpuset, errCpuset := inspectField(containerJSON.ID, "HostConfig.CpusetCpus")
  592. c.Assert(errCpuset, checker.IsNil, check.Commentf("Output: %s", outCpuset))
  593. c.Assert(outCpuset, checker.Equals, "0")
  594. }
  595. func (s *DockerSuite) TestContainerApiVerifyHeader(c *check.C) {
  596. testRequires(c, DaemonIsLinux)
  597. config := map[string]interface{}{
  598. "Image": "busybox",
  599. }
  600. create := func(ct string) (*http.Response, io.ReadCloser, error) {
  601. jsonData := bytes.NewBuffer(nil)
  602. c.Assert(json.NewEncoder(jsonData).Encode(config), checker.IsNil)
  603. return sockRequestRaw("POST", "/containers/create", jsonData, ct)
  604. }
  605. // Try with no content-type
  606. res, body, err := create("")
  607. c.Assert(err, checker.IsNil)
  608. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  609. body.Close()
  610. // Try with wrong content-type
  611. res, body, err = create("application/xml")
  612. c.Assert(err, checker.IsNil)
  613. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  614. body.Close()
  615. // now application/json
  616. res, body, err = create("application/json")
  617. c.Assert(err, checker.IsNil)
  618. c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
  619. body.Close()
  620. }
  621. //Issue 14230. daemon should return 500 for invalid port syntax
  622. func (s *DockerSuite) TestContainerApiInvalidPortSyntax(c *check.C) {
  623. testRequires(c, DaemonIsLinux)
  624. config := `{
  625. "Image": "busybox",
  626. "HostConfig": {
  627. "PortBindings": {
  628. "19039;1230": [
  629. {}
  630. ]
  631. }
  632. }
  633. }`
  634. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  635. c.Assert(err, checker.IsNil)
  636. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  637. b, err := readBody(body)
  638. c.Assert(err, checker.IsNil)
  639. c.Assert(string(b[:]), checker.Contains, "Invalid port")
  640. }
  641. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  642. // W/o this fix a null in JSON would be parsed into a string var as "null"
  643. func (s *DockerSuite) TestContainerApiPostCreateNull(c *check.C) {
  644. testRequires(c, DaemonIsLinux)
  645. config := `{
  646. "Hostname":"",
  647. "Domainname":"",
  648. "Memory":0,
  649. "MemorySwap":0,
  650. "CpuShares":0,
  651. "Cpuset":null,
  652. "AttachStdin":true,
  653. "AttachStdout":true,
  654. "AttachStderr":true,
  655. "ExposedPorts":{},
  656. "Tty":true,
  657. "OpenStdin":true,
  658. "StdinOnce":true,
  659. "Env":[],
  660. "Cmd":"ls",
  661. "Image":"busybox",
  662. "Volumes":{},
  663. "WorkingDir":"",
  664. "Entrypoint":null,
  665. "NetworkDisabled":false,
  666. "OnBuild":null}`
  667. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  668. c.Assert(err, checker.IsNil)
  669. c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
  670. b, err := readBody(body)
  671. c.Assert(err, checker.IsNil)
  672. type createResp struct {
  673. ID string
  674. }
  675. var container createResp
  676. c.Assert(json.Unmarshal(b, &container), checker.IsNil)
  677. out, err := inspectField(container.ID, "HostConfig.CpusetCpus")
  678. c.Assert(err, checker.IsNil)
  679. c.Assert(out, checker.Equals, "")
  680. outMemory, errMemory := inspectField(container.ID, "HostConfig.Memory")
  681. c.Assert(outMemory, checker.Equals, "0")
  682. c.Assert(errMemory, checker.IsNil)
  683. outMemorySwap, errMemorySwap := inspectField(container.ID, "HostConfig.MemorySwap")
  684. c.Assert(outMemorySwap, checker.Equals, "0")
  685. c.Assert(errMemorySwap, checker.IsNil)
  686. }
  687. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  688. testRequires(c, DaemonIsLinux)
  689. config := `{
  690. "Image": "busybox",
  691. "Cmd": "ls",
  692. "OpenStdin": true,
  693. "CpuShares": 100,
  694. "Memory": 524287
  695. }`
  696. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  697. c.Assert(err, checker.IsNil)
  698. b, err2 := readBody(body)
  699. c.Assert(err2, checker.IsNil)
  700. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  701. c.Assert(string(b), checker.Contains, "Minimum memory limit allowed is 4MB")
  702. }
  703. func (s *DockerSuite) TestStartWithTooLowMemoryLimit(c *check.C) {
  704. testRequires(c, DaemonIsLinux)
  705. out, _ := dockerCmd(c, "create", "busybox")
  706. containerID := strings.TrimSpace(out)
  707. config := `{
  708. "CpuShares": 100,
  709. "Memory": 524287
  710. }`
  711. res, body, err := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  712. c.Assert(err, checker.IsNil)
  713. b, err2 := readBody(body)
  714. c.Assert(err2, checker.IsNil)
  715. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  716. c.Assert(string(b), checker.Contains, "Minimum memory limit allowed is 4MB")
  717. }
  718. func (s *DockerSuite) TestContainerApiRename(c *check.C) {
  719. testRequires(c, DaemonIsLinux)
  720. out, _ := dockerCmd(c, "run", "--name", "TestContainerApiRename", "-d", "busybox", "sh")
  721. containerID := strings.TrimSpace(out)
  722. newName := "TestContainerApiRenameNew"
  723. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
  724. c.Assert(err, checker.IsNil)
  725. // 204 No Content is expected, not 200
  726. c.Assert(statusCode, checker.Equals, http.StatusNoContent)
  727. name, err := inspectField(containerID, "Name")
  728. c.Assert(name, checker.Equals, "/"+newName, check.Commentf("Failed to rename container"))
  729. }
  730. func (s *DockerSuite) TestContainerApiKill(c *check.C) {
  731. testRequires(c, DaemonIsLinux)
  732. name := "test-api-kill"
  733. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  734. status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil)
  735. c.Assert(err, checker.IsNil)
  736. c.Assert(status, checker.Equals, http.StatusNoContent)
  737. state, err := inspectField(name, "State.Running")
  738. c.Assert(err, checker.IsNil)
  739. c.Assert(state, checker.Equals, "false", check.Commentf("got wrong State from container %s: %q", name, state))
  740. }
  741. func (s *DockerSuite) TestContainerApiRestart(c *check.C) {
  742. testRequires(c, DaemonIsLinux)
  743. name := "test-api-restart"
  744. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  745. status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil)
  746. c.Assert(err, checker.IsNil)
  747. c.Assert(status, checker.Equals, http.StatusNoContent)
  748. c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5*time.Second), checker.IsNil)
  749. }
  750. func (s *DockerSuite) TestContainerApiRestartNotimeoutParam(c *check.C) {
  751. testRequires(c, DaemonIsLinux)
  752. name := "test-api-restart-no-timeout-param"
  753. out, _ := dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  754. id := strings.TrimSpace(out)
  755. c.Assert(waitRun(id), checker.IsNil)
  756. status, _, err := sockRequest("POST", "/containers/"+name+"/restart", nil)
  757. c.Assert(err, checker.IsNil)
  758. c.Assert(status, checker.Equals, http.StatusNoContent)
  759. c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5*time.Second), checker.IsNil)
  760. }
  761. func (s *DockerSuite) TestContainerApiStart(c *check.C) {
  762. testRequires(c, DaemonIsLinux)
  763. name := "testing-start"
  764. config := map[string]interface{}{
  765. "Image": "busybox",
  766. "Cmd": []string{"/bin/sh", "-c", "/bin/top"},
  767. "OpenStdin": true,
  768. }
  769. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  770. c.Assert(err, checker.IsNil)
  771. c.Assert(status, checker.Equals, http.StatusCreated)
  772. conf := make(map[string]interface{})
  773. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  774. c.Assert(err, checker.IsNil)
  775. c.Assert(status, checker.Equals, http.StatusNoContent)
  776. // second call to start should give 304
  777. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  778. c.Assert(err, checker.IsNil)
  779. c.Assert(status, checker.Equals, http.StatusNotModified)
  780. }
  781. func (s *DockerSuite) TestContainerApiStop(c *check.C) {
  782. testRequires(c, DaemonIsLinux)
  783. name := "test-api-stop"
  784. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  785. status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  786. c.Assert(err, checker.IsNil)
  787. c.Assert(status, checker.Equals, http.StatusNoContent)
  788. c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 5*time.Second), checker.IsNil)
  789. // second call to start should give 304
  790. status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  791. c.Assert(err, checker.IsNil)
  792. c.Assert(status, checker.Equals, http.StatusNotModified)
  793. }
  794. func (s *DockerSuite) TestContainerApiWait(c *check.C) {
  795. testRequires(c, DaemonIsLinux)
  796. name := "test-api-wait"
  797. dockerCmd(c, "run", "--name", name, "busybox", "sleep", "5")
  798. status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil)
  799. c.Assert(err, checker.IsNil)
  800. c.Assert(status, checker.Equals, http.StatusOK)
  801. c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 5*time.Second), checker.IsNil)
  802. var waitres types.ContainerWaitResponse
  803. c.Assert(json.Unmarshal(body, &waitres), checker.IsNil)
  804. c.Assert(waitres.StatusCode, checker.Equals, 0)
  805. }
  806. func (s *DockerSuite) TestContainerApiCopy(c *check.C) {
  807. testRequires(c, DaemonIsLinux)
  808. name := "test-container-api-copy"
  809. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  810. postData := types.CopyConfig{
  811. Resource: "/test.txt",
  812. }
  813. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  814. c.Assert(err, checker.IsNil)
  815. c.Assert(status, checker.Equals, http.StatusOK)
  816. found := false
  817. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  818. h, err := tarReader.Next()
  819. if err != nil {
  820. if err == io.EOF {
  821. break
  822. }
  823. c.Fatal(err)
  824. }
  825. if h.Name == "test.txt" {
  826. found = true
  827. break
  828. }
  829. }
  830. c.Assert(found, checker.True)
  831. }
  832. func (s *DockerSuite) TestContainerApiCopyResourcePathEmpty(c *check.C) {
  833. testRequires(c, DaemonIsLinux)
  834. name := "test-container-api-copy-resource-empty"
  835. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  836. postData := types.CopyConfig{
  837. Resource: "",
  838. }
  839. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  840. c.Assert(err, checker.IsNil)
  841. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  842. c.Assert(string(body), checker.Matches, "Path cannot be empty\n")
  843. }
  844. func (s *DockerSuite) TestContainerApiCopyResourcePathNotFound(c *check.C) {
  845. testRequires(c, DaemonIsLinux)
  846. name := "test-container-api-copy-resource-not-found"
  847. dockerCmd(c, "run", "--name", name, "busybox")
  848. postData := types.CopyConfig{
  849. Resource: "/notexist",
  850. }
  851. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  852. c.Assert(err, checker.IsNil)
  853. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  854. c.Assert(string(body), checker.Matches, "Could not find the file /notexist in container "+name+"\n")
  855. }
  856. func (s *DockerSuite) TestContainerApiCopyContainerNotFound(c *check.C) {
  857. postData := types.CopyConfig{
  858. Resource: "/something",
  859. }
  860. status, _, err := sockRequest("POST", "/containers/notexists/copy", postData)
  861. c.Assert(err, checker.IsNil)
  862. c.Assert(status, checker.Equals, http.StatusNotFound)
  863. }
  864. func (s *DockerSuite) TestContainerApiDelete(c *check.C) {
  865. testRequires(c, DaemonIsLinux)
  866. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  867. id := strings.TrimSpace(out)
  868. c.Assert(waitRun(id), checker.IsNil)
  869. dockerCmd(c, "stop", id)
  870. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  871. c.Assert(err, checker.IsNil)
  872. c.Assert(status, checker.Equals, http.StatusNoContent)
  873. }
  874. func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) {
  875. status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
  876. c.Assert(err, checker.IsNil)
  877. c.Assert(status, checker.Equals, http.StatusNotFound)
  878. c.Assert(string(body), checker.Matches, "No such container: doesnotexist\n")
  879. }
  880. func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) {
  881. testRequires(c, DaemonIsLinux)
  882. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  883. id := strings.TrimSpace(out)
  884. c.Assert(waitRun(id), checker.IsNil)
  885. status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
  886. c.Assert(err, checker.IsNil)
  887. c.Assert(status, checker.Equals, http.StatusNoContent)
  888. }
  889. func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) {
  890. testRequires(c, DaemonIsLinux)
  891. out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top")
  892. id := strings.TrimSpace(out)
  893. c.Assert(waitRun(id), checker.IsNil)
  894. out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  895. id2 := strings.TrimSpace(out)
  896. c.Assert(waitRun(id2), checker.IsNil)
  897. links, err := inspectFieldJSON(id2, "HostConfig.Links")
  898. c.Assert(err, checker.IsNil)
  899. c.Assert(links, checker.Equals, "[\"/tlink1:/tlink2/tlink1\"]", check.Commentf("expected to have links between containers"))
  900. status, b, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
  901. c.Assert(err, check.IsNil)
  902. c.Assert(status, check.Equals, http.StatusNoContent, check.Commentf(string(b)))
  903. linksPostRm, err := inspectFieldJSON(id2, "HostConfig.Links")
  904. c.Assert(err, checker.IsNil)
  905. c.Assert(linksPostRm, checker.Equals, "null", check.Commentf("call to api deleteContainer links should have removed the specified links"))
  906. }
  907. func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) {
  908. testRequires(c, DaemonIsLinux)
  909. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  910. id := strings.TrimSpace(out)
  911. c.Assert(waitRun(id), checker.IsNil)
  912. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  913. c.Assert(err, checker.IsNil)
  914. c.Assert(status, checker.Equals, http.StatusConflict)
  915. }
  916. func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) {
  917. testRequires(c, DaemonIsLinux)
  918. testRequires(c, SameHostDaemon)
  919. out, _ := dockerCmd(c, "run", "-d", "-v", "/testvolume", "busybox", "top")
  920. id := strings.TrimSpace(out)
  921. c.Assert(waitRun(id), checker.IsNil)
  922. source, err := inspectMountSourceField(id, "/testvolume")
  923. _, err = os.Stat(source)
  924. c.Assert(err, checker.IsNil)
  925. status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
  926. c.Assert(err, checker.IsNil)
  927. c.Assert(status, checker.Equals, http.StatusNoContent)
  928. _, err = os.Stat(source)
  929. c.Assert(os.IsNotExist(err), checker.True, check.Commentf("expected to get ErrNotExist error, got %v", err))
  930. }
  931. // Regression test for https://github.com/docker/docker/issues/6231
  932. func (s *DockerSuite) TestContainersApiChunkedEncoding(c *check.C) {
  933. testRequires(c, DaemonIsLinux)
  934. out, _ := dockerCmd(c, "create", "-v", "/foo", "busybox", "true")
  935. id := strings.TrimSpace(out)
  936. conn, err := sockConn(time.Duration(10 * time.Second))
  937. c.Assert(err, checker.IsNil)
  938. client := httputil.NewClientConn(conn, nil)
  939. defer client.Close()
  940. bindCfg := strings.NewReader(`{"Binds": ["/tmp:/foo"]}`)
  941. req, err := http.NewRequest("POST", "/containers/"+id+"/start", bindCfg)
  942. c.Assert(err, checker.IsNil)
  943. req.Header.Set("Content-Type", "application/json")
  944. // This is a cheat to make the http request do chunked encoding
  945. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  946. // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
  947. req.ContentLength = -1
  948. resp, err := client.Do(req)
  949. c.Assert(err, checker.IsNil, check.Commentf("error starting container with chunked encoding"))
  950. resp.Body.Close()
  951. c.Assert(resp.StatusCode, checker.Equals, 204)
  952. out, err = inspectFieldJSON(id, "HostConfig.Binds")
  953. c.Assert(err, checker.IsNil)
  954. var binds []string
  955. c.Assert(json.NewDecoder(strings.NewReader(out)).Decode(&binds), checker.IsNil)
  956. c.Assert(binds, checker.HasLen, 1, check.Commentf("Got unexpected binds: %v", binds))
  957. expected := "/tmp:/foo"
  958. c.Assert(binds[0], checker.Equals, expected, check.Commentf("got incorrect bind spec"))
  959. }
  960. func (s *DockerSuite) TestPostContainerStop(c *check.C) {
  961. testRequires(c, DaemonIsLinux)
  962. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  963. containerID := strings.TrimSpace(out)
  964. c.Assert(waitRun(containerID), checker.IsNil)
  965. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/stop", nil)
  966. c.Assert(err, checker.IsNil)
  967. // 204 No Content is expected, not 200
  968. c.Assert(statusCode, checker.Equals, http.StatusNoContent)
  969. c.Assert(waitInspect(containerID, "{{ .State.Running }}", "false", 5*time.Second), checker.IsNil)
  970. }
  971. // #14170
  972. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceEntrypoint(c *check.C) {
  973. testRequires(c, DaemonIsLinux)
  974. config := struct {
  975. Image string
  976. Entrypoint string
  977. Cmd []string
  978. }{"busybox", "echo", []string{"hello", "world"}}
  979. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  980. c.Assert(err, checker.IsNil)
  981. out, _ := dockerCmd(c, "start", "-a", "echotest")
  982. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  983. config2 := struct {
  984. Image string
  985. Entrypoint []string
  986. Cmd []string
  987. }{"busybox", []string{"echo"}, []string{"hello", "world"}}
  988. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  989. c.Assert(err, checker.IsNil)
  990. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  991. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  992. }
  993. // #14170
  994. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) {
  995. testRequires(c, DaemonIsLinux)
  996. config := struct {
  997. Image string
  998. Entrypoint string
  999. Cmd string
  1000. }{"busybox", "echo", "hello world"}
  1001. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  1002. c.Assert(err, checker.IsNil)
  1003. out, _ := dockerCmd(c, "start", "-a", "echotest")
  1004. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1005. config2 := struct {
  1006. Image string
  1007. Cmd []string
  1008. }{"busybox", []string{"echo", "hello", "world"}}
  1009. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  1010. c.Assert(err, checker.IsNil)
  1011. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  1012. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1013. }
  1014. // regression #14318
  1015. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *check.C) {
  1016. testRequires(c, DaemonIsLinux)
  1017. config := struct {
  1018. Image string
  1019. CapAdd string
  1020. CapDrop string
  1021. }{"busybox", "NET_ADMIN", "SYS_ADMIN"}
  1022. status, _, err := sockRequest("POST", "/containers/create?name=capaddtest0", config)
  1023. c.Assert(err, checker.IsNil)
  1024. c.Assert(status, checker.Equals, http.StatusCreated)
  1025. config2 := struct {
  1026. Image string
  1027. CapAdd []string
  1028. CapDrop []string
  1029. }{"busybox", []string{"NET_ADMIN", "SYS_ADMIN"}, []string{"SETGID"}}
  1030. status, _, err = sockRequest("POST", "/containers/create?name=capaddtest1", config2)
  1031. c.Assert(err, checker.IsNil)
  1032. c.Assert(status, checker.Equals, http.StatusCreated)
  1033. }
  1034. // #14640
  1035. func (s *DockerSuite) TestPostContainersStartWithoutLinksInHostConfig(c *check.C) {
  1036. testRequires(c, DaemonIsLinux)
  1037. name := "test-host-config-links"
  1038. dockerCmd(c, "create", "--name", name, "busybox", "top")
  1039. hc, err := inspectFieldJSON(name, "HostConfig")
  1040. c.Assert(err, checker.IsNil)
  1041. config := `{"HostConfig":` + hc + `}`
  1042. res, b, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json")
  1043. c.Assert(err, checker.IsNil)
  1044. c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
  1045. b.Close()
  1046. }
  1047. // #14640
  1048. func (s *DockerSuite) TestPostContainersStartWithLinksInHostConfig(c *check.C) {
  1049. testRequires(c, DaemonIsLinux)
  1050. name := "test-host-config-links"
  1051. dockerCmd(c, "run", "--name", "foo", "-d", "busybox", "top")
  1052. dockerCmd(c, "create", "--name", name, "--link", "foo:bar", "busybox", "top")
  1053. hc, err := inspectFieldJSON(name, "HostConfig")
  1054. c.Assert(err, checker.IsNil)
  1055. config := `{"HostConfig":` + hc + `}`
  1056. res, b, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json")
  1057. c.Assert(err, checker.IsNil)
  1058. c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
  1059. b.Close()
  1060. }
  1061. // #14640
  1062. func (s *DockerSuite) TestPostContainersStartWithLinksInHostConfigIdLinked(c *check.C) {
  1063. testRequires(c, DaemonIsLinux)
  1064. name := "test-host-config-links"
  1065. out, _ := dockerCmd(c, "run", "--name", "link0", "-d", "busybox", "top")
  1066. id := strings.TrimSpace(out)
  1067. dockerCmd(c, "create", "--name", name, "--link", id, "busybox", "top")
  1068. hc, err := inspectFieldJSON(name, "HostConfig")
  1069. c.Assert(err, checker.IsNil)
  1070. config := `{"HostConfig":` + hc + `}`
  1071. res, b, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json")
  1072. c.Assert(err, checker.IsNil)
  1073. c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
  1074. b.Close()
  1075. }
  1076. // #14915
  1077. func (s *DockerSuite) TestContainersApiCreateNoHostConfig118(c *check.C) {
  1078. testRequires(c, DaemonIsLinux)
  1079. config := struct {
  1080. Image string
  1081. }{"busybox"}
  1082. status, _, err := sockRequest("POST", "/v1.18/containers/create", config)
  1083. c.Assert(err, checker.IsNil)
  1084. c.Assert(status, checker.Equals, http.StatusCreated)
  1085. }
  1086. // Ensure an error occurs when you have a container read-only rootfs but you
  1087. // extract an archive to a symlink in a writable volume which points to a
  1088. // directory outside of the volume.
  1089. func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(c *check.C) {
  1090. // Requires local volume mount bind.
  1091. // --read-only + userns has remount issues
  1092. testRequires(c, SameHostDaemon, NotUserNamespace, DaemonIsLinux)
  1093. testVol := getTestDir(c, "test-put-container-archive-err-symlink-in-volume-to-read-only-rootfs-")
  1094. defer os.RemoveAll(testVol)
  1095. makeTestContentInDir(c, testVol)
  1096. cID := makeTestContainer(c, testContainerOptions{
  1097. readOnly: true,
  1098. volumes: defaultVolumes(testVol), // Our bind mount is at /vol2
  1099. })
  1100. defer deleteContainer(cID)
  1101. // Attempt to extract to a symlink in the volume which points to a
  1102. // directory outside the volume. This should cause an error because the
  1103. // rootfs is read-only.
  1104. query := make(url.Values, 1)
  1105. query.Set("path", "/vol2/symlinkToAbsDir")
  1106. urlPath := fmt.Sprintf("/v1.20/containers/%s/archive?%s", cID, query.Encode())
  1107. statusCode, body, err := sockRequest("PUT", urlPath, nil)
  1108. c.Assert(err, checker.IsNil)
  1109. if !isCpCannotCopyReadOnly(fmt.Errorf(string(body))) {
  1110. c.Fatalf("expected ErrContainerRootfsReadonly error, but got %d: %s", statusCode, string(body))
  1111. }
  1112. }
  1113. func (s *DockerSuite) TestContainersApiGetContainersJSONEmpty(c *check.C) {
  1114. testRequires(c, DaemonIsLinux)
  1115. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  1116. c.Assert(err, checker.IsNil)
  1117. c.Assert(status, checker.Equals, http.StatusOK)
  1118. c.Assert(string(body), checker.Equals, "[]\n")
  1119. }
  1120. func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) {
  1121. testRequires(c, DaemonIsLinux)
  1122. c1 := struct {
  1123. Image string
  1124. CpusetCpus string
  1125. }{"busybox", "1-42,,"}
  1126. name := "wrong-cpuset-cpus"
  1127. status, body, err := sockRequest("POST", "/containers/create?name="+name, c1)
  1128. c.Assert(err, checker.IsNil)
  1129. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  1130. expected := "Invalid value 1-42,, for cpuset cpus.\n"
  1131. c.Assert(string(body), checker.Equals, expected)
  1132. c2 := struct {
  1133. Image string
  1134. CpusetMems string
  1135. }{"busybox", "42-3,1--"}
  1136. name = "wrong-cpuset-mems"
  1137. status, body, err = sockRequest("POST", "/containers/create?name="+name, c2)
  1138. c.Assert(err, checker.IsNil)
  1139. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  1140. expected = "Invalid value 42-3,1-- for cpuset mems.\n"
  1141. c.Assert(string(body), checker.Equals, expected)
  1142. }
  1143. func (s *DockerSuite) TestStartWithNilDNS(c *check.C) {
  1144. testRequires(c, DaemonIsLinux)
  1145. out, _ := dockerCmd(c, "create", "busybox")
  1146. containerID := strings.TrimSpace(out)
  1147. config := `{"HostConfig": {"Dns": null}}`
  1148. res, b, err := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  1149. c.Assert(err, checker.IsNil)
  1150. c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent)
  1151. b.Close()
  1152. dns, err := inspectFieldJSON(containerID, "HostConfig.Dns")
  1153. c.Assert(err, checker.IsNil)
  1154. c.Assert(dns, checker.Equals, "[]")
  1155. }
  1156. func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) {
  1157. testRequires(c, DaemonIsLinux)
  1158. config := map[string]interface{}{
  1159. "Image": "busybox",
  1160. "HostConfig": map[string]interface{}{"ShmSize": -1},
  1161. }
  1162. status, body, err := sockRequest("POST", "/containers/create", config)
  1163. c.Assert(err, check.IsNil)
  1164. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1165. c.Assert(string(body), checker.Contains, "SHM size must be greater then 0")
  1166. }
  1167. func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check.C) {
  1168. testRequires(c, DaemonIsLinux)
  1169. var defaultSHMSize int64 = 67108864
  1170. config := map[string]interface{}{
  1171. "Image": "busybox",
  1172. "Cmd": "mount",
  1173. }
  1174. status, body, err := sockRequest("POST", "/containers/create", config)
  1175. c.Assert(err, check.IsNil)
  1176. c.Assert(status, check.Equals, http.StatusCreated)
  1177. var container types.ContainerCreateResponse
  1178. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1179. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1180. c.Assert(err, check.IsNil)
  1181. c.Assert(status, check.Equals, http.StatusOK)
  1182. var containerJSON types.ContainerJSON
  1183. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1184. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, defaultSHMSize)
  1185. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1186. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1187. if !shmRegexp.MatchString(out) {
  1188. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1189. }
  1190. }
  1191. func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *check.C) {
  1192. testRequires(c, DaemonIsLinux)
  1193. config := map[string]interface{}{
  1194. "Image": "busybox",
  1195. "HostConfig": map[string]interface{}{},
  1196. "Cmd": "mount",
  1197. }
  1198. status, body, err := sockRequest("POST", "/containers/create", config)
  1199. c.Assert(err, check.IsNil)
  1200. c.Assert(status, check.Equals, http.StatusCreated)
  1201. var container types.ContainerCreateResponse
  1202. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1203. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1204. c.Assert(err, check.IsNil)
  1205. c.Assert(status, check.Equals, http.StatusOK)
  1206. var containerJSON types.ContainerJSON
  1207. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1208. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(67108864))
  1209. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1210. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1211. if !shmRegexp.MatchString(out) {
  1212. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1213. }
  1214. }
  1215. func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *check.C) {
  1216. testRequires(c, DaemonIsLinux)
  1217. config := map[string]interface{}{
  1218. "Image": "busybox",
  1219. "Cmd": "mount",
  1220. "HostConfig": map[string]interface{}{"ShmSize": 1073741824},
  1221. }
  1222. status, body, err := sockRequest("POST", "/containers/create", config)
  1223. c.Assert(err, check.IsNil)
  1224. c.Assert(status, check.Equals, http.StatusCreated)
  1225. var container types.ContainerCreateResponse
  1226. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1227. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1228. c.Assert(err, check.IsNil)
  1229. c.Assert(status, check.Equals, http.StatusOK)
  1230. var containerJSON types.ContainerJSON
  1231. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1232. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(1073741824))
  1233. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1234. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  1235. if !shmRegex.MatchString(out) {
  1236. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  1237. }
  1238. }
  1239. func (s *DockerSuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted(c *check.C) {
  1240. testRequires(c, DaemonIsLinux)
  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. }
  1256. // check validation is done daemon side and not only in cli
  1257. func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *check.C) {
  1258. testRequires(c, DaemonIsLinux)
  1259. config := struct {
  1260. Image string
  1261. OomScoreAdj int
  1262. }{"busybox", 1001}
  1263. name := "oomscoreadj-over"
  1264. status, b, err := sockRequest("POST", "/containers/create?name="+name, config)
  1265. c.Assert(err, check.IsNil)
  1266. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1267. expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]."
  1268. if !strings.Contains(string(b), expected) {
  1269. c.Fatalf("Expected output to contain %q, got %q", expected, string(b))
  1270. }
  1271. config = struct {
  1272. Image string
  1273. OomScoreAdj int
  1274. }{"busybox", -1001}
  1275. name = "oomscoreadj-low"
  1276. status, b, err = sockRequest("POST", "/containers/create?name="+name, config)
  1277. c.Assert(err, check.IsNil)
  1278. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1279. expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]."
  1280. if !strings.Contains(string(b), expected) {
  1281. c.Fatalf("Expected output to contain %q, got %q", expected, string(b))
  1282. }
  1283. }