docker_cli_daemon_test.go 93 KB

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