docker_cli_daemon_test.go 47 KB

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