docker_api_containers_test.go 46 KB

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