docker_api_containers_test.go 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  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. func (s *DockerSuite) TestContainerApiInvalidRestartPolicyName(c *check.C) {
  588. config := `{
  589. "Image": "busybox",
  590. "HostConfig": {
  591. "RestartPolicy": {
  592. "Name": "something",
  593. "MaximumRetryCount": 0
  594. }
  595. }
  596. }`
  597. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  598. c.Assert(err, checker.IsNil)
  599. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  600. b, err := readBody(body)
  601. c.Assert(err, checker.IsNil)
  602. c.Assert(string(b[:]), checker.Contains, "invalid restart policy")
  603. }
  604. func (s *DockerSuite) TestContainerApiInvalidRestartPolicyRetryMismatch(c *check.C) {
  605. config := `{
  606. "Image": "busybox",
  607. "HostConfig": {
  608. "RestartPolicy": {
  609. "Name": "always",
  610. "MaximumRetryCount": 2
  611. }
  612. }
  613. }`
  614. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  615. c.Assert(err, checker.IsNil)
  616. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  617. b, err := readBody(body)
  618. c.Assert(err, checker.IsNil)
  619. c.Assert(string(b[:]), checker.Contains, "maximum restart count not valid with restart policy")
  620. }
  621. func (s *DockerSuite) TestContainerApiInvalidRestartPolicyPositiveRetryCount(c *check.C) {
  622. config := `{
  623. "Image": "busybox",
  624. "HostConfig": {
  625. "RestartPolicy": {
  626. "Name": "on-failure",
  627. "MaximumRetryCount": -2
  628. }
  629. }
  630. }`
  631. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  632. c.Assert(err, checker.IsNil)
  633. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  634. b, err := readBody(body)
  635. c.Assert(err, checker.IsNil)
  636. c.Assert(string(b[:]), checker.Contains, "maximum restart count must be a positive integer")
  637. }
  638. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  639. // W/o this fix a null in JSON would be parsed into a string var as "null"
  640. func (s *DockerSuite) TestContainerApiPostCreateNull(c *check.C) {
  641. // TODO Windows to Windows CI. Bit of this with alternate fields checked
  642. // can probably be ported.
  643. testRequires(c, DaemonIsLinux)
  644. config := `{
  645. "Hostname":"",
  646. "Domainname":"",
  647. "Memory":0,
  648. "MemorySwap":0,
  649. "CpuShares":0,
  650. "Cpuset":null,
  651. "AttachStdin":true,
  652. "AttachStdout":true,
  653. "AttachStderr":true,
  654. "ExposedPorts":{},
  655. "Tty":true,
  656. "OpenStdin":true,
  657. "StdinOnce":true,
  658. "Env":[],
  659. "Cmd":"ls",
  660. "Image":"busybox",
  661. "Volumes":{},
  662. "WorkingDir":"",
  663. "Entrypoint":null,
  664. "NetworkDisabled":false,
  665. "OnBuild":null}`
  666. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  667. c.Assert(err, checker.IsNil)
  668. c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
  669. b, err := readBody(body)
  670. c.Assert(err, checker.IsNil)
  671. type createResp struct {
  672. ID string
  673. }
  674. var container createResp
  675. c.Assert(json.Unmarshal(b, &container), checker.IsNil)
  676. out := inspectField(c, container.ID, "HostConfig.CpusetCpus")
  677. c.Assert(out, checker.Equals, "")
  678. outMemory := inspectField(c, container.ID, "HostConfig.Memory")
  679. c.Assert(outMemory, checker.Equals, "0")
  680. outMemorySwap := inspectField(c, container.ID, "HostConfig.MemorySwap")
  681. c.Assert(outMemorySwap, checker.Equals, "0")
  682. }
  683. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  684. // TODO Windows: Port once memory is supported
  685. testRequires(c, DaemonIsLinux)
  686. config := `{
  687. "Image": "busybox",
  688. "Cmd": "ls",
  689. "OpenStdin": true,
  690. "CpuShares": 100,
  691. "Memory": 524287
  692. }`
  693. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  694. c.Assert(err, checker.IsNil)
  695. b, err2 := readBody(body)
  696. c.Assert(err2, checker.IsNil)
  697. c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError)
  698. c.Assert(string(b), checker.Contains, "Minimum memory limit allowed is 4MB")
  699. }
  700. func (s *DockerSuite) TestContainerApiRename(c *check.C) {
  701. // TODO Windows: Debug why this sometimes fails on TP5. For now, leave disabled
  702. testRequires(c, DaemonIsLinux)
  703. out, _ := dockerCmd(c, "run", "--name", "TestContainerApiRename", "-d", "busybox", "sh")
  704. containerID := strings.TrimSpace(out)
  705. newName := "TestContainerApiRenameNew"
  706. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
  707. c.Assert(err, checker.IsNil)
  708. // 204 No Content is expected, not 200
  709. c.Assert(statusCode, checker.Equals, http.StatusNoContent)
  710. name := inspectField(c, containerID, "Name")
  711. c.Assert(name, checker.Equals, "/"+newName, check.Commentf("Failed to rename container"))
  712. }
  713. func (s *DockerSuite) TestContainerApiKill(c *check.C) {
  714. name := "test-api-kill"
  715. runSleepingContainer(c, "-i", "--name", name)
  716. status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil)
  717. c.Assert(err, checker.IsNil)
  718. c.Assert(status, checker.Equals, http.StatusNoContent)
  719. state := inspectField(c, name, "State.Running")
  720. c.Assert(state, checker.Equals, "false", check.Commentf("got wrong State from container %s: %q", name, state))
  721. }
  722. func (s *DockerSuite) TestContainerApiRestart(c *check.C) {
  723. // TODO Windows to Windows CI. This is flaky due to the timing
  724. testRequires(c, DaemonIsLinux)
  725. name := "test-api-restart"
  726. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  727. status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil)
  728. c.Assert(err, checker.IsNil)
  729. c.Assert(status, checker.Equals, http.StatusNoContent)
  730. c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5*time.Second), checker.IsNil)
  731. }
  732. func (s *DockerSuite) TestContainerApiRestartNotimeoutParam(c *check.C) {
  733. // TODO Windows to Windows CI. This is flaky due to the timing
  734. testRequires(c, DaemonIsLinux)
  735. name := "test-api-restart-no-timeout-param"
  736. out, _ := dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  737. id := strings.TrimSpace(out)
  738. c.Assert(waitRun(id), checker.IsNil)
  739. status, _, err := sockRequest("POST", "/containers/"+name+"/restart", nil)
  740. c.Assert(err, checker.IsNil)
  741. c.Assert(status, checker.Equals, http.StatusNoContent)
  742. c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5*time.Second), checker.IsNil)
  743. }
  744. func (s *DockerSuite) TestContainerApiStart(c *check.C) {
  745. name := "testing-start"
  746. config := map[string]interface{}{
  747. "Image": "busybox",
  748. "Cmd": append([]string{"/bin/sh", "-c"}, defaultSleepCommand...),
  749. "OpenStdin": true,
  750. }
  751. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  752. c.Assert(err, checker.IsNil)
  753. c.Assert(status, checker.Equals, http.StatusCreated)
  754. status, _, err = sockRequest("POST", "/containers/"+name+"/start", nil)
  755. c.Assert(err, checker.IsNil)
  756. c.Assert(status, checker.Equals, http.StatusNoContent)
  757. // second call to start should give 304
  758. status, _, err = sockRequest("POST", "/containers/"+name+"/start", nil)
  759. c.Assert(err, checker.IsNil)
  760. // TODO(tibor): figure out why this doesn't work on windows
  761. if isLocalDaemon {
  762. c.Assert(status, checker.Equals, http.StatusNotModified)
  763. }
  764. }
  765. func (s *DockerSuite) TestContainerApiStop(c *check.C) {
  766. name := "test-api-stop"
  767. runSleepingContainer(c, "-i", "--name", name)
  768. status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=30", nil)
  769. c.Assert(err, checker.IsNil)
  770. c.Assert(status, checker.Equals, http.StatusNoContent)
  771. c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil)
  772. // second call to start should give 304
  773. status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=30", nil)
  774. c.Assert(err, checker.IsNil)
  775. c.Assert(status, checker.Equals, http.StatusNotModified)
  776. }
  777. func (s *DockerSuite) TestContainerApiWait(c *check.C) {
  778. name := "test-api-wait"
  779. sleepCmd := "/bin/sleep"
  780. if daemonPlatform == "windows" {
  781. sleepCmd = "sleep"
  782. }
  783. dockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "2")
  784. status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil)
  785. c.Assert(err, checker.IsNil)
  786. c.Assert(status, checker.Equals, http.StatusOK)
  787. c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil)
  788. var waitres types.ContainerWaitResponse
  789. c.Assert(json.Unmarshal(body, &waitres), checker.IsNil)
  790. c.Assert(waitres.StatusCode, checker.Equals, 0)
  791. }
  792. func (s *DockerSuite) TestContainerApiCopyNotExistsAnyMore(c *check.C) {
  793. // TODO Windows to Windows CI. This can be ported.
  794. testRequires(c, DaemonIsLinux)
  795. name := "test-container-api-copy"
  796. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  797. postData := types.CopyConfig{
  798. Resource: "/test.txt",
  799. }
  800. status, _, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  801. c.Assert(err, checker.IsNil)
  802. c.Assert(status, checker.Equals, http.StatusNotFound)
  803. }
  804. func (s *DockerSuite) TestContainerApiCopyPre124(c *check.C) {
  805. // TODO Windows to Windows CI. This can be ported.
  806. testRequires(c, DaemonIsLinux)
  807. name := "test-container-api-copy"
  808. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  809. postData := types.CopyConfig{
  810. Resource: "/test.txt",
  811. }
  812. status, body, err := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
  813. c.Assert(err, checker.IsNil)
  814. c.Assert(status, checker.Equals, http.StatusOK)
  815. found := false
  816. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  817. h, err := tarReader.Next()
  818. if err != nil {
  819. if err == io.EOF {
  820. break
  821. }
  822. c.Fatal(err)
  823. }
  824. if h.Name == "test.txt" {
  825. found = true
  826. break
  827. }
  828. }
  829. c.Assert(found, checker.True)
  830. }
  831. func (s *DockerSuite) TestContainerApiCopyResourcePathEmptyPr124(c *check.C) {
  832. // TODO Windows to Windows CI. This can be ported.
  833. testRequires(c, DaemonIsLinux)
  834. name := "test-container-api-copy-resource-empty"
  835. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  836. postData := types.CopyConfig{
  837. Resource: "",
  838. }
  839. status, body, err := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
  840. c.Assert(err, checker.IsNil)
  841. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  842. c.Assert(string(body), checker.Matches, "Path cannot be empty\n")
  843. }
  844. func (s *DockerSuite) TestContainerApiCopyResourcePathNotFoundPre124(c *check.C) {
  845. // TODO Windows to Windows CI. This can be ported.
  846. testRequires(c, DaemonIsLinux)
  847. name := "test-container-api-copy-resource-not-found"
  848. dockerCmd(c, "run", "--name", name, "busybox")
  849. postData := types.CopyConfig{
  850. Resource: "/notexist",
  851. }
  852. status, body, err := sockRequest("POST", "/v1.23/containers/"+name+"/copy", postData)
  853. c.Assert(err, checker.IsNil)
  854. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  855. c.Assert(string(body), checker.Matches, "Could not find the file /notexist in container "+name+"\n")
  856. }
  857. func (s *DockerSuite) TestContainerApiCopyContainerNotFoundPr124(c *check.C) {
  858. postData := types.CopyConfig{
  859. Resource: "/something",
  860. }
  861. status, _, err := sockRequest("POST", "/v1.23/containers/notexists/copy", postData)
  862. c.Assert(err, checker.IsNil)
  863. c.Assert(status, checker.Equals, http.StatusNotFound)
  864. }
  865. func (s *DockerSuite) TestContainerApiDelete(c *check.C) {
  866. out, _ := runSleepingContainer(c)
  867. id := strings.TrimSpace(out)
  868. c.Assert(waitRun(id), checker.IsNil)
  869. dockerCmd(c, "stop", id)
  870. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  871. c.Assert(err, checker.IsNil)
  872. c.Assert(status, checker.Equals, http.StatusNoContent)
  873. }
  874. func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) {
  875. status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
  876. c.Assert(err, checker.IsNil)
  877. c.Assert(status, checker.Equals, http.StatusNotFound)
  878. c.Assert(getErrorMessage(c, body), checker.Matches, "No such container: doesnotexist")
  879. }
  880. func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) {
  881. out, _ := runSleepingContainer(c)
  882. id := strings.TrimSpace(out)
  883. c.Assert(waitRun(id), checker.IsNil)
  884. status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
  885. c.Assert(err, checker.IsNil)
  886. c.Assert(status, checker.Equals, http.StatusNoContent)
  887. }
  888. func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) {
  889. // Windows does not support links
  890. testRequires(c, DaemonIsLinux)
  891. out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top")
  892. id := strings.TrimSpace(out)
  893. c.Assert(waitRun(id), checker.IsNil)
  894. out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  895. id2 := strings.TrimSpace(out)
  896. c.Assert(waitRun(id2), checker.IsNil)
  897. links := inspectFieldJSON(c, id2, "HostConfig.Links")
  898. c.Assert(links, checker.Equals, "[\"/tlink1:/tlink2/tlink1\"]", check.Commentf("expected to have links between containers"))
  899. status, b, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
  900. c.Assert(err, check.IsNil)
  901. c.Assert(status, check.Equals, http.StatusNoContent, check.Commentf(string(b)))
  902. linksPostRm := inspectFieldJSON(c, id2, "HostConfig.Links")
  903. c.Assert(linksPostRm, checker.Equals, "null", check.Commentf("call to api deleteContainer links should have removed the specified links"))
  904. }
  905. func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) {
  906. out, _ := runSleepingContainer(c)
  907. id := strings.TrimSpace(out)
  908. c.Assert(waitRun(id), checker.IsNil)
  909. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  910. c.Assert(err, checker.IsNil)
  911. c.Assert(status, checker.Equals, http.StatusConflict)
  912. }
  913. func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) {
  914. testRequires(c, SameHostDaemon)
  915. vol := "/testvolume"
  916. if daemonPlatform == "windows" {
  917. vol = `c:\testvolume`
  918. }
  919. out, _ := runSleepingContainer(c, "-v", vol)
  920. id := strings.TrimSpace(out)
  921. c.Assert(waitRun(id), checker.IsNil)
  922. source, err := inspectMountSourceField(id, vol)
  923. _, err = os.Stat(source)
  924. c.Assert(err, checker.IsNil)
  925. status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
  926. c.Assert(err, checker.IsNil)
  927. c.Assert(status, checker.Equals, http.StatusNoContent)
  928. _, err = os.Stat(source)
  929. c.Assert(os.IsNotExist(err), checker.True, check.Commentf("expected to get ErrNotExist error, got %v", err))
  930. }
  931. // Regression test for https://github.com/docker/docker/issues/6231
  932. func (s *DockerSuite) TestContainerApiChunkedEncoding(c *check.C) {
  933. // TODO Windows CI: This can be ported
  934. testRequires(c, DaemonIsLinux)
  935. conn, err := sockConn(time.Duration(10*time.Second), "")
  936. c.Assert(err, checker.IsNil)
  937. client := httputil.NewClientConn(conn, nil)
  938. defer client.Close()
  939. config := map[string]interface{}{
  940. "Image": "busybox",
  941. "Cmd": append([]string{"/bin/sh", "-c"}, defaultSleepCommand...),
  942. "OpenStdin": true,
  943. }
  944. b, err := json.Marshal(config)
  945. c.Assert(err, checker.IsNil)
  946. req, err := http.NewRequest("POST", "/containers/create", bytes.NewBuffer(b))
  947. c.Assert(err, checker.IsNil)
  948. req.Header.Set("Content-Type", "application/json")
  949. // This is a cheat to make the http request do chunked encoding
  950. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  951. // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
  952. req.ContentLength = -1
  953. resp, err := client.Do(req)
  954. c.Assert(err, checker.IsNil, check.Commentf("error creating container with chunked encoding"))
  955. resp.Body.Close()
  956. c.Assert(resp.StatusCode, checker.Equals, http.StatusCreated)
  957. }
  958. func (s *DockerSuite) TestContainerApiPostContainerStop(c *check.C) {
  959. out, _ := runSleepingContainer(c)
  960. containerID := strings.TrimSpace(out)
  961. c.Assert(waitRun(containerID), checker.IsNil)
  962. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/stop", nil)
  963. c.Assert(err, checker.IsNil)
  964. // 204 No Content is expected, not 200
  965. c.Assert(statusCode, checker.Equals, http.StatusNoContent)
  966. c.Assert(waitInspect(containerID, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil)
  967. }
  968. // #14170
  969. func (s *DockerSuite) TestPostContainerApiCreateWithStringOrSliceEntrypoint(c *check.C) {
  970. config := struct {
  971. Image string
  972. Entrypoint string
  973. Cmd []string
  974. }{"busybox", "echo", []string{"hello", "world"}}
  975. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  976. c.Assert(err, checker.IsNil)
  977. out, _ := dockerCmd(c, "start", "-a", "echotest")
  978. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  979. config2 := struct {
  980. Image string
  981. Entrypoint []string
  982. Cmd []string
  983. }{"busybox", []string{"echo"}, []string{"hello", "world"}}
  984. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  985. c.Assert(err, checker.IsNil)
  986. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  987. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  988. }
  989. // #14170
  990. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) {
  991. config := struct {
  992. Image string
  993. Entrypoint string
  994. Cmd string
  995. }{"busybox", "echo", "hello world"}
  996. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  997. c.Assert(err, checker.IsNil)
  998. out, _ := dockerCmd(c, "start", "-a", "echotest")
  999. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1000. config2 := struct {
  1001. Image string
  1002. Cmd []string
  1003. }{"busybox", []string{"echo", "hello", "world"}}
  1004. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  1005. c.Assert(err, checker.IsNil)
  1006. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  1007. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1008. }
  1009. // regression #14318
  1010. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *check.C) {
  1011. // Windows doesn't support CapAdd/CapDrop
  1012. testRequires(c, DaemonIsLinux)
  1013. config := struct {
  1014. Image string
  1015. CapAdd string
  1016. CapDrop string
  1017. }{"busybox", "NET_ADMIN", "SYS_ADMIN"}
  1018. status, _, err := sockRequest("POST", "/containers/create?name=capaddtest0", config)
  1019. c.Assert(err, checker.IsNil)
  1020. c.Assert(status, checker.Equals, http.StatusCreated)
  1021. config2 := struct {
  1022. Image string
  1023. CapAdd []string
  1024. CapDrop []string
  1025. }{"busybox", []string{"NET_ADMIN", "SYS_ADMIN"}, []string{"SETGID"}}
  1026. status, _, err = sockRequest("POST", "/containers/create?name=capaddtest1", config2)
  1027. c.Assert(err, checker.IsNil)
  1028. c.Assert(status, checker.Equals, http.StatusCreated)
  1029. }
  1030. // #14915
  1031. func (s *DockerSuite) TestContainerApiCreateNoHostConfig118(c *check.C) {
  1032. config := struct {
  1033. Image string
  1034. }{"busybox"}
  1035. status, _, err := sockRequest("POST", "/v1.18/containers/create", config)
  1036. c.Assert(err, checker.IsNil)
  1037. c.Assert(status, checker.Equals, http.StatusCreated)
  1038. }
  1039. // Ensure an error occurs when you have a container read-only rootfs but you
  1040. // extract an archive to a symlink in a writable volume which points to a
  1041. // directory outside of the volume.
  1042. func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(c *check.C) {
  1043. // Windows does not support read-only rootfs
  1044. // Requires local volume mount bind.
  1045. // --read-only + userns has remount issues
  1046. testRequires(c, SameHostDaemon, NotUserNamespace, DaemonIsLinux)
  1047. testVol := getTestDir(c, "test-put-container-archive-err-symlink-in-volume-to-read-only-rootfs-")
  1048. defer os.RemoveAll(testVol)
  1049. makeTestContentInDir(c, testVol)
  1050. cID := makeTestContainer(c, testContainerOptions{
  1051. readOnly: true,
  1052. volumes: defaultVolumes(testVol), // Our bind mount is at /vol2
  1053. })
  1054. defer deleteContainer(cID)
  1055. // Attempt to extract to a symlink in the volume which points to a
  1056. // directory outside the volume. This should cause an error because the
  1057. // rootfs is read-only.
  1058. query := make(url.Values, 1)
  1059. query.Set("path", "/vol2/symlinkToAbsDir")
  1060. urlPath := fmt.Sprintf("/v1.20/containers/%s/archive?%s", cID, query.Encode())
  1061. statusCode, body, err := sockRequest("PUT", urlPath, nil)
  1062. c.Assert(err, checker.IsNil)
  1063. if !isCpCannotCopyReadOnly(fmt.Errorf(string(body))) {
  1064. c.Fatalf("expected ErrContainerRootfsReadonly error, but got %d: %s", statusCode, string(body))
  1065. }
  1066. }
  1067. func (s *DockerSuite) TestContainerApiGetContainersJSONEmpty(c *check.C) {
  1068. status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  1069. c.Assert(err, checker.IsNil)
  1070. c.Assert(status, checker.Equals, http.StatusOK)
  1071. c.Assert(string(body), checker.Equals, "[]\n")
  1072. }
  1073. func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) {
  1074. // Not supported on Windows
  1075. testRequires(c, DaemonIsLinux)
  1076. c1 := struct {
  1077. Image string
  1078. CpusetCpus string
  1079. }{"busybox", "1-42,,"}
  1080. name := "wrong-cpuset-cpus"
  1081. status, body, err := sockRequest("POST", "/containers/create?name="+name, c1)
  1082. c.Assert(err, checker.IsNil)
  1083. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  1084. expected := "Invalid value 1-42,, for cpuset cpus"
  1085. c.Assert(getErrorMessage(c, body), checker.Equals, expected)
  1086. c2 := struct {
  1087. Image string
  1088. CpusetMems string
  1089. }{"busybox", "42-3,1--"}
  1090. name = "wrong-cpuset-mems"
  1091. status, body, err = sockRequest("POST", "/containers/create?name="+name, c2)
  1092. c.Assert(err, checker.IsNil)
  1093. c.Assert(status, checker.Equals, http.StatusInternalServerError)
  1094. expected = "Invalid value 42-3,1-- for cpuset mems"
  1095. c.Assert(getErrorMessage(c, body), checker.Equals, expected)
  1096. }
  1097. func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) {
  1098. // ShmSize is not supported on Windows
  1099. testRequires(c, DaemonIsLinux)
  1100. config := map[string]interface{}{
  1101. "Image": "busybox",
  1102. "HostConfig": map[string]interface{}{"ShmSize": -1},
  1103. }
  1104. status, body, err := sockRequest("POST", "/containers/create", config)
  1105. c.Assert(err, check.IsNil)
  1106. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1107. c.Assert(getErrorMessage(c, body), checker.Contains, "SHM size can not be less than 0")
  1108. }
  1109. func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check.C) {
  1110. // ShmSize is not supported on Windows
  1111. testRequires(c, DaemonIsLinux)
  1112. var defaultSHMSize int64 = 67108864
  1113. config := map[string]interface{}{
  1114. "Image": "busybox",
  1115. "Cmd": "mount",
  1116. }
  1117. status, body, err := sockRequest("POST", "/containers/create", config)
  1118. c.Assert(err, check.IsNil)
  1119. c.Assert(status, check.Equals, http.StatusCreated)
  1120. var container types.ContainerCreateResponse
  1121. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1122. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1123. c.Assert(err, check.IsNil)
  1124. c.Assert(status, check.Equals, http.StatusOK)
  1125. var containerJSON types.ContainerJSON
  1126. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1127. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, defaultSHMSize)
  1128. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1129. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1130. if !shmRegexp.MatchString(out) {
  1131. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1132. }
  1133. }
  1134. func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *check.C) {
  1135. // ShmSize is not supported on Windows
  1136. testRequires(c, DaemonIsLinux)
  1137. config := map[string]interface{}{
  1138. "Image": "busybox",
  1139. "HostConfig": map[string]interface{}{},
  1140. "Cmd": "mount",
  1141. }
  1142. status, body, err := sockRequest("POST", "/containers/create", config)
  1143. c.Assert(err, check.IsNil)
  1144. c.Assert(status, check.Equals, http.StatusCreated)
  1145. var container types.ContainerCreateResponse
  1146. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1147. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1148. c.Assert(err, check.IsNil)
  1149. c.Assert(status, check.Equals, http.StatusOK)
  1150. var containerJSON types.ContainerJSON
  1151. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1152. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(67108864))
  1153. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1154. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1155. if !shmRegexp.MatchString(out) {
  1156. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1157. }
  1158. }
  1159. func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *check.C) {
  1160. // ShmSize is not supported on Windows
  1161. testRequires(c, DaemonIsLinux)
  1162. config := map[string]interface{}{
  1163. "Image": "busybox",
  1164. "Cmd": "mount",
  1165. "HostConfig": map[string]interface{}{"ShmSize": 1073741824},
  1166. }
  1167. status, body, err := sockRequest("POST", "/containers/create", config)
  1168. c.Assert(err, check.IsNil)
  1169. c.Assert(status, check.Equals, http.StatusCreated)
  1170. var container types.ContainerCreateResponse
  1171. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1172. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1173. c.Assert(err, check.IsNil)
  1174. c.Assert(status, check.Equals, http.StatusOK)
  1175. var containerJSON types.ContainerJSON
  1176. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1177. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(1073741824))
  1178. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1179. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  1180. if !shmRegex.MatchString(out) {
  1181. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  1182. }
  1183. }
  1184. func (s *DockerSuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted(c *check.C) {
  1185. // Swappiness is not supported on Windows
  1186. testRequires(c, DaemonIsLinux)
  1187. config := map[string]interface{}{
  1188. "Image": "busybox",
  1189. }
  1190. status, body, err := sockRequest("POST", "/containers/create", config)
  1191. c.Assert(err, check.IsNil)
  1192. c.Assert(status, check.Equals, http.StatusCreated)
  1193. var container types.ContainerCreateResponse
  1194. c.Assert(json.Unmarshal(body, &container), check.IsNil)
  1195. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  1196. c.Assert(err, check.IsNil)
  1197. c.Assert(status, check.Equals, http.StatusOK)
  1198. var containerJSON types.ContainerJSON
  1199. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  1200. c.Assert(*containerJSON.HostConfig.MemorySwappiness, check.Equals, int64(-1))
  1201. }
  1202. // check validation is done daemon side and not only in cli
  1203. func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *check.C) {
  1204. // OomScoreAdj is not supported on Windows
  1205. testRequires(c, DaemonIsLinux)
  1206. config := struct {
  1207. Image string
  1208. OomScoreAdj int
  1209. }{"busybox", 1001}
  1210. name := "oomscoreadj-over"
  1211. status, b, err := sockRequest("POST", "/containers/create?name="+name, config)
  1212. c.Assert(err, check.IsNil)
  1213. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1214. expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]"
  1215. msg := getErrorMessage(c, b)
  1216. if !strings.Contains(msg, expected) {
  1217. c.Fatalf("Expected output to contain %q, got %q", expected, msg)
  1218. }
  1219. config = struct {
  1220. Image string
  1221. OomScoreAdj int
  1222. }{"busybox", -1001}
  1223. name = "oomscoreadj-low"
  1224. status, b, err = sockRequest("POST", "/containers/create?name="+name, config)
  1225. c.Assert(err, check.IsNil)
  1226. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1227. expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]"
  1228. msg = getErrorMessage(c, b)
  1229. if !strings.Contains(msg, expected) {
  1230. c.Fatalf("Expected output to contain %q, got %q", expected, msg)
  1231. }
  1232. }
  1233. // test case for #22210 where an empty container name caused panic.
  1234. func (s *DockerSuite) TestContainerApiDeleteWithEmptyName(c *check.C) {
  1235. status, out, err := sockRequest("DELETE", "/containers/", nil)
  1236. c.Assert(err, checker.IsNil)
  1237. c.Assert(status, checker.Equals, http.StatusBadRequest)
  1238. c.Assert(string(out), checker.Contains, "No container name or ID supplied")
  1239. }