docker_cli_daemon_test.go 97 KB

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