docker_cli_daemon_test.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/docker/libtrust"
  15. "github.com/go-check/check"
  16. )
  17. func (s *DockerDaemonSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) {
  18. if err := s.d.StartWithBusybox(); err != nil {
  19. c.Fatalf("Could not start daemon with busybox: %v", err)
  20. }
  21. if out, err := s.d.Cmd("run", "-d", "--name", "top1", "-p", "1234:80", "--restart", "always", "busybox:latest", "top"); err != nil {
  22. c.Fatalf("Could not run top1: err=%v\n%s", err, out)
  23. }
  24. // --restart=no by default
  25. if out, err := s.d.Cmd("run", "-d", "--name", "top2", "-p", "80", "busybox:latest", "top"); err != nil {
  26. c.Fatalf("Could not run top2: err=%v\n%s", err, out)
  27. }
  28. testRun := func(m map[string]bool, prefix string) {
  29. var format string
  30. for cont, shouldRun := range m {
  31. out, err := s.d.Cmd("ps")
  32. if err != nil {
  33. c.Fatalf("Could not run ps: err=%v\n%q", err, out)
  34. }
  35. if shouldRun {
  36. format = "%scontainer %q is not running"
  37. } else {
  38. format = "%scontainer %q is running"
  39. }
  40. if shouldRun != strings.Contains(out, cont) {
  41. c.Fatalf(format, prefix, cont)
  42. }
  43. }
  44. }
  45. testRun(map[string]bool{"top1": true, "top2": true}, "")
  46. if err := s.d.Restart(); err != nil {
  47. c.Fatalf("Could not restart daemon: %v", err)
  48. }
  49. testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ")
  50. }
  51. func (s *DockerDaemonSuite) TestDaemonRestartWithVolumesRefs(c *check.C) {
  52. if err := s.d.StartWithBusybox(); err != nil {
  53. c.Fatal(err)
  54. }
  55. if out, err := s.d.Cmd("run", "-d", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil {
  56. c.Fatal(err, out)
  57. }
  58. if err := s.d.Restart(); err != nil {
  59. c.Fatal(err)
  60. }
  61. if _, err := s.d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox", "top"); err != nil {
  62. c.Fatal(err)
  63. }
  64. if out, err := s.d.Cmd("rm", "-fv", "volrestarttest2"); err != nil {
  65. c.Fatal(err, out)
  66. }
  67. v, err := s.d.Cmd("inspect", "--format", "{{ json .Volumes }}", "volrestarttest1")
  68. if err != nil {
  69. c.Fatal(err)
  70. }
  71. volumes := make(map[string]string)
  72. json.Unmarshal([]byte(v), &volumes)
  73. if _, err := os.Stat(volumes["/foo"]); err != nil {
  74. c.Fatalf("Expected volume to exist: %s - %s", volumes["/foo"], err)
  75. }
  76. }
  77. func (s *DockerDaemonSuite) TestDaemonStartIptablesFalse(c *check.C) {
  78. if err := s.d.Start("--iptables=false"); err != nil {
  79. c.Fatalf("we should have been able to start the daemon with passing iptables=false: %v", err)
  80. }
  81. }
  82. // Issue #8444: If docker0 bridge is modified (intentionally or unintentionally) and
  83. // no longer has an IP associated, we should gracefully handle that case and associate
  84. // an IP with it rather than fail daemon start
  85. func (s *DockerDaemonSuite) TestDaemonStartBridgeWithoutIPAssociation(c *check.C) {
  86. // rather than depending on brctl commands to verify docker0 is created and up
  87. // let's start the daemon and stop it, and then make a modification to run the
  88. // actual test
  89. if err := s.d.Start(); err != nil {
  90. c.Fatalf("Could not start daemon: %v", err)
  91. }
  92. if err := s.d.Stop(); err != nil {
  93. c.Fatalf("Could not stop daemon: %v", err)
  94. }
  95. // now we will remove the ip from docker0 and then try starting the daemon
  96. ipCmd := exec.Command("ip", "addr", "flush", "dev", "docker0")
  97. stdout, stderr, _, err := runCommandWithStdoutStderr(ipCmd)
  98. if err != nil {
  99. c.Fatalf("failed to remove docker0 IP association: %v, stdout: %q, stderr: %q", err, stdout, stderr)
  100. }
  101. if err := s.d.Start(); err != nil {
  102. warning := "**WARNING: Docker bridge network in bad state--delete docker0 bridge interface to fix"
  103. c.Fatalf("Could not start daemon when docker0 has no IP address: %v\n%s", err, warning)
  104. }
  105. }
  106. func (s *DockerDaemonSuite) TestDaemonIptablesClean(c *check.C) {
  107. if err := s.d.StartWithBusybox(); err != nil {
  108. c.Fatalf("Could not start daemon with busybox: %v", err)
  109. }
  110. if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil {
  111. c.Fatalf("Could not run top: %s, %v", out, err)
  112. }
  113. // get output from iptables with container running
  114. ipTablesSearchString := "tcp dpt:80"
  115. ipTablesCmd := exec.Command("iptables", "-nvL")
  116. out, _, err := runCommandWithOutput(ipTablesCmd)
  117. if err != nil {
  118. c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
  119. }
  120. if !strings.Contains(out, ipTablesSearchString) {
  121. c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, out)
  122. }
  123. if err := s.d.Stop(); err != nil {
  124. c.Fatalf("Could not stop daemon: %v", err)
  125. }
  126. // get output from iptables after restart
  127. ipTablesCmd = exec.Command("iptables", "-nvL")
  128. out, _, err = runCommandWithOutput(ipTablesCmd)
  129. if err != nil {
  130. c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
  131. }
  132. if strings.Contains(out, ipTablesSearchString) {
  133. c.Fatalf("iptables output should not have contained %q, but was %q", ipTablesSearchString, out)
  134. }
  135. }
  136. func (s *DockerDaemonSuite) TestDaemonIptablesCreate(c *check.C) {
  137. if err := s.d.StartWithBusybox(); err != nil {
  138. c.Fatalf("Could not start daemon with busybox: %v", err)
  139. }
  140. if out, err := s.d.Cmd("run", "-d", "--name", "top", "--restart=always", "-p", "80", "busybox:latest", "top"); err != nil {
  141. c.Fatalf("Could not run top: %s, %v", out, err)
  142. }
  143. // get output from iptables with container running
  144. ipTablesSearchString := "tcp dpt:80"
  145. ipTablesCmd := exec.Command("iptables", "-nvL")
  146. out, _, err := runCommandWithOutput(ipTablesCmd)
  147. if err != nil {
  148. c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
  149. }
  150. if !strings.Contains(out, ipTablesSearchString) {
  151. c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, out)
  152. }
  153. if err := s.d.Restart(); err != nil {
  154. c.Fatalf("Could not restart daemon: %v", err)
  155. }
  156. // make sure the container is not running
  157. runningOut, err := s.d.Cmd("inspect", "--format='{{.State.Running}}'", "top")
  158. if err != nil {
  159. c.Fatalf("Could not inspect on container: %s, %v", out, err)
  160. }
  161. if strings.TrimSpace(runningOut) != "true" {
  162. c.Fatalf("Container should have been restarted after daemon restart. Status running should have been true but was: %q", strings.TrimSpace(runningOut))
  163. }
  164. // get output from iptables after restart
  165. ipTablesCmd = exec.Command("iptables", "-nvL")
  166. out, _, err = runCommandWithOutput(ipTablesCmd)
  167. if err != nil {
  168. c.Fatalf("Could not run iptables -nvL: %s, %v", out, err)
  169. }
  170. if !strings.Contains(out, ipTablesSearchString) {
  171. c.Fatalf("iptables output after restart should have contained %q, but was %q", ipTablesSearchString, out)
  172. }
  173. }
  174. func (s *DockerDaemonSuite) TestDaemonLogLevelWrong(c *check.C) {
  175. c.Assert(s.d.Start("--log-level=bogus"), check.NotNil, check.Commentf("Daemon shouldn't start with wrong log level"))
  176. }
  177. func (s *DockerDaemonSuite) TestDaemonLogLevelDebug(c *check.C) {
  178. if err := s.d.Start("--log-level=debug"); err != nil {
  179. c.Fatal(err)
  180. }
  181. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  182. if !strings.Contains(string(content), `level=debug`) {
  183. c.Fatalf(`Missing level="debug" in log file:\n%s`, string(content))
  184. }
  185. }
  186. func (s *DockerDaemonSuite) TestDaemonLogLevelFatal(c *check.C) {
  187. // we creating new daemons to create new logFile
  188. if err := s.d.Start("--log-level=fatal"); err != nil {
  189. c.Fatal(err)
  190. }
  191. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  192. if strings.Contains(string(content), `level=debug`) {
  193. c.Fatalf(`Should not have level="debug" in log file:\n%s`, string(content))
  194. }
  195. }
  196. func (s *DockerDaemonSuite) TestDaemonFlagD(c *check.C) {
  197. if err := s.d.Start("-D"); err != nil {
  198. c.Fatal(err)
  199. }
  200. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  201. if !strings.Contains(string(content), `level=debug`) {
  202. c.Fatalf(`Missing level="debug" in log file using -D:\n%s`, string(content))
  203. }
  204. }
  205. func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *check.C) {
  206. if err := s.d.Start("--debug"); err != nil {
  207. c.Fatal(err)
  208. }
  209. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  210. if !strings.Contains(string(content), `level=debug`) {
  211. c.Fatalf(`Missing level="debug" in log file using --debug:\n%s`, string(content))
  212. }
  213. }
  214. func (s *DockerDaemonSuite) TestDaemonFlagDebugLogLevelFatal(c *check.C) {
  215. if err := s.d.Start("--debug", "--log-level=fatal"); err != nil {
  216. c.Fatal(err)
  217. }
  218. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  219. if !strings.Contains(string(content), `level=debug`) {
  220. c.Fatalf(`Missing level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content))
  221. }
  222. }
  223. func (s *DockerDaemonSuite) TestDaemonAllocatesListeningPort(c *check.C) {
  224. listeningPorts := [][]string{
  225. {"0.0.0.0", "0.0.0.0", "5678"},
  226. {"127.0.0.1", "127.0.0.1", "1234"},
  227. {"localhost", "127.0.0.1", "1235"},
  228. }
  229. cmdArgs := []string{}
  230. for _, hostDirective := range listeningPorts {
  231. cmdArgs = append(cmdArgs, "--host", fmt.Sprintf("tcp://%s:%s", hostDirective[0], hostDirective[2]))
  232. }
  233. if err := s.d.StartWithBusybox(cmdArgs...); err != nil {
  234. c.Fatalf("Could not start daemon with busybox: %v", err)
  235. }
  236. for _, hostDirective := range listeningPorts {
  237. output, err := s.d.Cmd("run", "-p", fmt.Sprintf("%s:%s:80", hostDirective[1], hostDirective[2]), "busybox", "true")
  238. if err == nil {
  239. c.Fatalf("Container should not start, expected port already allocated error: %q", output)
  240. } else if !strings.Contains(output, "port is already allocated") {
  241. c.Fatalf("Expected port is already allocated error: %q", output)
  242. }
  243. }
  244. }
  245. // #9629
  246. func (s *DockerDaemonSuite) TestDaemonVolumesBindsRefs(c *check.C) {
  247. if err := s.d.StartWithBusybox(); err != nil {
  248. c.Fatal(err)
  249. }
  250. tmp, err := ioutil.TempDir(os.TempDir(), "")
  251. if err != nil {
  252. c.Fatal(err)
  253. }
  254. defer os.RemoveAll(tmp)
  255. if err := ioutil.WriteFile(tmp+"/test", []byte("testing"), 0655); err != nil {
  256. c.Fatal(err)
  257. }
  258. if out, err := s.d.Cmd("create", "-v", tmp+":/foo", "--name=voltest", "busybox"); err != nil {
  259. c.Fatal(err, out)
  260. }
  261. if err := s.d.Restart(); err != nil {
  262. c.Fatal(err)
  263. }
  264. if out, err := s.d.Cmd("run", "--volumes-from=voltest", "--name=consumer", "busybox", "/bin/sh", "-c", "[ -f /foo/test ]"); err != nil {
  265. c.Fatal(err, out)
  266. }
  267. }
  268. func (s *DockerDaemonSuite) TestDaemonKeyGeneration(c *check.C) {
  269. // TODO: skip or update for Windows daemon
  270. os.Remove("/etc/docker/key.json")
  271. if err := s.d.Start(); err != nil {
  272. c.Fatalf("Could not start daemon: %v", err)
  273. }
  274. s.d.Stop()
  275. k, err := libtrust.LoadKeyFile("/etc/docker/key.json")
  276. if err != nil {
  277. c.Fatalf("Error opening key file")
  278. }
  279. kid := k.KeyID()
  280. // Test Key ID is a valid fingerprint (e.g. QQXN:JY5W:TBXI:MK3X:GX6P:PD5D:F56N:NHCS:LVRZ:JA46:R24J:XEFF)
  281. if len(kid) != 59 {
  282. c.Fatalf("Bad key ID: %s", kid)
  283. }
  284. }
  285. func (s *DockerDaemonSuite) TestDaemonKeyMigration(c *check.C) {
  286. // TODO: skip or update for Windows daemon
  287. os.Remove("/etc/docker/key.json")
  288. k1, err := libtrust.GenerateECP256PrivateKey()
  289. if err != nil {
  290. c.Fatalf("Error generating private key: %s", err)
  291. }
  292. if err := os.MkdirAll(filepath.Join(os.Getenv("HOME"), ".docker"), 0755); err != nil {
  293. c.Fatalf("Error creating .docker directory: %s", err)
  294. }
  295. if err := libtrust.SaveKey(filepath.Join(os.Getenv("HOME"), ".docker", "key.json"), k1); err != nil {
  296. c.Fatalf("Error saving private key: %s", err)
  297. }
  298. if err := s.d.Start(); err != nil {
  299. c.Fatalf("Could not start daemon: %v", err)
  300. }
  301. s.d.Stop()
  302. k2, err := libtrust.LoadKeyFile("/etc/docker/key.json")
  303. if err != nil {
  304. c.Fatalf("Error opening key file")
  305. }
  306. if k1.KeyID() != k2.KeyID() {
  307. c.Fatalf("Key not migrated")
  308. }
  309. }
  310. // Simulate an older daemon (pre 1.3) coming up with volumes specified in containers
  311. // without corresponding volume json
  312. func (s *DockerDaemonSuite) TestDaemonUpgradeWithVolumes(c *check.C) {
  313. graphDir := filepath.Join(os.TempDir(), "docker-test")
  314. defer os.RemoveAll(graphDir)
  315. if err := s.d.StartWithBusybox("-g", graphDir); err != nil {
  316. c.Fatal(err)
  317. }
  318. tmpDir := filepath.Join(os.TempDir(), "test")
  319. defer os.RemoveAll(tmpDir)
  320. if out, err := s.d.Cmd("create", "-v", tmpDir+":/foo", "--name=test", "busybox"); err != nil {
  321. c.Fatal(err, out)
  322. }
  323. if err := s.d.Stop(); err != nil {
  324. c.Fatal(err)
  325. }
  326. // Remove this since we're expecting the daemon to re-create it too
  327. if err := os.RemoveAll(tmpDir); err != nil {
  328. c.Fatal(err)
  329. }
  330. configDir := filepath.Join(graphDir, "volumes")
  331. if err := os.RemoveAll(configDir); err != nil {
  332. c.Fatal(err)
  333. }
  334. if err := s.d.Start("-g", graphDir); err != nil {
  335. c.Fatal(err)
  336. }
  337. if _, err := os.Stat(tmpDir); os.IsNotExist(err) {
  338. c.Fatalf("expected volume path %s to exist but it does not", tmpDir)
  339. }
  340. dir, err := ioutil.ReadDir(configDir)
  341. if err != nil {
  342. c.Fatal(err)
  343. }
  344. if len(dir) == 0 {
  345. c.Fatalf("expected volumes config dir to contain data for new volume")
  346. }
  347. // Now with just removing the volume config and not the volume data
  348. if err := s.d.Stop(); err != nil {
  349. c.Fatal(err)
  350. }
  351. if err := os.RemoveAll(configDir); err != nil {
  352. c.Fatal(err)
  353. }
  354. if err := s.d.Start("-g", graphDir); err != nil {
  355. c.Fatal(err)
  356. }
  357. dir, err = ioutil.ReadDir(configDir)
  358. if err != nil {
  359. c.Fatal(err)
  360. }
  361. if len(dir) == 0 {
  362. c.Fatalf("expected volumes config dir to contain data for new volume")
  363. }
  364. }
  365. // GH#11320 - verify that the daemon exits on failure properly
  366. // Note that this explicitly tests the conflict of {-b,--bridge} and {--bip} options as the means
  367. // to get a daemon init failure; no other tests for -b/--bip conflict are therefore required
  368. func (s *DockerDaemonSuite) TestDaemonExitOnFailure(c *check.C) {
  369. //attempt to start daemon with incorrect flags (we know -b and --bip conflict)
  370. if err := s.d.Start("--bridge", "nosuchbridge", "--bip", "1.1.1.1"); err != nil {
  371. //verify we got the right error
  372. if !strings.Contains(err.Error(), "Daemon exited and never started") {
  373. c.Fatalf("Expected daemon not to start, got %v", err)
  374. }
  375. // look in the log and make sure we got the message that daemon is shutting down
  376. runCmd := exec.Command("grep", "Error starting daemon", s.d.LogfileName())
  377. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  378. c.Fatalf("Expected 'Error starting daemon' message; but doesn't exist in log: %q, err: %v", out, err)
  379. }
  380. } else {
  381. //if we didn't get an error and the daemon is running, this is a failure
  382. c.Fatal("Conflicting options should cause the daemon to error out with a failure")
  383. }
  384. }
  385. func (s *DockerDaemonSuite) TestDaemonBridgeExternal(c *check.C) {
  386. d := s.d
  387. err := d.Start("--bridge", "nosuchbridge")
  388. c.Assert(err, check.Not(check.IsNil), check.Commentf("--bridge option with an invalid bridge should cause the daemon to fail"))
  389. bridgeName := "external-bridge"
  390. bridgeIp := "192.169.1.1/24"
  391. _, bridgeIPNet, _ := net.ParseCIDR(bridgeIp)
  392. args := []string{"link", "add", "name", bridgeName, "type", "bridge"}
  393. ipLinkCmd := exec.Command("ip", args...)
  394. _, _, _, err = runCommandWithStdoutStderr(ipLinkCmd)
  395. c.Assert(err, check.IsNil)
  396. ifCfgCmd := exec.Command("ifconfig", bridgeName, bridgeIp, "up")
  397. _, _, _, err = runCommandWithStdoutStderr(ifCfgCmd)
  398. c.Assert(err, check.IsNil)
  399. err = d.StartWithBusybox("--bridge", bridgeName)
  400. c.Assert(err, check.IsNil)
  401. ipTablesSearchString := bridgeIPNet.String()
  402. ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL")
  403. out, _, err := runCommandWithOutput(ipTablesCmd)
  404. c.Assert(err, check.IsNil)
  405. c.Assert(strings.Contains(out, ipTablesSearchString), check.Equals, true,
  406. check.Commentf("iptables output should have contained %q, but was %q",
  407. ipTablesSearchString, out))
  408. _, err = d.Cmd("run", "-d", "--name", "ExtContainer", "busybox", "top")
  409. c.Assert(err, check.IsNil)
  410. containerIp := d.findContainerIP(c, "ExtContainer")
  411. ip := net.ParseIP(containerIp)
  412. c.Assert(bridgeIPNet.Contains(ip), check.Equals, true,
  413. check.Commentf("Container IP-Address must be in the same subnet range : %s",
  414. containerIp))
  415. // Reset to Defaults
  416. deleteBridge(c, bridgeName)
  417. d.Restart()
  418. }
  419. func deleteBridge(c *check.C, bridge string) {
  420. ifCmd := exec.Command("ip", "link", "delete", bridge)
  421. _, _, _, err := runCommandWithStdoutStderr(ifCmd)
  422. c.Assert(err, check.IsNil)
  423. flushCmd := exec.Command("iptables", "-t", "nat", "--flush")
  424. _, _, _, err = runCommandWithStdoutStderr(flushCmd)
  425. c.Assert(err, check.IsNil)
  426. }
  427. func (s *DockerDaemonSuite) TestDaemonBridgeIP(c *check.C) {
  428. // TestDaemonBridgeIP Steps
  429. // 1. Delete the existing docker0 Bridge
  430. // 2. Set --bip daemon configuration and start the new Docker Daemon
  431. // 3. Check if the bip config has taken effect using ifconfig and iptables commands
  432. // 4. Launch a Container and make sure the IP-Address is in the expected subnet
  433. // 5. Delete the docker0 Bridge
  434. // 6. Restart the Docker Daemon (with no --bip settings)
  435. // This Restart takes care of bringing docker0 interface back to auto-assigned IP
  436. // 7. Stop the Docker Daemon (via defered action)
  437. defaultNetworkBridge := "docker0"
  438. deleteBridge(c, defaultNetworkBridge)
  439. d := s.d
  440. bridgeIp := "192.169.1.1/24"
  441. ip, bridgeIPNet, _ := net.ParseCIDR(bridgeIp)
  442. err := d.StartWithBusybox("--bip", bridgeIp)
  443. c.Assert(err, check.IsNil)
  444. ifconfigSearchString := ip.String()
  445. ifconfigCmd := exec.Command("ifconfig", defaultNetworkBridge)
  446. out, _, _, err := runCommandWithStdoutStderr(ifconfigCmd)
  447. c.Assert(err, check.IsNil)
  448. c.Assert(strings.Contains(out, ifconfigSearchString), check.Equals, true,
  449. check.Commentf("ifconfig output should have contained %q, but was %q",
  450. ifconfigSearchString, out))
  451. ipTablesSearchString := bridgeIPNet.String()
  452. ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL")
  453. out, _, err = runCommandWithOutput(ipTablesCmd)
  454. c.Assert(err, check.IsNil)
  455. c.Assert(strings.Contains(out, ipTablesSearchString), check.Equals, true,
  456. check.Commentf("iptables output should have contained %q, but was %q",
  457. ipTablesSearchString, out))
  458. out, err = d.Cmd("run", "-d", "--name", "test", "busybox", "top")
  459. c.Assert(err, check.IsNil)
  460. containerIp := d.findContainerIP(c, "test")
  461. ip = net.ParseIP(containerIp)
  462. c.Assert(bridgeIPNet.Contains(ip), check.Equals, true,
  463. check.Commentf("Container IP-Address must be in the same subnet range : %s",
  464. containerIp))
  465. // Reset to Defaults
  466. deleteBridge(c, defaultNetworkBridge)
  467. d.Restart()
  468. pingContainers(c)
  469. }
  470. func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr(c *check.C) {
  471. d := s.d
  472. bridgeName := "external-bridge"
  473. args := []string{"link", "add", "name", bridgeName, "type", "bridge"}
  474. ipLinkCmd := exec.Command("ip", args...)
  475. _, _, _, err := runCommandWithStdoutStderr(ipLinkCmd)
  476. c.Assert(err, check.IsNil)
  477. ifCmd := exec.Command("ifconfig", bridgeName, "192.169.1.1/24", "up")
  478. _, _, _, err = runCommandWithStdoutStderr(ifCmd)
  479. c.Assert(err, check.IsNil)
  480. args = []string{"--bridge", bridgeName, "--fixed-cidr", "192.169.1.0/30"}
  481. err = d.StartWithBusybox(args...)
  482. c.Assert(err, check.IsNil)
  483. for i := 0; i < 4; i++ {
  484. cName := "Container" + strconv.Itoa(i)
  485. out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
  486. if err != nil {
  487. c.Assert(strings.Contains(out, "no available ip addresses"), check.Equals, true,
  488. check.Commentf("Could not run a Container : %s %s", err.Error(), out))
  489. }
  490. }
  491. // Reset to Defaults
  492. deleteBridge(c, bridgeName)
  493. d.Restart()
  494. }
  495. func (s *DockerDaemonSuite) TestDaemonUlimitDefaults(c *check.C) {
  496. testRequires(c, NativeExecDriver)
  497. if err := s.d.StartWithBusybox("--default-ulimit", "nofile=42:42", "--default-ulimit", "nproc=1024:1024"); err != nil {
  498. c.Fatal(err)
  499. }
  500. out, err := s.d.Cmd("run", "--ulimit", "nproc=2048", "--name=test", "busybox", "/bin/sh", "-c", "echo $(ulimit -n); echo $(ulimit -p)")
  501. if err != nil {
  502. c.Fatal(out, err)
  503. }
  504. outArr := strings.Split(out, "\n")
  505. if len(outArr) < 2 {
  506. c.Fatalf("got unexpected output: %s", out)
  507. }
  508. nofile := strings.TrimSpace(outArr[0])
  509. nproc := strings.TrimSpace(outArr[1])
  510. if nofile != "42" {
  511. c.Fatalf("expected `ulimit -n` to be `42`, got: %s", nofile)
  512. }
  513. if nproc != "2048" {
  514. c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc)
  515. }
  516. // Now restart daemon with a new default
  517. if err := s.d.Restart("--default-ulimit", "nofile=43"); err != nil {
  518. c.Fatal(err)
  519. }
  520. out, err = s.d.Cmd("start", "-a", "test")
  521. if err != nil {
  522. c.Fatal(err)
  523. }
  524. outArr = strings.Split(out, "\n")
  525. if len(outArr) < 2 {
  526. c.Fatalf("got unexpected output: %s", out)
  527. }
  528. nofile = strings.TrimSpace(outArr[0])
  529. nproc = strings.TrimSpace(outArr[1])
  530. if nofile != "43" {
  531. c.Fatalf("expected `ulimit -n` to be `43`, got: %s", nofile)
  532. }
  533. if nproc != "2048" {
  534. c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc)
  535. }
  536. }
  537. // #11315
  538. func (s *DockerDaemonSuite) TestDaemonRestartRenameContainer(c *check.C) {
  539. if err := s.d.StartWithBusybox(); err != nil {
  540. c.Fatal(err)
  541. }
  542. if out, err := s.d.Cmd("run", "--name=test", "busybox"); err != nil {
  543. c.Fatal(err, out)
  544. }
  545. if out, err := s.d.Cmd("rename", "test", "test2"); err != nil {
  546. c.Fatal(err, out)
  547. }
  548. if err := s.d.Restart(); err != nil {
  549. c.Fatal(err)
  550. }
  551. if out, err := s.d.Cmd("start", "test2"); err != nil {
  552. c.Fatal(err, out)
  553. }
  554. }
  555. func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefault(c *check.C) {
  556. if err := s.d.StartWithBusybox(); err != nil {
  557. c.Fatal(err)
  558. }
  559. out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline")
  560. if err != nil {
  561. c.Fatal(out, err)
  562. }
  563. id := strings.TrimSpace(out)
  564. if out, err := s.d.Cmd("wait", id); err != nil {
  565. c.Fatal(out, err)
  566. }
  567. logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log")
  568. if _, err := os.Stat(logPath); err != nil {
  569. c.Fatal(err)
  570. }
  571. f, err := os.Open(logPath)
  572. if err != nil {
  573. c.Fatal(err)
  574. }
  575. var res struct {
  576. Log string `json:"log"`
  577. Stream string `json:"stream"`
  578. Time time.Time `json:"time"`
  579. }
  580. if err := json.NewDecoder(f).Decode(&res); err != nil {
  581. c.Fatal(err)
  582. }
  583. if res.Log != "testline\n" {
  584. c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n")
  585. }
  586. if res.Stream != "stdout" {
  587. c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout")
  588. }
  589. if !time.Now().After(res.Time) {
  590. c.Fatalf("Log time %v in future", res.Time)
  591. }
  592. }
  593. func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefaultOverride(c *check.C) {
  594. if err := s.d.StartWithBusybox(); err != nil {
  595. c.Fatal(err)
  596. }
  597. out, err := s.d.Cmd("run", "-d", "--log-driver=none", "busybox", "echo", "testline")
  598. if err != nil {
  599. c.Fatal(out, err)
  600. }
  601. id := strings.TrimSpace(out)
  602. if out, err := s.d.Cmd("wait", id); err != nil {
  603. c.Fatal(out, err)
  604. }
  605. logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log")
  606. if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) {
  607. c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err)
  608. }
  609. }
  610. func (s *DockerDaemonSuite) TestDaemonLoggingDriverNone(c *check.C) {
  611. if err := s.d.StartWithBusybox("--log-driver=none"); err != nil {
  612. c.Fatal(err)
  613. }
  614. out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline")
  615. if err != nil {
  616. c.Fatal(out, err)
  617. }
  618. id := strings.TrimSpace(out)
  619. if out, err := s.d.Cmd("wait", id); err != nil {
  620. c.Fatal(out, err)
  621. }
  622. logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log")
  623. if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) {
  624. c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err)
  625. }
  626. }
  627. func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) {
  628. if err := s.d.StartWithBusybox("--log-driver=none"); err != nil {
  629. c.Fatal(err)
  630. }
  631. out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "echo", "testline")
  632. if err != nil {
  633. c.Fatal(out, err)
  634. }
  635. id := strings.TrimSpace(out)
  636. if out, err := s.d.Cmd("wait", id); err != nil {
  637. c.Fatal(out, err)
  638. }
  639. logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log")
  640. if _, err := os.Stat(logPath); err != nil {
  641. c.Fatal(err)
  642. }
  643. f, err := os.Open(logPath)
  644. if err != nil {
  645. c.Fatal(err)
  646. }
  647. var res struct {
  648. Log string `json:"log"`
  649. Stream string `json:"stream"`
  650. Time time.Time `json:"time"`
  651. }
  652. if err := json.NewDecoder(f).Decode(&res); err != nil {
  653. c.Fatal(err)
  654. }
  655. if res.Log != "testline\n" {
  656. c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n")
  657. }
  658. if res.Stream != "stdout" {
  659. c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout")
  660. }
  661. if !time.Now().After(res.Time) {
  662. c.Fatalf("Log time %v in future", res.Time)
  663. }
  664. }
  665. func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) {
  666. if err := s.d.StartWithBusybox("--log-driver=none"); err != nil {
  667. c.Fatal(err)
  668. }
  669. out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline")
  670. if err != nil {
  671. c.Fatal(out, err)
  672. }
  673. id := strings.TrimSpace(out)
  674. out, err = s.d.Cmd("logs", id)
  675. if err == nil {
  676. c.Fatalf("Logs should fail with \"none\" driver")
  677. }
  678. if !strings.Contains(out, `\"logs\" command is supported only for \"json-file\" logging driver`) {
  679. c.Fatalf("There should be error about non-json-file driver, got %s", out)
  680. }
  681. }
  682. func (s *DockerDaemonSuite) TestDaemonDots(c *check.C) {
  683. if err := s.d.StartWithBusybox(); err != nil {
  684. c.Fatal(err)
  685. }
  686. // Now create 4 containers
  687. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  688. c.Fatalf("Error creating container: %q", err)
  689. }
  690. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  691. c.Fatalf("Error creating container: %q", err)
  692. }
  693. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  694. c.Fatalf("Error creating container: %q", err)
  695. }
  696. if _, err := s.d.Cmd("create", "busybox"); err != nil {
  697. c.Fatalf("Error creating container: %q", err)
  698. }
  699. s.d.Stop()
  700. s.d.Start("--log-level=debug")
  701. s.d.Stop()
  702. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  703. if strings.Contains(string(content), "....") {
  704. c.Fatalf("Debug level should not have ....\n%s", string(content))
  705. }
  706. s.d.Start("--log-level=error")
  707. s.d.Stop()
  708. content, _ = ioutil.ReadFile(s.d.logFile.Name())
  709. if strings.Contains(string(content), "....") {
  710. c.Fatalf("Error level should not have ....\n%s", string(content))
  711. }
  712. s.d.Start("--log-level=info")
  713. s.d.Stop()
  714. content, _ = ioutil.ReadFile(s.d.logFile.Name())
  715. if !strings.Contains(string(content), "....") {
  716. c.Fatalf("Info level should have ....\n%s", string(content))
  717. }
  718. }
  719. func (s *DockerDaemonSuite) TestDaemonUnixSockCleanedUp(c *check.C) {
  720. dir, err := ioutil.TempDir("", "socket-cleanup-test")
  721. if err != nil {
  722. c.Fatal(err)
  723. }
  724. defer os.RemoveAll(dir)
  725. sockPath := filepath.Join(dir, "docker.sock")
  726. if err := s.d.Start("--host", "unix://"+sockPath); err != nil {
  727. c.Fatal(err)
  728. }
  729. if _, err := os.Stat(sockPath); err != nil {
  730. c.Fatal("socket does not exist")
  731. }
  732. if err := s.d.Stop(); err != nil {
  733. c.Fatal(err)
  734. }
  735. if _, err := os.Stat(sockPath); err == nil || !os.IsNotExist(err) {
  736. c.Fatal("unix socket is not cleaned up")
  737. }
  738. }
  739. func (s *DockerDaemonSuite) TestDaemonwithwrongkey(c *check.C) {
  740. type Config struct {
  741. Crv string `json:"crv"`
  742. D string `json:"d"`
  743. Kid string `json:"kid"`
  744. Kty string `json:"kty"`
  745. X string `json:"x"`
  746. Y string `json:"y"`
  747. }
  748. os.Remove("/etc/docker/key.json")
  749. if err := s.d.Start(); err != nil {
  750. c.Fatalf("Failed to start daemon: %v", err)
  751. }
  752. if err := s.d.Stop(); err != nil {
  753. c.Fatalf("Could not stop daemon: %v", err)
  754. }
  755. config := &Config{}
  756. bytes, err := ioutil.ReadFile("/etc/docker/key.json")
  757. if err != nil {
  758. c.Fatalf("Error reading key.json file: %s", err)
  759. }
  760. // byte[] to Data-Struct
  761. if err := json.Unmarshal(bytes, &config); err != nil {
  762. c.Fatalf("Error Unmarshal: %s", err)
  763. }
  764. //replace config.Kid with the fake value
  765. config.Kid = "VSAJ:FUYR:X3H2:B2VZ:KZ6U:CJD5:K7BX:ZXHY:UZXT:P4FT:MJWG:HRJ4"
  766. // NEW Data-Struct to byte[]
  767. newBytes, err := json.Marshal(&config)
  768. if err != nil {
  769. c.Fatalf("Error Marshal: %s", err)
  770. }
  771. // write back
  772. if err := ioutil.WriteFile("/etc/docker/key.json", newBytes, 0400); err != nil {
  773. c.Fatalf("Error ioutil.WriteFile: %s", err)
  774. }
  775. defer os.Remove("/etc/docker/key.json")
  776. if err := s.d.Start(); err == nil {
  777. c.Fatalf("It should not be successful to start daemon with wrong key: %v", err)
  778. }
  779. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  780. if !strings.Contains(string(content), "Public Key ID does not match") {
  781. c.Fatal("Missing KeyID message from daemon logs")
  782. }
  783. }
  784. func (s *DockerDaemonSuite) TestDaemonRestartKillWait(c *check.C) {
  785. if err := s.d.StartWithBusybox(); err != nil {
  786. c.Fatalf("Could not start daemon with busybox: %v", err)
  787. }
  788. out, err := s.d.Cmd("run", "-id", "busybox", "/bin/cat")
  789. if err != nil {
  790. c.Fatalf("Could not run /bin/cat: err=%v\n%s", err, out)
  791. }
  792. containerID := strings.TrimSpace(out)
  793. if out, err := s.d.Cmd("kill", containerID); err != nil {
  794. c.Fatalf("Could not kill %s: err=%v\n%s", containerID, err, out)
  795. }
  796. if err := s.d.Restart(); err != nil {
  797. c.Fatalf("Could not restart daemon: %v", err)
  798. }
  799. errchan := make(chan error)
  800. go func() {
  801. if out, err := s.d.Cmd("wait", containerID); err != nil {
  802. errchan <- fmt.Errorf("%v:\n%s", err, out)
  803. }
  804. close(errchan)
  805. }()
  806. select {
  807. case <-time.After(5 * time.Second):
  808. c.Fatal("Waiting on a stopped (killed) container timed out")
  809. case err := <-errchan:
  810. if err != nil {
  811. c.Fatal(err)
  812. }
  813. }
  814. }
  815. // TestHttpsInfo connects via two-way authenticated HTTPS to the info endpoint
  816. func (s *DockerDaemonSuite) TestHttpsInfo(c *check.C) {
  817. const (
  818. testDaemonHttpsAddr = "localhost:4271"
  819. )
  820. if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  821. "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHttpsAddr); err != nil {
  822. c.Fatalf("Could not start daemon with busybox: %v", err)
  823. }
  824. //force tcp protocol
  825. host := fmt.Sprintf("tcp://%s", testDaemonHttpsAddr)
  826. daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"}
  827. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  828. if err != nil {
  829. c.Fatalf("Error Occurred: %s and output: %s", err, out)
  830. }
  831. }
  832. // TestHttpsInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint
  833. // by using a rogue client certificate and checks that it fails with the expected error.
  834. func (s *DockerDaemonSuite) TestHttpsInfoRogueCert(c *check.C) {
  835. const (
  836. errBadCertificate = "remote error: bad certificate"
  837. testDaemonHttpsAddr = "localhost:4271"
  838. )
  839. if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  840. "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHttpsAddr); err != nil {
  841. c.Fatalf("Could not start daemon with busybox: %v", err)
  842. }
  843. //force tcp protocol
  844. host := fmt.Sprintf("tcp://%s", testDaemonHttpsAddr)
  845. daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"}
  846. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  847. if err == nil || !strings.Contains(out, errBadCertificate) {
  848. c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out)
  849. }
  850. }
  851. // TestHttpsInfoRogueServerCert connects via two-way authenticated HTTPS to the info endpoint
  852. // which provides a rogue server certificate and checks that it fails with the expected error
  853. func (s *DockerDaemonSuite) TestHttpsInfoRogueServerCert(c *check.C) {
  854. const (
  855. errCaUnknown = "x509: certificate signed by unknown authority"
  856. testDaemonRogueHttpsAddr = "localhost:4272"
  857. )
  858. if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-rogue-cert.pem",
  859. "--tlskey", "fixtures/https/server-rogue-key.pem", "-H", testDaemonRogueHttpsAddr); err != nil {
  860. c.Fatalf("Could not start daemon with busybox: %v", err)
  861. }
  862. //force tcp protocol
  863. host := fmt.Sprintf("tcp://%s", testDaemonRogueHttpsAddr)
  864. daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"}
  865. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  866. if err == nil || !strings.Contains(out, errCaUnknown) {
  867. c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out)
  868. }
  869. }
  870. func pingContainers(c *check.C) {
  871. runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "container1",
  872. "--hostname", "fred", "busybox", "top")
  873. _, err := runCommand(runCmd)
  874. c.Assert(err, check.IsNil)
  875. runArgs := []string{"run", "--rm", "--link", "container1:alias1", "busybox", "sh", "-c"}
  876. pingCmd := "ping -c 1 %s -W 1"
  877. dockerCmd(c, append(runArgs, fmt.Sprintf(pingCmd, "alias1"))...)
  878. dockerCmd(c, "rm", "-f", "container1")
  879. }