docker_api_containers_test.go 45 KB

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