docker_api_containers_test.go 67 KB

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