docker_api_containers_test.go 52 KB

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