docker_api_containers_test.go 45 KB

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