docker_cli_daemon_test.go 87 KB

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