docker_cli_daemon_test.go 60 KB

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