docker_cli_daemon_test.go 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130
  1. // +build linux
  2. package main
  3. import (
  4. "bufio"
  5. "bytes"
  6. "context"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "regexp"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "time"
  21. "crypto/tls"
  22. "crypto/x509"
  23. "github.com/cloudflare/cfssl/helpers"
  24. "github.com/docker/docker/api"
  25. "github.com/docker/docker/api/types"
  26. "github.com/docker/docker/client"
  27. moby_daemon "github.com/docker/docker/daemon"
  28. "github.com/docker/docker/integration-cli/checker"
  29. "github.com/docker/docker/integration-cli/cli"
  30. "github.com/docker/docker/integration-cli/daemon"
  31. testdaemon "github.com/docker/docker/internal/test/daemon"
  32. "github.com/docker/docker/opts"
  33. "github.com/docker/docker/pkg/mount"
  34. units "github.com/docker/go-units"
  35. "github.com/docker/libnetwork/iptables"
  36. "github.com/docker/libtrust"
  37. "github.com/go-check/check"
  38. "github.com/gotestyourself/gotestyourself/icmd"
  39. "github.com/kr/pty"
  40. "golang.org/x/sys/unix"
  41. )
  42. // TestLegacyDaemonCommand test starting docker daemon using "deprecated" docker daemon
  43. // command. Remove this test when we remove this.
  44. func (s *DockerDaemonSuite) TestLegacyDaemonCommand(c *check.C) {
  45. cmd := exec.Command(dockerBinary, "daemon", "--storage-driver=vfs", "--debug")
  46. err := cmd.Start()
  47. go cmd.Wait()
  48. c.Assert(err, checker.IsNil, check.Commentf("could not start daemon using 'docker daemon'"))
  49. c.Assert(cmd.Process.Kill(), checker.IsNil)
  50. }
  51. func (s *DockerDaemonSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) {
  52. s.d.StartWithBusybox(c)
  53. cli.Docker(
  54. cli.Args("run", "-d", "--name", "top1", "-p", "1234:80", "--restart", "always", "busybox:latest", "top"),
  55. cli.Daemon(s.d),
  56. ).Assert(c, icmd.Success)
  57. cli.Docker(
  58. cli.Args("run", "-d", "--name", "top2", "-p", "80", "busybox:latest", "top"),
  59. cli.Daemon(s.d),
  60. ).Assert(c, icmd.Success)
  61. testRun := func(m map[string]bool, prefix string) {
  62. var format string
  63. for cont, shouldRun := range m {
  64. out := cli.Docker(cli.Args("ps"), cli.Daemon(s.d)).Assert(c, icmd.Success).Combined()
  65. if shouldRun {
  66. format = "%scontainer %q is not running"
  67. } else {
  68. format = "%scontainer %q is running"
  69. }
  70. if shouldRun != strings.Contains(out, cont) {
  71. c.Fatalf(format, prefix, cont)
  72. }
  73. }
  74. }
  75. testRun(map[string]bool{"top1": true, "top2": true}, "")
  76. s.d.Restart(c)
  77. testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ")
  78. }
  79. func (s *DockerDaemonSuite) TestDaemonRestartWithVolumesRefs(c *check.C) {
  80. s.d.StartWithBusybox(c)
  81. if out, err := s.d.Cmd("run", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil {
  82. c.Fatal(err, out)
  83. }
  84. s.d.Restart(c)
  85. if out, err := s.d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox", "top"); err != nil {
  86. c.Fatal(err, out)
  87. }
  88. if out, err := s.d.Cmd("rm", "-fv", "volrestarttest2"); err != nil {
  89. c.Fatal(err, out)
  90. }
  91. out, err := s.d.Cmd("inspect", "-f", "{{json .Mounts}}", "volrestarttest1")
  92. c.Assert(err, check.IsNil)
  93. if _, err := inspectMountPointJSON(out, "/foo"); err != nil {
  94. c.Fatalf("Expected volume to exist: /foo, error: %v\n", err)
  95. }
  96. }
  97. // #11008
  98. func (s *DockerDaemonSuite) TestDaemonRestartUnlessStopped(c *check.C) {
  99. s.d.StartWithBusybox(c)
  100. out, err := s.d.Cmd("run", "-d", "--name", "top1", "--restart", "always", "busybox:latest", "top")
  101. c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out))
  102. out, err = s.d.Cmd("run", "-d", "--name", "top2", "--restart", "unless-stopped", "busybox:latest", "top")
  103. c.Assert(err, check.IsNil, check.Commentf("run top2: %v", out))
  104. testRun := func(m map[string]bool, prefix string) {
  105. var format string
  106. for name, shouldRun := range m {
  107. out, err := s.d.Cmd("ps")
  108. c.Assert(err, check.IsNil, check.Commentf("run ps: %v", out))
  109. if shouldRun {
  110. format = "%scontainer %q is not running"
  111. } else {
  112. format = "%scontainer %q is running"
  113. }
  114. c.Assert(strings.Contains(out, name), check.Equals, shouldRun, check.Commentf(format, prefix, name))
  115. }
  116. }
  117. // both running
  118. testRun(map[string]bool{"top1": true, "top2": true}, "")
  119. out, err = s.d.Cmd("stop", "top1")
  120. c.Assert(err, check.IsNil, check.Commentf(out))
  121. out, err = s.d.Cmd("stop", "top2")
  122. c.Assert(err, check.IsNil, check.Commentf(out))
  123. // both stopped
  124. testRun(map[string]bool{"top1": false, "top2": false}, "")
  125. s.d.Restart(c)
  126. // restart=always running
  127. testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ")
  128. out, err = s.d.Cmd("start", "top2")
  129. c.Assert(err, check.IsNil, check.Commentf("start top2: %v", out))
  130. s.d.Restart(c)
  131. // both running
  132. testRun(map[string]bool{"top1": true, "top2": true}, "After second daemon restart: ")
  133. }
  134. func (s *DockerDaemonSuite) TestDaemonRestartOnFailure(c *check.C) {
  135. s.d.StartWithBusybox(c)
  136. out, err := s.d.Cmd("run", "-d", "--name", "test1", "--restart", "on-failure:3", "busybox:latest", "false")
  137. c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out))
  138. // wait test1 to stop
  139. hostArgs := []string{"--host", s.d.Sock()}
  140. err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 10*time.Second, hostArgs...)
  141. c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not"))
  142. // record last start time
  143. out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1")
  144. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  145. lastStartTime := out
  146. s.d.Restart(c)
  147. // test1 shouldn't restart at all
  148. err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 0, hostArgs...)
  149. c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not"))
  150. // make sure test1 isn't restarted when daemon restart
  151. // if "StartAt" time updates, means test1 was once restarted.
  152. out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1")
  153. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  154. c.Assert(out, checker.Equals, lastStartTime, check.Commentf("test1 shouldn't start after daemon restarts"))
  155. }
  156. func (s *DockerDaemonSuite) TestDaemonStartIptablesFalse(c *check.C) {
  157. s.d.Start(c, "--iptables=false")
  158. }
  159. // Make sure we cannot shrink base device at daemon restart.
  160. func (s *DockerDaemonSuite) TestDaemonRestartWithInvalidBasesize(c *check.C) {
  161. testRequires(c, Devicemapper)
  162. s.d.Start(c)
  163. oldBasesizeBytes := getBaseDeviceSize(c, s.d)
  164. var newBasesizeBytes int64 = 1073741824 //1GB in bytes
  165. if newBasesizeBytes < oldBasesizeBytes {
  166. err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes))
  167. c.Assert(err, check.NotNil, check.Commentf("daemon should not have started as new base device size is less than existing base device size: %v", err))
  168. // 'err != nil' is expected behaviour, no new daemon started,
  169. // so no need to stop daemon.
  170. if err != nil {
  171. return
  172. }
  173. }
  174. s.d.Stop(c)
  175. }
  176. // Make sure we can grow base device at daemon restart.
  177. func (s *DockerDaemonSuite) TestDaemonRestartWithIncreasedBasesize(c *check.C) {
  178. testRequires(c, Devicemapper)
  179. s.d.Start(c)
  180. oldBasesizeBytes := getBaseDeviceSize(c, s.d)
  181. var newBasesizeBytes int64 = 53687091200 //50GB in bytes
  182. if newBasesizeBytes < oldBasesizeBytes {
  183. c.Skip(fmt.Sprintf("New base device size (%v) must be greater than (%s)", units.HumanSize(float64(newBasesizeBytes)), units.HumanSize(float64(oldBasesizeBytes))))
  184. }
  185. err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes))
  186. c.Assert(err, check.IsNil, check.Commentf("we should have been able to start the daemon with increased base device size: %v", err))
  187. basesizeAfterRestart := getBaseDeviceSize(c, s.d)
  188. newBasesize, err := convertBasesize(newBasesizeBytes)
  189. c.Assert(err, check.IsNil, check.Commentf("Error in converting base device size: %v", err))
  190. c.Assert(newBasesize, check.Equals, basesizeAfterRestart, check.Commentf("Basesize passed is not equal to Basesize set"))
  191. s.d.Stop(c)
  192. }
  193. func getBaseDeviceSize(c *check.C, d *daemon.Daemon) int64 {
  194. info := d.Info(c)
  195. for _, statusLine := range info.DriverStatus {
  196. key, value := statusLine[0], statusLine[1]
  197. if key == "Base Device Size" {
  198. return parseDeviceSize(c, value)
  199. }
  200. }
  201. c.Fatal("failed to parse Base Device Size from info")
  202. return int64(0)
  203. }
  204. func parseDeviceSize(c *check.C, raw string) int64 {
  205. size, err := units.RAMInBytes(strings.TrimSpace(raw))
  206. c.Assert(err, check.IsNil)
  207. return size
  208. }
  209. func convertBasesize(basesizeBytes int64) (int64, error) {
  210. basesize := units.HumanSize(float64(basesizeBytes))
  211. basesize = strings.Trim(basesize, " ")[:len(basesize)-3]
  212. basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64)
  213. if err != nil {
  214. return 0, err
  215. }
  216. return int64(basesizeFloat) * 1024 * 1024 * 1024, nil
  217. }
  218. // Issue #8444: If docker0 bridge is modified (intentionally or unintentionally) and
  219. // no longer has an IP associated, we should gracefully handle that case and associate
  220. // an IP with it rather than fail daemon start
  221. func (s *DockerDaemonSuite) TestDaemonStartBridgeWithoutIPAssociation(c *check.C) {
  222. // rather than depending on brctl commands to verify docker0 is created and up
  223. // let's start the daemon and stop it, and then make a modification to run the
  224. // actual test
  225. s.d.Start(c)
  226. s.d.Stop(c)
  227. // now we will remove the ip from docker0 and then try starting the daemon
  228. icmd.RunCommand("ip", "addr", "flush", "dev", "docker0").Assert(c, icmd.Success)
  229. if err := s.d.StartWithError(); err != nil {
  230. warning := "**WARNING: Docker bridge network in bad state--delete docker0 bridge interface to fix"
  231. c.Fatalf("Could not start daemon when docker0 has no IP address: %v\n%s", err, warning)
  232. }
  233. }
  234. func (s *DockerDaemonSuite) TestDaemonIptablesClean(c *check.C) {
  235. s.d.StartWithBusybox(c)
  236. if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil {
  237. c.Fatalf("Could not run top: %s, %v", out, err)
  238. }
  239. ipTablesSearchString := "tcp dpt:80"
  240. // get output from iptables with container running
  241. verifyIPTablesContains(c, ipTablesSearchString)
  242. s.d.Stop(c)
  243. // get output from iptables after restart
  244. verifyIPTablesDoesNotContains(c, ipTablesSearchString)
  245. }
  246. func (s *DockerDaemonSuite) TestDaemonIptablesCreate(c *check.C) {
  247. s.d.StartWithBusybox(c)
  248. if out, err := s.d.Cmd("run", "-d", "--name", "top", "--restart=always", "-p", "80", "busybox:latest", "top"); err != nil {
  249. c.Fatalf("Could not run top: %s, %v", out, err)
  250. }
  251. // get output from iptables with container running
  252. ipTablesSearchString := "tcp dpt:80"
  253. verifyIPTablesContains(c, ipTablesSearchString)
  254. s.d.Restart(c)
  255. // make sure the container is not running
  256. runningOut, err := s.d.Cmd("inspect", "--format={{.State.Running}}", "top")
  257. if err != nil {
  258. c.Fatalf("Could not inspect on container: %s, %v", runningOut, err)
  259. }
  260. if strings.TrimSpace(runningOut) != "true" {
  261. c.Fatalf("Container should have been restarted after daemon restart. Status running should have been true but was: %q", strings.TrimSpace(runningOut))
  262. }
  263. // get output from iptables after restart
  264. verifyIPTablesContains(c, ipTablesSearchString)
  265. }
  266. func verifyIPTablesContains(c *check.C, ipTablesSearchString string) {
  267. result := icmd.RunCommand("iptables", "-nvL")
  268. result.Assert(c, icmd.Success)
  269. if !strings.Contains(result.Combined(), ipTablesSearchString) {
  270. c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, result.Combined())
  271. }
  272. }
  273. func verifyIPTablesDoesNotContains(c *check.C, ipTablesSearchString string) {
  274. result := icmd.RunCommand("iptables", "-nvL")
  275. result.Assert(c, icmd.Success)
  276. if strings.Contains(result.Combined(), ipTablesSearchString) {
  277. c.Fatalf("iptables output should not have contained %q, but was %q", ipTablesSearchString, result.Combined())
  278. }
  279. }
  280. // TestDaemonIPv6Enabled checks that when the daemon is started with --ipv6=true that the docker0 bridge
  281. // has the fe80::1 address and that a container is assigned a link-local address
  282. func (s *DockerDaemonSuite) TestDaemonIPv6Enabled(c *check.C) {
  283. testRequires(c, IPv6)
  284. setupV6(c)
  285. defer teardownV6(c)
  286. s.d.StartWithBusybox(c, "--ipv6")
  287. iface, err := net.InterfaceByName("docker0")
  288. if err != nil {
  289. c.Fatalf("Error getting docker0 interface: %v", err)
  290. }
  291. addrs, err := iface.Addrs()
  292. if err != nil {
  293. c.Fatalf("Error getting addresses for docker0 interface: %v", err)
  294. }
  295. var found bool
  296. expected := "fe80::1/64"
  297. for i := range addrs {
  298. if addrs[i].String() == expected {
  299. found = true
  300. break
  301. }
  302. }
  303. if !found {
  304. c.Fatalf("Bridge does not have an IPv6 Address")
  305. }
  306. if out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest"); err != nil {
  307. c.Fatalf("Could not run container: %s, %v", out, err)
  308. }
  309. out, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.LinkLocalIPv6Address}}'", "ipv6test")
  310. out = strings.Trim(out, " \r\n'")
  311. if err != nil {
  312. c.Fatalf("Error inspecting container: %s, %v", out, err)
  313. }
  314. if ip := net.ParseIP(out); ip == nil {
  315. c.Fatalf("Container should have a link-local IPv6 address")
  316. }
  317. out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}'", "ipv6test")
  318. out = strings.Trim(out, " \r\n'")
  319. if err != nil {
  320. c.Fatalf("Error inspecting container: %s, %v", out, err)
  321. }
  322. if ip := net.ParseIP(out); ip != nil {
  323. c.Fatalf("Container should not have a global IPv6 address: %v", out)
  324. }
  325. }
  326. // TestDaemonIPv6FixedCIDR checks that when the daemon is started with --ipv6=true and a fixed CIDR
  327. // that running containers are given a link-local and global IPv6 address
  328. func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDR(c *check.C) {
  329. // IPv6 setup is messing with local bridge address.
  330. testRequires(c, SameHostDaemon)
  331. // Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with
  332. // ipv6 enabled
  333. deleteInterface(c, "docker0")
  334. s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:2::/64", "--default-gateway-v6=2001:db8:2::100")
  335. out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest")
  336. c.Assert(err, checker.IsNil, check.Commentf("Could not run container: %s, %v", out, err))
  337. out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test")
  338. out = strings.Trim(out, " \r\n'")
  339. c.Assert(err, checker.IsNil, check.Commentf(out))
  340. ip := net.ParseIP(out)
  341. c.Assert(ip, checker.NotNil, check.Commentf("Container should have a global IPv6 address"))
  342. out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.IPv6Gateway}}", "ipv6test")
  343. c.Assert(err, checker.IsNil, check.Commentf(out))
  344. c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:2::100", check.Commentf("Container should have a global IPv6 gateway"))
  345. }
  346. // TestDaemonIPv6FixedCIDRAndMac checks that when the daemon is started with ipv6 fixed CIDR
  347. // the running containers are given an IPv6 address derived from the MAC address and the ipv6 fixed CIDR
  348. func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDRAndMac(c *check.C) {
  349. // IPv6 setup is messing with local bridge address.
  350. testRequires(c, SameHostDaemon)
  351. // Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with
  352. // ipv6 enabled
  353. deleteInterface(c, "docker0")
  354. s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:1::/64")
  355. out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "--mac-address", "AA:BB:CC:DD:EE:FF", "busybox")
  356. c.Assert(err, checker.IsNil)
  357. out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test")
  358. c.Assert(err, checker.IsNil)
  359. c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:1::aabb:ccdd:eeff")
  360. }
  361. // TestDaemonIPv6HostMode checks that when the running a container with
  362. // network=host the host ipv6 addresses are not removed
  363. func (s *DockerDaemonSuite) TestDaemonIPv6HostMode(c *check.C) {
  364. testRequires(c, SameHostDaemon)
  365. deleteInterface(c, "docker0")
  366. s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:2::/64")
  367. out, err := s.d.Cmd("run", "-itd", "--name=hostcnt", "--network=host", "busybox:latest")
  368. c.Assert(err, checker.IsNil, check.Commentf("Could not run container: %s, %v", out, err))
  369. out, err = s.d.Cmd("exec", "hostcnt", "ip", "-6", "addr", "show", "docker0")
  370. c.Assert(err, checker.IsNil)
  371. c.Assert(strings.Trim(out, " \r\n'"), checker.Contains, "2001:db8:2::1")
  372. }
  373. func (s *DockerDaemonSuite) TestDaemonLogLevelWrong(c *check.C) {
  374. c.Assert(s.d.StartWithError("--log-level=bogus"), check.NotNil, check.Commentf("Daemon shouldn't start with wrong log level"))
  375. }
  376. func (s *DockerDaemonSuite) TestDaemonLogLevelDebug(c *check.C) {
  377. s.d.Start(c, "--log-level=debug")
  378. content, err := s.d.ReadLogFile()
  379. c.Assert(err, checker.IsNil)
  380. if !strings.Contains(string(content), `level=debug`) {
  381. c.Fatalf(`Missing level="debug" in log file:\n%s`, string(content))
  382. }
  383. }
  384. func (s *DockerDaemonSuite) TestDaemonLogLevelFatal(c *check.C) {
  385. // we creating new daemons to create new logFile
  386. s.d.Start(c, "--log-level=fatal")
  387. content, err := s.d.ReadLogFile()
  388. c.Assert(err, checker.IsNil)
  389. if strings.Contains(string(content), `level=debug`) {
  390. c.Fatalf(`Should not have level="debug" in log file:\n%s`, string(content))
  391. }
  392. }
  393. func (s *DockerDaemonSuite) TestDaemonFlagD(c *check.C) {
  394. s.d.Start(c, "-D")
  395. content, err := s.d.ReadLogFile()
  396. c.Assert(err, checker.IsNil)
  397. if !strings.Contains(string(content), `level=debug`) {
  398. c.Fatalf(`Should have level="debug" in log file using -D:\n%s`, string(content))
  399. }
  400. }
  401. func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *check.C) {
  402. s.d.Start(c, "--debug")
  403. content, err := s.d.ReadLogFile()
  404. c.Assert(err, checker.IsNil)
  405. if !strings.Contains(string(content), `level=debug`) {
  406. c.Fatalf(`Should have level="debug" in log file using --debug:\n%s`, string(content))
  407. }
  408. }
  409. func (s *DockerDaemonSuite) TestDaemonFlagDebugLogLevelFatal(c *check.C) {
  410. s.d.Start(c, "--debug", "--log-level=fatal")
  411. content, err := s.d.ReadLogFile()
  412. c.Assert(err, checker.IsNil)
  413. if !strings.Contains(string(content), `level=debug`) {
  414. c.Fatalf(`Should have level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content))
  415. }
  416. }
  417. func (s *DockerDaemonSuite) TestDaemonAllocatesListeningPort(c *check.C) {
  418. listeningPorts := [][]string{
  419. {"0.0.0.0", "0.0.0.0", "5678"},
  420. {"127.0.0.1", "127.0.0.1", "1234"},
  421. {"localhost", "127.0.0.1", "1235"},
  422. }
  423. cmdArgs := make([]string, 0, len(listeningPorts)*2)
  424. for _, hostDirective := range listeningPorts {
  425. cmdArgs = append(cmdArgs, "--host", fmt.Sprintf("tcp://%s:%s", hostDirective[0], hostDirective[2]))
  426. }
  427. s.d.StartWithBusybox(c, cmdArgs...)
  428. for _, hostDirective := range listeningPorts {
  429. output, err := s.d.Cmd("run", "-p", fmt.Sprintf("%s:%s:80", hostDirective[1], hostDirective[2]), "busybox", "true")
  430. if err == nil {
  431. c.Fatalf("Container should not start, expected port already allocated error: %q", output)
  432. } else if !strings.Contains(output, "port is already allocated") {
  433. c.Fatalf("Expected port is already allocated error: %q", output)
  434. }
  435. }
  436. }
  437. func (s *DockerDaemonSuite) TestDaemonKeyGeneration(c *check.C) {
  438. // TODO: skip or update for Windows daemon
  439. os.Remove("/etc/docker/key.json")
  440. s.d.Start(c)
  441. s.d.Stop(c)
  442. k, err := libtrust.LoadKeyFile("/etc/docker/key.json")
  443. if err != nil {
  444. c.Fatalf("Error opening key file")
  445. }
  446. kid := k.KeyID()
  447. // Test Key ID is a valid fingerprint (e.g. QQXN:JY5W:TBXI:MK3X:GX6P:PD5D:F56N:NHCS:LVRZ:JA46:R24J:XEFF)
  448. if len(kid) != 59 {
  449. c.Fatalf("Bad key ID: %s", kid)
  450. }
  451. }
  452. // GH#11320 - verify that the daemon exits on failure properly
  453. // Note that this explicitly tests the conflict of {-b,--bridge} and {--bip} options as the means
  454. // to get a daemon init failure; no other tests for -b/--bip conflict are therefore required
  455. func (s *DockerDaemonSuite) TestDaemonExitOnFailure(c *check.C) {
  456. //attempt to start daemon with incorrect flags (we know -b and --bip conflict)
  457. if err := s.d.StartWithError("--bridge", "nosuchbridge", "--bip", "1.1.1.1"); err != nil {
  458. //verify we got the right error
  459. if !strings.Contains(err.Error(), "Daemon exited") {
  460. c.Fatalf("Expected daemon not to start, got %v", err)
  461. }
  462. // look in the log and make sure we got the message that daemon is shutting down
  463. icmd.RunCommand("grep", "Error starting daemon", s.d.LogFileName()).Assert(c, icmd.Success)
  464. } else {
  465. //if we didn't get an error and the daemon is running, this is a failure
  466. c.Fatal("Conflicting options should cause the daemon to error out with a failure")
  467. }
  468. }
  469. func (s *DockerDaemonSuite) TestDaemonBridgeExternal(c *check.C) {
  470. d := s.d
  471. err := d.StartWithError("--bridge", "nosuchbridge")
  472. c.Assert(err, check.NotNil, check.Commentf("--bridge option with an invalid bridge should cause the daemon to fail"))
  473. defer d.Restart(c)
  474. bridgeName := "external-bridge"
  475. bridgeIP := "192.169.1.1/24"
  476. _, bridgeIPNet, _ := net.ParseCIDR(bridgeIP)
  477. createInterface(c, "bridge", bridgeName, bridgeIP)
  478. defer deleteInterface(c, bridgeName)
  479. d.StartWithBusybox(c, "--bridge", bridgeName)
  480. ipTablesSearchString := bridgeIPNet.String()
  481. icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{
  482. Out: ipTablesSearchString,
  483. })
  484. _, err = d.Cmd("run", "-d", "--name", "ExtContainer", "busybox", "top")
  485. c.Assert(err, check.IsNil)
  486. containerIP := d.FindContainerIP(c, "ExtContainer")
  487. ip := net.ParseIP(containerIP)
  488. c.Assert(bridgeIPNet.Contains(ip), check.Equals, true,
  489. check.Commentf("Container IP-Address must be in the same subnet range : %s",
  490. containerIP))
  491. }
  492. func (s *DockerDaemonSuite) TestDaemonBridgeNone(c *check.C) {
  493. // start with bridge none
  494. d := s.d
  495. d.StartWithBusybox(c, "--bridge", "none")
  496. defer d.Restart(c)
  497. // verify docker0 iface is not there
  498. icmd.RunCommand("ifconfig", "docker0").Assert(c, icmd.Expected{
  499. ExitCode: 1,
  500. Error: "exit status 1",
  501. Err: "Device not found",
  502. })
  503. // verify default "bridge" network is not there
  504. out, err := d.Cmd("network", "inspect", "bridge")
  505. c.Assert(err, check.NotNil, check.Commentf("\"bridge\" network should not be present if daemon started with --bridge=none"))
  506. c.Assert(strings.Contains(out, "No such network"), check.Equals, true)
  507. }
  508. func createInterface(c *check.C, ifType string, ifName string, ipNet string) {
  509. icmd.RunCommand("ip", "link", "add", "name", ifName, "type", ifType).Assert(c, icmd.Success)
  510. icmd.RunCommand("ifconfig", ifName, ipNet, "up").Assert(c, icmd.Success)
  511. }
  512. func deleteInterface(c *check.C, ifName string) {
  513. icmd.RunCommand("ip", "link", "delete", ifName).Assert(c, icmd.Success)
  514. icmd.RunCommand("iptables", "-t", "nat", "--flush").Assert(c, icmd.Success)
  515. icmd.RunCommand("iptables", "--flush").Assert(c, icmd.Success)
  516. }
  517. func (s *DockerDaemonSuite) TestDaemonBridgeIP(c *check.C) {
  518. // TestDaemonBridgeIP Steps
  519. // 1. Delete the existing docker0 Bridge
  520. // 2. Set --bip daemon configuration and start the new Docker Daemon
  521. // 3. Check if the bip config has taken effect using ifconfig and iptables commands
  522. // 4. Launch a Container and make sure the IP-Address is in the expected subnet
  523. // 5. Delete the docker0 Bridge
  524. // 6. Restart the Docker Daemon (via deferred action)
  525. // This Restart takes care of bringing docker0 interface back to auto-assigned IP
  526. defaultNetworkBridge := "docker0"
  527. deleteInterface(c, defaultNetworkBridge)
  528. d := s.d
  529. bridgeIP := "192.169.1.1/24"
  530. ip, bridgeIPNet, _ := net.ParseCIDR(bridgeIP)
  531. d.StartWithBusybox(c, "--bip", bridgeIP)
  532. defer d.Restart(c)
  533. ifconfigSearchString := ip.String()
  534. icmd.RunCommand("ifconfig", defaultNetworkBridge).Assert(c, icmd.Expected{
  535. Out: ifconfigSearchString,
  536. })
  537. ipTablesSearchString := bridgeIPNet.String()
  538. icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{
  539. Out: ipTablesSearchString,
  540. })
  541. _, err := d.Cmd("run", "-d", "--name", "test", "busybox", "top")
  542. c.Assert(err, check.IsNil)
  543. containerIP := d.FindContainerIP(c, "test")
  544. ip = net.ParseIP(containerIP)
  545. c.Assert(bridgeIPNet.Contains(ip), check.Equals, true,
  546. check.Commentf("Container IP-Address must be in the same subnet range : %s",
  547. containerIP))
  548. deleteInterface(c, defaultNetworkBridge)
  549. }
  550. func (s *DockerDaemonSuite) TestDaemonRestartWithBridgeIPChange(c *check.C) {
  551. s.d.Start(c)
  552. defer s.d.Restart(c)
  553. s.d.Stop(c)
  554. // now we will change the docker0's IP and then try starting the daemon
  555. bridgeIP := "192.169.100.1/24"
  556. _, bridgeIPNet, _ := net.ParseCIDR(bridgeIP)
  557. icmd.RunCommand("ifconfig", "docker0", bridgeIP).Assert(c, icmd.Success)
  558. s.d.Start(c, "--bip", bridgeIP)
  559. //check if the iptables contains new bridgeIP MASQUERADE rule
  560. ipTablesSearchString := bridgeIPNet.String()
  561. icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{
  562. Out: ipTablesSearchString,
  563. })
  564. }
  565. func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr(c *check.C) {
  566. d := s.d
  567. bridgeName := "external-bridge"
  568. bridgeIP := "192.169.1.1/24"
  569. createInterface(c, "bridge", bridgeName, bridgeIP)
  570. defer deleteInterface(c, bridgeName)
  571. args := []string{"--bridge", bridgeName, "--fixed-cidr", "192.169.1.0/30"}
  572. d.StartWithBusybox(c, args...)
  573. defer d.Restart(c)
  574. for i := 0; i < 4; i++ {
  575. cName := "Container" + strconv.Itoa(i)
  576. out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
  577. if err != nil {
  578. c.Assert(strings.Contains(out, "no available IPv4 addresses"), check.Equals, true,
  579. check.Commentf("Could not run a Container : %s %s", err.Error(), out))
  580. }
  581. }
  582. }
  583. func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr2(c *check.C) {
  584. d := s.d
  585. bridgeName := "external-bridge"
  586. bridgeIP := "10.2.2.1/16"
  587. createInterface(c, "bridge", bridgeName, bridgeIP)
  588. defer deleteInterface(c, bridgeName)
  589. d.StartWithBusybox(c, "--bip", bridgeIP, "--fixed-cidr", "10.2.2.0/24")
  590. defer s.d.Restart(c)
  591. out, err := d.Cmd("run", "-d", "--name", "bb", "busybox", "top")
  592. c.Assert(err, checker.IsNil, check.Commentf(out))
  593. defer d.Cmd("stop", "bb")
  594. out, err = d.Cmd("exec", "bb", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'")
  595. c.Assert(out, checker.Equals, "10.2.2.0\n")
  596. out, err = d.Cmd("run", "--rm", "busybox", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'")
  597. c.Assert(err, checker.IsNil, check.Commentf(out))
  598. c.Assert(out, checker.Equals, "10.2.2.2\n")
  599. }
  600. func (s *DockerDaemonSuite) TestDaemonBridgeFixedCIDREqualBridgeNetwork(c *check.C) {
  601. d := s.d
  602. bridgeName := "external-bridge"
  603. bridgeIP := "172.27.42.1/16"
  604. createInterface(c, "bridge", bridgeName, bridgeIP)
  605. defer deleteInterface(c, bridgeName)
  606. d.StartWithBusybox(c, "--bridge", bridgeName, "--fixed-cidr", bridgeIP)
  607. defer s.d.Restart(c)
  608. out, err := d.Cmd("run", "-d", "busybox", "top")
  609. c.Assert(err, check.IsNil, check.Commentf(out))
  610. cid1 := strings.TrimSpace(out)
  611. defer d.Cmd("stop", cid1)
  612. }
  613. func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Implicit(c *check.C) {
  614. defaultNetworkBridge := "docker0"
  615. deleteInterface(c, defaultNetworkBridge)
  616. d := s.d
  617. bridgeIP := "192.169.1.1"
  618. bridgeIPNet := fmt.Sprintf("%s/24", bridgeIP)
  619. d.StartWithBusybox(c, "--bip", bridgeIPNet)
  620. defer d.Restart(c)
  621. expectedMessage := fmt.Sprintf("default via %s dev", bridgeIP)
  622. out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0")
  623. c.Assert(err, checker.IsNil)
  624. c.Assert(strings.Contains(out, expectedMessage), check.Equals, true,
  625. check.Commentf("Implicit default gateway should be bridge IP %s, but default route was '%s'",
  626. bridgeIP, strings.TrimSpace(out)))
  627. deleteInterface(c, defaultNetworkBridge)
  628. }
  629. func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Explicit(c *check.C) {
  630. defaultNetworkBridge := "docker0"
  631. deleteInterface(c, defaultNetworkBridge)
  632. d := s.d
  633. bridgeIP := "192.169.1.1"
  634. bridgeIPNet := fmt.Sprintf("%s/24", bridgeIP)
  635. gatewayIP := "192.169.1.254"
  636. d.StartWithBusybox(c, "--bip", bridgeIPNet, "--default-gateway", gatewayIP)
  637. defer d.Restart(c)
  638. expectedMessage := fmt.Sprintf("default via %s dev", gatewayIP)
  639. out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0")
  640. c.Assert(err, checker.IsNil)
  641. c.Assert(strings.Contains(out, expectedMessage), check.Equals, true,
  642. check.Commentf("Explicit default gateway should be %s, but default route was '%s'",
  643. gatewayIP, strings.TrimSpace(out)))
  644. deleteInterface(c, defaultNetworkBridge)
  645. }
  646. func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4ExplicitOutsideContainerSubnet(c *check.C) {
  647. defaultNetworkBridge := "docker0"
  648. deleteInterface(c, defaultNetworkBridge)
  649. // Program a custom default gateway outside of the container subnet, daemon should accept it and start
  650. s.d.StartWithBusybox(c, "--bip", "172.16.0.10/16", "--fixed-cidr", "172.16.1.0/24", "--default-gateway", "172.16.0.254")
  651. deleteInterface(c, defaultNetworkBridge)
  652. s.d.Restart(c)
  653. }
  654. func (s *DockerDaemonSuite) TestDaemonDefaultNetworkInvalidClusterConfig(c *check.C) {
  655. testRequires(c, DaemonIsLinux, SameHostDaemon)
  656. // Start daemon without docker0 bridge
  657. defaultNetworkBridge := "docker0"
  658. deleteInterface(c, defaultNetworkBridge)
  659. discoveryBackend := "consul://consuladdr:consulport/some/path"
  660. s.d.Start(c, fmt.Sprintf("--cluster-store=%s", discoveryBackend))
  661. // Start daemon with docker0 bridge
  662. result := icmd.RunCommand("ifconfig", defaultNetworkBridge)
  663. result.Assert(c, icmd.Success)
  664. s.d.Restart(c, fmt.Sprintf("--cluster-store=%s", discoveryBackend))
  665. }
  666. func (s *DockerDaemonSuite) TestDaemonIP(c *check.C) {
  667. d := s.d
  668. ipStr := "192.170.1.1/24"
  669. ip, _, _ := net.ParseCIDR(ipStr)
  670. args := []string{"--ip", ip.String()}
  671. d.StartWithBusybox(c, args...)
  672. defer d.Restart(c)
  673. out, err := d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top")
  674. c.Assert(err, check.NotNil,
  675. check.Commentf("Running a container must fail with an invalid --ip option"))
  676. c.Assert(strings.Contains(out, "Error starting userland proxy"), check.Equals, true)
  677. ifName := "dummy"
  678. createInterface(c, "dummy", ifName, ipStr)
  679. defer deleteInterface(c, ifName)
  680. _, err = d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top")
  681. c.Assert(err, check.IsNil)
  682. result := icmd.RunCommand("iptables", "-t", "nat", "-nvL")
  683. result.Assert(c, icmd.Success)
  684. regex := fmt.Sprintf("DNAT.*%s.*dpt:8000", ip.String())
  685. matched, _ := regexp.MatchString(regex, result.Combined())
  686. c.Assert(matched, check.Equals, true,
  687. check.Commentf("iptables output should have contained %q, but was %q", regex, result.Combined()))
  688. }
  689. func (s *DockerDaemonSuite) TestDaemonICCPing(c *check.C) {
  690. testRequires(c, bridgeNfIptables)
  691. d := s.d
  692. bridgeName := "external-bridge"
  693. bridgeIP := "192.169.1.1/24"
  694. createInterface(c, "bridge", bridgeName, bridgeIP)
  695. defer deleteInterface(c, bridgeName)
  696. d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false")
  697. defer d.Restart(c)
  698. result := icmd.RunCommand("iptables", "-nvL", "FORWARD")
  699. result.Assert(c, icmd.Success)
  700. regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName)
  701. matched, _ := regexp.MatchString(regex, result.Combined())
  702. c.Assert(matched, check.Equals, true,
  703. check.Commentf("iptables output should have contained %q, but was %q", regex, result.Combined()))
  704. // Pinging another container must fail with --icc=false
  705. pingContainers(c, d, true)
  706. ipStr := "192.171.1.1/24"
  707. ip, _, _ := net.ParseCIDR(ipStr)
  708. ifName := "icc-dummy"
  709. createInterface(c, "dummy", ifName, ipStr)
  710. // But, Pinging external or a Host interface must succeed
  711. pingCmd := fmt.Sprintf("ping -c 1 %s -W 1", ip.String())
  712. runArgs := []string{"run", "--rm", "busybox", "sh", "-c", pingCmd}
  713. _, err := d.Cmd(runArgs...)
  714. c.Assert(err, check.IsNil)
  715. }
  716. func (s *DockerDaemonSuite) TestDaemonICCLinkExpose(c *check.C) {
  717. d := s.d
  718. bridgeName := "external-bridge"
  719. bridgeIP := "192.169.1.1/24"
  720. createInterface(c, "bridge", bridgeName, bridgeIP)
  721. defer deleteInterface(c, bridgeName)
  722. d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false")
  723. defer d.Restart(c)
  724. result := icmd.RunCommand("iptables", "-nvL", "FORWARD")
  725. result.Assert(c, icmd.Success)
  726. regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName)
  727. matched, _ := regexp.MatchString(regex, result.Combined())
  728. c.Assert(matched, check.Equals, true,
  729. check.Commentf("iptables output should have contained %q, but was %q", regex, result.Combined()))
  730. out, err := d.Cmd("run", "-d", "--expose", "4567", "--name", "icc1", "busybox", "nc", "-l", "-p", "4567")
  731. c.Assert(err, check.IsNil, check.Commentf(out))
  732. out, err = d.Cmd("run", "--link", "icc1:icc1", "busybox", "nc", "icc1", "4567")
  733. c.Assert(err, check.IsNil, check.Commentf(out))
  734. }
  735. func (s *DockerDaemonSuite) TestDaemonLinksIpTablesRulesWhenLinkAndUnlink(c *check.C) {
  736. bridgeName := "external-bridge"
  737. bridgeIP := "192.169.1.1/24"
  738. createInterface(c, "bridge", bridgeName, bridgeIP)
  739. defer deleteInterface(c, bridgeName)
  740. s.d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false")
  741. defer s.d.Restart(c)
  742. _, err := s.d.Cmd("run", "-d", "--name", "child", "--publish", "8080:80", "busybox", "top")
  743. c.Assert(err, check.IsNil)
  744. _, err = s.d.Cmd("run", "-d", "--name", "parent", "--link", "child:http", "busybox", "top")
  745. c.Assert(err, check.IsNil)
  746. childIP := s.d.FindContainerIP(c, "child")
  747. parentIP := s.d.FindContainerIP(c, "parent")
  748. sourceRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", childIP, "--sport", "80", "-d", parentIP, "-j", "ACCEPT"}
  749. destinationRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", parentIP, "--dport", "80", "-d", childIP, "-j", "ACCEPT"}
  750. if !iptables.Exists("filter", "DOCKER", sourceRule...) || !iptables.Exists("filter", "DOCKER", destinationRule...) {
  751. c.Fatal("Iptables rules not found")
  752. }
  753. s.d.Cmd("rm", "--link", "parent/http")
  754. if iptables.Exists("filter", "DOCKER", sourceRule...) || iptables.Exists("filter", "DOCKER", destinationRule...) {
  755. c.Fatal("Iptables rules should be removed when unlink")
  756. }
  757. s.d.Cmd("kill", "child")
  758. s.d.Cmd("kill", "parent")
  759. }
  760. func (s *DockerDaemonSuite) TestDaemonUlimitDefaults(c *check.C) {
  761. testRequires(c, DaemonIsLinux)
  762. s.d.StartWithBusybox(c, "--default-ulimit", "nofile=42:42", "--default-ulimit", "nproc=1024:1024")
  763. out, err := s.d.Cmd("run", "--ulimit", "nproc=2048", "--name=test", "busybox", "/bin/sh", "-c", "echo $(ulimit -n); echo $(ulimit -p)")
  764. if err != nil {
  765. c.Fatal(out, err)
  766. }
  767. outArr := strings.Split(out, "\n")
  768. if len(outArr) < 2 {
  769. c.Fatalf("got unexpected output: %s", out)
  770. }
  771. nofile := strings.TrimSpace(outArr[0])
  772. nproc := strings.TrimSpace(outArr[1])
  773. if nofile != "42" {
  774. c.Fatalf("expected `ulimit -n` to be `42`, got: %s", nofile)
  775. }
  776. if nproc != "2048" {
  777. c.Fatalf("expected `ulimit -p` to be 2048, got: %s", nproc)
  778. }
  779. // Now restart daemon with a new default
  780. s.d.Restart(c, "--default-ulimit", "nofile=43")
  781. out, err = s.d.Cmd("start", "-a", "test")
  782. if err != nil {
  783. c.Fatal(err)
  784. }
  785. outArr = strings.Split(out, "\n")
  786. if len(outArr) < 2 {
  787. c.Fatalf("got unexpected output: %s", out)
  788. }
  789. nofile = strings.TrimSpace(outArr[0])
  790. nproc = strings.TrimSpace(outArr[1])
  791. if nofile != "43" {
  792. c.Fatalf("expected `ulimit -n` to be `43`, got: %s", nofile)
  793. }
  794. if nproc != "2048" {
  795. c.Fatalf("expected `ulimit -p` to be 2048, got: %s", nproc)
  796. }
  797. }
  798. // #11315
  799. func (s *DockerDaemonSuite) TestDaemonRestartRenameContainer(c *check.C) {
  800. s.d.StartWithBusybox(c)
  801. if out, err := s.d.Cmd("run", "--name=test", "busybox"); err != nil {
  802. c.Fatal(err, out)
  803. }
  804. if out, err := s.d.Cmd("rename", "test", "test2"); err != nil {
  805. c.Fatal(err, out)
  806. }
  807. s.d.Restart(c)
  808. if out, err := s.d.Cmd("start", "test2"); err != nil {
  809. c.Fatal(err, out)
  810. }
  811. }
  812. func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefault(c *check.C) {
  813. s.d.StartWithBusybox(c)
  814. out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline")
  815. c.Assert(err, check.IsNil, check.Commentf(out))
  816. id, err := s.d.GetIDByName("test")
  817. c.Assert(err, check.IsNil)
  818. logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log")
  819. if _, err := os.Stat(logPath); err != nil {
  820. c.Fatal(err)
  821. }
  822. f, err := os.Open(logPath)
  823. if err != nil {
  824. c.Fatal(err)
  825. }
  826. defer f.Close()
  827. var res struct {
  828. Log string `json:"log"`
  829. Stream string `json:"stream"`
  830. Time time.Time `json:"time"`
  831. }
  832. if err := json.NewDecoder(f).Decode(&res); err != nil {
  833. c.Fatal(err)
  834. }
  835. if res.Log != "testline\n" {
  836. c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n")
  837. }
  838. if res.Stream != "stdout" {
  839. c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout")
  840. }
  841. if !time.Now().After(res.Time) {
  842. c.Fatalf("Log time %v in future", res.Time)
  843. }
  844. }
  845. func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefaultOverride(c *check.C) {
  846. s.d.StartWithBusybox(c)
  847. out, err := s.d.Cmd("run", "--name=test", "--log-driver=none", "busybox", "echo", "testline")
  848. if err != nil {
  849. c.Fatal(out, err)
  850. }
  851. id, err := s.d.GetIDByName("test")
  852. c.Assert(err, check.IsNil)
  853. logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log")
  854. if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) {
  855. c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err)
  856. }
  857. }
  858. func (s *DockerDaemonSuite) TestDaemonLoggingDriverNone(c *check.C) {
  859. s.d.StartWithBusybox(c, "--log-driver=none")
  860. out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline")
  861. if err != nil {
  862. c.Fatal(out, err)
  863. }
  864. id, err := s.d.GetIDByName("test")
  865. c.Assert(err, check.IsNil)
  866. logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log")
  867. if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) {
  868. c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err)
  869. }
  870. }
  871. func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) {
  872. s.d.StartWithBusybox(c, "--log-driver=none")
  873. out, err := s.d.Cmd("run", "--name=test", "--log-driver=json-file", "busybox", "echo", "testline")
  874. if err != nil {
  875. c.Fatal(out, err)
  876. }
  877. id, err := s.d.GetIDByName("test")
  878. c.Assert(err, check.IsNil)
  879. logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log")
  880. if _, err := os.Stat(logPath); err != nil {
  881. c.Fatal(err)
  882. }
  883. f, err := os.Open(logPath)
  884. if err != nil {
  885. c.Fatal(err)
  886. }
  887. defer f.Close()
  888. var res struct {
  889. Log string `json:"log"`
  890. Stream string `json:"stream"`
  891. Time time.Time `json:"time"`
  892. }
  893. if err := json.NewDecoder(f).Decode(&res); err != nil {
  894. c.Fatal(err)
  895. }
  896. if res.Log != "testline\n" {
  897. c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n")
  898. }
  899. if res.Stream != "stdout" {
  900. c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout")
  901. }
  902. if !time.Now().After(res.Time) {
  903. c.Fatalf("Log time %v in future", res.Time)
  904. }
  905. }
  906. func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) {
  907. s.d.StartWithBusybox(c, "--log-driver=none")
  908. out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline")
  909. c.Assert(err, checker.IsNil, check.Commentf(out))
  910. out, err = s.d.Cmd("logs", "test")
  911. c.Assert(err, check.NotNil, check.Commentf("Logs should fail with 'none' driver"))
  912. expected := `configured logging driver does not support reading`
  913. c.Assert(out, checker.Contains, expected)
  914. }
  915. func (s *DockerDaemonSuite) TestDaemonLoggingDriverShouldBeIgnoredForBuild(c *check.C) {
  916. s.d.StartWithBusybox(c, "--log-driver=splunk")
  917. out, err := s.d.Cmd("build")
  918. out, code, err := s.d.BuildImageWithOut("busyboxs", `
  919. FROM busybox
  920. RUN echo foo`, false)
  921. comment := check.Commentf("Failed to build image. output %s, exitCode %d, err %v", out, code, err)
  922. c.Assert(err, check.IsNil, comment)
  923. c.Assert(code, check.Equals, 0, comment)
  924. c.Assert(out, checker.Contains, "foo", comment)
  925. }
  926. func (s *DockerDaemonSuite) TestDaemonUnixSockCleanedUp(c *check.C) {
  927. dir, err := ioutil.TempDir("", "socket-cleanup-test")
  928. if err != nil {
  929. c.Fatal(err)
  930. }
  931. defer os.RemoveAll(dir)
  932. sockPath := filepath.Join(dir, "docker.sock")
  933. s.d.Start(c, "--host", "unix://"+sockPath)
  934. if _, err := os.Stat(sockPath); err != nil {
  935. c.Fatal("socket does not exist")
  936. }
  937. s.d.Stop(c)
  938. if _, err := os.Stat(sockPath); err == nil || !os.IsNotExist(err) {
  939. c.Fatal("unix socket is not cleaned up")
  940. }
  941. }
  942. func (s *DockerDaemonSuite) TestDaemonWithWrongkey(c *check.C) {
  943. type Config struct {
  944. Crv string `json:"crv"`
  945. D string `json:"d"`
  946. Kid string `json:"kid"`
  947. Kty string `json:"kty"`
  948. X string `json:"x"`
  949. Y string `json:"y"`
  950. }
  951. os.Remove("/etc/docker/key.json")
  952. s.d.Start(c)
  953. s.d.Stop(c)
  954. config := &Config{}
  955. bytes, err := ioutil.ReadFile("/etc/docker/key.json")
  956. if err != nil {
  957. c.Fatalf("Error reading key.json file: %s", err)
  958. }
  959. // byte[] to Data-Struct
  960. if err := json.Unmarshal(bytes, &config); err != nil {
  961. c.Fatalf("Error Unmarshal: %s", err)
  962. }
  963. //replace config.Kid with the fake value
  964. config.Kid = "VSAJ:FUYR:X3H2:B2VZ:KZ6U:CJD5:K7BX:ZXHY:UZXT:P4FT:MJWG:HRJ4"
  965. // NEW Data-Struct to byte[]
  966. newBytes, err := json.Marshal(&config)
  967. if err != nil {
  968. c.Fatalf("Error Marshal: %s", err)
  969. }
  970. // write back
  971. if err := ioutil.WriteFile("/etc/docker/key.json", newBytes, 0400); err != nil {
  972. c.Fatalf("Error ioutil.WriteFile: %s", err)
  973. }
  974. defer os.Remove("/etc/docker/key.json")
  975. if err := s.d.StartWithError(); err == nil {
  976. c.Fatalf("It should not be successful to start daemon with wrong key: %v", err)
  977. }
  978. content, err := s.d.ReadLogFile()
  979. c.Assert(err, checker.IsNil)
  980. if !strings.Contains(string(content), "Public Key ID does not match") {
  981. c.Fatalf("Missing KeyID message from daemon logs: %s", string(content))
  982. }
  983. }
  984. func (s *DockerDaemonSuite) TestDaemonRestartKillWait(c *check.C) {
  985. s.d.StartWithBusybox(c)
  986. out, err := s.d.Cmd("run", "-id", "busybox", "/bin/cat")
  987. if err != nil {
  988. c.Fatalf("Could not run /bin/cat: err=%v\n%s", err, out)
  989. }
  990. containerID := strings.TrimSpace(out)
  991. if out, err := s.d.Cmd("kill", containerID); err != nil {
  992. c.Fatalf("Could not kill %s: err=%v\n%s", containerID, err, out)
  993. }
  994. s.d.Restart(c)
  995. errchan := make(chan error)
  996. go func() {
  997. if out, err := s.d.Cmd("wait", containerID); err != nil {
  998. errchan <- fmt.Errorf("%v:\n%s", err, out)
  999. }
  1000. close(errchan)
  1001. }()
  1002. select {
  1003. case <-time.After(5 * time.Second):
  1004. c.Fatal("Waiting on a stopped (killed) container timed out")
  1005. case err := <-errchan:
  1006. if err != nil {
  1007. c.Fatal(err)
  1008. }
  1009. }
  1010. }
  1011. // TestHTTPSInfo connects via two-way authenticated HTTPS to the info endpoint
  1012. func (s *DockerDaemonSuite) TestHTTPSInfo(c *check.C) {
  1013. const (
  1014. testDaemonHTTPSAddr = "tcp://localhost:4271"
  1015. )
  1016. s.d.Start(c,
  1017. "--tlsverify",
  1018. "--tlscacert", "fixtures/https/ca.pem",
  1019. "--tlscert", "fixtures/https/server-cert.pem",
  1020. "--tlskey", "fixtures/https/server-key.pem",
  1021. "-H", testDaemonHTTPSAddr)
  1022. args := []string{
  1023. "--host", testDaemonHTTPSAddr,
  1024. "--tlsverify",
  1025. "--tlscacert", "fixtures/https/ca.pem",
  1026. "--tlscert", "fixtures/https/client-cert.pem",
  1027. "--tlskey", "fixtures/https/client-key.pem",
  1028. "info",
  1029. }
  1030. out, err := s.d.Cmd(args...)
  1031. if err != nil {
  1032. c.Fatalf("Error Occurred: %s and output: %s", err, out)
  1033. }
  1034. }
  1035. // TestHTTPSRun connects via two-way authenticated HTTPS to the create, attach, start, and wait endpoints.
  1036. // https://github.com/docker/docker/issues/19280
  1037. func (s *DockerDaemonSuite) TestHTTPSRun(c *check.C) {
  1038. const (
  1039. testDaemonHTTPSAddr = "tcp://localhost:4271"
  1040. )
  1041. s.d.StartWithBusybox(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  1042. "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr)
  1043. args := []string{
  1044. "--host", testDaemonHTTPSAddr,
  1045. "--tlsverify", "--tlscacert", "fixtures/https/ca.pem",
  1046. "--tlscert", "fixtures/https/client-cert.pem",
  1047. "--tlskey", "fixtures/https/client-key.pem",
  1048. "run", "busybox", "echo", "TLS response",
  1049. }
  1050. out, err := s.d.Cmd(args...)
  1051. if err != nil {
  1052. c.Fatalf("Error Occurred: %s and output: %s", err, out)
  1053. }
  1054. if !strings.Contains(out, "TLS response") {
  1055. c.Fatalf("expected output to include `TLS response`, got %v", out)
  1056. }
  1057. }
  1058. // TestTLSVerify verifies that --tlsverify=false turns on tls
  1059. func (s *DockerDaemonSuite) TestTLSVerify(c *check.C) {
  1060. out, err := exec.Command(dockerdBinary, "--tlsverify=false").CombinedOutput()
  1061. if err == nil || !strings.Contains(string(out), "Could not load X509 key pair") {
  1062. c.Fatalf("Daemon should not have started due to missing certs: %v\n%s", err, string(out))
  1063. }
  1064. }
  1065. // TestHTTPSInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint
  1066. // by using a rogue client certificate and checks that it fails with the expected error.
  1067. func (s *DockerDaemonSuite) TestHTTPSInfoRogueCert(c *check.C) {
  1068. const (
  1069. errBadCertificate = "bad certificate"
  1070. testDaemonHTTPSAddr = "tcp://localhost:4271"
  1071. )
  1072. s.d.Start(c,
  1073. "--tlsverify",
  1074. "--tlscacert", "fixtures/https/ca.pem",
  1075. "--tlscert", "fixtures/https/server-cert.pem",
  1076. "--tlskey", "fixtures/https/server-key.pem",
  1077. "-H", testDaemonHTTPSAddr)
  1078. args := []string{
  1079. "--host", testDaemonHTTPSAddr,
  1080. "--tlsverify",
  1081. "--tlscacert", "fixtures/https/ca.pem",
  1082. "--tlscert", "fixtures/https/client-rogue-cert.pem",
  1083. "--tlskey", "fixtures/https/client-rogue-key.pem",
  1084. "info",
  1085. }
  1086. out, err := s.d.Cmd(args...)
  1087. if err == nil || !strings.Contains(out, errBadCertificate) {
  1088. c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out)
  1089. }
  1090. }
  1091. // TestHTTPSInfoRogueServerCert connects via two-way authenticated HTTPS to the info endpoint
  1092. // which provides a rogue server certificate and checks that it fails with the expected error
  1093. func (s *DockerDaemonSuite) TestHTTPSInfoRogueServerCert(c *check.C) {
  1094. const (
  1095. errCaUnknown = "x509: certificate signed by unknown authority"
  1096. testDaemonRogueHTTPSAddr = "tcp://localhost:4272"
  1097. )
  1098. s.d.Start(c,
  1099. "--tlsverify",
  1100. "--tlscacert", "fixtures/https/ca.pem",
  1101. "--tlscert", "fixtures/https/server-rogue-cert.pem",
  1102. "--tlskey", "fixtures/https/server-rogue-key.pem",
  1103. "-H", testDaemonRogueHTTPSAddr)
  1104. args := []string{
  1105. "--host", testDaemonRogueHTTPSAddr,
  1106. "--tlsverify",
  1107. "--tlscacert", "fixtures/https/ca.pem",
  1108. "--tlscert", "fixtures/https/client-rogue-cert.pem",
  1109. "--tlskey", "fixtures/https/client-rogue-key.pem",
  1110. "info",
  1111. }
  1112. out, err := s.d.Cmd(args...)
  1113. if err == nil || !strings.Contains(out, errCaUnknown) {
  1114. c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out)
  1115. }
  1116. }
  1117. func pingContainers(c *check.C, d *daemon.Daemon, expectFailure bool) {
  1118. var dargs []string
  1119. if d != nil {
  1120. dargs = []string{"--host", d.Sock()}
  1121. }
  1122. args := append(dargs, "run", "-d", "--name", "container1", "busybox", "top")
  1123. dockerCmd(c, args...)
  1124. args = append(dargs, "run", "--rm", "--link", "container1:alias1", "busybox", "sh", "-c")
  1125. pingCmd := "ping -c 1 %s -W 1"
  1126. args = append(args, fmt.Sprintf(pingCmd, "alias1"))
  1127. _, _, err := dockerCmdWithError(args...)
  1128. if expectFailure {
  1129. c.Assert(err, check.NotNil)
  1130. } else {
  1131. c.Assert(err, check.IsNil)
  1132. }
  1133. args = append(dargs, "rm", "-f", "container1")
  1134. dockerCmd(c, args...)
  1135. }
  1136. func (s *DockerDaemonSuite) TestDaemonRestartWithSocketAsVolume(c *check.C) {
  1137. s.d.StartWithBusybox(c)
  1138. socket := filepath.Join(s.d.Folder, "docker.sock")
  1139. out, err := s.d.Cmd("run", "--restart=always", "-v", socket+":/sock", "busybox")
  1140. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1141. s.d.Restart(c)
  1142. }
  1143. // os.Kill should kill daemon ungracefully, leaving behind container mounts.
  1144. // A subsequent daemon restart should clean up said mounts.
  1145. func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonAndContainerKill(c *check.C) {
  1146. d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
  1147. d.StartWithBusybox(c)
  1148. out, err := d.Cmd("run", "-d", "busybox", "top")
  1149. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1150. id := strings.TrimSpace(out)
  1151. // If there are no mounts with container id visible from the host
  1152. // (as those are in container's own mount ns), there is nothing
  1153. // to check here and the test should be skipped.
  1154. mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1155. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1156. if !strings.Contains(string(mountOut), id) {
  1157. d.Stop(c)
  1158. c.Skip("no container mounts visible in host ns")
  1159. }
  1160. // kill the daemon
  1161. c.Assert(d.Kill(), check.IsNil)
  1162. // kill the container
  1163. icmd.RunCommand(ctrBinary, "--address", "/var/run/docker/containerd/docker-containerd.sock",
  1164. "--namespace", moby_daemon.ContainersNamespace, "tasks", "kill", id).Assert(c, icmd.Success)
  1165. // restart daemon.
  1166. d.Restart(c)
  1167. // Now, container mounts should be gone.
  1168. mountOut, err = ioutil.ReadFile("/proc/self/mountinfo")
  1169. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1170. comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut)
  1171. c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1172. d.Stop(c)
  1173. }
  1174. // os.Interrupt should perform a graceful daemon shutdown and hence cleanup mounts.
  1175. func (s *DockerDaemonSuite) TestCleanupMountsAfterGracefulShutdown(c *check.C) {
  1176. d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
  1177. d.StartWithBusybox(c)
  1178. out, err := d.Cmd("run", "-d", "busybox", "top")
  1179. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1180. id := strings.TrimSpace(out)
  1181. // Send SIGINT and daemon should clean up
  1182. c.Assert(d.Signal(os.Interrupt), check.IsNil)
  1183. // Wait for the daemon to stop.
  1184. c.Assert(<-d.Wait, checker.IsNil)
  1185. mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1186. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1187. comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut)
  1188. c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1189. }
  1190. func (s *DockerDaemonSuite) TestRunContainerWithBridgeNone(c *check.C) {
  1191. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1192. s.d.StartWithBusybox(c, "-b", "none")
  1193. out, err := s.d.Cmd("run", "--rm", "busybox", "ip", "l")
  1194. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1195. c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1196. check.Commentf("There shouldn't be eth0 in container in default(bridge) mode when bridge network is disabled: %s", out))
  1197. out, err = s.d.Cmd("run", "--rm", "--net=bridge", "busybox", "ip", "l")
  1198. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1199. c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1200. check.Commentf("There shouldn't be eth0 in container in bridge mode when bridge network is disabled: %s", out))
  1201. // the extra grep and awk clean up the output of `ip` to only list the number and name of
  1202. // interfaces, allowing for different versions of ip (e.g. inside and outside the container) to
  1203. // be used while still verifying that the interface list is the exact same
  1204. cmd := exec.Command("sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '")
  1205. stdout := bytes.NewBuffer(nil)
  1206. cmd.Stdout = stdout
  1207. if err := cmd.Run(); err != nil {
  1208. c.Fatal("Failed to get host network interface")
  1209. }
  1210. out, err = s.d.Cmd("run", "--rm", "--net=host", "busybox", "sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '")
  1211. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1212. c.Assert(out, check.Equals, fmt.Sprintf("%s", stdout),
  1213. check.Commentf("The network interfaces in container should be the same with host when --net=host when bridge network is disabled: %s", out))
  1214. }
  1215. func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *check.C) {
  1216. s.d.StartWithBusybox(t)
  1217. if out, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top"); err != nil {
  1218. t.Fatal(out, err)
  1219. }
  1220. s.d.Restart(t)
  1221. // Container 'test' should be removed without error
  1222. if out, err := s.d.Cmd("rm", "test"); err != nil {
  1223. t.Fatal(out, err)
  1224. }
  1225. }
  1226. func (s *DockerDaemonSuite) TestDaemonRestartCleanupNetns(c *check.C) {
  1227. s.d.StartWithBusybox(c)
  1228. out, err := s.d.Cmd("run", "--name", "netns", "-d", "busybox", "top")
  1229. if err != nil {
  1230. c.Fatal(out, err)
  1231. }
  1232. // Get sandbox key via inspect
  1233. out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.SandboxKey}}'", "netns")
  1234. if err != nil {
  1235. c.Fatalf("Error inspecting container: %s, %v", out, err)
  1236. }
  1237. fileName := strings.Trim(out, " \r\n'")
  1238. if out, err := s.d.Cmd("stop", "netns"); err != nil {
  1239. c.Fatal(out, err)
  1240. }
  1241. // Test if the file still exists
  1242. icmd.RunCommand("stat", "-c", "%n", fileName).Assert(c, icmd.Expected{
  1243. Out: fileName,
  1244. })
  1245. // Remove the container and restart the daemon
  1246. if out, err := s.d.Cmd("rm", "netns"); err != nil {
  1247. c.Fatal(out, err)
  1248. }
  1249. s.d.Restart(c)
  1250. // Test again and see now the netns file does not exist
  1251. icmd.RunCommand("stat", "-c", "%n", fileName).Assert(c, icmd.Expected{
  1252. Err: "No such file or directory",
  1253. ExitCode: 1,
  1254. })
  1255. }
  1256. // tests regression detailed in #13964 where DOCKER_TLS_VERIFY env is ignored
  1257. func (s *DockerDaemonSuite) TestDaemonTLSVerifyIssue13964(c *check.C) {
  1258. host := "tcp://localhost:4271"
  1259. s.d.Start(c, "-H", host)
  1260. icmd.RunCmd(icmd.Cmd{
  1261. Command: []string{dockerBinary, "-H", host, "info"},
  1262. Env: []string{"DOCKER_TLS_VERIFY=1", "DOCKER_CERT_PATH=fixtures/https"},
  1263. }).Assert(c, icmd.Expected{
  1264. ExitCode: 1,
  1265. Err: "error during connect",
  1266. })
  1267. }
  1268. func setupV6(c *check.C) {
  1269. // Hack to get the right IPv6 address on docker0, which has already been created
  1270. result := icmd.RunCommand("ip", "addr", "add", "fe80::1/64", "dev", "docker0")
  1271. result.Assert(c, icmd.Success)
  1272. }
  1273. func teardownV6(c *check.C) {
  1274. result := icmd.RunCommand("ip", "addr", "del", "fe80::1/64", "dev", "docker0")
  1275. result.Assert(c, icmd.Success)
  1276. }
  1277. func (s *DockerDaemonSuite) TestDaemonRestartWithContainerWithRestartPolicyAlways(c *check.C) {
  1278. s.d.StartWithBusybox(c)
  1279. out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top")
  1280. c.Assert(err, check.IsNil)
  1281. id := strings.TrimSpace(out)
  1282. _, err = s.d.Cmd("stop", id)
  1283. c.Assert(err, check.IsNil)
  1284. _, err = s.d.Cmd("wait", id)
  1285. c.Assert(err, check.IsNil)
  1286. out, err = s.d.Cmd("ps", "-q")
  1287. c.Assert(err, check.IsNil)
  1288. c.Assert(out, check.Equals, "")
  1289. s.d.Restart(c)
  1290. out, err = s.d.Cmd("ps", "-q")
  1291. c.Assert(err, check.IsNil)
  1292. c.Assert(strings.TrimSpace(out), check.Equals, id[:12])
  1293. }
  1294. func (s *DockerDaemonSuite) TestDaemonWideLogConfig(c *check.C) {
  1295. s.d.StartWithBusybox(c, "--log-opt=max-size=1k")
  1296. name := "logtest"
  1297. out, err := s.d.Cmd("run", "-d", "--log-opt=max-file=5", "--name", name, "busybox", "top")
  1298. c.Assert(err, check.IsNil, check.Commentf("Output: %s, err: %v", out, err))
  1299. out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Config }}", name)
  1300. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1301. c.Assert(out, checker.Contains, "max-size:1k")
  1302. c.Assert(out, checker.Contains, "max-file:5")
  1303. out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Type }}", name)
  1304. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1305. c.Assert(strings.TrimSpace(out), checker.Equals, "json-file")
  1306. }
  1307. func (s *DockerDaemonSuite) TestDaemonRestartWithPausedContainer(c *check.C) {
  1308. s.d.StartWithBusybox(c)
  1309. if out, err := s.d.Cmd("run", "-i", "-d", "--name", "test", "busybox", "top"); err != nil {
  1310. c.Fatal(err, out)
  1311. }
  1312. if out, err := s.d.Cmd("pause", "test"); err != nil {
  1313. c.Fatal(err, out)
  1314. }
  1315. s.d.Restart(c)
  1316. errchan := make(chan error)
  1317. go func() {
  1318. out, err := s.d.Cmd("start", "test")
  1319. if err != nil {
  1320. errchan <- fmt.Errorf("%v:\n%s", err, out)
  1321. }
  1322. name := strings.TrimSpace(out)
  1323. if name != "test" {
  1324. errchan <- fmt.Errorf("Paused container start error on docker daemon restart, expected 'test' but got '%s'", name)
  1325. }
  1326. close(errchan)
  1327. }()
  1328. select {
  1329. case <-time.After(5 * time.Second):
  1330. c.Fatal("Waiting on start a container timed out")
  1331. case err := <-errchan:
  1332. if err != nil {
  1333. c.Fatal(err)
  1334. }
  1335. }
  1336. }
  1337. func (s *DockerDaemonSuite) TestDaemonRestartRmVolumeInUse(c *check.C) {
  1338. s.d.StartWithBusybox(c)
  1339. out, err := s.d.Cmd("create", "-v", "test:/foo", "busybox")
  1340. c.Assert(err, check.IsNil, check.Commentf(out))
  1341. s.d.Restart(c)
  1342. out, err = s.d.Cmd("volume", "rm", "test")
  1343. c.Assert(err, check.NotNil, check.Commentf("should not be able to remove in use volume after daemon restart"))
  1344. c.Assert(out, checker.Contains, "in use")
  1345. }
  1346. func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *check.C) {
  1347. s.d.Start(c)
  1348. _, err := s.d.Cmd("volume", "create", "test")
  1349. c.Assert(err, check.IsNil)
  1350. s.d.Restart(c)
  1351. _, err = s.d.Cmd("volume", "inspect", "test")
  1352. c.Assert(err, check.IsNil)
  1353. }
  1354. // FIXME(vdemeester) should be a unit test
  1355. func (s *DockerDaemonSuite) TestDaemonCorruptedLogDriverAddress(c *check.C) {
  1356. d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
  1357. c.Assert(d.StartWithError("--log-driver=syslog", "--log-opt", "syslog-address=corrupted:42"), check.NotNil)
  1358. expected := "syslog-address should be in form proto://address"
  1359. icmd.RunCommand("grep", expected, d.LogFileName()).Assert(c, icmd.Success)
  1360. }
  1361. // FIXME(vdemeester) should be a unit test
  1362. func (s *DockerDaemonSuite) TestDaemonCorruptedFluentdAddress(c *check.C) {
  1363. d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
  1364. c.Assert(d.StartWithError("--log-driver=fluentd", "--log-opt", "fluentd-address=corrupted:c"), check.NotNil)
  1365. expected := "invalid fluentd-address corrupted:c: "
  1366. icmd.RunCommand("grep", expected, d.LogFileName()).Assert(c, icmd.Success)
  1367. }
  1368. // FIXME(vdemeester) Use a new daemon instance instead of the Suite one
  1369. func (s *DockerDaemonSuite) TestDaemonStartWithoutHost(c *check.C) {
  1370. s.d.UseDefaultHost = true
  1371. defer func() {
  1372. s.d.UseDefaultHost = false
  1373. }()
  1374. s.d.Start(c)
  1375. }
  1376. // FIXME(vdemeester) Use a new daemon instance instead of the Suite one
  1377. func (s *DockerDaemonSuite) TestDaemonStartWithDefaultTLSHost(c *check.C) {
  1378. s.d.UseDefaultTLSHost = true
  1379. defer func() {
  1380. s.d.UseDefaultTLSHost = false
  1381. }()
  1382. s.d.Start(c,
  1383. "--tlsverify",
  1384. "--tlscacert", "fixtures/https/ca.pem",
  1385. "--tlscert", "fixtures/https/server-cert.pem",
  1386. "--tlskey", "fixtures/https/server-key.pem")
  1387. // The client with --tlsverify should also use default host localhost:2376
  1388. tmpHost := os.Getenv("DOCKER_HOST")
  1389. defer func() {
  1390. os.Setenv("DOCKER_HOST", tmpHost)
  1391. }()
  1392. os.Setenv("DOCKER_HOST", "")
  1393. out, _ := dockerCmd(
  1394. c,
  1395. "--tlsverify",
  1396. "--tlscacert", "fixtures/https/ca.pem",
  1397. "--tlscert", "fixtures/https/client-cert.pem",
  1398. "--tlskey", "fixtures/https/client-key.pem",
  1399. "version",
  1400. )
  1401. if !strings.Contains(out, "Server") {
  1402. c.Fatalf("docker version should return information of server side")
  1403. }
  1404. // ensure when connecting to the server that only a single acceptable CA is requested
  1405. contents, err := ioutil.ReadFile("fixtures/https/ca.pem")
  1406. c.Assert(err, checker.IsNil)
  1407. rootCert, err := helpers.ParseCertificatePEM(contents)
  1408. c.Assert(err, checker.IsNil)
  1409. rootPool := x509.NewCertPool()
  1410. rootPool.AddCert(rootCert)
  1411. var certRequestInfo *tls.CertificateRequestInfo
  1412. conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", opts.DefaultHTTPHost, opts.DefaultTLSHTTPPort), &tls.Config{
  1413. RootCAs: rootPool,
  1414. GetClientCertificate: func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
  1415. certRequestInfo = cri
  1416. cert, err := tls.LoadX509KeyPair("fixtures/https/client-cert.pem", "fixtures/https/client-key.pem")
  1417. if err != nil {
  1418. return nil, err
  1419. }
  1420. return &cert, nil
  1421. },
  1422. })
  1423. c.Assert(err, checker.IsNil)
  1424. conn.Close()
  1425. c.Assert(certRequestInfo, checker.NotNil)
  1426. c.Assert(certRequestInfo.AcceptableCAs, checker.HasLen, 1)
  1427. c.Assert(certRequestInfo.AcceptableCAs[0], checker.DeepEquals, rootCert.RawSubject)
  1428. }
  1429. func (s *DockerDaemonSuite) TestBridgeIPIsExcludedFromAllocatorPool(c *check.C) {
  1430. defaultNetworkBridge := "docker0"
  1431. deleteInterface(c, defaultNetworkBridge)
  1432. bridgeIP := "192.169.1.1"
  1433. bridgeRange := bridgeIP + "/30"
  1434. s.d.StartWithBusybox(c, "--bip", bridgeRange)
  1435. defer s.d.Restart(c)
  1436. var cont int
  1437. for {
  1438. contName := fmt.Sprintf("container%d", cont)
  1439. _, err := s.d.Cmd("run", "--name", contName, "-d", "busybox", "/bin/sleep", "2")
  1440. if err != nil {
  1441. // pool exhausted
  1442. break
  1443. }
  1444. ip, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.IPAddress}}'", contName)
  1445. c.Assert(err, check.IsNil)
  1446. c.Assert(ip, check.Not(check.Equals), bridgeIP)
  1447. cont++
  1448. }
  1449. }
  1450. // Test daemon for no space left on device error
  1451. func (s *DockerDaemonSuite) TestDaemonNoSpaceLeftOnDeviceError(c *check.C) {
  1452. testRequires(c, SameHostDaemon, DaemonIsLinux, Network)
  1453. testDir, err := ioutil.TempDir("", "no-space-left-on-device-test")
  1454. c.Assert(err, checker.IsNil)
  1455. defer os.RemoveAll(testDir)
  1456. c.Assert(mount.MakeRShared(testDir), checker.IsNil)
  1457. defer mount.Unmount(testDir)
  1458. // create a 2MiB image and mount it as graph root
  1459. // Why in a container? Because `mount` sometimes behaves weirdly and often fails outright on this test in debian:jessie (which is what the test suite runs under if run from the Makefile)
  1460. dockerCmd(c, "run", "--rm", "-v", testDir+":/test", "busybox", "sh", "-c", "dd of=/test/testfs.img bs=1M seek=3 count=0")
  1461. icmd.RunCommand("mkfs.ext4", "-F", filepath.Join(testDir, "testfs.img")).Assert(c, icmd.Success)
  1462. result := icmd.RunCommand("losetup", "-f", "--show", filepath.Join(testDir, "testfs.img"))
  1463. result.Assert(c, icmd.Success)
  1464. loopname := strings.TrimSpace(string(result.Combined()))
  1465. defer exec.Command("losetup", "-d", loopname).Run()
  1466. dockerCmd(c, "run", "--privileged", "--rm", "-v", testDir+":/test:shared", "busybox", "sh", "-c", fmt.Sprintf("mkdir -p /test/test-mount && mount -t ext4 -no loop,rw %v /test/test-mount", loopname))
  1467. defer mount.Unmount(filepath.Join(testDir, "test-mount"))
  1468. s.d.Start(c, "--data-root", filepath.Join(testDir, "test-mount"))
  1469. defer s.d.Stop(c)
  1470. // pull a repository large enough to fill the mount point
  1471. pullOut, err := s.d.Cmd("pull", "debian:stretch")
  1472. c.Assert(err, checker.NotNil, check.Commentf(pullOut))
  1473. c.Assert(pullOut, checker.Contains, "no space left on device")
  1474. }
  1475. // Test daemon restart with container links + auto restart
  1476. func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) {
  1477. s.d.StartWithBusybox(c)
  1478. parent1Args := []string{}
  1479. parent2Args := []string{}
  1480. wg := sync.WaitGroup{}
  1481. maxChildren := 10
  1482. chErr := make(chan error, maxChildren)
  1483. for i := 0; i < maxChildren; i++ {
  1484. wg.Add(1)
  1485. name := fmt.Sprintf("test%d", i)
  1486. if i < maxChildren/2 {
  1487. parent1Args = append(parent1Args, []string{"--link", name}...)
  1488. } else {
  1489. parent2Args = append(parent2Args, []string{"--link", name}...)
  1490. }
  1491. go func() {
  1492. _, err := s.d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top")
  1493. chErr <- err
  1494. wg.Done()
  1495. }()
  1496. }
  1497. wg.Wait()
  1498. close(chErr)
  1499. for err := range chErr {
  1500. c.Assert(err, check.IsNil)
  1501. }
  1502. parent1Args = append([]string{"run", "-d"}, parent1Args...)
  1503. parent1Args = append(parent1Args, []string{"--name=parent1", "--restart=always", "busybox", "top"}...)
  1504. parent2Args = append([]string{"run", "-d"}, parent2Args...)
  1505. parent2Args = append(parent2Args, []string{"--name=parent2", "--restart=always", "busybox", "top"}...)
  1506. _, err := s.d.Cmd(parent1Args...)
  1507. c.Assert(err, check.IsNil)
  1508. _, err = s.d.Cmd(parent2Args...)
  1509. c.Assert(err, check.IsNil)
  1510. s.d.Stop(c)
  1511. // clear the log file -- we don't need any of it but may for the next part
  1512. // can ignore the error here, this is just a cleanup
  1513. os.Truncate(s.d.LogFileName(), 0)
  1514. s.d.Start(c)
  1515. for _, num := range []string{"1", "2"} {
  1516. out, err := s.d.Cmd("inspect", "-f", "{{ .State.Running }}", "parent"+num)
  1517. c.Assert(err, check.IsNil)
  1518. if strings.TrimSpace(out) != "true" {
  1519. log, _ := ioutil.ReadFile(s.d.LogFileName())
  1520. c.Fatalf("parent container is not running\n%s", string(log))
  1521. }
  1522. }
  1523. }
  1524. func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *check.C) {
  1525. testRequires(c, DaemonIsLinux)
  1526. cgroupParent := "test"
  1527. name := "cgroup-test"
  1528. s.d.StartWithBusybox(c, "--cgroup-parent", cgroupParent)
  1529. defer s.d.Restart(c)
  1530. out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup")
  1531. c.Assert(err, checker.IsNil)
  1532. cgroupPaths := ParseCgroupPaths(string(out))
  1533. c.Assert(len(cgroupPaths), checker.Not(checker.Equals), 0, check.Commentf("unexpected output - %q", string(out)))
  1534. out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name)
  1535. c.Assert(err, checker.IsNil)
  1536. id := strings.TrimSpace(string(out))
  1537. expectedCgroup := path.Join(cgroupParent, id)
  1538. found := false
  1539. for _, path := range cgroupPaths {
  1540. if strings.HasSuffix(path, expectedCgroup) {
  1541. found = true
  1542. break
  1543. }
  1544. }
  1545. c.Assert(found, checker.True, check.Commentf("Cgroup path for container (%s) doesn't found in cgroups file: %s", expectedCgroup, cgroupPaths))
  1546. }
  1547. func (s *DockerDaemonSuite) TestDaemonRestartWithLinks(c *check.C) {
  1548. testRequires(c, DaemonIsLinux) // Windows does not support links
  1549. s.d.StartWithBusybox(c)
  1550. out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1551. c.Assert(err, check.IsNil, check.Commentf(out))
  1552. out, err = s.d.Cmd("run", "--name=test2", "--link", "test:abc", "busybox", "sh", "-c", "ping -c 1 -w 1 abc")
  1553. c.Assert(err, check.IsNil, check.Commentf(out))
  1554. s.d.Restart(c)
  1555. // should fail since test is not running yet
  1556. out, err = s.d.Cmd("start", "test2")
  1557. c.Assert(err, check.NotNil, check.Commentf(out))
  1558. out, err = s.d.Cmd("start", "test")
  1559. c.Assert(err, check.IsNil, check.Commentf(out))
  1560. out, err = s.d.Cmd("start", "-a", "test2")
  1561. c.Assert(err, check.IsNil, check.Commentf(out))
  1562. c.Assert(strings.Contains(out, "1 packets transmitted, 1 packets received"), check.Equals, true, check.Commentf(out))
  1563. }
  1564. func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *check.C) {
  1565. testRequires(c, DaemonIsLinux) // Windows does not support links
  1566. s.d.StartWithBusybox(c)
  1567. out, err := s.d.Cmd("create", "--name=test", "busybox")
  1568. c.Assert(err, check.IsNil, check.Commentf(out))
  1569. out, err = s.d.Cmd("run", "-d", "--name=test2", "busybox", "top")
  1570. c.Assert(err, check.IsNil, check.Commentf(out))
  1571. test2ID := strings.TrimSpace(out)
  1572. out, err = s.d.Cmd("run", "-d", "--name=test3", "--link", "test2:abc", "busybox", "top")
  1573. test3ID := strings.TrimSpace(out)
  1574. s.d.Restart(c)
  1575. out, err = s.d.Cmd("create", "--name=test", "busybox")
  1576. c.Assert(err, check.NotNil, check.Commentf("expected error trying to create container with duplicate name"))
  1577. // this one is no longer needed, removing simplifies the remainder of the test
  1578. out, err = s.d.Cmd("rm", "-f", "test")
  1579. c.Assert(err, check.IsNil, check.Commentf(out))
  1580. out, err = s.d.Cmd("ps", "-a", "--no-trunc")
  1581. c.Assert(err, check.IsNil, check.Commentf(out))
  1582. lines := strings.Split(strings.TrimSpace(out), "\n")[1:]
  1583. test2validated := false
  1584. test3validated := false
  1585. for _, line := range lines {
  1586. fields := strings.Fields(line)
  1587. names := fields[len(fields)-1]
  1588. switch fields[0] {
  1589. case test2ID:
  1590. c.Assert(names, check.Equals, "test2,test3/abc")
  1591. test2validated = true
  1592. case test3ID:
  1593. c.Assert(names, check.Equals, "test3")
  1594. test3validated = true
  1595. }
  1596. }
  1597. c.Assert(test2validated, check.Equals, true)
  1598. c.Assert(test3validated, check.Equals, true)
  1599. }
  1600. // TestDaemonRestartWithKilledRunningContainer requires live restore of running containers
  1601. func (s *DockerDaemonSuite) TestDaemonRestartWithKilledRunningContainer(t *check.C) {
  1602. testRequires(t, DaemonIsLinux)
  1603. s.d.StartWithBusybox(t)
  1604. cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top")
  1605. defer s.d.Stop(t)
  1606. if err != nil {
  1607. t.Fatal(cid, err)
  1608. }
  1609. cid = strings.TrimSpace(cid)
  1610. pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid)
  1611. t.Assert(err, check.IsNil)
  1612. pid = strings.TrimSpace(pid)
  1613. // Kill the daemon
  1614. if err := s.d.Kill(); err != nil {
  1615. t.Fatal(err)
  1616. }
  1617. // kill the container
  1618. icmd.RunCommand(ctrBinary, "--address", "/var/run/docker/containerd/docker-containerd.sock",
  1619. "--namespace", moby_daemon.ContainersNamespace, "tasks", "kill", cid).Assert(t, icmd.Success)
  1620. // Give time to containerd to process the command if we don't
  1621. // the exit event might be received after we do the inspect
  1622. result := icmd.RunCommand("kill", "-0", pid)
  1623. for result.ExitCode == 0 {
  1624. time.Sleep(1 * time.Second)
  1625. // FIXME(vdemeester) should we check it doesn't error out ?
  1626. result = icmd.RunCommand("kill", "-0", pid)
  1627. }
  1628. // restart the daemon
  1629. s.d.Start(t)
  1630. // Check that we've got the correct exit code
  1631. out, err := s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", cid)
  1632. t.Assert(err, check.IsNil)
  1633. out = strings.TrimSpace(out)
  1634. if out != "143" {
  1635. t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "143", out, cid)
  1636. }
  1637. }
  1638. // os.Kill should kill daemon ungracefully, leaving behind live containers.
  1639. // The live containers should be known to the restarted daemon. Stopping
  1640. // them now, should remove the mounts.
  1641. func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonCrash(c *check.C) {
  1642. testRequires(c, DaemonIsLinux)
  1643. s.d.StartWithBusybox(c, "--live-restore")
  1644. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  1645. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1646. id := strings.TrimSpace(out)
  1647. // kill the daemon
  1648. c.Assert(s.d.Kill(), check.IsNil)
  1649. // Check if there are mounts with container id visible from the host.
  1650. // If not, those mounts exist in container's own mount ns, and so
  1651. // the following check for mounts being cleared is pointless.
  1652. skipMountCheck := false
  1653. mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1654. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1655. if !strings.Contains(string(mountOut), id) {
  1656. skipMountCheck = true
  1657. }
  1658. // restart daemon.
  1659. s.d.Start(c, "--live-restore")
  1660. // container should be running.
  1661. out, err = s.d.Cmd("inspect", "--format={{.State.Running}}", id)
  1662. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1663. out = strings.TrimSpace(out)
  1664. if out != "true" {
  1665. c.Fatalf("Container %s expected to stay alive after daemon restart", id)
  1666. }
  1667. // 'docker stop' should work.
  1668. out, err = s.d.Cmd("stop", id)
  1669. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1670. if skipMountCheck {
  1671. return
  1672. }
  1673. // Now, container mounts should be gone.
  1674. mountOut, err = ioutil.ReadFile("/proc/self/mountinfo")
  1675. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1676. comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.Root, mountOut)
  1677. c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1678. }
  1679. // TestDaemonRestartWithUnpausedRunningContainer requires live restore of running containers.
  1680. func (s *DockerDaemonSuite) TestDaemonRestartWithUnpausedRunningContainer(t *check.C) {
  1681. testRequires(t, DaemonIsLinux)
  1682. s.d.StartWithBusybox(t, "--live-restore")
  1683. cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top")
  1684. defer s.d.Stop(t)
  1685. if err != nil {
  1686. t.Fatal(cid, err)
  1687. }
  1688. cid = strings.TrimSpace(cid)
  1689. pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid)
  1690. t.Assert(err, check.IsNil)
  1691. // pause the container
  1692. if _, err := s.d.Cmd("pause", cid); err != nil {
  1693. t.Fatal(cid, err)
  1694. }
  1695. // Kill the daemon
  1696. if err := s.d.Kill(); err != nil {
  1697. t.Fatal(err)
  1698. }
  1699. // resume the container
  1700. result := icmd.RunCommand(
  1701. ctrBinary,
  1702. "--address", "/var/run/docker/containerd/docker-containerd.sock",
  1703. "--namespace", moby_daemon.ContainersNamespace,
  1704. "tasks", "resume", cid)
  1705. result.Assert(t, icmd.Success)
  1706. // Give time to containerd to process the command if we don't
  1707. // the resume event might be received after we do the inspect
  1708. waitAndAssert(t, defaultReconciliationTimeout, func(*check.C) (interface{}, check.CommentInterface) {
  1709. result := icmd.RunCommand("kill", "-0", strings.TrimSpace(pid))
  1710. return result.ExitCode, nil
  1711. }, checker.Equals, 0)
  1712. // restart the daemon
  1713. s.d.Start(t, "--live-restore")
  1714. // Check that we've got the correct status
  1715. out, err := s.d.Cmd("inspect", "-f", "{{.State.Status}}", cid)
  1716. t.Assert(err, check.IsNil)
  1717. out = strings.TrimSpace(out)
  1718. if out != "running" {
  1719. t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "running", out, cid)
  1720. }
  1721. if _, err := s.d.Cmd("kill", cid); err != nil {
  1722. t.Fatal(err)
  1723. }
  1724. }
  1725. // TestRunLinksChanged checks that creating a new container with the same name does not update links
  1726. // this ensures that the old, pre gh#16032 functionality continues on
  1727. func (s *DockerDaemonSuite) TestRunLinksChanged(c *check.C) {
  1728. testRequires(c, DaemonIsLinux) // Windows does not support links
  1729. s.d.StartWithBusybox(c)
  1730. out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1731. c.Assert(err, check.IsNil, check.Commentf(out))
  1732. out, err = s.d.Cmd("run", "--name=test2", "--link=test:abc", "busybox", "sh", "-c", "ping -c 1 abc")
  1733. c.Assert(err, check.IsNil, check.Commentf(out))
  1734. c.Assert(out, checker.Contains, "1 packets transmitted, 1 packets received")
  1735. out, err = s.d.Cmd("rm", "-f", "test")
  1736. c.Assert(err, check.IsNil, check.Commentf(out))
  1737. out, err = s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1738. c.Assert(err, check.IsNil, check.Commentf(out))
  1739. out, err = s.d.Cmd("start", "-a", "test2")
  1740. c.Assert(err, check.NotNil, check.Commentf(out))
  1741. c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  1742. s.d.Restart(c)
  1743. out, err = s.d.Cmd("start", "-a", "test2")
  1744. c.Assert(err, check.NotNil, check.Commentf(out))
  1745. c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  1746. }
  1747. func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *check.C) {
  1748. testRequires(c, DaemonIsLinux)
  1749. infoLog := "\x1b[36mINFO\x1b"
  1750. b := bytes.NewBuffer(nil)
  1751. done := make(chan bool)
  1752. p, tty, err := pty.Open()
  1753. c.Assert(err, checker.IsNil)
  1754. defer func() {
  1755. tty.Close()
  1756. p.Close()
  1757. }()
  1758. go func() {
  1759. io.Copy(b, p)
  1760. done <- true
  1761. }()
  1762. // Enable coloring explicitly
  1763. s.d.StartWithLogFile(tty, "--raw-logs=false")
  1764. s.d.Stop(c)
  1765. // Wait for io.Copy() before checking output
  1766. <-done
  1767. c.Assert(b.String(), checker.Contains, infoLog)
  1768. b.Reset()
  1769. // "tty" is already closed in prev s.d.Stop(),
  1770. // we have to close the other side "p" and open another pair of
  1771. // pty for the next test.
  1772. p.Close()
  1773. p, tty, err = pty.Open()
  1774. c.Assert(err, checker.IsNil)
  1775. go func() {
  1776. io.Copy(b, p)
  1777. done <- true
  1778. }()
  1779. // Disable coloring explicitly
  1780. s.d.StartWithLogFile(tty, "--raw-logs=true")
  1781. s.d.Stop(c)
  1782. // Wait for io.Copy() before checking output
  1783. <-done
  1784. c.Assert(b.String(), check.Not(check.Equals), "")
  1785. c.Assert(b.String(), check.Not(checker.Contains), infoLog)
  1786. }
  1787. func (s *DockerDaemonSuite) TestDaemonDebugLog(c *check.C) {
  1788. testRequires(c, DaemonIsLinux)
  1789. debugLog := "\x1b[37mDEBU\x1b"
  1790. p, tty, err := pty.Open()
  1791. c.Assert(err, checker.IsNil)
  1792. defer func() {
  1793. tty.Close()
  1794. p.Close()
  1795. }()
  1796. b := bytes.NewBuffer(nil)
  1797. go io.Copy(b, p)
  1798. s.d.StartWithLogFile(tty, "--debug")
  1799. s.d.Stop(c)
  1800. c.Assert(b.String(), checker.Contains, debugLog)
  1801. }
  1802. func (s *DockerDaemonSuite) TestDaemonDiscoveryBackendConfigReload(c *check.C) {
  1803. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1804. // daemon config file
  1805. daemonConfig := `{ "debug" : false }`
  1806. configFile, err := ioutil.TempFile("", "test-daemon-discovery-backend-config-reload-config")
  1807. c.Assert(err, checker.IsNil, check.Commentf("could not create temp file for config reload"))
  1808. configFilePath := configFile.Name()
  1809. defer func() {
  1810. configFile.Close()
  1811. os.RemoveAll(configFile.Name())
  1812. }()
  1813. _, err = configFile.Write([]byte(daemonConfig))
  1814. c.Assert(err, checker.IsNil)
  1815. // --log-level needs to be set so that d.Start() doesn't add --debug causing
  1816. // a conflict with the config
  1817. s.d.Start(c, "--config-file", configFilePath, "--log-level=info")
  1818. // daemon config file
  1819. daemonConfig = `{
  1820. "cluster-store": "consul://consuladdr:consulport/some/path",
  1821. "cluster-advertise": "192.168.56.100:0",
  1822. "debug" : false
  1823. }`
  1824. err = configFile.Truncate(0)
  1825. c.Assert(err, checker.IsNil)
  1826. _, err = configFile.Seek(0, os.SEEK_SET)
  1827. c.Assert(err, checker.IsNil)
  1828. _, err = configFile.Write([]byte(daemonConfig))
  1829. c.Assert(err, checker.IsNil)
  1830. err = s.d.ReloadConfig()
  1831. c.Assert(err, checker.IsNil, check.Commentf("error reloading daemon config"))
  1832. out, err := s.d.Cmd("info")
  1833. c.Assert(err, checker.IsNil)
  1834. c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Store: consul://consuladdr:consulport/some/path"))
  1835. c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Advertise: 192.168.56.100:0"))
  1836. }
  1837. // Test for #21956
  1838. func (s *DockerDaemonSuite) TestDaemonLogOptions(c *check.C) {
  1839. s.d.StartWithBusybox(c, "--log-driver=syslog", "--log-opt=syslog-address=udp://127.0.0.1:514")
  1840. out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "top")
  1841. c.Assert(err, check.IsNil, check.Commentf(out))
  1842. id := strings.TrimSpace(out)
  1843. out, err = s.d.Cmd("inspect", "--format='{{.HostConfig.LogConfig}}'", id)
  1844. c.Assert(err, check.IsNil, check.Commentf(out))
  1845. c.Assert(out, checker.Contains, "{json-file map[]}")
  1846. }
  1847. // Test case for #20936, #22443
  1848. func (s *DockerDaemonSuite) TestDaemonMaxConcurrency(c *check.C) {
  1849. s.d.Start(c, "--max-concurrent-uploads=6", "--max-concurrent-downloads=8")
  1850. expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 6"`
  1851. expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"`
  1852. content, err := s.d.ReadLogFile()
  1853. c.Assert(err, checker.IsNil)
  1854. c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  1855. c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  1856. }
  1857. // Test case for #20936, #22443
  1858. func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *check.C) {
  1859. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1860. // daemon config file
  1861. configFilePath := "test.json"
  1862. configFile, err := os.Create(configFilePath)
  1863. c.Assert(err, checker.IsNil)
  1864. defer os.Remove(configFilePath)
  1865. daemonConfig := `{ "max-concurrent-downloads" : 8 }`
  1866. fmt.Fprintf(configFile, "%s", daemonConfig)
  1867. configFile.Close()
  1868. s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath))
  1869. expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"`
  1870. expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"`
  1871. content, err := s.d.ReadLogFile()
  1872. c.Assert(err, checker.IsNil)
  1873. c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  1874. c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  1875. configFile, err = os.Create(configFilePath)
  1876. c.Assert(err, checker.IsNil)
  1877. daemonConfig = `{ "max-concurrent-uploads" : 7, "max-concurrent-downloads" : 9 }`
  1878. fmt.Fprintf(configFile, "%s", daemonConfig)
  1879. configFile.Close()
  1880. c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  1881. // unix.Kill(s.d.cmd.Process.Pid, unix.SIGHUP)
  1882. time.Sleep(3 * time.Second)
  1883. expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 7"`
  1884. expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 9"`
  1885. content, err = s.d.ReadLogFile()
  1886. c.Assert(err, checker.IsNil)
  1887. c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  1888. c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  1889. }
  1890. // Test case for #20936, #22443
  1891. func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *check.C) {
  1892. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1893. // daemon config file
  1894. configFilePath := "test.json"
  1895. configFile, err := os.Create(configFilePath)
  1896. c.Assert(err, checker.IsNil)
  1897. defer os.Remove(configFilePath)
  1898. daemonConfig := `{ "max-concurrent-uploads" : null }`
  1899. fmt.Fprintf(configFile, "%s", daemonConfig)
  1900. configFile.Close()
  1901. s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath))
  1902. expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"`
  1903. expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 3"`
  1904. content, err := s.d.ReadLogFile()
  1905. c.Assert(err, checker.IsNil)
  1906. c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  1907. c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  1908. configFile, err = os.Create(configFilePath)
  1909. c.Assert(err, checker.IsNil)
  1910. daemonConfig = `{ "max-concurrent-uploads" : 1, "max-concurrent-downloads" : null }`
  1911. fmt.Fprintf(configFile, "%s", daemonConfig)
  1912. configFile.Close()
  1913. c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  1914. // unix.Kill(s.d.cmd.Process.Pid, unix.SIGHUP)
  1915. time.Sleep(3 * time.Second)
  1916. expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 1"`
  1917. expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"`
  1918. content, err = s.d.ReadLogFile()
  1919. c.Assert(err, checker.IsNil)
  1920. c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  1921. c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  1922. configFile, err = os.Create(configFilePath)
  1923. c.Assert(err, checker.IsNil)
  1924. daemonConfig = `{ "labels":["foo=bar"] }`
  1925. fmt.Fprintf(configFile, "%s", daemonConfig)
  1926. configFile.Close()
  1927. c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  1928. time.Sleep(3 * time.Second)
  1929. expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 5"`
  1930. expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"`
  1931. content, err = s.d.ReadLogFile()
  1932. c.Assert(err, checker.IsNil)
  1933. c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  1934. c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  1935. }
  1936. func (s *DockerDaemonSuite) TestBuildOnDisabledBridgeNetworkDaemon(c *check.C) {
  1937. s.d.StartWithBusybox(c, "-b=none", "--iptables=false")
  1938. out, code, err := s.d.BuildImageWithOut("busyboxs",
  1939. `FROM busybox
  1940. RUN cat /etc/hosts`, false)
  1941. comment := check.Commentf("Failed to build image. output %s, exitCode %d, err %v", out, code, err)
  1942. c.Assert(err, check.IsNil, comment)
  1943. c.Assert(code, check.Equals, 0, comment)
  1944. }
  1945. // Test case for #21976
  1946. func (s *DockerDaemonSuite) TestDaemonDNSFlagsInHostMode(c *check.C) {
  1947. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1948. s.d.StartWithBusybox(c, "--dns", "1.2.3.4", "--dns-search", "example.com", "--dns-opt", "timeout:3")
  1949. expectedOutput := "nameserver 1.2.3.4"
  1950. out, _ := s.d.Cmd("run", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  1951. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  1952. expectedOutput = "search example.com"
  1953. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  1954. expectedOutput = "options timeout:3"
  1955. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  1956. }
  1957. func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) {
  1958. conf, err := ioutil.TempFile("", "config-file-")
  1959. c.Assert(err, check.IsNil)
  1960. configName := conf.Name()
  1961. conf.Close()
  1962. defer os.Remove(configName)
  1963. config := `
  1964. {
  1965. "runtimes": {
  1966. "oci": {
  1967. "path": "docker-runc"
  1968. },
  1969. "vm": {
  1970. "path": "/usr/local/bin/vm-manager",
  1971. "runtimeArgs": [
  1972. "--debug"
  1973. ]
  1974. }
  1975. }
  1976. }
  1977. `
  1978. ioutil.WriteFile(configName, []byte(config), 0644)
  1979. s.d.StartWithBusybox(c, "--config-file", configName)
  1980. // Run with default runtime
  1981. out, err := s.d.Cmd("run", "--rm", "busybox", "ls")
  1982. c.Assert(err, check.IsNil, check.Commentf(out))
  1983. // Run with default runtime explicitly
  1984. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  1985. c.Assert(err, check.IsNil, check.Commentf(out))
  1986. // Run with oci (same path as default) but keep it around
  1987. out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls")
  1988. c.Assert(err, check.IsNil, check.Commentf(out))
  1989. // Run with "vm"
  1990. out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls")
  1991. c.Assert(err, check.NotNil, check.Commentf(out))
  1992. c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  1993. // Reset config to only have the default
  1994. config = `
  1995. {
  1996. "runtimes": {
  1997. }
  1998. }
  1999. `
  2000. ioutil.WriteFile(configName, []byte(config), 0644)
  2001. c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  2002. // Give daemon time to reload config
  2003. <-time.After(1 * time.Second)
  2004. // Run with default runtime
  2005. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2006. c.Assert(err, check.IsNil, check.Commentf(out))
  2007. // Run with "oci"
  2008. out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls")
  2009. c.Assert(err, check.NotNil, check.Commentf(out))
  2010. c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2011. // Start previously created container with oci
  2012. out, err = s.d.Cmd("start", "oci-runtime-ls")
  2013. c.Assert(err, check.NotNil, check.Commentf(out))
  2014. c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2015. // Check that we can't override the default runtime
  2016. config = `
  2017. {
  2018. "runtimes": {
  2019. "runc": {
  2020. "path": "my-runc"
  2021. }
  2022. }
  2023. }
  2024. `
  2025. ioutil.WriteFile(configName, []byte(config), 0644)
  2026. c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  2027. // Give daemon time to reload config
  2028. <-time.After(1 * time.Second)
  2029. content, err := s.d.ReadLogFile()
  2030. c.Assert(err, checker.IsNil)
  2031. c.Assert(string(content), checker.Contains, `file configuration validation failed (runtime name 'runc' is reserved)`)
  2032. // Check that we can select a default runtime
  2033. config = `
  2034. {
  2035. "default-runtime": "vm",
  2036. "runtimes": {
  2037. "oci": {
  2038. "path": "docker-runc"
  2039. },
  2040. "vm": {
  2041. "path": "/usr/local/bin/vm-manager",
  2042. "runtimeArgs": [
  2043. "--debug"
  2044. ]
  2045. }
  2046. }
  2047. }
  2048. `
  2049. ioutil.WriteFile(configName, []byte(config), 0644)
  2050. c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  2051. // Give daemon time to reload config
  2052. <-time.After(1 * time.Second)
  2053. out, err = s.d.Cmd("run", "--rm", "busybox", "ls")
  2054. c.Assert(err, check.NotNil, check.Commentf(out))
  2055. c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2056. // Run with default runtime explicitly
  2057. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2058. c.Assert(err, check.IsNil, check.Commentf(out))
  2059. }
  2060. func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) {
  2061. s.d.StartWithBusybox(c, "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
  2062. // Run with default runtime
  2063. out, err := s.d.Cmd("run", "--rm", "busybox", "ls")
  2064. c.Assert(err, check.IsNil, check.Commentf(out))
  2065. // Run with default runtime explicitly
  2066. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2067. c.Assert(err, check.IsNil, check.Commentf(out))
  2068. // Run with oci (same path as default) but keep it around
  2069. out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls")
  2070. c.Assert(err, check.IsNil, check.Commentf(out))
  2071. // Run with "vm"
  2072. out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls")
  2073. c.Assert(err, check.NotNil, check.Commentf(out))
  2074. c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2075. // Start a daemon without any extra runtimes
  2076. s.d.Stop(c)
  2077. s.d.StartWithBusybox(c)
  2078. // Run with default runtime
  2079. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2080. c.Assert(err, check.IsNil, check.Commentf(out))
  2081. // Run with "oci"
  2082. out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls")
  2083. c.Assert(err, check.NotNil, check.Commentf(out))
  2084. c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2085. // Start previously created container with oci
  2086. out, err = s.d.Cmd("start", "oci-runtime-ls")
  2087. c.Assert(err, check.NotNil, check.Commentf(out))
  2088. c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2089. // Check that we can't override the default runtime
  2090. s.d.Stop(c)
  2091. c.Assert(s.d.StartWithError("--add-runtime", "runc=my-runc"), checker.NotNil)
  2092. content, err := s.d.ReadLogFile()
  2093. c.Assert(err, checker.IsNil)
  2094. c.Assert(string(content), checker.Contains, `runtime name 'runc' is reserved`)
  2095. // Check that we can select a default runtime
  2096. s.d.Stop(c)
  2097. s.d.StartWithBusybox(c, "--default-runtime=vm", "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
  2098. out, err = s.d.Cmd("run", "--rm", "busybox", "ls")
  2099. c.Assert(err, check.NotNil, check.Commentf(out))
  2100. c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2101. // Run with default runtime explicitly
  2102. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2103. c.Assert(err, check.IsNil, check.Commentf(out))
  2104. }
  2105. func (s *DockerDaemonSuite) TestDaemonRestartWithAutoRemoveContainer(c *check.C) {
  2106. s.d.StartWithBusybox(c)
  2107. // top1 will exist after daemon restarts
  2108. out, err := s.d.Cmd("run", "-d", "--name", "top1", "busybox:latest", "top")
  2109. c.Assert(err, checker.IsNil, check.Commentf("run top1: %v", out))
  2110. // top2 will be removed after daemon restarts
  2111. out, err = s.d.Cmd("run", "-d", "--rm", "--name", "top2", "busybox:latest", "top")
  2112. c.Assert(err, checker.IsNil, check.Commentf("run top2: %v", out))
  2113. out, err = s.d.Cmd("ps")
  2114. c.Assert(out, checker.Contains, "top1", check.Commentf("top1 should be running"))
  2115. c.Assert(out, checker.Contains, "top2", check.Commentf("top2 should be running"))
  2116. // now restart daemon gracefully
  2117. s.d.Restart(c)
  2118. out, err = s.d.Cmd("ps", "-a")
  2119. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  2120. c.Assert(out, checker.Contains, "top1", check.Commentf("top1 should exist after daemon restarts"))
  2121. c.Assert(out, checker.Not(checker.Contains), "top2", check.Commentf("top2 should be removed after daemon restarts"))
  2122. }
  2123. func (s *DockerDaemonSuite) TestDaemonRestartSaveContainerExitCode(c *check.C) {
  2124. s.d.StartWithBusybox(c)
  2125. containerName := "error-values"
  2126. // Make a container with both a non 0 exit code and an error message
  2127. // We explicitly disable `--init` for this test, because `--init` is enabled by default
  2128. // on "experimental". Enabling `--init` results in a different behavior; because the "init"
  2129. // process itself is PID1, the container does not fail on _startup_ (i.e., `docker-init` starting),
  2130. // but directly after. The exit code of the container is still 127, but the Error Message is not
  2131. // captured, so `.State.Error` is empty.
  2132. // See the discussion on https://github.com/docker/docker/pull/30227#issuecomment-274161426,
  2133. // and https://github.com/docker/docker/pull/26061#r78054578 for more information.
  2134. out, err := s.d.Cmd("run", "--name", containerName, "--init=false", "busybox", "toto")
  2135. c.Assert(err, checker.NotNil)
  2136. // Check that those values were saved on disk
  2137. out, err = s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName)
  2138. out = strings.TrimSpace(out)
  2139. c.Assert(err, checker.IsNil)
  2140. c.Assert(out, checker.Equals, "127")
  2141. errMsg1, err := s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName)
  2142. errMsg1 = strings.TrimSpace(errMsg1)
  2143. c.Assert(err, checker.IsNil)
  2144. c.Assert(errMsg1, checker.Contains, "executable file not found")
  2145. // now restart daemon
  2146. s.d.Restart(c)
  2147. // Check that those values are still around
  2148. out, err = s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName)
  2149. out = strings.TrimSpace(out)
  2150. c.Assert(err, checker.IsNil)
  2151. c.Assert(out, checker.Equals, "127")
  2152. out, err = s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName)
  2153. out = strings.TrimSpace(out)
  2154. c.Assert(err, checker.IsNil)
  2155. c.Assert(out, checker.Equals, errMsg1)
  2156. }
  2157. func (s *DockerDaemonSuite) TestDaemonWithUserlandProxyPath(c *check.C) {
  2158. testRequires(c, SameHostDaemon, DaemonIsLinux)
  2159. dockerProxyPath, err := exec.LookPath("docker-proxy")
  2160. c.Assert(err, checker.IsNil)
  2161. tmpDir, err := ioutil.TempDir("", "test-docker-proxy")
  2162. c.Assert(err, checker.IsNil)
  2163. newProxyPath := filepath.Join(tmpDir, "docker-proxy")
  2164. cmd := exec.Command("cp", dockerProxyPath, newProxyPath)
  2165. c.Assert(cmd.Run(), checker.IsNil)
  2166. // custom one
  2167. s.d.StartWithBusybox(c, "--userland-proxy-path", newProxyPath)
  2168. out, err := s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true")
  2169. c.Assert(err, checker.IsNil, check.Commentf(out))
  2170. // try with the original one
  2171. s.d.Restart(c, "--userland-proxy-path", dockerProxyPath)
  2172. out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true")
  2173. c.Assert(err, checker.IsNil, check.Commentf(out))
  2174. // not exist
  2175. s.d.Restart(c, "--userland-proxy-path", "/does/not/exist")
  2176. out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true")
  2177. c.Assert(err, checker.NotNil, check.Commentf(out))
  2178. c.Assert(out, checker.Contains, "driver failed programming external connectivity on endpoint")
  2179. c.Assert(out, checker.Contains, "/does/not/exist: no such file or directory")
  2180. }
  2181. // Test case for #22471
  2182. func (s *DockerDaemonSuite) TestDaemonShutdownTimeout(c *check.C) {
  2183. testRequires(c, SameHostDaemon)
  2184. s.d.StartWithBusybox(c, "--shutdown-timeout=3")
  2185. _, err := s.d.Cmd("run", "-d", "busybox", "top")
  2186. c.Assert(err, check.IsNil)
  2187. c.Assert(s.d.Signal(unix.SIGINT), checker.IsNil)
  2188. select {
  2189. case <-s.d.Wait:
  2190. case <-time.After(5 * time.Second):
  2191. }
  2192. expectedMessage := `level=debug msg="daemon configured with a 3 seconds minimum shutdown timeout"`
  2193. content, err := s.d.ReadLogFile()
  2194. c.Assert(err, checker.IsNil)
  2195. c.Assert(string(content), checker.Contains, expectedMessage)
  2196. }
  2197. // Test case for #22471
  2198. func (s *DockerDaemonSuite) TestDaemonShutdownTimeoutWithConfigFile(c *check.C) {
  2199. testRequires(c, SameHostDaemon)
  2200. // daemon config file
  2201. configFilePath := "test.json"
  2202. configFile, err := os.Create(configFilePath)
  2203. c.Assert(err, checker.IsNil)
  2204. defer os.Remove(configFilePath)
  2205. daemonConfig := `{ "shutdown-timeout" : 8 }`
  2206. fmt.Fprintf(configFile, "%s", daemonConfig)
  2207. configFile.Close()
  2208. s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath))
  2209. configFile, err = os.Create(configFilePath)
  2210. c.Assert(err, checker.IsNil)
  2211. daemonConfig = `{ "shutdown-timeout" : 5 }`
  2212. fmt.Fprintf(configFile, "%s", daemonConfig)
  2213. configFile.Close()
  2214. c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil)
  2215. select {
  2216. case <-s.d.Wait:
  2217. case <-time.After(3 * time.Second):
  2218. }
  2219. expectedMessage := `level=debug msg="Reset Shutdown Timeout: 5"`
  2220. content, err := s.d.ReadLogFile()
  2221. c.Assert(err, checker.IsNil)
  2222. c.Assert(string(content), checker.Contains, expectedMessage)
  2223. }
  2224. // Test case for 29342
  2225. func (s *DockerDaemonSuite) TestExecWithUserAfterLiveRestore(c *check.C) {
  2226. testRequires(c, DaemonIsLinux)
  2227. s.d.StartWithBusybox(c, "--live-restore")
  2228. out, err := s.d.Cmd("run", "-d", "--name=top", "busybox", "sh", "-c", "addgroup -S test && adduser -S -G test test -D -s /bin/sh && touch /adduser_end && top")
  2229. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2230. s.d.WaitRun("top")
  2231. // Wait for shell command to be completed
  2232. _, err = s.d.Cmd("exec", "top", "sh", "-c", `for i in $(seq 1 5); do if [ -e /adduser_end ]; then rm -f /adduser_end && break; else sleep 1 && false; fi; done`)
  2233. c.Assert(err, check.IsNil, check.Commentf("Timeout waiting for shell command to be completed"))
  2234. out1, err := s.d.Cmd("exec", "-u", "test", "top", "id")
  2235. // uid=100(test) gid=101(test) groups=101(test)
  2236. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out1))
  2237. // restart daemon.
  2238. s.d.Restart(c, "--live-restore")
  2239. out2, err := s.d.Cmd("exec", "-u", "test", "top", "id")
  2240. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out2))
  2241. c.Assert(out2, check.Equals, out1, check.Commentf("Output: before restart '%s', after restart '%s'", out1, out2))
  2242. out, err = s.d.Cmd("stop", "top")
  2243. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2244. }
  2245. func (s *DockerDaemonSuite) TestRemoveContainerAfterLiveRestore(c *check.C) {
  2246. testRequires(c, DaemonIsLinux, overlayFSSupported, SameHostDaemon)
  2247. s.d.StartWithBusybox(c, "--live-restore", "--storage-driver", "overlay")
  2248. out, err := s.d.Cmd("run", "-d", "--name=top", "busybox", "top")
  2249. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2250. s.d.WaitRun("top")
  2251. // restart daemon.
  2252. s.d.Restart(c, "--live-restore", "--storage-driver", "overlay")
  2253. out, err = s.d.Cmd("stop", "top")
  2254. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2255. // test if the rootfs mountpoint still exist
  2256. mountpoint, err := s.d.InspectField("top", ".GraphDriver.Data.MergedDir")
  2257. c.Assert(err, check.IsNil)
  2258. f, err := os.Open("/proc/self/mountinfo")
  2259. c.Assert(err, check.IsNil)
  2260. defer f.Close()
  2261. sc := bufio.NewScanner(f)
  2262. for sc.Scan() {
  2263. line := sc.Text()
  2264. if strings.Contains(line, mountpoint) {
  2265. c.Fatalf("mountinfo should not include the mountpoint of stop container")
  2266. }
  2267. }
  2268. out, err = s.d.Cmd("rm", "top")
  2269. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2270. }
  2271. // #29598
  2272. func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *check.C) {
  2273. testRequires(c, DaemonIsLinux, SameHostDaemon)
  2274. s.d.StartWithBusybox(c, "--live-restore")
  2275. out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top")
  2276. c.Assert(err, check.IsNil, check.Commentf("output: %s", out))
  2277. id := strings.TrimSpace(out)
  2278. type state struct {
  2279. Running bool
  2280. StartedAt time.Time
  2281. }
  2282. out, err = s.d.Cmd("inspect", "-f", "{{json .State}}", id)
  2283. c.Assert(err, checker.IsNil, check.Commentf("output: %s", out))
  2284. var origState state
  2285. err = json.Unmarshal([]byte(strings.TrimSpace(out)), &origState)
  2286. c.Assert(err, checker.IsNil)
  2287. s.d.Restart(c, "--live-restore")
  2288. pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", id)
  2289. c.Assert(err, check.IsNil)
  2290. pidint, err := strconv.Atoi(strings.TrimSpace(pid))
  2291. c.Assert(err, check.IsNil)
  2292. c.Assert(pidint, checker.GreaterThan, 0)
  2293. c.Assert(unix.Kill(pidint, unix.SIGKILL), check.IsNil)
  2294. ticker := time.NewTicker(50 * time.Millisecond)
  2295. timeout := time.After(10 * time.Second)
  2296. for range ticker.C {
  2297. select {
  2298. case <-timeout:
  2299. c.Fatal("timeout waiting for container restart")
  2300. default:
  2301. }
  2302. out, err := s.d.Cmd("inspect", "-f", "{{json .State}}", id)
  2303. c.Assert(err, checker.IsNil, check.Commentf("output: %s", out))
  2304. var newState state
  2305. err = json.Unmarshal([]byte(strings.TrimSpace(out)), &newState)
  2306. c.Assert(err, checker.IsNil)
  2307. if !newState.Running {
  2308. continue
  2309. }
  2310. if newState.StartedAt.After(origState.StartedAt) {
  2311. break
  2312. }
  2313. }
  2314. out, err = s.d.Cmd("stop", id)
  2315. c.Assert(err, check.IsNil, check.Commentf("output: %s", out))
  2316. }
  2317. func (s *DockerDaemonSuite) TestShmSize(c *check.C) {
  2318. testRequires(c, DaemonIsLinux)
  2319. size := 67108864 * 2
  2320. pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024))
  2321. s.d.StartWithBusybox(c, "--default-shm-size", fmt.Sprintf("%v", size))
  2322. name := "shm1"
  2323. out, err := s.d.Cmd("run", "--name", name, "busybox", "mount")
  2324. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2325. c.Assert(pattern.MatchString(out), checker.True)
  2326. out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name)
  2327. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2328. c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size))
  2329. }
  2330. func (s *DockerDaemonSuite) TestShmSizeReload(c *check.C) {
  2331. testRequires(c, DaemonIsLinux)
  2332. configPath, err := ioutil.TempDir("", "test-daemon-shm-size-reload-config")
  2333. c.Assert(err, checker.IsNil, check.Commentf("could not create temp file for config reload"))
  2334. defer os.RemoveAll(configPath) // clean up
  2335. configFile := filepath.Join(configPath, "config.json")
  2336. size := 67108864 * 2
  2337. configData := []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024))
  2338. c.Assert(ioutil.WriteFile(configFile, configData, 0666), checker.IsNil, check.Commentf("could not write temp file for config reload"))
  2339. pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024))
  2340. s.d.StartWithBusybox(c, "--config-file", configFile)
  2341. name := "shm1"
  2342. out, err := s.d.Cmd("run", "--name", name, "busybox", "mount")
  2343. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2344. c.Assert(pattern.MatchString(out), checker.True)
  2345. out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name)
  2346. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2347. c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size))
  2348. size = 67108864 * 3
  2349. configData = []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024))
  2350. c.Assert(ioutil.WriteFile(configFile, configData, 0666), checker.IsNil, check.Commentf("could not write temp file for config reload"))
  2351. pattern = regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024))
  2352. err = s.d.ReloadConfig()
  2353. c.Assert(err, checker.IsNil, check.Commentf("error reloading daemon config"))
  2354. name = "shm2"
  2355. out, err = s.d.Cmd("run", "--name", name, "busybox", "mount")
  2356. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2357. c.Assert(pattern.MatchString(out), checker.True)
  2358. out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name)
  2359. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  2360. c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size))
  2361. }
  2362. // this is used to test both "private" and "shareable" daemon default ipc modes
  2363. func testDaemonIpcPrivateShareable(d *daemon.Daemon, c *check.C, mustExist bool) {
  2364. name := "test-ipcmode"
  2365. _, err := d.Cmd("run", "-d", "--name", name, "busybox", "top")
  2366. c.Assert(err, checker.IsNil)
  2367. // get major:minor pair for /dev/shm from container's /proc/self/mountinfo
  2368. cmd := "awk '($5 == \"/dev/shm\") {printf $3}' /proc/self/mountinfo"
  2369. mm, err := d.Cmd("exec", "-i", name, "sh", "-c", cmd)
  2370. c.Assert(err, checker.IsNil)
  2371. c.Assert(mm, checker.Matches, "^[0-9]+:[0-9]+$")
  2372. exists, err := testIpcCheckDevExists(mm)
  2373. c.Assert(err, checker.IsNil)
  2374. c.Logf("[testDaemonIpcPrivateShareable] ipcdev: %v, exists: %v, mustExist: %v\n", mm, exists, mustExist)
  2375. c.Assert(exists, checker.Equals, mustExist)
  2376. }
  2377. // TestDaemonIpcModeShareable checks that --default-ipc-mode shareable works as intended.
  2378. func (s *DockerDaemonSuite) TestDaemonIpcModeShareable(c *check.C) {
  2379. testRequires(c, DaemonIsLinux, SameHostDaemon)
  2380. s.d.StartWithBusybox(c, "--default-ipc-mode", "shareable")
  2381. testDaemonIpcPrivateShareable(s.d, c, true)
  2382. }
  2383. // TestDaemonIpcModePrivate checks that --default-ipc-mode private works as intended.
  2384. func (s *DockerDaemonSuite) TestDaemonIpcModePrivate(c *check.C) {
  2385. testRequires(c, DaemonIsLinux, SameHostDaemon)
  2386. s.d.StartWithBusybox(c, "--default-ipc-mode", "private")
  2387. testDaemonIpcPrivateShareable(s.d, c, false)
  2388. }
  2389. // used to check if an IpcMode given in config works as intended
  2390. func testDaemonIpcFromConfig(s *DockerDaemonSuite, c *check.C, mode string, mustExist bool) {
  2391. f, err := ioutil.TempFile("", "test-daemon-ipc-config")
  2392. c.Assert(err, checker.IsNil)
  2393. defer os.Remove(f.Name())
  2394. config := `{"default-ipc-mode": "` + mode + `"}`
  2395. _, err = f.WriteString(config)
  2396. c.Assert(f.Close(), checker.IsNil)
  2397. c.Assert(err, checker.IsNil)
  2398. s.d.StartWithBusybox(c, "--config-file", f.Name())
  2399. testDaemonIpcPrivateShareable(s.d, c, mustExist)
  2400. }
  2401. // TestDaemonIpcModePrivateFromConfig checks that "default-ipc-mode: private" config works as intended.
  2402. func (s *DockerDaemonSuite) TestDaemonIpcModePrivateFromConfig(c *check.C) {
  2403. testRequires(c, DaemonIsLinux, SameHostDaemon)
  2404. testDaemonIpcFromConfig(s, c, "private", false)
  2405. }
  2406. // TestDaemonIpcModeShareableFromConfig checks that "default-ipc-mode: shareable" config works as intended.
  2407. func (s *DockerDaemonSuite) TestDaemonIpcModeShareableFromConfig(c *check.C) {
  2408. testRequires(c, DaemonIsLinux, SameHostDaemon)
  2409. testDaemonIpcFromConfig(s, c, "shareable", true)
  2410. }
  2411. func testDaemonStartIpcMode(c *check.C, from, mode string, valid bool) {
  2412. d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
  2413. c.Logf("Checking IpcMode %s set from %s\n", mode, from)
  2414. var serr error
  2415. switch from {
  2416. case "config":
  2417. f, err := ioutil.TempFile("", "test-daemon-ipc-config")
  2418. c.Assert(err, checker.IsNil)
  2419. defer os.Remove(f.Name())
  2420. config := `{"default-ipc-mode": "` + mode + `"}`
  2421. _, err = f.WriteString(config)
  2422. c.Assert(f.Close(), checker.IsNil)
  2423. c.Assert(err, checker.IsNil)
  2424. serr = d.StartWithError("--config-file", f.Name())
  2425. case "cli":
  2426. serr = d.StartWithError("--default-ipc-mode", mode)
  2427. default:
  2428. c.Fatalf("testDaemonStartIpcMode: invalid 'from' argument")
  2429. }
  2430. if serr == nil {
  2431. d.Stop(c)
  2432. }
  2433. if valid {
  2434. c.Assert(serr, check.IsNil)
  2435. } else {
  2436. c.Assert(serr, check.NotNil)
  2437. icmd.RunCommand("grep", "-E", "IPC .* is (invalid|not supported)", d.LogFileName()).Assert(c, icmd.Success)
  2438. }
  2439. }
  2440. // TestDaemonStartWithIpcModes checks that daemon starts fine given correct
  2441. // arguments for default IPC mode, and bails out with incorrect ones.
  2442. // Both CLI option (--default-ipc-mode) and config parameter are tested.
  2443. func (s *DockerDaemonSuite) TestDaemonStartWithIpcModes(c *check.C) {
  2444. testRequires(c, DaemonIsLinux, SameHostDaemon)
  2445. ipcModes := []struct {
  2446. mode string
  2447. valid bool
  2448. }{
  2449. {"private", true},
  2450. {"shareable", true},
  2451. {"host", false},
  2452. {"container:123", false},
  2453. {"nosuchmode", false},
  2454. }
  2455. for _, from := range []string{"config", "cli"} {
  2456. for _, m := range ipcModes {
  2457. testDaemonStartIpcMode(c, from, m.mode, m.valid)
  2458. }
  2459. }
  2460. }
  2461. // TestDaemonRestartIpcMode makes sure a container keeps its ipc mode
  2462. // (derived from daemon default) even after the daemon is restarted
  2463. // with a different default ipc mode.
  2464. func (s *DockerDaemonSuite) TestDaemonRestartIpcMode(c *check.C) {
  2465. f, err := ioutil.TempFile("", "test-daemon-ipc-config-restart")
  2466. c.Assert(err, checker.IsNil)
  2467. file := f.Name()
  2468. defer os.Remove(file)
  2469. c.Assert(f.Close(), checker.IsNil)
  2470. config := []byte(`{"default-ipc-mode": "private"}`)
  2471. c.Assert(ioutil.WriteFile(file, config, 0644), checker.IsNil)
  2472. s.d.StartWithBusybox(c, "--config-file", file)
  2473. // check the container is created with private ipc mode as per daemon default
  2474. name := "ipc1"
  2475. _, err = s.d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top")
  2476. c.Assert(err, checker.IsNil)
  2477. m, err := s.d.InspectField(name, ".HostConfig.IpcMode")
  2478. c.Assert(err, check.IsNil)
  2479. c.Assert(m, checker.Equals, "private")
  2480. // restart the daemon with shareable default ipc mode
  2481. config = []byte(`{"default-ipc-mode": "shareable"}`)
  2482. c.Assert(ioutil.WriteFile(file, config, 0644), checker.IsNil)
  2483. s.d.Restart(c, "--config-file", file)
  2484. // check the container is still having private ipc mode
  2485. m, err = s.d.InspectField(name, ".HostConfig.IpcMode")
  2486. c.Assert(err, check.IsNil)
  2487. c.Assert(m, checker.Equals, "private")
  2488. // check a new container is created with shareable ipc mode as per new daemon default
  2489. name = "ipc2"
  2490. _, err = s.d.Cmd("run", "-d", "--name", name, "busybox", "top")
  2491. c.Assert(err, checker.IsNil)
  2492. m, err = s.d.InspectField(name, ".HostConfig.IpcMode")
  2493. c.Assert(err, check.IsNil)
  2494. c.Assert(m, checker.Equals, "shareable")
  2495. }
  2496. // TestFailedPluginRemove makes sure that a failed plugin remove does not block
  2497. // the daemon from starting
  2498. func (s *DockerDaemonSuite) TestFailedPluginRemove(c *check.C) {
  2499. testRequires(c, DaemonIsLinux, IsAmd64, SameHostDaemon)
  2500. d := daemon.New(c, dockerBinary, dockerdBinary)
  2501. d.Start(c)
  2502. cli, err := client.NewClient(d.Sock(), api.DefaultVersion, nil, nil)
  2503. c.Assert(err, checker.IsNil)
  2504. ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
  2505. defer cancel()
  2506. name := "test-plugin-rm-fail"
  2507. out, err := cli.PluginInstall(ctx, name, types.PluginInstallOptions{
  2508. Disabled: true,
  2509. AcceptAllPermissions: true,
  2510. RemoteRef: "cpuguy83/docker-logdriver-test",
  2511. })
  2512. c.Assert(err, checker.IsNil)
  2513. defer out.Close()
  2514. io.Copy(ioutil.Discard, out)
  2515. ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
  2516. defer cancel()
  2517. p, _, err := cli.PluginInspectWithRaw(ctx, name)
  2518. c.Assert(err, checker.IsNil)
  2519. // simulate a bad/partial removal by removing the plugin config.
  2520. configPath := filepath.Join(d.Root, "plugins", p.ID, "config.json")
  2521. c.Assert(os.Remove(configPath), checker.IsNil)
  2522. d.Restart(c)
  2523. ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
  2524. defer cancel()
  2525. _, err = cli.Ping(ctx)
  2526. c.Assert(err, checker.IsNil)
  2527. _, _, err = cli.PluginInspectWithRaw(ctx, name)
  2528. // plugin should be gone since the config.json is gone
  2529. c.Assert(err, checker.NotNil)
  2530. }