docker_api_containers_test.go 50 KB

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