docker_api_containers_test.go 52 KB

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