docker_cli_daemon_test.go 108 KB

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