docker_cli_daemon_test.go 95 KB

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