docker_cli_daemon_test.go 94 KB

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