docker_api_containers_test.go 67 KB

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