docker_cli_daemon_test.go 92 KB

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