docker_cli_daemon_test.go 94 KB

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