docker_cli_daemon_test.go 101 KB

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