docker_api_containers_test.go 67 KB

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