docker_api_containers_test.go 68 KB

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