docker_cli_daemon_test.go 99 KB

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