docker_api_containers_test.go 48 KB

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