docker_api_containers_test.go 47 KB

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