docker_cli_daemon_test.go 108 KB

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