docker_cli_daemon_test.go 102 KB

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