docker_cli_daemon_test.go 96 KB

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