docker_cli_daemon_test.go 106 KB

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