docker_cli_daemon_test.go 70 KB

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