docker_cli_daemon_test.go 95 KB

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