docker_cli_daemon_test.go 71 KB

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