docker_cli_daemon_test.go 74 KB

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