docker_cli_daemon_test.go 73 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", "--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. // os.Kill should kill daemon ungracefully, leaving behind container mounts.
  1286. // A subsequent daemon restart shoud clean up said mounts.
  1287. func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonKill(c *check.C) {
  1288. testRequires(c, NotExperimentalDaemon)
  1289. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1290. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  1291. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1292. id := strings.TrimSpace(out)
  1293. c.Assert(s.d.cmd.Process.Signal(os.Kill), check.IsNil)
  1294. mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1295. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1296. // container mounts should exist even after daemon has crashed.
  1297. comment := check.Commentf("%s should stay mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  1298. c.Assert(strings.Contains(string(mountOut), id), check.Equals, true, comment)
  1299. // restart daemon.
  1300. if err := s.d.Restart(); err != nil {
  1301. c.Fatal(err)
  1302. }
  1303. // Now, container mounts should be gone.
  1304. mountOut, err = ioutil.ReadFile("/proc/self/mountinfo")
  1305. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1306. comment = check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  1307. c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1308. }
  1309. func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *check.C) {
  1310. if err := s.d.StartWithBusybox(); err != nil {
  1311. t.Fatal(err)
  1312. }
  1313. if out, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top"); err != nil {
  1314. t.Fatal(out, err)
  1315. }
  1316. if err := s.d.Restart(); err != nil {
  1317. t.Fatal(err)
  1318. }
  1319. // Container 'test' should be removed without error
  1320. if out, err := s.d.Cmd("rm", "test"); err != nil {
  1321. t.Fatal(out, err)
  1322. }
  1323. }
  1324. func (s *DockerDaemonSuite) TestDaemonRestartCleanupNetns(c *check.C) {
  1325. if err := s.d.StartWithBusybox(); err != nil {
  1326. c.Fatal(err)
  1327. }
  1328. out, err := s.d.Cmd("run", "--name", "netns", "-d", "busybox", "top")
  1329. if err != nil {
  1330. c.Fatal(out, err)
  1331. }
  1332. // Get sandbox key via inspect
  1333. out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.SandboxKey}}'", "netns")
  1334. if err != nil {
  1335. c.Fatalf("Error inspecting container: %s, %v", out, err)
  1336. }
  1337. fileName := strings.Trim(out, " \r\n'")
  1338. if out, err := s.d.Cmd("stop", "netns"); err != nil {
  1339. c.Fatal(out, err)
  1340. }
  1341. // Test if the file still exists
  1342. out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", fileName))
  1343. out = strings.TrimSpace(out)
  1344. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1345. c.Assert(out, check.Equals, fileName, check.Commentf("Output: %s", out))
  1346. // Remove the container and restart the daemon
  1347. if out, err := s.d.Cmd("rm", "netns"); err != nil {
  1348. c.Fatal(out, err)
  1349. }
  1350. if err := s.d.Restart(); err != nil {
  1351. c.Fatal(err)
  1352. }
  1353. // Test again and see now the netns file does not exist
  1354. out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", fileName))
  1355. out = strings.TrimSpace(out)
  1356. c.Assert(err, check.Not(check.IsNil), check.Commentf("Output: %s", out))
  1357. }
  1358. // tests regression detailed in #13964 where DOCKER_TLS_VERIFY env is ignored
  1359. func (s *DockerDaemonSuite) TestDaemonNoTlsCliTlsVerifyWithEnv(c *check.C) {
  1360. host := "tcp://localhost:4271"
  1361. c.Assert(s.d.Start("-H", host), check.IsNil)
  1362. cmd := exec.Command(dockerBinary, "-H", host, "info")
  1363. cmd.Env = []string{"DOCKER_TLS_VERIFY=1", "DOCKER_CERT_PATH=fixtures/https"}
  1364. out, _, err := runCommandWithOutput(cmd)
  1365. c.Assert(err, check.Not(check.IsNil), check.Commentf("%s", out))
  1366. c.Assert(strings.Contains(out, "error occurred trying to connect"), check.Equals, true)
  1367. }
  1368. func setupV6() error {
  1369. // Hack to get the right IPv6 address on docker0, which has already been created
  1370. return exec.Command("ip", "addr", "add", "fe80::1/64", "dev", "docker0").Run()
  1371. }
  1372. func teardownV6() error {
  1373. return exec.Command("ip", "addr", "del", "fe80::1/64", "dev", "docker0").Run()
  1374. }
  1375. func (s *DockerDaemonSuite) TestDaemonRestartWithContainerWithRestartPolicyAlways(c *check.C) {
  1376. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1377. out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top")
  1378. c.Assert(err, check.IsNil)
  1379. id := strings.TrimSpace(out)
  1380. _, err = s.d.Cmd("stop", id)
  1381. c.Assert(err, check.IsNil)
  1382. _, err = s.d.Cmd("wait", id)
  1383. c.Assert(err, check.IsNil)
  1384. out, err = s.d.Cmd("ps", "-q")
  1385. c.Assert(err, check.IsNil)
  1386. c.Assert(out, check.Equals, "")
  1387. c.Assert(s.d.Restart(), check.IsNil)
  1388. out, err = s.d.Cmd("ps", "-q")
  1389. c.Assert(err, check.IsNil)
  1390. c.Assert(strings.TrimSpace(out), check.Equals, id[:12])
  1391. }
  1392. func (s *DockerDaemonSuite) TestDaemonWideLogConfig(c *check.C) {
  1393. if err := s.d.StartWithBusybox("--log-driver=json-file", "--log-opt=max-size=1k"); err != nil {
  1394. c.Fatal(err)
  1395. }
  1396. out, err := s.d.Cmd("run", "-d", "--name=logtest", "busybox", "top")
  1397. c.Assert(err, check.IsNil, check.Commentf("Output: %s, err: %v", out, err))
  1398. out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Config }}", "logtest")
  1399. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1400. cfg := strings.TrimSpace(out)
  1401. if cfg != "map[max-size:1k]" {
  1402. c.Fatalf("Unexpected log-opt: %s, expected map[max-size:1k]", cfg)
  1403. }
  1404. }
  1405. func (s *DockerDaemonSuite) TestDaemonRestartWithPausedContainer(c *check.C) {
  1406. if err := s.d.StartWithBusybox(); err != nil {
  1407. c.Fatal(err)
  1408. }
  1409. if out, err := s.d.Cmd("run", "-i", "-d", "--name", "test", "busybox", "top"); err != nil {
  1410. c.Fatal(err, out)
  1411. }
  1412. if out, err := s.d.Cmd("pause", "test"); err != nil {
  1413. c.Fatal(err, out)
  1414. }
  1415. if err := s.d.Restart(); err != nil {
  1416. c.Fatal(err)
  1417. }
  1418. errchan := make(chan error)
  1419. go func() {
  1420. out, err := s.d.Cmd("start", "test")
  1421. if err != nil {
  1422. errchan <- fmt.Errorf("%v:\n%s", err, out)
  1423. }
  1424. name := strings.TrimSpace(out)
  1425. if name != "test" {
  1426. errchan <- fmt.Errorf("Paused container start error on docker daemon restart, expected 'test' but got '%s'", name)
  1427. }
  1428. close(errchan)
  1429. }()
  1430. select {
  1431. case <-time.After(5 * time.Second):
  1432. c.Fatal("Waiting on start a container timed out")
  1433. case err := <-errchan:
  1434. if err != nil {
  1435. c.Fatal(err)
  1436. }
  1437. }
  1438. }
  1439. func (s *DockerDaemonSuite) TestDaemonRestartRmVolumeInUse(c *check.C) {
  1440. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1441. out, err := s.d.Cmd("create", "-v", "test:/foo", "busybox")
  1442. c.Assert(err, check.IsNil, check.Commentf(out))
  1443. c.Assert(s.d.Restart(), check.IsNil)
  1444. out, err = s.d.Cmd("volume", "rm", "test")
  1445. c.Assert(err, check.NotNil, check.Commentf("should not be able to remove in use volume after daemon restart"))
  1446. c.Assert(out, checker.Contains, "in use")
  1447. }
  1448. func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *check.C) {
  1449. c.Assert(s.d.Start(), check.IsNil)
  1450. _, err := s.d.Cmd("volume", "create", "--name", "test")
  1451. c.Assert(err, check.IsNil)
  1452. c.Assert(s.d.Restart(), check.IsNil)
  1453. _, err = s.d.Cmd("volume", "inspect", "test")
  1454. c.Assert(err, check.IsNil)
  1455. }
  1456. func (s *DockerDaemonSuite) TestDaemonCorruptedLogDriverAddress(c *check.C) {
  1457. c.Assert(s.d.Start("--log-driver=syslog", "--log-opt", "syslog-address=corrupted:42"), check.NotNil)
  1458. expected := "Failed to set log opts: syslog-address should be in form proto://address"
  1459. runCmd := exec.Command("grep", expected, s.d.LogFileName())
  1460. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  1461. c.Fatalf("Expected %q message; but doesn't exist in log: %q, err: %v", expected, out, err)
  1462. }
  1463. }
  1464. func (s *DockerDaemonSuite) TestDaemonCorruptedFluentdAddress(c *check.C) {
  1465. c.Assert(s.d.Start("--log-driver=fluentd", "--log-opt", "fluentd-address=corrupted:c"), check.NotNil)
  1466. expected := "Failed to set log opts: invalid fluentd-address corrupted:c: "
  1467. runCmd := exec.Command("grep", expected, s.d.LogFileName())
  1468. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  1469. c.Fatalf("Expected %q message; but doesn't exist in log: %q, err: %v", expected, out, err)
  1470. }
  1471. }
  1472. func (s *DockerDaemonSuite) TestDaemonStartWithoutHost(c *check.C) {
  1473. s.d.useDefaultHost = true
  1474. defer func() {
  1475. s.d.useDefaultHost = false
  1476. }()
  1477. c.Assert(s.d.Start(), check.IsNil)
  1478. }
  1479. func (s *DockerDaemonSuite) TestDaemonStartWithDefalutTlsHost(c *check.C) {
  1480. s.d.useDefaultTLSHost = true
  1481. defer func() {
  1482. s.d.useDefaultTLSHost = false
  1483. }()
  1484. if err := s.d.Start(
  1485. "--tlsverify",
  1486. "--tlscacert", "fixtures/https/ca.pem",
  1487. "--tlscert", "fixtures/https/server-cert.pem",
  1488. "--tlskey", "fixtures/https/server-key.pem"); err != nil {
  1489. c.Fatalf("Could not start daemon: %v", err)
  1490. }
  1491. // The client with --tlsverify should also use default host localhost:2376
  1492. tmpHost := os.Getenv("DOCKER_HOST")
  1493. defer func() {
  1494. os.Setenv("DOCKER_HOST", tmpHost)
  1495. }()
  1496. os.Setenv("DOCKER_HOST", "")
  1497. out, _ := dockerCmd(
  1498. c,
  1499. "--tlsverify",
  1500. "--tlscacert", "fixtures/https/ca.pem",
  1501. "--tlscert", "fixtures/https/client-cert.pem",
  1502. "--tlskey", "fixtures/https/client-key.pem",
  1503. "version",
  1504. )
  1505. if !strings.Contains(out, "Server") {
  1506. c.Fatalf("docker version should return information of server side")
  1507. }
  1508. }
  1509. func (s *DockerDaemonSuite) TestBridgeIPIsExcludedFromAllocatorPool(c *check.C) {
  1510. defaultNetworkBridge := "docker0"
  1511. deleteInterface(c, defaultNetworkBridge)
  1512. bridgeIP := "192.169.1.1"
  1513. bridgeRange := bridgeIP + "/30"
  1514. err := s.d.StartWithBusybox("--bip", bridgeRange)
  1515. c.Assert(err, check.IsNil)
  1516. defer s.d.Restart()
  1517. var cont int
  1518. for {
  1519. contName := fmt.Sprintf("container%d", cont)
  1520. _, err = s.d.Cmd("run", "--name", contName, "-d", "busybox", "/bin/sleep", "2")
  1521. if err != nil {
  1522. // pool exhausted
  1523. break
  1524. }
  1525. ip, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.IPAddress}}'", contName)
  1526. c.Assert(err, check.IsNil)
  1527. c.Assert(ip, check.Not(check.Equals), bridgeIP)
  1528. cont++
  1529. }
  1530. }
  1531. // Test daemon for no space left on device error
  1532. func (s *DockerDaemonSuite) TestDaemonNoSpaceleftOnDeviceError(c *check.C) {
  1533. testRequires(c, SameHostDaemon, DaemonIsLinux, Network)
  1534. // create a 2MiB image and mount it as graph root
  1535. cmd := exec.Command("dd", "of=/tmp/testfs.img", "bs=1M", "seek=2", "count=0")
  1536. if err := cmd.Run(); err != nil {
  1537. c.Fatalf("dd failed: %v", err)
  1538. }
  1539. cmd = exec.Command("mkfs.ext4", "-F", "/tmp/testfs.img")
  1540. if err := cmd.Run(); err != nil {
  1541. c.Fatalf("mkfs.ext4 failed: %v", err)
  1542. }
  1543. cmd = exec.Command("mkdir", "-p", "/tmp/testfs-mount")
  1544. if err := cmd.Run(); err != nil {
  1545. c.Fatalf("mkdir failed: %v", err)
  1546. }
  1547. cmd = exec.Command("mount", "-t", "ext4", "-no", "loop,rw", "/tmp/testfs.img", "/tmp/testfs-mount")
  1548. if err := cmd.Run(); err != nil {
  1549. c.Fatalf("mount failed: %v", err)
  1550. }
  1551. err := s.d.Start("--graph", "/tmp/testfs-mount")
  1552. c.Assert(err, check.IsNil)
  1553. // pull a repository large enough to fill the mount point
  1554. out, err := s.d.Cmd("pull", "registry:2")
  1555. c.Assert(out, checker.Contains, "no space left on device")
  1556. }
  1557. // Test daemon restart with container links + auto restart
  1558. func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) {
  1559. d := NewDaemon(c)
  1560. defer d.Stop()
  1561. err := d.StartWithBusybox()
  1562. c.Assert(err, checker.IsNil)
  1563. parent1Args := []string{}
  1564. parent2Args := []string{}
  1565. wg := sync.WaitGroup{}
  1566. maxChildren := 10
  1567. chErr := make(chan error, maxChildren)
  1568. for i := 0; i < maxChildren; i++ {
  1569. wg.Add(1)
  1570. name := fmt.Sprintf("test%d", i)
  1571. if i < maxChildren/2 {
  1572. parent1Args = append(parent1Args, []string{"--link", name}...)
  1573. } else {
  1574. parent2Args = append(parent2Args, []string{"--link", name}...)
  1575. }
  1576. go func() {
  1577. _, err = d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top")
  1578. chErr <- err
  1579. wg.Done()
  1580. }()
  1581. }
  1582. wg.Wait()
  1583. close(chErr)
  1584. for err := range chErr {
  1585. c.Assert(err, check.IsNil)
  1586. }
  1587. parent1Args = append([]string{"run", "-d"}, parent1Args...)
  1588. parent1Args = append(parent1Args, []string{"--name=parent1", "--restart=always", "busybox", "top"}...)
  1589. parent2Args = append([]string{"run", "-d"}, parent2Args...)
  1590. parent2Args = append(parent2Args, []string{"--name=parent2", "--restart=always", "busybox", "top"}...)
  1591. _, err = d.Cmd(parent1Args[0], parent1Args[1:]...)
  1592. c.Assert(err, check.IsNil)
  1593. _, err = d.Cmd(parent2Args[0], parent2Args[1:]...)
  1594. c.Assert(err, check.IsNil)
  1595. err = d.Stop()
  1596. c.Assert(err, check.IsNil)
  1597. // clear the log file -- we don't need any of it but may for the next part
  1598. // can ignore the error here, this is just a cleanup
  1599. os.Truncate(d.LogFileName(), 0)
  1600. err = d.Start()
  1601. c.Assert(err, check.IsNil)
  1602. for _, num := range []string{"1", "2"} {
  1603. out, err := d.Cmd("inspect", "-f", "{{ .State.Running }}", "parent"+num)
  1604. c.Assert(err, check.IsNil)
  1605. if strings.TrimSpace(out) != "true" {
  1606. log, _ := ioutil.ReadFile(d.LogFileName())
  1607. c.Fatalf("parent container is not running\n%s", string(log))
  1608. }
  1609. }
  1610. }
  1611. func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *check.C) {
  1612. testRequires(c, DaemonIsLinux)
  1613. cgroupParent := "test"
  1614. name := "cgroup-test"
  1615. err := s.d.StartWithBusybox("--cgroup-parent", cgroupParent)
  1616. c.Assert(err, check.IsNil)
  1617. defer s.d.Restart()
  1618. out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup")
  1619. c.Assert(err, checker.IsNil)
  1620. cgroupPaths := parseCgroupPaths(string(out))
  1621. c.Assert(len(cgroupPaths), checker.Not(checker.Equals), 0, check.Commentf("unexpected output - %q", string(out)))
  1622. out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name)
  1623. c.Assert(err, checker.IsNil)
  1624. id := strings.TrimSpace(string(out))
  1625. expectedCgroup := path.Join(cgroupParent, id)
  1626. found := false
  1627. for _, path := range cgroupPaths {
  1628. if strings.HasSuffix(path, expectedCgroup) {
  1629. found = true
  1630. break
  1631. }
  1632. }
  1633. c.Assert(found, checker.True, check.Commentf("Cgroup path for container (%s) doesn't found in cgroups file: %s", expectedCgroup, cgroupPaths))
  1634. }
  1635. func (s *DockerDaemonSuite) TestDaemonRestartWithLinks(c *check.C) {
  1636. testRequires(c, DaemonIsLinux) // Windows does not support links
  1637. err := s.d.StartWithBusybox()
  1638. c.Assert(err, check.IsNil)
  1639. out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1640. c.Assert(err, check.IsNil, check.Commentf(out))
  1641. out, err = s.d.Cmd("run", "--name=test2", "--link", "test:abc", "busybox", "sh", "-c", "ping -c 1 -w 1 abc")
  1642. c.Assert(err, check.IsNil, check.Commentf(out))
  1643. c.Assert(s.d.Restart(), check.IsNil)
  1644. // should fail since test is not running yet
  1645. out, err = s.d.Cmd("start", "test2")
  1646. c.Assert(err, check.NotNil, check.Commentf(out))
  1647. out, err = s.d.Cmd("start", "test")
  1648. c.Assert(err, check.IsNil, check.Commentf(out))
  1649. out, err = s.d.Cmd("start", "-a", "test2")
  1650. c.Assert(err, check.IsNil, check.Commentf(out))
  1651. c.Assert(strings.Contains(out, "1 packets transmitted, 1 packets received"), check.Equals, true, check.Commentf(out))
  1652. }
  1653. func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *check.C) {
  1654. testRequires(c, DaemonIsLinux) // Windows does not support links
  1655. err := s.d.StartWithBusybox()
  1656. c.Assert(err, check.IsNil)
  1657. out, err := s.d.Cmd("create", "--name=test", "busybox")
  1658. c.Assert(err, check.IsNil, check.Commentf(out))
  1659. out, err = s.d.Cmd("run", "-d", "--name=test2", "busybox", "top")
  1660. c.Assert(err, check.IsNil, check.Commentf(out))
  1661. test2ID := strings.TrimSpace(out)
  1662. out, err = s.d.Cmd("run", "-d", "--name=test3", "--link", "test2:abc", "busybox", "top")
  1663. test3ID := strings.TrimSpace(out)
  1664. c.Assert(s.d.Restart(), check.IsNil)
  1665. out, err = s.d.Cmd("create", "--name=test", "busybox")
  1666. c.Assert(err, check.NotNil, check.Commentf("expected error trying to create container with duplicate name"))
  1667. // this one is no longer needed, removing simplifies the remainder of the test
  1668. out, err = s.d.Cmd("rm", "-f", "test")
  1669. c.Assert(err, check.IsNil, check.Commentf(out))
  1670. out, err = s.d.Cmd("ps", "-a", "--no-trunc")
  1671. c.Assert(err, check.IsNil, check.Commentf(out))
  1672. lines := strings.Split(strings.TrimSpace(out), "\n")[1:]
  1673. test2validated := false
  1674. test3validated := false
  1675. for _, line := range lines {
  1676. fields := strings.Fields(line)
  1677. names := fields[len(fields)-1]
  1678. switch fields[0] {
  1679. case test2ID:
  1680. c.Assert(names, check.Equals, "test2,test3/abc")
  1681. test2validated = true
  1682. case test3ID:
  1683. c.Assert(names, check.Equals, "test3")
  1684. test3validated = true
  1685. }
  1686. }
  1687. c.Assert(test2validated, check.Equals, true)
  1688. c.Assert(test3validated, check.Equals, true)
  1689. }
  1690. // TestRunLinksChanged checks that creating a new container with the same name does not update links
  1691. // this ensures that the old, pre gh#16032 functionality continues on
  1692. func (s *DockerDaemonSuite) TestRunLinksChanged(c *check.C) {
  1693. testRequires(c, DaemonIsLinux) // Windows does not support links
  1694. err := s.d.StartWithBusybox()
  1695. c.Assert(err, check.IsNil)
  1696. out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1697. c.Assert(err, check.IsNil, check.Commentf(out))
  1698. out, err = s.d.Cmd("run", "--name=test2", "--link=test:abc", "busybox", "sh", "-c", "ping -c 1 abc")
  1699. c.Assert(err, check.IsNil, check.Commentf(out))
  1700. c.Assert(out, checker.Contains, "1 packets transmitted, 1 packets received")
  1701. out, err = s.d.Cmd("rm", "-f", "test")
  1702. c.Assert(err, check.IsNil, check.Commentf(out))
  1703. out, err = s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1704. c.Assert(err, check.IsNil, check.Commentf(out))
  1705. out, err = s.d.Cmd("start", "-a", "test2")
  1706. c.Assert(err, check.NotNil, check.Commentf(out))
  1707. c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  1708. err = s.d.Restart()
  1709. c.Assert(err, check.IsNil)
  1710. out, err = s.d.Cmd("start", "-a", "test2")
  1711. c.Assert(err, check.NotNil, check.Commentf(out))
  1712. c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  1713. }
  1714. func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *check.C) {
  1715. testRequires(c, DaemonIsLinux, NotPpc64le)
  1716. newD := NewDaemon(c)
  1717. infoLog := "\x1b[34mINFO\x1b"
  1718. p, tty, err := pty.Open()
  1719. c.Assert(err, checker.IsNil)
  1720. defer func() {
  1721. tty.Close()
  1722. p.Close()
  1723. }()
  1724. b := bytes.NewBuffer(nil)
  1725. go io.Copy(b, p)
  1726. // Enable coloring explicitly
  1727. newD.StartWithLogFile(tty, "--raw-logs=false")
  1728. newD.Stop()
  1729. c.Assert(b.String(), checker.Contains, infoLog)
  1730. b.Reset()
  1731. // Disable coloring explicitly
  1732. newD.StartWithLogFile(tty, "--raw-logs=true")
  1733. newD.Stop()
  1734. c.Assert(b.String(), check.Not(checker.Contains), infoLog)
  1735. }
  1736. func (s *DockerDaemonSuite) TestDaemonDebugLog(c *check.C) {
  1737. testRequires(c, DaemonIsLinux, NotPpc64le)
  1738. newD := NewDaemon(c)
  1739. debugLog := "\x1b[37mDEBU\x1b"
  1740. p, tty, err := pty.Open()
  1741. c.Assert(err, checker.IsNil)
  1742. defer func() {
  1743. tty.Close()
  1744. p.Close()
  1745. }()
  1746. b := bytes.NewBuffer(nil)
  1747. go io.Copy(b, p)
  1748. newD.StartWithLogFile(tty, "--debug")
  1749. newD.Stop()
  1750. c.Assert(b.String(), checker.Contains, debugLog)
  1751. }
  1752. func (s *DockerSuite) TestDaemonDiscoveryBackendConfigReload(c *check.C) {
  1753. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1754. // daemon config file
  1755. daemonConfig := `{ "debug" : false }`
  1756. configFilePath := "test.json"
  1757. configFile, err := os.Create(configFilePath)
  1758. c.Assert(err, checker.IsNil)
  1759. fmt.Fprintf(configFile, "%s", daemonConfig)
  1760. d := NewDaemon(c)
  1761. err = d.Start(fmt.Sprintf("--config-file=%s", configFilePath))
  1762. c.Assert(err, checker.IsNil)
  1763. defer d.Stop()
  1764. // daemon config file
  1765. daemonConfig = `{
  1766. "cluster-store": "consul://consuladdr:consulport/some/path",
  1767. "cluster-advertise": "192.168.56.100:0",
  1768. "debug" : false
  1769. }`
  1770. configFile.Close()
  1771. os.Remove(configFilePath)
  1772. configFile, err = os.Create(configFilePath)
  1773. c.Assert(err, checker.IsNil)
  1774. defer os.Remove(configFilePath)
  1775. fmt.Fprintf(configFile, "%s", daemonConfig)
  1776. configFile.Close()
  1777. syscall.Kill(d.cmd.Process.Pid, syscall.SIGHUP)
  1778. time.Sleep(3 * time.Second)
  1779. out, err := d.Cmd("info")
  1780. c.Assert(err, checker.IsNil)
  1781. c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Store: consul://consuladdr:consulport/some/path"))
  1782. c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Advertise: 192.168.56.100:0"))
  1783. }