docker_cli_daemon_test.go 104 KB

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