docker_cli_daemon_test.go 99 KB

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