docker_cli_daemon_test.go 98 KB

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