docker_cli_daemon_test.go 94 KB

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