docker_cli_daemon_test.go 99 KB

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