docker_cli_daemon_test.go 92 KB

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