docker_cli_daemon_test.go 102 KB

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