docker_cli_daemon_test.go 102 KB

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