docker_cli_daemon_test.go 98 KB

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