docker_cli_daemon_test.go 58 KB

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