docker_api_containers_test.go 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  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, b, 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. b.Close()
  451. }
  452. func (s *DockerSuite) TestBuildApiRemoteTarballContextWithCustomDockerfile(c *check.C) {
  453. buffer := new(bytes.Buffer)
  454. tw := tar.NewWriter(buffer)
  455. defer tw.Close()
  456. dockerfile := []byte(`FROM busybox
  457. RUN echo 'wrong'`)
  458. if err := tw.WriteHeader(&tar.Header{
  459. Name: "Dockerfile",
  460. Size: int64(len(dockerfile)),
  461. }); err != nil {
  462. c.Fatalf("failed to write tar file header: %v", err)
  463. }
  464. if _, err := tw.Write(dockerfile); err != nil {
  465. c.Fatalf("failed to write tar file content: %v", err)
  466. }
  467. custom := []byte(`FROM busybox
  468. RUN echo 'right'
  469. `)
  470. if err := tw.WriteHeader(&tar.Header{
  471. Name: "custom",
  472. Size: int64(len(custom)),
  473. }); err != nil {
  474. c.Fatalf("failed to write tar file header: %v", err)
  475. }
  476. if _, err := tw.Write(custom); err != nil {
  477. c.Fatalf("failed to write tar file content: %v", err)
  478. }
  479. if err := tw.Close(); err != nil {
  480. c.Fatalf("failed to close tar archive: %v", err)
  481. }
  482. server, err := fakeBinaryStorage(map[string]*bytes.Buffer{
  483. "testT.tar": buffer,
  484. })
  485. c.Assert(err, check.IsNil)
  486. defer server.Close()
  487. url := "/build?dockerfile=custom&remote=" + server.URL() + "/testT.tar"
  488. res, body, err := sockRequestRaw("POST", url, nil, "application/tar")
  489. c.Assert(err, check.IsNil)
  490. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  491. defer body.Close()
  492. content, err := readBody(body)
  493. c.Assert(err, check.IsNil)
  494. if strings.Contains(string(content), "wrong") {
  495. c.Fatalf("Build used the wrong dockerfile.")
  496. }
  497. }
  498. func (s *DockerSuite) TestBuildApiLowerDockerfile(c *check.C) {
  499. git, err := newFakeGit("repo", map[string]string{
  500. "dockerfile": `FROM busybox
  501. RUN echo from dockerfile`,
  502. }, false)
  503. if err != nil {
  504. c.Fatal(err)
  505. }
  506. defer git.Close()
  507. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  508. c.Assert(err, check.IsNil)
  509. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  510. buf, err := readBody(body)
  511. if err != nil {
  512. c.Fatal(err)
  513. }
  514. out := string(buf)
  515. if !strings.Contains(out, "from dockerfile") {
  516. c.Fatalf("Incorrect output: %s", out)
  517. }
  518. }
  519. func (s *DockerSuite) TestBuildApiBuildGitWithF(c *check.C) {
  520. git, err := newFakeGit("repo", map[string]string{
  521. "baz": `FROM busybox
  522. RUN echo from baz`,
  523. "Dockerfile": `FROM busybox
  524. RUN echo from Dockerfile`,
  525. }, false)
  526. if err != nil {
  527. c.Fatal(err)
  528. }
  529. defer git.Close()
  530. // Make sure it tries to 'dockerfile' query param value
  531. res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
  532. c.Assert(err, check.IsNil)
  533. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  534. buf, err := readBody(body)
  535. if err != nil {
  536. c.Fatal(err)
  537. }
  538. out := string(buf)
  539. if !strings.Contains(out, "from baz") {
  540. c.Fatalf("Incorrect output: %s", out)
  541. }
  542. }
  543. func (s *DockerSuite) TestBuildApiDoubleDockerfile(c *check.C) {
  544. testRequires(c, UnixCli) // dockerfile overwrites Dockerfile on Windows
  545. git, err := newFakeGit("repo", map[string]string{
  546. "Dockerfile": `FROM busybox
  547. RUN echo from Dockerfile`,
  548. "dockerfile": `FROM busybox
  549. RUN echo from dockerfile`,
  550. }, false)
  551. if err != nil {
  552. c.Fatal(err)
  553. }
  554. defer git.Close()
  555. // Make sure it tries to 'dockerfile' query param value
  556. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  557. c.Assert(err, check.IsNil)
  558. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  559. buf, err := readBody(body)
  560. if err != nil {
  561. c.Fatal(err)
  562. }
  563. out := string(buf)
  564. if !strings.Contains(out, "from Dockerfile") {
  565. c.Fatalf("Incorrect output: %s", out)
  566. }
  567. }
  568. func (s *DockerSuite) TestBuildApiDockerfileSymlink(c *check.C) {
  569. // Test to make sure we stop people from trying to leave the
  570. // build context when specifying a symlink as the path to the dockerfile
  571. buffer := new(bytes.Buffer)
  572. tw := tar.NewWriter(buffer)
  573. defer tw.Close()
  574. if err := tw.WriteHeader(&tar.Header{
  575. Name: "Dockerfile",
  576. Typeflag: tar.TypeSymlink,
  577. Linkname: "/etc/passwd",
  578. }); err != nil {
  579. c.Fatalf("failed to write tar file header: %v", err)
  580. }
  581. if err := tw.Close(); err != nil {
  582. c.Fatalf("failed to close tar archive: %v", err)
  583. }
  584. res, body, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  585. c.Assert(err, check.IsNil)
  586. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  587. out, err := readBody(body)
  588. if err != nil {
  589. c.Fatal(err)
  590. }
  591. // The reason the error is "Cannot locate specified Dockerfile" is because
  592. // in the builder, the symlink is resolved within the context, therefore
  593. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  594. // a nonexistent file.
  595. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  596. c.Fatalf("Didn't complain about leaving build context: %s", out)
  597. }
  598. }
  599. // #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
  600. func (s *DockerSuite) TestPostContainerBindNormalVolume(c *check.C) {
  601. dockerCmd(c, "create", "-v", "/foo", "--name=one", "busybox")
  602. fooDir, err := inspectMountSourceField("one", "/foo")
  603. if err != nil {
  604. c.Fatal(err)
  605. }
  606. dockerCmd(c, "create", "-v", "/foo", "--name=two", "busybox")
  607. bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
  608. status, _, err := sockRequest("POST", "/containers/two/start", bindSpec)
  609. c.Assert(err, check.IsNil)
  610. c.Assert(status, check.Equals, http.StatusNoContent)
  611. fooDir2, err := inspectMountSourceField("two", "/foo")
  612. if err != nil {
  613. c.Fatal(err)
  614. }
  615. if fooDir2 != fooDir {
  616. c.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2)
  617. }
  618. }
  619. func (s *DockerSuite) TestContainerApiPause(c *check.C) {
  620. defer unpauseAllContainers()
  621. out, _ := dockerCmd(c, "run", "-d", "busybox", "sleep", "30")
  622. ContainerID := strings.TrimSpace(out)
  623. status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil)
  624. c.Assert(err, check.IsNil)
  625. c.Assert(status, check.Equals, http.StatusNoContent)
  626. pausedContainers, err := getSliceOfPausedContainers()
  627. if err != nil {
  628. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  629. }
  630. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  631. c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  632. }
  633. status, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil)
  634. c.Assert(err, check.IsNil)
  635. c.Assert(status, check.Equals, http.StatusNoContent)
  636. pausedContainers, err = getSliceOfPausedContainers()
  637. if err != nil {
  638. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  639. }
  640. if pausedContainers != nil {
  641. c.Fatalf("There should be no paused container.")
  642. }
  643. }
  644. func (s *DockerSuite) TestContainerApiTop(c *check.C) {
  645. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top")
  646. id := strings.TrimSpace(string(out))
  647. if err := waitRun(id); err != nil {
  648. c.Fatal(err)
  649. }
  650. type topResp struct {
  651. Titles []string
  652. Processes [][]string
  653. }
  654. var top topResp
  655. status, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil)
  656. c.Assert(err, check.IsNil)
  657. c.Assert(status, check.Equals, http.StatusOK)
  658. if err := json.Unmarshal(b, &top); err != nil {
  659. c.Fatal(err)
  660. }
  661. if len(top.Titles) != 11 {
  662. c.Fatalf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles)
  663. }
  664. if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
  665. c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
  666. }
  667. if len(top.Processes) != 2 {
  668. c.Fatalf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes)
  669. }
  670. if top.Processes[0][10] != "/bin/sh -c top" {
  671. c.Fatalf("expected `/bin/sh -c top`, found: %s", top.Processes[0][10])
  672. }
  673. if top.Processes[1][10] != "top" {
  674. c.Fatalf("expected `top`, found: %s", top.Processes[1][10])
  675. }
  676. }
  677. func (s *DockerSuite) TestContainerApiCommit(c *check.C) {
  678. cName := "testapicommit"
  679. dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
  680. name := "TestContainerApiCommit"
  681. status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil)
  682. c.Assert(err, check.IsNil)
  683. c.Assert(status, check.Equals, http.StatusCreated)
  684. type resp struct {
  685. ID string
  686. }
  687. var img resp
  688. if err := json.Unmarshal(b, &img); err != nil {
  689. c.Fatal(err)
  690. }
  691. cmd, err := inspectField(img.ID, "Config.Cmd")
  692. if err != nil {
  693. c.Fatal(err)
  694. }
  695. if cmd != "{[/bin/sh -c touch /test]}" {
  696. c.Fatalf("got wrong Cmd from commit: %q", cmd)
  697. }
  698. // sanity check, make sure the image is what we think it is
  699. dockerCmd(c, "run", img.ID, "ls", "/test")
  700. }
  701. func (s *DockerSuite) TestContainerApiCommitWithLabelInConfig(c *check.C) {
  702. cName := "testapicommitwithconfig"
  703. dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
  704. config := map[string]interface{}{
  705. "Labels": map[string]string{"key1": "value1", "key2": "value2"},
  706. }
  707. name := "TestContainerApiCommitWithConfig"
  708. status, b, err := sockRequest("POST", "/commit?repo="+name+"&container="+cName, config)
  709. c.Assert(err, check.IsNil)
  710. c.Assert(status, check.Equals, http.StatusCreated)
  711. type resp struct {
  712. ID string
  713. }
  714. var img resp
  715. if err := json.Unmarshal(b, &img); err != nil {
  716. c.Fatal(err)
  717. }
  718. label1, err := inspectFieldMap(img.ID, "Config.Labels", "key1")
  719. if err != nil {
  720. c.Fatal(err)
  721. }
  722. c.Assert(label1, check.Equals, "value1")
  723. label2, err := inspectFieldMap(img.ID, "Config.Labels", "key2")
  724. if err != nil {
  725. c.Fatal(err)
  726. }
  727. c.Assert(label2, check.Equals, "value2")
  728. cmd, err := inspectField(img.ID, "Config.Cmd")
  729. if err != nil {
  730. c.Fatal(err)
  731. }
  732. if cmd != "{[/bin/sh -c touch /test]}" {
  733. c.Fatalf("got wrong Cmd from commit: %q", cmd)
  734. }
  735. // sanity check, make sure the image is what we think it is
  736. dockerCmd(c, "run", img.ID, "ls", "/test")
  737. }
  738. func (s *DockerSuite) TestContainerApiBadPort(c *check.C) {
  739. config := map[string]interface{}{
  740. "Image": "busybox",
  741. "Cmd": []string{"/bin/sh", "-c", "echo test"},
  742. "PortBindings": map[string]interface{}{
  743. "8080/tcp": []map[string]interface{}{
  744. {
  745. "HostIP": "",
  746. "HostPort": "aa80",
  747. },
  748. },
  749. },
  750. }
  751. jsonData := bytes.NewBuffer(nil)
  752. json.NewEncoder(jsonData).Encode(config)
  753. status, b, err := sockRequest("POST", "/containers/create", config)
  754. c.Assert(err, check.IsNil)
  755. c.Assert(status, check.Equals, http.StatusInternalServerError)
  756. if strings.TrimSpace(string(b)) != `Invalid port specification: "aa80"` {
  757. c.Fatalf("Incorrect error msg: %s", string(b))
  758. }
  759. }
  760. func (s *DockerSuite) TestContainerApiCreate(c *check.C) {
  761. config := map[string]interface{}{
  762. "Image": "busybox",
  763. "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"},
  764. }
  765. status, b, err := sockRequest("POST", "/containers/create", config)
  766. c.Assert(err, check.IsNil)
  767. c.Assert(status, check.Equals, http.StatusCreated)
  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, _ := dockerCmd(c, "start", "-a", container.ID)
  776. if strings.TrimSpace(out) != "/test" {
  777. c.Fatalf("expected output `/test`, got %q", out)
  778. }
  779. }
  780. func (s *DockerSuite) TestContainerApiCreateEmptyConfig(c *check.C) {
  781. config := map[string]interface{}{}
  782. status, b, err := sockRequest("POST", "/containers/create", config)
  783. c.Assert(err, check.IsNil)
  784. c.Assert(status, check.Equals, http.StatusInternalServerError)
  785. expected := "Config cannot be empty in order to create a container\n"
  786. if body := string(b); body != expected {
  787. c.Fatalf("Expected to get %q, got %q", expected, body)
  788. }
  789. }
  790. func (s *DockerSuite) TestContainerApiCreateWithHostName(c *check.C) {
  791. hostName := "test-host"
  792. config := map[string]interface{}{
  793. "Image": "busybox",
  794. "Hostname": hostName,
  795. }
  796. status, body, err := sockRequest("POST", "/containers/create", config)
  797. c.Assert(err, check.IsNil)
  798. c.Assert(status, check.Equals, http.StatusCreated)
  799. var container types.ContainerCreateResponse
  800. if err := json.Unmarshal(body, &container); err != nil {
  801. c.Fatal(err)
  802. }
  803. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  804. c.Assert(err, check.IsNil)
  805. c.Assert(status, check.Equals, http.StatusOK)
  806. var containerJSON types.ContainerJSON
  807. if err := json.Unmarshal(body, &containerJSON); err != nil {
  808. c.Fatal(err)
  809. }
  810. if containerJSON.Config.Hostname != hostName {
  811. c.Fatalf("Mismatched Hostname, Expected %s, Actual: %s ", hostName, containerJSON.Config.Hostname)
  812. }
  813. }
  814. func (s *DockerSuite) TestContainerApiCreateWithDomainName(c *check.C) {
  815. domainName := "test-domain"
  816. config := map[string]interface{}{
  817. "Image": "busybox",
  818. "Domainname": domainName,
  819. }
  820. status, body, err := sockRequest("POST", "/containers/create", config)
  821. c.Assert(err, check.IsNil)
  822. c.Assert(status, check.Equals, http.StatusCreated)
  823. var container types.ContainerCreateResponse
  824. if err := json.Unmarshal(body, &container); err != nil {
  825. c.Fatal(err)
  826. }
  827. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  828. c.Assert(err, check.IsNil)
  829. c.Assert(status, check.Equals, http.StatusOK)
  830. var containerJSON types.ContainerJSON
  831. if err := json.Unmarshal(body, &containerJSON); err != nil {
  832. c.Fatal(err)
  833. }
  834. if containerJSON.Config.Domainname != domainName {
  835. c.Fatalf("Mismatched Domainname, Expected %s, Actual: %s ", domainName, containerJSON.Config.Domainname)
  836. }
  837. }
  838. func (s *DockerSuite) TestContainerApiCreateNetworkMode(c *check.C) {
  839. UtilCreateNetworkMode(c, "host")
  840. UtilCreateNetworkMode(c, "bridge")
  841. UtilCreateNetworkMode(c, "container:web1")
  842. }
  843. func UtilCreateNetworkMode(c *check.C, networkMode string) {
  844. config := map[string]interface{}{
  845. "Image": "busybox",
  846. "HostConfig": map[string]interface{}{"NetworkMode": networkMode},
  847. }
  848. status, body, err := sockRequest("POST", "/containers/create", config)
  849. c.Assert(err, check.IsNil)
  850. c.Assert(status, check.Equals, http.StatusCreated)
  851. var container types.ContainerCreateResponse
  852. if err := json.Unmarshal(body, &container); err != nil {
  853. c.Fatal(err)
  854. }
  855. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  856. c.Assert(err, check.IsNil)
  857. c.Assert(status, check.Equals, http.StatusOK)
  858. var containerJSON types.ContainerJSON
  859. if err := json.Unmarshal(body, &containerJSON); err != nil {
  860. c.Fatal(err)
  861. }
  862. if containerJSON.HostConfig.NetworkMode != runconfig.NetworkMode(networkMode) {
  863. c.Fatalf("Mismatched NetworkMode, Expected %s, Actual: %s ", networkMode, containerJSON.HostConfig.NetworkMode)
  864. }
  865. }
  866. func (s *DockerSuite) TestContainerApiCreateWithCpuSharesCpuset(c *check.C) {
  867. config := map[string]interface{}{
  868. "Image": "busybox",
  869. "CpuShares": 512,
  870. "CpusetCpus": "0,1",
  871. }
  872. status, body, err := sockRequest("POST", "/containers/create", config)
  873. c.Assert(err, check.IsNil)
  874. c.Assert(status, check.Equals, http.StatusCreated)
  875. var container types.ContainerCreateResponse
  876. if err := json.Unmarshal(body, &container); err != nil {
  877. c.Fatal(err)
  878. }
  879. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  880. c.Assert(err, check.IsNil)
  881. c.Assert(status, check.Equals, http.StatusOK)
  882. var containerJSON types.ContainerJSON
  883. c.Assert(json.Unmarshal(body, &containerJSON), check.IsNil)
  884. out, err := inspectField(containerJSON.Id, "HostConfig.CpuShares")
  885. c.Assert(err, check.IsNil)
  886. c.Assert(out, check.Equals, "512")
  887. outCpuset, errCpuset := inspectField(containerJSON.Id, "HostConfig.CpusetCpus")
  888. c.Assert(errCpuset, check.IsNil, check.Commentf("Output: %s", outCpuset))
  889. c.Assert(outCpuset, check.Equals, "0,1")
  890. }
  891. func (s *DockerSuite) TestContainerApiVerifyHeader(c *check.C) {
  892. config := map[string]interface{}{
  893. "Image": "busybox",
  894. }
  895. create := func(ct string) (*http.Response, io.ReadCloser, error) {
  896. jsonData := bytes.NewBuffer(nil)
  897. if err := json.NewEncoder(jsonData).Encode(config); err != nil {
  898. c.Fatal(err)
  899. }
  900. return sockRequestRaw("POST", "/containers/create", jsonData, ct)
  901. }
  902. // Try with no content-type
  903. res, body, err := create("")
  904. c.Assert(err, check.IsNil)
  905. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  906. body.Close()
  907. // Try with wrong content-type
  908. res, body, err = create("application/xml")
  909. c.Assert(err, check.IsNil)
  910. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  911. body.Close()
  912. // now application/json
  913. res, body, err = create("application/json")
  914. c.Assert(err, check.IsNil)
  915. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  916. body.Close()
  917. }
  918. //Issue 14230. daemon should return 500 for invalid port syntax
  919. func (s *DockerSuite) TestContainerApiInvalidPortSyntax(c *check.C) {
  920. config := `{
  921. "Image": "busybox",
  922. "HostConfig": {
  923. "PortBindings": {
  924. "19039;1230": [
  925. {}
  926. ]
  927. }
  928. }
  929. }`
  930. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  931. c.Assert(err, check.IsNil)
  932. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  933. b, err := readBody(body)
  934. if err != nil {
  935. c.Fatal(err)
  936. }
  937. c.Assert(strings.Contains(string(b[:]), "Invalid port"), check.Equals, true)
  938. }
  939. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  940. // W/o this fix a null in JSON would be parsed into a string var as "null"
  941. func (s *DockerSuite) TestContainerApiPostCreateNull(c *check.C) {
  942. config := `{
  943. "Hostname":"",
  944. "Domainname":"",
  945. "Memory":0,
  946. "MemorySwap":0,
  947. "CpuShares":0,
  948. "Cpuset":null,
  949. "AttachStdin":true,
  950. "AttachStdout":true,
  951. "AttachStderr":true,
  952. "ExposedPorts":{},
  953. "Tty":true,
  954. "OpenStdin":true,
  955. "StdinOnce":true,
  956. "Env":[],
  957. "Cmd":"ls",
  958. "Image":"busybox",
  959. "Volumes":{},
  960. "WorkingDir":"",
  961. "Entrypoint":null,
  962. "NetworkDisabled":false,
  963. "OnBuild":null}`
  964. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  965. c.Assert(err, check.IsNil)
  966. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  967. b, err := readBody(body)
  968. if err != nil {
  969. c.Fatal(err)
  970. }
  971. type createResp struct {
  972. ID string
  973. }
  974. var container createResp
  975. if err := json.Unmarshal(b, &container); err != nil {
  976. c.Fatal(err)
  977. }
  978. out, err := inspectField(container.ID, "HostConfig.CpusetCpus")
  979. if err != nil {
  980. c.Fatal(err, out)
  981. }
  982. if out != "" {
  983. c.Fatalf("expected empty string, got %q", out)
  984. }
  985. outMemory, errMemory := inspectField(container.ID, "HostConfig.Memory")
  986. c.Assert(outMemory, check.Equals, "0")
  987. if errMemory != nil {
  988. c.Fatal(errMemory, outMemory)
  989. }
  990. outMemorySwap, errMemorySwap := inspectField(container.ID, "HostConfig.MemorySwap")
  991. c.Assert(outMemorySwap, check.Equals, "0")
  992. if errMemorySwap != nil {
  993. c.Fatal(errMemorySwap, outMemorySwap)
  994. }
  995. }
  996. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  997. config := `{
  998. "Image": "busybox",
  999. "Cmd": "ls",
  1000. "OpenStdin": true,
  1001. "CpuShares": 100,
  1002. "Memory": 524287
  1003. }`
  1004. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  1005. c.Assert(err, check.IsNil)
  1006. b, err2 := readBody(body)
  1007. if err2 != nil {
  1008. c.Fatal(err2)
  1009. }
  1010. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  1011. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  1012. }
  1013. func (s *DockerSuite) TestStartWithTooLowMemoryLimit(c *check.C) {
  1014. out, _ := dockerCmd(c, "create", "busybox")
  1015. containerID := strings.TrimSpace(out)
  1016. config := `{
  1017. "CpuShares": 100,
  1018. "Memory": 524287
  1019. }`
  1020. res, body, err := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  1021. c.Assert(err, check.IsNil)
  1022. b, err2 := readBody(body)
  1023. if err2 != nil {
  1024. c.Fatal(err2)
  1025. }
  1026. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  1027. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  1028. }
  1029. func (s *DockerSuite) TestContainerApiRename(c *check.C) {
  1030. out, _ := dockerCmd(c, "run", "--name", "TestContainerApiRename", "-d", "busybox", "sh")
  1031. containerID := strings.TrimSpace(out)
  1032. newName := "TestContainerApiRenameNew"
  1033. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
  1034. c.Assert(err, check.IsNil)
  1035. // 204 No Content is expected, not 200
  1036. c.Assert(statusCode, check.Equals, http.StatusNoContent)
  1037. name, err := inspectField(containerID, "Name")
  1038. if name != "/"+newName {
  1039. c.Fatalf("Failed to rename container, expected %v, got %v. Container rename API failed", newName, name)
  1040. }
  1041. }
  1042. func (s *DockerSuite) TestContainerApiKill(c *check.C) {
  1043. name := "test-api-kill"
  1044. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  1045. status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil)
  1046. c.Assert(err, check.IsNil)
  1047. c.Assert(status, check.Equals, http.StatusNoContent)
  1048. state, err := inspectField(name, "State.Running")
  1049. if err != nil {
  1050. c.Fatal(err)
  1051. }
  1052. if state != "false" {
  1053. c.Fatalf("got wrong State from container %s: %q", name, state)
  1054. }
  1055. }
  1056. func (s *DockerSuite) TestContainerApiRestart(c *check.C) {
  1057. name := "test-api-restart"
  1058. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  1059. status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil)
  1060. c.Assert(err, check.IsNil)
  1061. c.Assert(status, check.Equals, http.StatusNoContent)
  1062. if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil {
  1063. c.Fatal(err)
  1064. }
  1065. }
  1066. func (s *DockerSuite) TestContainerApiRestartNotimeoutParam(c *check.C) {
  1067. name := "test-api-restart-no-timeout-param"
  1068. out, _ := dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  1069. id := strings.TrimSpace(out)
  1070. c.Assert(waitRun(id), check.IsNil)
  1071. status, _, err := sockRequest("POST", "/containers/"+name+"/restart", nil)
  1072. c.Assert(err, check.IsNil)
  1073. c.Assert(status, check.Equals, http.StatusNoContent)
  1074. if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil {
  1075. c.Fatal(err)
  1076. }
  1077. }
  1078. func (s *DockerSuite) TestContainerApiStart(c *check.C) {
  1079. name := "testing-start"
  1080. config := map[string]interface{}{
  1081. "Image": "busybox",
  1082. "Cmd": []string{"/bin/sh", "-c", "/bin/top"},
  1083. "OpenStdin": true,
  1084. }
  1085. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  1086. c.Assert(err, check.IsNil)
  1087. c.Assert(status, check.Equals, http.StatusCreated)
  1088. conf := make(map[string]interface{})
  1089. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  1090. c.Assert(err, check.IsNil)
  1091. c.Assert(status, check.Equals, http.StatusNoContent)
  1092. // second call to start should give 304
  1093. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  1094. c.Assert(err, check.IsNil)
  1095. c.Assert(status, check.Equals, http.StatusNotModified)
  1096. }
  1097. func (s *DockerSuite) TestContainerApiStop(c *check.C) {
  1098. name := "test-api-stop"
  1099. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  1100. status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  1101. c.Assert(err, check.IsNil)
  1102. c.Assert(status, check.Equals, http.StatusNoContent)
  1103. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  1104. c.Fatal(err)
  1105. }
  1106. // second call to start should give 304
  1107. status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  1108. c.Assert(err, check.IsNil)
  1109. c.Assert(status, check.Equals, http.StatusNotModified)
  1110. }
  1111. func (s *DockerSuite) TestContainerApiWait(c *check.C) {
  1112. name := "test-api-wait"
  1113. dockerCmd(c, "run", "--name", name, "busybox", "sleep", "5")
  1114. status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil)
  1115. c.Assert(err, check.IsNil)
  1116. c.Assert(status, check.Equals, http.StatusOK)
  1117. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  1118. c.Fatal(err)
  1119. }
  1120. var waitres types.ContainerWaitResponse
  1121. if err := json.Unmarshal(body, &waitres); err != nil {
  1122. c.Fatalf("unable to unmarshal response body: %v", err)
  1123. }
  1124. if waitres.StatusCode != 0 {
  1125. c.Fatalf("Expected wait response StatusCode to be 0, got %d", waitres.StatusCode)
  1126. }
  1127. }
  1128. func (s *DockerSuite) TestContainerApiCopy(c *check.C) {
  1129. name := "test-container-api-copy"
  1130. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  1131. postData := types.CopyConfig{
  1132. Resource: "/test.txt",
  1133. }
  1134. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  1135. c.Assert(err, check.IsNil)
  1136. c.Assert(status, check.Equals, http.StatusOK)
  1137. found := false
  1138. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  1139. h, err := tarReader.Next()
  1140. if err != nil {
  1141. if err == io.EOF {
  1142. break
  1143. }
  1144. c.Fatal(err)
  1145. }
  1146. if h.Name == "test.txt" {
  1147. found = true
  1148. break
  1149. }
  1150. }
  1151. c.Assert(found, check.Equals, true)
  1152. }
  1153. func (s *DockerSuite) TestContainerApiCopyResourcePathEmpty(c *check.C) {
  1154. name := "test-container-api-copy-resource-empty"
  1155. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  1156. postData := types.CopyConfig{
  1157. Resource: "",
  1158. }
  1159. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  1160. c.Assert(err, check.IsNil)
  1161. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1162. c.Assert(string(body), check.Matches, "Path cannot be empty\n")
  1163. }
  1164. func (s *DockerSuite) TestContainerApiCopyResourcePathNotFound(c *check.C) {
  1165. name := "test-container-api-copy-resource-not-found"
  1166. dockerCmd(c, "run", "--name", name, "busybox")
  1167. postData := types.CopyConfig{
  1168. Resource: "/notexist",
  1169. }
  1170. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  1171. c.Assert(err, check.IsNil)
  1172. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1173. c.Assert(string(body), check.Matches, "Could not find the file /notexist in container "+name+"\n")
  1174. }
  1175. func (s *DockerSuite) TestContainerApiCopyContainerNotFound(c *check.C) {
  1176. postData := types.CopyConfig{
  1177. Resource: "/something",
  1178. }
  1179. status, _, err := sockRequest("POST", "/containers/notexists/copy", postData)
  1180. c.Assert(err, check.IsNil)
  1181. c.Assert(status, check.Equals, http.StatusNotFound)
  1182. }
  1183. func (s *DockerSuite) TestContainerApiDelete(c *check.C) {
  1184. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1185. id := strings.TrimSpace(out)
  1186. c.Assert(waitRun(id), check.IsNil)
  1187. dockerCmd(c, "stop", id)
  1188. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  1189. c.Assert(err, check.IsNil)
  1190. c.Assert(status, check.Equals, http.StatusNoContent)
  1191. }
  1192. func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) {
  1193. status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
  1194. c.Assert(err, check.IsNil)
  1195. c.Assert(status, check.Equals, http.StatusNotFound)
  1196. c.Assert(string(body), check.Matches, "no such id: doesnotexist\n")
  1197. }
  1198. func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) {
  1199. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1200. id := strings.TrimSpace(out)
  1201. c.Assert(waitRun(id), check.IsNil)
  1202. status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
  1203. c.Assert(err, check.IsNil)
  1204. c.Assert(status, check.Equals, http.StatusNoContent)
  1205. }
  1206. func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) {
  1207. out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top")
  1208. id := strings.TrimSpace(out)
  1209. c.Assert(waitRun(id), check.IsNil)
  1210. out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  1211. id2 := strings.TrimSpace(out)
  1212. c.Assert(waitRun(id2), check.IsNil)
  1213. links, err := inspectFieldJSON(id2, "HostConfig.Links")
  1214. c.Assert(err, check.IsNil)
  1215. if links != "[\"/tlink1:/tlink2/tlink1\"]" {
  1216. c.Fatal("expected to have links between containers")
  1217. }
  1218. status, _, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
  1219. c.Assert(err, check.IsNil)
  1220. c.Assert(status, check.Equals, http.StatusNoContent)
  1221. linksPostRm, err := inspectFieldJSON(id2, "HostConfig.Links")
  1222. c.Assert(err, check.IsNil)
  1223. if linksPostRm != "null" {
  1224. c.Fatal("call to api deleteContainer links should have removed the specified links")
  1225. }
  1226. }
  1227. func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) {
  1228. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1229. id := strings.TrimSpace(out)
  1230. c.Assert(waitRun(id), check.IsNil)
  1231. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  1232. c.Assert(err, check.IsNil)
  1233. c.Assert(status, check.Equals, http.StatusConflict)
  1234. }
  1235. func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) {
  1236. testRequires(c, SameHostDaemon)
  1237. out, _ := dockerCmd(c, "run", "-d", "-v", "/testvolume", "busybox", "top")
  1238. id := strings.TrimSpace(out)
  1239. c.Assert(waitRun(id), check.IsNil)
  1240. source, err := inspectMountSourceField(id, "/testvolume")
  1241. _, err = os.Stat(source)
  1242. c.Assert(err, check.IsNil)
  1243. status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
  1244. c.Assert(err, check.IsNil)
  1245. c.Assert(status, check.Equals, http.StatusNoContent)
  1246. if _, err := os.Stat(source); !os.IsNotExist(err) {
  1247. c.Fatalf("expected to get ErrNotExist error, got %v", err)
  1248. }
  1249. }
  1250. // Regression test for https://github.com/docker/docker/issues/6231
  1251. func (s *DockerSuite) TestContainersApiChunkedEncoding(c *check.C) {
  1252. out, _ := dockerCmd(c, "create", "-v", "/foo", "busybox", "true")
  1253. id := strings.TrimSpace(out)
  1254. conn, err := sockConn(time.Duration(10 * time.Second))
  1255. if err != nil {
  1256. c.Fatal(err)
  1257. }
  1258. client := httputil.NewClientConn(conn, nil)
  1259. defer client.Close()
  1260. bindCfg := strings.NewReader(`{"Binds": ["/tmp:/foo"]}`)
  1261. req, err := http.NewRequest("POST", "/containers/"+id+"/start", bindCfg)
  1262. if err != nil {
  1263. c.Fatal(err)
  1264. }
  1265. req.Header.Set("Content-Type", "application/json")
  1266. // This is a cheat to make the http request do chunked encoding
  1267. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  1268. // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
  1269. req.ContentLength = -1
  1270. resp, err := client.Do(req)
  1271. if err != nil {
  1272. c.Fatalf("error starting container with chunked encoding: %v", err)
  1273. }
  1274. resp.Body.Close()
  1275. if resp.StatusCode != 204 {
  1276. c.Fatalf("expected status code 204, got %d", resp.StatusCode)
  1277. }
  1278. out, err = inspectFieldJSON(id, "HostConfig.Binds")
  1279. if err != nil {
  1280. c.Fatal(err)
  1281. }
  1282. var binds []string
  1283. if err := json.NewDecoder(strings.NewReader(out)).Decode(&binds); err != nil {
  1284. c.Fatal(err)
  1285. }
  1286. if len(binds) != 1 {
  1287. c.Fatalf("got unexpected binds: %v", binds)
  1288. }
  1289. expected := "/tmp:/foo"
  1290. if binds[0] != expected {
  1291. c.Fatalf("got incorrect bind spec, wanted %s, got: %s", expected, binds[0])
  1292. }
  1293. }
  1294. func (s *DockerSuite) TestPostContainerStop(c *check.C) {
  1295. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1296. containerID := strings.TrimSpace(out)
  1297. c.Assert(waitRun(containerID), check.IsNil)
  1298. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/stop", nil)
  1299. c.Assert(err, check.IsNil)
  1300. // 204 No Content is expected, not 200
  1301. c.Assert(statusCode, check.Equals, http.StatusNoContent)
  1302. if err := waitInspect(containerID, "{{ .State.Running }}", "false", 5); err != nil {
  1303. c.Fatal(err)
  1304. }
  1305. }
  1306. // #14170
  1307. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceEntrypoint(c *check.C) {
  1308. config := struct {
  1309. Image string
  1310. Entrypoint string
  1311. Cmd []string
  1312. }{"busybox", "echo", []string{"hello", "world"}}
  1313. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  1314. c.Assert(err, check.IsNil)
  1315. out, _ := dockerCmd(c, "start", "-a", "echotest")
  1316. c.Assert(strings.TrimSpace(out), check.Equals, "hello world")
  1317. config2 := struct {
  1318. Image string
  1319. Entrypoint []string
  1320. Cmd []string
  1321. }{"busybox", []string{"echo"}, []string{"hello", "world"}}
  1322. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  1323. c.Assert(err, check.IsNil)
  1324. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  1325. c.Assert(strings.TrimSpace(out), check.Equals, "hello world")
  1326. }
  1327. // #14170
  1328. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) {
  1329. config := struct {
  1330. Image string
  1331. Entrypoint string
  1332. Cmd string
  1333. }{"busybox", "echo", "hello world"}
  1334. _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
  1335. c.Assert(err, check.IsNil)
  1336. out, _ := dockerCmd(c, "start", "-a", "echotest")
  1337. c.Assert(strings.TrimSpace(out), check.Equals, "hello world")
  1338. config2 := struct {
  1339. Image string
  1340. Cmd []string
  1341. }{"busybox", []string{"echo", "hello", "world"}}
  1342. _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
  1343. c.Assert(err, check.IsNil)
  1344. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  1345. c.Assert(strings.TrimSpace(out), check.Equals, "hello world")
  1346. }
  1347. // regression #14318
  1348. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *check.C) {
  1349. config := struct {
  1350. Image string
  1351. CapAdd string
  1352. CapDrop string
  1353. }{"busybox", "NET_ADMIN", "SYS_ADMIN"}
  1354. status, _, err := sockRequest("POST", "/containers/create?name=capaddtest0", config)
  1355. c.Assert(err, check.IsNil)
  1356. c.Assert(status, check.Equals, http.StatusCreated)
  1357. config2 := struct {
  1358. Image string
  1359. CapAdd []string
  1360. CapDrop []string
  1361. }{"busybox", []string{"NET_ADMIN", "SYS_ADMIN"}, []string{"SETGID"}}
  1362. status, _, err = sockRequest("POST", "/containers/create?name=capaddtest1", config2)
  1363. c.Assert(err, check.IsNil)
  1364. c.Assert(status, check.Equals, http.StatusCreated)
  1365. }
  1366. // #14640
  1367. func (s *DockerSuite) TestPostContainersStartWithoutLinksInHostConfig(c *check.C) {
  1368. name := "test-host-config-links"
  1369. dockerCmd(c, "create", "--name", name, "busybox", "top")
  1370. hc, err := inspectFieldJSON(name, "HostConfig")
  1371. c.Assert(err, check.IsNil)
  1372. config := `{"HostConfig":` + hc + `}`
  1373. res, b, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json")
  1374. c.Assert(err, check.IsNil)
  1375. c.Assert(res.StatusCode, check.Equals, http.StatusNoContent)
  1376. b.Close()
  1377. }
  1378. // #14640
  1379. func (s *DockerSuite) TestPostContainersStartWithLinksInHostConfig(c *check.C) {
  1380. name := "test-host-config-links"
  1381. dockerCmd(c, "run", "--name", "foo", "-d", "busybox", "top")
  1382. dockerCmd(c, "create", "--name", name, "--link", "foo:bar", "busybox", "top")
  1383. hc, err := inspectFieldJSON(name, "HostConfig")
  1384. c.Assert(err, check.IsNil)
  1385. config := `{"HostConfig":` + hc + `}`
  1386. res, b, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json")
  1387. c.Assert(err, check.IsNil)
  1388. c.Assert(res.StatusCode, check.Equals, http.StatusNoContent)
  1389. b.Close()
  1390. }
  1391. // #14640
  1392. func (s *DockerSuite) TestPostContainersStartWithLinksInHostConfigIdLinked(c *check.C) {
  1393. name := "test-host-config-links"
  1394. out, _ := dockerCmd(c, "run", "--name", "link0", "-d", "busybox", "top")
  1395. id := strings.TrimSpace(out)
  1396. dockerCmd(c, "create", "--name", name, "--link", id, "busybox", "top")
  1397. hc, err := inspectFieldJSON(name, "HostConfig")
  1398. c.Assert(err, check.IsNil)
  1399. config := `{"HostConfig":` + hc + `}`
  1400. res, b, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json")
  1401. c.Assert(err, check.IsNil)
  1402. c.Assert(res.StatusCode, check.Equals, http.StatusNoContent)
  1403. b.Close()
  1404. }