docker_cli_daemon_test.go 71 KB

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