docker_api_containers_test.go 46 KB

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