docker_cli_daemon_test.go 98 KB

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