docker_api_containers_test.go 67 KB

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