docker_cli_daemon_test.go 99 KB

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