docker_cli_daemon_test.go 99 KB

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