docker_cli_daemon_test.go 92 KB

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