docker_cli_daemon_test.go 96 KB

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