docker_cli_daemon_test.go 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  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. c.Assert(s.d.StartWithBusybox("--log-driver=none"), checker.IsNil)
  1040. out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline")
  1041. c.Assert(err, checker.IsNil, check.Commentf(out))
  1042. out, err = s.d.Cmd("logs", "test")
  1043. c.Assert(err, check.NotNil, check.Commentf("Logs should fail with 'none' driver"))
  1044. expected := `"logs" command is supported only for "json-file" and "journald" logging drivers (got: none)`
  1045. c.Assert(out, checker.Contains, expected)
  1046. }
  1047. func (s *DockerDaemonSuite) TestDaemonDots(c *check.C) {
  1048. if err := s.d.StartWithBusybox(); err != nil {
  1049. c.Fatal(err)
  1050. }
  1051. // Now create 4 containers
  1052. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  1053. c.Fatalf("Error creating container: %q", err)
  1054. }
  1055. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  1056. c.Fatalf("Error creating container: %q", err)
  1057. }
  1058. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  1059. c.Fatalf("Error creating container: %q", err)
  1060. }
  1061. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  1062. c.Fatalf("Error creating container: %q", err)
  1063. }
  1064. s.d.Stop()
  1065. s.d.Start("--log-level=debug")
  1066. s.d.Stop()
  1067. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  1068. if strings.Contains(string(content), "....") {
  1069. c.Fatalf("Debug level should not have ....\n%s", string(content))
  1070. }
  1071. s.d.Start("--log-level=error")
  1072. s.d.Stop()
  1073. content, _ = ioutil.ReadFile(s.d.logFile.Name())
  1074. if strings.Contains(string(content), "....") {
  1075. c.Fatalf("Error level should not have ....\n%s", string(content))
  1076. }
  1077. s.d.Start("--log-level=info")
  1078. s.d.Stop()
  1079. content, _ = ioutil.ReadFile(s.d.logFile.Name())
  1080. if !strings.Contains(string(content), "....") {
  1081. c.Fatalf("Info level should have ....\n%s", string(content))
  1082. }
  1083. }
  1084. func (s *DockerDaemonSuite) TestDaemonUnixSockCleanedUp(c *check.C) {
  1085. dir, err := ioutil.TempDir("", "socket-cleanup-test")
  1086. if err != nil {
  1087. c.Fatal(err)
  1088. }
  1089. defer os.RemoveAll(dir)
  1090. sockPath := filepath.Join(dir, "docker.sock")
  1091. if err := s.d.Start("--host", "unix://"+sockPath); err != nil {
  1092. c.Fatal(err)
  1093. }
  1094. if _, err := os.Stat(sockPath); err != nil {
  1095. c.Fatal("socket does not exist")
  1096. }
  1097. if err := s.d.Stop(); err != nil {
  1098. c.Fatal(err)
  1099. }
  1100. if _, err := os.Stat(sockPath); err == nil || !os.IsNotExist(err) {
  1101. c.Fatal("unix socket is not cleaned up")
  1102. }
  1103. }
  1104. func (s *DockerDaemonSuite) TestDaemonWithWrongkey(c *check.C) {
  1105. type Config struct {
  1106. Crv string `json:"crv"`
  1107. D string `json:"d"`
  1108. Kid string `json:"kid"`
  1109. Kty string `json:"kty"`
  1110. X string `json:"x"`
  1111. Y string `json:"y"`
  1112. }
  1113. os.Remove("/etc/docker/key.json")
  1114. if err := s.d.Start(); err != nil {
  1115. c.Fatalf("Failed to start daemon: %v", err)
  1116. }
  1117. if err := s.d.Stop(); err != nil {
  1118. c.Fatalf("Could not stop daemon: %v", err)
  1119. }
  1120. config := &Config{}
  1121. bytes, err := ioutil.ReadFile("/etc/docker/key.json")
  1122. if err != nil {
  1123. c.Fatalf("Error reading key.json file: %s", err)
  1124. }
  1125. // byte[] to Data-Struct
  1126. if err := json.Unmarshal(bytes, &config); err != nil {
  1127. c.Fatalf("Error Unmarshal: %s", err)
  1128. }
  1129. //replace config.Kid with the fake value
  1130. config.Kid = "VSAJ:FUYR:X3H2:B2VZ:KZ6U:CJD5:K7BX:ZXHY:UZXT:P4FT:MJWG:HRJ4"
  1131. // NEW Data-Struct to byte[]
  1132. newBytes, err := json.Marshal(&config)
  1133. if err != nil {
  1134. c.Fatalf("Error Marshal: %s", err)
  1135. }
  1136. // write back
  1137. if err := ioutil.WriteFile("/etc/docker/key.json", newBytes, 0400); err != nil {
  1138. c.Fatalf("Error ioutil.WriteFile: %s", err)
  1139. }
  1140. defer os.Remove("/etc/docker/key.json")
  1141. if err := s.d.Start(); err == nil {
  1142. c.Fatalf("It should not be successful to start daemon with wrong key: %v", err)
  1143. }
  1144. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  1145. if !strings.Contains(string(content), "Public Key ID does not match") {
  1146. c.Fatal("Missing KeyID message from daemon logs")
  1147. }
  1148. }
  1149. func (s *DockerDaemonSuite) TestDaemonRestartKillWait(c *check.C) {
  1150. if err := s.d.StartWithBusybox(); err != nil {
  1151. c.Fatalf("Could not start daemon with busybox: %v", err)
  1152. }
  1153. out, err := s.d.Cmd("run", "-id", "busybox", "/bin/cat")
  1154. if err != nil {
  1155. c.Fatalf("Could not run /bin/cat: err=%v\n%s", err, out)
  1156. }
  1157. containerID := strings.TrimSpace(out)
  1158. if out, err := s.d.Cmd("kill", containerID); err != nil {
  1159. c.Fatalf("Could not kill %s: err=%v\n%s", containerID, err, out)
  1160. }
  1161. if err := s.d.Restart(); err != nil {
  1162. c.Fatalf("Could not restart daemon: %v", err)
  1163. }
  1164. errchan := make(chan error)
  1165. go func() {
  1166. if out, err := s.d.Cmd("wait", containerID); err != nil {
  1167. errchan <- fmt.Errorf("%v:\n%s", err, out)
  1168. }
  1169. close(errchan)
  1170. }()
  1171. select {
  1172. case <-time.After(5 * time.Second):
  1173. c.Fatal("Waiting on a stopped (killed) container timed out")
  1174. case err := <-errchan:
  1175. if err != nil {
  1176. c.Fatal(err)
  1177. }
  1178. }
  1179. }
  1180. // TestHttpsInfo connects via two-way authenticated HTTPS to the info endpoint
  1181. func (s *DockerDaemonSuite) TestHttpsInfo(c *check.C) {
  1182. const (
  1183. testDaemonHTTPSAddr = "tcp://localhost:4271"
  1184. )
  1185. if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  1186. "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr); err != nil {
  1187. c.Fatalf("Could not start daemon with busybox: %v", err)
  1188. }
  1189. daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"}
  1190. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1191. if err != nil {
  1192. c.Fatalf("Error Occurred: %s and output: %s", err, out)
  1193. }
  1194. }
  1195. // TestHttpsRun connects via two-way authenticated HTTPS to the create, attach, start, and wait endpoints.
  1196. // https://github.com/docker/docker/issues/19280
  1197. func (s *DockerDaemonSuite) TestHttpsRun(c *check.C) {
  1198. const (
  1199. testDaemonHTTPSAddr = "tcp://localhost:4271"
  1200. )
  1201. if err := s.d.StartWithBusybox("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  1202. "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr); err != nil {
  1203. c.Fatalf("Could not start daemon with busybox: %v", err)
  1204. }
  1205. daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"}
  1206. out, err := s.d.CmdWithArgs(daemonArgs, "run", "busybox", "echo", "TLS response")
  1207. if err != nil {
  1208. c.Fatalf("Error Occurred: %s and output: %s", err, out)
  1209. }
  1210. if !strings.Contains(out, "TLS response") {
  1211. c.Fatalf("expected output to include `TLS response`, got %v", out)
  1212. }
  1213. }
  1214. // TestTlsVerify verifies that --tlsverify=false turns on tls
  1215. func (s *DockerDaemonSuite) TestTlsVerify(c *check.C) {
  1216. out, err := exec.Command(dockerBinary, "daemon", "--tlsverify=false").CombinedOutput()
  1217. if err == nil || !strings.Contains(string(out), "Could not load X509 key pair") {
  1218. c.Fatalf("Daemon should not have started due to missing certs: %v\n%s", err, string(out))
  1219. }
  1220. }
  1221. // TestHttpsInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint
  1222. // by using a rogue client certificate and checks that it fails with the expected error.
  1223. func (s *DockerDaemonSuite) TestHttpsInfoRogueCert(c *check.C) {
  1224. const (
  1225. errBadCertificate = "remote error: bad certificate"
  1226. testDaemonHTTPSAddr = "tcp://localhost:4271"
  1227. )
  1228. if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  1229. "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr); err != nil {
  1230. c.Fatalf("Could not start daemon with busybox: %v", err)
  1231. }
  1232. daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"}
  1233. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1234. if err == nil || !strings.Contains(out, errBadCertificate) {
  1235. c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out)
  1236. }
  1237. }
  1238. // TestHttpsInfoRogueServerCert connects via two-way authenticated HTTPS to the info endpoint
  1239. // which provides a rogue server certificate and checks that it fails with the expected error
  1240. func (s *DockerDaemonSuite) TestHttpsInfoRogueServerCert(c *check.C) {
  1241. const (
  1242. errCaUnknown = "x509: certificate signed by unknown authority"
  1243. testDaemonRogueHTTPSAddr = "tcp://localhost:4272"
  1244. )
  1245. if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-rogue-cert.pem",
  1246. "--tlskey", "fixtures/https/server-rogue-key.pem", "-H", testDaemonRogueHTTPSAddr); err != nil {
  1247. c.Fatalf("Could not start daemon with busybox: %v", err)
  1248. }
  1249. daemonArgs := []string{"--host", testDaemonRogueHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"}
  1250. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1251. if err == nil || !strings.Contains(out, errCaUnknown) {
  1252. c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out)
  1253. }
  1254. }
  1255. func pingContainers(c *check.C, d *Daemon, expectFailure bool) {
  1256. var dargs []string
  1257. if d != nil {
  1258. dargs = []string{"--host", d.sock()}
  1259. }
  1260. args := append(dargs, "run", "-d", "--name", "container1", "busybox", "top")
  1261. dockerCmd(c, args...)
  1262. args = append(dargs, "run", "--rm", "--link", "container1:alias1", "busybox", "sh", "-c")
  1263. pingCmd := "ping -c 1 %s -W 1"
  1264. args = append(args, fmt.Sprintf(pingCmd, "alias1"))
  1265. _, _, err := dockerCmdWithError(args...)
  1266. if expectFailure {
  1267. c.Assert(err, check.NotNil)
  1268. } else {
  1269. c.Assert(err, check.IsNil)
  1270. }
  1271. args = append(dargs, "rm", "-f", "container1")
  1272. dockerCmd(c, args...)
  1273. }
  1274. func (s *DockerDaemonSuite) TestDaemonRestartWithSocketAsVolume(c *check.C) {
  1275. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1276. socket := filepath.Join(s.d.folder, "docker.sock")
  1277. out, err := s.d.Cmd("run", "-d", "--restart=always", "-v", socket+":/sock", "busybox")
  1278. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1279. c.Assert(s.d.Restart(), check.IsNil)
  1280. }
  1281. func (s *DockerDaemonSuite) TestCleanupMountsAfterCrash(c *check.C) {
  1282. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1283. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  1284. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1285. id := strings.TrimSpace(out)
  1286. c.Assert(s.d.cmd.Process.Signal(os.Kill), check.IsNil)
  1287. c.Assert(s.d.Start(), check.IsNil)
  1288. mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1289. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1290. comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  1291. c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1292. }
  1293. func (s *DockerDaemonSuite) TestRunContainerWithBridgeNone(c *check.C) {
  1294. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1295. c.Assert(s.d.StartWithBusybox("-b", "none"), check.IsNil)
  1296. out, err := s.d.Cmd("run", "--rm", "busybox", "ip", "l")
  1297. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1298. c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1299. check.Commentf("There shouldn't be eth0 in container in default(bridge) mode when bridge network is disabled: %s", out))
  1300. out, err = s.d.Cmd("run", "--rm", "--net=bridge", "busybox", "ip", "l")
  1301. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1302. c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1303. check.Commentf("There shouldn't be eth0 in container in bridge mode when bridge network is disabled: %s", out))
  1304. // the extra grep and awk clean up the output of `ip` to only list the number and name of
  1305. // interfaces, allowing for different versions of ip (e.g. inside and outside the container) to
  1306. // be used while still verifying that the interface list is the exact same
  1307. cmd := exec.Command("sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '")
  1308. stdout := bytes.NewBuffer(nil)
  1309. cmd.Stdout = stdout
  1310. if err := cmd.Run(); err != nil {
  1311. c.Fatal("Failed to get host network interface")
  1312. }
  1313. out, err = s.d.Cmd("run", "--rm", "--net=host", "busybox", "sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '")
  1314. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1315. c.Assert(out, check.Equals, fmt.Sprintf("%s", stdout),
  1316. check.Commentf("The network interfaces in container should be the same with host when --net=host when bridge network is disabled: %s", out))
  1317. }
  1318. func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *check.C) {
  1319. if err := s.d.StartWithBusybox(); err != nil {
  1320. t.Fatal(err)
  1321. }
  1322. if out, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top"); err != nil {
  1323. t.Fatal(out, err)
  1324. }
  1325. if err := s.d.Restart(); err != nil {
  1326. t.Fatal(err)
  1327. }
  1328. // Container 'test' should be removed without error
  1329. if out, err := s.d.Cmd("rm", "test"); err != nil {
  1330. t.Fatal(out, err)
  1331. }
  1332. }
  1333. func (s *DockerDaemonSuite) TestDaemonRestartCleanupNetns(c *check.C) {
  1334. if err := s.d.StartWithBusybox(); err != nil {
  1335. c.Fatal(err)
  1336. }
  1337. out, err := s.d.Cmd("run", "--name", "netns", "-d", "busybox", "top")
  1338. if err != nil {
  1339. c.Fatal(out, err)
  1340. }
  1341. // Get sandbox key via inspect
  1342. out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.SandboxKey}}'", "netns")
  1343. if err != nil {
  1344. c.Fatalf("Error inspecting container: %s, %v", out, err)
  1345. }
  1346. fileName := strings.Trim(out, " \r\n'")
  1347. if out, err := s.d.Cmd("stop", "netns"); err != nil {
  1348. c.Fatal(out, err)
  1349. }
  1350. // Test if the file still exists
  1351. out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", fileName))
  1352. out = strings.TrimSpace(out)
  1353. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1354. c.Assert(out, check.Equals, fileName, check.Commentf("Output: %s", out))
  1355. // Remove the container and restart the daemon
  1356. if out, err := s.d.Cmd("rm", "netns"); err != nil {
  1357. c.Fatal(out, err)
  1358. }
  1359. if err := s.d.Restart(); err != nil {
  1360. c.Fatal(err)
  1361. }
  1362. // Test again and see now the netns file does not exist
  1363. out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", fileName))
  1364. out = strings.TrimSpace(out)
  1365. c.Assert(err, check.Not(check.IsNil), check.Commentf("Output: %s", out))
  1366. }
  1367. // tests regression detailed in #13964 where DOCKER_TLS_VERIFY env is ignored
  1368. func (s *DockerDaemonSuite) TestDaemonNoTlsCliTlsVerifyWithEnv(c *check.C) {
  1369. host := "tcp://localhost:4271"
  1370. c.Assert(s.d.Start("-H", host), check.IsNil)
  1371. cmd := exec.Command(dockerBinary, "-H", host, "info")
  1372. cmd.Env = []string{"DOCKER_TLS_VERIFY=1", "DOCKER_CERT_PATH=fixtures/https"}
  1373. out, _, err := runCommandWithOutput(cmd)
  1374. c.Assert(err, check.Not(check.IsNil), check.Commentf("%s", out))
  1375. c.Assert(strings.Contains(out, "error occurred trying to connect"), check.Equals, true)
  1376. }
  1377. func setupV6() error {
  1378. // Hack to get the right IPv6 address on docker0, which has already been created
  1379. return exec.Command("ip", "addr", "add", "fe80::1/64", "dev", "docker0").Run()
  1380. }
  1381. func teardownV6() error {
  1382. return exec.Command("ip", "addr", "del", "fe80::1/64", "dev", "docker0").Run()
  1383. }
  1384. func (s *DockerDaemonSuite) TestDaemonRestartWithContainerWithRestartPolicyAlways(c *check.C) {
  1385. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1386. out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top")
  1387. c.Assert(err, check.IsNil)
  1388. id := strings.TrimSpace(out)
  1389. _, err = s.d.Cmd("stop", id)
  1390. c.Assert(err, check.IsNil)
  1391. _, err = s.d.Cmd("wait", id)
  1392. c.Assert(err, check.IsNil)
  1393. out, err = s.d.Cmd("ps", "-q")
  1394. c.Assert(err, check.IsNil)
  1395. c.Assert(out, check.Equals, "")
  1396. c.Assert(s.d.Restart(), check.IsNil)
  1397. out, err = s.d.Cmd("ps", "-q")
  1398. c.Assert(err, check.IsNil)
  1399. c.Assert(strings.TrimSpace(out), check.Equals, id[:12])
  1400. }
  1401. func (s *DockerDaemonSuite) TestDaemonWideLogConfig(c *check.C) {
  1402. if err := s.d.StartWithBusybox("--log-driver=json-file", "--log-opt=max-size=1k"); err != nil {
  1403. c.Fatal(err)
  1404. }
  1405. out, err := s.d.Cmd("run", "-d", "--name=logtest", "busybox", "top")
  1406. c.Assert(err, check.IsNil, check.Commentf("Output: %s, err: %v", out, err))
  1407. out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Config }}", "logtest")
  1408. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1409. cfg := strings.TrimSpace(out)
  1410. if cfg != "map[max-size:1k]" {
  1411. c.Fatalf("Unexpected log-opt: %s, expected map[max-size:1k]", cfg)
  1412. }
  1413. }
  1414. func (s *DockerDaemonSuite) TestDaemonRestartWithPausedContainer(c *check.C) {
  1415. if err := s.d.StartWithBusybox(); err != nil {
  1416. c.Fatal(err)
  1417. }
  1418. if out, err := s.d.Cmd("run", "-i", "-d", "--name", "test", "busybox", "top"); err != nil {
  1419. c.Fatal(err, out)
  1420. }
  1421. if out, err := s.d.Cmd("pause", "test"); err != nil {
  1422. c.Fatal(err, out)
  1423. }
  1424. if err := s.d.Restart(); err != nil {
  1425. c.Fatal(err)
  1426. }
  1427. errchan := make(chan error)
  1428. go func() {
  1429. out, err := s.d.Cmd("start", "test")
  1430. if err != nil {
  1431. errchan <- fmt.Errorf("%v:\n%s", err, out)
  1432. }
  1433. name := strings.TrimSpace(out)
  1434. if name != "test" {
  1435. errchan <- fmt.Errorf("Paused container start error on docker daemon restart, expected 'test' but got '%s'", name)
  1436. }
  1437. close(errchan)
  1438. }()
  1439. select {
  1440. case <-time.After(5 * time.Second):
  1441. c.Fatal("Waiting on start a container timed out")
  1442. case err := <-errchan:
  1443. if err != nil {
  1444. c.Fatal(err)
  1445. }
  1446. }
  1447. }
  1448. func (s *DockerDaemonSuite) TestDaemonRestartRmVolumeInUse(c *check.C) {
  1449. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1450. out, err := s.d.Cmd("create", "-v", "test:/foo", "busybox")
  1451. c.Assert(err, check.IsNil, check.Commentf(out))
  1452. c.Assert(s.d.Restart(), check.IsNil)
  1453. out, err = s.d.Cmd("volume", "rm", "test")
  1454. c.Assert(err, check.NotNil, check.Commentf("should not be able to remove in use volume after daemon restart"))
  1455. c.Assert(out, checker.Contains, "in use")
  1456. }
  1457. func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *check.C) {
  1458. c.Assert(s.d.Start(), check.IsNil)
  1459. _, err := s.d.Cmd("volume", "create", "--name", "test")
  1460. c.Assert(err, check.IsNil)
  1461. c.Assert(s.d.Restart(), check.IsNil)
  1462. _, err = s.d.Cmd("volume", "inspect", "test")
  1463. c.Assert(err, check.IsNil)
  1464. }
  1465. func (s *DockerDaemonSuite) TestDaemonCorruptedLogDriverAddress(c *check.C) {
  1466. c.Assert(s.d.Start("--log-driver=syslog", "--log-opt", "syslog-address=corrupted:42"), check.NotNil)
  1467. expected := "Failed to set log opts: syslog-address should be in form proto://address"
  1468. runCmd := exec.Command("grep", expected, s.d.LogFileName())
  1469. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  1470. c.Fatalf("Expected %q message; but doesn't exist in log: %q, err: %v", expected, out, err)
  1471. }
  1472. }
  1473. func (s *DockerDaemonSuite) TestDaemonCorruptedFluentdAddress(c *check.C) {
  1474. c.Assert(s.d.Start("--log-driver=fluentd", "--log-opt", "fluentd-address=corrupted:c"), check.NotNil)
  1475. expected := "Failed to set log opts: invalid fluentd-address corrupted:c: "
  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) TestDaemonStartWithoutHost(c *check.C) {
  1482. s.d.useDefaultHost = true
  1483. defer func() {
  1484. s.d.useDefaultHost = false
  1485. }()
  1486. c.Assert(s.d.Start(), check.IsNil)
  1487. }
  1488. func (s *DockerDaemonSuite) TestDaemonStartWithDefalutTlsHost(c *check.C) {
  1489. s.d.useDefaultTLSHost = true
  1490. defer func() {
  1491. s.d.useDefaultTLSHost = false
  1492. }()
  1493. if err := s.d.Start(
  1494. "--tlsverify",
  1495. "--tlscacert", "fixtures/https/ca.pem",
  1496. "--tlscert", "fixtures/https/server-cert.pem",
  1497. "--tlskey", "fixtures/https/server-key.pem"); err != nil {
  1498. c.Fatalf("Could not start daemon: %v", err)
  1499. }
  1500. // The client with --tlsverify should also use default host localhost:2376
  1501. tmpHost := os.Getenv("DOCKER_HOST")
  1502. defer func() {
  1503. os.Setenv("DOCKER_HOST", tmpHost)
  1504. }()
  1505. os.Setenv("DOCKER_HOST", "")
  1506. out, _ := dockerCmd(
  1507. c,
  1508. "--tlsverify",
  1509. "--tlscacert", "fixtures/https/ca.pem",
  1510. "--tlscert", "fixtures/https/client-cert.pem",
  1511. "--tlskey", "fixtures/https/client-key.pem",
  1512. "version",
  1513. )
  1514. if !strings.Contains(out, "Server") {
  1515. c.Fatalf("docker version should return information of server side")
  1516. }
  1517. }
  1518. func (s *DockerDaemonSuite) TestBridgeIPIsExcludedFromAllocatorPool(c *check.C) {
  1519. defaultNetworkBridge := "docker0"
  1520. deleteInterface(c, defaultNetworkBridge)
  1521. bridgeIP := "192.169.1.1"
  1522. bridgeRange := bridgeIP + "/30"
  1523. err := s.d.StartWithBusybox("--bip", bridgeRange)
  1524. c.Assert(err, check.IsNil)
  1525. defer s.d.Restart()
  1526. var cont int
  1527. for {
  1528. contName := fmt.Sprintf("container%d", cont)
  1529. _, err = s.d.Cmd("run", "--name", contName, "-d", "busybox", "/bin/sleep", "2")
  1530. if err != nil {
  1531. // pool exhausted
  1532. break
  1533. }
  1534. ip, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.IPAddress}}'", contName)
  1535. c.Assert(err, check.IsNil)
  1536. c.Assert(ip, check.Not(check.Equals), bridgeIP)
  1537. cont++
  1538. }
  1539. }
  1540. // Test daemon for no space left on device error
  1541. func (s *DockerDaemonSuite) TestDaemonNoSpaceleftOnDeviceError(c *check.C) {
  1542. testRequires(c, SameHostDaemon, DaemonIsLinux, Network)
  1543. // create a 2MiB image and mount it as graph root
  1544. cmd := exec.Command("dd", "of=/tmp/testfs.img", "bs=1M", "seek=2", "count=0")
  1545. if err := cmd.Run(); err != nil {
  1546. c.Fatalf("dd failed: %v", err)
  1547. }
  1548. cmd = exec.Command("mkfs.ext4", "-F", "/tmp/testfs.img")
  1549. if err := cmd.Run(); err != nil {
  1550. c.Fatalf("mkfs.ext4 failed: %v", err)
  1551. }
  1552. cmd = exec.Command("mkdir", "-p", "/tmp/testfs-mount")
  1553. if err := cmd.Run(); err != nil {
  1554. c.Fatalf("mkdir failed: %v", err)
  1555. }
  1556. cmd = exec.Command("mount", "-t", "ext4", "-no", "loop,rw", "/tmp/testfs.img", "/tmp/testfs-mount")
  1557. if err := cmd.Run(); err != nil {
  1558. c.Fatalf("mount failed: %v", err)
  1559. }
  1560. err := s.d.Start("--graph", "/tmp/testfs-mount")
  1561. c.Assert(err, check.IsNil)
  1562. // pull a repository large enough to fill the mount point
  1563. out, err := s.d.Cmd("pull", "registry:2")
  1564. c.Assert(out, checker.Contains, "no space left on device")
  1565. }
  1566. // Test daemon restart with container links + auto restart
  1567. func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) {
  1568. d := NewDaemon(c)
  1569. err := d.StartWithBusybox()
  1570. c.Assert(err, checker.IsNil)
  1571. parent1Args := []string{}
  1572. parent2Args := []string{}
  1573. wg := sync.WaitGroup{}
  1574. maxChildren := 10
  1575. chErr := make(chan error, maxChildren)
  1576. for i := 0; i < maxChildren; i++ {
  1577. wg.Add(1)
  1578. name := fmt.Sprintf("test%d", i)
  1579. if i < maxChildren/2 {
  1580. parent1Args = append(parent1Args, []string{"--link", name}...)
  1581. } else {
  1582. parent2Args = append(parent2Args, []string{"--link", name}...)
  1583. }
  1584. go func() {
  1585. _, err = d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top")
  1586. chErr <- err
  1587. wg.Done()
  1588. }()
  1589. }
  1590. wg.Wait()
  1591. close(chErr)
  1592. for err := range chErr {
  1593. c.Assert(err, check.IsNil)
  1594. }
  1595. parent1Args = append([]string{"run", "-d"}, parent1Args...)
  1596. parent1Args = append(parent1Args, []string{"--name=parent1", "--restart=always", "busybox", "top"}...)
  1597. parent2Args = append([]string{"run", "-d"}, parent2Args...)
  1598. parent2Args = append(parent2Args, []string{"--name=parent2", "--restart=always", "busybox", "top"}...)
  1599. _, err = d.Cmd(parent1Args[0], parent1Args[1:]...)
  1600. c.Assert(err, check.IsNil)
  1601. _, err = d.Cmd(parent2Args[0], parent2Args[1:]...)
  1602. c.Assert(err, check.IsNil)
  1603. err = d.Stop()
  1604. c.Assert(err, check.IsNil)
  1605. // clear the log file -- we don't need any of it but may for the next part
  1606. // can ignore the error here, this is just a cleanup
  1607. os.Truncate(d.LogFileName(), 0)
  1608. err = d.Start()
  1609. c.Assert(err, check.IsNil)
  1610. for _, num := range []string{"1", "2"} {
  1611. out, err := d.Cmd("inspect", "-f", "{{ .State.Running }}", "parent"+num)
  1612. c.Assert(err, check.IsNil)
  1613. if strings.TrimSpace(out) != "true" {
  1614. log, _ := ioutil.ReadFile(d.LogFileName())
  1615. c.Fatalf("parent container is not running\n%s", string(log))
  1616. }
  1617. }
  1618. }
  1619. func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *check.C) {
  1620. testRequires(c, DaemonIsLinux)
  1621. cgroupParent := "test"
  1622. name := "cgroup-test"
  1623. err := s.d.StartWithBusybox("--cgroup-parent", cgroupParent)
  1624. c.Assert(err, check.IsNil)
  1625. defer s.d.Restart()
  1626. out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup")
  1627. c.Assert(err, checker.IsNil)
  1628. cgroupPaths := parseCgroupPaths(string(out))
  1629. c.Assert(len(cgroupPaths), checker.Not(checker.Equals), 0, check.Commentf("unexpected output - %q", string(out)))
  1630. out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name)
  1631. c.Assert(err, checker.IsNil)
  1632. id := strings.TrimSpace(string(out))
  1633. expectedCgroup := path.Join(cgroupParent, id)
  1634. found := false
  1635. for _, path := range cgroupPaths {
  1636. if strings.HasSuffix(path, expectedCgroup) {
  1637. found = true
  1638. break
  1639. }
  1640. }
  1641. c.Assert(found, checker.True, check.Commentf("Cgroup path for container (%s) doesn't found in cgroups file: %s", expectedCgroup, cgroupPaths))
  1642. }
  1643. func (s *DockerDaemonSuite) TestDaemonRestartWithLinks(c *check.C) {
  1644. testRequires(c, DaemonIsLinux) // Windows does not support links
  1645. err := s.d.StartWithBusybox()
  1646. c.Assert(err, check.IsNil)
  1647. out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1648. c.Assert(err, check.IsNil, check.Commentf(out))
  1649. out, err = s.d.Cmd("run", "--name=test2", "--link", "test:abc", "busybox", "sh", "-c", "ping -c 1 -w 1 abc")
  1650. c.Assert(err, check.IsNil, check.Commentf(out))
  1651. c.Assert(s.d.Restart(), check.IsNil)
  1652. // should fail since test is not running yet
  1653. out, err = s.d.Cmd("start", "test2")
  1654. c.Assert(err, check.NotNil, check.Commentf(out))
  1655. out, err = s.d.Cmd("start", "test")
  1656. c.Assert(err, check.IsNil, check.Commentf(out))
  1657. out, err = s.d.Cmd("start", "-a", "test2")
  1658. c.Assert(err, check.IsNil, check.Commentf(out))
  1659. c.Assert(strings.Contains(out, "1 packets transmitted, 1 packets received"), check.Equals, true, check.Commentf(out))
  1660. }
  1661. func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *check.C) {
  1662. testRequires(c, DaemonIsLinux) // Windows does not support links
  1663. err := s.d.StartWithBusybox()
  1664. c.Assert(err, check.IsNil)
  1665. out, err := s.d.Cmd("create", "--name=test", "busybox")
  1666. c.Assert(err, check.IsNil, check.Commentf(out))
  1667. out, err = s.d.Cmd("run", "-d", "--name=test2", "busybox", "top")
  1668. c.Assert(err, check.IsNil, check.Commentf(out))
  1669. test2ID := strings.TrimSpace(out)
  1670. out, err = s.d.Cmd("run", "-d", "--name=test3", "--link", "test2:abc", "busybox", "top")
  1671. test3ID := strings.TrimSpace(out)
  1672. c.Assert(s.d.Restart(), check.IsNil)
  1673. out, err = s.d.Cmd("create", "--name=test", "busybox")
  1674. c.Assert(err, check.NotNil, check.Commentf("expected error trying to create container with duplicate name"))
  1675. // this one is no longer needed, removing simplifies the remainder of the test
  1676. out, err = s.d.Cmd("rm", "-f", "test")
  1677. c.Assert(err, check.IsNil, check.Commentf(out))
  1678. out, err = s.d.Cmd("ps", "-a", "--no-trunc")
  1679. c.Assert(err, check.IsNil, check.Commentf(out))
  1680. lines := strings.Split(strings.TrimSpace(out), "\n")[1:]
  1681. test2validated := false
  1682. test3validated := false
  1683. for _, line := range lines {
  1684. fields := strings.Fields(line)
  1685. names := fields[len(fields)-1]
  1686. switch fields[0] {
  1687. case test2ID:
  1688. c.Assert(names, check.Equals, "test2,test3/abc")
  1689. test2validated = true
  1690. case test3ID:
  1691. c.Assert(names, check.Equals, "test3")
  1692. test3validated = true
  1693. }
  1694. }
  1695. c.Assert(test2validated, check.Equals, true)
  1696. c.Assert(test3validated, check.Equals, true)
  1697. }
  1698. // TestRunLinksChanged checks that creating a new container with the same name does not update links
  1699. // this ensures that the old, pre gh#16032 functionality continues on
  1700. func (s *DockerDaemonSuite) TestRunLinksChanged(c *check.C) {
  1701. testRequires(c, DaemonIsLinux) // Windows does not support links
  1702. err := s.d.StartWithBusybox()
  1703. c.Assert(err, check.IsNil)
  1704. out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1705. c.Assert(err, check.IsNil, check.Commentf(out))
  1706. out, err = s.d.Cmd("run", "--name=test2", "--link=test:abc", "busybox", "sh", "-c", "ping -c 1 abc")
  1707. c.Assert(err, check.IsNil, check.Commentf(out))
  1708. c.Assert(out, checker.Contains, "1 packets transmitted, 1 packets received")
  1709. out, err = s.d.Cmd("rm", "-f", "test")
  1710. c.Assert(err, check.IsNil, check.Commentf(out))
  1711. out, err = s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1712. c.Assert(err, check.IsNil, check.Commentf(out))
  1713. out, err = s.d.Cmd("start", "-a", "test2")
  1714. c.Assert(err, check.NotNil, check.Commentf(out))
  1715. c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  1716. err = s.d.Restart()
  1717. c.Assert(err, check.IsNil)
  1718. out, err = s.d.Cmd("start", "-a", "test2")
  1719. c.Assert(err, check.NotNil, check.Commentf(out))
  1720. c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  1721. }
  1722. func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *check.C) {
  1723. testRequires(c, DaemonIsLinux, NotPpc64le)
  1724. newD := NewDaemon(c)
  1725. infoLog := "\x1b[34mINFO\x1b"
  1726. p, tty, err := pty.Open()
  1727. c.Assert(err, checker.IsNil)
  1728. defer func() {
  1729. tty.Close()
  1730. p.Close()
  1731. }()
  1732. b := bytes.NewBuffer(nil)
  1733. go io.Copy(b, p)
  1734. // Enable coloring explicitly
  1735. newD.StartWithLogFile(tty, "--raw-logs=false")
  1736. newD.Stop()
  1737. c.Assert(b.String(), checker.Contains, infoLog)
  1738. b.Reset()
  1739. // Disable coloring explicitly
  1740. newD.StartWithLogFile(tty, "--raw-logs=true")
  1741. newD.Stop()
  1742. c.Assert(b.String(), check.Not(checker.Contains), infoLog)
  1743. }
  1744. func (s *DockerDaemonSuite) TestDaemonDebugLog(c *check.C) {
  1745. testRequires(c, DaemonIsLinux, NotPpc64le)
  1746. newD := NewDaemon(c)
  1747. debugLog := "\x1b[37mDEBU\x1b"
  1748. p, tty, err := pty.Open()
  1749. c.Assert(err, checker.IsNil)
  1750. defer func() {
  1751. tty.Close()
  1752. p.Close()
  1753. }()
  1754. b := bytes.NewBuffer(nil)
  1755. go io.Copy(b, p)
  1756. newD.StartWithLogFile(tty, "--debug")
  1757. newD.Stop()
  1758. c.Assert(b.String(), checker.Contains, debugLog)
  1759. }
  1760. func (s *DockerSuite) TestDaemonDiscoveryBackendConfigReload(c *check.C) {
  1761. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1762. // daemon config file
  1763. daemonConfig := `{ "debug" : false }`
  1764. configFilePath := "test.json"
  1765. configFile, err := os.Create(configFilePath)
  1766. c.Assert(err, checker.IsNil)
  1767. fmt.Fprintf(configFile, "%s", daemonConfig)
  1768. d := NewDaemon(c)
  1769. err = d.Start(fmt.Sprintf("--config-file=%s", configFilePath))
  1770. c.Assert(err, checker.IsNil)
  1771. defer d.Stop()
  1772. // daemon config file
  1773. daemonConfig = `{
  1774. "cluster-store": "consul://consuladdr:consulport/some/path",
  1775. "cluster-advertise": "192.168.56.100:0",
  1776. "debug" : false
  1777. }`
  1778. configFile.Close()
  1779. os.Remove(configFilePath)
  1780. configFile, err = os.Create(configFilePath)
  1781. c.Assert(err, checker.IsNil)
  1782. fmt.Fprintf(configFile, "%s", daemonConfig)
  1783. syscall.Kill(d.cmd.Process.Pid, syscall.SIGHUP)
  1784. time.Sleep(3 * time.Second)
  1785. out, err := d.Cmd("info")
  1786. c.Assert(err, checker.IsNil)
  1787. c.Assert(out, checker.Contains, fmt.Sprintf("Cluster store: consul://consuladdr:consulport/some/path"))
  1788. c.Assert(out, checker.Contains, fmt.Sprintf("Cluster advertise: 192.168.56.100:0"))
  1789. }