docker_cli_daemon_test.go 94 KB

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