docker_cli_daemon_test.go 96 KB

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