docker_api_containers_test.go 44 KB

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