docker_api_containers_test.go 46 KB

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