docker_cli_daemon_test.go 96 KB

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