docker_cli_daemon_test.go 94 KB

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