docker_cli_daemon_test.go 97 KB

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