docker_cli_daemon_test.go 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720
  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{"--rm", "busybox", "sh", "-c", pingCmd}
  795. _, err = d.Cmd("run", 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. daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"}
  1160. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1161. if err != nil {
  1162. c.Fatalf("Error Occurred: %s and output: %s", err, out)
  1163. }
  1164. }
  1165. // TestHttpsRun connects via two-way authenticated HTTPS to the create, attach, start, and wait endpoints.
  1166. // https://github.com/docker/docker/issues/19280
  1167. func (s *DockerDaemonSuite) TestHttpsRun(c *check.C) {
  1168. const (
  1169. testDaemonHTTPSAddr = "tcp://localhost:4271"
  1170. )
  1171. if err := s.d.StartWithBusybox("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  1172. "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr); err != nil {
  1173. c.Fatalf("Could not start daemon with busybox: %v", err)
  1174. }
  1175. daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"}
  1176. out, err := s.d.CmdWithArgs(daemonArgs, "run", "busybox", "echo", "TLS response")
  1177. if err != nil {
  1178. c.Fatalf("Error Occurred: %s and output: %s", err, out)
  1179. }
  1180. if !strings.Contains(out, "TLS response") {
  1181. c.Fatalf("expected output to include `TLS response`, got %v", out)
  1182. }
  1183. }
  1184. // TestTlsVerify verifies that --tlsverify=false turns on tls
  1185. func (s *DockerDaemonSuite) TestTlsVerify(c *check.C) {
  1186. out, err := exec.Command(dockerdBinary, "--tlsverify=false").CombinedOutput()
  1187. if err == nil || !strings.Contains(string(out), "Could not load X509 key pair") {
  1188. c.Fatalf("Daemon should not have started due to missing certs: %v\n%s", err, string(out))
  1189. }
  1190. }
  1191. // TestHttpsInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint
  1192. // by using a rogue client certificate and checks that it fails with the expected error.
  1193. func (s *DockerDaemonSuite) TestHttpsInfoRogueCert(c *check.C) {
  1194. const (
  1195. errBadCertificate = "bad certificate"
  1196. testDaemonHTTPSAddr = "tcp://localhost:4271"
  1197. )
  1198. if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem",
  1199. "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr); err != nil {
  1200. c.Fatalf("Could not start daemon with busybox: %v", err)
  1201. }
  1202. daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"}
  1203. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1204. if err == nil || !strings.Contains(out, errBadCertificate) {
  1205. c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out)
  1206. }
  1207. }
  1208. // TestHttpsInfoRogueServerCert connects via two-way authenticated HTTPS to the info endpoint
  1209. // which provides a rogue server certificate and checks that it fails with the expected error
  1210. func (s *DockerDaemonSuite) TestHttpsInfoRogueServerCert(c *check.C) {
  1211. const (
  1212. errCaUnknown = "x509: certificate signed by unknown authority"
  1213. testDaemonRogueHTTPSAddr = "tcp://localhost:4272"
  1214. )
  1215. if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-rogue-cert.pem",
  1216. "--tlskey", "fixtures/https/server-rogue-key.pem", "-H", testDaemonRogueHTTPSAddr); err != nil {
  1217. c.Fatalf("Could not start daemon with busybox: %v", err)
  1218. }
  1219. daemonArgs := []string{"--host", testDaemonRogueHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"}
  1220. out, err := s.d.CmdWithArgs(daemonArgs, "info")
  1221. if err == nil || !strings.Contains(out, errCaUnknown) {
  1222. c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out)
  1223. }
  1224. }
  1225. func pingContainers(c *check.C, d *Daemon, expectFailure bool) {
  1226. var dargs []string
  1227. if d != nil {
  1228. dargs = []string{"--host", d.sock()}
  1229. }
  1230. args := append(dargs, "run", "-d", "--name", "container1", "busybox", "top")
  1231. dockerCmd(c, args...)
  1232. args = append(dargs, "run", "--rm", "--link", "container1:alias1", "busybox", "sh", "-c")
  1233. pingCmd := "ping -c 1 %s -W 1"
  1234. args = append(args, fmt.Sprintf(pingCmd, "alias1"))
  1235. _, _, err := dockerCmdWithError(args...)
  1236. if expectFailure {
  1237. c.Assert(err, check.NotNil)
  1238. } else {
  1239. c.Assert(err, check.IsNil)
  1240. }
  1241. args = append(dargs, "rm", "-f", "container1")
  1242. dockerCmd(c, args...)
  1243. }
  1244. func (s *DockerDaemonSuite) TestDaemonRestartWithSocketAsVolume(c *check.C) {
  1245. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1246. socket := filepath.Join(s.d.folder, "docker.sock")
  1247. out, err := s.d.Cmd("run", "--restart=always", "-v", socket+":/sock", "busybox")
  1248. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1249. c.Assert(s.d.Restart(), check.IsNil)
  1250. }
  1251. // os.Kill should kill daemon ungracefully, leaving behind container mounts.
  1252. // A subsequent daemon restart shoud clean up said mounts.
  1253. func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonAndContainerKill(c *check.C) {
  1254. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1255. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  1256. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1257. id := strings.TrimSpace(out)
  1258. c.Assert(s.d.cmd.Process.Signal(os.Kill), check.IsNil)
  1259. mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1260. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1261. // container mounts should exist even after daemon has crashed.
  1262. comment := check.Commentf("%s should stay mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  1263. c.Assert(strings.Contains(string(mountOut), id), check.Equals, true, comment)
  1264. // kill the container
  1265. runCmd := exec.Command(ctrBinary, "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", "containers", "kill", id)
  1266. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  1267. c.Fatalf("Failed to run ctr, ExitCode: %d, err: %v output: %s id: %s\n", ec, err, out, id)
  1268. }
  1269. // restart daemon.
  1270. if err := s.d.Restart(); err != nil {
  1271. c.Fatal(err)
  1272. }
  1273. // Now, container mounts should be gone.
  1274. mountOut, err = ioutil.ReadFile("/proc/self/mountinfo")
  1275. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1276. comment = check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  1277. c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1278. }
  1279. // os.Interrupt should perform a graceful daemon shutdown and hence cleanup mounts.
  1280. func (s *DockerDaemonSuite) TestCleanupMountsAfterGracefulShutdown(c *check.C) {
  1281. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1282. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  1283. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1284. id := strings.TrimSpace(out)
  1285. // Send SIGINT and daemon should clean up
  1286. c.Assert(s.d.cmd.Process.Signal(os.Interrupt), check.IsNil)
  1287. // Wait for the daemon to stop.
  1288. c.Assert(<-s.d.wait, checker.IsNil)
  1289. mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1290. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1291. comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  1292. c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1293. }
  1294. func (s *DockerDaemonSuite) TestRunContainerWithBridgeNone(c *check.C) {
  1295. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1296. c.Assert(s.d.StartWithBusybox("-b", "none"), check.IsNil)
  1297. out, err := s.d.Cmd("run", "--rm", "busybox", "ip", "l")
  1298. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1299. c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1300. check.Commentf("There shouldn't be eth0 in container in default(bridge) mode when bridge network is disabled: %s", out))
  1301. out, err = s.d.Cmd("run", "--rm", "--net=bridge", "busybox", "ip", "l")
  1302. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1303. c.Assert(strings.Contains(out, "eth0"), check.Equals, false,
  1304. check.Commentf("There shouldn't be eth0 in container in bridge mode when bridge network is disabled: %s", out))
  1305. // the extra grep and awk clean up the output of `ip` to only list the number and name of
  1306. // interfaces, allowing for different versions of ip (e.g. inside and outside the container) to
  1307. // be used while still verifying that the interface list is the exact same
  1308. cmd := exec.Command("sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '")
  1309. stdout := bytes.NewBuffer(nil)
  1310. cmd.Stdout = stdout
  1311. if err := cmd.Run(); err != nil {
  1312. c.Fatal("Failed to get host network interface")
  1313. }
  1314. out, err = s.d.Cmd("run", "--rm", "--net=host", "busybox", "sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '")
  1315. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1316. c.Assert(out, check.Equals, fmt.Sprintf("%s", stdout),
  1317. check.Commentf("The network interfaces in container should be the same with host when --net=host when bridge network is disabled: %s", out))
  1318. }
  1319. func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *check.C) {
  1320. if err := s.d.StartWithBusybox(); err != nil {
  1321. t.Fatal(err)
  1322. }
  1323. if out, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top"); err != nil {
  1324. t.Fatal(out, err)
  1325. }
  1326. if err := s.d.Restart(); err != nil {
  1327. t.Fatal(err)
  1328. }
  1329. // Container 'test' should be removed without error
  1330. if out, err := s.d.Cmd("rm", "test"); err != nil {
  1331. t.Fatal(out, err)
  1332. }
  1333. }
  1334. func (s *DockerDaemonSuite) TestDaemonRestartCleanupNetns(c *check.C) {
  1335. if err := s.d.StartWithBusybox(); err != nil {
  1336. c.Fatal(err)
  1337. }
  1338. out, err := s.d.Cmd("run", "--name", "netns", "-d", "busybox", "top")
  1339. if err != nil {
  1340. c.Fatal(out, err)
  1341. }
  1342. // Get sandbox key via inspect
  1343. out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.SandboxKey}}'", "netns")
  1344. if err != nil {
  1345. c.Fatalf("Error inspecting container: %s, %v", out, err)
  1346. }
  1347. fileName := strings.Trim(out, " \r\n'")
  1348. if out, err := s.d.Cmd("stop", "netns"); err != nil {
  1349. c.Fatal(out, err)
  1350. }
  1351. // Test if the file still exists
  1352. out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", fileName))
  1353. out = strings.TrimSpace(out)
  1354. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1355. c.Assert(out, check.Equals, fileName, check.Commentf("Output: %s", out))
  1356. // Remove the container and restart the daemon
  1357. if out, err := s.d.Cmd("rm", "netns"); err != nil {
  1358. c.Fatal(out, err)
  1359. }
  1360. if err := s.d.Restart(); err != nil {
  1361. c.Fatal(err)
  1362. }
  1363. // Test again and see now the netns file does not exist
  1364. out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", fileName))
  1365. out = strings.TrimSpace(out)
  1366. c.Assert(err, check.Not(check.IsNil), check.Commentf("Output: %s", out))
  1367. }
  1368. // tests regression detailed in #13964 where DOCKER_TLS_VERIFY env is ignored
  1369. func (s *DockerDaemonSuite) TestDaemonNoTlsCliTlsVerifyWithEnv(c *check.C) {
  1370. host := "tcp://localhost:4271"
  1371. c.Assert(s.d.Start("-H", host), check.IsNil)
  1372. cmd := exec.Command(dockerBinary, "-H", host, "info")
  1373. cmd.Env = []string{"DOCKER_TLS_VERIFY=1", "DOCKER_CERT_PATH=fixtures/https"}
  1374. out, _, err := runCommandWithOutput(cmd)
  1375. c.Assert(err, check.Not(check.IsNil), check.Commentf("%s", out))
  1376. c.Assert(strings.Contains(out, "error occurred trying to connect"), check.Equals, true)
  1377. }
  1378. func setupV6() error {
  1379. // Hack to get the right IPv6 address on docker0, which has already been created
  1380. return exec.Command("ip", "addr", "add", "fe80::1/64", "dev", "docker0").Run()
  1381. }
  1382. func teardownV6() error {
  1383. return exec.Command("ip", "addr", "del", "fe80::1/64", "dev", "docker0").Run()
  1384. }
  1385. func (s *DockerDaemonSuite) TestDaemonRestartWithContainerWithRestartPolicyAlways(c *check.C) {
  1386. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1387. out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top")
  1388. c.Assert(err, check.IsNil)
  1389. id := strings.TrimSpace(out)
  1390. _, err = s.d.Cmd("stop", id)
  1391. c.Assert(err, check.IsNil)
  1392. _, err = s.d.Cmd("wait", id)
  1393. c.Assert(err, check.IsNil)
  1394. out, err = s.d.Cmd("ps", "-q")
  1395. c.Assert(err, check.IsNil)
  1396. c.Assert(out, check.Equals, "")
  1397. c.Assert(s.d.Restart(), check.IsNil)
  1398. out, err = s.d.Cmd("ps", "-q")
  1399. c.Assert(err, check.IsNil)
  1400. c.Assert(strings.TrimSpace(out), check.Equals, id[:12])
  1401. }
  1402. func (s *DockerDaemonSuite) TestDaemonWideLogConfig(c *check.C) {
  1403. if err := s.d.StartWithBusybox("--log-opt=max-size=1k"); err != nil {
  1404. c.Fatal(err)
  1405. }
  1406. name := "logtest"
  1407. out, err := s.d.Cmd("run", "-d", "--log-opt=max-file=5", "--name", name, "busybox", "top")
  1408. c.Assert(err, check.IsNil, check.Commentf("Output: %s, err: %v", out, err))
  1409. out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Config }}", name)
  1410. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1411. c.Assert(out, checker.Contains, "max-size:1k")
  1412. c.Assert(out, checker.Contains, "max-file:5")
  1413. out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Type }}", name)
  1414. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1415. c.Assert(strings.TrimSpace(out), checker.Equals, "json-file")
  1416. }
  1417. func (s *DockerDaemonSuite) TestDaemonRestartWithPausedContainer(c *check.C) {
  1418. if err := s.d.StartWithBusybox(); err != nil {
  1419. c.Fatal(err)
  1420. }
  1421. if out, err := s.d.Cmd("run", "-i", "-d", "--name", "test", "busybox", "top"); err != nil {
  1422. c.Fatal(err, out)
  1423. }
  1424. if out, err := s.d.Cmd("pause", "test"); err != nil {
  1425. c.Fatal(err, out)
  1426. }
  1427. if err := s.d.Restart(); err != nil {
  1428. c.Fatal(err)
  1429. }
  1430. errchan := make(chan error)
  1431. go func() {
  1432. out, err := s.d.Cmd("start", "test")
  1433. if err != nil {
  1434. errchan <- fmt.Errorf("%v:\n%s", err, out)
  1435. }
  1436. name := strings.TrimSpace(out)
  1437. if name != "test" {
  1438. errchan <- fmt.Errorf("Paused container start error on docker daemon restart, expected 'test' but got '%s'", name)
  1439. }
  1440. close(errchan)
  1441. }()
  1442. select {
  1443. case <-time.After(5 * time.Second):
  1444. c.Fatal("Waiting on start a container timed out")
  1445. case err := <-errchan:
  1446. if err != nil {
  1447. c.Fatal(err)
  1448. }
  1449. }
  1450. }
  1451. func (s *DockerDaemonSuite) TestDaemonRestartRmVolumeInUse(c *check.C) {
  1452. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  1453. out, err := s.d.Cmd("create", "-v", "test:/foo", "busybox")
  1454. c.Assert(err, check.IsNil, check.Commentf(out))
  1455. c.Assert(s.d.Restart(), check.IsNil)
  1456. out, err = s.d.Cmd("volume", "rm", "test")
  1457. c.Assert(err, check.NotNil, check.Commentf("should not be able to remove in use volume after daemon restart"))
  1458. c.Assert(out, checker.Contains, "in use")
  1459. }
  1460. func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *check.C) {
  1461. c.Assert(s.d.Start(), check.IsNil)
  1462. _, err := s.d.Cmd("volume", "create", "--name", "test")
  1463. c.Assert(err, check.IsNil)
  1464. c.Assert(s.d.Restart(), check.IsNil)
  1465. _, err = s.d.Cmd("volume", "inspect", "test")
  1466. c.Assert(err, check.IsNil)
  1467. }
  1468. func (s *DockerDaemonSuite) TestDaemonCorruptedLogDriverAddress(c *check.C) {
  1469. c.Assert(s.d.Start("--log-driver=syslog", "--log-opt", "syslog-address=corrupted:42"), check.NotNil)
  1470. expected := "Failed to set log opts: syslog-address should be in form proto://address"
  1471. runCmd := exec.Command("grep", expected, s.d.LogFileName())
  1472. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  1473. c.Fatalf("Expected %q message; but doesn't exist in log: %q, err: %v", expected, out, err)
  1474. }
  1475. }
  1476. func (s *DockerDaemonSuite) TestDaemonCorruptedFluentdAddress(c *check.C) {
  1477. c.Assert(s.d.Start("--log-driver=fluentd", "--log-opt", "fluentd-address=corrupted:c"), check.NotNil)
  1478. expected := "Failed to set log opts: invalid fluentd-address corrupted:c: "
  1479. runCmd := exec.Command("grep", expected, s.d.LogFileName())
  1480. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  1481. c.Fatalf("Expected %q message; but doesn't exist in log: %q, err: %v", expected, out, err)
  1482. }
  1483. }
  1484. func (s *DockerDaemonSuite) TestDaemonStartWithoutHost(c *check.C) {
  1485. s.d.useDefaultHost = true
  1486. defer func() {
  1487. s.d.useDefaultHost = false
  1488. }()
  1489. c.Assert(s.d.Start(), check.IsNil)
  1490. }
  1491. func (s *DockerDaemonSuite) TestDaemonStartWithDefalutTlsHost(c *check.C) {
  1492. s.d.useDefaultTLSHost = true
  1493. defer func() {
  1494. s.d.useDefaultTLSHost = false
  1495. }()
  1496. if err := s.d.Start(
  1497. "--tlsverify",
  1498. "--tlscacert", "fixtures/https/ca.pem",
  1499. "--tlscert", "fixtures/https/server-cert.pem",
  1500. "--tlskey", "fixtures/https/server-key.pem"); err != nil {
  1501. c.Fatalf("Could not start daemon: %v", err)
  1502. }
  1503. // The client with --tlsverify should also use default host localhost:2376
  1504. tmpHost := os.Getenv("DOCKER_HOST")
  1505. defer func() {
  1506. os.Setenv("DOCKER_HOST", tmpHost)
  1507. }()
  1508. os.Setenv("DOCKER_HOST", "")
  1509. out, _ := dockerCmd(
  1510. c,
  1511. "--tlsverify",
  1512. "--tlscacert", "fixtures/https/ca.pem",
  1513. "--tlscert", "fixtures/https/client-cert.pem",
  1514. "--tlskey", "fixtures/https/client-key.pem",
  1515. "version",
  1516. )
  1517. if !strings.Contains(out, "Server") {
  1518. c.Fatalf("docker version should return information of server side")
  1519. }
  1520. }
  1521. func (s *DockerDaemonSuite) TestBridgeIPIsExcludedFromAllocatorPool(c *check.C) {
  1522. defaultNetworkBridge := "docker0"
  1523. deleteInterface(c, defaultNetworkBridge)
  1524. bridgeIP := "192.169.1.1"
  1525. bridgeRange := bridgeIP + "/30"
  1526. err := s.d.StartWithBusybox("--bip", bridgeRange)
  1527. c.Assert(err, check.IsNil)
  1528. defer s.d.Restart()
  1529. var cont int
  1530. for {
  1531. contName := fmt.Sprintf("container%d", cont)
  1532. _, err = s.d.Cmd("run", "--name", contName, "-d", "busybox", "/bin/sleep", "2")
  1533. if err != nil {
  1534. // pool exhausted
  1535. break
  1536. }
  1537. ip, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.IPAddress}}'", contName)
  1538. c.Assert(err, check.IsNil)
  1539. c.Assert(ip, check.Not(check.Equals), bridgeIP)
  1540. cont++
  1541. }
  1542. }
  1543. // Test daemon for no space left on device error
  1544. func (s *DockerDaemonSuite) TestDaemonNoSpaceLeftOnDeviceError(c *check.C) {
  1545. testRequires(c, SameHostDaemon, DaemonIsLinux, Network)
  1546. testDir, err := ioutil.TempDir("", "no-space-left-on-device-test")
  1547. c.Assert(err, checker.IsNil)
  1548. defer os.RemoveAll(testDir)
  1549. c.Assert(mount.MakeRShared(testDir), checker.IsNil)
  1550. defer mount.Unmount(testDir)
  1551. // create a 2MiB image and mount it as graph root
  1552. // 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)
  1553. dockerCmd(c, "run", "--rm", "-v", testDir+":/test", "busybox", "sh", "-c", "dd of=/test/testfs.img bs=1M seek=2 count=0")
  1554. out, _, err := runCommandWithOutput(exec.Command("mkfs.ext4", "-F", filepath.Join(testDir, "testfs.img"))) // `mkfs.ext4` is not in busybox
  1555. c.Assert(err, checker.IsNil, check.Commentf(out))
  1556. cmd := exec.Command("losetup", "-f", "--show", filepath.Join(testDir, "testfs.img"))
  1557. loout, err := cmd.CombinedOutput()
  1558. c.Assert(err, checker.IsNil)
  1559. loopname := strings.TrimSpace(string(loout))
  1560. defer exec.Command("losetup", "-d", loopname).Run()
  1561. 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))
  1562. defer mount.Unmount(filepath.Join(testDir, "test-mount"))
  1563. err = s.d.Start("--graph", filepath.Join(testDir, "test-mount"))
  1564. defer s.d.Stop()
  1565. c.Assert(err, check.IsNil)
  1566. // pull a repository large enough to fill the mount point
  1567. pullOut, err := s.d.Cmd("pull", "registry:2")
  1568. c.Assert(err, checker.NotNil, check.Commentf(pullOut))
  1569. c.Assert(pullOut, checker.Contains, "no space left on device")
  1570. }
  1571. // Test daemon restart with container links + auto restart
  1572. func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) {
  1573. d := NewDaemon(c)
  1574. defer d.Stop()
  1575. err := d.StartWithBusybox()
  1576. c.Assert(err, checker.IsNil)
  1577. parent1Args := []string{}
  1578. parent2Args := []string{}
  1579. wg := sync.WaitGroup{}
  1580. maxChildren := 10
  1581. chErr := make(chan error, maxChildren)
  1582. for i := 0; i < maxChildren; i++ {
  1583. wg.Add(1)
  1584. name := fmt.Sprintf("test%d", i)
  1585. if i < maxChildren/2 {
  1586. parent1Args = append(parent1Args, []string{"--link", name}...)
  1587. } else {
  1588. parent2Args = append(parent2Args, []string{"--link", name}...)
  1589. }
  1590. go func() {
  1591. _, err = d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top")
  1592. chErr <- err
  1593. wg.Done()
  1594. }()
  1595. }
  1596. wg.Wait()
  1597. close(chErr)
  1598. for err := range chErr {
  1599. c.Assert(err, check.IsNil)
  1600. }
  1601. parent1Args = append([]string{"run", "-d"}, parent1Args...)
  1602. parent1Args = append(parent1Args, []string{"--name=parent1", "--restart=always", "busybox", "top"}...)
  1603. parent2Args = append([]string{"run", "-d"}, parent2Args...)
  1604. parent2Args = append(parent2Args, []string{"--name=parent2", "--restart=always", "busybox", "top"}...)
  1605. _, err = d.Cmd(parent1Args[0], parent1Args[1:]...)
  1606. c.Assert(err, check.IsNil)
  1607. _, err = d.Cmd(parent2Args[0], parent2Args[1:]...)
  1608. c.Assert(err, check.IsNil)
  1609. err = d.Stop()
  1610. c.Assert(err, check.IsNil)
  1611. // clear the log file -- we don't need any of it but may for the next part
  1612. // can ignore the error here, this is just a cleanup
  1613. os.Truncate(d.LogFileName(), 0)
  1614. err = d.Start()
  1615. c.Assert(err, check.IsNil)
  1616. for _, num := range []string{"1", "2"} {
  1617. out, err := d.Cmd("inspect", "-f", "{{ .State.Running }}", "parent"+num)
  1618. c.Assert(err, check.IsNil)
  1619. if strings.TrimSpace(out) != "true" {
  1620. log, _ := ioutil.ReadFile(d.LogFileName())
  1621. c.Fatalf("parent container is not running\n%s", string(log))
  1622. }
  1623. }
  1624. }
  1625. func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *check.C) {
  1626. testRequires(c, DaemonIsLinux)
  1627. cgroupParent := "test"
  1628. name := "cgroup-test"
  1629. err := s.d.StartWithBusybox("--cgroup-parent", cgroupParent)
  1630. c.Assert(err, check.IsNil)
  1631. defer s.d.Restart()
  1632. out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup")
  1633. c.Assert(err, checker.IsNil)
  1634. cgroupPaths := parseCgroupPaths(string(out))
  1635. c.Assert(len(cgroupPaths), checker.Not(checker.Equals), 0, check.Commentf("unexpected output - %q", string(out)))
  1636. out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name)
  1637. c.Assert(err, checker.IsNil)
  1638. id := strings.TrimSpace(string(out))
  1639. expectedCgroup := path.Join(cgroupParent, id)
  1640. found := false
  1641. for _, path := range cgroupPaths {
  1642. if strings.HasSuffix(path, expectedCgroup) {
  1643. found = true
  1644. break
  1645. }
  1646. }
  1647. c.Assert(found, checker.True, check.Commentf("Cgroup path for container (%s) doesn't found in cgroups file: %s", expectedCgroup, cgroupPaths))
  1648. }
  1649. func (s *DockerDaemonSuite) TestDaemonRestartWithLinks(c *check.C) {
  1650. testRequires(c, DaemonIsLinux) // Windows does not support links
  1651. err := s.d.StartWithBusybox()
  1652. c.Assert(err, check.IsNil)
  1653. out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1654. c.Assert(err, check.IsNil, check.Commentf(out))
  1655. out, err = s.d.Cmd("run", "--name=test2", "--link", "test:abc", "busybox", "sh", "-c", "ping -c 1 -w 1 abc")
  1656. c.Assert(err, check.IsNil, check.Commentf(out))
  1657. c.Assert(s.d.Restart(), check.IsNil)
  1658. // should fail since test is not running yet
  1659. out, err = s.d.Cmd("start", "test2")
  1660. c.Assert(err, check.NotNil, check.Commentf(out))
  1661. out, err = s.d.Cmd("start", "test")
  1662. c.Assert(err, check.IsNil, check.Commentf(out))
  1663. out, err = s.d.Cmd("start", "-a", "test2")
  1664. c.Assert(err, check.IsNil, check.Commentf(out))
  1665. c.Assert(strings.Contains(out, "1 packets transmitted, 1 packets received"), check.Equals, true, check.Commentf(out))
  1666. }
  1667. func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *check.C) {
  1668. testRequires(c, DaemonIsLinux) // Windows does not support links
  1669. err := s.d.StartWithBusybox()
  1670. c.Assert(err, check.IsNil)
  1671. out, err := s.d.Cmd("create", "--name=test", "busybox")
  1672. c.Assert(err, check.IsNil, check.Commentf(out))
  1673. out, err = s.d.Cmd("run", "-d", "--name=test2", "busybox", "top")
  1674. c.Assert(err, check.IsNil, check.Commentf(out))
  1675. test2ID := strings.TrimSpace(out)
  1676. out, err = s.d.Cmd("run", "-d", "--name=test3", "--link", "test2:abc", "busybox", "top")
  1677. test3ID := strings.TrimSpace(out)
  1678. c.Assert(s.d.Restart(), check.IsNil)
  1679. out, err = s.d.Cmd("create", "--name=test", "busybox")
  1680. c.Assert(err, check.NotNil, check.Commentf("expected error trying to create container with duplicate name"))
  1681. // this one is no longer needed, removing simplifies the remainder of the test
  1682. out, err = s.d.Cmd("rm", "-f", "test")
  1683. c.Assert(err, check.IsNil, check.Commentf(out))
  1684. out, err = s.d.Cmd("ps", "-a", "--no-trunc")
  1685. c.Assert(err, check.IsNil, check.Commentf(out))
  1686. lines := strings.Split(strings.TrimSpace(out), "\n")[1:]
  1687. test2validated := false
  1688. test3validated := false
  1689. for _, line := range lines {
  1690. fields := strings.Fields(line)
  1691. names := fields[len(fields)-1]
  1692. switch fields[0] {
  1693. case test2ID:
  1694. c.Assert(names, check.Equals, "test2,test3/abc")
  1695. test2validated = true
  1696. case test3ID:
  1697. c.Assert(names, check.Equals, "test3")
  1698. test3validated = true
  1699. }
  1700. }
  1701. c.Assert(test2validated, check.Equals, true)
  1702. c.Assert(test3validated, check.Equals, true)
  1703. }
  1704. // TestDaemonRestartWithKilledRunningContainer requires live restore of running containers
  1705. func (s *DockerDaemonSuite) TestDaemonRestartWithKilledRunningContainer(t *check.C) {
  1706. // TODO(mlaventure): Not sure what would the exit code be on windows
  1707. testRequires(t, DaemonIsLinux)
  1708. if err := s.d.StartWithBusybox(); err != nil {
  1709. t.Fatal(err)
  1710. }
  1711. cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top")
  1712. defer s.d.Stop()
  1713. if err != nil {
  1714. t.Fatal(cid, err)
  1715. }
  1716. cid = strings.TrimSpace(cid)
  1717. pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid)
  1718. t.Assert(err, check.IsNil)
  1719. pid = strings.TrimSpace(pid)
  1720. // Kill the daemon
  1721. if err := s.d.Kill(); err != nil {
  1722. t.Fatal(err)
  1723. }
  1724. // kill the container
  1725. runCmd := exec.Command(ctrBinary, "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", "containers", "kill", cid)
  1726. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  1727. t.Fatalf("Failed to run ctr, ExitCode: %d, err: '%v' output: '%s' cid: '%s'\n", ec, err, out, cid)
  1728. }
  1729. // Give time to containerd to process the command if we don't
  1730. // the exit event might be received after we do the inspect
  1731. pidCmd := exec.Command("kill", "-0", pid)
  1732. _, ec, _ := runCommandWithOutput(pidCmd)
  1733. for ec == 0 {
  1734. time.Sleep(1 * time.Second)
  1735. _, ec, _ = runCommandWithOutput(pidCmd)
  1736. }
  1737. // restart the daemon
  1738. if err := s.d.Start(); err != nil {
  1739. t.Fatal(err)
  1740. }
  1741. // Check that we've got the correct exit code
  1742. out, err := s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", cid)
  1743. t.Assert(err, check.IsNil)
  1744. out = strings.TrimSpace(out)
  1745. if out != "143" {
  1746. t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "143", out, cid)
  1747. }
  1748. }
  1749. // os.Kill should kill daemon ungracefully, leaving behind live containers.
  1750. // The live containers should be known to the restarted daemon. Stopping
  1751. // them now, should remove the mounts.
  1752. func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonCrash(c *check.C) {
  1753. testRequires(c, DaemonIsLinux)
  1754. c.Assert(s.d.StartWithBusybox("--live-restore"), check.IsNil)
  1755. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  1756. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1757. id := strings.TrimSpace(out)
  1758. c.Assert(s.d.cmd.Process.Signal(os.Kill), check.IsNil)
  1759. mountOut, err := ioutil.ReadFile("/proc/self/mountinfo")
  1760. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1761. // container mounts should exist even after daemon has crashed.
  1762. comment := check.Commentf("%s should stay mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  1763. c.Assert(strings.Contains(string(mountOut), id), check.Equals, true, comment)
  1764. // restart daemon.
  1765. if err := s.d.Restart("--live-restore"); err != nil {
  1766. c.Fatal(err)
  1767. }
  1768. // container should be running.
  1769. out, err = s.d.Cmd("inspect", "--format='{{.State.Running}}'", id)
  1770. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1771. out = strings.TrimSpace(out)
  1772. if out != "true" {
  1773. c.Fatalf("Container %s expected to stay alive after daemon restart", id)
  1774. }
  1775. // 'docker stop' should work.
  1776. out, err = s.d.Cmd("stop", id)
  1777. c.Assert(err, check.IsNil, check.Commentf("Output: %s", out))
  1778. // Now, container mounts should be gone.
  1779. mountOut, err = ioutil.ReadFile("/proc/self/mountinfo")
  1780. c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut))
  1781. comment = check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.folder, mountOut)
  1782. c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment)
  1783. }
  1784. // TestDaemonRestartWithUnpausedRunningContainer requires live restore of running containers.
  1785. func (s *DockerDaemonSuite) TestDaemonRestartWithUnpausedRunningContainer(t *check.C) {
  1786. // TODO(mlaventure): Not sure what would the exit code be on windows
  1787. testRequires(t, DaemonIsLinux)
  1788. if err := s.d.StartWithBusybox("--live-restore"); err != nil {
  1789. t.Fatal(err)
  1790. }
  1791. cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top")
  1792. defer s.d.Stop()
  1793. if err != nil {
  1794. t.Fatal(cid, err)
  1795. }
  1796. cid = strings.TrimSpace(cid)
  1797. pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid)
  1798. t.Assert(err, check.IsNil)
  1799. pid = strings.TrimSpace(pid)
  1800. // pause the container
  1801. if _, err := s.d.Cmd("pause", cid); err != nil {
  1802. t.Fatal(cid, err)
  1803. }
  1804. // Kill the daemon
  1805. if err := s.d.Kill(); err != nil {
  1806. t.Fatal(err)
  1807. }
  1808. // resume the container
  1809. runCmd := exec.Command(ctrBinary, "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", "containers", "resume", cid)
  1810. if out, ec, err := runCommandWithOutput(runCmd); err != nil {
  1811. t.Fatalf("Failed to run ctr, ExitCode: %d, err: '%v' output: '%s' cid: '%s'\n", ec, err, out, cid)
  1812. }
  1813. // Give time to containerd to process the command if we don't
  1814. // the resume event might be received after we do the inspect
  1815. pidCmd := exec.Command("kill", "-0", pid)
  1816. _, ec, _ := runCommandWithOutput(pidCmd)
  1817. for ec == 0 {
  1818. time.Sleep(1 * time.Second)
  1819. _, ec, _ = runCommandWithOutput(pidCmd)
  1820. }
  1821. // restart the daemon
  1822. if err := s.d.Start("--live-restore"); err != nil {
  1823. t.Fatal(err)
  1824. }
  1825. // Check that we've got the correct status
  1826. out, err := s.d.Cmd("inspect", "-f", "{{.State.Status}}", cid)
  1827. t.Assert(err, check.IsNil)
  1828. out = strings.TrimSpace(out)
  1829. if out != "running" {
  1830. t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "running", out, cid)
  1831. }
  1832. if _, err := s.d.Cmd("kill", cid); err != nil {
  1833. t.Fatal(err)
  1834. }
  1835. }
  1836. // TestRunLinksChanged checks that creating a new container with the same name does not update links
  1837. // this ensures that the old, pre gh#16032 functionality continues on
  1838. func (s *DockerDaemonSuite) TestRunLinksChanged(c *check.C) {
  1839. testRequires(c, DaemonIsLinux) // Windows does not support links
  1840. err := s.d.StartWithBusybox()
  1841. c.Assert(err, check.IsNil)
  1842. out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1843. c.Assert(err, check.IsNil, check.Commentf(out))
  1844. out, err = s.d.Cmd("run", "--name=test2", "--link=test:abc", "busybox", "sh", "-c", "ping -c 1 abc")
  1845. c.Assert(err, check.IsNil, check.Commentf(out))
  1846. c.Assert(out, checker.Contains, "1 packets transmitted, 1 packets received")
  1847. out, err = s.d.Cmd("rm", "-f", "test")
  1848. c.Assert(err, check.IsNil, check.Commentf(out))
  1849. out, err = s.d.Cmd("run", "-d", "--name=test", "busybox", "top")
  1850. c.Assert(err, check.IsNil, check.Commentf(out))
  1851. out, err = s.d.Cmd("start", "-a", "test2")
  1852. c.Assert(err, check.NotNil, check.Commentf(out))
  1853. c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  1854. err = s.d.Restart()
  1855. c.Assert(err, check.IsNil)
  1856. out, err = s.d.Cmd("start", "-a", "test2")
  1857. c.Assert(err, check.NotNil, check.Commentf(out))
  1858. c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received")
  1859. }
  1860. func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *check.C) {
  1861. testRequires(c, DaemonIsLinux, NotPpc64le)
  1862. newD := NewDaemon(c)
  1863. infoLog := "\x1b[34mINFO\x1b"
  1864. p, tty, err := pty.Open()
  1865. c.Assert(err, checker.IsNil)
  1866. defer func() {
  1867. tty.Close()
  1868. p.Close()
  1869. }()
  1870. b := bytes.NewBuffer(nil)
  1871. go io.Copy(b, p)
  1872. // Enable coloring explicitly
  1873. newD.StartWithLogFile(tty, "--raw-logs=false")
  1874. newD.Stop()
  1875. c.Assert(b.String(), checker.Contains, infoLog)
  1876. b.Reset()
  1877. // Disable coloring explicitly
  1878. newD.StartWithLogFile(tty, "--raw-logs=true")
  1879. newD.Stop()
  1880. c.Assert(b.String(), check.Not(checker.Contains), infoLog)
  1881. }
  1882. func (s *DockerDaemonSuite) TestDaemonDebugLog(c *check.C) {
  1883. testRequires(c, DaemonIsLinux, NotPpc64le)
  1884. newD := NewDaemon(c)
  1885. debugLog := "\x1b[37mDEBU\x1b"
  1886. p, tty, err := pty.Open()
  1887. c.Assert(err, checker.IsNil)
  1888. defer func() {
  1889. tty.Close()
  1890. p.Close()
  1891. }()
  1892. b := bytes.NewBuffer(nil)
  1893. go io.Copy(b, p)
  1894. newD.StartWithLogFile(tty, "--debug")
  1895. newD.Stop()
  1896. c.Assert(b.String(), checker.Contains, debugLog)
  1897. }
  1898. func (s *DockerSuite) TestDaemonDiscoveryBackendConfigReload(c *check.C) {
  1899. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1900. // daemon config file
  1901. daemonConfig := `{ "debug" : false }`
  1902. configFilePath := "test.json"
  1903. configFile, err := os.Create(configFilePath)
  1904. c.Assert(err, checker.IsNil)
  1905. fmt.Fprintf(configFile, "%s", daemonConfig)
  1906. d := NewDaemon(c)
  1907. err = d.Start(fmt.Sprintf("--config-file=%s", configFilePath))
  1908. c.Assert(err, checker.IsNil)
  1909. defer d.Stop()
  1910. // daemon config file
  1911. daemonConfig = `{
  1912. "cluster-store": "consul://consuladdr:consulport/some/path",
  1913. "cluster-advertise": "192.168.56.100:0",
  1914. "debug" : false
  1915. }`
  1916. configFile.Close()
  1917. os.Remove(configFilePath)
  1918. configFile, err = os.Create(configFilePath)
  1919. c.Assert(err, checker.IsNil)
  1920. defer os.Remove(configFilePath)
  1921. fmt.Fprintf(configFile, "%s", daemonConfig)
  1922. configFile.Close()
  1923. syscall.Kill(d.cmd.Process.Pid, syscall.SIGHUP)
  1924. time.Sleep(3 * time.Second)
  1925. out, err := d.Cmd("info")
  1926. c.Assert(err, checker.IsNil)
  1927. c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Store: consul://consuladdr:consulport/some/path"))
  1928. c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Advertise: 192.168.56.100:0"))
  1929. }
  1930. // Test for #21956
  1931. func (s *DockerDaemonSuite) TestDaemonLogOptions(c *check.C) {
  1932. err := s.d.StartWithBusybox("--log-driver=syslog", "--log-opt=syslog-address=udp://127.0.0.1:514")
  1933. c.Assert(err, check.IsNil)
  1934. out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "top")
  1935. c.Assert(err, check.IsNil, check.Commentf(out))
  1936. id := strings.TrimSpace(out)
  1937. out, err = s.d.Cmd("inspect", "--format='{{.HostConfig.LogConfig}}'", id)
  1938. c.Assert(err, check.IsNil, check.Commentf(out))
  1939. c.Assert(out, checker.Contains, "{json-file map[]}")
  1940. }
  1941. // Test case for #20936, #22443
  1942. func (s *DockerDaemonSuite) TestDaemonMaxConcurrency(c *check.C) {
  1943. c.Assert(s.d.Start("--max-concurrent-uploads=6", "--max-concurrent-downloads=8"), check.IsNil)
  1944. expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 6"`
  1945. expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"`
  1946. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  1947. c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  1948. c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  1949. }
  1950. // Test case for #20936, #22443
  1951. func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *check.C) {
  1952. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1953. // daemon config file
  1954. configFilePath := "test.json"
  1955. configFile, err := os.Create(configFilePath)
  1956. c.Assert(err, checker.IsNil)
  1957. defer os.Remove(configFilePath)
  1958. daemonConfig := `{ "max-concurrent-downloads" : 8 }`
  1959. fmt.Fprintf(configFile, "%s", daemonConfig)
  1960. configFile.Close()
  1961. c.Assert(s.d.Start(fmt.Sprintf("--config-file=%s", configFilePath)), check.IsNil)
  1962. expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"`
  1963. expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"`
  1964. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  1965. c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  1966. c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  1967. configFile, err = os.Create(configFilePath)
  1968. c.Assert(err, checker.IsNil)
  1969. daemonConfig = `{ "max-concurrent-uploads" : 7, "max-concurrent-downloads" : 9 }`
  1970. fmt.Fprintf(configFile, "%s", daemonConfig)
  1971. configFile.Close()
  1972. syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  1973. time.Sleep(3 * time.Second)
  1974. expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 7"`
  1975. expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 9"`
  1976. content, _ = ioutil.ReadFile(s.d.logFile.Name())
  1977. c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  1978. c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  1979. }
  1980. // Test case for #20936, #22443
  1981. func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *check.C) {
  1982. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1983. // daemon config file
  1984. configFilePath := "test.json"
  1985. configFile, err := os.Create(configFilePath)
  1986. c.Assert(err, checker.IsNil)
  1987. defer os.Remove(configFilePath)
  1988. daemonConfig := `{ "max-concurrent-uploads" : null }`
  1989. fmt.Fprintf(configFile, "%s", daemonConfig)
  1990. configFile.Close()
  1991. c.Assert(s.d.Start(fmt.Sprintf("--config-file=%s", configFilePath)), check.IsNil)
  1992. expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"`
  1993. expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 3"`
  1994. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  1995. c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  1996. c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  1997. configFile, err = os.Create(configFilePath)
  1998. c.Assert(err, checker.IsNil)
  1999. daemonConfig = `{ "max-concurrent-uploads" : 1, "max-concurrent-downloads" : null }`
  2000. fmt.Fprintf(configFile, "%s", daemonConfig)
  2001. configFile.Close()
  2002. syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  2003. time.Sleep(3 * time.Second)
  2004. expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 1"`
  2005. expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"`
  2006. content, _ = ioutil.ReadFile(s.d.logFile.Name())
  2007. c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads)
  2008. c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads)
  2009. configFile, err = os.Create(configFilePath)
  2010. c.Assert(err, checker.IsNil)
  2011. daemonConfig = `{ "labels":["foo=bar"] }`
  2012. fmt.Fprintf(configFile, "%s", daemonConfig)
  2013. configFile.Close()
  2014. syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  2015. time.Sleep(3 * time.Second)
  2016. expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 5"`
  2017. expectedMaxConcurrentDownloads = `level=debug msg="Reset 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. }
  2022. func (s *DockerDaemonSuite) TestBuildOnDisabledBridgeNetworkDaemon(c *check.C) {
  2023. err := s.d.StartWithBusybox("-b=none", "--iptables=false")
  2024. c.Assert(err, check.IsNil)
  2025. s.d.c.Logf("dockerBinary %s", dockerBinary)
  2026. out, code, err := s.d.buildImageWithOut("busyboxs",
  2027. `FROM busybox
  2028. RUN cat /etc/hosts`, false)
  2029. comment := check.Commentf("Failed to build image. output %s, exitCode %d, err %v", out, code, err)
  2030. c.Assert(err, check.IsNil, comment)
  2031. c.Assert(code, check.Equals, 0, comment)
  2032. }
  2033. // Test case for #21976
  2034. func (s *DockerDaemonSuite) TestDaemonDNSInHostMode(c *check.C) {
  2035. testRequires(c, SameHostDaemon, DaemonIsLinux)
  2036. err := s.d.StartWithBusybox("--dns", "1.2.3.4")
  2037. c.Assert(err, checker.IsNil)
  2038. expectedOutput := "nameserver 1.2.3.4"
  2039. out, _ := s.d.Cmd("run", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  2040. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  2041. }
  2042. // Test case for #21976
  2043. func (s *DockerDaemonSuite) TestDaemonDNSSearchInHostMode(c *check.C) {
  2044. testRequires(c, SameHostDaemon, DaemonIsLinux)
  2045. err := s.d.StartWithBusybox("--dns-search", "example.com")
  2046. c.Assert(err, checker.IsNil)
  2047. expectedOutput := "search example.com"
  2048. out, _ := s.d.Cmd("run", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  2049. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  2050. }
  2051. // Test case for #21976
  2052. func (s *DockerDaemonSuite) TestDaemonDNSOptionsInHostMode(c *check.C) {
  2053. testRequires(c, SameHostDaemon, DaemonIsLinux)
  2054. err := s.d.StartWithBusybox("--dns-opt", "timeout:3")
  2055. c.Assert(err, checker.IsNil)
  2056. expectedOutput := "options timeout:3"
  2057. out, _ := s.d.Cmd("run", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  2058. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  2059. }
  2060. func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) {
  2061. conf, err := ioutil.TempFile("", "config-file-")
  2062. c.Assert(err, check.IsNil)
  2063. configName := conf.Name()
  2064. conf.Close()
  2065. defer os.Remove(configName)
  2066. config := `
  2067. {
  2068. "runtimes": {
  2069. "oci": {
  2070. "path": "docker-runc"
  2071. },
  2072. "vm": {
  2073. "path": "/usr/local/bin/vm-manager",
  2074. "runtimeArgs": [
  2075. "--debug"
  2076. ]
  2077. }
  2078. }
  2079. }
  2080. `
  2081. ioutil.WriteFile(configName, []byte(config), 0644)
  2082. err = s.d.StartWithBusybox("--config-file", configName)
  2083. c.Assert(err, check.IsNil)
  2084. // Run with default runtime
  2085. out, err := s.d.Cmd("run", "--rm", "busybox", "ls")
  2086. c.Assert(err, check.IsNil, check.Commentf(out))
  2087. // Run with default runtime explicitly
  2088. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2089. c.Assert(err, check.IsNil, check.Commentf(out))
  2090. // Run with oci (same path as default) but keep it around
  2091. out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls")
  2092. c.Assert(err, check.IsNil, check.Commentf(out))
  2093. // Run with "vm"
  2094. out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls")
  2095. c.Assert(err, check.NotNil, check.Commentf(out))
  2096. c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2097. // Reset config to only have the default
  2098. config = `
  2099. {
  2100. "runtimes": {
  2101. }
  2102. }
  2103. `
  2104. ioutil.WriteFile(configName, []byte(config), 0644)
  2105. syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  2106. // Give daemon time to reload config
  2107. <-time.After(1 * time.Second)
  2108. // Run with default runtime
  2109. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2110. c.Assert(err, check.IsNil, check.Commentf(out))
  2111. // Run with "oci"
  2112. out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls")
  2113. c.Assert(err, check.NotNil, check.Commentf(out))
  2114. c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2115. // Start previously created container with oci
  2116. out, err = s.d.Cmd("start", "oci-runtime-ls")
  2117. c.Assert(err, check.NotNil, check.Commentf(out))
  2118. c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2119. // Check that we can't override the default runtime
  2120. config = `
  2121. {
  2122. "runtimes": {
  2123. "runc": {
  2124. "path": "my-runc"
  2125. }
  2126. }
  2127. }
  2128. `
  2129. ioutil.WriteFile(configName, []byte(config), 0644)
  2130. syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  2131. // Give daemon time to reload config
  2132. <-time.After(1 * time.Second)
  2133. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  2134. c.Assert(string(content), checker.Contains, `file configuration validation failed (runtime name 'runc' is reserved)`)
  2135. // Check that we can select a default runtime
  2136. config = `
  2137. {
  2138. "default-runtime": "vm",
  2139. "runtimes": {
  2140. "oci": {
  2141. "path": "docker-runc"
  2142. },
  2143. "vm": {
  2144. "path": "/usr/local/bin/vm-manager",
  2145. "runtimeArgs": [
  2146. "--debug"
  2147. ]
  2148. }
  2149. }
  2150. }
  2151. `
  2152. ioutil.WriteFile(configName, []byte(config), 0644)
  2153. syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP)
  2154. // Give daemon time to reload config
  2155. <-time.After(1 * time.Second)
  2156. out, err = s.d.Cmd("run", "--rm", "busybox", "ls")
  2157. c.Assert(err, check.NotNil, check.Commentf(out))
  2158. c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2159. // Run with default runtime explicitly
  2160. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2161. c.Assert(err, check.IsNil, check.Commentf(out))
  2162. }
  2163. func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) {
  2164. err := s.d.StartWithBusybox("--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
  2165. c.Assert(err, check.IsNil)
  2166. // Run with default runtime
  2167. out, err := s.d.Cmd("run", "--rm", "busybox", "ls")
  2168. c.Assert(err, check.IsNil, check.Commentf(out))
  2169. // Run with default runtime explicitly
  2170. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2171. c.Assert(err, check.IsNil, check.Commentf(out))
  2172. // Run with oci (same path as default) but keep it around
  2173. out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls")
  2174. c.Assert(err, check.IsNil, check.Commentf(out))
  2175. // Run with "vm"
  2176. out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls")
  2177. c.Assert(err, check.NotNil, check.Commentf(out))
  2178. c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2179. // Start a daemon without any extra runtimes
  2180. s.d.Stop()
  2181. err = s.d.StartWithBusybox()
  2182. c.Assert(err, check.IsNil)
  2183. // Run with default runtime
  2184. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2185. c.Assert(err, check.IsNil, check.Commentf(out))
  2186. // Run with "oci"
  2187. out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls")
  2188. c.Assert(err, check.NotNil, check.Commentf(out))
  2189. c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2190. // Start previously created container with oci
  2191. out, err = s.d.Cmd("start", "oci-runtime-ls")
  2192. c.Assert(err, check.NotNil, check.Commentf(out))
  2193. c.Assert(out, checker.Contains, "Unknown runtime specified oci")
  2194. // Check that we can't override the default runtime
  2195. s.d.Stop()
  2196. err = s.d.Start("--add-runtime", "runc=my-runc")
  2197. c.Assert(err, check.NotNil)
  2198. content, _ := ioutil.ReadFile(s.d.logFile.Name())
  2199. c.Assert(string(content), checker.Contains, `runtime name 'runc' is reserved`)
  2200. // Check that we can select a default runtime
  2201. s.d.Stop()
  2202. err = s.d.StartWithBusybox("--default-runtime=vm", "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager")
  2203. c.Assert(err, check.IsNil)
  2204. out, err = s.d.Cmd("run", "--rm", "busybox", "ls")
  2205. c.Assert(err, check.NotNil, check.Commentf(out))
  2206. c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory")
  2207. // Run with default runtime explicitly
  2208. out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls")
  2209. c.Assert(err, check.IsNil, check.Commentf(out))
  2210. }