docker_cli_daemon_test.go 96 KB

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