docker_cli_daemon_test.go 72 KB

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