docker_cli_daemon_test.go 96 KB

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