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. "github.com/docker/docker/api/types/container"
  19. "github.com/docker/docker/api/types/mount"
  20. "github.com/docker/docker/api/types/network"
  21. "github.com/docker/docker/api/types/versions"
  22. "github.com/docker/docker/client"
  23. dconfig "github.com/docker/docker/daemon/config"
  24. "github.com/docker/docker/errdefs"
  25. "github.com/docker/docker/integration-cli/cli"
  26. "github.com/docker/docker/integration-cli/cli/build"
  27. "github.com/docker/docker/pkg/ioutils"
  28. "github.com/docker/docker/pkg/stringid"
  29. "github.com/docker/docker/testutil/request"
  30. "github.com/docker/docker/volume"
  31. "github.com/docker/go-connections/nat"
  32. "gotest.tools/v3/assert"
  33. is "gotest.tools/v3/assert/cmp"
  34. "gotest.tools/v3/poll"
  35. )
  36. func (s *DockerAPISuite) TestContainerAPIGetAll(c *testing.T) {
  37. startCount := getContainerCount(c)
  38. name := "getall"
  39. dockerCmd(c, "run", "--name", name, "busybox", "true")
  40. cli, err := client.NewClientWithOpts(client.FromEnv)
  41. assert.NilError(c, err)
  42. defer cli.Close()
  43. options := types.ContainerListOptions{
  44. All: true,
  45. }
  46. containers, err := cli.ContainerList(context.Background(), options)
  47. assert.NilError(c, err)
  48. assert.Equal(c, len(containers), startCount+1)
  49. actual := containers[0].Names[0]
  50. assert.Equal(c, actual, "/"+name)
  51. }
  52. // regression test for empty json field being omitted #13691
  53. func (s *DockerAPISuite) TestContainerAPIGetJSONNoFieldsOmitted(c *testing.T) {
  54. startCount := getContainerCount(c)
  55. dockerCmd(c, "run", "busybox", "true")
  56. cli, err := client.NewClientWithOpts(client.FromEnv)
  57. assert.NilError(c, err)
  58. defer cli.Close()
  59. options := types.ContainerListOptions{
  60. All: true,
  61. }
  62. containers, err := cli.ContainerList(context.Background(), options)
  63. assert.NilError(c, err)
  64. assert.Equal(c, len(containers), startCount+1)
  65. actual := fmt.Sprintf("%+v", containers[0])
  66. // empty Labels field triggered this bug, make sense to check for everything
  67. // cause even Ports for instance can trigger this bug
  68. // better safe than sorry..
  69. fields := []string{
  70. "ID",
  71. "Names",
  72. "Image",
  73. "Command",
  74. "Created",
  75. "Ports",
  76. "Labels",
  77. "Status",
  78. "NetworkSettings",
  79. }
  80. // decoding into types.Container do not work since it eventually unmarshal
  81. // and empty field to an empty go map, so we just check for a string
  82. for _, f := range fields {
  83. if !strings.Contains(actual, f) {
  84. c.Fatalf("Field %s is missing and it shouldn't", f)
  85. }
  86. }
  87. }
  88. func (s *DockerAPISuite) TestContainerAPIGetExport(c *testing.T) {
  89. // Not supported on Windows as Windows does not support docker export
  90. testRequires(c, DaemonIsLinux)
  91. name := "exportcontainer"
  92. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test")
  93. cli, err := client.NewClientWithOpts(client.FromEnv)
  94. assert.NilError(c, err)
  95. defer cli.Close()
  96. body, err := cli.ContainerExport(context.Background(), name)
  97. assert.NilError(c, err)
  98. defer body.Close()
  99. found := false
  100. for tarReader := tar.NewReader(body); ; {
  101. h, err := tarReader.Next()
  102. if err != nil && err == io.EOF {
  103. break
  104. }
  105. if h.Name == "test" {
  106. found = true
  107. break
  108. }
  109. }
  110. assert.Assert(c, found, "The created test file has not been found in the exported image")
  111. }
  112. func (s *DockerAPISuite) TestContainerAPIGetChanges(c *testing.T) {
  113. // Not supported on Windows as Windows does not support docker diff (/containers/name/changes)
  114. testRequires(c, DaemonIsLinux)
  115. name := "changescontainer"
  116. dockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd")
  117. cli, err := client.NewClientWithOpts(client.FromEnv)
  118. assert.NilError(c, err)
  119. defer cli.Close()
  120. changes, err := cli.ContainerDiff(context.Background(), name)
  121. assert.NilError(c, err)
  122. // Check the changelog for removal of /etc/passwd
  123. success := false
  124. for _, elem := range changes {
  125. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  126. success = true
  127. }
  128. }
  129. assert.Assert(c, success, "/etc/passwd has been removed but is not present in the diff")
  130. }
  131. func (s *DockerAPISuite) TestGetContainerStats(c *testing.T) {
  132. var (
  133. name = "statscontainer"
  134. )
  135. runSleepingContainer(c, "--name", name)
  136. type b struct {
  137. stats types.ContainerStats
  138. err error
  139. }
  140. bc := make(chan b, 1)
  141. go func() {
  142. cli, err := client.NewClientWithOpts(client.FromEnv)
  143. assert.NilError(c, err)
  144. defer cli.Close()
  145. stats, err := cli.ContainerStats(context.Background(), name, true)
  146. assert.NilError(c, err)
  147. bc <- b{stats, err}
  148. }()
  149. // allow some time to stream the stats from the container
  150. time.Sleep(4 * time.Second)
  151. dockerCmd(c, "rm", "-f", name)
  152. // collect the results from the stats stream or timeout and fail
  153. // if the stream was not disconnected.
  154. select {
  155. case <-time.After(2 * time.Second):
  156. c.Fatal("stream was not closed after container was removed")
  157. case sr := <-bc:
  158. dec := json.NewDecoder(sr.stats.Body)
  159. defer sr.stats.Body.Close()
  160. var s *types.Stats
  161. // decode only one object from the stream
  162. assert.NilError(c, dec.Decode(&s))
  163. }
  164. }
  165. func (s *DockerAPISuite) TestGetContainerStatsRmRunning(c *testing.T) {
  166. out := runSleepingContainer(c)
  167. id := strings.TrimSpace(out)
  168. buf := &ChannelBuffer{C: make(chan []byte, 1)}
  169. defer buf.Close()
  170. cli, err := client.NewClientWithOpts(client.FromEnv)
  171. assert.NilError(c, err)
  172. defer cli.Close()
  173. stats, err := cli.ContainerStats(context.Background(), id, true)
  174. assert.NilError(c, err)
  175. defer stats.Body.Close()
  176. chErr := make(chan error, 1)
  177. go func() {
  178. _, err = io.Copy(buf, stats.Body)
  179. chErr <- err
  180. }()
  181. b := make([]byte, 32)
  182. // make sure we've got some stats
  183. _, err = buf.ReadTimeout(b, 2*time.Second)
  184. assert.NilError(c, err)
  185. // Now remove without `-f` and make sure we are still pulling stats
  186. _, _, err = dockerCmdWithError("rm", id)
  187. assert.Assert(c, err != nil, "rm should have failed but didn't")
  188. _, err = buf.ReadTimeout(b, 2*time.Second)
  189. assert.NilError(c, err)
  190. dockerCmd(c, "rm", "-f", id)
  191. assert.Assert(c, <-chErr == nil)
  192. }
  193. // ChannelBuffer holds a chan of byte array that can be populate in a goroutine.
  194. type ChannelBuffer struct {
  195. C chan []byte
  196. }
  197. // Write implements Writer.
  198. func (c *ChannelBuffer) Write(b []byte) (int, error) {
  199. c.C <- b
  200. return len(b), nil
  201. }
  202. // Close closes the go channel.
  203. func (c *ChannelBuffer) Close() error {
  204. close(c.C)
  205. return nil
  206. }
  207. // ReadTimeout reads the content of the channel in the specified byte array with
  208. // the specified duration as timeout.
  209. func (c *ChannelBuffer) ReadTimeout(p []byte, n time.Duration) (int, error) {
  210. select {
  211. case b := <-c.C:
  212. return copy(p[0:], b), nil
  213. case <-time.After(n):
  214. return -1, fmt.Errorf("timeout reading from channel")
  215. }
  216. }
  217. // regression test for gh13421
  218. // previous test was just checking one stat entry so it didn't fail (stats with
  219. // stream false always return one stat)
  220. func (s *DockerAPISuite) TestGetContainerStatsStream(c *testing.T) {
  221. name := "statscontainer"
  222. runSleepingContainer(c, "--name", name)
  223. type b struct {
  224. stats types.ContainerStats
  225. err error
  226. }
  227. bc := make(chan b, 1)
  228. go func() {
  229. cli, err := client.NewClientWithOpts(client.FromEnv)
  230. assert.NilError(c, err)
  231. defer cli.Close()
  232. stats, err := cli.ContainerStats(context.Background(), name, true)
  233. assert.NilError(c, err)
  234. bc <- b{stats, err}
  235. }()
  236. // allow some time to stream the stats from the container
  237. time.Sleep(4 * time.Second)
  238. dockerCmd(c, "rm", "-f", name)
  239. // collect the results from the stats stream or timeout and fail
  240. // if the stream was not disconnected.
  241. select {
  242. case <-time.After(2 * time.Second):
  243. c.Fatal("stream was not closed after container was removed")
  244. case sr := <-bc:
  245. b, err := io.ReadAll(sr.stats.Body)
  246. defer sr.stats.Body.Close()
  247. assert.NilError(c, err)
  248. s := string(b)
  249. // count occurrences of "read" of types.Stats
  250. if l := strings.Count(s, "read"); l < 2 {
  251. c.Fatalf("Expected more than one stat streamed, got %d", l)
  252. }
  253. }
  254. }
  255. func (s *DockerAPISuite) TestGetContainerStatsNoStream(c *testing.T) {
  256. name := "statscontainer"
  257. runSleepingContainer(c, "--name", name)
  258. type b struct {
  259. stats types.ContainerStats
  260. err error
  261. }
  262. bc := make(chan b, 1)
  263. go func() {
  264. cli, err := client.NewClientWithOpts(client.FromEnv)
  265. assert.NilError(c, err)
  266. defer cli.Close()
  267. stats, err := cli.ContainerStats(context.Background(), name, false)
  268. assert.NilError(c, err)
  269. bc <- b{stats, err}
  270. }()
  271. // allow some time to stream the stats from the container
  272. time.Sleep(4 * time.Second)
  273. dockerCmd(c, "rm", "-f", name)
  274. // collect the results from the stats stream or timeout and fail
  275. // if the stream was not disconnected.
  276. select {
  277. case <-time.After(2 * time.Second):
  278. c.Fatal("stream was not closed after container was removed")
  279. case sr := <-bc:
  280. b, err := io.ReadAll(sr.stats.Body)
  281. defer sr.stats.Body.Close()
  282. assert.NilError(c, err)
  283. s := string(b)
  284. // count occurrences of `"read"` of types.Stats
  285. assert.Assert(c, strings.Count(s, `"read"`) == 1, "Expected only one stat streamed, got %d", strings.Count(s, `"read"`))
  286. }
  287. }
  288. func (s *DockerAPISuite) TestGetStoppedContainerStats(c *testing.T) {
  289. name := "statscontainer"
  290. dockerCmd(c, "create", "--name", name, "busybox", "ps")
  291. chResp := make(chan error, 1)
  292. // We expect an immediate response, but if it's not immediate, the test would hang, so put it in a goroutine
  293. // below we'll check this on a timeout.
  294. go func() {
  295. cli, err := client.NewClientWithOpts(client.FromEnv)
  296. assert.NilError(c, err)
  297. defer cli.Close()
  298. resp, err := cli.ContainerStats(context.Background(), name, false)
  299. assert.NilError(c, err)
  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 *DockerAPISuite) 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.Equal(c, len(pausedContainers), 0, "There should be no paused container.")
  331. }
  332. func (s *DockerAPISuite) TestContainerAPITop(c *testing.T) {
  333. testRequires(c, DaemonIsLinux)
  334. out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top && true")
  335. id := strings.TrimSpace(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.Equal(c, len(top.Titles), 11, fmt.Sprintf("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.Equal(c, len(top.Processes), 2, fmt.Sprintf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes))
  348. assert.Equal(c, top.Processes[0][10], "/bin/sh -c top && true")
  349. assert.Equal(c, top.Processes[1][10], "top")
  350. }
  351. func (s *DockerAPISuite) TestContainerAPITopWindows(c *testing.T) {
  352. testRequires(c, DaemonIsWindows)
  353. out := runSleepingContainer(c, "-d")
  354. id := strings.TrimSpace(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 *DockerAPISuite) 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.Equal(c, cmd, "[/bin/sh -c touch /test]", fmt.Sprintf("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 *DockerAPISuite) 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 := container.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.Equal(c, label1, "value1")
  408. label2 := inspectFieldMap(c, img.ID, "Config.Labels", "key2")
  409. assert.Equal(c, label2, "value2")
  410. cmd := inspectField(c, img.ID, "Config.Cmd")
  411. assert.Equal(c, cmd, "[/bin/sh -c touch /test]", fmt.Sprintf("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 *DockerAPISuite) TestContainerAPIBadPort(c *testing.T) {
  416. // TODO Windows to Windows CI - Port this test
  417. testRequires(c, DaemonIsLinux)
  418. config := container.Config{
  419. Image: "busybox",
  420. Cmd: []string{"/bin/sh", "-c", "echo test"},
  421. }
  422. hostConfig := container.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, &network.NetworkingConfig{}, nil, "")
  435. assert.ErrorContains(c, err, `invalid port specification: "aa80"`)
  436. }
  437. func (s *DockerAPISuite) TestContainerAPICreate(c *testing.T) {
  438. config := container.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, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "")
  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 *DockerAPISuite) 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(), &container.Config{}, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "")
  455. expected := "No command specified"
  456. assert.ErrorContains(c, err, expected)
  457. }
  458. func (s *DockerAPISuite) TestContainerAPICreateMultipleNetworksConfig(c *testing.T) {
  459. // Container creation must fail if client specified configurations for more than one network
  460. config := container.Config{
  461. Image: "busybox",
  462. }
  463. networkingConfig := network.NetworkingConfig{
  464. EndpointsConfig: map[string]*network.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, &container.HostConfig{}, &networkingConfig, nil, "")
  474. msg := err.Error()
  475. // network name order in error message is not deterministic
  476. assert.Assert(c, strings.Contains(msg, "Container cannot be connected to network endpoints"))
  477. assert.Assert(c, strings.Contains(msg, "net1"))
  478. assert.Assert(c, strings.Contains(msg, "net2"))
  479. assert.Assert(c, strings.Contains(msg, "net3"))
  480. }
  481. func (s *DockerAPISuite) TestContainerAPICreateBridgeNetworkMode(c *testing.T) {
  482. // Windows does not support bridge
  483. testRequires(c, DaemonIsLinux)
  484. UtilCreateNetworkMode(c, "bridge")
  485. }
  486. func (s *DockerAPISuite) 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 container.NetworkMode) {
  493. config := container.Config{
  494. Image: "busybox",
  495. }
  496. hostConfig := container.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, &network.NetworkingConfig{}, nil, "")
  503. assert.NilError(c, err)
  504. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  505. assert.NilError(c, err)
  506. assert.Equal(c, containerJSON.HostConfig.NetworkMode, networkMode, "Mismatched NetworkMode")
  507. }
  508. func (s *DockerAPISuite) TestContainerAPICreateWithCpuSharesCpuset(c *testing.T) {
  509. // TODO Windows to Windows CI. The CpuShares part could be ported.
  510. testRequires(c, DaemonIsLinux)
  511. config := container.Config{
  512. Image: "busybox",
  513. }
  514. hostConfig := container.HostConfig{
  515. Resources: container.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, &network.NetworkingConfig{}, nil, "")
  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.Equal(c, outCpuset, "0")
  531. }
  532. func (s *DockerAPISuite) 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) == nil)
  539. return request.Post("/containers/create", request.RawContent(io.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 != 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 != 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 *DockerAPISuite) 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 != http.StatusOK)
  586. }
  587. b, err := request.ReadBody(body)
  588. assert.NilError(c, err)
  589. assert.Assert(c, strings.Contains(string(b[:]), "invalid port"))
  590. }
  591. func (s *DockerAPISuite) 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 != http.StatusOK)
  607. }
  608. b, err := request.ReadBody(body)
  609. assert.NilError(c, err)
  610. assert.Assert(c, strings.Contains(string(b[:]), "invalid restart policy"))
  611. }
  612. func (s *DockerAPISuite) 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 != http.StatusOK)
  628. }
  629. b, err := request.ReadBody(body)
  630. assert.NilError(c, err)
  631. assert.Assert(c, strings.Contains(string(b[:]), "maximum retry count cannot be used with restart policy"))
  632. }
  633. func (s *DockerAPISuite) 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 != http.StatusOK)
  649. }
  650. b, err := request.ReadBody(body)
  651. assert.NilError(c, err)
  652. assert.Assert(c, strings.Contains(string(b[:]), "maximum retry count cannot be negative"))
  653. }
  654. func (s *DockerAPISuite) 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 *DockerAPISuite) 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) == nil)
  703. out := inspectField(c, container.ID, "HostConfig.CpusetCpus")
  704. assert.Equal(c, out, "")
  705. outMemory := inspectField(c, container.ID, "HostConfig.Memory")
  706. assert.Equal(c, outMemory, "0")
  707. outMemorySwap := inspectField(c, container.ID, "HostConfig.MemorySwap")
  708. assert.Equal(c, outMemorySwap, "0")
  709. }
  710. func (s *DockerAPISuite) 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 == nil)
  724. if versions.GreaterThanOrEqualTo(testEnv.DaemonAPIVersion(), "1.32") {
  725. assert.Equal(c, res.StatusCode, http.StatusBadRequest)
  726. } else {
  727. assert.Assert(c, res.StatusCode != http.StatusOK)
  728. }
  729. assert.Assert(c, strings.Contains(string(b), "Minimum memory limit allowed is 6MB"))
  730. }
  731. func (s *DockerAPISuite) 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.Equal(c, name, "/"+newName, "Failed to rename container")
  742. }
  743. func (s *DockerAPISuite) 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.Equal(c, state, "false", fmt.Sprintf("got wrong State from container %s: %q", name, state))
  753. }
  754. func (s *DockerAPISuite) 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
  761. err = cli.ContainerRestart(context.Background(), name, container.StopOptions{Timeout: &timeout})
  762. assert.NilError(c, err)
  763. assert.Assert(c, waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second) == nil)
  764. }
  765. func (s *DockerAPISuite) 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, container.StopOptions{})
  774. assert.NilError(c, err)
  775. assert.Assert(c, waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second) == nil)
  776. }
  777. func (s *DockerAPISuite) TestContainerAPIStart(c *testing.T) {
  778. name := "testing-start"
  779. config := container.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, &container.HostConfig{}, &network.NetworkingConfig{}, nil, 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 *DockerAPISuite) TestContainerAPIStop(c *testing.T) {
  798. name := "test-api-stop"
  799. runSleepingContainer(c, "-i", "--name", name)
  800. timeout := 30
  801. cli, err := client.NewClientWithOpts(client.FromEnv)
  802. assert.NilError(c, err)
  803. defer cli.Close()
  804. err = cli.ContainerStop(context.Background(), name, container.StopOptions{
  805. Timeout: &timeout,
  806. })
  807. assert.NilError(c, err)
  808. assert.Assert(c, waitInspect(name, "{{ .State.Running }}", "false", 60*time.Second) == nil)
  809. // second call to start should give 304
  810. // maybe add ContainerStartWithRaw to test it
  811. err = cli.ContainerStop(context.Background(), name, container.StopOptions{
  812. Timeout: &timeout,
  813. })
  814. assert.NilError(c, err)
  815. }
  816. func (s *DockerAPISuite) TestContainerAPIWait(c *testing.T) {
  817. name := "test-api-wait"
  818. sleepCmd := "/bin/sleep"
  819. if testEnv.OSType == "windows" {
  820. sleepCmd = "sleep"
  821. }
  822. dockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "2")
  823. cli, err := client.NewClientWithOpts(client.FromEnv)
  824. assert.NilError(c, err)
  825. defer cli.Close()
  826. waitResC, errC := cli.ContainerWait(context.Background(), name, "")
  827. select {
  828. case err = <-errC:
  829. assert.NilError(c, err)
  830. case waitRes := <-waitResC:
  831. assert.Equal(c, waitRes.StatusCode, int64(0))
  832. }
  833. }
  834. func (s *DockerAPISuite) TestContainerAPICopyNotExistsAnyMore(c *testing.T) {
  835. name := "test-container-api-copy"
  836. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  837. postData := types.CopyConfig{
  838. Resource: "/test.txt",
  839. }
  840. // no copy in client/
  841. res, _, err := request.Post("/containers/"+name+"/copy", request.JSONBody(postData))
  842. assert.NilError(c, err)
  843. assert.Equal(c, res.StatusCode, http.StatusNotFound)
  844. }
  845. func (s *DockerAPISuite) TestContainerAPICopyPre124(c *testing.T) {
  846. testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later
  847. name := "test-container-api-copy"
  848. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  849. postData := types.CopyConfig{
  850. Resource: "/test.txt",
  851. }
  852. res, body, err := request.Post("/v1.23/containers/"+name+"/copy", request.JSONBody(postData))
  853. assert.NilError(c, err)
  854. assert.Equal(c, res.StatusCode, http.StatusOK)
  855. found := false
  856. for tarReader := tar.NewReader(body); ; {
  857. h, err := tarReader.Next()
  858. if err != nil {
  859. if err == io.EOF {
  860. break
  861. }
  862. c.Fatal(err)
  863. }
  864. if h.Name == "test.txt" {
  865. found = true
  866. break
  867. }
  868. }
  869. assert.Assert(c, found)
  870. }
  871. func (s *DockerAPISuite) TestContainerAPICopyResourcePathEmptyPre124(c *testing.T) {
  872. testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later
  873. name := "test-container-api-copy-resource-empty"
  874. dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
  875. postData := types.CopyConfig{
  876. Resource: "",
  877. }
  878. res, body, err := request.Post("/v1.23/containers/"+name+"/copy", request.JSONBody(postData))
  879. assert.NilError(c, err)
  880. if versions.GreaterThanOrEqualTo(testEnv.DaemonAPIVersion(), "1.32") {
  881. assert.Equal(c, res.StatusCode, http.StatusBadRequest)
  882. } else {
  883. assert.Assert(c, res.StatusCode != http.StatusOK)
  884. }
  885. b, err := request.ReadBody(body)
  886. assert.NilError(c, err)
  887. assert.Assert(c, is.Regexp("^Path cannot be empty\n$", string(b)))
  888. }
  889. func (s *DockerAPISuite) TestContainerAPICopyResourcePathNotFoundPre124(c *testing.T) {
  890. testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later
  891. name := "test-container-api-copy-resource-not-found"
  892. dockerCmd(c, "run", "--name", name, "busybox")
  893. postData := types.CopyConfig{
  894. Resource: "/notexist",
  895. }
  896. res, body, err := request.Post("/v1.23/containers/"+name+"/copy", request.JSONBody(postData))
  897. assert.NilError(c, err)
  898. if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") {
  899. assert.Equal(c, res.StatusCode, http.StatusInternalServerError)
  900. } else {
  901. assert.Equal(c, res.StatusCode, http.StatusNotFound)
  902. }
  903. b, err := request.ReadBody(body)
  904. assert.NilError(c, err)
  905. assert.Assert(c, is.Regexp("^Could not find the file /notexist in container "+name+"\n$", string(b)))
  906. }
  907. func (s *DockerAPISuite) TestContainerAPICopyContainerNotFoundPr124(c *testing.T) {
  908. testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later
  909. postData := types.CopyConfig{
  910. Resource: "/something",
  911. }
  912. res, _, err := request.Post("/v1.23/containers/notexists/copy", request.JSONBody(postData))
  913. assert.NilError(c, err)
  914. assert.Equal(c, res.StatusCode, http.StatusNotFound)
  915. }
  916. func (s *DockerAPISuite) TestContainerAPIDelete(c *testing.T) {
  917. out := runSleepingContainer(c)
  918. id := strings.TrimSpace(out)
  919. assert.NilError(c, waitRun(id))
  920. dockerCmd(c, "stop", id)
  921. cli, err := client.NewClientWithOpts(client.FromEnv)
  922. assert.NilError(c, err)
  923. defer cli.Close()
  924. err = cli.ContainerRemove(context.Background(), id, types.ContainerRemoveOptions{})
  925. assert.NilError(c, err)
  926. }
  927. func (s *DockerAPISuite) TestContainerAPIDeleteNotExist(c *testing.T) {
  928. cli, err := client.NewClientWithOpts(client.FromEnv)
  929. assert.NilError(c, err)
  930. defer cli.Close()
  931. err = cli.ContainerRemove(context.Background(), "doesnotexist", types.ContainerRemoveOptions{})
  932. assert.ErrorContains(c, err, "No such container: doesnotexist")
  933. }
  934. func (s *DockerAPISuite) TestContainerAPIDeleteForce(c *testing.T) {
  935. out := runSleepingContainer(c)
  936. id := strings.TrimSpace(out)
  937. assert.NilError(c, waitRun(id))
  938. removeOptions := types.ContainerRemoveOptions{
  939. Force: true,
  940. }
  941. cli, err := client.NewClientWithOpts(client.FromEnv)
  942. assert.NilError(c, err)
  943. defer cli.Close()
  944. err = cli.ContainerRemove(context.Background(), id, removeOptions)
  945. assert.NilError(c, err)
  946. }
  947. func (s *DockerAPISuite) TestContainerAPIDeleteRemoveLinks(c *testing.T) {
  948. // Windows does not support links
  949. testRequires(c, DaemonIsLinux)
  950. out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top")
  951. id := strings.TrimSpace(out)
  952. assert.NilError(c, waitRun(id))
  953. out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
  954. id2 := strings.TrimSpace(out)
  955. assert.Assert(c, waitRun(id2) == nil)
  956. links := inspectFieldJSON(c, id2, "HostConfig.Links")
  957. assert.Equal(c, links, "[\"/tlink1:/tlink2/tlink1\"]", "expected to have links between containers")
  958. removeOptions := types.ContainerRemoveOptions{
  959. RemoveLinks: true,
  960. }
  961. cli, err := client.NewClientWithOpts(client.FromEnv)
  962. assert.NilError(c, err)
  963. defer cli.Close()
  964. err = cli.ContainerRemove(context.Background(), "tlink2/tlink1", removeOptions)
  965. assert.NilError(c, err)
  966. linksPostRm := inspectFieldJSON(c, id2, "HostConfig.Links")
  967. assert.Equal(c, linksPostRm, "null", "call to api deleteContainer links should have removed the specified links")
  968. }
  969. func (s *DockerAPISuite) TestContainerAPIDeleteConflict(c *testing.T) {
  970. out := runSleepingContainer(c)
  971. id := strings.TrimSpace(out)
  972. assert.NilError(c, waitRun(id))
  973. cli, err := client.NewClientWithOpts(client.FromEnv)
  974. assert.NilError(c, err)
  975. defer cli.Close()
  976. err = cli.ContainerRemove(context.Background(), id, types.ContainerRemoveOptions{})
  977. expected := "cannot remove a running container"
  978. assert.ErrorContains(c, err, expected)
  979. }
  980. func (s *DockerAPISuite) TestContainerAPIDeleteRemoveVolume(c *testing.T) {
  981. testRequires(c, testEnv.IsLocalDaemon)
  982. vol := "/testvolume"
  983. if testEnv.OSType == "windows" {
  984. vol = `c:\testvolume`
  985. }
  986. out := runSleepingContainer(c, "-v", vol)
  987. id := strings.TrimSpace(out)
  988. assert.NilError(c, waitRun(id))
  989. source, err := inspectMountSourceField(id, vol)
  990. assert.NilError(c, err)
  991. _, err = os.Stat(source)
  992. assert.NilError(c, err)
  993. removeOptions := types.ContainerRemoveOptions{
  994. Force: true,
  995. RemoveVolumes: true,
  996. }
  997. cli, err := client.NewClientWithOpts(client.FromEnv)
  998. assert.NilError(c, err)
  999. defer cli.Close()
  1000. err = cli.ContainerRemove(context.Background(), id, removeOptions)
  1001. assert.NilError(c, err)
  1002. _, err = os.Stat(source)
  1003. assert.Assert(c, os.IsNotExist(err), "expected to get ErrNotExist error, got %v", err)
  1004. }
  1005. // Regression test for https://github.com/docker/docker/issues/6231
  1006. func (s *DockerAPISuite) TestContainerAPIChunkedEncoding(c *testing.T) {
  1007. config := map[string]interface{}{
  1008. "Image": "busybox",
  1009. "Cmd": append([]string{"/bin/sh", "-c"}, sleepCommandForDaemonPlatform()...),
  1010. "OpenStdin": true,
  1011. }
  1012. resp, _, err := request.Post("/containers/create", request.JSONBody(config), request.With(func(req *http.Request) error {
  1013. // This is a cheat to make the http request do chunked encoding
  1014. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  1015. // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
  1016. req.ContentLength = -1
  1017. return nil
  1018. }))
  1019. assert.Assert(c, err == nil, "error creating container with chunked encoding")
  1020. defer resp.Body.Close()
  1021. assert.Equal(c, resp.StatusCode, http.StatusCreated)
  1022. }
  1023. func (s *DockerAPISuite) TestContainerAPIPostContainerStop(c *testing.T) {
  1024. out := runSleepingContainer(c)
  1025. containerID := strings.TrimSpace(out)
  1026. assert.Assert(c, waitRun(containerID) == nil)
  1027. cli, err := client.NewClientWithOpts(client.FromEnv)
  1028. assert.NilError(c, err)
  1029. defer cli.Close()
  1030. err = cli.ContainerStop(context.Background(), containerID, container.StopOptions{})
  1031. assert.NilError(c, err)
  1032. assert.Assert(c, waitInspect(containerID, "{{ .State.Running }}", "false", 60*time.Second) == nil)
  1033. }
  1034. // #14170
  1035. func (s *DockerAPISuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *testing.T) {
  1036. config := container.Config{
  1037. Image: "busybox",
  1038. Entrypoint: []string{"echo"},
  1039. Cmd: []string{"hello", "world"},
  1040. }
  1041. cli, err := client.NewClientWithOpts(client.FromEnv)
  1042. assert.NilError(c, err)
  1043. defer cli.Close()
  1044. _, err = cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "echotest")
  1045. assert.NilError(c, err)
  1046. out, _ := dockerCmd(c, "start", "-a", "echotest")
  1047. assert.Equal(c, strings.TrimSpace(out), "hello world")
  1048. config2 := struct {
  1049. Image string
  1050. Entrypoint string
  1051. Cmd []string
  1052. }{"busybox", "echo", []string{"hello", "world"}}
  1053. _, _, err = request.Post("/containers/create?name=echotest2", request.JSONBody(config2))
  1054. assert.NilError(c, err)
  1055. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  1056. assert.Equal(c, strings.TrimSpace(out), "hello world")
  1057. }
  1058. // #14170
  1059. func (s *DockerAPISuite) TestPostContainersCreateWithStringOrSliceCmd(c *testing.T) {
  1060. config := container.Config{
  1061. Image: "busybox",
  1062. Cmd: []string{"echo", "hello", "world"},
  1063. }
  1064. cli, err := client.NewClientWithOpts(client.FromEnv)
  1065. assert.NilError(c, err)
  1066. defer cli.Close()
  1067. _, err = cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "echotest")
  1068. assert.NilError(c, err)
  1069. out, _ := dockerCmd(c, "start", "-a", "echotest")
  1070. assert.Equal(c, strings.TrimSpace(out), "hello world")
  1071. config2 := struct {
  1072. Image string
  1073. Entrypoint string
  1074. Cmd string
  1075. }{"busybox", "echo", "hello world"}
  1076. _, _, err = request.Post("/containers/create?name=echotest2", request.JSONBody(config2))
  1077. assert.NilError(c, err)
  1078. out, _ = dockerCmd(c, "start", "-a", "echotest2")
  1079. assert.Equal(c, strings.TrimSpace(out), "hello world")
  1080. }
  1081. // regression #14318
  1082. // for backward compatibility testing with and without CAP_ prefix
  1083. // and with upper and lowercase
  1084. func (s *DockerAPISuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *testing.T) {
  1085. // Windows doesn't support CapAdd/CapDrop
  1086. testRequires(c, DaemonIsLinux)
  1087. config := struct {
  1088. Image string
  1089. CapAdd string
  1090. CapDrop string
  1091. }{"busybox", "NET_ADMIN", "cap_sys_admin"}
  1092. res, _, err := request.Post("/containers/create?name=capaddtest0", request.JSONBody(config))
  1093. assert.NilError(c, err)
  1094. assert.Equal(c, res.StatusCode, http.StatusCreated)
  1095. config2 := container.Config{
  1096. Image: "busybox",
  1097. }
  1098. hostConfig := container.HostConfig{
  1099. CapAdd: []string{"net_admin", "SYS_ADMIN"},
  1100. CapDrop: []string{"SETGID", "CAP_SETPCAP"},
  1101. }
  1102. cli, err := client.NewClientWithOpts(client.FromEnv)
  1103. assert.NilError(c, err)
  1104. defer cli.Close()
  1105. _, err = cli.ContainerCreate(context.Background(), &config2, &hostConfig, &network.NetworkingConfig{}, nil, "capaddtest1")
  1106. assert.NilError(c, err)
  1107. }
  1108. // #14915
  1109. func (s *DockerAPISuite) TestContainerAPICreateNoHostConfig118(c *testing.T) {
  1110. testRequires(c, DaemonIsLinux) // Windows only support 1.25 or later
  1111. config := container.Config{
  1112. Image: "busybox",
  1113. }
  1114. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("v1.18"))
  1115. assert.NilError(c, err)
  1116. _, err = cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "")
  1117. assert.NilError(c, err)
  1118. }
  1119. // Ensure an error occurs when you have a container read-only rootfs but you
  1120. // extract an archive to a symlink in a writable volume which points to a
  1121. // directory outside of the volume.
  1122. func (s *DockerAPISuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(c *testing.T) {
  1123. // Windows does not support read-only rootfs
  1124. // Requires local volume mount bind.
  1125. // --read-only + userns has remount issues
  1126. testRequires(c, testEnv.IsLocalDaemon, NotUserNamespace, DaemonIsLinux)
  1127. testVol := getTestDir(c, "test-put-container-archive-err-symlink-in-volume-to-read-only-rootfs-")
  1128. defer os.RemoveAll(testVol)
  1129. makeTestContentInDir(c, testVol)
  1130. cID := makeTestContainer(c, testContainerOptions{
  1131. readOnly: true,
  1132. volumes: defaultVolumes(testVol), // Our bind mount is at /vol2
  1133. })
  1134. // Attempt to extract to a symlink in the volume which points to a
  1135. // directory outside the volume. This should cause an error because the
  1136. // rootfs is read-only.
  1137. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("v1.20"))
  1138. assert.NilError(c, err)
  1139. err = cli.CopyToContainer(context.Background(), cID, "/vol2/symlinkToAbsDir", nil, types.CopyToContainerOptions{})
  1140. assert.ErrorContains(c, err, "container rootfs is marked read-only")
  1141. }
  1142. func (s *DockerAPISuite) TestPostContainersCreateWithWrongCpusetValues(c *testing.T) {
  1143. // Not supported on Windows
  1144. testRequires(c, DaemonIsLinux)
  1145. cli, err := client.NewClientWithOpts(client.FromEnv)
  1146. assert.NilError(c, err)
  1147. defer cli.Close()
  1148. config := container.Config{
  1149. Image: "busybox",
  1150. }
  1151. hostConfig1 := container.HostConfig{
  1152. Resources: container.Resources{
  1153. CpusetCpus: "1-42,,",
  1154. },
  1155. }
  1156. name := "wrong-cpuset-cpus"
  1157. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig1, &network.NetworkingConfig{}, nil, name)
  1158. expected := "Invalid value 1-42,, for cpuset cpus"
  1159. assert.ErrorContains(c, err, expected)
  1160. hostConfig2 := container.HostConfig{
  1161. Resources: container.Resources{
  1162. CpusetMems: "42-3,1--",
  1163. },
  1164. }
  1165. name = "wrong-cpuset-mems"
  1166. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig2, &network.NetworkingConfig{}, nil, name)
  1167. expected = "Invalid value 42-3,1-- for cpuset mems"
  1168. assert.ErrorContains(c, err, expected)
  1169. }
  1170. func (s *DockerAPISuite) TestPostContainersCreateShmSizeNegative(c *testing.T) {
  1171. // ShmSize is not supported on Windows
  1172. testRequires(c, DaemonIsLinux)
  1173. config := container.Config{
  1174. Image: "busybox",
  1175. }
  1176. hostConfig := container.HostConfig{
  1177. ShmSize: -1,
  1178. }
  1179. cli, err := client.NewClientWithOpts(client.FromEnv)
  1180. assert.NilError(c, err)
  1181. defer cli.Close()
  1182. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, "")
  1183. assert.ErrorContains(c, err, "SHM size can not be less than 0")
  1184. }
  1185. func (s *DockerAPISuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *testing.T) {
  1186. // ShmSize is not supported on Windows
  1187. testRequires(c, DaemonIsLinux)
  1188. config := container.Config{
  1189. Image: "busybox",
  1190. Cmd: []string{"mount"},
  1191. }
  1192. cli, err := client.NewClientWithOpts(client.FromEnv)
  1193. assert.NilError(c, err)
  1194. defer cli.Close()
  1195. container, err := cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "")
  1196. assert.NilError(c, err)
  1197. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  1198. assert.NilError(c, err)
  1199. assert.Equal(c, containerJSON.HostConfig.ShmSize, dconfig.DefaultShmSize)
  1200. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1201. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1202. if !shmRegexp.MatchString(out) {
  1203. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1204. }
  1205. }
  1206. func (s *DockerAPISuite) TestPostContainersCreateShmSizeOmitted(c *testing.T) {
  1207. // ShmSize is not supported on Windows
  1208. testRequires(c, DaemonIsLinux)
  1209. config := container.Config{
  1210. Image: "busybox",
  1211. Cmd: []string{"mount"},
  1212. }
  1213. cli, err := client.NewClientWithOpts(client.FromEnv)
  1214. assert.NilError(c, err)
  1215. defer cli.Close()
  1216. container, err := cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "")
  1217. assert.NilError(c, err)
  1218. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  1219. assert.NilError(c, err)
  1220. assert.Equal(c, containerJSON.HostConfig.ShmSize, int64(67108864))
  1221. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1222. shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  1223. if !shmRegexp.MatchString(out) {
  1224. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  1225. }
  1226. }
  1227. func (s *DockerAPISuite) TestPostContainersCreateWithShmSize(c *testing.T) {
  1228. // ShmSize is not supported on Windows
  1229. testRequires(c, DaemonIsLinux)
  1230. config := container.Config{
  1231. Image: "busybox",
  1232. Cmd: []string{"mount"},
  1233. }
  1234. hostConfig := container.HostConfig{
  1235. ShmSize: 1073741824,
  1236. }
  1237. cli, err := client.NewClientWithOpts(client.FromEnv)
  1238. assert.NilError(c, err)
  1239. defer cli.Close()
  1240. container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, "")
  1241. assert.NilError(c, err)
  1242. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  1243. assert.NilError(c, err)
  1244. assert.Equal(c, containerJSON.HostConfig.ShmSize, int64(1073741824))
  1245. out, _ := dockerCmd(c, "start", "-i", containerJSON.ID)
  1246. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  1247. if !shmRegex.MatchString(out) {
  1248. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  1249. }
  1250. }
  1251. func (s *DockerAPISuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted(c *testing.T) {
  1252. // Swappiness is not supported on Windows
  1253. testRequires(c, DaemonIsLinux)
  1254. config := container.Config{
  1255. Image: "busybox",
  1256. }
  1257. cli, err := client.NewClientWithOpts(client.FromEnv)
  1258. assert.NilError(c, err)
  1259. defer cli.Close()
  1260. container, err := cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "")
  1261. assert.NilError(c, err)
  1262. containerJSON, err := cli.ContainerInspect(context.Background(), container.ID)
  1263. assert.NilError(c, err)
  1264. if versions.LessThan(testEnv.DaemonAPIVersion(), "1.31") {
  1265. assert.Equal(c, *containerJSON.HostConfig.MemorySwappiness, int64(-1))
  1266. } else {
  1267. assert.Assert(c, containerJSON.HostConfig.MemorySwappiness == nil)
  1268. }
  1269. }
  1270. // check validation is done daemon side and not only in cli
  1271. func (s *DockerAPISuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *testing.T) {
  1272. // OomScoreAdj is not supported on Windows
  1273. testRequires(c, DaemonIsLinux)
  1274. config := container.Config{
  1275. Image: "busybox",
  1276. }
  1277. hostConfig := container.HostConfig{
  1278. OomScoreAdj: 1001,
  1279. }
  1280. cli, err := client.NewClientWithOpts(client.FromEnv)
  1281. assert.NilError(c, err)
  1282. defer cli.Close()
  1283. name := "oomscoreadj-over"
  1284. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, name)
  1285. expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]"
  1286. assert.ErrorContains(c, err, expected)
  1287. hostConfig = container.HostConfig{
  1288. OomScoreAdj: -1001,
  1289. }
  1290. name = "oomscoreadj-low"
  1291. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, name)
  1292. expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]"
  1293. assert.ErrorContains(c, err, expected)
  1294. }
  1295. // test case for #22210 where an empty container name caused panic.
  1296. func (s *DockerAPISuite) TestContainerAPIDeleteWithEmptyName(c *testing.T) {
  1297. cli, err := client.NewClientWithOpts(client.FromEnv)
  1298. assert.NilError(c, err)
  1299. defer cli.Close()
  1300. err = cli.ContainerRemove(context.Background(), "", types.ContainerRemoveOptions{})
  1301. assert.Check(c, errdefs.IsNotFound(err))
  1302. }
  1303. func (s *DockerAPISuite) TestContainerAPIStatsWithNetworkDisabled(c *testing.T) {
  1304. // Problematic on Windows as Windows does not support stats
  1305. testRequires(c, DaemonIsLinux)
  1306. name := "testing-network-disabled"
  1307. config := container.Config{
  1308. Image: "busybox",
  1309. Cmd: []string{"top"},
  1310. NetworkDisabled: true,
  1311. }
  1312. cli, err := client.NewClientWithOpts(client.FromEnv)
  1313. assert.NilError(c, err)
  1314. defer cli.Close()
  1315. _, err = cli.ContainerCreate(context.Background(), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, name)
  1316. assert.NilError(c, err)
  1317. err = cli.ContainerStart(context.Background(), name, types.ContainerStartOptions{})
  1318. assert.NilError(c, err)
  1319. assert.Assert(c, waitRun(name) == nil)
  1320. type b struct {
  1321. stats types.ContainerStats
  1322. err error
  1323. }
  1324. bc := make(chan b, 1)
  1325. go func() {
  1326. stats, err := cli.ContainerStats(context.Background(), name, false)
  1327. bc <- b{stats, err}
  1328. }()
  1329. // allow some time to stream the stats from the container
  1330. time.Sleep(4 * time.Second)
  1331. dockerCmd(c, "rm", "-f", name)
  1332. // collect the results from the stats stream or timeout and fail
  1333. // if the stream was not disconnected.
  1334. select {
  1335. case <-time.After(2 * time.Second):
  1336. c.Fatal("stream was not closed after container was removed")
  1337. case sr := <-bc:
  1338. assert.Assert(c, sr.err == nil)
  1339. sr.stats.Body.Close()
  1340. }
  1341. }
  1342. func (s *DockerAPISuite) TestContainersAPICreateMountsValidation(c *testing.T) {
  1343. type testCase struct {
  1344. config container.Config
  1345. hostConfig container.HostConfig
  1346. msg string
  1347. }
  1348. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1349. destPath := prefix + slash + "foo"
  1350. notExistPath := prefix + slash + "notexist"
  1351. cases := []testCase{
  1352. {
  1353. config: container.Config{
  1354. Image: "busybox",
  1355. },
  1356. hostConfig: container.HostConfig{
  1357. Mounts: []mount.Mount{{
  1358. Type: "notreal",
  1359. Target: destPath,
  1360. },
  1361. },
  1362. },
  1363. msg: "mount type unknown",
  1364. },
  1365. {
  1366. config: container.Config{
  1367. Image: "busybox",
  1368. },
  1369. hostConfig: container.HostConfig{
  1370. Mounts: []mount.Mount{{
  1371. Type: "bind"}}},
  1372. msg: "Target must not be empty",
  1373. },
  1374. {
  1375. config: container.Config{
  1376. Image: "busybox",
  1377. },
  1378. hostConfig: container.HostConfig{
  1379. Mounts: []mount.Mount{{
  1380. Type: "bind",
  1381. Target: destPath}}},
  1382. msg: "Source must not be empty",
  1383. },
  1384. {
  1385. config: container.Config{
  1386. Image: "busybox",
  1387. },
  1388. hostConfig: container.HostConfig{
  1389. Mounts: []mount.Mount{{
  1390. Type: "bind",
  1391. Source: notExistPath,
  1392. Target: destPath}}},
  1393. msg: "source path does not exist",
  1394. // FIXME(vdemeester) fails into e2e, migrate to integration/container anyway
  1395. // msg: "source path does not exist: " + notExistPath,
  1396. },
  1397. {
  1398. config: container.Config{
  1399. Image: "busybox",
  1400. },
  1401. hostConfig: container.HostConfig{
  1402. Mounts: []mount.Mount{{
  1403. Type: "volume"}}},
  1404. msg: "Target must not be empty",
  1405. },
  1406. {
  1407. config: container.Config{
  1408. Image: "busybox",
  1409. },
  1410. hostConfig: container.HostConfig{
  1411. Mounts: []mount.Mount{{
  1412. Type: "volume",
  1413. Source: "hello",
  1414. Target: destPath}}},
  1415. msg: "",
  1416. },
  1417. {
  1418. config: container.Config{
  1419. Image: "busybox",
  1420. },
  1421. hostConfig: container.HostConfig{
  1422. Mounts: []mount.Mount{{
  1423. Type: "volume",
  1424. Source: "hello2",
  1425. Target: destPath,
  1426. VolumeOptions: &mount.VolumeOptions{
  1427. DriverConfig: &mount.Driver{
  1428. Name: "local"}}}}},
  1429. msg: "",
  1430. },
  1431. }
  1432. if testEnv.IsLocalDaemon() {
  1433. tmpDir, err := ioutils.TempDir("", "test-mounts-api")
  1434. assert.NilError(c, err)
  1435. defer os.RemoveAll(tmpDir)
  1436. cases = append(cases, []testCase{
  1437. {
  1438. config: container.Config{
  1439. Image: "busybox",
  1440. },
  1441. hostConfig: container.HostConfig{
  1442. Mounts: []mount.Mount{{
  1443. Type: "bind",
  1444. Source: tmpDir,
  1445. Target: destPath}}},
  1446. msg: "",
  1447. },
  1448. {
  1449. config: container.Config{
  1450. Image: "busybox",
  1451. },
  1452. hostConfig: container.HostConfig{
  1453. Mounts: []mount.Mount{{
  1454. Type: "bind",
  1455. Source: tmpDir,
  1456. Target: destPath,
  1457. VolumeOptions: &mount.VolumeOptions{}}}},
  1458. msg: "VolumeOptions must not be specified",
  1459. },
  1460. }...)
  1461. }
  1462. if DaemonIsWindows() {
  1463. cases = append(cases, []testCase{
  1464. {
  1465. config: container.Config{
  1466. Image: "busybox",
  1467. },
  1468. hostConfig: container.HostConfig{
  1469. Mounts: []mount.Mount{
  1470. {
  1471. Type: "volume",
  1472. Source: "not-supported-on-windows",
  1473. Target: destPath,
  1474. VolumeOptions: &mount.VolumeOptions{
  1475. DriverConfig: &mount.Driver{
  1476. Name: "local",
  1477. Options: map[string]string{"type": "tmpfs"},
  1478. },
  1479. },
  1480. },
  1481. },
  1482. },
  1483. msg: `options are not supported on this platform`,
  1484. },
  1485. }...)
  1486. }
  1487. if DaemonIsLinux() {
  1488. cases = append(cases, []testCase{
  1489. {
  1490. config: container.Config{
  1491. Image: "busybox",
  1492. },
  1493. hostConfig: container.HostConfig{
  1494. Mounts: []mount.Mount{
  1495. {
  1496. Type: "volume",
  1497. Source: "missing-device-opt",
  1498. Target: destPath,
  1499. VolumeOptions: &mount.VolumeOptions{
  1500. DriverConfig: &mount.Driver{
  1501. Name: "local",
  1502. Options: map[string]string{"foobar": "foobaz"},
  1503. },
  1504. },
  1505. },
  1506. },
  1507. },
  1508. msg: `invalid option: "foobar"`,
  1509. },
  1510. {
  1511. config: container.Config{
  1512. Image: "busybox",
  1513. },
  1514. hostConfig: container.HostConfig{
  1515. Mounts: []mount.Mount{
  1516. {
  1517. Type: "volume",
  1518. Source: "missing-device-opt",
  1519. Target: destPath,
  1520. VolumeOptions: &mount.VolumeOptions{
  1521. DriverConfig: &mount.Driver{
  1522. Name: "local",
  1523. Options: map[string]string{"type": "tmpfs"},
  1524. },
  1525. },
  1526. },
  1527. },
  1528. },
  1529. msg: `missing required option: "device"`,
  1530. },
  1531. {
  1532. config: container.Config{
  1533. Image: "busybox",
  1534. },
  1535. hostConfig: container.HostConfig{
  1536. Mounts: []mount.Mount{
  1537. {
  1538. Type: "volume",
  1539. Source: "missing-type-opt",
  1540. Target: destPath,
  1541. VolumeOptions: &mount.VolumeOptions{
  1542. DriverConfig: &mount.Driver{
  1543. Name: "local",
  1544. Options: map[string]string{"device": "tmpfs"},
  1545. },
  1546. },
  1547. },
  1548. },
  1549. },
  1550. msg: `missing required option: "type"`,
  1551. },
  1552. {
  1553. config: container.Config{
  1554. Image: "busybox",
  1555. },
  1556. hostConfig: container.HostConfig{
  1557. Mounts: []mount.Mount{
  1558. {
  1559. Type: "volume",
  1560. Source: "hello4",
  1561. Target: destPath,
  1562. VolumeOptions: &mount.VolumeOptions{
  1563. DriverConfig: &mount.Driver{
  1564. Name: "local",
  1565. Options: map[string]string{"o": "size=1", "type": "tmpfs", "device": "tmpfs"},
  1566. },
  1567. },
  1568. },
  1569. },
  1570. },
  1571. msg: "",
  1572. },
  1573. {
  1574. config: container.Config{
  1575. Image: "busybox",
  1576. },
  1577. hostConfig: container.HostConfig{
  1578. Mounts: []mount.Mount{{
  1579. Type: "tmpfs",
  1580. Target: destPath}}},
  1581. msg: "",
  1582. },
  1583. {
  1584. config: container.Config{
  1585. Image: "busybox",
  1586. },
  1587. hostConfig: container.HostConfig{
  1588. Mounts: []mount.Mount{{
  1589. Type: "tmpfs",
  1590. Target: destPath,
  1591. TmpfsOptions: &mount.TmpfsOptions{
  1592. SizeBytes: 4096 * 1024,
  1593. Mode: 0700,
  1594. }}}},
  1595. msg: "",
  1596. },
  1597. {
  1598. config: container.Config{
  1599. Image: "busybox",
  1600. },
  1601. hostConfig: container.HostConfig{
  1602. Mounts: []mount.Mount{{
  1603. Type: "tmpfs",
  1604. Source: "/shouldnotbespecified",
  1605. Target: destPath}}},
  1606. msg: "Source must not be specified",
  1607. },
  1608. }...)
  1609. }
  1610. apiClient, err := client.NewClientWithOpts(client.FromEnv)
  1611. assert.NilError(c, err)
  1612. defer apiClient.Close()
  1613. // TODO add checks for statuscode returned by API
  1614. for i, x := range cases {
  1615. x := x
  1616. c.Run(fmt.Sprintf("case %d", i), func(c *testing.T) {
  1617. _, err = apiClient.ContainerCreate(context.Background(), &x.config, &x.hostConfig, &network.NetworkingConfig{}, nil, "")
  1618. if len(x.msg) > 0 {
  1619. assert.ErrorContains(c, err, x.msg, "%v", cases[i].config)
  1620. } else {
  1621. assert.NilError(c, err)
  1622. }
  1623. })
  1624. }
  1625. }
  1626. func (s *DockerAPISuite) TestContainerAPICreateMountsBindRead(c *testing.T) {
  1627. testRequires(c, NotUserNamespace, testEnv.IsLocalDaemon)
  1628. // also with data in the host side
  1629. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1630. destPath := prefix + slash + "foo"
  1631. tmpDir, err := os.MkdirTemp("", "test-mounts-api-bind")
  1632. assert.NilError(c, err)
  1633. defer os.RemoveAll(tmpDir)
  1634. err = os.WriteFile(filepath.Join(tmpDir, "bar"), []byte("hello"), 0666)
  1635. assert.NilError(c, err)
  1636. config := container.Config{
  1637. Image: "busybox",
  1638. Cmd: []string{"/bin/sh", "-c", "cat /foo/bar"},
  1639. }
  1640. hostConfig := container.HostConfig{
  1641. Mounts: []mount.Mount{
  1642. {Type: "bind", Source: tmpDir, Target: destPath},
  1643. },
  1644. }
  1645. cli, err := client.NewClientWithOpts(client.FromEnv)
  1646. assert.NilError(c, err)
  1647. defer cli.Close()
  1648. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, "test")
  1649. assert.NilError(c, err)
  1650. out, _ := dockerCmd(c, "start", "-a", "test")
  1651. assert.Equal(c, out, "hello")
  1652. }
  1653. // Test Mounts comes out as expected for the MountPoint
  1654. func (s *DockerAPISuite) TestContainersAPICreateMountsCreate(c *testing.T) {
  1655. prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  1656. destPath := prefix + slash + "foo"
  1657. var (
  1658. testImg string
  1659. )
  1660. if testEnv.OSType != "windows" {
  1661. testImg = "test-mount-config"
  1662. buildImageSuccessfully(c, testImg, build.WithDockerfile(`
  1663. FROM busybox
  1664. RUN mkdir `+destPath+` && touch `+destPath+slash+`bar
  1665. CMD cat `+destPath+slash+`bar
  1666. `))
  1667. } else {
  1668. testImg = "busybox"
  1669. }
  1670. type testCase struct {
  1671. spec mount.Mount
  1672. expected types.MountPoint
  1673. }
  1674. var selinuxSharedLabel string
  1675. // this test label was added after a bug fix in 1.32, thus add requirements min API >= 1.32
  1676. // for the sake of making test pass in earlier versions
  1677. // bug fixed in https://github.com/moby/moby/pull/34684
  1678. if !versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") {
  1679. if runtime.GOOS == "linux" {
  1680. selinuxSharedLabel = "z"
  1681. }
  1682. }
  1683. cases := []testCase{
  1684. // use literal strings here for `Type` instead of the defined constants in the volume package to keep this honest
  1685. // Validation of the actual `Mount` struct is done in another test is not needed here
  1686. {
  1687. spec: mount.Mount{Type: "volume", Target: destPath},
  1688. expected: types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath, Mode: selinuxSharedLabel},
  1689. },
  1690. {
  1691. spec: mount.Mount{Type: "volume", Target: destPath + slash},
  1692. expected: types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath, Mode: selinuxSharedLabel},
  1693. },
  1694. {
  1695. spec: mount.Mount{Type: "volume", Target: destPath, Source: "test1"},
  1696. expected: types.MountPoint{Type: "volume", Name: "test1", RW: true, Destination: destPath, Mode: selinuxSharedLabel},
  1697. },
  1698. {
  1699. spec: mount.Mount{Type: "volume", Target: destPath, ReadOnly: true, Source: "test2"},
  1700. expected: types.MountPoint{Type: "volume", Name: "test2", RW: false, Destination: destPath, Mode: selinuxSharedLabel},
  1701. },
  1702. {
  1703. spec: mount.Mount{Type: "volume", Target: destPath, Source: "test3", VolumeOptions: &mount.VolumeOptions{DriverConfig: &mount.Driver{Name: volume.DefaultDriverName}}},
  1704. expected: types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", Name: "test3", RW: true, Destination: destPath, Mode: selinuxSharedLabel},
  1705. },
  1706. }
  1707. if testEnv.IsLocalDaemon() {
  1708. // setup temp dir for testing binds
  1709. tmpDir1, err := os.MkdirTemp("", "test-mounts-api-1")
  1710. assert.NilError(c, err)
  1711. defer os.RemoveAll(tmpDir1)
  1712. cases = append(cases, []testCase{
  1713. {
  1714. spec: mount.Mount{
  1715. Type: "bind",
  1716. Source: tmpDir1,
  1717. Target: destPath,
  1718. },
  1719. expected: types.MountPoint{
  1720. Type: "bind",
  1721. RW: true,
  1722. Destination: destPath,
  1723. Source: tmpDir1,
  1724. },
  1725. },
  1726. {
  1727. spec: mount.Mount{Type: "bind", Source: tmpDir1, Target: destPath, ReadOnly: true},
  1728. expected: types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir1},
  1729. },
  1730. }...)
  1731. // for modes only supported on Linux
  1732. if DaemonIsLinux() {
  1733. tmpDir3, err := ioutils.TempDir("", "test-mounts-api-3")
  1734. assert.NilError(c, err)
  1735. defer os.RemoveAll(tmpDir3)
  1736. assert.Assert(c, mountWrapper(tmpDir3, tmpDir3, "none", "bind,shared") == nil)
  1737. cases = append(cases, []testCase{
  1738. {
  1739. spec: mount.Mount{Type: "bind", Source: tmpDir3, Target: destPath},
  1740. expected: types.MountPoint{Type: "bind", RW: true, Destination: destPath, Source: tmpDir3},
  1741. },
  1742. {
  1743. spec: mount.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true},
  1744. expected: types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir3},
  1745. },
  1746. {
  1747. spec: mount.Mount{Type: "bind", Source: tmpDir3, Target: destPath, ReadOnly: true, BindOptions: &mount.BindOptions{Propagation: "shared"}},
  1748. expected: types.MountPoint{Type: "bind", RW: false, Destination: destPath, Source: tmpDir3, Propagation: "shared"},
  1749. },
  1750. }...)
  1751. }
  1752. }
  1753. if testEnv.OSType != "windows" { // Windows does not support volume populate
  1754. cases = append(cases, []testCase{
  1755. {
  1756. spec: mount.Mount{Type: "volume", Target: destPath, VolumeOptions: &mount.VolumeOptions{NoCopy: true}},
  1757. expected: types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath, Mode: selinuxSharedLabel},
  1758. },
  1759. {
  1760. spec: mount.Mount{Type: "volume", Target: destPath + slash, VolumeOptions: &mount.VolumeOptions{NoCopy: true}},
  1761. expected: types.MountPoint{Driver: volume.DefaultDriverName, Type: "volume", RW: true, Destination: destPath, Mode: selinuxSharedLabel},
  1762. },
  1763. {
  1764. spec: mount.Mount{Type: "volume", Target: destPath, Source: "test4", VolumeOptions: &mount.VolumeOptions{NoCopy: true}},
  1765. expected: types.MountPoint{Type: "volume", Name: "test4", RW: true, Destination: destPath, Mode: selinuxSharedLabel},
  1766. },
  1767. {
  1768. spec: mount.Mount{Type: "volume", Target: destPath, Source: "test5", ReadOnly: true, VolumeOptions: &mount.VolumeOptions{NoCopy: true}},
  1769. expected: types.MountPoint{Type: "volume", Name: "test5", RW: false, Destination: destPath, Mode: selinuxSharedLabel},
  1770. },
  1771. }...)
  1772. }
  1773. ctx := context.Background()
  1774. apiclient := testEnv.APIClient()
  1775. for i, x := range cases {
  1776. x := x
  1777. c.Run(fmt.Sprintf("%d config: %v", i, x.spec), func(c *testing.T) {
  1778. container, err := apiclient.ContainerCreate(
  1779. ctx,
  1780. &container.Config{Image: testImg},
  1781. &container.HostConfig{Mounts: []mount.Mount{x.spec}},
  1782. &network.NetworkingConfig{},
  1783. nil,
  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. }
  1830. func containerExit(apiclient client.APIClient, name string) func(poll.LogT) poll.Result {
  1831. return func(logT poll.LogT) poll.Result {
  1832. container, err := apiclient.ContainerInspect(context.Background(), name)
  1833. if err != nil {
  1834. return poll.Error(err)
  1835. }
  1836. switch container.State.Status {
  1837. case "created", "running":
  1838. return poll.Continue("container %s is %s, waiting for exit", name, container.State.Status)
  1839. }
  1840. return poll.Success()
  1841. }
  1842. }
  1843. func (s *DockerAPISuite) TestContainersAPICreateMountsTmpfs(c *testing.T) {
  1844. testRequires(c, DaemonIsLinux)
  1845. type testCase struct {
  1846. cfg mount.Mount
  1847. expectedOptions []string
  1848. }
  1849. target := "/foo"
  1850. cases := []testCase{
  1851. {
  1852. cfg: mount.Mount{
  1853. Type: "tmpfs",
  1854. Target: target},
  1855. expectedOptions: []string{"rw", "nosuid", "nodev", "noexec", "relatime"},
  1856. },
  1857. {
  1858. cfg: mount.Mount{
  1859. Type: "tmpfs",
  1860. Target: target,
  1861. TmpfsOptions: &mount.TmpfsOptions{
  1862. SizeBytes: 4096 * 1024, Mode: 0700}},
  1863. expectedOptions: []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=4096k", "mode=700"},
  1864. },
  1865. }
  1866. cli, err := client.NewClientWithOpts(client.FromEnv)
  1867. assert.NilError(c, err)
  1868. defer cli.Close()
  1869. config := container.Config{
  1870. Image: "busybox",
  1871. Cmd: []string{"/bin/sh", "-c", fmt.Sprintf("mount | grep 'tmpfs on %s'", target)},
  1872. }
  1873. for i, x := range cases {
  1874. cName := fmt.Sprintf("test-tmpfs-%d", i)
  1875. hostConfig := container.HostConfig{
  1876. Mounts: []mount.Mount{x.cfg},
  1877. }
  1878. _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, nil, cName)
  1879. assert.NilError(c, err)
  1880. out, _ := dockerCmd(c, "start", "-a", cName)
  1881. for _, option := range x.expectedOptions {
  1882. assert.Assert(c, strings.Contains(out, option))
  1883. }
  1884. }
  1885. }
  1886. // Regression test for #33334
  1887. // Makes sure that when a container which has a custom stop signal + restart=always
  1888. // gets killed (with SIGKILL) by the kill API, that the restart policy is cancelled.
  1889. func (s *DockerAPISuite) TestContainerKillCustomStopSignal(c *testing.T) {
  1890. id := strings.TrimSpace(runSleepingContainer(c, "--stop-signal=SIGTERM", "--restart=always"))
  1891. res, _, err := request.Post("/containers/" + id + "/kill")
  1892. assert.NilError(c, err)
  1893. defer res.Body.Close()
  1894. b, err := io.ReadAll(res.Body)
  1895. assert.NilError(c, err)
  1896. assert.Equal(c, res.StatusCode, http.StatusNoContent, string(b))
  1897. err = waitInspect(id, "{{.State.Running}} {{.State.Restarting}}", "false false", 30*time.Second)
  1898. assert.NilError(c, err)
  1899. }