docker_api_containers_test.go 44 KB

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