docker_cli_daemon_test.go 81 KB

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