docker_api_containers_test.go 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  1. package main
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/docker/docker/api/types"
  17. containertypes "github.com/docker/docker/api/types/container"
  18. mounttypes "github.com/docker/docker/api/types/mount"
  19. networktypes "github.com/docker/docker/api/types/network"
  20. "github.com/docker/docker/client"
  21. "github.com/docker/docker/integration-cli/checker"
  22. "github.com/docker/docker/integration-cli/cli"
  23. "github.com/docker/docker/integration-cli/cli/build"
  24. "github.com/docker/docker/integration-cli/request"
  25. "github.com/docker/docker/pkg/ioutils"
  26. "github.com/docker/docker/pkg/mount"
  27. "github.com/docker/docker/pkg/stringid"
  28. "github.com/docker/docker/volume"
  29. "github.com/docker/go-connections/nat"
  30. "github.com/go-check/check"
  31. "github.com/gotestyourself/gotestyourself/poll"
  32. "github.com/stretchr/testify/assert"
  33. "github.com/stretchr/testify/require"
  34. "golang.org/x/net/context"
  35. )
  36. func (s *DockerSuite) TestContainerAPIGetAll(c *check.C) {
  37. startCount := getContainerCount(c)
  38. name := "getall"
  39. dockerCmd(c, "run", "--name", name, "busybox", "true")
  40. cli, err := client.NewEnvClient()
  41. c.Assert(err, checker.IsNil)
  42. defer cli.Close()
  43. options := types.ContainerListOptions{
  44. All: true,
  45. }
  46. containers, err := cli.ContainerList(context.Background(), options)
  47. c.Assert(err, checker.IsNil)
  48. c.Assert(containers, checker.HasLen, startCount+1)
  49. actual := containers[0].Names[0]
  50. c.Assert(actual, checker.Equals, "/"+name)
  51. }
  52. // regression test for empty json field being omitted #13691
  53. func (s *DockerSuite) TestContainerAPIGetJSONNoFieldsOmitted(c *check.C) {
  54. startCount := getContainerCount(c)
  55. dockerCmd(c, "run", "busybox", "true")
  56. cli, err := client.NewEnvClient()
  57. c.Assert(err, checker.IsNil)
  58. defer cli.Close()
  59. options := types.ContainerListOptions{
  60. All: true,
  61. }
  62. containers, err := cli.ContainerList(context.Background(), options)
  63. c.Assert(err, checker.IsNil)
  64. c.Assert(containers, checker.HasLen, startCount+1)
  65. actual := fmt.Sprintf("%+v", containers[0])
  66. // empty Labels field triggered this bug, make sense to check for everything
  67. // cause even Ports for instance can trigger this bug
  68. // better safe than sorry..
  69. fields := []string{
  70. "ID",
  71. "Names",
  72. "Image",
  73. "Command",
  74. "Created",
  75. "Ports",
  76. "Labels",
  77. "Status",
  78. "NetworkSettings",
  79. }
  80. // decoding into types.Container do not work since it eventually unmarshal
  81. // and empty field to an empty go map, so we just check for a string
  82. for _, f := range fields {
  83. if !strings.Contains(actual, f) {
  84. c.Fatalf("Field %s is missing and it shouldn't", f)
  85. }
  86. }
  87. }
  88. type containerPs struct {
  89. Names []string
  90. Ports []types.Port
  91. }
  92. // regression test for non-empty fields from #13901
  93. func (s *DockerSuite) TestContainerAPIPsOmitFields(c *check.C) {
  94. // Problematic for Windows porting due to networking not yet being passed back
  95. testRequires(c, DaemonIsLinux)
  96. name := "pstest"
  97. port := 80
  98. runSleepingContainer(c, "--name", name, "--expose", strconv.Itoa(port))
  99. cli, err := client.NewEnvClient()
  100. c.Assert(err, checker.IsNil)
  101. defer cli.Close()
  102. options := types.ContainerListOptions{
  103. All: true,
  104. }
  105. containers, err := cli.ContainerList(context.Background(), options)
  106. c.Assert(err, checker.IsNil)
  107. var foundContainer containerPs
  108. for _, c := range containers {
  109. for _, testName := range c.Names {
  110. if "/"+name == testName {
  111. foundContainer.Names = c.Names
  112. foundContainer.Ports = c.Ports
  113. break
  114. }
  115. }
  116. }
  117. c.Assert(foundContainer.Ports, checker.HasLen, 1)
  118. c.Assert(foundContainer.Ports[0].PrivatePort, checker.Equals, uint16(port))
  119. c.Assert(foundContainer.Ports[0].PublicPort, checker.NotNil)
  120. c.Assert(foundContainer.Ports[0].IP, checker.NotNil)
  121. }
  122. func (s *DockerSuite) TestContainerAPIGetExport(c *check.C) {
  123. // Not supported on Windows as Windows does not support docker export
  124. testRequires(c, DaemonIsLinux)
  125. name := "exportcontainer"
  126. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test")
  127. cli, err := client.NewEnvClient()
  128. c.Assert(err, checker.IsNil)
  129. defer cli.Close()
  130. body, err := cli.ContainerExport(context.Background(), name)
  131. c.Assert(err, checker.IsNil)
  132. defer body.Close()
  133. found := false
  134. for tarReader := tar.NewReader(body); ; {
  135. h, err := tarReader.Next()
  136. if err != nil && err == io.EOF {
  137. break
  138. }
  139. if h.Name == "test" {
  140. found = true
  141. break
  142. }
  143. }
  144. c.Assert(found, checker.True, check.Commentf("The created test file has not been found in the exported image"))
  145. }
  146. func (s *DockerSuite) TestContainerAPIGetChanges(c *check.C) {
  147. // Not supported on Windows as Windows does not support docker diff (/containers/name/changes)
  148. testRequires(c, DaemonIsLinux)
  149. name := "changescontainer"
  150. dockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd")
  151. cli, err := client.NewEnvClient()
  152. c.Assert(err, checker.IsNil)
  153. defer cli.Close()
  154. changes, err := cli.ContainerDiff(context.Background(), name)
  155. c.Assert(err, checker.IsNil)
  156. // Check the changelog for removal of /etc/passwd
  157. success := false
  158. for _, elem := range changes {
  159. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  160. success = true
  161. }
  162. }
  163. c.Assert(success, checker.True, check.Commentf("/etc/passwd has been removed but is not present in the diff"))
  164. }
  165. func (s *DockerSuite) TestGetContainerStats(c *check.C) {
  166. var (
  167. name = "statscontainer"
  168. )
  169. runSleepingContainer(c, "--name", name)
  170. type b struct {
  171. stats types.ContainerStats
  172. err error
  173. }
  174. bc := make(chan b, 1)
  175. go func() {
  176. cli, err := client.NewEnvClient()
  177. c.Assert(err, checker.IsNil)
  178. defer cli.Close()
  179. stats, err := cli.ContainerStats(context.Background(), name, true)
  180. c.Assert(err, checker.IsNil)
  181. bc <- b{stats, err}
  182. }()
  183. // allow some time to stream the stats from the container
  184. time.Sleep(4 * time.Second)
  185. dockerCmd(c, "rm", "-f", name)
  186. // collect the results from the stats stream or timeout and fail
  187. // if the stream was not disconnected.
  188. select {
  189. case <-time.After(2 * time.Second):
  190. c.Fatal("stream was not closed after container was removed")
  191. case sr := <-bc:
  192. dec := json.NewDecoder(sr.stats.Body)
  193. defer sr.stats.Body.Close()
  194. var s *types.Stats
  195. // decode only one object from the stream
  196. c.Assert(dec.Decode(&s), checker.IsNil)
  197. }
  198. }
  199. func (s *DockerSuite) TestGetContainerStatsRmRunning(c *check.C) {
  200. out := runSleepingContainer(c)
  201. id := strings.TrimSpace(out)
  202. buf := &ChannelBuffer{C: make(chan []byte, 1)}
  203. defer buf.Close()
  204. cli, err := client.NewEnvClient()
  205. c.Assert(err, checker.IsNil)
  206. defer cli.Close()
  207. stats, err := cli.ContainerStats(context.Background(), id, true)
  208. c.Assert(err, checker.IsNil)
  209. defer stats.Body.Close()
  210. chErr := make(chan error, 1)
  211. go func() {
  212. _, err = io.Copy(buf, stats.Body)
  213. chErr <- err
  214. }()
  215. b := make([]byte, 32)
  216. // make sure we've got some stats
  217. _, err = buf.ReadTimeout(b, 2*time.Second)
  218. c.Assert(err, checker.IsNil)
  219. // Now remove without `-f` and make sure we are still pulling stats
  220. _, _, err = dockerCmdWithError("rm", id)
  221. c.Assert(err, checker.Not(checker.IsNil), check.Commentf("rm should have failed but didn't"))
  222. _, err = buf.ReadTimeout(b, 2*time.Second)
  223. c.Assert(err, checker.IsNil)
  224. dockerCmd(c, "rm", "-f", id)
  225. c.Assert(<-chErr, checker.IsNil)
  226. }
  227. // ChannelBuffer holds a chan of byte array that can be populate in a goroutine.
  228. type ChannelBuffer struct {
  229. C chan []byte
  230. }
  231. // Write implements Writer.
  232. func (c *ChannelBuffer) Write(b []byte) (int, error) {
  233. c.C <- b
  234. return len(b), nil
  235. }
  236. // Close closes the go channel.
  237. func (c *ChannelBuffer) Close() error {
  238. close(c.C)
  239. return nil
  240. }
  241. // ReadTimeout reads the content of the channel in the specified byte array with
  242. // the specified duration as timeout.
  243. func (c *ChannelBuffer) ReadTimeout(p []byte, n time.Duration) (int, error) {
  244. select {
  245. case b := <-c.C:
  246. return copy(p[0:], b), nil
  247. case <-time.After(n):
  248. return -1, fmt.Errorf("timeout reading from channel")
  249. }
  250. }
  251. // regression test for gh13421
  252. // previous test was just checking one stat entry so it didn't fail (stats with
  253. // stream false always return one stat)
  254. func (s *DockerSuite) TestGetContainerStatsStream(c *check.C) {
  255. name := "statscontainer"
  256. runSleepingContainer(c, "--name", name)
  257. type b struct {
  258. stats types.ContainerStats
  259. err error
  260. }
  261. bc := make(chan b, 1)
  262. go func() {
  263. cli, err := client.NewEnvClient()
  264. c.Assert(err, checker.IsNil)
  265. defer cli.Close()
  266. stats, err := cli.ContainerStats(context.Background(), name, true)
  267. c.Assert(err, checker.IsNil)
  268. bc <- b{stats, err}
  269. }()
  270. // allow some time to stream the stats from the container
  271. time.Sleep(4 * time.Second)
  272. dockerCmd(c, "rm", "-f", name)
  273. // collect the results from the stats stream or timeout and fail
  274. // if the stream was not disconnected.
  275. select {
  276. case <-time.After(2 * time.Second):
  277. c.Fatal("stream was not closed after container was removed")
  278. case sr := <-bc:
  279. b, err := ioutil.ReadAll(sr.stats.Body)
  280. defer sr.stats.Body.Close()
  281. c.Assert(err, checker.IsNil)
  282. s := string(b)
  283. // count occurrences of "read" of types.Stats
  284. if l := strings.Count(s, "read"); l < 2 {
  285. c.Fatalf("Expected more than one stat streamed, got %d", l)
  286. }
  287. }
  288. }
  289. func (s *DockerSuite) TestGetContainerStatsNoStream(c *check.C) {
  290. name := "statscontainer"
  291. runSleepingContainer(c, "--name", name)
  292. type b struct {
  293. stats types.ContainerStats
  294. err error
  295. }
  296. bc := make(chan b, 1)
  297. go func() {
  298. cli, err := client.NewEnvClient()
  299. c.Assert(err, checker.IsNil)
  300. defer cli.Close()
  301. stats, err := cli.ContainerStats(context.Background(), name, false)
  302. c.Assert(err, checker.IsNil)
  303. bc <- b{stats, err}
  304. }()
  305. // allow some time to stream the stats from the container
  306. time.Sleep(4 * time.Second)
  307. dockerCmd(c, "rm", "-f", name)
  308. // collect the results from the stats stream or timeout and fail
  309. // if the stream was not disconnected.
  310. select {
  311. case <-time.After(2 * time.Second):
  312. c.Fatal("stream was not closed after container was removed")
  313. case sr := <-bc:
  314. b, err := ioutil.ReadAll(sr.stats.Body)
  315. defer sr.stats.Body.Close()
  316. c.Assert(err, checker.IsNil)
  317. s := string(b)
  318. // count occurrences of `"read"` of types.Stats
  319. c.Assert(strings.Count(s, `"read"`), checker.Equals, 1, check.Commentf("Expected only one stat streamed, got %d", strings.Count(s, `"read"`)))
  320. }
  321. }
  322. func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) {
  323. name := "statscontainer"
  324. dockerCmd(c, "create", "--name", name, "busybox", "ps")
  325. chResp := make(chan error)
  326. // We expect an immediate response, but if it's not immediate, the test would hang, so put it in a goroutine
  327. // below we'll check this on a timeout.
  328. go func() {
  329. cli, err := client.NewEnvClient()
  330. c.Assert(err, checker.IsNil)
  331. defer cli.Close()
  332. resp, err := cli.ContainerStats(context.Background(), name, false)
  333. defer resp.Body.Close()
  334. chResp <- err
  335. }()
  336. select {
  337. case err := <-chResp:
  338. c.Assert(err, checker.IsNil)
  339. case <-time.After(10 * time.Second):
  340. c.Fatal("timeout waiting for stats response for stopped container")
  341. }
  342. }
  343. func (s *DockerSuite) TestContainerAPIPause(c *check.C) {
  344. // Problematic on Windows as Windows does not support pause
  345. testRequires(c, DaemonIsLinux)
  346. getPaused := func(c *check.C) []string {
  347. return strings.Fields(cli.DockerCmd(c, "ps", "-f", "status=paused", "-q", "-a").Combined())
  348. }
  349. out := cli.DockerCmd(c, "run", "-d", "busybox", "sleep", "30").Combined()
  350. ContainerID := strings.TrimSpace(out)
  351. cli, err := client.NewEnvClient()
  352. c.Assert(err, checker.IsNil)
  353. defer cli.Close()
  354. err = cli.ContainerPause(context.Background(), ContainerID)
  355. c.Assert(err, checker.IsNil)
  356. pausedContainers := getPaused(c)
  357. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  358. c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  359. }
  360. err = cli.ContainerUnpause(context.Background(), ContainerID)
  361. c.Assert(err, checker.IsNil)
  362. pausedContainers = getPaused(c)
  363. c.Assert(pausedContainers, checker.HasLen, 0, check.Commentf("There should be no paused container."))
  364. }
  365. func (s *DockerSuite) TestContainerAPITop(c *check.C) {
  366. testRequires(c, DaemonIsLinux)
  367. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top")
  368. id := strings.TrimSpace(string(out))
  369. c.Assert(waitRun(id), checker.IsNil)
  370. cli, err := client.NewEnvClient()
  371. c.Assert(err, checker.IsNil)
  372. defer cli.Close()
  373. top, err := cli.ContainerTop(context.Background(), id, []string{"aux"})
  374. c.Assert(err, checker.IsNil)
  375. c.Assert(top.Titles, checker.HasLen, 11, check.Commentf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles))
  376. if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
  377. c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
  378. }
  379. c.Assert(top.Processes, checker.HasLen, 2, check.Commentf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes))
  380. c.Assert(top.Processes[0][10], checker.Equals, "/bin/sh -c top")
  381. c.Assert(top.Processes[1][10], checker.Equals, "top")
  382. }
  383. func (s *DockerSuite) TestContainerAPITopWindows(c *check.C) {
  384. testRequires(c, DaemonIsWindows)
  385. out := runSleepingContainer(c, "-d")
  386. id := strings.TrimSpace(string(out))
  387. c.Assert(waitRun(id), checker.IsNil)
  388. cli, err := client.NewEnvClient()
  389. c.Assert(err, checker.IsNil)
  390. defer cli.Close()
  391. top, err := cli.ContainerTop(context.Background(), id, nil)
  392. c.Assert(err, checker.IsNil)
  393. c.Assert(top.Titles, checker.HasLen, 4, check.Commentf("expected 4 titles, found %d: %v", len(top.Titles), top.Titles))
  394. if top.Titles[0] != "Name" || top.Titles[3] != "Private Working Set" {
  395. c.Fatalf("expected `Name` at `Titles[0]` and `Private Working Set` at Titles[3]: %v", top.Titles)
  396. }
  397. c.Assert(len(top.Processes), checker.GreaterOrEqualThan, 2, check.Commentf("expected at least 2 processes, found %d: %v", len(top.Processes), top.Processes))
  398. foundProcess := false
  399. expectedProcess := "busybox.exe"
  400. for _, process := range top.Processes {
  401. if process[0] == expectedProcess {
  402. foundProcess = true
  403. break
  404. }
  405. }
  406. c.Assert(foundProcess, checker.Equals, true, check.Commentf("expected to find %s: %v", expectedProcess, top.Processes))
  407. }
  408. func (s *DockerSuite) TestContainerAPICommit(c *check.C) {
  409. cName := "testapicommit"
  410. dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
  411. cli, err := client.NewEnvClient()
  412. c.Assert(err, checker.IsNil)
  413. defer cli.Close()
  414. options := types.ContainerCommitOptions{
  415. Reference: "testcontainerapicommit:testtag",
  416. }
  417. img, err := cli.ContainerCommit(context.Background(), cName, options)
  418. c.Assert(err, checker.IsNil)
  419. cmd := inspectField(c, img.ID, "Config.Cmd")
  420. c.Assert(cmd, checker.Equals, "[/bin/sh -c touch /test]", check.Commentf("got wrong Cmd from commit: %q", cmd))
  421. // sanity check, make sure the image is what we think it is
  422. dockerCmd(c, "run", img.ID, "ls", "/test")
  423. }
  424. func (s *DockerSuite) TestContainerAPICommitWithLabelInConfig(c *check.C) {
  425. cName := "testapicommitwithconfig"
  426. dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
  427. cli, err := client.NewEnvClient()
  428. c.Assert(err, checker.IsNil)
  429. defer cli.Close()
  430. config := containertypes.Config{
  431. Labels: map[string]string{"key1": "value1", "key2": "value2"}}
  432. options := types.ContainerCommitOptions{
  433. Reference: "testcontainerapicommitwithconfig",
  434. Config: &config,
  435. }
  436. img, err := cli.ContainerCommit(context.Background(), cName, options)
  437. c.Assert(err, checker.IsNil)
  438. label1 := inspectFieldMap(c, img.ID, "Config.Labels", "key1")
  439. c.Assert(label1, checker.Equals, "value1")
  440. label2 := inspectFieldMap(c, img.ID, "Config.Labels", "key2")
  441. c.Assert(label2, checker.Equals, "value2")
  442. cmd := inspectField(c, img.ID, "Config.Cmd")
  443. c.Assert(cmd, checker.Equals, "[/bin/sh -c touch /test]", check.Commentf("got wrong Cmd from commit: %q", cmd))
  444. // sanity check, make sure the image is what we think it is
  445. dockerCmd(c, "run", img.ID, "ls", "/test")
  446. }
  447. func (s *DockerSuite) TestContainerAPIBadPort(c *check.C) {
  448. // TODO Windows to Windows CI - Port this test
  449. testRequires(c, DaemonIsLinux)
  450. config := containertypes.Config{
  451. Image: "busybox",
  452. Cmd: []string{"/bin/sh", "-c", "echo test"},
  453. }
  454. hostConfig := containertypes.HostConfig{
  455. PortBindings: nat.PortMap{
  456. "8080/tcp": []nat.PortBinding{
  457. {
  458. HostIP: "",
  459. HostPort: "aa80"},
  460. },
  461. },
  462. }
  463. cli, err := client.NewEnvClient()
  464. c.Assert(err, checker.IsNil)
  465. defer cli.Close()
  466. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "")
  467. c.Assert(err.Error(), checker.Contains, `invalid port specification: "aa80"`)
  468. }
  469. func (s *DockerSuite) TestContainerAPICreate(c *check.C) {
  470. config := containertypes.Config{
  471. Image: "busybox",
  472. Cmd: []string{"/bin/sh", "-c", "touch /test && ls /test"},
  473. }
  474. cli, err := client.NewEnvClient()
  475. c.Assert(err, checker.IsNil)
  476. defer cli.Close()
  477. container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
  478. c.Assert(err, checker.IsNil)
  479. out, _ := dockerCmd(c, "start", "-a", container.ID)
  480. c.Assert(strings.TrimSpace(out), checker.Equals, "/test")
  481. }
  482. func (s *DockerSuite) TestContainerAPICreateEmptyConfig(c *check.C) {
  483. cli, err := client.NewEnvClient()
  484. c.Assert(err, checker.IsNil)
  485. defer cli.Close()
  486. _, err = cli.ContainerCreate(context.Background(), &containertypes.Config{}, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
  487. expected := "No command specified"
  488. c.Assert(err.Error(), checker.Contains, expected)
  489. }
  490. func (s *DockerSuite) TestContainerAPICreateMultipleNetworksConfig(c *check.C) {
  491. // Container creation must fail if client specified configurations for more than one network
  492. config := containertypes.Config{
  493. Image: "busybox",
  494. }
  495. networkingConfig := networktypes.NetworkingConfig{
  496. EndpointsConfig: map[string]*networktypes.EndpointSettings{
  497. "net1": {},
  498. "net2": {},
  499. "net3": {},
  500. },
  501. }
  502. cli, err := client.NewEnvClient()
  503. c.Assert(err, checker.IsNil)
  504. defer cli.Close()
  505. _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networkingConfig, "")
  506. msg := err.Error()
  507. // network name order in error message is not deterministic
  508. c.Assert(msg, checker.Contains, "Container cannot be connected to network endpoints")
  509. c.Assert(msg, checker.Contains, "net1")
  510. c.Assert(msg, checker.Contains, "net2")
  511. c.Assert(msg, checker.Contains, "net3")
  512. }
  513. func (s *DockerSuite) TestContainerAPICreateWithHostName(c *check.C) {
  514. domainName := "test-domain"
  515. hostName := "test-hostname"
  516. config := containertypes.Config{
  517. Image: "busybox",
  518. Hostname: hostName,
  519. Domainname: domainName,
  520. }
  521. cli, err := client.NewEnvClient()
  522. c.Assert(err, checker.IsNil)
  523. defer cli.Close()
  524. container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
  525. c.Assert(err, checker.IsNil)
  526. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  527. c.Assert(err, checker.IsNil)
  528. c.Assert(containerJSON.Config.Hostname, checker.Equals, hostName, check.Commentf("Mismatched Hostname"))
  529. c.Assert(containerJSON.Config.Domainname, checker.Equals, domainName, check.Commentf("Mismatched Domainname"))
  530. }
  531. func (s *DockerSuite) TestContainerAPICreateBridgeNetworkMode(c *check.C) {
  532. // Windows does not support bridge
  533. testRequires(c, DaemonIsLinux)
  534. UtilCreateNetworkMode(c, "bridge")
  535. }
  536. func (s *DockerSuite) TestContainerAPICreateOtherNetworkModes(c *check.C) {
  537. // Windows does not support these network modes
  538. testRequires(c, DaemonIsLinux, NotUserNamespace)
  539. UtilCreateNetworkMode(c, "host")
  540. UtilCreateNetworkMode(c, "container:web1")
  541. }
  542. func UtilCreateNetworkMode(c *check.C, networkMode containertypes.NetworkMode) {
  543. config := containertypes.Config{
  544. Image: "busybox",
  545. }
  546. hostConfig := containertypes.HostConfig{
  547. NetworkMode: networkMode,
  548. }
  549. cli, err := client.NewEnvClient()
  550. c.Assert(err, checker.IsNil)
  551. defer cli.Close()
  552. container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "")
  553. c.Assert(err, checker.IsNil)
  554. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  555. c.Assert(err, checker.IsNil)
  556. c.Assert(containerJSON.HostConfig.NetworkMode, checker.Equals, containertypes.NetworkMode(networkMode), check.Commentf("Mismatched NetworkMode"))
  557. }
  558. func (s *DockerSuite) TestContainerAPICreateWithCpuSharesCpuset(c *check.C) {
  559. // TODO Windows to Windows CI. The CpuShares part could be ported.
  560. testRequires(c, DaemonIsLinux)
  561. config := containertypes.Config{
  562. Image: "busybox",
  563. }
  564. hostConfig := containertypes.HostConfig{
  565. Resources: containertypes.Resources{
  566. CPUShares: 512,
  567. CpusetCpus: "0",
  568. },
  569. }
  570. cli, err := client.NewEnvClient()
  571. c.Assert(err, checker.IsNil)
  572. defer cli.Close()
  573. container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "")
  574. c.Assert(err, checker.IsNil)
  575. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  576. c.Assert(err, checker.IsNil)
  577. out := inspectField(c, containerJSON.ID, "HostConfig.CpuShares")
  578. c.Assert(out, checker.Equals, "512")
  579. outCpuset := inspectField(c, containerJSON.ID, "HostConfig.CpusetCpus")
  580. c.Assert(outCpuset, checker.Equals, "0")
  581. }
  582. func (s *DockerSuite) TestContainerAPIVerifyHeader(c *check.C) {
  583. config := map[string]interface{}{
  584. "Image": "busybox",
  585. }
  586. create := func(ct string) (*http.Response, io.ReadCloser, error) {
  587. jsonData := bytes.NewBuffer(nil)
  588. c.Assert(json.NewEncoder(jsonData).Encode(config), checker.IsNil)
  589. return request.Post("/containers/create", request.RawContent(ioutil.NopCloser(jsonData)), request.ContentType(ct))
  590. }
  591. // Try with no content-type
  592. res, body, err := create("")
  593. c.Assert(err, checker.IsNil)
  594. c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
  595. body.Close()
  596. // Try with wrong content-type
  597. res, body, err = create("application/xml")
  598. c.Assert(err, checker.IsNil)
  599. c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
  600. body.Close()
  601. // now application/json
  602. res, body, err = create("application/json")
  603. c.Assert(err, checker.IsNil)
  604. c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
  605. body.Close()
  606. }
  607. //Issue 14230. daemon should return 500 for invalid port syntax
  608. func (s *DockerSuite) TestContainerAPIInvalidPortSyntax(c *check.C) {
  609. config := `{
  610. "Image": "busybox",
  611. "HostConfig": {
  612. "NetworkMode": "default",
  613. "PortBindings": {
  614. "19039;1230": [
  615. {}
  616. ]
  617. }
  618. }
  619. }`
  620. res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON)
  621. c.Assert(err, checker.IsNil)
  622. c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
  623. b, err := request.ReadBody(body)
  624. c.Assert(err, checker.IsNil)
  625. c.Assert(string(b[:]), checker.Contains, "invalid port")
  626. }
  627. func (s *DockerSuite) TestContainerAPIRestartPolicyInvalidPolicyName(c *check.C) {
  628. config := `{
  629. "Image": "busybox",
  630. "HostConfig": {
  631. "RestartPolicy": {
  632. "Name": "something",
  633. "MaximumRetryCount": 0
  634. }
  635. }
  636. }`
  637. res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON)
  638. c.Assert(err, checker.IsNil)
  639. c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
  640. b, err := request.ReadBody(body)
  641. c.Assert(err, checker.IsNil)
  642. c.Assert(string(b[:]), checker.Contains, "invalid restart policy")
  643. }
  644. func (s *DockerSuite) TestContainerAPIRestartPolicyRetryMismatch(c *check.C) {
  645. config := `{
  646. "Image": "busybox",
  647. "HostConfig": {
  648. "RestartPolicy": {
  649. "Name": "always",
  650. "MaximumRetryCount": 2
  651. }
  652. }
  653. }`
  654. res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON)
  655. c.Assert(err, checker.IsNil)
  656. c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
  657. b, err := request.ReadBody(body)
  658. c.Assert(err, checker.IsNil)
  659. c.Assert(string(b[:]), checker.Contains, "maximum retry count cannot be used with restart policy")
  660. }
  661. func (s *DockerSuite) TestContainerAPIRestartPolicyNegativeRetryCount(c *check.C) {
  662. config := `{
  663. "Image": "busybox",
  664. "HostConfig": {
  665. "RestartPolicy": {
  666. "Name": "on-failure",
  667. "MaximumRetryCount": -2
  668. }
  669. }
  670. }`
  671. res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON)
  672. c.Assert(err, checker.IsNil)
  673. c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
  674. b, err := request.ReadBody(body)
  675. c.Assert(err, checker.IsNil)
  676. c.Assert(string(b[:]), checker.Contains, "maximum retry count cannot be negative")
  677. }
  678. func (s *DockerSuite) TestContainerAPIRestartPolicyDefaultRetryCount(c *check.C) {
  679. config := `{
  680. "Image": "busybox",
  681. "HostConfig": {
  682. "RestartPolicy": {
  683. "Name": "on-failure",
  684. "MaximumRetryCount": 0
  685. }
  686. }
  687. }`
  688. res, _, err := request.Post("/containers/create", request.RawString(config), request.JSON)
  689. c.Assert(err, checker.IsNil)
  690. c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
  691. }
  692. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  693. // W/o this fix a null in JSON would be parsed into a string var as "null"
  694. func (s *DockerSuite) TestContainerAPIPostCreateNull(c *check.C) {
  695. config := `{
  696. "Hostname":"",
  697. "Domainname":"",
  698. "Memory":0,
  699. "MemorySwap":0,
  700. "CpuShares":0,
  701. "Cpuset":null,
  702. "AttachStdin":true,
  703. "AttachStdout":true,
  704. "AttachStderr":true,
  705. "ExposedPorts":{},
  706. "Tty":true,
  707. "OpenStdin":true,
  708. "StdinOnce":true,
  709. "Env":[],
  710. "Cmd":"ls",
  711. "Image":"busybox",
  712. "Volumes":{},
  713. "WorkingDir":"",
  714. "Entrypoint":null,
  715. "NetworkDisabled":false,
  716. "OnBuild":null}`
  717. res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON)
  718. c.Assert(err, checker.IsNil)
  719. c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
  720. b, err := request.ReadBody(body)
  721. c.Assert(err, checker.IsNil)
  722. type createResp struct {
  723. ID string
  724. }
  725. var container createResp
  726. c.Assert(json.Unmarshal(b, &container), checker.IsNil)
  727. out := inspectField(c, container.ID, "HostConfig.CpusetCpus")
  728. c.Assert(out, checker.Equals, "")
  729. outMemory := inspectField(c, container.ID, "HostConfig.Memory")
  730. c.Assert(outMemory, checker.Equals, "0")
  731. outMemorySwap := inspectField(c, container.ID, "HostConfig.MemorySwap")
  732. c.Assert(outMemorySwap, checker.Equals, "0")
  733. }
  734. func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) {
  735. // TODO Windows: Port once memory is supported
  736. testRequires(c, DaemonIsLinux)
  737. config := `{
  738. "Image": "busybox",
  739. "Cmd": "ls",
  740. "OpenStdin": true,
  741. "CpuShares": 100,
  742. "Memory": 524287
  743. }`
  744. res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON)
  745. c.Assert(err, checker.IsNil)
  746. b, err2 := request.ReadBody(body)
  747. c.Assert(err2, checker.IsNil)
  748. c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
  749. c.Assert(string(b), checker.Contains, "Minimum memory limit allowed is 4MB")
  750. }
  751. func (s *DockerSuite) TestContainerAPIRename(c *check.C) {
  752. out, _ := dockerCmd(c, "run", "--name", "TestContainerAPIRename", "-d", "busybox", "sh")
  753. containerID := strings.TrimSpace(out)
  754. newName := "TestContainerAPIRenameNew"
  755. cli, err := client.NewEnvClient()
  756. c.Assert(err, checker.IsNil)
  757. defer cli.Close()
  758. err = cli.ContainerRename(context.Background(), containerID, newName)
  759. c.Assert(err, checker.IsNil)
  760. name := inspectField(c, containerID, "Name")
  761. c.Assert(name, checker.Equals, "/"+newName, check.Commentf("Failed to rename container"))
  762. }
  763. func (s *DockerSuite) TestContainerAPIKill(c *check.C) {
  764. name := "test-api-kill"
  765. runSleepingContainer(c, "-i", "--name", name)
  766. cli, err := client.NewEnvClient()
  767. c.Assert(err, checker.IsNil)
  768. defer cli.Close()
  769. err = cli.ContainerKill(context.Background(), name, "SIGKILL")
  770. c.Assert(err, checker.IsNil)
  771. state := inspectField(c, name, "State.Running")
  772. c.Assert(state, checker.Equals, "false", check.Commentf("got wrong State from container %s: %q", name, state))
  773. }
  774. func (s *DockerSuite) TestContainerAPIRestart(c *check.C) {
  775. name := "test-api-restart"
  776. runSleepingContainer(c, "-di", "--name", name)
  777. cli, err := client.NewEnvClient()
  778. c.Assert(err, checker.IsNil)
  779. defer cli.Close()
  780. timeout := 1 * time.Second
  781. err = cli.ContainerRestart(context.Background(), name, &timeout)
  782. c.Assert(err, checker.IsNil)
  783. c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second), checker.IsNil)
  784. }
  785. func (s *DockerSuite) TestContainerAPIRestartNotimeoutParam(c *check.C) {
  786. name := "test-api-restart-no-timeout-param"
  787. out := runSleepingContainer(c, "-di", "--name", name)
  788. id := strings.TrimSpace(out)
  789. c.Assert(waitRun(id), checker.IsNil)
  790. cli, err := client.NewEnvClient()
  791. c.Assert(err, checker.IsNil)
  792. defer cli.Close()
  793. err = cli.ContainerRestart(context.Background(), name, nil)
  794. c.Assert(err, checker.IsNil)
  795. c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second), checker.IsNil)
  796. }
  797. func (s *DockerSuite) TestContainerAPIStart(c *check.C) {
  798. name := "testing-start"
  799. config := containertypes.Config{
  800. Image: "busybox",
  801. Cmd: append([]string{"/bin/sh", "-c"}, sleepCommandForDaemonPlatform()...),
  802. OpenStdin: true,
  803. }
  804. cli, err := client.NewEnvClient()
  805. c.Assert(err, checker.IsNil)
  806. defer cli.Close()
  807. _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, name)
  808. c.Assert(err, checker.IsNil)
  809. err = cli.ContainerStart(context.Background(), name, types.ContainerStartOptions{})
  810. c.Assert(err, checker.IsNil)
  811. // second call to start should give 304
  812. // maybe add ContainerStartWithRaw to test it
  813. err = cli.ContainerStart(context.Background(), name, types.ContainerStartOptions{})
  814. c.Assert(err, checker.IsNil)
  815. // TODO(tibor): figure out why this doesn't work on windows
  816. }
  817. func (s *DockerSuite) TestContainerAPIStop(c *check.C) {
  818. name := "test-api-stop"
  819. runSleepingContainer(c, "-i", "--name", name)
  820. timeout := 30 * time.Second
  821. cli, err := client.NewEnvClient()
  822. c.Assert(err, checker.IsNil)
  823. defer cli.Close()
  824. err = cli.ContainerStop(context.Background(), name, &timeout)
  825. c.Assert(err, checker.IsNil)
  826. c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil)
  827. // second call to start should give 304
  828. // maybe add ContainerStartWithRaw to test it
  829. err = cli.ContainerStop(context.Background(), name, &timeout)
  830. c.Assert(err, checker.IsNil)
  831. }
  832. func (s *DockerSuite) TestContainerAPIWait(c *check.C) {
  833. name := "test-api-wait"
  834. sleepCmd := "/bin/sleep"
  835. if testEnv.DaemonPlatform() == "windows" {
  836. sleepCmd = "sleep"
  837. }
  838. dockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "2")
  839. cli, err := client.NewEnvClient()
  840. c.Assert(err, checker.IsNil)
  841. defer cli.Close()
  842. waitresC, errC := cli.ContainerWait(context.Background(), name, "")
  843. select {
  844. case err = <-errC:
  845. c.Assert(err, checker.IsNil)
  846. case waitres := <-waitresC:
  847. c.Assert(waitres.StatusCode, checker.Equals, int64(0))
  848. }
  849. }
  850. func (s *DockerSuite) TestContainerAPICopyNotExistsAnyMore(c *check.C) {
  851. name := "test-container-api-copy"
  852. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  853. postData := types.CopyConfig{
  854. Resource: "/test.txt",
  855. }
  856. // no copy in client/
  857. res, _, err := request.Post("/containers/"+name+"/copy", request.JSONBody(postData))
  858. c.Assert(err, checker.IsNil)
  859. c.Assert(res.StatusCode, checker.Equals, http.StatusNotFound)
  860. }
  861. func (s *DockerSuite) TestContainerAPICopyPre124(c *check.C) {
  862. testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later
  863. name := "test-container-api-copy"
  864. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  865. postData := types.CopyConfig{
  866. Resource: "/test.txt",
  867. }
  868. res, body, err := request.Post("/v1.23/containers/"+name+"/copy", request.JSONBody(postData))
  869. c.Assert(err, checker.IsNil)
  870. c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
  871. found := false
  872. for tarReader := tar.NewReader(body); ; {
  873. h, err := tarReader.Next()
  874. if err != nil {
  875. if err == io.EOF {
  876. break
  877. }
  878. c.Fatal(err)
  879. }
  880. if h.Name == "test.txt" {
  881. found = true
  882. break
  883. }
  884. }
  885. c.Assert(found, checker.True)
  886. }
  887. func (s *DockerSuite) TestContainerAPICopyResourcePathEmptyPre124(c *check.C) {
  888. testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later
  889. name := "test-container-api-copy-resource-empty"
  890. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  891. postData := types.CopyConfig{
  892. Resource: "",
  893. }
  894. res, body, err := request.Post("/v1.23/containers/"+name+"/copy", request.JSONBody(postData))
  895. c.Assert(err, checker.IsNil)
  896. c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest)
  897. b, err := request.ReadBody(body)
  898. c.Assert(err, checker.IsNil)
  899. c.Assert(string(b), checker.Matches, "Path cannot be empty\n")
  900. }
  901. func (s *DockerSuite) TestContainerAPICopyResourcePathNotFoundPre124(c *check.C) {
  902. testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later
  903. name := "test-container-api-copy-resource-not-found"
  904. dockerCmd(c, "run", "--name", name, "busybox")
  905. postData := types.CopyConfig{
  906. Resource: "/notexist",
  907. }
  908. res, body, err := request.Post("/v1.23/containers/"+name+"/copy", request.JSONBody(postData))
  909. c.Assert(err, checker.IsNil)
  910. c.Assert(res.StatusCode, checker.Equals, http.StatusNotFound)
  911. b, err := request.ReadBody(body)
  912. c.Assert(err, checker.IsNil)
  913. c.Assert(string(b), checker.Matches, "Could not find the file /notexist in container "+name+"\n")
  914. }
  915. func (s *DockerSuite) TestContainerAPICopyContainerNotFoundPr124(c *check.C) {
  916. testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later
  917. postData := types.CopyConfig{
  918. Resource: "/something",
  919. }
  920. res, _, err := request.Post("/v1.23/containers/notexists/copy", request.JSONBody(postData))
  921. c.Assert(err, checker.IsNil)
  922. c.Assert(res.StatusCode, checker.Equals, http.StatusNotFound)
  923. }
  924. func (s *DockerSuite) TestContainerAPIDelete(c *check.C) {
  925. out := runSleepingContainer(c)
  926. id := strings.TrimSpace(out)
  927. c.Assert(waitRun(id), checker.IsNil)
  928. dockerCmd(c, "stop", id)
  929. cli, err := client.NewEnvClient()
  930. c.Assert(err, checker.IsNil)
  931. defer cli.Close()
  932. err = cli.ContainerRemove(context.Background(), id, types.ContainerRemoveOptions{})
  933. c.Assert(err, checker.IsNil)
  934. }
  935. func (s *DockerSuite) TestContainerAPIDeleteNotExist(c *check.C) {
  936. cli, err := client.NewEnvClient()
  937. c.Assert(err, checker.IsNil)
  938. defer cli.Close()
  939. err = cli.ContainerRemove(context.Background(), "doesnotexist", types.ContainerRemoveOptions{})
  940. c.Assert(err.Error(), checker.Contains, "No such container: doesnotexist")
  941. }
  942. func (s *DockerSuite) TestContainerAPIDeleteForce(c *check.C) {
  943. out := runSleepingContainer(c)
  944. id := strings.TrimSpace(out)
  945. c.Assert(waitRun(id), checker.IsNil)
  946. removeOptions := types.ContainerRemoveOptions{
  947. Force: true,
  948. }
  949. cli, err := client.NewEnvClient()
  950. c.Assert(err, checker.IsNil)
  951. defer cli.Close()
  952. err = cli.ContainerRemove(context.Background(), id, removeOptions)
  953. c.Assert(err, checker.IsNil)
  954. }
  955. func (s *DockerSuite) TestContainerAPIDeleteRemoveLinks(c *check.C) {
  956. // Windows does not support links
  957. testRequires(c, DaemonIsLinux)
  958. out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top")
  959. id := strings.TrimSpace(out)
  960. c.Assert(waitRun(id), checker.IsNil)
  961. out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  962. id2 := strings.TrimSpace(out)
  963. c.Assert(waitRun(id2), checker.IsNil)
  964. links := inspectFieldJSON(c, id2, "HostConfig.Links")
  965. c.Assert(links, checker.Equals, "[\"/tlink1:/tlink2/tlink1\"]", check.Commentf("expected to have links between containers"))
  966. removeOptions := types.ContainerRemoveOptions{
  967. RemoveLinks: true,
  968. }
  969. cli, err := client.NewEnvClient()
  970. c.Assert(err, checker.IsNil)
  971. defer cli.Close()
  972. err = cli.ContainerRemove(context.Background(), "tlink2/tlink1", removeOptions)
  973. c.Assert(err, check.IsNil)
  974. linksPostRm := inspectFieldJSON(c, id2, "HostConfig.Links")
  975. c.Assert(linksPostRm, checker.Equals, "null", check.Commentf("call to api deleteContainer links should have removed the specified links"))
  976. }
  977. func (s *DockerSuite) TestContainerAPIDeleteConflict(c *check.C) {
  978. out := runSleepingContainer(c)
  979. id := strings.TrimSpace(out)
  980. c.Assert(waitRun(id), checker.IsNil)
  981. cli, err := client.NewEnvClient()
  982. c.Assert(err, checker.IsNil)
  983. defer cli.Close()
  984. err = cli.ContainerRemove(context.Background(), id, types.ContainerRemoveOptions{})
  985. expected := "cannot remove a running container"
  986. c.Assert(err.Error(), checker.Contains, expected)
  987. }
  988. func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) {
  989. testRequires(c, SameHostDaemon)
  990. vol := "/testvolume"
  991. if testEnv.DaemonPlatform() == "windows" {
  992. vol = `c:\testvolume`
  993. }
  994. out := runSleepingContainer(c, "-v", vol)
  995. id := strings.TrimSpace(out)
  996. c.Assert(waitRun(id), checker.IsNil)
  997. source, err := inspectMountSourceField(id, vol)
  998. _, err = os.Stat(source)
  999. c.Assert(err, checker.IsNil)
  1000. removeOptions := types.ContainerRemoveOptions{
  1001. Force: true,
  1002. RemoveVolumes: true,
  1003. }
  1004. cli, err := client.NewEnvClient()
  1005. c.Assert(err, checker.IsNil)
  1006. defer cli.Close()
  1007. err = cli.ContainerRemove(context.Background(), id, removeOptions)
  1008. c.Assert(err, check.IsNil)
  1009. _, err = os.Stat(source)
  1010. c.Assert(os.IsNotExist(err), checker.True, check.Commentf("expected to get ErrNotExist error, got %v", err))
  1011. }
  1012. // Regression test for https://github.com/docker/docker/issues/6231
  1013. func (s *DockerSuite) TestContainerAPIChunkedEncoding(c *check.C) {
  1014. config := map[string]interface{}{
  1015. "Image": "busybox",
  1016. "Cmd": append([]string{"/bin/sh", "-c"}, sleepCommandForDaemonPlatform()...),
  1017. "OpenStdin": true,
  1018. }
  1019. resp, _, err := request.Post("/containers/create", request.JSONBody(config), func(req *http.Request) error {
  1020. // This is a cheat to make the http request do chunked encoding
  1021. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  1022. // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
  1023. req.ContentLength = -1
  1024. return nil
  1025. })
  1026. c.Assert(err, checker.IsNil, check.Commentf("error creating container with chunked encoding"))
  1027. defer resp.Body.Close()
  1028. c.Assert(resp.StatusCode, checker.Equals, http.StatusCreated)
  1029. }
  1030. func (s *DockerSuite) TestContainerAPIPostContainerStop(c *check.C) {
  1031. out := runSleepingContainer(c)
  1032. containerID := strings.TrimSpace(out)
  1033. c.Assert(waitRun(containerID), checker.IsNil)
  1034. cli, err := client.NewEnvClient()
  1035. c.Assert(err, checker.IsNil)
  1036. defer cli.Close()
  1037. err = cli.ContainerStop(context.Background(), containerID, nil)
  1038. c.Assert(err, checker.IsNil)
  1039. c.Assert(waitInspect(containerID, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil)
  1040. }
  1041. // #14170
  1042. func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *check.C) {
  1043. config := containertypes.Config{
  1044. Image: "busybox",
  1045. Entrypoint: []string{"echo"},
  1046. Cmd: []string{"hello", "world"},
  1047. }
  1048. cli, err := client.NewEnvClient()
  1049. c.Assert(err, checker.IsNil)
  1050. defer cli.Close()
  1051. _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "echotest")
  1052. c.Assert(err, checker.IsNil)
  1053. out, _ := dockerCmd(c, "start", "-a", "echotest")
  1054. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1055. config2 := struct {
  1056. Image string
  1057. Entrypoint string
  1058. Cmd []string
  1059. }{"busybox", "echo", []string{"hello", "world"}}
  1060. _, _, err = request.Post("/containers/create?name=echotest2", request.JSONBody(config2))
  1061. c.Assert(err, checker.IsNil)
  1062. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  1063. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1064. }
  1065. // #14170
  1066. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) {
  1067. config := containertypes.Config{
  1068. Image: "busybox",
  1069. Cmd: []string{"echo", "hello", "world"},
  1070. }
  1071. cli, err := client.NewEnvClient()
  1072. c.Assert(err, checker.IsNil)
  1073. defer cli.Close()
  1074. _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "echotest")
  1075. c.Assert(err, checker.IsNil)
  1076. out, _ := dockerCmd(c, "start", "-a", "echotest")
  1077. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1078. config2 := struct {
  1079. Image string
  1080. Entrypoint string
  1081. Cmd string
  1082. }{"busybox", "echo", "hello world"}
  1083. _, _, err = request.Post("/containers/create?name=echotest2", request.JSONBody(config2))
  1084. c.Assert(err, checker.IsNil)
  1085. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  1086. c.Assert(strings.TrimSpace(out), checker.Equals, "hello world")
  1087. }
  1088. // regression #14318
  1089. func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *check.C) {
  1090. // Windows doesn't support CapAdd/CapDrop
  1091. testRequires(c, DaemonIsLinux)
  1092. config := struct {
  1093. Image string
  1094. CapAdd string
  1095. CapDrop string
  1096. }{"busybox", "NET_ADMIN", "SYS_ADMIN"}
  1097. res, _, err := request.Post("/containers/create?name=capaddtest0", request.JSONBody(config))
  1098. c.Assert(err, checker.IsNil)
  1099. c.Assert(res.StatusCode, checker.Equals, http.StatusCreated)
  1100. config2 := containertypes.Config{
  1101. Image: "busybox",
  1102. }
  1103. hostConfig := containertypes.HostConfig{
  1104. CapAdd: []string{"NET_ADMIN", "SYS_ADMIN"},
  1105. CapDrop: []string{"SETGID"},
  1106. }
  1107. cli, err := client.NewEnvClient()
  1108. c.Assert(err, checker.IsNil)
  1109. defer cli.Close()
  1110. _, err = cli.ContainerCreate(context.Background(), &config2, &hostConfig, &networktypes.NetworkingConfig{}, "capaddtest1")
  1111. c.Assert(err, checker.IsNil)
  1112. }
  1113. // #14915
  1114. func (s *DockerSuite) TestContainerAPICreateNoHostConfig118(c *check.C) {
  1115. testRequires(c, DaemonIsLinux) // Windows only support 1.25 or later
  1116. config := containertypes.Config{
  1117. Image: "busybox",
  1118. }
  1119. cli, err := request.NewEnvClientWithVersion("v1.18")
  1120. _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
  1121. c.Assert(err, checker.IsNil)
  1122. }
  1123. // Ensure an error occurs when you have a container read-only rootfs but you
  1124. // extract an archive to a symlink in a writable volume which points to a
  1125. // directory outside of the volume.
  1126. func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(c *check.C) {
  1127. // Windows does not support read-only rootfs
  1128. // Requires local volume mount bind.
  1129. // --read-only + userns has remount issues
  1130. testRequires(c, SameHostDaemon, NotUserNamespace, DaemonIsLinux)
  1131. testVol := getTestDir(c, "test-put-container-archive-err-symlink-in-volume-to-read-only-rootfs-")
  1132. defer os.RemoveAll(testVol)
  1133. makeTestContentInDir(c, testVol)
  1134. cID := makeTestContainer(c, testContainerOptions{
  1135. readOnly: true,
  1136. volumes: defaultVolumes(testVol), // Our bind mount is at /vol2
  1137. })
  1138. // Attempt to extract to a symlink in the volume which points to a
  1139. // directory outside the volume. This should cause an error because the
  1140. // rootfs is read-only.
  1141. var httpClient *http.Client
  1142. cli, err := client.NewClient(daemonHost(), "v1.20", httpClient, map[string]string{})
  1143. c.Assert(err, checker.IsNil)
  1144. err = cli.CopyToContainer(context.Background(), cID, "/vol2/symlinkToAbsDir", nil, types.CopyToContainerOptions{})
  1145. c.Assert(err.Error(), checker.Contains, "container rootfs is marked read-only")
  1146. }
  1147. func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) {
  1148. // Not supported on Windows
  1149. testRequires(c, DaemonIsLinux)
  1150. cli, err := client.NewEnvClient()
  1151. c.Assert(err, checker.IsNil)
  1152. defer cli.Close()
  1153. config := containertypes.Config{
  1154. Image: "busybox",
  1155. }
  1156. hostConfig1 := containertypes.HostConfig{
  1157. Resources: containertypes.Resources{
  1158. CpusetCpus: "1-42,,",
  1159. },
  1160. }
  1161. name := "wrong-cpuset-cpus"
  1162. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig1, &networktypes.NetworkingConfig{}, name)
  1163. expected := "Invalid value 1-42,, for cpuset cpus"
  1164. c.Assert(err.Error(), checker.Contains, expected)
  1165. hostConfig2 := containertypes.HostConfig{
  1166. Resources: containertypes.Resources{
  1167. CpusetMems: "42-3,1--",
  1168. },
  1169. }
  1170. name = "wrong-cpuset-mems"
  1171. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig2, &networktypes.NetworkingConfig{}, name)
  1172. expected = "Invalid value 42-3,1-- for cpuset mems"
  1173. c.Assert(err.Error(), checker.Contains, expected)
  1174. }
  1175. func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) {
  1176. // ShmSize is not supported on Windows
  1177. testRequires(c, DaemonIsLinux)
  1178. config := containertypes.Config{
  1179. Image: "busybox",
  1180. }
  1181. hostConfig := containertypes.HostConfig{
  1182. ShmSize: -1,
  1183. }
  1184. cli, err := client.NewEnvClient()
  1185. c.Assert(err, checker.IsNil)
  1186. defer cli.Close()
  1187. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "")
  1188. c.Assert(err.Error(), checker.Contains, "SHM size can not be less than 0")
  1189. }
  1190. func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check.C) {
  1191. // ShmSize is not supported on Windows
  1192. testRequires(c, DaemonIsLinux)
  1193. var defaultSHMSize int64 = 67108864
  1194. config := containertypes.Config{
  1195. Image: "busybox",
  1196. Cmd: []string{"mount"},
  1197. }
  1198. cli, err := client.NewEnvClient()
  1199. c.Assert(err, checker.IsNil)
  1200. defer cli.Close()
  1201. container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
  1202. c.Assert(err, check.IsNil)
  1203. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  1204. c.Assert(err, check.IsNil)
  1205. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, defaultSHMSize)
  1206. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1207. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1208. if !shmRegexp.MatchString(out) {
  1209. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1210. }
  1211. }
  1212. func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *check.C) {
  1213. // ShmSize is not supported on Windows
  1214. testRequires(c, DaemonIsLinux)
  1215. config := containertypes.Config{
  1216. Image: "busybox",
  1217. Cmd: []string{"mount"},
  1218. }
  1219. cli, err := client.NewEnvClient()
  1220. c.Assert(err, checker.IsNil)
  1221. defer cli.Close()
  1222. container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
  1223. c.Assert(err, check.IsNil)
  1224. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  1225. c.Assert(err, check.IsNil)
  1226. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(67108864))
  1227. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1228. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1229. if !shmRegexp.MatchString(out) {
  1230. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1231. }
  1232. }
  1233. func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *check.C) {
  1234. // ShmSize is not supported on Windows
  1235. testRequires(c, DaemonIsLinux)
  1236. config := containertypes.Config{
  1237. Image: "busybox",
  1238. Cmd: []string{"mount"},
  1239. }
  1240. hostConfig := containertypes.HostConfig{
  1241. ShmSize: 1073741824,
  1242. }
  1243. cli, err := client.NewEnvClient()
  1244. c.Assert(err, checker.IsNil)
  1245. defer cli.Close()
  1246. container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "")
  1247. c.Assert(err, check.IsNil)
  1248. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  1249. c.Assert(err, check.IsNil)
  1250. c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(1073741824))
  1251. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1252. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  1253. if !shmRegex.MatchString(out) {
  1254. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  1255. }
  1256. }
  1257. func (s *DockerSuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted(c *check.C) {
  1258. // Swappiness is not supported on Windows
  1259. testRequires(c, DaemonIsLinux)
  1260. config := containertypes.Config{
  1261. Image: "busybox",
  1262. }
  1263. cli, err := client.NewEnvClient()
  1264. c.Assert(err, checker.IsNil)
  1265. defer cli.Close()
  1266. container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "")
  1267. c.Assert(err, check.IsNil)
  1268. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  1269. c.Assert(err, check.IsNil)
  1270. c.Assert(containerJSON.HostConfig.MemorySwappiness, check.IsNil)
  1271. }
  1272. // check validation is done daemon side and not only in cli
  1273. func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *check.C) {
  1274. // OomScoreAdj is not supported on Windows
  1275. testRequires(c, DaemonIsLinux)
  1276. config := containertypes.Config{
  1277. Image: "busybox",
  1278. }
  1279. hostConfig := containertypes.HostConfig{
  1280. OomScoreAdj: 1001,
  1281. }
  1282. cli, err := client.NewEnvClient()
  1283. c.Assert(err, checker.IsNil)
  1284. defer cli.Close()
  1285. name := "oomscoreadj-over"
  1286. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, name)
  1287. expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]"
  1288. c.Assert(err.Error(), checker.Contains, expected)
  1289. hostConfig = containertypes.HostConfig{
  1290. OomScoreAdj: -1001,
  1291. }
  1292. name = "oomscoreadj-low"
  1293. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, name)
  1294. expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]"
  1295. c.Assert(err.Error(), checker.Contains, expected)
  1296. }
  1297. // test case for #22210 where an empty container name caused panic.
  1298. func (s *DockerSuite) TestContainerAPIDeleteWithEmptyName(c *check.C) {
  1299. cli, err := client.NewEnvClient()
  1300. c.Assert(err, checker.IsNil)
  1301. defer cli.Close()
  1302. err = cli.ContainerRemove(context.Background(), "", types.ContainerRemoveOptions{})
  1303. c.Assert(err.Error(), checker.Contains, "No such container")
  1304. }
  1305. func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *check.C) {
  1306. // Problematic on Windows as Windows does not support stats
  1307. testRequires(c, DaemonIsLinux)
  1308. name := "testing-network-disabled"
  1309. config := containertypes.Config{
  1310. Image: "busybox",
  1311. Cmd: []string{"top"},
  1312. NetworkDisabled: true,
  1313. }
  1314. cli, err := client.NewEnvClient()
  1315. c.Assert(err, checker.IsNil)
  1316. defer cli.Close()
  1317. _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, name)
  1318. c.Assert(err, checker.IsNil)
  1319. err = cli.ContainerStart(context.Background(), name, types.ContainerStartOptions{})
  1320. c.Assert(err, checker.IsNil)
  1321. c.Assert(waitRun(name), check.IsNil)
  1322. type b struct {
  1323. stats types.ContainerStats
  1324. err error
  1325. }
  1326. bc := make(chan b, 1)
  1327. go func() {
  1328. stats, err := cli.ContainerStats(context.Background(), name, false)
  1329. bc <- b{stats, err}
  1330. }()
  1331. // allow some time to stream the stats from the container
  1332. time.Sleep(4 * time.Second)
  1333. dockerCmd(c, "rm", "-f", name)
  1334. // collect the results from the stats stream or timeout and fail
  1335. // if the stream was not disconnected.
  1336. select {
  1337. case <-time.After(2 * time.Second):
  1338. c.Fatal("stream was not closed after container was removed")
  1339. case sr := <-bc:
  1340. c.Assert(sr.err, checker.IsNil)
  1341. sr.stats.Body.Close()
  1342. }
  1343. }
  1344. func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *check.C) {
  1345. type testCase struct {
  1346. config containertypes.Config
  1347. hostConfig containertypes.HostConfig
  1348. msg string
  1349. }
  1350. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1351. destPath := prefix + slash + "foo"
  1352. notExistPath := prefix + slash + "notexist"
  1353. cases := []testCase{
  1354. {
  1355. config: containertypes.Config{
  1356. Image: "busybox",
  1357. },
  1358. hostConfig: containertypes.HostConfig{
  1359. Mounts: []mounttypes.Mount{{
  1360. Type: "notreal",
  1361. Target: destPath,
  1362. },
  1363. },
  1364. },
  1365. msg: "mount type unknown",
  1366. },
  1367. {
  1368. config: containertypes.Config{
  1369. Image: "busybox",
  1370. },
  1371. hostConfig: containertypes.HostConfig{
  1372. Mounts: []mounttypes.Mount{{
  1373. Type: "bind"}}},
  1374. msg: "Target must not be empty",
  1375. },
  1376. {
  1377. config: containertypes.Config{
  1378. Image: "busybox",
  1379. },
  1380. hostConfig: containertypes.HostConfig{
  1381. Mounts: []mounttypes.Mount{{
  1382. Type: "bind",
  1383. Target: destPath}}},
  1384. msg: "Source must not be empty",
  1385. },
  1386. {
  1387. config: containertypes.Config{
  1388. Image: "busybox",
  1389. },
  1390. hostConfig: containertypes.HostConfig{
  1391. Mounts: []mounttypes.Mount{{
  1392. Type: "bind",
  1393. Source: notExistPath,
  1394. Target: destPath}}},
  1395. msg: "bind source path does not exist",
  1396. },
  1397. {
  1398. config: containertypes.Config{
  1399. Image: "busybox",
  1400. },
  1401. hostConfig: containertypes.HostConfig{
  1402. Mounts: []mounttypes.Mount{{
  1403. Type: "volume"}}},
  1404. msg: "Target must not be empty",
  1405. },
  1406. {
  1407. config: containertypes.Config{
  1408. Image: "busybox",
  1409. },
  1410. hostConfig: containertypes.HostConfig{
  1411. Mounts: []mounttypes.Mount{{
  1412. Type: "volume",
  1413. Source: "hello",
  1414. Target: destPath}}},
  1415. msg: "",
  1416. },
  1417. {
  1418. config: containertypes.Config{
  1419. Image: "busybox",
  1420. },
  1421. hostConfig: containertypes.HostConfig{
  1422. Mounts: []mounttypes.Mount{{
  1423. Type: "volume",
  1424. Source: "hello2",
  1425. Target: destPath,
  1426. VolumeOptions: &mounttypes.VolumeOptions{
  1427. DriverConfig: &mounttypes.Driver{
  1428. Name: "local"}}}}},
  1429. msg: "",
  1430. },
  1431. }
  1432. if SameHostDaemon() {
  1433. tmpDir, err := ioutils.TempDir("", "test-mounts-api")
  1434. c.Assert(err, checker.IsNil)
  1435. defer os.RemoveAll(tmpDir)
  1436. cases = append(cases, []testCase{
  1437. {
  1438. config: containertypes.Config{
  1439. Image: "busybox",
  1440. },
  1441. hostConfig: containertypes.HostConfig{
  1442. Mounts: []mounttypes.Mount{{
  1443. Type: "bind",
  1444. Source: tmpDir,
  1445. Target: destPath}}},
  1446. msg: "",
  1447. },
  1448. {
  1449. config: containertypes.Config{
  1450. Image: "busybox",
  1451. },
  1452. hostConfig: containertypes.HostConfig{
  1453. Mounts: []mounttypes.Mount{{
  1454. Type: "bind",
  1455. Source: tmpDir,
  1456. Target: destPath,
  1457. VolumeOptions: &mounttypes.VolumeOptions{}}}},
  1458. msg: "VolumeOptions must not be specified",
  1459. },
  1460. }...)
  1461. }
  1462. if DaemonIsLinux() {
  1463. cases = append(cases, []testCase{
  1464. {
  1465. config: containertypes.Config{
  1466. Image: "busybox",
  1467. },
  1468. hostConfig: containertypes.HostConfig{
  1469. Mounts: []mounttypes.Mount{{
  1470. Type: "volume",
  1471. Source: "hello3",
  1472. Target: destPath,
  1473. VolumeOptions: &mounttypes.VolumeOptions{
  1474. DriverConfig: &mounttypes.Driver{
  1475. Name: "local",
  1476. Options: map[string]string{"o": "size=1"}}}}}},
  1477. msg: "",
  1478. },
  1479. {
  1480. config: containertypes.Config{
  1481. Image: "busybox",
  1482. },
  1483. hostConfig: containertypes.HostConfig{
  1484. Mounts: []mounttypes.Mount{{
  1485. Type: "tmpfs",
  1486. Target: destPath}}},
  1487. msg: "",
  1488. },
  1489. {
  1490. config: containertypes.Config{
  1491. Image: "busybox",
  1492. },
  1493. hostConfig: containertypes.HostConfig{
  1494. Mounts: []mounttypes.Mount{{
  1495. Type: "tmpfs",
  1496. Target: destPath,
  1497. TmpfsOptions: &mounttypes.TmpfsOptions{
  1498. SizeBytes: 4096 * 1024,
  1499. Mode: 0700,
  1500. }}}},
  1501. msg: "",
  1502. },
  1503. {
  1504. config: containertypes.Config{
  1505. Image: "busybox",
  1506. },
  1507. hostConfig: containertypes.HostConfig{
  1508. Mounts: []mounttypes.Mount{{
  1509. Type: "tmpfs",
  1510. Source: "/shouldnotbespecified",
  1511. Target: destPath}}},
  1512. msg: "Source must not be specified",
  1513. },
  1514. }...)
  1515. }
  1516. cli, err := client.NewEnvClient()
  1517. c.Assert(err, checker.IsNil)
  1518. defer cli.Close()
  1519. for i, x := range cases {
  1520. c.Logf("case %d", i)
  1521. _, err = cli.ContainerCreate(context.Background(), &x.config, &x.hostConfig, &networktypes.NetworkingConfig{}, "")
  1522. if len(x.msg) > 0 {
  1523. c.Assert(err.Error(), checker.Contains, x.msg, check.Commentf("%v", cases[i].config))
  1524. } else {
  1525. c.Assert(err, checker.IsNil)
  1526. }
  1527. }
  1528. }
  1529. func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *check.C) {
  1530. testRequires(c, NotUserNamespace, SameHostDaemon)
  1531. // also with data in the host side
  1532. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1533. destPath := prefix + slash + "foo"
  1534. tmpDir, err := ioutil.TempDir("", "test-mounts-api-bind")
  1535. c.Assert(err, checker.IsNil)
  1536. defer os.RemoveAll(tmpDir)
  1537. err = ioutil.WriteFile(filepath.Join(tmpDir, "bar"), []byte("hello"), 666)
  1538. c.Assert(err, checker.IsNil)
  1539. config := containertypes.Config{
  1540. Image: "busybox",
  1541. Cmd: []string{"/bin/sh", "-c", "cat /foo/bar"},
  1542. }
  1543. hostConfig := containertypes.HostConfig{
  1544. Mounts: []mounttypes.Mount{
  1545. {Type: "bind", Source: tmpDir, Target: destPath},
  1546. },
  1547. }
  1548. cli, err := client.NewEnvClient()
  1549. c.Assert(err, checker.IsNil)
  1550. defer cli.Close()
  1551. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "test")
  1552. c.Assert(err, checker.IsNil)
  1553. out, _ := dockerCmd(c, "start", "-a", "test")
  1554. c.Assert(out, checker.Equals, "hello")
  1555. }
  1556. // Test Mounts comes out as expected for the MountPoint
  1557. func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *check.C) {
  1558. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1559. destPath := prefix + slash + "foo"
  1560. var (
  1561. testImg string
  1562. )
  1563. if testEnv.DaemonPlatform() != "windows" {
  1564. testImg = "test-mount-config"
  1565. buildImageSuccessfully(c, testImg, build.WithDockerfile(`
  1566. FROM busybox
  1567. RUN mkdir `+destPath+` && touch `+destPath+slash+`bar
  1568. CMD cat `+destPath+slash+`bar
  1569. `))
  1570. } else {
  1571. testImg = "busybox"
  1572. }
  1573. type testCase struct {
  1574. cfg mounttypes.Mount
  1575. expected types.MountPoint
  1576. }
  1577. cases := []testCase{
  1578. // use literal strings here for `Type` instead of the defined constants in the volume package to keep this honest
  1579. // Validation of the actual `Mount` struct is done in another test is not needed here
  1580. {mounttypes.Mount{Type: "volume", Target: destPath}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1581. {mounttypes.Mount{Type: "volume", Target: destPath + slash}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1582. {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test1"}, types.MountPoint{Type: "volume", Name: "test1", RW: true, Destination: destPath}},
  1583. {mounttypes.Mount{Type: "volume", Target: destPath, ReadOnly: true, Source: "test2"}, types.MountPoint{Type: "volume", Name: "test2", RW: false, Destination: destPath}},
  1584. {
  1585. mounttypes.Mount{
  1586. Type: "volume",
  1587. Target: destPath,
  1588. Source: "test3",
  1589. VolumeOptions: &mounttypes.VolumeOptions{
  1590. DriverConfig: &mounttypes.Driver{Name: volume.DefaultDriverName},
  1591. },
  1592. },
  1593. types.MountPoint{
  1594. Driver: volume.DefaultDriverName,
  1595. Type: "volume",
  1596. Name: "test3",
  1597. RW: true,
  1598. Destination: destPath,
  1599. },
  1600. },
  1601. }
  1602. if SameHostDaemon() {
  1603. // setup temp dir for testing binds
  1604. tmpDir1, err := ioutil.TempDir("", "test-mounts-api-1")
  1605. c.Assert(err, checker.IsNil)
  1606. defer os.RemoveAll(tmpDir1)
  1607. cases = append(cases, []testCase{
  1608. {
  1609. mounttypes.Mount{
  1610. Type: "bind",
  1611. Source: tmpDir1,
  1612. Target: destPath,
  1613. },
  1614. types.MountPoint{
  1615. Type: "bind",
  1616. RW: true,
  1617. Destination: destPath,
  1618. Source: tmpDir1,
  1619. },
  1620. },
  1621. {mounttypes.Mount{Type: "bind", Source: tmpDir1, Target: destPath, ReadOnly: true}, types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir1}},
  1622. }...)
  1623. // for modes only supported on Linux
  1624. if DaemonIsLinux() {
  1625. tmpDir3, err := ioutils.TempDir("", "test-mounts-api-3")
  1626. c.Assert(err, checker.IsNil)
  1627. defer os.RemoveAll(tmpDir3)
  1628. c.Assert(mount.Mount(tmpDir3, tmpDir3, "none", "bind,rw"), checker.IsNil)
  1629. c.Assert(mount.ForceMount("", tmpDir3, "none", "shared"), checker.IsNil)
  1630. cases = append(cases, []testCase{
  1631. {mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath}, types.MountPoint{Type: "bind", RW: true, Destination: destPath, Source: tmpDir3}},
  1632. {mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true}, types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir3}},
  1633. {mounttypes.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true, BindOptions: &mounttypes.BindOptions{Propagation: "shared"}}, types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir3, Propagation: "shared"}},
  1634. }...)
  1635. }
  1636. }
  1637. if testEnv.DaemonPlatform() != "windows" { // Windows does not support volume populate
  1638. cases = append(cases, []testCase{
  1639. {mounttypes.Mount{Type: "volume", Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1640. {mounttypes.Mount{Type: "volume", Target: destPath + slash, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath}},
  1641. {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test4", VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Type: "volume", Name: "test4", RW: true, Destination: destPath}},
  1642. {mounttypes.Mount{Type: "volume", Target: destPath, Source: "test5", ReadOnly: true, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, types.MountPoint{Type: "volume", Name: "test5", RW: false, Destination: destPath}},
  1643. }...)
  1644. }
  1645. type wrapper struct {
  1646. containertypes.Config
  1647. HostConfig containertypes.HostConfig
  1648. }
  1649. type createResp struct {
  1650. ID string `json:"Id"`
  1651. }
  1652. ctx := context.Background()
  1653. apiclient := testEnv.APIClient()
  1654. for i, x := range cases {
  1655. c.Logf("case %d - config: %v", i, x.cfg)
  1656. container, err := apiclient.ContainerCreate(
  1657. ctx,
  1658. &containertypes.Config{Image: testImg},
  1659. &containertypes.HostConfig{Mounts: []mounttypes.Mount{x.cfg}},
  1660. &networktypes.NetworkingConfig{},
  1661. "")
  1662. require.NoError(c, err)
  1663. containerInspect, err := apiclient.ContainerInspect(ctx, container.ID)
  1664. require.NoError(c, err)
  1665. mps := containerInspect.Mounts
  1666. require.Len(c, mps, 1)
  1667. mountPoint := mps[0]
  1668. if x.expected.Source != "" {
  1669. assert.Equal(c, x.expected.Source, mountPoint.Source)
  1670. }
  1671. if x.expected.Name != "" {
  1672. assert.Equal(c, x.expected.Name, mountPoint.Name)
  1673. }
  1674. if x.expected.Driver != "" {
  1675. assert.Equal(c, x.expected.Driver, mountPoint.Driver)
  1676. }
  1677. if x.expected.Propagation != "" {
  1678. assert.Equal(c, x.expected.Propagation, mountPoint.Propagation)
  1679. }
  1680. assert.Equal(c, x.expected.RW, mountPoint.RW)
  1681. assert.Equal(c, x.expected.Type, mountPoint.Type)
  1682. assert.Equal(c, x.expected.Mode, mountPoint.Mode)
  1683. assert.Equal(c, x.expected.Destination, mountPoint.Destination)
  1684. err = apiclient.ContainerStart(ctx, container.ID, types.ContainerStartOptions{})
  1685. require.NoError(c, err)
  1686. poll.WaitOn(c, containerExit(apiclient, container.ID), poll.WithDelay(time.Second))
  1687. err = apiclient.ContainerRemove(ctx, container.ID, types.ContainerRemoveOptions{
  1688. RemoveVolumes: true,
  1689. Force: true,
  1690. })
  1691. require.NoError(c, err)
  1692. switch {
  1693. // Named volumes still exist after the container is removed
  1694. case x.cfg.Type == "volume" && len(x.cfg.Source) > 0:
  1695. _, err := apiclient.VolumeInspect(ctx, mountPoint.Name)
  1696. require.NoError(c, err)
  1697. // Bind mounts are never removed with the container
  1698. case x.cfg.Type == "bind":
  1699. // anonymous volumes are removed
  1700. default:
  1701. _, err := apiclient.VolumeInspect(ctx, mountPoint.Name)
  1702. assert.True(c, client.IsErrNotFound(err))
  1703. }
  1704. }
  1705. }
  1706. func containerExit(apiclient client.APIClient, name string) func(poll.LogT) poll.Result {
  1707. return func(logT poll.LogT) poll.Result {
  1708. container, err := apiclient.ContainerInspect(context.Background(), name)
  1709. if err != nil {
  1710. return poll.Error(err)
  1711. }
  1712. switch container.State.Status {
  1713. case "created", "running":
  1714. return poll.Continue("container %s is %s, waiting for exit", name, container.State.Status)
  1715. }
  1716. return poll.Success()
  1717. }
  1718. }
  1719. func (s *DockerSuite) TestContainersAPICreateMountsTmpfs(c *check.C) {
  1720. testRequires(c, DaemonIsLinux)
  1721. type testCase struct {
  1722. cfg mounttypes.Mount
  1723. expectedOptions []string
  1724. }
  1725. target := "/foo"
  1726. cases := []testCase{
  1727. {
  1728. cfg: mounttypes.Mount{
  1729. Type: "tmpfs",
  1730. Target: target},
  1731. expectedOptions: []string{"rw", "nosuid", "nodev", "noexec", "relatime"},
  1732. },
  1733. {
  1734. cfg: mounttypes.Mount{
  1735. Type: "tmpfs",
  1736. Target: target,
  1737. TmpfsOptions: &mounttypes.TmpfsOptions{
  1738. SizeBytes: 4096 * 1024, Mode: 0700}},
  1739. expectedOptions: []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=4096k", "mode=700"},
  1740. },
  1741. }
  1742. cli, err := client.NewEnvClient()
  1743. c.Assert(err, checker.IsNil)
  1744. defer cli.Close()
  1745. config := containertypes.Config{
  1746. Image: "busybox",
  1747. Cmd: []string{"/bin/sh", "-c", fmt.Sprintf("mount | grep 'tmpfs on %s'", target)},
  1748. }
  1749. for i, x := range cases {
  1750. cName := fmt.Sprintf("test-tmpfs-%d", i)
  1751. hostConfig := containertypes.HostConfig{
  1752. Mounts: []mounttypes.Mount{x.cfg},
  1753. }
  1754. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, cName)
  1755. c.Assert(err, checker.IsNil)
  1756. out, _ := dockerCmd(c, "start", "-a", cName)
  1757. for _, option := range x.expectedOptions {
  1758. c.Assert(out, checker.Contains, option)
  1759. }
  1760. }
  1761. }
  1762. // Regression test for #33334
  1763. // Makes sure that when a container which has a custom stop signal + restart=always
  1764. // gets killed (with SIGKILL) by the kill API, that the restart policy is cancelled.
  1765. func (s *DockerSuite) TestContainerKillCustomStopSignal(c *check.C) {
  1766. id := strings.TrimSpace(runSleepingContainer(c, "--stop-signal=SIGTERM", "--restart=always"))
  1767. res, _, err := request.Post("/containers/" + id + "/kill")
  1768. c.Assert(err, checker.IsNil)
  1769. defer res.Body.Close()
  1770. b, err := ioutil.ReadAll(res.Body)
  1771. c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent, check.Commentf(string(b)))
  1772. err = waitInspect(id, "{{.State.Running}} {{.State.Restarting}}", "false false", 30*time.Second)
  1773. c.Assert(err, checker.IsNil)
  1774. }