docker_api_containers_test.go 47 KB

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