docker_api_containers_test.go 49 KB

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