docker_api_containers_test.go 43 KB

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