docker_cli_daemon_test.go 92 KB

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