docker_cli_daemon_test.go 75 KB

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