docker_cli_daemon_test.go 100 KB

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