docker_api_containers_test.go 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  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 := inspectFieldMap(name, "Volumes", "/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 := "TestContainerApiStartDupVolumeBinds"
  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 := inspectFieldMap(name, "Volumes", volPath)
  212. if err != nil {
  213. c.Fatal(err)
  214. }
  215. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  216. if err != nil {
  217. c.Fatal(err)
  218. }
  219. if pth != pth2 {
  220. c.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  221. }
  222. }
  223. func (s *DockerSuite) TestGetContainerStats(c *check.C) {
  224. var (
  225. name = "statscontainer"
  226. )
  227. dockerCmd(c, "run", "-d", "--name", name, "busybox", "top")
  228. type b struct {
  229. status int
  230. body []byte
  231. err error
  232. }
  233. bc := make(chan b, 1)
  234. go func() {
  235. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  236. bc <- b{status, body, err}
  237. }()
  238. // allow some time to stream the stats from the container
  239. time.Sleep(4 * time.Second)
  240. dockerCmd(c, "rm", "-f", name)
  241. // collect the results from the stats stream or timeout and fail
  242. // if the stream was not disconnected.
  243. select {
  244. case <-time.After(2 * time.Second):
  245. c.Fatal("stream was not closed after container was removed")
  246. case sr := <-bc:
  247. c.Assert(sr.err, check.IsNil)
  248. c.Assert(sr.status, check.Equals, http.StatusOK)
  249. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  250. var s *types.Stats
  251. // decode only one object from the stream
  252. if err := dec.Decode(&s); err != nil {
  253. c.Fatal(err)
  254. }
  255. }
  256. }
  257. func (s *DockerSuite) TestGetContainerStatsRmRunning(c *check.C) {
  258. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  259. id := strings.TrimSpace(out)
  260. buf := &channelBuffer{make(chan []byte, 1)}
  261. defer buf.Close()
  262. chErr := make(chan error)
  263. go func() {
  264. _, body, err := sockRequestRaw("GET", "/containers/"+id+"/stats?stream=1", nil, "application/json")
  265. if err != nil {
  266. chErr <- err
  267. }
  268. defer body.Close()
  269. _, err = io.Copy(buf, body)
  270. chErr <- err
  271. }()
  272. defer func() {
  273. c.Assert(<-chErr, check.IsNil)
  274. }()
  275. b := make([]byte, 32)
  276. // make sure we've got some stats
  277. _, err := buf.ReadTimeout(b, 2*time.Second)
  278. c.Assert(err, check.IsNil)
  279. // Now remove without `-f` and make sure we are still pulling stats
  280. _, _, err = dockerCmdWithError(c, "rm", id)
  281. c.Assert(err, check.Not(check.IsNil), check.Commentf("rm should have failed but didn't"))
  282. _, err = buf.ReadTimeout(b, 2*time.Second)
  283. c.Assert(err, check.IsNil)
  284. dockerCmd(c, "rm", "-f", id)
  285. _, err = buf.ReadTimeout(b, 2*time.Second)
  286. c.Assert(err, check.Not(check.IsNil))
  287. }
  288. // regression test for gh13421
  289. // previous test was just checking one stat entry so it didn't fail (stats with
  290. // stream false always return one stat)
  291. func (s *DockerSuite) TestGetContainerStatsStream(c *check.C) {
  292. name := "statscontainer"
  293. dockerCmd(c, "run", "-d", "--name", name, "busybox", "top")
  294. type b struct {
  295. status int
  296. body []byte
  297. err error
  298. }
  299. bc := make(chan b, 1)
  300. go func() {
  301. status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  302. bc <- b{status, body, err}
  303. }()
  304. // allow some time to stream the stats from the container
  305. time.Sleep(4 * time.Second)
  306. dockerCmd(c, "rm", "-f", name)
  307. // collect the results from the stats stream or timeout and fail
  308. // if the stream was not disconnected.
  309. select {
  310. case <-time.After(2 * time.Second):
  311. c.Fatal("stream was not closed after container was removed")
  312. case sr := <-bc:
  313. c.Assert(sr.err, check.IsNil)
  314. c.Assert(sr.status, check.Equals, http.StatusOK)
  315. s := string(sr.body)
  316. // count occurrences of "read" of types.Stats
  317. if l := strings.Count(s, "read"); l < 2 {
  318. c.Fatalf("Expected more than one stat streamed, got %d", l)
  319. }
  320. }
  321. }
  322. func (s *DockerSuite) TestGetContainerStatsNoStream(c *check.C) {
  323. name := "statscontainer"
  324. dockerCmd(c, "run", "-d", "--name", name, "busybox", "top")
  325. type b struct {
  326. status int
  327. body []byte
  328. err error
  329. }
  330. bc := make(chan b, 1)
  331. go func() {
  332. status, body, err := sockRequest("GET", "/containers/"+name+"/stats?stream=0", nil)
  333. bc <- b{status, body, err}
  334. }()
  335. // allow some time to stream the stats from the container
  336. time.Sleep(4 * time.Second)
  337. dockerCmd(c, "rm", "-f", name)
  338. // collect the results from the stats stream or timeout and fail
  339. // if the stream was not disconnected.
  340. select {
  341. case <-time.After(2 * time.Second):
  342. c.Fatal("stream was not closed after container was removed")
  343. case sr := <-bc:
  344. c.Assert(sr.err, check.IsNil)
  345. c.Assert(sr.status, check.Equals, http.StatusOK)
  346. s := string(sr.body)
  347. // count occurrences of "read" of types.Stats
  348. if l := strings.Count(s, "read"); l != 1 {
  349. c.Fatalf("Expected only one stat streamed, got %d", l)
  350. }
  351. }
  352. }
  353. func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) {
  354. // TODO: this test does nothing because we are c.Assert'ing in goroutine
  355. var (
  356. name = "statscontainer"
  357. )
  358. dockerCmd(c, "create", "--name", name, "busybox", "top")
  359. go func() {
  360. // We'll never get return for GET stats from sockRequest as of now,
  361. // just send request and see if panic or error would happen on daemon side.
  362. status, _, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  363. c.Assert(err, check.IsNil)
  364. c.Assert(status, check.Equals, http.StatusOK)
  365. }()
  366. // allow some time to send request and let daemon deal with it
  367. time.Sleep(1 * time.Second)
  368. }
  369. func (s *DockerSuite) TestBuildApiDockerfilePath(c *check.C) {
  370. // Test to make sure we stop people from trying to leave the
  371. // build context when specifying the path to the dockerfile
  372. buffer := new(bytes.Buffer)
  373. tw := tar.NewWriter(buffer)
  374. defer tw.Close()
  375. dockerfile := []byte("FROM busybox")
  376. if err := tw.WriteHeader(&tar.Header{
  377. Name: "Dockerfile",
  378. Size: int64(len(dockerfile)),
  379. }); err != nil {
  380. c.Fatalf("failed to write tar file header: %v", err)
  381. }
  382. if _, err := tw.Write(dockerfile); err != nil {
  383. c.Fatalf("failed to write tar file content: %v", err)
  384. }
  385. if err := tw.Close(); err != nil {
  386. c.Fatalf("failed to close tar archive: %v", err)
  387. }
  388. res, body, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
  389. c.Assert(err, check.IsNil)
  390. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  391. out, err := readBody(body)
  392. if err != nil {
  393. c.Fatal(err)
  394. }
  395. if !strings.Contains(string(out), "must be within the build context") {
  396. c.Fatalf("Didn't complain about leaving build context: %s", out)
  397. }
  398. }
  399. func (s *DockerSuite) TestBuildApiDockerFileRemote(c *check.C) {
  400. server, err := fakeStorage(map[string]string{
  401. "testD": `FROM busybox
  402. COPY * /tmp/
  403. RUN find / -name ba*
  404. RUN find /tmp/`,
  405. })
  406. if err != nil {
  407. c.Fatal(err)
  408. }
  409. defer server.Close()
  410. res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json")
  411. c.Assert(err, check.IsNil)
  412. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  413. buf, err := readBody(body)
  414. if err != nil {
  415. c.Fatal(err)
  416. }
  417. // Make sure Dockerfile exists.
  418. // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL
  419. out := string(buf)
  420. if !strings.Contains(out, "/tmp/Dockerfile") ||
  421. strings.Contains(out, "baz") {
  422. c.Fatalf("Incorrect output: %s", out)
  423. }
  424. }
  425. func (s *DockerSuite) TestBuildApiRemoteTarballContext(c *check.C) {
  426. buffer := new(bytes.Buffer)
  427. tw := tar.NewWriter(buffer)
  428. defer tw.Close()
  429. dockerfile := []byte("FROM busybox")
  430. if err := tw.WriteHeader(&tar.Header{
  431. Name: "Dockerfile",
  432. Size: int64(len(dockerfile)),
  433. }); err != nil {
  434. c.Fatalf("failed to write tar file header: %v", err)
  435. }
  436. if _, err := tw.Write(dockerfile); err != nil {
  437. c.Fatalf("failed to write tar file content: %v", err)
  438. }
  439. if err := tw.Close(); err != nil {
  440. c.Fatalf("failed to close tar archive: %v", err)
  441. }
  442. server, err := fakeBinaryStorage(map[string]*bytes.Buffer{
  443. "testT.tar": buffer,
  444. })
  445. c.Assert(err, check.IsNil)
  446. defer server.Close()
  447. res, _, err := sockRequestRaw("POST", "/build?remote="+server.URL()+"/testT.tar", nil, "application/tar")
  448. c.Assert(err, check.IsNil)
  449. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  450. }
  451. func (s *DockerSuite) TestBuildApiRemoteTarballContextWithCustomDockerfile(c *check.C) {
  452. buffer := new(bytes.Buffer)
  453. tw := tar.NewWriter(buffer)
  454. defer tw.Close()
  455. dockerfile := []byte(`FROM busybox
  456. RUN echo 'wrong'`)
  457. if err := tw.WriteHeader(&tar.Header{
  458. Name: "Dockerfile",
  459. Size: int64(len(dockerfile)),
  460. }); err != nil {
  461. c.Fatalf("failed to write tar file header: %v", err)
  462. }
  463. if _, err := tw.Write(dockerfile); err != nil {
  464. c.Fatalf("failed to write tar file content: %v", err)
  465. }
  466. custom := []byte(`FROM busybox
  467. RUN echo 'right'
  468. `)
  469. if err := tw.WriteHeader(&tar.Header{
  470. Name: "custom",
  471. Size: int64(len(custom)),
  472. }); err != nil {
  473. c.Fatalf("failed to write tar file header: %v", err)
  474. }
  475. if _, err := tw.Write(custom); err != nil {
  476. c.Fatalf("failed to write tar file content: %v", err)
  477. }
  478. if err := tw.Close(); err != nil {
  479. c.Fatalf("failed to close tar archive: %v", err)
  480. }
  481. server, err := fakeBinaryStorage(map[string]*bytes.Buffer{
  482. "testT.tar": buffer,
  483. })
  484. c.Assert(err, check.IsNil)
  485. defer server.Close()
  486. url := "/build?dockerfile=custom&remote=" + server.URL() + "/testT.tar"
  487. res, body, err := sockRequestRaw("POST", url, nil, "application/tar")
  488. c.Assert(err, check.IsNil)
  489. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  490. defer body.Close()
  491. content, err := readBody(body)
  492. c.Assert(err, check.IsNil)
  493. if strings.Contains(string(content), "wrong") {
  494. c.Fatalf("Build used the wrong dockerfile.")
  495. }
  496. }
  497. func (s *DockerSuite) TestBuildApiLowerDockerfile(c *check.C) {
  498. git, err := fakeGIT("repo", map[string]string{
  499. "dockerfile": `FROM busybox
  500. RUN echo from dockerfile`,
  501. }, false)
  502. if err != nil {
  503. c.Fatal(err)
  504. }
  505. defer git.Close()
  506. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  507. c.Assert(err, check.IsNil)
  508. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  509. buf, err := readBody(body)
  510. if err != nil {
  511. c.Fatal(err)
  512. }
  513. out := string(buf)
  514. if !strings.Contains(out, "from dockerfile") {
  515. c.Fatalf("Incorrect output: %s", out)
  516. }
  517. }
  518. func (s *DockerSuite) TestBuildApiBuildGitWithF(c *check.C) {
  519. git, err := fakeGIT("repo", map[string]string{
  520. "baz": `FROM busybox
  521. RUN echo from baz`,
  522. "Dockerfile": `FROM busybox
  523. RUN echo from Dockerfile`,
  524. }, false)
  525. if err != nil {
  526. c.Fatal(err)
  527. }
  528. defer git.Close()
  529. // Make sure it tries to 'dockerfile' query param value
  530. res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
  531. c.Assert(err, check.IsNil)
  532. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  533. buf, err := readBody(body)
  534. if err != nil {
  535. c.Fatal(err)
  536. }
  537. out := string(buf)
  538. if !strings.Contains(out, "from baz") {
  539. c.Fatalf("Incorrect output: %s", out)
  540. }
  541. }
  542. func (s *DockerSuite) TestBuildApiDoubleDockerfile(c *check.C) {
  543. testRequires(c, UnixCli) // dockerfile overwrites Dockerfile on Windows
  544. git, err := fakeGIT("repo", map[string]string{
  545. "Dockerfile": `FROM busybox
  546. RUN echo from Dockerfile`,
  547. "dockerfile": `FROM busybox
  548. RUN echo from dockerfile`,
  549. }, false)
  550. if err != nil {
  551. c.Fatal(err)
  552. }
  553. defer git.Close()
  554. // Make sure it tries to 'dockerfile' query param value
  555. res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  556. c.Assert(err, check.IsNil)
  557. c.Assert(res.StatusCode, check.Equals, http.StatusOK)
  558. buf, err := readBody(body)
  559. if err != nil {
  560. c.Fatal(err)
  561. }
  562. out := string(buf)
  563. if !strings.Contains(out, "from Dockerfile") {
  564. c.Fatalf("Incorrect output: %s", out)
  565. }
  566. }
  567. func (s *DockerSuite) TestBuildApiDockerfileSymlink(c *check.C) {
  568. // Test to make sure we stop people from trying to leave the
  569. // build context when specifying a symlink as the path to the dockerfile
  570. buffer := new(bytes.Buffer)
  571. tw := tar.NewWriter(buffer)
  572. defer tw.Close()
  573. if err := tw.WriteHeader(&tar.Header{
  574. Name: "Dockerfile",
  575. Typeflag: tar.TypeSymlink,
  576. Linkname: "/etc/passwd",
  577. }); err != nil {
  578. c.Fatalf("failed to write tar file header: %v", err)
  579. }
  580. if err := tw.Close(); err != nil {
  581. c.Fatalf("failed to close tar archive: %v", err)
  582. }
  583. res, body, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  584. c.Assert(err, check.IsNil)
  585. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  586. out, err := readBody(body)
  587. if err != nil {
  588. c.Fatal(err)
  589. }
  590. // The reason the error is "Cannot locate specified Dockerfile" is because
  591. // in the builder, the symlink is resolved within the context, therefore
  592. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  593. // a nonexistent file.
  594. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  595. c.Fatalf("Didn't complain about leaving build context: %s", out)
  596. }
  597. }
  598. // #9981 - Allow a docker created volume (ie, one in /var/lib/docker/volumes) to be used to overwrite (via passing in Binds on api start) an existing volume
  599. func (s *DockerSuite) TestPostContainerBindNormalVolume(c *check.C) {
  600. dockerCmd(c, "create", "-v", "/foo", "--name=one", "busybox")
  601. fooDir, err := inspectFieldMap("one", "Volumes", "/foo")
  602. if err != nil {
  603. c.Fatal(err)
  604. }
  605. dockerCmd(c, "create", "-v", "/foo", "--name=two", "busybox")
  606. bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
  607. status, _, err := sockRequest("POST", "/containers/two/start", bindSpec)
  608. c.Assert(err, check.IsNil)
  609. c.Assert(status, check.Equals, http.StatusNoContent)
  610. fooDir2, err := inspectFieldMap("two", "Volumes", "/foo")
  611. if err != nil {
  612. c.Fatal(err)
  613. }
  614. if fooDir2 != fooDir {
  615. c.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2)
  616. }
  617. }
  618. func (s *DockerSuite) TestContainerApiPause(c *check.C) {
  619. defer unpauseAllContainers()
  620. out, _ := dockerCmd(c, "run", "-d", "busybox", "sleep", "30")
  621. ContainerID := strings.TrimSpace(out)
  622. status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil)
  623. c.Assert(err, check.IsNil)
  624. c.Assert(status, check.Equals, http.StatusNoContent)
  625. pausedContainers, err := getSliceOfPausedContainers()
  626. if err != nil {
  627. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  628. }
  629. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  630. c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  631. }
  632. status, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil)
  633. c.Assert(err, check.IsNil)
  634. c.Assert(status, check.Equals, http.StatusNoContent)
  635. pausedContainers, err = getSliceOfPausedContainers()
  636. if err != nil {
  637. c.Fatalf("error thrown while checking if containers were paused: %v", err)
  638. }
  639. if pausedContainers != nil {
  640. c.Fatalf("There should be no paused container.")
  641. }
  642. }
  643. func (s *DockerSuite) TestContainerApiTop(c *check.C) {
  644. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top")
  645. id := strings.TrimSpace(string(out))
  646. if err := waitRun(id); err != nil {
  647. c.Fatal(err)
  648. }
  649. type topResp struct {
  650. Titles []string
  651. Processes [][]string
  652. }
  653. var top topResp
  654. status, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil)
  655. c.Assert(err, check.IsNil)
  656. c.Assert(status, check.Equals, http.StatusOK)
  657. if err := json.Unmarshal(b, &top); err != nil {
  658. c.Fatal(err)
  659. }
  660. if len(top.Titles) != 11 {
  661. c.Fatalf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles)
  662. }
  663. if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
  664. c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
  665. }
  666. if len(top.Processes) != 2 {
  667. c.Fatalf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes)
  668. }
  669. if top.Processes[0][10] != "/bin/sh -c top" {
  670. c.Fatalf("expected `/bin/sh -c top`, found: %s", top.Processes[0][10])
  671. }
  672. if top.Processes[1][10] != "top" {
  673. c.Fatalf("expected `top`, found: %s", top.Processes[1][10])
  674. }
  675. }
  676. func (s *DockerSuite) TestContainerApiCommit(c *check.C) {
  677. cName := "testapicommit"
  678. dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
  679. name := "TestContainerApiCommit"
  680. status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil)
  681. c.Assert(err, check.IsNil)
  682. c.Assert(status, check.Equals, http.StatusCreated)
  683. type resp struct {
  684. Id string
  685. }
  686. var img resp
  687. if err := json.Unmarshal(b, &img); err != nil {
  688. c.Fatal(err)
  689. }
  690. cmd, err := inspectField(img.Id, "Config.Cmd")
  691. if err != nil {
  692. c.Fatal(err)
  693. }
  694. if cmd != "{[/bin/sh -c touch /test]}" {
  695. c.Fatalf("got wrong Cmd from commit: %q", cmd)
  696. }
  697. // sanity check, make sure the image is what we think it is
  698. dockerCmd(c, "run", img.Id, "ls", "/test")
  699. }
  700. func (s *DockerSuite) TestContainerApiCommitWithLabelInConfig(c *check.C) {
  701. cName := "testapicommitwithconfig"
  702. dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
  703. config := map[string]interface{}{
  704. "Labels": map[string]string{"key1": "value1", "key2": "value2"},
  705. }
  706. name := "TestContainerApiCommitWithConfig"
  707. status, b, err := sockRequest("POST", "/commit?repo="+name+"&container="+cName, config)
  708. c.Assert(err, check.IsNil)
  709. c.Assert(status, check.Equals, http.StatusCreated)
  710. type resp struct {
  711. Id string
  712. }
  713. var img resp
  714. if err := json.Unmarshal(b, &img); err != nil {
  715. c.Fatal(err)
  716. }
  717. label1, err := inspectFieldMap(img.Id, "Config.Labels", "key1")
  718. if err != nil {
  719. c.Fatal(err)
  720. }
  721. c.Assert(label1, check.Equals, "value1")
  722. label2, err := inspectFieldMap(img.Id, "Config.Labels", "key2")
  723. if err != nil {
  724. c.Fatal(err)
  725. }
  726. c.Assert(label2, check.Equals, "value2")
  727. cmd, err := inspectField(img.Id, "Config.Cmd")
  728. if err != nil {
  729. c.Fatal(err)
  730. }
  731. if cmd != "{[/bin/sh -c touch /test]}" {
  732. c.Fatalf("got wrong Cmd from commit: %q", cmd)
  733. }
  734. // sanity check, make sure the image is what we think it is
  735. dockerCmd(c, "run", img.Id, "ls", "/test")
  736. }
  737. func (s *DockerSuite) TestContainerApiBadPort(c *check.C) {
  738. config := map[string]interface{}{
  739. "Image": "busybox",
  740. "Cmd": []string{"/bin/sh", "-c", "echo test"},
  741. "PortBindings": map[string]interface{}{
  742. "8080/tcp": []map[string]interface{}{
  743. {
  744. "HostIp": "",
  745. "HostPort": "aa80",
  746. },
  747. },
  748. },
  749. }
  750. jsonData := bytes.NewBuffer(nil)
  751. json.NewEncoder(jsonData).Encode(config)
  752. status, b, err := sockRequest("POST", "/containers/create", config)
  753. c.Assert(err, check.IsNil)
  754. c.Assert(status, check.Equals, http.StatusInternalServerError)
  755. if strings.TrimSpace(string(b)) != `Invalid port specification: "aa80"` {
  756. c.Fatalf("Incorrect error msg: %s", string(b))
  757. }
  758. }
  759. func (s *DockerSuite) TestContainerApiCreate(c *check.C) {
  760. config := map[string]interface{}{
  761. "Image": "busybox",
  762. "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"},
  763. }
  764. status, b, err := sockRequest("POST", "/containers/create", config)
  765. c.Assert(err, check.IsNil)
  766. c.Assert(status, check.Equals, http.StatusCreated)
  767. type createResp struct {
  768. Id string
  769. }
  770. var container createResp
  771. if err := json.Unmarshal(b, &container); err != nil {
  772. c.Fatal(err)
  773. }
  774. out, _ := dockerCmd(c, "start", "-a", container.Id)
  775. if strings.TrimSpace(out) != "/test" {
  776. c.Fatalf("expected output `/test`, got %q", out)
  777. }
  778. }
  779. func (s *DockerSuite) TestContainerApiCreateEmptyConfig(c *check.C) {
  780. config := map[string]interface{}{}
  781. status, b, err := sockRequest("POST", "/containers/create", config)
  782. c.Assert(err, check.IsNil)
  783. c.Assert(status, check.Equals, http.StatusInternalServerError)
  784. expected := "Config cannot be empty in order to create a container\n"
  785. if body := string(b); body != expected {
  786. c.Fatalf("Expected to get %q, got %q", expected, body)
  787. }
  788. }
  789. func (s *DockerSuite) TestContainerApiCreateWithHostName(c *check.C) {
  790. hostName := "test-host"
  791. config := map[string]interface{}{
  792. "Image": "busybox",
  793. "Hostname": hostName,
  794. }
  795. status, body, err := sockRequest("POST", "/containers/create", config)
  796. c.Assert(err, check.IsNil)
  797. c.Assert(status, check.Equals, http.StatusCreated)
  798. var container types.ContainerCreateResponse
  799. if err := json.Unmarshal(body, &container); err != nil {
  800. c.Fatal(err)
  801. }
  802. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  803. c.Assert(err, check.IsNil)
  804. c.Assert(status, check.Equals, http.StatusOK)
  805. var containerJSON types.ContainerJSON
  806. if err := json.Unmarshal(body, &containerJSON); err != nil {
  807. c.Fatal(err)
  808. }
  809. if containerJSON.Config.Hostname != hostName {
  810. c.Fatalf("Mismatched Hostname, Expected %s, Actual: %s ", hostName, containerJSON.Config.Hostname)
  811. }
  812. }
  813. func (s *DockerSuite) TestContainerApiCreateWithDomainName(c *check.C) {
  814. domainName := "test-domain"
  815. config := map[string]interface{}{
  816. "Image": "busybox",
  817. "Domainname": domainName,
  818. }
  819. status, body, err := sockRequest("POST", "/containers/create", config)
  820. c.Assert(err, check.IsNil)
  821. c.Assert(status, check.Equals, http.StatusCreated)
  822. var container types.ContainerCreateResponse
  823. if err := json.Unmarshal(body, &container); err != nil {
  824. c.Fatal(err)
  825. }
  826. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  827. c.Assert(err, check.IsNil)
  828. c.Assert(status, check.Equals, http.StatusOK)
  829. var containerJSON types.ContainerJSON
  830. if err := json.Unmarshal(body, &containerJSON); err != nil {
  831. c.Fatal(err)
  832. }
  833. if containerJSON.Config.Domainname != domainName {
  834. c.Fatalf("Mismatched Domainname, Expected %s, Actual: %s ", domainName, containerJSON.Config.Domainname)
  835. }
  836. }
  837. func (s *DockerSuite) TestContainerApiCreateNetworkMode(c *check.C) {
  838. UtilCreateNetworkMode(c, "host")
  839. UtilCreateNetworkMode(c, "bridge")
  840. UtilCreateNetworkMode(c, "container:web1")
  841. }
  842. func UtilCreateNetworkMode(c *check.C, networkMode string) {
  843. config := map[string]interface{}{
  844. "Image": "busybox",
  845. "HostConfig": map[string]interface{}{"NetworkMode": networkMode},
  846. }
  847. status, body, err := sockRequest("POST", "/containers/create", config)
  848. c.Assert(err, check.IsNil)
  849. c.Assert(status, check.Equals, http.StatusCreated)
  850. var container types.ContainerCreateResponse
  851. if err := json.Unmarshal(body, &container); err != nil {
  852. c.Fatal(err)
  853. }
  854. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  855. c.Assert(err, check.IsNil)
  856. c.Assert(status, check.Equals, http.StatusOK)
  857. var containerJSON types.ContainerJSON
  858. if err := json.Unmarshal(body, &containerJSON); err != nil {
  859. c.Fatal(err)
  860. }
  861. if containerJSON.HostConfig.NetworkMode != runconfig.NetworkMode(networkMode) {
  862. c.Fatalf("Mismatched NetworkMode, Expected %s, Actual: %s ", networkMode, containerJSON.HostConfig.NetworkMode)
  863. }
  864. }
  865. func (s *DockerSuite) TestContainerApiCreateWithCpuSharesCpuset(c *check.C) {
  866. config := map[string]interface{}{
  867. "Image": "busybox",
  868. "CpuShares": 512,
  869. "CpusetCpus": "0,1",
  870. }
  871. status, body, err := sockRequest("POST", "/containers/create", config)
  872. c.Assert(err, check.IsNil)
  873. c.Assert(status, check.Equals, http.StatusCreated)
  874. var container types.ContainerCreateResponse
  875. if err := json.Unmarshal(body, &container); err != nil {
  876. c.Fatal(err)
  877. }
  878. status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil)
  879. c.Assert(err, check.IsNil)
  880. c.Assert(status, check.Equals, http.StatusOK)
  881. var containerJson types.ContainerJSON
  882. c.Assert(json.Unmarshal(body, &containerJson), check.IsNil)
  883. out, err := inspectField(containerJson.Id, "HostConfig.CpuShares")
  884. c.Assert(err, check.IsNil)
  885. c.Assert(out, check.Equals, "512")
  886. outCpuset, errCpuset := inspectField(containerJson.Id, "HostConfig.CpusetCpus")
  887. c.Assert(errCpuset, check.IsNil, check.Commentf("Output: %s", outCpuset))
  888. c.Assert(outCpuset, check.Equals, "0,1")
  889. }
  890. func (s *DockerSuite) TestContainerApiVerifyHeader(c *check.C) {
  891. config := map[string]interface{}{
  892. "Image": "busybox",
  893. }
  894. create := func(ct string) (*http.Response, io.ReadCloser, error) {
  895. jsonData := bytes.NewBuffer(nil)
  896. if err := json.NewEncoder(jsonData).Encode(config); err != nil {
  897. c.Fatal(err)
  898. }
  899. return sockRequestRaw("POST", "/containers/create", jsonData, ct)
  900. }
  901. // Try with no content-type
  902. res, body, err := create("")
  903. c.Assert(err, check.IsNil)
  904. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  905. body.Close()
  906. // Try with wrong content-type
  907. res, body, err = create("application/xml")
  908. c.Assert(err, check.IsNil)
  909. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  910. body.Close()
  911. // now application/json
  912. res, body, err = create("application/json")
  913. c.Assert(err, check.IsNil)
  914. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  915. body.Close()
  916. }
  917. //Issue 14230. daemon should return 500 for invalid port syntax
  918. func (s *DockerSuite) TestContainerApiInvalidPortSyntax(c *check.C) {
  919. config := `{
  920. "Image": "busybox",
  921. "HostConfig": {
  922. "PortBindings": {
  923. "19039;1230": [
  924. {}
  925. ]
  926. }
  927. }
  928. }`
  929. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  930. c.Assert(err, check.IsNil)
  931. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  932. b, err := readBody(body)
  933. if err != nil {
  934. c.Fatal(err)
  935. }
  936. c.Assert(strings.Contains(string(b[:]), "Invalid port"), check.Equals, true)
  937. }
  938. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  939. // W/o this fix a null in JSON would be parsed into a string var as "null"
  940. func (s *DockerSuite) TestContainerApiPostCreateNull(c *check.C) {
  941. config := `{
  942. "Hostname":"",
  943. "Domainname":"",
  944. "Memory":0,
  945. "MemorySwap":0,
  946. "CpuShares":0,
  947. "Cpuset":null,
  948. "AttachStdin":true,
  949. "AttachStdout":true,
  950. "AttachStderr":true,
  951. "ExposedPorts":{},
  952. "Tty":true,
  953. "OpenStdin":true,
  954. "StdinOnce":true,
  955. "Env":[],
  956. "Cmd":"ls",
  957. "Image":"busybox",
  958. "Volumes":{},
  959. "WorkingDir":"",
  960. "Entrypoint":null,
  961. "NetworkDisabled":false,
  962. "OnBuild":null}`
  963. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  964. c.Assert(err, check.IsNil)
  965. c.Assert(res.StatusCode, check.Equals, http.StatusCreated)
  966. b, err := readBody(body)
  967. if err != nil {
  968. c.Fatal(err)
  969. }
  970. type createResp struct {
  971. Id string
  972. }
  973. var container createResp
  974. if err := json.Unmarshal(b, &container); err != nil {
  975. c.Fatal(err)
  976. }
  977. out, err := inspectField(container.Id, "HostConfig.CpusetCpus")
  978. if err != nil {
  979. c.Fatal(err, out)
  980. }
  981. if out != "" {
  982. c.Fatalf("expected empty string, got %q", out)
  983. }
  984. outMemory, errMemory := inspectField(container.Id, "HostConfig.Memory")
  985. c.Assert(outMemory, check.Equals, "0")
  986. if errMemory != nil {
  987. c.Fatal(errMemory, outMemory)
  988. }
  989. outMemorySwap, errMemorySwap := inspectField(container.Id, "HostConfig.MemorySwap")
  990. c.Assert(outMemorySwap, check.Equals, "0")
  991. if errMemorySwap != nil {
  992. c.Fatal(errMemorySwap, outMemorySwap)
  993. }
  994. }
  995. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  996. config := `{
  997. "Image": "busybox",
  998. "Cmd": "ls",
  999. "OpenStdin": true,
  1000. "CpuShares": 100,
  1001. "Memory": 524287
  1002. }`
  1003. res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  1004. c.Assert(err, check.IsNil)
  1005. b, err2 := readBody(body)
  1006. if err2 != nil {
  1007. c.Fatal(err2)
  1008. }
  1009. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  1010. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  1011. }
  1012. func (s *DockerSuite) TestStartWithTooLowMemoryLimit(c *check.C) {
  1013. out, _ := dockerCmd(c, "create", "busybox")
  1014. containerID := strings.TrimSpace(out)
  1015. config := `{
  1016. "CpuShares": 100,
  1017. "Memory": 524287
  1018. }`
  1019. res, body, err := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  1020. c.Assert(err, check.IsNil)
  1021. b, err2 := readBody(body)
  1022. if err2 != nil {
  1023. c.Fatal(err2)
  1024. }
  1025. c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
  1026. c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true)
  1027. }
  1028. func (s *DockerSuite) TestContainerApiRename(c *check.C) {
  1029. out, _ := dockerCmd(c, "run", "--name", "TestContainerApiRename", "-d", "busybox", "sh")
  1030. containerID := strings.TrimSpace(out)
  1031. newName := "TestContainerApiRenameNew"
  1032. statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil)
  1033. c.Assert(err, check.IsNil)
  1034. // 204 No Content is expected, not 200
  1035. c.Assert(statusCode, check.Equals, http.StatusNoContent)
  1036. name, err := inspectField(containerID, "Name")
  1037. if name != "/"+newName {
  1038. c.Fatalf("Failed to rename container, expected %v, got %v. Container rename API failed", newName, name)
  1039. }
  1040. }
  1041. func (s *DockerSuite) TestContainerApiKill(c *check.C) {
  1042. name := "test-api-kill"
  1043. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  1044. status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil)
  1045. c.Assert(err, check.IsNil)
  1046. c.Assert(status, check.Equals, http.StatusNoContent)
  1047. state, err := inspectField(name, "State.Running")
  1048. if err != nil {
  1049. c.Fatal(err)
  1050. }
  1051. if state != "false" {
  1052. c.Fatalf("got wrong State from container %s: %q", name, state)
  1053. }
  1054. }
  1055. func (s *DockerSuite) TestContainerApiRestart(c *check.C) {
  1056. name := "test-api-restart"
  1057. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  1058. status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil)
  1059. c.Assert(err, check.IsNil)
  1060. c.Assert(status, check.Equals, http.StatusNoContent)
  1061. if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil {
  1062. c.Fatal(err)
  1063. }
  1064. }
  1065. func (s *DockerSuite) TestContainerApiRestartNotimeoutParam(c *check.C) {
  1066. name := "test-api-restart-no-timeout-param"
  1067. out, _ := dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  1068. id := strings.TrimSpace(out)
  1069. c.Assert(waitRun(id), check.IsNil)
  1070. status, _, err := sockRequest("POST", "/containers/"+name+"/restart", nil)
  1071. c.Assert(err, check.IsNil)
  1072. c.Assert(status, check.Equals, http.StatusNoContent)
  1073. if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil {
  1074. c.Fatal(err)
  1075. }
  1076. }
  1077. func (s *DockerSuite) TestContainerApiStart(c *check.C) {
  1078. name := "testing-start"
  1079. config := map[string]interface{}{
  1080. "Image": "busybox",
  1081. "Cmd": []string{"/bin/sh", "-c", "/bin/top"},
  1082. "OpenStdin": true,
  1083. }
  1084. status, _, err := sockRequest("POST", "/containers/create?name="+name, config)
  1085. c.Assert(err, check.IsNil)
  1086. c.Assert(status, check.Equals, http.StatusCreated)
  1087. conf := make(map[string]interface{})
  1088. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  1089. c.Assert(err, check.IsNil)
  1090. c.Assert(status, check.Equals, http.StatusNoContent)
  1091. // second call to start should give 304
  1092. status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf)
  1093. c.Assert(err, check.IsNil)
  1094. c.Assert(status, check.Equals, http.StatusNotModified)
  1095. }
  1096. func (s *DockerSuite) TestContainerApiStop(c *check.C) {
  1097. name := "test-api-stop"
  1098. dockerCmd(c, "run", "-di", "--name", name, "busybox", "top")
  1099. status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  1100. c.Assert(err, check.IsNil)
  1101. c.Assert(status, check.Equals, http.StatusNoContent)
  1102. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  1103. c.Fatal(err)
  1104. }
  1105. // second call to start should give 304
  1106. status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=1", nil)
  1107. c.Assert(err, check.IsNil)
  1108. c.Assert(status, check.Equals, http.StatusNotModified)
  1109. }
  1110. func (s *DockerSuite) TestContainerApiWait(c *check.C) {
  1111. name := "test-api-wait"
  1112. dockerCmd(c, "run", "--name", name, "busybox", "sleep", "5")
  1113. status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil)
  1114. c.Assert(err, check.IsNil)
  1115. c.Assert(status, check.Equals, http.StatusOK)
  1116. if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil {
  1117. c.Fatal(err)
  1118. }
  1119. var waitres types.ContainerWaitResponse
  1120. if err := json.Unmarshal(body, &waitres); err != nil {
  1121. c.Fatalf("unable to unmarshal response body: %v", err)
  1122. }
  1123. if waitres.StatusCode != 0 {
  1124. c.Fatalf("Expected wait response StatusCode to be 0, got %d", waitres.StatusCode)
  1125. }
  1126. }
  1127. func (s *DockerSuite) TestContainerApiCopy(c *check.C) {
  1128. name := "test-container-api-copy"
  1129. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  1130. postData := types.CopyConfig{
  1131. Resource: "/test.txt",
  1132. }
  1133. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  1134. c.Assert(err, check.IsNil)
  1135. c.Assert(status, check.Equals, http.StatusOK)
  1136. found := false
  1137. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  1138. h, err := tarReader.Next()
  1139. if err != nil {
  1140. if err == io.EOF {
  1141. break
  1142. }
  1143. c.Fatal(err)
  1144. }
  1145. if h.Name == "test.txt" {
  1146. found = true
  1147. break
  1148. }
  1149. }
  1150. c.Assert(found, check.Equals, true)
  1151. }
  1152. func (s *DockerSuite) TestContainerApiCopyResourcePathEmpty(c *check.C) {
  1153. name := "test-container-api-copy-resource-empty"
  1154. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  1155. postData := types.CopyConfig{
  1156. Resource: "",
  1157. }
  1158. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  1159. c.Assert(err, check.IsNil)
  1160. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1161. c.Assert(string(body), check.Matches, "Path cannot be empty\n")
  1162. }
  1163. func (s *DockerSuite) TestContainerApiCopyResourcePathNotFound(c *check.C) {
  1164. name := "test-container-api-copy-resource-not-found"
  1165. dockerCmd(c, "run", "--name", name, "busybox")
  1166. postData := types.CopyConfig{
  1167. Resource: "/notexist",
  1168. }
  1169. status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData)
  1170. c.Assert(err, check.IsNil)
  1171. c.Assert(status, check.Equals, http.StatusInternalServerError)
  1172. c.Assert(string(body), check.Matches, "Could not find the file /notexist in container "+name+"\n")
  1173. }
  1174. func (s *DockerSuite) TestContainerApiCopyContainerNotFound(c *check.C) {
  1175. postData := types.CopyConfig{
  1176. Resource: "/something",
  1177. }
  1178. status, _, err := sockRequest("POST", "/containers/notexists/copy", postData)
  1179. c.Assert(err, check.IsNil)
  1180. c.Assert(status, check.Equals, http.StatusNotFound)
  1181. }
  1182. func (s *DockerSuite) TestContainerApiDelete(c *check.C) {
  1183. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1184. id := strings.TrimSpace(out)
  1185. c.Assert(waitRun(id), check.IsNil)
  1186. dockerCmd(c, "stop", id)
  1187. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  1188. c.Assert(err, check.IsNil)
  1189. c.Assert(status, check.Equals, http.StatusNoContent)
  1190. }
  1191. func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) {
  1192. status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
  1193. c.Assert(err, check.IsNil)
  1194. c.Assert(status, check.Equals, http.StatusNotFound)
  1195. c.Assert(string(body), check.Matches, "no such id: doesnotexist\n")
  1196. }
  1197. func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) {
  1198. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1199. id := strings.TrimSpace(out)
  1200. c.Assert(waitRun(id), check.IsNil)
  1201. status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
  1202. c.Assert(err, check.IsNil)
  1203. c.Assert(status, check.Equals, http.StatusNoContent)
  1204. }
  1205. func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) {
  1206. out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top")
  1207. id := strings.TrimSpace(out)
  1208. c.Assert(waitRun(id), check.IsNil)
  1209. out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  1210. id2 := strings.TrimSpace(out)
  1211. c.Assert(waitRun(id2), check.IsNil)
  1212. links, err := inspectFieldJSON(id2, "HostConfig.Links")
  1213. c.Assert(err, check.IsNil)
  1214. if links != "[\"/tlink1:/tlink2/tlink1\"]" {
  1215. c.Fatal("expected to have links between containers")
  1216. }
  1217. status, _, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
  1218. c.Assert(err, check.IsNil)
  1219. c.Assert(status, check.Equals, http.StatusNoContent)
  1220. linksPostRm, err := inspectFieldJSON(id2, "HostConfig.Links")
  1221. c.Assert(err, check.IsNil)
  1222. if linksPostRm != "null" {
  1223. c.Fatal("call to api deleteContainer links should have removed the specified links")
  1224. }
  1225. }
  1226. func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) {
  1227. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1228. id := strings.TrimSpace(out)
  1229. c.Assert(waitRun(id), check.IsNil)
  1230. status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
  1231. c.Assert(err, check.IsNil)
  1232. c.Assert(status, check.Equals, http.StatusConflict)
  1233. }
  1234. func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) {
  1235. testRequires(c, SameHostDaemon)
  1236. out, _ := dockerCmd(c, "run", "-d", "-v", "/testvolume", "busybox", "top")
  1237. id := strings.TrimSpace(out)
  1238. c.Assert(waitRun(id), check.IsNil)
  1239. vol, err := inspectFieldMap(id, "Volumes", "/testvolume")
  1240. c.Assert(err, check.IsNil)
  1241. _, err = os.Stat(vol)
  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(vol); !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. }