docker_cli_daemon_test.go 98 KB

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