docker_cli_daemon_test.go 33 KB

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