docker_cli_daemon_test.go 95 KB

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