docker_cli_daemon_test.go 62 KB

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