docker_cli_daemon_test.go 98 KB

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