docker_cli_daemon_test.go 96 KB

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