docker_cli_daemon_test.go 105 KB

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