docker_api_containers_test.go 67 KB

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