docker_cli_daemon_test.go 75 KB

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