docker_cli_daemon_test.go 94 KB

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