docker_cli_daemon_test.go 70 KB

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