docker_api_containers_test.go 55 KB

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