docker_cli_daemon_test.go 94 KB

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