docker_cli_daemon_test.go 45 KB

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