docker_cli_daemon_test.go 98 KB

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