docker_api_containers_test.go 46 KB

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