docker_cli_daemon_test.go 74 KB

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