docker_api_containers_test.go 67 KB

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