docker_cli_daemon_test.go 98 KB

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