docker_cli_daemon_test.go 108 KB

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