docker_cli_daemon_test.go 98 KB

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