docker_api_containers_test.go 67 KB

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