docker_cli_daemon_test.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  1. // +build daemon
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/docker/libnetwork/iptables"
  16. "github.com/docker/libtrust"
  17. "github.com/go-check/check"
  18. )
  19. func (s *DockerDaemonSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) {
  20. if err := s.d.StartWithBusybox(); err != nil {
  21. c.Fatalf("Could not start daemon with busybox: %v", err)
  22. }
  23. if out, err := s.d.Cmd("run", "-d", "--name", "top1", "-p", "1234:80", "--restart", "always", "busybox:latest", "top"); err != nil {
  24. c.Fatalf("Could not run top1: err=%v\n%s", err, out)
  25. }
  26. // --restart=no by default
  27. if out, err := s.d.Cmd("run", "-d", "--name", "top2", "-p", "80", "busybox:latest", "top"); err != nil {
  28. c.Fatalf("Could not run top2: err=%v\n%s", err, out)
  29. }
  30. testRun := func(m map[string]bool, prefix string) {
  31. var format string
  32. for cont, shouldRun := range m {
  33. out, err := s.d.Cmd("ps")
  34. if err != nil {
  35. c.Fatalf("Could not run ps: err=%v\n%q", err, out)
  36. }
  37. if shouldRun {
  38. format = "%scontainer %q is not running"
  39. } else {
  40. format = "%scontainer %q is running"
  41. }
  42. if shouldRun != strings.Contains(out, cont) {
  43. c.Fatalf(format, prefix, cont)
  44. }
  45. }
  46. }
  47. testRun(map[string]bool{"top1": true, "top2": true}, "")
  48. if err := s.d.Restart(); err != nil {
  49. c.Fatalf("Could not restart daemon: %v", err)
  50. }
  51. testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ")
  52. }
  53. func (s *DockerDaemonSuite) TestDaemonRestartWithVolumesRefs(c *check.C) {
  54. if err := s.d.StartWithBusybox(); err != nil {
  55. c.Fatal(err)
  56. }
  57. if out, err := s.d.Cmd("run", "-d", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil {
  58. c.Fatal(err, out)
  59. }
  60. if err := s.d.Restart(); err != nil {
  61. c.Fatal(err)
  62. }
  63. if _, err := s.d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox", "top"); err != nil {
  64. c.Fatal(err)
  65. }
  66. if out, err := s.d.Cmd("rm", "-fv", "volrestarttest2"); err != nil {
  67. c.Fatal(err, out)
  68. }
  69. out, err := s.d.Cmd("inspect", "-f", "{{json .Mounts}}", "volrestarttest1")
  70. c.Assert(err, check.IsNil)
  71. if _, err := inspectMountPointJSON(out, "/foo"); err != nil {
  72. c.Fatalf("Expected volume to exist: /foo, error: %v\n", err)
  73. }
  74. }
  75. func (s *DockerDaemonSuite) TestDaemonStartIptablesFalse(c *check.C) {
  76. if err := s.d.Start("--iptables=false"); err != nil {
  77. c.Fatalf("we should have been able to start the daemon with passing iptables=false: %v", err)
  78. }
  79. }
  80. // Issue #8444: If docker0 bridge is modified (intentionally or unintentionally) and
  81. // no longer has an IP associated, we should gracefully handle that case and associate
  82. // an IP with it rather than fail daemon start
  83. func (s *DockerDaemonSuite) TestDaemonStartBridgeWithoutIPAssociation(c *check.C) {
  84. // rather than depending on brctl commands to verify docker0 is created and up
  85. // let's start the daemon and stop it, and then make a modification to run the
  86. // actual test
  87. if err := s.d.Start(); err != nil {
  88. c.Fatalf("Could not start daemon: %v", err)
  89. }
  90. if err := s.d.Stop(); err != nil {
  91. c.Fatalf("Could not stop daemon: %v", err)
  92. }
  93. // now we will remove the ip from docker0 and then try starting the daemon
  94. ipCmd := exec.Command("ip", "addr", "flush", "dev", "docker0")
  95. stdout, stderr, _, err := runCommandWithStdoutStderr(ipCmd)
  96. if err != nil {
  97. c.Fatalf("failed to remove docker0 IP association: %v, stdout: %q, stderr: %q", err, stdout, stderr)
  98. }
  99. if err := s.d.Start(); err != nil {
  100. warning := "**WARNING: Docker bridge network in bad state--delete docker0 bridge interface to fix"
  101. c.Fatalf("Could not start daemon when docker0 has no IP address: %v\n%s", err, warning)
  102. }
  103. }
  104. func (s *DockerDaemonSuite) TestDaemonIptablesClean(c *check.C) {
  105. if err := s.d.StartWithBusybox(); err != nil {
  106. c.Fatalf("Could not start daemon with busybox: %v", err)
  107. }
  108. if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil {
  109. c.Fatalf("Could not run top: %s, %v", out, err)
  110. }
  111. // get output from iptables with container running
  112. ipTablesSearchString := "tcp dpt:80"
  113. ipTablesCmd := exec.Command("iptables", "-nvL")
  114. out, _, err := runCommandWithOutput(ipTablesCmd)
  115. if err != nil {
  116. c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
  117. }
  118. if !strings.Contains(out, ipTablesSearchString) {
  119. c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, out)
  120. }
  121. if err := s.d.Stop(); err != nil {
  122. c.Fatalf("Could not stop daemon: %v", err)
  123. }
  124. // get output from iptables after restart
  125. ipTablesCmd = exec.Command("iptables", "-nvL")
  126. out, _, err = runCommandWithOutput(ipTablesCmd)
  127. if err != nil {
  128. c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
  129. }
  130. if strings.Contains(out, ipTablesSearchString) {
  131. c.Fatalf("iptables output should not have contained %q, but was %q", ipTablesSearchString, out)
  132. }
  133. }
  134. func (s *DockerDaemonSuite) TestDaemonIptablesCreate(c *check.C) {
  135. if err := s.d.StartWithBusybox(); err != nil {
  136. c.Fatalf("Could not start daemon with busybox: %v", err)
  137. }
  138. if out, err := s.d.Cmd("run", "-d", "--name", "top", "--restart=always", "-p", "80", "busybox:latest", "top"); err != nil {
  139. c.Fatalf("Could not run top: %s, %v", out, err)
  140. }
  141. // get output from iptables with container running
  142. ipTablesSearchString := "tcp dpt:80"
  143. ipTablesCmd := exec.Command("iptables", "-nvL")
  144. out, _, err := runCommandWithOutput(ipTablesCmd)
  145. if err != nil {
  146. c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
  147. }
  148. if !strings.Contains(out, ipTablesSearchString) {
  149. c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, out)
  150. }
  151. if err := s.d.Restart(); err != nil {
  152. c.Fatalf("Could not restart daemon: %v", err)
  153. }
  154. // make sure the container is not running
  155. runningOut, err := s.d.Cmd("inspect", "--format='{{.State.Running}}'", "top")
  156. if err != nil {
  157. c.Fatalf("Could not inspect on container: %s, %v", out, err)
  158. }
  159. if strings.TrimSpace(runningOut) != "true" {
  160. c.Fatalf("Container should have been restarted after daemon restart. Status running should have been true but was: %q", strings.TrimSpace(runningOut))
  161. }
  162. // get output from iptables after restart
  163. ipTablesCmd = exec.Command("iptables", "-nvL")
  164. out, _, err = runCommandWithOutput(ipTablesCmd)
  165. if err != nil {
  166. c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
  167. }
  168. if !strings.Contains(out, ipTablesSearchString) {
  169. c.Fatalf("iptables output after restart should have contained %q, but was %q", ipTablesSearchString, out)
  170. }
  171. }
  172. // TestDaemonIPv6Enabled checks that when the daemon is started with --ipv6=true that the docker0 bridge
  173. // has the fe80::1 address and that a container is assigned a link-local address
  174. func (s *DockerSuite) TestDaemonIPv6Enabled(c *check.C) {
  175. testRequires(c, IPv6)
  176. if err := setupV6(); err != nil {
  177. c.Fatal("Could not set up host for IPv6 tests")
  178. }
  179. d := NewDaemon(c)
  180. if err := d.StartWithBusybox("--ipv6"); err != nil {
  181. c.Fatal(err)
  182. }
  183. defer d.Stop()
  184. iface, err := net.InterfaceByName("docker0")
  185. if err != nil {
  186. c.Fatalf("Error getting docker0 interface: %v", err)
  187. }
  188. addrs, err := iface.Addrs()
  189. if err != nil {
  190. c.Fatalf("Error getting addresses for docker0 interface: %v", err)
  191. }
  192. var found bool
  193. expected := "fe80::1/64"
  194. for i := range addrs {
  195. if addrs[i].String() == expected {
  196. found = true
  197. }
  198. }
  199. if !found {
  200. c.Fatalf("Bridge does not have an IPv6 Address")
  201. }
  202. if out, err := d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest"); err != nil {
  203. c.Fatalf("Could not run container: %s, %v", out, err)
  204. }
  205. out, err := d.Cmd("inspect", "--format", "'{{.NetworkSettings.LinkLocalIPv6Address}}'", "ipv6test")
  206. out = strings.Trim(out, " \r\n'")
  207. if err != nil {
  208. c.Fatalf("Error inspecting container: %s, %v", out, err)
  209. }
  210. if ip := net.ParseIP(out); ip == nil {
  211. c.Fatalf("Container should have a link-local IPv6 address")
  212. }
  213. out, err = d.Cmd("inspect", "--format", "'{{.NetworkSettings.GlobalIPv6Address}}'", "ipv6test")
  214. out = strings.Trim(out, " \r\n'")
  215. if err != nil {
  216. c.Fatalf("Error inspecting container: %s, %v", out, err)
  217. }
  218. if ip := net.ParseIP(out); ip != nil {
  219. c.Fatalf("Container should not have a global IPv6 address: %v", out)
  220. }
  221. if err := teardownV6(); err != nil {
  222. c.Fatal("Could not perform teardown for IPv6 tests")
  223. }
  224. }
  225. // TestDaemonIPv6FixedCIDR checks that when the daemon is started with --ipv6=true and a fixed CIDR
  226. // that running containers are given a link-local and global IPv6 address
  227. func (s *DockerSuite) TestDaemonIPv6FixedCIDR(c *check.C) {
  228. testRequires(c, IPv6)
  229. if err := setupV6(); err != nil {
  230. c.Fatal("Could not set up host for IPv6 tests")
  231. }
  232. d := NewDaemon(c)
  233. if err := d.StartWithBusybox("--ipv6", "--fixed-cidr-v6='2001:db8:1::/64'"); err != nil {
  234. c.Fatalf("Could not start daemon with busybox: %v", err)
  235. }
  236. defer d.Stop()
  237. if out, err := d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest"); err != nil {
  238. c.Fatalf("Could not run container: %s, %v", out, err)
  239. }
  240. out, err := d.Cmd("inspect", "--format", "'{{.NetworkSettings.LinkLocalIPv6Address}}'", "ipv6test")
  241. out = strings.Trim(out, " \r\n'")
  242. if err != nil {
  243. c.Fatalf("Error inspecting container: %s, %v", out, err)
  244. }
  245. if ip := net.ParseIP(out); ip == nil {
  246. c.Fatalf("Container should have a link-local IPv6 address")
  247. }
  248. out, err = d.Cmd("inspect", "--format", "'{{.NetworkSettings.GlobalIPv6Address}}'", "ipv6test")
  249. out = strings.Trim(out, " \r\n'")
  250. if err != nil {
  251. c.Fatalf("Error inspecting container: %s, %v", out, err)
  252. }
  253. if ip := net.ParseIP(out); ip == nil {
  254. c.Fatalf("Container should have a global IPv6 address")
  255. }
  256. if err := teardownV6(); err != nil {
  257. c.Fatal("Could not perform teardown for IPv6 tests")
  258. }
  259. }
  260. func (s *DockerDaemonSuite) TestDaemonLogLevelWrong(c *check.C) {
  261. c.Assert(s.d.Start("--log-level=bogus"), check.NotNil, check.Commentf("Daemon shouldn't start with wrong log level"))
  262. }
  263. func (s *DockerDaemonSuite) TestDaemonLogLevelDebug(c *check.C) {
  264. if err := s.d.Start("--log-level=debug"); err != nil {
  265. c.Fatal(err)
  266. }
  267. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  268. if !strings.Contains(string(content), `level=debug`) {
  269. c.Fatalf(`Missing level="debug" in log file:\n%s`, string(content))
  270. }
  271. }
  272. func (s *DockerDaemonSuite) TestDaemonLogLevelFatal(c *check.C) {
  273. // we creating new daemons to create new logFile
  274. if err := s.d.Start("--log-level=fatal"); err != nil {
  275. c.Fatal(err)
  276. }
  277. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  278. if strings.Contains(string(content), `level=debug`) {
  279. c.Fatalf(`Should not have level="debug" in log file:\n%s`, string(content))
  280. }
  281. }
  282. func (s *DockerDaemonSuite) TestDaemonFlagD(c *check.C) {
  283. if err := s.d.Start("-D"); err != nil {
  284. c.Fatal(err)
  285. }
  286. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  287. if !strings.Contains(string(content), `level=debug`) {
  288. c.Fatalf(`Should have level="debug" in log file using -D:\n%s`, string(content))
  289. }
  290. }
  291. func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *check.C) {
  292. if err := s.d.Start("--debug"); err != nil {
  293. c.Fatal(err)
  294. }
  295. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  296. if !strings.Contains(string(content), `level=debug`) {
  297. c.Fatalf(`Should have level="debug" in log file using --debug:\n%s`, string(content))
  298. }
  299. }
  300. func (s *DockerDaemonSuite) TestDaemonFlagDebugLogLevelFatal(c *check.C) {
  301. if err := s.d.Start("--debug", "--log-level=fatal"); err != nil {
  302. c.Fatal(err)
  303. }
  304. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  305. if !strings.Contains(string(content), `level=debug`) {
  306. c.Fatalf(`Should have level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content))
  307. }
  308. }
  309. func (s *DockerDaemonSuite) TestDaemonAllocatesListeningPort(c *check.C) {
  310. listeningPorts := [][]string{
  311. {"0.0.0.0", "0.0.0.0", "5678"},
  312. {"127.0.0.1", "127.0.0.1", "1234"},
  313. {"localhost", "127.0.0.1", "1235"},
  314. }
  315. cmdArgs := []string{}
  316. for _, hostDirective := range listeningPorts {
  317. cmdArgs = append(cmdArgs, "--host", fmt.Sprintf("tcp://%s:%s", hostDirective[0], hostDirective[2]))
  318. }
  319. if err := s.d.StartWithBusybox(cmdArgs...); err != nil {
  320. c.Fatalf("Could not start daemon with busybox: %v", err)
  321. }
  322. for _, hostDirective := range listeningPorts {
  323. output, err := s.d.Cmd("run", "-p", fmt.Sprintf("%s:%s:80", hostDirective[1], hostDirective[2]), "busybox", "true")
  324. if err == nil {
  325. c.Fatalf("Container should not start, expected port already allocated error: %q", output)
  326. } else if !strings.Contains(output, "port is already allocated") {
  327. c.Fatalf("Expected port is already allocated error: %q", output)
  328. }
  329. }
  330. }
  331. func (s *DockerDaemonSuite) TestDaemonKeyGeneration(c *check.C) {
  332. // TODO: skip or update for Windows daemon
  333. os.Remove("/etc/docker/key.json")
  334. if err := s.d.Start(); err != nil {
  335. c.Fatalf("Could not start daemon: %v", err)
  336. }
  337. s.d.Stop()
  338. k, err := libtrust.LoadKeyFile("/etc/docker/key.json")
  339. if err != nil {
  340. c.Fatalf("Error opening key file")
  341. }
  342. kid := k.KeyID()
  343. // Test Key ID is a valid fingerprint (e.g. QQXN:JY5W:TBXI:MK3X:GX6P:PD5D:F56N:NHCS:LVRZ:JA46:R24J:XEFF)
  344. if len(kid) != 59 {
  345. c.Fatalf("Bad key ID: %s", kid)
  346. }
  347. }
  348. func (s *DockerDaemonSuite) TestDaemonKeyMigration(c *check.C) {
  349. // TODO: skip or update for Windows daemon
  350. os.Remove("/etc/docker/key.json")
  351. k1, err := libtrust.GenerateECP256PrivateKey()
  352. if err != nil {
  353. c.Fatalf("Error generating private key: %s", err)
  354. }
  355. if err := os.MkdirAll(filepath.Join(os.Getenv("HOME"), ".docker"), 0755); err != nil {
  356. c.Fatalf("Error creating .docker directory: %s", err)
  357. }
  358. if err := libtrust.SaveKey(filepath.Join(os.Getenv("HOME"), ".docker", "key.json"), k1); err != nil {
  359. c.Fatalf("Error saving private key: %s", err)
  360. }
  361. if err := s.d.Start(); err != nil {
  362. c.Fatalf("Could not start daemon: %v", err)
  363. }
  364. s.d.Stop()
  365. k2, err := libtrust.LoadKeyFile("/etc/docker/key.json")
  366. if err != nil {
  367. c.Fatalf("Error opening key file")
  368. }
  369. if k1.KeyID() != k2.KeyID() {
  370. c.Fatalf("Key not migrated")
  371. }
  372. }
  373. // GH#11320 - verify that the daemon exits on failure properly
  374. // Note that this explicitly tests the conflict of {-b,--bridge} and {--bip} options as the means
  375. // to get a daemon init failure; no other tests for -b/--bip conflict are therefore required
  376. func (s *DockerDaemonSuite) TestDaemonExitOnFailure(c *check.C) {
  377. //attempt to start daemon with incorrect flags (we know -b and --bip conflict)
  378. if err := s.d.Start("--bridge", "nosuchbridge", "--bip", "1.1.1.1"); err != nil {
  379. //verify we got the right error
  380. if !strings.Contains(err.Error(), "Daemon exited and never started") {
  381. c.Fatalf("Expected daemon not to start, got %v", err)
  382. }
  383. // look in the log and make sure we got the message that daemon is shutting down
  384. runCmd := exec.Command("grep", "Error starting daemon", s.d.LogfileName())
  385. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  386. c.Fatalf("Expected 'Error starting daemon' message; but doesn't exist in log: %q, err: %v", out, err)
  387. }
  388. } else {
  389. //if we didn't get an error and the daemon is running, this is a failure
  390. c.Fatal("Conflicting options should cause the daemon to error out with a failure")
  391. }
  392. }
  393. func (s *DockerDaemonSuite) TestDaemonBridgeExternal(c *check.C) {
  394. d := s.d
  395. err := d.Start("--bridge", "nosuchbridge")
  396. c.Assert(err, check.NotNil, check.Commentf("--bridge option with an invalid bridge should cause the daemon to fail"))
  397. defer d.Restart()
  398. bridgeName := "external-bridge"
  399. bridgeIp := "192.169.1.1/24"
  400. _, bridgeIPNet, _ := net.ParseCIDR(bridgeIp)
  401. out, err := createInterface(c, "bridge", bridgeName, bridgeIp)
  402. c.Assert(err, check.IsNil, check.Commentf(out))
  403. defer deleteInterface(c, bridgeName)
  404. err = d.StartWithBusybox("--bridge", bridgeName)
  405. c.Assert(err, check.IsNil)
  406. ipTablesSearchString := bridgeIPNet.String()
  407. ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL")
  408. out, _, err = runCommandWithOutput(ipTablesCmd)
  409. c.Assert(err, check.IsNil)
  410. c.Assert(strings.Contains(out, ipTablesSearchString), check.Equals, true,
  411. check.Commentf("iptables output should have contained %q, but was %q",
  412. ipTablesSearchString, out))
  413. _, err = d.Cmd("run", "-d", "--name", "ExtContainer", "busybox", "top")
  414. c.Assert(err, check.IsNil)
  415. containerIp := d.findContainerIP("ExtContainer")
  416. ip := net.ParseIP(containerIp)
  417. c.Assert(bridgeIPNet.Contains(ip), check.Equals, true,
  418. check.Commentf("Container IP-Address must be in the same subnet range : %s",
  419. containerIp))
  420. }
  421. func createInterface(c *check.C, ifType string, ifName string, ipNet string) (string, error) {
  422. args := []string{"link", "add", "name", ifName, "type", ifType}
  423. ipLinkCmd := exec.Command("ip", args...)
  424. out, _, err := runCommandWithOutput(ipLinkCmd)
  425. if err != nil {
  426. return out, err
  427. }
  428. ifCfgCmd := exec.Command("ifconfig", ifName, ipNet, "up")
  429. out, _, err = runCommandWithOutput(ifCfgCmd)
  430. return out, err
  431. }
  432. func deleteInterface(c *check.C, ifName string) {
  433. ifCmd := exec.Command("ip", "link", "delete", ifName)
  434. out, _, err := runCommandWithOutput(ifCmd)
  435. c.Assert(err, check.IsNil, check.Commentf(out))
  436. flushCmd := exec.Command("iptables", "-t", "nat", "--flush")
  437. out, _, err = runCommandWithOutput(flushCmd)
  438. c.Assert(err, check.IsNil, check.Commentf(out))
  439. flushCmd = exec.Command("iptables", "--flush")
  440. out, _, err = runCommandWithOutput(flushCmd)
  441. c.Assert(err, check.IsNil, check.Commentf(out))
  442. }
  443. func (s *DockerDaemonSuite) TestDaemonBridgeIP(c *check.C) {
  444. // TestDaemonBridgeIP Steps
  445. // 1. Delete the existing docker0 Bridge
  446. // 2. Set --bip daemon configuration and start the new Docker Daemon
  447. // 3. Check if the bip config has taken effect using ifconfig and iptables commands
  448. // 4. Launch a Container and make sure the IP-Address is in the expected subnet
  449. // 5. Delete the docker0 Bridge
  450. // 6. Restart the Docker Daemon (via defered action)
  451. // This Restart takes care of bringing docker0 interface back to auto-assigned IP
  452. defaultNetworkBridge := "docker0"
  453. deleteInterface(c, defaultNetworkBridge)
  454. d := s.d
  455. bridgeIp := "192.169.1.1/24"
  456. ip, bridgeIPNet, _ := net.ParseCIDR(bridgeIp)
  457. err := d.StartWithBusybox("--bip", bridgeIp)
  458. c.Assert(err, check.IsNil)
  459. defer d.Restart()
  460. ifconfigSearchString := ip.String()
  461. ifconfigCmd := exec.Command("ifconfig", defaultNetworkBridge)
  462. out, _, _, err := runCommandWithStdoutStderr(ifconfigCmd)
  463. c.Assert(err, check.IsNil)
  464. c.Assert(strings.Contains(out, ifconfigSearchString), check.Equals, true,
  465. check.Commentf("ifconfig output should have contained %q, but was %q",
  466. ifconfigSearchString, out))
  467. ipTablesSearchString := bridgeIPNet.String()
  468. ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL")
  469. out, _, err = runCommandWithOutput(ipTablesCmd)
  470. c.Assert(err, check.IsNil)
  471. c.Assert(strings.Contains(out, ipTablesSearchString), check.Equals, true,
  472. check.Commentf("iptables output should have contained %q, but was %q",
  473. ipTablesSearchString, out))
  474. out, err = d.Cmd("run", "-d", "--name", "test", "busybox", "top")
  475. c.Assert(err, check.IsNil)
  476. containerIp := d.findContainerIP("test")
  477. ip = net.ParseIP(containerIp)
  478. c.Assert(bridgeIPNet.Contains(ip), check.Equals, true,
  479. check.Commentf("Container IP-Address must be in the same subnet range : %s",
  480. containerIp))
  481. deleteInterface(c, defaultNetworkBridge)
  482. }
  483. func (s *DockerDaemonSuite) TestDaemonRestartWithBridgeIPChange(c *check.C) {
  484. if err := s.d.Start(); err != nil {
  485. c.Fatalf("Could not start daemon: %v", err)
  486. }
  487. defer s.d.Restart()
  488. if err := s.d.Stop(); err != nil {
  489. c.Fatalf("Could not stop daemon: %v", err)
  490. }
  491. // now we will change the docker0's IP and then try starting the daemon
  492. bridgeIP := "192.169.100.1/24"
  493. _, bridgeIPNet, _ := net.ParseCIDR(bridgeIP)
  494. ipCmd := exec.Command("ifconfig", "docker0", bridgeIP)
  495. stdout, stderr, _, err := runCommandWithStdoutStderr(ipCmd)
  496. if err != nil {
  497. c.Fatalf("failed to change docker0's IP association: %v, stdout: %q, stderr: %q", err, stdout, stderr)
  498. }
  499. if err := s.d.Start("--bip", bridgeIP); err != nil {
  500. c.Fatalf("Could not start daemon: %v", err)
  501. }
  502. //check if the iptables contains new bridgeIP MASQUERADE rule
  503. ipTablesSearchString := bridgeIPNet.String()
  504. ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL")
  505. out, _, err := runCommandWithOutput(ipTablesCmd)
  506. if err != nil {
  507. c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
  508. }
  509. if !strings.Contains(out, ipTablesSearchString) {
  510. c.Fatalf("iptables output should have contained new MASQUERADE rule with IP %q, but was %q", ipTablesSearchString, out)
  511. }
  512. }
  513. func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr(c *check.C) {
  514. d := s.d
  515. bridgeName := "external-bridge"
  516. bridgeIp := "192.169.1.1/24"
  517. out, err := createInterface(c, "bridge", bridgeName, bridgeIp)
  518. c.Assert(err, check.IsNil, check.Commentf(out))
  519. defer deleteInterface(c, bridgeName)
  520. args := []string{"--bridge", bridgeName, "--fixed-cidr", "192.169.1.0/30"}
  521. err = d.StartWithBusybox(args...)
  522. c.Assert(err, check.IsNil)
  523. defer d.Restart()
  524. for i := 0; i < 4; i++ {
  525. cName := "Container" + strconv.Itoa(i)
  526. out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
  527. if err != nil {
  528. c.Assert(strings.Contains(out, "no available ip addresses"), check.Equals, true,
  529. check.Commentf("Could not run a Container : %s %s", err.Error(), out))
  530. }
  531. }
  532. }
  533. func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Implicit(c *check.C) {
  534. defaultNetworkBridge := "docker0"
  535. deleteInterface(c, defaultNetworkBridge)
  536. d := s.d
  537. bridgeIp := "192.169.1.1"
  538. bridgeIpNet := fmt.Sprintf("%s/24", bridgeIp)
  539. err := d.StartWithBusybox("--bip", bridgeIpNet)
  540. c.Assert(err, check.IsNil)
  541. defer d.Restart()
  542. expectedMessage := fmt.Sprintf("default via %s dev", bridgeIp)
  543. out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0")
  544. c.Assert(strings.Contains(out, expectedMessage), check.Equals, true,
  545. check.Commentf("Implicit default gateway should be bridge IP %s, but default route was '%s'",
  546. bridgeIp, strings.TrimSpace(out)))
  547. deleteInterface(c, defaultNetworkBridge)
  548. }
  549. func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Explicit(c *check.C) {
  550. defaultNetworkBridge := "docker0"
  551. deleteInterface(c, defaultNetworkBridge)
  552. d := s.d
  553. bridgeIp := "192.169.1.1"
  554. bridgeIpNet := fmt.Sprintf("%s/24", bridgeIp)
  555. gatewayIp := "192.169.1.254"
  556. err := d.StartWithBusybox("--bip", bridgeIpNet, "--default-gateway", gatewayIp)
  557. c.Assert(err, check.IsNil)
  558. defer d.Restart()
  559. expectedMessage := fmt.Sprintf("default via %s dev", gatewayIp)
  560. out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0")
  561. c.Assert(strings.Contains(out, expectedMessage), check.Equals, true,
  562. check.Commentf("Explicit default gateway should be %s, but default route was '%s'",
  563. gatewayIp, strings.TrimSpace(out)))
  564. deleteInterface(c, defaultNetworkBridge)
  565. }
  566. func (s *DockerDaemonSuite) TestDaemonIP(c *check.C) {
  567. d := s.d
  568. ipStr := "192.170.1.1/24"
  569. ip, _, _ := net.ParseCIDR(ipStr)
  570. args := []string{"--ip", ip.String()}
  571. err := d.StartWithBusybox(args...)
  572. c.Assert(err, check.IsNil)
  573. defer d.Restart()
  574. out, err := d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top")
  575. c.Assert(err, check.NotNil,
  576. check.Commentf("Running a container must fail with an invalid --ip option"))
  577. c.Assert(strings.Contains(out, "Error starting userland proxy"), check.Equals, true)
  578. ifName := "dummy"
  579. out, err = createInterface(c, "dummy", ifName, ipStr)
  580. c.Assert(err, check.IsNil, check.Commentf(out))
  581. defer deleteInterface(c, ifName)
  582. _, err = d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top")
  583. c.Assert(err, check.IsNil)
  584. ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL")
  585. out, _, err = runCommandWithOutput(ipTablesCmd)
  586. c.Assert(err, check.IsNil)
  587. regex := fmt.Sprintf("DNAT.*%s.*dpt:8000", ip.String())
  588. matched, _ := regexp.MatchString(regex, out)
  589. c.Assert(matched, check.Equals, true,
  590. check.Commentf("iptables output should have contained %q, but was %q", regex, out))
  591. }
  592. func (s *DockerDaemonSuite) TestDaemonICCPing(c *check.C) {
  593. d := s.d
  594. bridgeName := "external-bridge"
  595. bridgeIp := "192.169.1.1/24"
  596. out, err := createInterface(c, "bridge", bridgeName, bridgeIp)
  597. c.Assert(err, check.IsNil, check.Commentf(out))
  598. defer deleteInterface(c, bridgeName)
  599. args := []string{"--bridge", bridgeName, "--icc=false"}
  600. err = d.StartWithBusybox(args...)
  601. c.Assert(err, check.IsNil)
  602. defer d.Restart()
  603. ipTablesCmd := exec.Command("iptables", "-nvL", "FORWARD")
  604. out, _, err = runCommandWithOutput(ipTablesCmd)
  605. c.Assert(err, check.IsNil)
  606. regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName)
  607. matched, _ := regexp.MatchString(regex, out)
  608. c.Assert(matched, check.Equals, true,
  609. check.Commentf("iptables output should have contained %q, but was %q", regex, out))
  610. // Pinging another container must fail with --icc=false
  611. pingContainers(c, d, true)
  612. ipStr := "192.171.1.1/24"
  613. ip, _, _ := net.ParseCIDR(ipStr)
  614. ifName := "icc-dummy"
  615. createInterface(c, "dummy", ifName, ipStr)
  616. // But, Pinging external or a Host interface must succeed
  617. pingCmd := fmt.Sprintf("ping -c 1 %s -W 1", ip.String())
  618. runArgs := []string{"--rm", "busybox", "sh", "-c", pingCmd}
  619. _, err = d.Cmd("run", runArgs...)
  620. c.Assert(err, check.IsNil)
  621. }
  622. func (s *DockerDaemonSuite) TestDaemonICCLinkExpose(c *check.C) {
  623. d := s.d
  624. bridgeName := "external-bridge"
  625. bridgeIp := "192.169.1.1/24"
  626. out, err := createInterface(c, "bridge", bridgeName, bridgeIp)
  627. c.Assert(err, check.IsNil, check.Commentf(out))
  628. defer deleteInterface(c, bridgeName)
  629. args := []string{"--bridge", bridgeName, "--icc=false"}
  630. err = d.StartWithBusybox(args...)
  631. c.Assert(err, check.IsNil)
  632. defer d.Restart()
  633. ipTablesCmd := exec.Command("iptables", "-nvL", "FORWARD")
  634. out, _, err = runCommandWithOutput(ipTablesCmd)
  635. c.Assert(err, check.IsNil)
  636. regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName)
  637. matched, _ := regexp.MatchString(regex, out)
  638. c.Assert(matched, check.Equals, true,
  639. check.Commentf("iptables output should have contained %q, but was %q", regex, out))
  640. out, err = d.Cmd("run", "-d", "--expose", "4567", "--name", "icc1", "busybox", "nc", "-l", "-p", "4567")
  641. c.Assert(err, check.IsNil, check.Commentf(out))
  642. out, err = d.Cmd("run", "--link", "icc1:icc1", "busybox", "nc", "icc1", "4567")
  643. c.Assert(err, check.IsNil, check.Commentf(out))
  644. }
  645. func (s *DockerDaemonSuite) TestDaemonLinksIpTablesRulesWhenLinkAndUnlink(c *check.C) {
  646. bridgeName := "external-bridge"
  647. bridgeIp := "192.169.1.1/24"
  648. out, err := createInterface(c, "bridge", bridgeName, bridgeIp)
  649. c.Assert(err, check.IsNil, check.Commentf(out))
  650. defer deleteInterface(c, bridgeName)
  651. args := []string{"--bridge", bridgeName, "--icc=false"}
  652. err = s.d.StartWithBusybox(args...)
  653. c.Assert(err, check.IsNil)
  654. defer s.d.Restart()
  655. _, err = s.d.Cmd("run", "-d", "--name", "child", "--publish", "8080:80", "busybox", "top")
  656. c.Assert(err, check.IsNil)
  657. _, err = s.d.Cmd("run", "-d", "--name", "parent", "--link", "child:http", "busybox", "top")
  658. c.Assert(err, check.IsNil)
  659. childIP := s.d.findContainerIP("child")
  660. parentIP := s.d.findContainerIP("parent")
  661. sourceRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", childIP, "--sport", "80", "-d", parentIP, "-j", "ACCEPT"}
  662. destinationRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", parentIP, "--dport", "80", "-d", childIP, "-j", "ACCEPT"}
  663. if !iptables.Exists("filter", "DOCKER", sourceRule...) || !iptables.Exists("filter", "DOCKER", destinationRule...) {
  664. c.Fatal("Iptables rules not found")
  665. }
  666. s.d.Cmd("rm", "--link", "parent/http")
  667. if iptables.Exists("filter", "DOCKER", sourceRule...) || iptables.Exists("filter", "DOCKER", destinationRule...) {
  668. c.Fatal("Iptables rules should be removed when unlink")
  669. }
  670. s.d.Cmd("kill", "child")
  671. s.d.Cmd("kill", "parent")
  672. }
  673. func (s *DockerDaemonSuite) TestDaemonUlimitDefaults(c *check.C) {
  674. testRequires(c, NativeExecDriver)
  675. if err := s.d.StartWithBusybox("--default-ulimit", "nofile=42:42", "--default-ulimit", "nproc=1024:1024"); err != nil {
  676. c.Fatal(err)
  677. }
  678. out, err := s.d.Cmd("run", "--ulimit", "nproc=2048", "--name=test", "busybox", "/bin/sh", "-c", "echo $(ulimit -n); echo $(ulimit -p)")
  679. if err != nil {
  680. c.Fatal(out, err)
  681. }
  682. outArr := strings.Split(out, "\n")
  683. if len(outArr) < 2 {
  684. c.Fatalf("got unexpected output: %s", out)
  685. }
  686. nofile := strings.TrimSpace(outArr[0])
  687. nproc := strings.TrimSpace(outArr[1])
  688. if nofile != "42" {
  689. c.Fatalf("expected `ulimit -n` to be `42`, got: %s", nofile)
  690. }
  691. if nproc != "2048" {
  692. c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc)
  693. }
  694. // Now restart daemon with a new default
  695. if err := s.d.Restart("--default-ulimit", "nofile=43"); err != nil {
  696. c.Fatal(err)
  697. }
  698. out, err = s.d.Cmd("start", "-a", "test")
  699. if err != nil {
  700. c.Fatal(err)
  701. }
  702. outArr = strings.Split(out, "\n")
  703. if len(outArr) < 2 {
  704. c.Fatalf("got unexpected output: %s", out)
  705. }
  706. nofile = strings.TrimSpace(outArr[0])
  707. nproc = strings.TrimSpace(outArr[1])
  708. if nofile != "43" {
  709. c.Fatalf("expected `ulimit -n` to be `43`, got: %s", nofile)
  710. }
  711. if nproc != "2048" {
  712. c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc)
  713. }
  714. }
  715. // #11315
  716. func (s *DockerDaemonSuite) TestDaemonRestartRenameContainer(c *check.C) {
  717. if err := s.d.StartWithBusybox(); err != nil {
  718. c.Fatal(err)
  719. }
  720. if out, err := s.d.Cmd("run", "--name=test", "busybox"); err != nil {
  721. c.Fatal(err, out)
  722. }
  723. if out, err := s.d.Cmd("rename", "test", "test2"); err != nil {
  724. c.Fatal(err, out)
  725. }
  726. if err := s.d.Restart(); err != nil {
  727. c.Fatal(err)
  728. }
  729. if out, err := s.d.Cmd("start", "test2"); err != nil {
  730. c.Fatal(err, out)
  731. }
  732. }
  733. func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefault(c *check.C) {
  734. if err := s.d.StartWithBusybox(); err != nil {
  735. c.Fatal(err)
  736. }
  737. out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline")
  738. if err != nil {
  739. c.Fatal(out, err)
  740. }
  741. id := strings.TrimSpace(out)
  742. if out, err := s.d.Cmd("wait", id); err != nil {
  743. c.Fatal(out, err)
  744. }
  745. logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log")
  746. if _, err := os.Stat(logPath); err != nil {
  747. c.Fatal(err)
  748. }
  749. f, err := os.Open(logPath)
  750. if err != nil {
  751. c.Fatal(err)
  752. }
  753. var res struct {
  754. Log string `json:"log"`
  755. Stream string `json:"stream"`
  756. Time time.Time `json:"time"`
  757. }
  758. if err := json.NewDecoder(f).Decode(&res); err != nil {
  759. c.Fatal(err)
  760. }
  761. if res.Log != "testline\n" {
  762. c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n")
  763. }
  764. if res.Stream != "stdout" {
  765. c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout")
  766. }
  767. if !time.Now().After(res.Time) {
  768. c.Fatalf("Log time %v in future", res.Time)
  769. }
  770. }
  771. func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefaultOverride(c *check.C) {
  772. if err := s.d.StartWithBusybox(); err != nil {
  773. c.Fatal(err)
  774. }
  775. out, err := s.d.Cmd("run", "-d", "--log-driver=none", "busybox", "echo", "testline")
  776. if err != nil {
  777. c.Fatal(out, err)
  778. }
  779. id := strings.TrimSpace(out)
  780. if out, err := s.d.Cmd("wait", id); err != nil {
  781. c.Fatal(out, err)
  782. }
  783. logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log")
  784. if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) {
  785. c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err)
  786. }
  787. }
  788. func (s *DockerDaemonSuite) TestDaemonLoggingDriverNone(c *check.C) {
  789. if err := s.d.StartWithBusybox("--log-driver=none"); err != nil {
  790. c.Fatal(err)
  791. }
  792. out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline")
  793. if err != nil {
  794. c.Fatal(out, err)
  795. }
  796. id := strings.TrimSpace(out)
  797. if out, err := s.d.Cmd("wait", id); err != nil {
  798. c.Fatal(out, err)
  799. }
  800. logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log")
  801. if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) {
  802. c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err)
  803. }
  804. }
  805. func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) {
  806. if err := s.d.StartWithBusybox("--log-driver=none"); err != nil {
  807. c.Fatal(err)
  808. }
  809. out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "echo", "testline")
  810. if err != nil {
  811. c.Fatal(out, err)
  812. }
  813. id := strings.TrimSpace(out)
  814. if out, err := s.d.Cmd("wait", id); err != nil {
  815. c.Fatal(out, err)
  816. }
  817. logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log")
  818. if _, err := os.Stat(logPath); err != nil {
  819. c.Fatal(err)
  820. }
  821. f, err := os.Open(logPath)
  822. if err != nil {
  823. c.Fatal(err)
  824. }
  825. var res struct {
  826. Log string `json:"log"`
  827. Stream string `json:"stream"`
  828. Time time.Time `json:"time"`
  829. }
  830. if err := json.NewDecoder(f).Decode(&res); err != nil {
  831. c.Fatal(err)
  832. }
  833. if res.Log != "testline\n" {
  834. c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n")
  835. }
  836. if res.Stream != "stdout" {
  837. c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout")
  838. }
  839. if !time.Now().After(res.Time) {
  840. c.Fatalf("Log time %v in future", res.Time)
  841. }
  842. }
  843. func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) {
  844. if err := s.d.StartWithBusybox("--log-driver=none"); err != nil {
  845. c.Fatal(err)
  846. }
  847. out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline")
  848. if err != nil {
  849. c.Fatal(out, err)
  850. }
  851. id := strings.TrimSpace(out)
  852. out, err = s.d.Cmd("logs", id)
  853. if err == nil {
  854. c.Fatalf("Logs should fail with \"none\" driver")
  855. }
  856. if !strings.Contains(out, `"logs" command is supported only for "json-file" logging driver`) {
  857. c.Fatalf("There should be error about non-json-file driver, got: %s", out)
  858. }
  859. }
  860. func (s *DockerDaemonSuite) TestDaemonDots(c *check.C) {
  861. if err := s.d.StartWithBusybox(); err != nil {
  862. c.Fatal(err)
  863. }
  864. // Now create 4 containers
  865. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  866. c.Fatalf("Error creating container: %q", err)
  867. }
  868. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  869. c.Fatalf("Error creating container: %q", err)
  870. }
  871. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  872. c.Fatalf("Error creating container: %q", err)
  873. }
  874. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  875. c.Fatalf("Error creating container: %q", err)
  876. }
  877. s.d.Stop()
  878. s.d.Start("--log-level=debug")
  879. s.d.Stop()
  880. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  881. if strings.Contains(string(content), "....") {
  882. c.Fatalf("Debug level should not have ....\n%s", string(content))
  883. }
  884. s.d.Start("--log-level=error")
  885. s.d.Stop()
  886. content, _ = ioutil.ReadFile(s.d.logFile.Name())
  887. if strings.Contains(string(content), "....") {
  888. c.Fatalf("Error level should not have ....\n%s", string(content))
  889. }
  890. s.d.Start("--log-level=info")
  891. s.d.Stop()
  892. content, _ = ioutil.ReadFile(s.d.logFile.Name())
  893. if !strings.Contains(string(content), "....") {
  894. c.Fatalf("Info level should have ....\n%s", string(content))
  895. }
  896. }
  897. func (s *DockerDaemonSuite) TestDaemonUnixSockCleanedUp(c *check.C) {
  898. dir, err := ioutil.TempDir("", "socket-cleanup-test")
  899. if err != nil {
  900. c.Fatal(err)
  901. }
  902. defer os.RemoveAll(dir)
  903. sockPath := filepath.Join(dir, "docker.sock")
  904. if err := s.d.Start("--host", "unix://"+sockPath); err != nil {
  905. c.Fatal(err)
  906. }
  907. if _, err := os.Stat(sockPath); err != nil {
  908. c.Fatal("socket does not exist")
  909. }
  910. if err := s.d.Stop(); err != nil {
  911. c.Fatal(err)
  912. }
  913. if _, err := os.Stat(sockPath); err == nil || !os.IsNotExist(err) {
  914. c.Fatal("unix socket is not cleaned up")
  915. }
  916. }
  917. func (s *DockerDaemonSuite) TestDaemonWithWrongkey(c *check.C) {
  918. type Config struct {
  919. Crv string `json:"crv"`
  920. D string `json:"d"`
  921. Kid string `json:"kid"`
  922. Kty string `json:"kty"`
  923. X string `json:"x"`
  924. Y string `json:"y"`
  925. }
  926. os.Remove("/etc/docker/key.json")
  927. if err := s.d.Start(); err != nil {
  928. c.Fatalf("Failed to start daemon: %v", err)
  929. }
  930. if err := s.d.Stop(); err != nil {
  931. c.Fatalf("Could not stop daemon: %v", err)
  932. }
  933. config := &Config{}
  934. bytes, err := ioutil.ReadFile("/etc/docker/key.json")
  935. if err != nil {
  936. c.Fatalf("Error reading key.json file: %s", err)
  937. }
  938. // byte[] to Data-Struct
  939. if err := json.Unmarshal(bytes, &config); err != nil {
  940. c.Fatalf("Error Unmarshal: %s", err)
  941. }
  942. //replace config.Kid with the fake value
  943. config.Kid = "VSAJ:FUYR:X3H2:B2VZ:KZ6U:CJD5:K7BX:ZXHY:UZXT:P4FT:MJWG:HRJ4"
  944. // NEW Data-Struct to byte[]
  945. newBytes, err := json.Marshal(&config)
  946. if err != nil {
  947. c.Fatalf("Error Marshal: %s", err)
  948. }
  949. // write back
  950. if err := ioutil.WriteFile("/etc/docker/key.json", newBytes, 0400); err != nil {
  951. c.Fatalf("Error ioutil.WriteFile: %s", err)
  952. }
  953. defer os.Remove("/etc/docker/key.json")
  954. if err := s.d.Start(); err == nil {
  955. c.Fatalf("It should not be successful to start daemon with wrong key: %v", err)
  956. }
  957. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  958. if !strings.Contains(string(content), "Public Key ID does not match") {
  959. c.Fatal("Missing KeyID message from daemon logs")
  960. }
  961. }
  962. func (s *DockerDaemonSuite) TestDaemonRestartKillWait(c *check.C) {
  963. if err := s.d.StartWithBusybox(); err != nil {
  964. c.Fatalf("Could not start daemon with busybox: %v", err)
  965. }
  966. out, err := s.d.Cmd("run", "-id", "busybox", "/bin/cat")
  967. if err != nil {
  968. c.Fatalf("Could not run /bin/cat: err=%v\n%s", err, out)
  969. }
  970. containerID := strings.TrimSpace(out)
  971. if out, err := s.d.Cmd("kill", containerID); err != nil {
  972. c.Fatalf("Could not kill %s: err=%v\n%s", containerID, err, out)
  973. }
  974. if err := s.d.Restart(); err != nil {
  975. c.Fatalf("Could not restart daemon: %v", err)
  976. }
  977. errchan := make(chan error)
  978. go func() {
  979. if out, err := s.d.Cmd("wait", containerID); err != nil {
  980. errchan <- fmt.Errorf("%v:\n%s", err, out)
  981. }
  982. close(errchan)
  983. }()
  984. select {
  985. case <-time.After(5 * time.Second):
  986. c.Fatal("Waiting on a stopped (killed) container timed out")
  987. case err := <-errchan:
  988. if err != nil {
  989. c.Fatal(err)
  990. }
  991. }
  992. }
  993. // TestHttpsInfo connects via two-way authenticated HTTPS to the info endpoint
  994. func (s *DockerDaemonSuite) TestHttpsInfo(c *check.C) {
  995. const (
  996. testDaemonHttpsAddr = "localhost:4271"
  997. )
  998. if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  999. "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHttpsAddr); err != nil {
  1000. c.Fatalf("Could not start daemon with busybox: %v", err)
  1001. }
  1002. //force tcp protocol
  1003. host := fmt.Sprintf("tcp://%s", testDaemonHttpsAddr)
  1004. daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"}
  1005. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1006. if err != nil {
  1007. c.Fatalf("Error Occurred: %s and output: %s", err, out)
  1008. }
  1009. }
  1010. // TestHttpsInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint
  1011. // by using a rogue client certificate and checks that it fails with the expected error.
  1012. func (s *DockerDaemonSuite) TestHttpsInfoRogueCert(c *check.C) {
  1013. const (
  1014. errBadCertificate = "remote error: bad certificate"
  1015. testDaemonHttpsAddr = "localhost:4271"
  1016. )
  1017. if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  1018. "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHttpsAddr); err != nil {
  1019. c.Fatalf("Could not start daemon with busybox: %v", err)
  1020. }
  1021. //force tcp protocol
  1022. host := fmt.Sprintf("tcp://%s", testDaemonHttpsAddr)
  1023. daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"}
  1024. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1025. if err == nil || !strings.Contains(out, errBadCertificate) {
  1026. c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out)
  1027. }
  1028. }
  1029. // TestHttpsInfoRogueServerCert connects via two-way authenticated HTTPS to the info endpoint
  1030. // which provides a rogue server certificate and checks that it fails with the expected error
  1031. func (s *DockerDaemonSuite) TestHttpsInfoRogueServerCert(c *check.C) {
  1032. const (
  1033. errCaUnknown = "x509: certificate signed by unknown authority"
  1034. testDaemonRogueHttpsAddr = "localhost:4272"
  1035. )
  1036. if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-rogue-cert.pem",
  1037. "--tlskey", "fixtures/https/server-rogue-key.pem", "-H", testDaemonRogueHttpsAddr); err != nil {
  1038. c.Fatalf("Could not start daemon with busybox: %v", err)
  1039. }
  1040. //force tcp protocol
  1041. host := fmt.Sprintf("tcp://%s", testDaemonRogueHttpsAddr)
  1042. daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"}
  1043. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1044. if err == nil || !strings.Contains(out, errCaUnknown) {
  1045. c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out)
  1046. }
  1047. }
  1048. func pingContainers(c *check.C, d *Daemon, expectFailure bool) {
  1049. var dargs []string
  1050. if d != nil {
  1051. dargs = []string{"--host", d.sock()}
  1052. }
  1053. args := append(dargs, "run", "-d", "--name", "container1", "busybox", "top")
  1054. dockerCmd(c, args...)
  1055. args = append(dargs, "run", "--rm", "--link", "container1:alias1", "busybox", "sh", "-c")
  1056. pingCmd := "ping -c 1 %s -W 1"
  1057. args = append(args, fmt.Sprintf(pingCmd, "alias1"))
  1058. _, _, err := dockerCmdWithError(c, args...)
  1059. if expectFailure {
  1060. c.Assert(err, check.NotNil)
  1061. } else {
  1062. c.Assert(err, check.IsNil)
  1063. }
  1064. args = append(dargs, "rm", "-f", "container1")
  1065. dockerCmd(c, args...)
  1066. }
  1067. func (s *DockerDaemonSuite) TestDaemonRestartWithSocketAsVolume(c *check.C) {
  1068. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1069. socket := filepath.Join(s.d.folder, "docker.sock")
  1070. out, err := s.d.Cmd("run", "-d", "-v", socket+":/sock", "busybox")
  1071. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1072. c.Assert(s.d.Restart(), check.IsNil)
  1073. }
  1074. func (s *DockerDaemonSuite) TestCleanupMountsAfterCrash(c *check.C) {
  1075. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1076. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  1077. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1078. id := strings.TrimSpace(out)
  1079. c.Assert(s.d.cmd.Process.Signal(os.Kill), check.IsNil)
  1080. c.Assert(s.d.Start(), check.IsNil)
  1081. mountOut, err := exec.Command("mount").CombinedOutput()
  1082. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1083. c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, check.Commentf("Something mounted from older daemon start: %s", mountOut))
  1084. }
  1085. func (s *DockerDaemonSuite) TestRunContainerWithBridgeNone(c *check.C) {
  1086. testRequires(c, NativeExecDriver)
  1087. c.Assert(s.d.StartWithBusybox("-b", "none"), check.IsNil)
  1088. out, err := s.d.Cmd("run", "--rm", "busybox", "ip", "l")
  1089. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1090. c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1091. check.Commentf("There shouldn't be eth0 in container in default(bridge) mode when bridge network is disabled: %s", out))
  1092. out, err = s.d.Cmd("run", "--rm", "--net=bridge", "busybox", "ip", "l")
  1093. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1094. c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1095. check.Commentf("There shouldn't be eth0 in container in bridge mode when bridge network is disabled: %s", out))
  1096. out, err = s.d.Cmd("run", "--rm", "--net=host", "busybox", "ip", "l")
  1097. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1098. c.Assert(strings.Contains(out, "eth0"), check.Equals, true,
  1099. check.Commentf("There should be eth0 in container when --net=host when bridge network is disabled: %s", out))
  1100. }
  1101. func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *check.C) {
  1102. if err := s.d.StartWithBusybox(); err != nil {
  1103. t.Fatal(err)
  1104. }
  1105. if out, err := s.d.Cmd("run", "-ti", "-d", "--name", "test", "busybox"); err != nil {
  1106. t.Fatal(out, err)
  1107. }
  1108. if err := s.d.Restart(); err != nil {
  1109. t.Fatal(err)
  1110. }
  1111. // Container 'test' should be removed without error
  1112. if out, err := s.d.Cmd("rm", "test"); err != nil {
  1113. t.Fatal(out, err)
  1114. }
  1115. }
  1116. func (s *DockerDaemonSuite) TestDaemonRestartCleanupNetns(c *check.C) {
  1117. if err := s.d.StartWithBusybox(); err != nil {
  1118. c.Fatal(err)
  1119. }
  1120. out, err := s.d.Cmd("run", "--name", "netns", "-d", "busybox", "top")
  1121. if err != nil {
  1122. c.Fatal(out, err)
  1123. }
  1124. if out, err := s.d.Cmd("stop", "netns"); err != nil {
  1125. c.Fatal(out, err)
  1126. }
  1127. // Construct netns file name from container id
  1128. out = strings.TrimSpace(out)
  1129. nsFile := out[:12]
  1130. // Test if the file still exists
  1131. out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", "/var/run/docker/netns/"+nsFile))
  1132. out = strings.TrimSpace(out)
  1133. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1134. c.Assert(out, check.Equals, "/var/run/docker/netns/"+nsFile, check.Commentf("Output: %s", out))
  1135. // Remove the container and restart the daemon
  1136. if out, err := s.d.Cmd("rm", "netns"); err != nil {
  1137. c.Fatal(out, err)
  1138. }
  1139. if err := s.d.Restart(); err != nil {
  1140. c.Fatal(err)
  1141. }
  1142. // Test again and see now the netns file does not exist
  1143. out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", "/var/run/docker/netns/"+nsFile))
  1144. out = strings.TrimSpace(out)
  1145. c.Assert(err, check.Not(check.IsNil), check.Commentf("Output: %s", out))
  1146. // c.Assert(out, check.Equals, "", check.Commentf("Output: %s", out))
  1147. }
  1148. // tests regression detailed in #13964 where DOCKER_TLS_VERIFY env is ignored
  1149. func (s *DockerDaemonSuite) TestDaemonNoTlsCliTlsVerifyWithEnv(c *check.C) {
  1150. host := "tcp://localhost:4271"
  1151. c.Assert(s.d.Start("-H", host), check.IsNil)
  1152. cmd := exec.Command(dockerBinary, "-H", host, "info")
  1153. cmd.Env = []string{"DOCKER_TLS_VERIFY=1", "DOCKER_CERT_PATH=fixtures/https"}
  1154. out, _, err := runCommandWithOutput(cmd)
  1155. c.Assert(err, check.Not(check.IsNil), check.Commentf("%s", out))
  1156. c.Assert(strings.Contains(out, "error occurred trying to connect"), check.Equals, true)
  1157. }
  1158. func setupV6() error {
  1159. // Hack to get the right IPv6 address on docker0, which has already been created
  1160. err := exec.Command("ip", "addr", "add", "fe80::1/64", "dev", "docker0").Run()
  1161. if err != nil {
  1162. return err
  1163. }
  1164. return nil
  1165. }
  1166. func teardownV6() error {
  1167. err := exec.Command("ip", "addr", "del", "fe80::1/64", "dev", "docker0").Run()
  1168. if err != nil {
  1169. return err
  1170. }
  1171. return nil
  1172. }