docker_api_containers_test.go 47 KB

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