docker_cli_daemon_test.go 95 KB

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