docker_cli_daemon_test.go 97 KB

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