docker_api_containers_test.go 45 KB

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