docker_cli_daemon_test.go 99 KB

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