docker_cli_daemon_test.go 71 KB

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