docker_cli_swarm_test.go 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003
  1. // +build !windows
  2. package main
  3. import (
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "encoding/pem"
  8. "fmt"
  9. "io/ioutil"
  10. "net/http"
  11. "net/http/httptest"
  12. "os"
  13. "path/filepath"
  14. "runtime"
  15. "strings"
  16. "time"
  17. "github.com/cloudflare/cfssl/helpers"
  18. "github.com/docker/docker/api/types"
  19. "github.com/docker/docker/api/types/swarm"
  20. "github.com/docker/docker/integration-cli/checker"
  21. "github.com/docker/docker/integration-cli/cli"
  22. "github.com/docker/docker/integration-cli/daemon"
  23. "github.com/docker/libnetwork/driverapi"
  24. "github.com/docker/libnetwork/ipamapi"
  25. remoteipam "github.com/docker/libnetwork/ipams/remote/api"
  26. "github.com/docker/swarmkit/ca/keyutils"
  27. "github.com/go-check/check"
  28. "github.com/vishvananda/netlink"
  29. "gotest.tools/fs"
  30. "gotest.tools/icmd"
  31. )
  32. func (s *DockerSwarmSuite) TestSwarmUpdate(c *check.C) {
  33. d := s.AddDaemon(c, true, true)
  34. getSpec := func() swarm.Spec {
  35. sw := d.GetSwarm(c)
  36. return sw.Spec
  37. }
  38. out, err := d.Cmd("swarm", "update", "--cert-expiry", "30h", "--dispatcher-heartbeat", "11s")
  39. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  40. spec := getSpec()
  41. c.Assert(spec.CAConfig.NodeCertExpiry, checker.Equals, 30*time.Hour)
  42. c.Assert(spec.Dispatcher.HeartbeatPeriod, checker.Equals, 11*time.Second)
  43. // setting anything under 30m for cert-expiry is not allowed
  44. out, err = d.Cmd("swarm", "update", "--cert-expiry", "15m")
  45. c.Assert(err, checker.NotNil)
  46. c.Assert(out, checker.Contains, "minimum certificate expiry time")
  47. spec = getSpec()
  48. c.Assert(spec.CAConfig.NodeCertExpiry, checker.Equals, 30*time.Hour)
  49. // passing an external CA (this is without starting a root rotation) does not fail
  50. cli.Docker(cli.Args("swarm", "update", "--external-ca", "protocol=cfssl,url=https://something.org",
  51. "--external-ca", "protocol=cfssl,url=https://somethingelse.org,cacert=fixtures/https/ca.pem"),
  52. cli.Daemon(d)).Assert(c, icmd.Success)
  53. expected, err := ioutil.ReadFile("fixtures/https/ca.pem")
  54. c.Assert(err, checker.IsNil)
  55. spec = getSpec()
  56. c.Assert(spec.CAConfig.ExternalCAs, checker.HasLen, 2)
  57. c.Assert(spec.CAConfig.ExternalCAs[0].CACert, checker.Equals, "")
  58. c.Assert(spec.CAConfig.ExternalCAs[1].CACert, checker.Equals, string(expected))
  59. // passing an invalid external CA fails
  60. tempFile := fs.NewFile(c, "testfile", fs.WithContent("fakecert"))
  61. defer tempFile.Remove()
  62. result := cli.Docker(cli.Args("swarm", "update",
  63. "--external-ca", fmt.Sprintf("protocol=cfssl,url=https://something.org,cacert=%s", tempFile.Path())),
  64. cli.Daemon(d))
  65. result.Assert(c, icmd.Expected{
  66. ExitCode: 125,
  67. Err: "must be in PEM format",
  68. })
  69. }
  70. func (s *DockerSwarmSuite) TestSwarmInit(c *check.C) {
  71. d := s.AddDaemon(c, false, false)
  72. getSpec := func() swarm.Spec {
  73. sw := d.GetSwarm(c)
  74. return sw.Spec
  75. }
  76. // passing an invalid external CA fails
  77. tempFile := fs.NewFile(c, "testfile", fs.WithContent("fakecert"))
  78. defer tempFile.Remove()
  79. result := cli.Docker(cli.Args("swarm", "init", "--cert-expiry", "30h", "--dispatcher-heartbeat", "11s",
  80. "--external-ca", fmt.Sprintf("protocol=cfssl,url=https://somethingelse.org,cacert=%s", tempFile.Path())),
  81. cli.Daemon(d))
  82. result.Assert(c, icmd.Expected{
  83. ExitCode: 125,
  84. Err: "must be in PEM format",
  85. })
  86. cli.Docker(cli.Args("swarm", "init", "--cert-expiry", "30h", "--dispatcher-heartbeat", "11s",
  87. "--external-ca", "protocol=cfssl,url=https://something.org",
  88. "--external-ca", "protocol=cfssl,url=https://somethingelse.org,cacert=fixtures/https/ca.pem"),
  89. cli.Daemon(d)).Assert(c, icmd.Success)
  90. expected, err := ioutil.ReadFile("fixtures/https/ca.pem")
  91. c.Assert(err, checker.IsNil)
  92. spec := getSpec()
  93. c.Assert(spec.CAConfig.NodeCertExpiry, checker.Equals, 30*time.Hour)
  94. c.Assert(spec.Dispatcher.HeartbeatPeriod, checker.Equals, 11*time.Second)
  95. c.Assert(spec.CAConfig.ExternalCAs, checker.HasLen, 2)
  96. c.Assert(spec.CAConfig.ExternalCAs[0].CACert, checker.Equals, "")
  97. c.Assert(spec.CAConfig.ExternalCAs[1].CACert, checker.Equals, string(expected))
  98. c.Assert(d.SwarmLeave(true), checker.IsNil)
  99. cli.Docker(cli.Args("swarm", "init"), cli.Daemon(d)).Assert(c, icmd.Success)
  100. spec = getSpec()
  101. c.Assert(spec.CAConfig.NodeCertExpiry, checker.Equals, 90*24*time.Hour)
  102. c.Assert(spec.Dispatcher.HeartbeatPeriod, checker.Equals, 5*time.Second)
  103. }
  104. func (s *DockerSwarmSuite) TestSwarmInitIPv6(c *check.C) {
  105. testRequires(c, IPv6)
  106. d1 := s.AddDaemon(c, false, false)
  107. cli.Docker(cli.Args("swarm", "init", "--listen-add", "::1"), cli.Daemon(d1)).Assert(c, icmd.Success)
  108. d2 := s.AddDaemon(c, false, false)
  109. cli.Docker(cli.Args("swarm", "join", "::1"), cli.Daemon(d2)).Assert(c, icmd.Success)
  110. out := cli.Docker(cli.Args("info"), cli.Daemon(d2)).Assert(c, icmd.Success).Combined()
  111. c.Assert(out, checker.Contains, "Swarm: active")
  112. }
  113. func (s *DockerSwarmSuite) TestSwarmInitUnspecifiedAdvertiseAddr(c *check.C) {
  114. d := s.AddDaemon(c, false, false)
  115. out, err := d.Cmd("swarm", "init", "--advertise-addr", "0.0.0.0")
  116. c.Assert(err, checker.NotNil)
  117. c.Assert(out, checker.Contains, "advertise address must be a non-zero IP address")
  118. }
  119. func (s *DockerSwarmSuite) TestSwarmIncompatibleDaemon(c *check.C) {
  120. // init swarm mode and stop a daemon
  121. d := s.AddDaemon(c, true, true)
  122. info := d.SwarmInfo(c)
  123. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive)
  124. d.Stop(c)
  125. // start a daemon with --cluster-store and --cluster-advertise
  126. err := d.StartWithError("--cluster-store=consul://consuladdr:consulport/some/path", "--cluster-advertise=1.1.1.1:2375")
  127. c.Assert(err, checker.NotNil)
  128. content, err := d.ReadLogFile()
  129. c.Assert(err, checker.IsNil)
  130. c.Assert(string(content), checker.Contains, "--cluster-store and --cluster-advertise daemon configurations are incompatible with swarm mode")
  131. // start a daemon with --live-restore
  132. err = d.StartWithError("--live-restore")
  133. c.Assert(err, checker.NotNil)
  134. content, err = d.ReadLogFile()
  135. c.Assert(err, checker.IsNil)
  136. c.Assert(string(content), checker.Contains, "--live-restore daemon configuration is incompatible with swarm mode")
  137. // restart for teardown
  138. d.StartNode(c)
  139. }
  140. func (s *DockerSwarmSuite) TestSwarmServiceTemplatingHostname(c *check.C) {
  141. d := s.AddDaemon(c, true, true)
  142. hostname, err := d.Cmd("node", "inspect", "--format", "{{.Description.Hostname}}", "self")
  143. c.Assert(err, checker.IsNil, check.Commentf("%s", hostname))
  144. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "test", "--hostname", "{{.Service.Name}}-{{.Task.Slot}}-{{.Node.Hostname}}", "busybox", "top")
  145. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  146. // make sure task has been deployed.
  147. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  148. containers := d.ActiveContainers(c)
  149. out, err = d.Cmd("inspect", "--type", "container", "--format", "{{.Config.Hostname}}", containers[0])
  150. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  151. c.Assert(strings.Split(out, "\n")[0], checker.Equals, "test-1-"+strings.Split(hostname, "\n")[0], check.Commentf("hostname with templating invalid"))
  152. }
  153. // Test case for #24270
  154. func (s *DockerSwarmSuite) TestSwarmServiceListFilter(c *check.C) {
  155. d := s.AddDaemon(c, true, true)
  156. name1 := "redis-cluster-md5"
  157. name2 := "redis-cluster"
  158. name3 := "other-cluster"
  159. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name1, "busybox", "top")
  160. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  161. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  162. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name2, "busybox", "top")
  163. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  164. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  165. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name3, "busybox", "top")
  166. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  167. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  168. filter1 := "name=redis-cluster-md5"
  169. filter2 := "name=redis-cluster"
  170. // We search checker.Contains with `name+" "` to prevent prefix only.
  171. out, err = d.Cmd("service", "ls", "--filter", filter1)
  172. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  173. c.Assert(out, checker.Contains, name1+" ")
  174. c.Assert(out, checker.Not(checker.Contains), name2+" ")
  175. c.Assert(out, checker.Not(checker.Contains), name3+" ")
  176. out, err = d.Cmd("service", "ls", "--filter", filter2)
  177. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  178. c.Assert(out, checker.Contains, name1+" ")
  179. c.Assert(out, checker.Contains, name2+" ")
  180. c.Assert(out, checker.Not(checker.Contains), name3+" ")
  181. out, err = d.Cmd("service", "ls")
  182. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  183. c.Assert(out, checker.Contains, name1+" ")
  184. c.Assert(out, checker.Contains, name2+" ")
  185. c.Assert(out, checker.Contains, name3+" ")
  186. }
  187. func (s *DockerSwarmSuite) TestSwarmNodeListFilter(c *check.C) {
  188. d := s.AddDaemon(c, true, true)
  189. out, err := d.Cmd("node", "inspect", "--format", "{{ .Description.Hostname }}", "self")
  190. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  191. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  192. name := strings.TrimSpace(out)
  193. filter := "name=" + name[:4]
  194. out, err = d.Cmd("node", "ls", "--filter", filter)
  195. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  196. c.Assert(out, checker.Contains, name)
  197. out, err = d.Cmd("node", "ls", "--filter", "name=none")
  198. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  199. c.Assert(out, checker.Not(checker.Contains), name)
  200. }
  201. func (s *DockerSwarmSuite) TestSwarmNodeTaskListFilter(c *check.C) {
  202. d := s.AddDaemon(c, true, true)
  203. name := "redis-cluster-md5"
  204. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--replicas=3", "busybox", "top")
  205. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  206. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  207. // make sure task has been deployed.
  208. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 3)
  209. filter := "name=redis-cluster"
  210. out, err = d.Cmd("node", "ps", "--filter", filter, "self")
  211. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  212. c.Assert(out, checker.Contains, name+".1")
  213. c.Assert(out, checker.Contains, name+".2")
  214. c.Assert(out, checker.Contains, name+".3")
  215. out, err = d.Cmd("node", "ps", "--filter", "name=none", "self")
  216. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  217. c.Assert(out, checker.Not(checker.Contains), name+".1")
  218. c.Assert(out, checker.Not(checker.Contains), name+".2")
  219. c.Assert(out, checker.Not(checker.Contains), name+".3")
  220. }
  221. // Test case for #25375
  222. func (s *DockerSwarmSuite) TestSwarmPublishAdd(c *check.C) {
  223. d := s.AddDaemon(c, true, true)
  224. name := "top"
  225. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--label", "x=y", "busybox", "top")
  226. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  227. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  228. out, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", name)
  229. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  230. out, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", name)
  231. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  232. _, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", "--publish-add", "80:20", name)
  233. c.Assert(err, checker.NotNil)
  234. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.EndpointSpec.Ports }}", name)
  235. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  236. c.Assert(strings.TrimSpace(out), checker.Equals, "[{ tcp 80 80 ingress}]")
  237. }
  238. func (s *DockerSwarmSuite) TestSwarmServiceWithGroup(c *check.C) {
  239. d := s.AddDaemon(c, true, true)
  240. name := "top"
  241. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--user", "root:root", "--group", "wheel", "--group", "audio", "--group", "staff", "--group", "777", "busybox", "top")
  242. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  243. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  244. // make sure task has been deployed.
  245. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  246. out, err = d.Cmd("ps", "-q")
  247. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  248. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  249. container := strings.TrimSpace(out)
  250. out, err = d.Cmd("exec", container, "id")
  251. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  252. c.Assert(strings.TrimSpace(out), checker.Equals, "uid=0(root) gid=0(root) groups=10(wheel),29(audio),50(staff),777")
  253. }
  254. func (s *DockerSwarmSuite) TestSwarmContainerAutoStart(c *check.C) {
  255. d := s.AddDaemon(c, true, true)
  256. out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo")
  257. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  258. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  259. out, err = d.Cmd("run", "-id", "--restart=always", "--net=foo", "--name=test", "busybox", "top")
  260. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  261. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  262. out, err = d.Cmd("ps", "-q")
  263. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  264. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  265. d.RestartNode(c)
  266. out, err = d.Cmd("ps", "-q")
  267. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  268. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  269. }
  270. func (s *DockerSwarmSuite) TestSwarmContainerEndpointOptions(c *check.C) {
  271. d := s.AddDaemon(c, true, true)
  272. out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo")
  273. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  274. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  275. out, err = d.Cmd("run", "-d", "--net=foo", "--name=first", "--net-alias=first-alias", "busybox:glibc", "top")
  276. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  277. out, err = d.Cmd("run", "-d", "--net=foo", "--name=second", "busybox:glibc", "top")
  278. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  279. out, err = d.Cmd("run", "-d", "--net=foo", "--net-alias=third-alias", "busybox:glibc", "top")
  280. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  281. // ping first container and its alias, also ping third and anonymous container by its alias
  282. out, err = d.Cmd("exec", "second", "ping", "-c", "1", "first")
  283. c.Assert(err, check.IsNil, check.Commentf("%s", out))
  284. out, err = d.Cmd("exec", "second", "ping", "-c", "1", "first-alias")
  285. c.Assert(err, check.IsNil, check.Commentf("%s", out))
  286. out, err = d.Cmd("exec", "second", "ping", "-c", "1", "third-alias")
  287. c.Assert(err, check.IsNil, check.Commentf("%s", out))
  288. }
  289. func (s *DockerSwarmSuite) TestSwarmContainerAttachByNetworkId(c *check.C) {
  290. d := s.AddDaemon(c, true, true)
  291. out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "testnet")
  292. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  293. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  294. networkID := strings.TrimSpace(out)
  295. out, err = d.Cmd("run", "-d", "--net", networkID, "busybox", "top")
  296. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  297. cID := strings.TrimSpace(out)
  298. d.WaitRun(cID)
  299. out, err = d.Cmd("rm", "-f", cID)
  300. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  301. out, err = d.Cmd("network", "rm", "testnet")
  302. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  303. checkNetwork := func(*check.C) (interface{}, check.CommentInterface) {
  304. out, err := d.Cmd("network", "ls")
  305. c.Assert(err, checker.IsNil)
  306. return out, nil
  307. }
  308. waitAndAssert(c, 3*time.Second, checkNetwork, checker.Not(checker.Contains), "testnet")
  309. }
  310. func (s *DockerSwarmSuite) TestOverlayAttachable(c *check.C) {
  311. d := s.AddDaemon(c, true, true)
  312. out, err := d.Cmd("network", "create", "-d", "overlay", "--attachable", "ovnet")
  313. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  314. // validate attachable
  315. out, err = d.Cmd("network", "inspect", "--format", "{{json .Attachable}}", "ovnet")
  316. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  317. c.Assert(strings.TrimSpace(out), checker.Equals, "true")
  318. // validate containers can attach to this overlay network
  319. out, err = d.Cmd("run", "-d", "--network", "ovnet", "--name", "c1", "busybox", "top")
  320. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  321. // redo validation, there was a bug that the value of attachable changes after
  322. // containers attach to the network
  323. out, err = d.Cmd("network", "inspect", "--format", "{{json .Attachable}}", "ovnet")
  324. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  325. c.Assert(strings.TrimSpace(out), checker.Equals, "true")
  326. }
  327. func (s *DockerSwarmSuite) TestOverlayAttachableOnSwarmLeave(c *check.C) {
  328. d := s.AddDaemon(c, true, true)
  329. // Create an attachable swarm network
  330. nwName := "attovl"
  331. out, err := d.Cmd("network", "create", "-d", "overlay", "--attachable", nwName)
  332. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  333. // Connect a container to the network
  334. out, err = d.Cmd("run", "-d", "--network", nwName, "--name", "c1", "busybox", "top")
  335. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  336. // Leave the swarm
  337. c.Assert(d.SwarmLeave(true), checker.IsNil)
  338. // Check the container is disconnected
  339. out, err = d.Cmd("inspect", "c1", "--format", "{{.NetworkSettings.Networks."+nwName+"}}")
  340. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  341. c.Assert(strings.TrimSpace(out), checker.Equals, "<no value>")
  342. // Check the network is gone
  343. out, err = d.Cmd("network", "ls", "--format", "{{.Name}}")
  344. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  345. c.Assert(out, checker.Not(checker.Contains), nwName)
  346. }
  347. func (s *DockerSwarmSuite) TestOverlayAttachableReleaseResourcesOnFailure(c *check.C) {
  348. d := s.AddDaemon(c, true, true)
  349. // Create attachable network
  350. out, err := d.Cmd("network", "create", "-d", "overlay", "--attachable", "--subnet", "10.10.9.0/24", "ovnet")
  351. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  352. // Attach a container with specific IP
  353. out, err = d.Cmd("run", "-d", "--network", "ovnet", "--name", "c1", "--ip", "10.10.9.33", "busybox", "top")
  354. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  355. // Attempt to attach another container with same IP, must fail
  356. out, err = d.Cmd("run", "-d", "--network", "ovnet", "--name", "c2", "--ip", "10.10.9.33", "busybox", "top")
  357. c.Assert(err, checker.NotNil, check.Commentf("%s", out))
  358. // Remove first container
  359. out, err = d.Cmd("rm", "-f", "c1")
  360. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  361. // Verify the network can be removed, no phantom network attachment task left over
  362. out, err = d.Cmd("network", "rm", "ovnet")
  363. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  364. }
  365. func (s *DockerSwarmSuite) TestSwarmIngressNetwork(c *check.C) {
  366. d := s.AddDaemon(c, true, true)
  367. // Ingress network can be removed
  368. removeNetwork := func(name string) *icmd.Result {
  369. return cli.Docker(
  370. cli.Args("-H", d.Sock(), "network", "rm", name),
  371. cli.WithStdin(strings.NewReader("Y")))
  372. }
  373. result := removeNetwork("ingress")
  374. result.Assert(c, icmd.Success)
  375. // And recreated
  376. out, err := d.Cmd("network", "create", "-d", "overlay", "--ingress", "new-ingress")
  377. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  378. // But only one is allowed
  379. out, err = d.Cmd("network", "create", "-d", "overlay", "--ingress", "another-ingress")
  380. c.Assert(err, checker.NotNil)
  381. c.Assert(strings.TrimSpace(out), checker.Contains, "is already present")
  382. // It cannot be removed if it is being used
  383. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv1", "-p", "9000:8000", "busybox", "top")
  384. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  385. result = removeNetwork("new-ingress")
  386. result.Assert(c, icmd.Expected{
  387. ExitCode: 1,
  388. Err: "ingress network cannot be removed because service",
  389. })
  390. // But it can be removed once no more services depend on it
  391. out, err = d.Cmd("service", "update", "--detach", "--publish-rm", "9000:8000", "srv1")
  392. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  393. result = removeNetwork("new-ingress")
  394. result.Assert(c, icmd.Success)
  395. // A service which needs the ingress network cannot be created if no ingress is present
  396. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv2", "-p", "500:500", "busybox", "top")
  397. c.Assert(err, checker.NotNil)
  398. c.Assert(strings.TrimSpace(out), checker.Contains, "no ingress network is present")
  399. // An existing service cannot be updated to use the ingress nw if the nw is not present
  400. out, err = d.Cmd("service", "update", "--detach", "--publish-add", "9000:8000", "srv1")
  401. c.Assert(err, checker.NotNil)
  402. c.Assert(strings.TrimSpace(out), checker.Contains, "no ingress network is present")
  403. // But services which do not need routing mesh can be created regardless
  404. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv3", "--endpoint-mode", "dnsrr", "busybox", "top")
  405. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  406. }
  407. func (s *DockerSwarmSuite) TestSwarmCreateServiceWithNoIngressNetwork(c *check.C) {
  408. d := s.AddDaemon(c, true, true)
  409. // Remove ingress network
  410. result := cli.Docker(
  411. cli.Args("-H", d.Sock(), "network", "rm", "ingress"),
  412. cli.WithStdin(strings.NewReader("Y")))
  413. result.Assert(c, icmd.Success)
  414. // Create a overlay network and launch a service on it
  415. // Make sure nothing panics because ingress network is missing
  416. out, err := d.Cmd("network", "create", "-d", "overlay", "another-network")
  417. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  418. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv4", "--network", "another-network", "busybox", "top")
  419. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  420. }
  421. // Test case for #24108, also the case from:
  422. // https://github.com/docker/docker/pull/24620#issuecomment-233715656
  423. func (s *DockerSwarmSuite) TestSwarmTaskListFilter(c *check.C) {
  424. d := s.AddDaemon(c, true, true)
  425. name := "redis-cluster-md5"
  426. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--replicas=3", "busybox", "top")
  427. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  428. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  429. filter := "name=redis-cluster"
  430. checkNumTasks := func(*check.C) (interface{}, check.CommentInterface) {
  431. out, err := d.Cmd("service", "ps", "--filter", filter, name)
  432. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  433. return len(strings.Split(out, "\n")) - 2, nil // includes header and nl in last line
  434. }
  435. // wait until all tasks have been created
  436. waitAndAssert(c, defaultReconciliationTimeout, checkNumTasks, checker.Equals, 3)
  437. out, err = d.Cmd("service", "ps", "--filter", filter, name)
  438. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  439. c.Assert(out, checker.Contains, name+".1")
  440. c.Assert(out, checker.Contains, name+".2")
  441. c.Assert(out, checker.Contains, name+".3")
  442. out, err = d.Cmd("service", "ps", "--filter", "name="+name+".1", name)
  443. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  444. c.Assert(out, checker.Contains, name+".1")
  445. c.Assert(out, checker.Not(checker.Contains), name+".2")
  446. c.Assert(out, checker.Not(checker.Contains), name+".3")
  447. out, err = d.Cmd("service", "ps", "--filter", "name=none", name)
  448. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  449. c.Assert(out, checker.Not(checker.Contains), name+".1")
  450. c.Assert(out, checker.Not(checker.Contains), name+".2")
  451. c.Assert(out, checker.Not(checker.Contains), name+".3")
  452. name = "redis-cluster-sha1"
  453. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--mode=global", "busybox", "top")
  454. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  455. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  456. waitAndAssert(c, defaultReconciliationTimeout, checkNumTasks, checker.Equals, 1)
  457. filter = "name=redis-cluster"
  458. out, err = d.Cmd("service", "ps", "--filter", filter, name)
  459. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  460. c.Assert(out, checker.Contains, name)
  461. out, err = d.Cmd("service", "ps", "--filter", "name="+name, name)
  462. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  463. c.Assert(out, checker.Contains, name)
  464. out, err = d.Cmd("service", "ps", "--filter", "name=none", name)
  465. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  466. c.Assert(out, checker.Not(checker.Contains), name)
  467. }
  468. func (s *DockerSwarmSuite) TestPsListContainersFilterIsTask(c *check.C) {
  469. d := s.AddDaemon(c, true, true)
  470. // Create a bare container
  471. out, err := d.Cmd("run", "-d", "--name=bare-container", "busybox", "top")
  472. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  473. bareID := strings.TrimSpace(out)[:12]
  474. // Create a service
  475. name := "busybox-top"
  476. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "top")
  477. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  478. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  479. // make sure task has been deployed.
  480. waitAndAssert(c, defaultReconciliationTimeout, d.CheckServiceRunningTasks(name), checker.Equals, 1)
  481. // Filter non-tasks
  482. out, err = d.Cmd("ps", "-a", "-q", "--filter=is-task=false")
  483. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  484. psOut := strings.TrimSpace(out)
  485. c.Assert(psOut, checker.Equals, bareID, check.Commentf("Expected id %s, got %s for is-task label, output %q", bareID, psOut, out))
  486. // Filter tasks
  487. out, err = d.Cmd("ps", "-a", "-q", "--filter=is-task=true")
  488. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  489. lines := strings.Split(strings.Trim(out, "\n "), "\n")
  490. c.Assert(lines, checker.HasLen, 1)
  491. c.Assert(lines[0], checker.Not(checker.Equals), bareID, check.Commentf("Expected not %s, but got it for is-task label, output %q", bareID, out))
  492. }
  493. const globalNetworkPlugin = "global-network-plugin"
  494. const globalIPAMPlugin = "global-ipam-plugin"
  495. func setupRemoteGlobalNetworkPlugin(c *check.C, mux *http.ServeMux, url, netDrv, ipamDrv string) {
  496. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  497. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  498. fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
  499. })
  500. // Network driver implementation
  501. mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  502. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  503. fmt.Fprintf(w, `{"Scope":"global"}`)
  504. })
  505. mux.HandleFunc(fmt.Sprintf("/%s.AllocateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  506. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  507. if err != nil {
  508. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  509. return
  510. }
  511. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  512. fmt.Fprintf(w, "null")
  513. })
  514. mux.HandleFunc(fmt.Sprintf("/%s.FreeNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  515. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  516. fmt.Fprintf(w, "null")
  517. })
  518. mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  519. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  520. if err != nil {
  521. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  522. return
  523. }
  524. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  525. fmt.Fprintf(w, "null")
  526. })
  527. mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  528. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  529. fmt.Fprintf(w, "null")
  530. })
  531. mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  532. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  533. fmt.Fprintf(w, `{"Interface":{"MacAddress":"a0:b1:c2:d3:e4:f5"}}`)
  534. })
  535. mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  536. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  537. veth := &netlink.Veth{
  538. LinkAttrs: netlink.LinkAttrs{Name: "randomIfName", TxQLen: 0}, PeerName: "cnt0"}
  539. if err := netlink.LinkAdd(veth); err != nil {
  540. fmt.Fprintf(w, `{"Error":"failed to add veth pair: `+err.Error()+`"}`)
  541. } else {
  542. fmt.Fprintf(w, `{"InterfaceName":{ "SrcName":"cnt0", "DstPrefix":"veth"}}`)
  543. }
  544. })
  545. mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  546. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  547. fmt.Fprintf(w, "null")
  548. })
  549. mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  550. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  551. if link, err := netlink.LinkByName("cnt0"); err == nil {
  552. netlink.LinkDel(link)
  553. }
  554. fmt.Fprintf(w, "null")
  555. })
  556. // IPAM Driver implementation
  557. var (
  558. poolRequest remoteipam.RequestPoolRequest
  559. poolReleaseReq remoteipam.ReleasePoolRequest
  560. addressRequest remoteipam.RequestAddressRequest
  561. addressReleaseReq remoteipam.ReleaseAddressRequest
  562. lAS = "localAS"
  563. gAS = "globalAS"
  564. pool = "172.28.0.0/16"
  565. poolID = lAS + "/" + pool
  566. gw = "172.28.255.254/16"
  567. )
  568. mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  569. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  570. fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
  571. })
  572. mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  573. err := json.NewDecoder(r.Body).Decode(&poolRequest)
  574. if err != nil {
  575. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  576. return
  577. }
  578. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  579. if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
  580. fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
  581. } else if poolRequest.Pool != "" && poolRequest.Pool != pool {
  582. fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
  583. } else {
  584. fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
  585. }
  586. })
  587. mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  588. err := json.NewDecoder(r.Body).Decode(&addressRequest)
  589. if err != nil {
  590. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  591. return
  592. }
  593. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  594. // make sure libnetwork is now querying on the expected pool id
  595. if addressRequest.PoolID != poolID {
  596. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  597. } else if addressRequest.Address != "" {
  598. fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
  599. } else {
  600. fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
  601. }
  602. })
  603. mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  604. err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
  605. if err != nil {
  606. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  607. return
  608. }
  609. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  610. // make sure libnetwork is now asking to release the expected address from the expected poolid
  611. if addressRequest.PoolID != poolID {
  612. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  613. } else if addressReleaseReq.Address != gw {
  614. fmt.Fprintf(w, `{"Error":"unknown address"}`)
  615. } else {
  616. fmt.Fprintf(w, "null")
  617. }
  618. })
  619. mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  620. err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
  621. if err != nil {
  622. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  623. return
  624. }
  625. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  626. // make sure libnetwork is now asking to release the expected poolid
  627. if addressRequest.PoolID != poolID {
  628. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  629. } else {
  630. fmt.Fprintf(w, "null")
  631. }
  632. })
  633. err := os.MkdirAll("/etc/docker/plugins", 0755)
  634. c.Assert(err, checker.IsNil)
  635. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", netDrv)
  636. err = ioutil.WriteFile(fileName, []byte(url), 0644)
  637. c.Assert(err, checker.IsNil)
  638. ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", ipamDrv)
  639. err = ioutil.WriteFile(ipamFileName, []byte(url), 0644)
  640. c.Assert(err, checker.IsNil)
  641. }
  642. func (s *DockerSwarmSuite) TestSwarmNetworkPlugin(c *check.C) {
  643. mux := http.NewServeMux()
  644. s.server = httptest.NewServer(mux)
  645. c.Assert(s.server, check.NotNil) // check that HTTP server has started
  646. setupRemoteGlobalNetworkPlugin(c, mux, s.server.URL, globalNetworkPlugin, globalIPAMPlugin)
  647. defer func() {
  648. s.server.Close()
  649. err := os.RemoveAll("/etc/docker/plugins")
  650. c.Assert(err, checker.IsNil)
  651. }()
  652. d := s.AddDaemon(c, true, true)
  653. out, err := d.Cmd("network", "create", "-d", globalNetworkPlugin, "foo")
  654. c.Assert(err, checker.NotNil, check.Commentf("%s", out))
  655. c.Assert(out, checker.Contains, "not supported in swarm mode")
  656. }
  657. // Test case for #24712
  658. func (s *DockerSwarmSuite) TestSwarmServiceEnvFile(c *check.C) {
  659. d := s.AddDaemon(c, true, true)
  660. path := filepath.Join(d.Folder, "env.txt")
  661. err := ioutil.WriteFile(path, []byte("VAR1=A\nVAR2=A\n"), 0644)
  662. c.Assert(err, checker.IsNil)
  663. name := "worker"
  664. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--env-file", path, "--env", "VAR1=B", "--env", "VAR1=C", "--env", "VAR2=", "--env", "VAR2", "--name", name, "busybox", "top")
  665. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  666. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  667. // The complete env is [VAR1=A VAR2=A VAR1=B VAR1=C VAR2= VAR2] and duplicates will be removed => [VAR1=C VAR2]
  668. out, err = d.Cmd("inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.Env }}", name)
  669. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  670. c.Assert(out, checker.Contains, "[VAR1=C VAR2]")
  671. }
  672. func (s *DockerSwarmSuite) TestSwarmServiceTTY(c *check.C) {
  673. d := s.AddDaemon(c, true, true)
  674. name := "top"
  675. ttyCheck := "if [ -t 0 ]; then echo TTY > /status && top; else echo none > /status && top; fi"
  676. // Without --tty
  677. expectedOutput := "none"
  678. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", ttyCheck)
  679. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  680. // Make sure task has been deployed.
  681. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  682. // We need to get the container id.
  683. out, err = d.Cmd("ps", "-q", "--no-trunc")
  684. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  685. id := strings.TrimSpace(out)
  686. out, err = d.Cmd("exec", id, "cat", "/status")
  687. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  688. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  689. // Remove service
  690. out, err = d.Cmd("service", "rm", name)
  691. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  692. // Make sure container has been destroyed.
  693. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 0)
  694. // With --tty
  695. expectedOutput = "TTY"
  696. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--tty", "busybox", "sh", "-c", ttyCheck)
  697. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  698. // Make sure task has been deployed.
  699. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  700. // We need to get the container id.
  701. out, err = d.Cmd("ps", "-q", "--no-trunc")
  702. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  703. id = strings.TrimSpace(out)
  704. out, err = d.Cmd("exec", id, "cat", "/status")
  705. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  706. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  707. }
  708. func (s *DockerSwarmSuite) TestSwarmServiceTTYUpdate(c *check.C) {
  709. d := s.AddDaemon(c, true, true)
  710. // Create a service
  711. name := "top"
  712. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "top")
  713. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  714. // Make sure task has been deployed.
  715. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  716. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.TTY }}", name)
  717. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  718. c.Assert(strings.TrimSpace(out), checker.Equals, "false")
  719. out, err = d.Cmd("service", "update", "--detach", "--tty", name)
  720. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  721. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.TTY }}", name)
  722. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  723. c.Assert(strings.TrimSpace(out), checker.Equals, "true")
  724. }
  725. func (s *DockerSwarmSuite) TestSwarmServiceNetworkUpdate(c *check.C) {
  726. d := s.AddDaemon(c, true, true)
  727. result := icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "foo"))
  728. result.Assert(c, icmd.Success)
  729. fooNetwork := strings.TrimSpace(string(result.Combined()))
  730. result = icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "bar"))
  731. result.Assert(c, icmd.Success)
  732. barNetwork := strings.TrimSpace(string(result.Combined()))
  733. result = icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "baz"))
  734. result.Assert(c, icmd.Success)
  735. bazNetwork := strings.TrimSpace(string(result.Combined()))
  736. // Create a service
  737. name := "top"
  738. result = icmd.RunCmd(d.Command("service", "create", "--detach", "--no-resolve-image", "--network", "foo", "--network", "bar", "--name", name, "busybox", "top"))
  739. result.Assert(c, icmd.Success)
  740. // Make sure task has been deployed.
  741. waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskNetworks, checker.DeepEquals,
  742. map[string]int{fooNetwork: 1, barNetwork: 1})
  743. // Remove a network
  744. result = icmd.RunCmd(d.Command("service", "update", "--detach", "--network-rm", "foo", name))
  745. result.Assert(c, icmd.Success)
  746. waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskNetworks, checker.DeepEquals,
  747. map[string]int{barNetwork: 1})
  748. // Add a network
  749. result = icmd.RunCmd(d.Command("service", "update", "--detach", "--network-add", "baz", name))
  750. result.Assert(c, icmd.Success)
  751. waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskNetworks, checker.DeepEquals,
  752. map[string]int{barNetwork: 1, bazNetwork: 1})
  753. }
  754. func (s *DockerSwarmSuite) TestDNSConfig(c *check.C) {
  755. d := s.AddDaemon(c, true, true)
  756. // Create a service
  757. name := "top"
  758. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--dns=1.2.3.4", "--dns-search=example.com", "--dns-option=timeout:3", "busybox", "top")
  759. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  760. // Make sure task has been deployed.
  761. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  762. // We need to get the container id.
  763. out, err = d.Cmd("ps", "-a", "-q", "--no-trunc")
  764. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  765. id := strings.TrimSpace(out)
  766. // Compare against expected output.
  767. expectedOutput1 := "nameserver 1.2.3.4"
  768. expectedOutput2 := "search example.com"
  769. expectedOutput3 := "options timeout:3"
  770. out, err = d.Cmd("exec", id, "cat", "/etc/resolv.conf")
  771. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  772. c.Assert(out, checker.Contains, expectedOutput1, check.Commentf("Expected '%s', but got %q", expectedOutput1, out))
  773. c.Assert(out, checker.Contains, expectedOutput2, check.Commentf("Expected '%s', but got %q", expectedOutput2, out))
  774. c.Assert(out, checker.Contains, expectedOutput3, check.Commentf("Expected '%s', but got %q", expectedOutput3, out))
  775. }
  776. func (s *DockerSwarmSuite) TestDNSConfigUpdate(c *check.C) {
  777. d := s.AddDaemon(c, true, true)
  778. // Create a service
  779. name := "top"
  780. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "top")
  781. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  782. // Make sure task has been deployed.
  783. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  784. out, err = d.Cmd("service", "update", "--detach", "--dns-add=1.2.3.4", "--dns-search-add=example.com", "--dns-option-add=timeout:3", name)
  785. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  786. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.DNSConfig }}", name)
  787. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  788. c.Assert(strings.TrimSpace(out), checker.Equals, "{[1.2.3.4] [example.com] [timeout:3]}")
  789. }
  790. func getNodeStatus(c *check.C, d *daemon.Daemon) swarm.LocalNodeState {
  791. info := d.SwarmInfo(c)
  792. return info.LocalNodeState
  793. }
  794. func checkKeyIsEncrypted(d *daemon.Daemon) func(*check.C) (interface{}, check.CommentInterface) {
  795. return func(c *check.C) (interface{}, check.CommentInterface) {
  796. keyBytes, err := ioutil.ReadFile(filepath.Join(d.Folder, "root", "swarm", "certificates", "swarm-node.key"))
  797. if err != nil {
  798. return fmt.Errorf("error reading key: %v", err), nil
  799. }
  800. keyBlock, _ := pem.Decode(keyBytes)
  801. if keyBlock == nil {
  802. return fmt.Errorf("invalid PEM-encoded private key"), nil
  803. }
  804. return keyutils.IsEncryptedPEMBlock(keyBlock), nil
  805. }
  806. }
  807. func checkSwarmLockedToUnlocked(c *check.C, d *daemon.Daemon) {
  808. // Wait for the PEM file to become unencrypted
  809. waitAndAssert(c, defaultReconciliationTimeout, checkKeyIsEncrypted(d), checker.Equals, false)
  810. d.RestartNode(c)
  811. waitAndAssert(c, time.Second, d.CheckLocalNodeState, checker.Equals, swarm.LocalNodeStateActive)
  812. }
  813. func checkSwarmUnlockedToLocked(c *check.C, d *daemon.Daemon) {
  814. // Wait for the PEM file to become encrypted
  815. waitAndAssert(c, defaultReconciliationTimeout, checkKeyIsEncrypted(d), checker.Equals, true)
  816. d.RestartNode(c)
  817. waitAndAssert(c, time.Second, d.CheckLocalNodeState, checker.Equals, swarm.LocalNodeStateLocked)
  818. }
  819. func (s *DockerSwarmSuite) TestUnlockEngineAndUnlockedSwarm(c *check.C) {
  820. d := s.AddDaemon(c, false, false)
  821. // unlocking a normal engine should return an error - it does not even ask for the key
  822. cmd := d.Command("swarm", "unlock")
  823. result := icmd.RunCmd(cmd)
  824. result.Assert(c, icmd.Expected{
  825. ExitCode: 1,
  826. })
  827. c.Assert(result.Combined(), checker.Contains, "Error: This node is not part of a swarm")
  828. c.Assert(result.Combined(), checker.Not(checker.Contains), "Please enter unlock key")
  829. out, err := d.Cmd("swarm", "init")
  830. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  831. // unlocking an unlocked swarm should return an error - it does not even ask for the key
  832. cmd = d.Command("swarm", "unlock")
  833. result = icmd.RunCmd(cmd)
  834. result.Assert(c, icmd.Expected{
  835. ExitCode: 1,
  836. })
  837. c.Assert(result.Combined(), checker.Contains, "Error: swarm is not locked")
  838. c.Assert(result.Combined(), checker.Not(checker.Contains), "Please enter unlock key")
  839. }
  840. func (s *DockerSwarmSuite) TestSwarmInitLocked(c *check.C) {
  841. d := s.AddDaemon(c, false, false)
  842. outs, err := d.Cmd("swarm", "init", "--autolock")
  843. c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
  844. unlockKey := getUnlockKey(d, c, outs)
  845. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  846. // It starts off locked
  847. d.RestartNode(c)
  848. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  849. cmd := d.Command("swarm", "unlock")
  850. cmd.Stdin = bytes.NewBufferString("wrong-secret-key")
  851. icmd.RunCmd(cmd).Assert(c, icmd.Expected{
  852. ExitCode: 1,
  853. Err: "invalid key",
  854. })
  855. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  856. cmd = d.Command("swarm", "unlock")
  857. cmd.Stdin = bytes.NewBufferString(unlockKey)
  858. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  859. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  860. outs, err = d.Cmd("node", "ls")
  861. c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
  862. c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked")
  863. outs, err = d.Cmd("swarm", "update", "--autolock=false")
  864. c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
  865. checkSwarmLockedToUnlocked(c, d)
  866. outs, err = d.Cmd("node", "ls")
  867. c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
  868. c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked")
  869. }
  870. func (s *DockerSwarmSuite) TestSwarmLeaveLocked(c *check.C) {
  871. d := s.AddDaemon(c, false, false)
  872. outs, err := d.Cmd("swarm", "init", "--autolock")
  873. c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
  874. // It starts off locked
  875. d.RestartNode(c)
  876. info := d.SwarmInfo(c)
  877. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateLocked)
  878. outs, _ = d.Cmd("node", "ls")
  879. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  880. // `docker swarm leave` a locked swarm without --force will return an error
  881. outs, _ = d.Cmd("swarm", "leave")
  882. c.Assert(outs, checker.Contains, "Swarm is encrypted and locked.")
  883. // It is OK for user to leave a locked swarm with --force
  884. outs, err = d.Cmd("swarm", "leave", "--force")
  885. c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
  886. info = d.SwarmInfo(c)
  887. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive)
  888. outs, err = d.Cmd("swarm", "init")
  889. c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
  890. info = d.SwarmInfo(c)
  891. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive)
  892. }
  893. func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) {
  894. d1 := s.AddDaemon(c, true, true)
  895. d2 := s.AddDaemon(c, true, true)
  896. d3 := s.AddDaemon(c, true, true)
  897. // they start off unlocked
  898. d2.RestartNode(c)
  899. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
  900. // stop this one so it does not get autolock info
  901. d2.Stop(c)
  902. // enable autolock
  903. outs, err := d1.Cmd("swarm", "update", "--autolock")
  904. c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
  905. unlockKey := getUnlockKey(d1, c, outs)
  906. // The ones that got the cluster update should be set to locked
  907. for _, d := range []*daemon.Daemon{d1, d3} {
  908. checkSwarmUnlockedToLocked(c, d)
  909. cmd := d.Command("swarm", "unlock")
  910. cmd.Stdin = bytes.NewBufferString(unlockKey)
  911. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  912. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  913. }
  914. // d2 never got the cluster update, so it is still set to unlocked
  915. d2.StartNode(c)
  916. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
  917. // d2 is now set to lock
  918. checkSwarmUnlockedToLocked(c, d2)
  919. // leave it locked, and set the cluster to no longer autolock
  920. outs, err = d1.Cmd("swarm", "update", "--autolock=false")
  921. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  922. // the ones that got the update are now set to unlocked
  923. for _, d := range []*daemon.Daemon{d1, d3} {
  924. checkSwarmLockedToUnlocked(c, d)
  925. }
  926. // d2 still locked
  927. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateLocked)
  928. // unlock it
  929. cmd := d2.Command("swarm", "unlock")
  930. cmd.Stdin = bytes.NewBufferString(unlockKey)
  931. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  932. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
  933. // once it's caught up, d2 is set to not be locked
  934. checkSwarmLockedToUnlocked(c, d2)
  935. // managers who join now are never set to locked in the first place
  936. d4 := s.AddDaemon(c, true, true)
  937. d4.RestartNode(c)
  938. c.Assert(getNodeStatus(c, d4), checker.Equals, swarm.LocalNodeStateActive)
  939. }
  940. func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) {
  941. d1 := s.AddDaemon(c, true, true)
  942. // enable autolock
  943. outs, err := d1.Cmd("swarm", "update", "--autolock")
  944. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  945. unlockKey := getUnlockKey(d1, c, outs)
  946. // joined workers start off unlocked
  947. d2 := s.AddDaemon(c, true, false)
  948. d2.RestartNode(c)
  949. waitAndAssert(c, time.Second, d2.CheckLocalNodeState, checker.Equals, swarm.LocalNodeStateActive)
  950. // promote worker
  951. outs, err = d1.Cmd("node", "promote", d2.NodeID())
  952. c.Assert(err, checker.IsNil)
  953. c.Assert(outs, checker.Contains, "promoted to a manager in the swarm")
  954. // join new manager node
  955. d3 := s.AddDaemon(c, true, true)
  956. // both new nodes are locked
  957. for _, d := range []*daemon.Daemon{d2, d3} {
  958. checkSwarmUnlockedToLocked(c, d)
  959. cmd := d.Command("swarm", "unlock")
  960. cmd.Stdin = bytes.NewBufferString(unlockKey)
  961. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  962. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  963. }
  964. // demote manager back to worker - workers are not locked
  965. outs, err = d1.Cmd("node", "demote", d3.NodeID())
  966. c.Assert(err, checker.IsNil)
  967. c.Assert(outs, checker.Contains, "demoted in the swarm")
  968. // Wait for it to actually be demoted, for the key and cert to be replaced.
  969. // Then restart and assert that the node is not locked. If we don't wait for the cert
  970. // to be replaced, then the node still has the manager TLS key which is still locked
  971. // (because we never want a manager TLS key to be on disk unencrypted if the cluster
  972. // is set to autolock)
  973. waitAndAssert(c, defaultReconciliationTimeout, d3.CheckControlAvailable, checker.False)
  974. waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) {
  975. certBytes, err := ioutil.ReadFile(filepath.Join(d3.Folder, "root", "swarm", "certificates", "swarm-node.crt"))
  976. if err != nil {
  977. return "", check.Commentf("error: %v", err)
  978. }
  979. certs, err := helpers.ParseCertificatesPEM(certBytes)
  980. if err == nil && len(certs) > 0 && len(certs[0].Subject.OrganizationalUnit) > 0 {
  981. return certs[0].Subject.OrganizationalUnit[0], nil
  982. }
  983. return "", check.Commentf("could not get organizational unit from certificate")
  984. }, checker.Equals, "swarm-worker")
  985. // by now, it should *never* be locked on restart
  986. d3.RestartNode(c)
  987. waitAndAssert(c, time.Second, d3.CheckLocalNodeState, checker.Equals, swarm.LocalNodeStateActive)
  988. }
  989. func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *check.C) {
  990. d := s.AddDaemon(c, true, true)
  991. outs, err := d.Cmd("swarm", "update", "--autolock")
  992. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  993. unlockKey := getUnlockKey(d, c, outs)
  994. // Rotate multiple times
  995. for i := 0; i != 3; i++ {
  996. outs, err = d.Cmd("swarm", "unlock-key", "-q", "--rotate")
  997. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  998. // Strip \n
  999. newUnlockKey := outs[:len(outs)-1]
  1000. c.Assert(newUnlockKey, checker.Not(checker.Equals), "")
  1001. c.Assert(newUnlockKey, checker.Not(checker.Equals), unlockKey)
  1002. d.RestartNode(c)
  1003. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  1004. outs, _ = d.Cmd("node", "ls")
  1005. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  1006. cmd := d.Command("swarm", "unlock")
  1007. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1008. result := icmd.RunCmd(cmd)
  1009. if result.Error == nil {
  1010. // On occasion, the daemon may not have finished
  1011. // rotating the KEK before restarting. The test is
  1012. // intentionally written to explore this behavior.
  1013. // When this happens, unlocking with the old key will
  1014. // succeed. If we wait for the rotation to happen and
  1015. // restart again, the new key should be required this
  1016. // time.
  1017. time.Sleep(3 * time.Second)
  1018. d.RestartNode(c)
  1019. cmd = d.Command("swarm", "unlock")
  1020. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1021. result = icmd.RunCmd(cmd)
  1022. }
  1023. result.Assert(c, icmd.Expected{
  1024. ExitCode: 1,
  1025. Err: "invalid key",
  1026. })
  1027. outs, _ = d.Cmd("node", "ls")
  1028. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  1029. cmd = d.Command("swarm", "unlock")
  1030. cmd.Stdin = bytes.NewBufferString(newUnlockKey)
  1031. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  1032. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  1033. outs, err = d.Cmd("node", "ls")
  1034. c.Assert(err, checker.IsNil)
  1035. c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked")
  1036. unlockKey = newUnlockKey
  1037. }
  1038. }
  1039. // This differs from `TestSwarmRotateUnlockKey` because that one rotates a single node, which is the leader.
  1040. // This one keeps the leader up, and asserts that other manager nodes in the cluster also have their unlock
  1041. // key rotated.
  1042. func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *check.C) {
  1043. if runtime.GOARCH == "s390x" {
  1044. c.Skip("Disabled on s390x")
  1045. }
  1046. if runtime.GOARCH == "ppc64le" {
  1047. c.Skip("Disabled on ppc64le")
  1048. }
  1049. d1 := s.AddDaemon(c, true, true) // leader - don't restart this one, we don't want leader election delays
  1050. d2 := s.AddDaemon(c, true, true)
  1051. d3 := s.AddDaemon(c, true, true)
  1052. outs, err := d1.Cmd("swarm", "update", "--autolock")
  1053. c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
  1054. unlockKey := getUnlockKey(d1, c, outs)
  1055. // Rotate multiple times
  1056. for i := 0; i != 3; i++ {
  1057. outs, err = d1.Cmd("swarm", "unlock-key", "-q", "--rotate")
  1058. c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
  1059. // Strip \n
  1060. newUnlockKey := outs[:len(outs)-1]
  1061. c.Assert(newUnlockKey, checker.Not(checker.Equals), "")
  1062. c.Assert(newUnlockKey, checker.Not(checker.Equals), unlockKey)
  1063. d2.RestartNode(c)
  1064. d3.RestartNode(c)
  1065. for _, d := range []*daemon.Daemon{d2, d3} {
  1066. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  1067. outs, _ := d.Cmd("node", "ls")
  1068. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  1069. cmd := d.Command("swarm", "unlock")
  1070. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1071. result := icmd.RunCmd(cmd)
  1072. if result.Error == nil {
  1073. // On occasion, the daemon may not have finished
  1074. // rotating the KEK before restarting. The test is
  1075. // intentionally written to explore this behavior.
  1076. // When this happens, unlocking with the old key will
  1077. // succeed. If we wait for the rotation to happen and
  1078. // restart again, the new key should be required this
  1079. // time.
  1080. time.Sleep(3 * time.Second)
  1081. d.RestartNode(c)
  1082. cmd = d.Command("swarm", "unlock")
  1083. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1084. result = icmd.RunCmd(cmd)
  1085. }
  1086. result.Assert(c, icmd.Expected{
  1087. ExitCode: 1,
  1088. Err: "invalid key",
  1089. })
  1090. outs, _ = d.Cmd("node", "ls")
  1091. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  1092. cmd = d.Command("swarm", "unlock")
  1093. cmd.Stdin = bytes.NewBufferString(newUnlockKey)
  1094. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  1095. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  1096. outs, err = d.Cmd("node", "ls")
  1097. c.Assert(err, checker.IsNil, check.Commentf("%s", outs))
  1098. c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked")
  1099. }
  1100. unlockKey = newUnlockKey
  1101. }
  1102. }
  1103. func (s *DockerSwarmSuite) TestSwarmAlternateLockUnlock(c *check.C) {
  1104. d := s.AddDaemon(c, true, true)
  1105. for i := 0; i < 2; i++ {
  1106. // set to lock
  1107. outs, err := d.Cmd("swarm", "update", "--autolock")
  1108. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  1109. c.Assert(outs, checker.Contains, "docker swarm unlock")
  1110. unlockKey := getUnlockKey(d, c, outs)
  1111. checkSwarmUnlockedToLocked(c, d)
  1112. cmd := d.Command("swarm", "unlock")
  1113. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1114. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  1115. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  1116. outs, err = d.Cmd("swarm", "update", "--autolock=false")
  1117. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  1118. checkSwarmLockedToUnlocked(c, d)
  1119. }
  1120. }
  1121. func (s *DockerSwarmSuite) TestExtraHosts(c *check.C) {
  1122. d := s.AddDaemon(c, true, true)
  1123. // Create a service
  1124. name := "top"
  1125. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--host=example.com:1.2.3.4", "busybox", "top")
  1126. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1127. // Make sure task has been deployed.
  1128. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  1129. // We need to get the container id.
  1130. out, err = d.Cmd("ps", "-a", "-q", "--no-trunc")
  1131. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1132. id := strings.TrimSpace(out)
  1133. // Compare against expected output.
  1134. expectedOutput := "1.2.3.4\texample.com"
  1135. out, err = d.Cmd("exec", id, "cat", "/etc/hosts")
  1136. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1137. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  1138. }
  1139. func (s *DockerSwarmSuite) TestSwarmManagerAddress(c *check.C) {
  1140. d1 := s.AddDaemon(c, true, true)
  1141. d2 := s.AddDaemon(c, true, false)
  1142. d3 := s.AddDaemon(c, true, false)
  1143. // Manager Addresses will always show Node 1's address
  1144. expectedOutput := fmt.Sprintf("Manager Addresses:\n 127.0.0.1:%d\n", d1.SwarmPort)
  1145. out, err := d1.Cmd("info")
  1146. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1147. c.Assert(out, checker.Contains, expectedOutput)
  1148. out, err = d2.Cmd("info")
  1149. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1150. c.Assert(out, checker.Contains, expectedOutput)
  1151. out, err = d3.Cmd("info")
  1152. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1153. c.Assert(out, checker.Contains, expectedOutput)
  1154. }
  1155. func (s *DockerSwarmSuite) TestSwarmNetworkIPAMOptions(c *check.C) {
  1156. d := s.AddDaemon(c, true, true)
  1157. out, err := d.Cmd("network", "create", "-d", "overlay", "--ipam-opt", "foo=bar", "foo")
  1158. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1159. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  1160. out, err = d.Cmd("network", "inspect", "--format", "{{.IPAM.Options}}", "foo")
  1161. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1162. c.Assert(strings.TrimSpace(out), checker.Contains, "foo:bar")
  1163. c.Assert(strings.TrimSpace(out), checker.Contains, "com.docker.network.ipam.serial:true")
  1164. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--network=foo", "--name", "top", "busybox", "top")
  1165. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1166. // make sure task has been deployed.
  1167. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  1168. out, err = d.Cmd("network", "inspect", "--format", "{{.IPAM.Options}}", "foo")
  1169. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1170. c.Assert(strings.TrimSpace(out), checker.Contains, "foo:bar")
  1171. c.Assert(strings.TrimSpace(out), checker.Contains, "com.docker.network.ipam.serial:true")
  1172. }
  1173. // Test case for issue #27866, which did not allow NW name that is the prefix of a swarm NW ID.
  1174. // e.g. if the ingress ID starts with "n1", it was impossible to create a NW named "n1".
  1175. func (s *DockerSwarmSuite) TestSwarmNetworkCreateIssue27866(c *check.C) {
  1176. d := s.AddDaemon(c, true, true)
  1177. out, err := d.Cmd("network", "inspect", "-f", "{{.Id}}", "ingress")
  1178. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  1179. ingressID := strings.TrimSpace(out)
  1180. c.Assert(ingressID, checker.Not(checker.Equals), "")
  1181. // create a network of which name is the prefix of the ID of an overlay network
  1182. // (ingressID in this case)
  1183. newNetName := ingressID[0:2]
  1184. out, err = d.Cmd("network", "create", "--driver", "overlay", newNetName)
  1185. // In #27866, it was failing because of "network with name %s already exists"
  1186. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  1187. out, err = d.Cmd("network", "rm", newNetName)
  1188. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  1189. }
  1190. // Test case for https://github.com/docker/docker/pull/27938#issuecomment-265768303
  1191. // This test creates two networks with the same name sequentially, with various drivers.
  1192. // Since the operations in this test are done sequentially, the 2nd call should fail with
  1193. // "network with name FOO already exists".
  1194. // Note that it is to ok have multiple networks with the same name if the operations are done
  1195. // in parallel. (#18864)
  1196. func (s *DockerSwarmSuite) TestSwarmNetworkCreateDup(c *check.C) {
  1197. d := s.AddDaemon(c, true, true)
  1198. drivers := []string{"bridge", "overlay"}
  1199. for i, driver1 := range drivers {
  1200. nwName := fmt.Sprintf("network-test-%d", i)
  1201. for _, driver2 := range drivers {
  1202. c.Logf("Creating a network named %q with %q, then %q",
  1203. nwName, driver1, driver2)
  1204. out, err := d.Cmd("network", "create", "--driver", driver1, nwName)
  1205. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  1206. out, err = d.Cmd("network", "create", "--driver", driver2, nwName)
  1207. c.Assert(out, checker.Contains,
  1208. fmt.Sprintf("network with name %s already exists", nwName))
  1209. c.Assert(err, checker.NotNil)
  1210. c.Logf("As expected, the attempt to network %q with %q failed: %s",
  1211. nwName, driver2, out)
  1212. out, err = d.Cmd("network", "rm", nwName)
  1213. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  1214. }
  1215. }
  1216. }
  1217. func (s *DockerSwarmSuite) TestSwarmPublishDuplicatePorts(c *check.C) {
  1218. d := s.AddDaemon(c, true, true)
  1219. out, err := d.Cmd("service", "create", "--no-resolve-image", "--detach=true", "--publish", "5005:80", "--publish", "5006:80", "--publish", "80", "--publish", "80", "busybox", "top")
  1220. c.Assert(err, check.IsNil, check.Commentf("%s", out))
  1221. id := strings.TrimSpace(out)
  1222. // make sure task has been deployed.
  1223. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  1224. // Total len = 4, with 2 dynamic ports and 2 non-dynamic ports
  1225. // Dynamic ports are likely to be 30000 and 30001 but doesn't matter
  1226. out, err = d.Cmd("service", "inspect", "--format", "{{.Endpoint.Ports}} len={{len .Endpoint.Ports}}", id)
  1227. c.Assert(err, check.IsNil, check.Commentf("%s", out))
  1228. c.Assert(out, checker.Contains, "len=4")
  1229. c.Assert(out, checker.Contains, "{ tcp 80 5005 ingress}")
  1230. c.Assert(out, checker.Contains, "{ tcp 80 5006 ingress}")
  1231. }
  1232. func (s *DockerSwarmSuite) TestSwarmJoinWithDrain(c *check.C) {
  1233. d := s.AddDaemon(c, true, true)
  1234. out, err := d.Cmd("node", "ls")
  1235. c.Assert(err, checker.IsNil)
  1236. c.Assert(out, checker.Not(checker.Contains), "Drain")
  1237. out, err = d.Cmd("swarm", "join-token", "-q", "manager")
  1238. c.Assert(err, checker.IsNil)
  1239. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  1240. token := strings.TrimSpace(out)
  1241. d1 := s.AddDaemon(c, false, false)
  1242. out, err = d1.Cmd("swarm", "join", "--availability=drain", "--token", token, d.SwarmListenAddr())
  1243. c.Assert(err, checker.IsNil)
  1244. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  1245. out, err = d.Cmd("node", "ls")
  1246. c.Assert(err, checker.IsNil)
  1247. c.Assert(out, checker.Contains, "Drain")
  1248. out, err = d1.Cmd("node", "ls")
  1249. c.Assert(err, checker.IsNil)
  1250. c.Assert(out, checker.Contains, "Drain")
  1251. }
  1252. func (s *DockerSwarmSuite) TestSwarmInitWithDrain(c *check.C) {
  1253. d := s.AddDaemon(c, false, false)
  1254. out, err := d.Cmd("swarm", "init", "--availability", "drain")
  1255. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  1256. out, err = d.Cmd("node", "ls")
  1257. c.Assert(err, checker.IsNil)
  1258. c.Assert(out, checker.Contains, "Drain")
  1259. }
  1260. func (s *DockerSwarmSuite) TestSwarmReadonlyRootfs(c *check.C) {
  1261. testRequires(c, DaemonIsLinux, UserNamespaceROMount)
  1262. d := s.AddDaemon(c, true, true)
  1263. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "top", "--read-only", "busybox", "top")
  1264. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1265. // make sure task has been deployed.
  1266. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  1267. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.ReadOnly }}", "top")
  1268. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1269. c.Assert(strings.TrimSpace(out), checker.Equals, "true")
  1270. containers := d.ActiveContainers(c)
  1271. out, err = d.Cmd("inspect", "--type", "container", "--format", "{{.HostConfig.ReadonlyRootfs}}", containers[0])
  1272. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1273. c.Assert(strings.TrimSpace(out), checker.Equals, "true")
  1274. }
  1275. func (s *DockerSwarmSuite) TestNetworkInspectWithDuplicateNames(c *check.C) {
  1276. d := s.AddDaemon(c, true, true)
  1277. name := "foo"
  1278. options := types.NetworkCreate{
  1279. CheckDuplicate: false,
  1280. Driver: "bridge",
  1281. }
  1282. cli := d.NewClientT(c)
  1283. defer cli.Close()
  1284. n1, err := cli.NetworkCreate(context.Background(), name, options)
  1285. c.Assert(err, checker.IsNil)
  1286. // Full ID always works
  1287. out, err := d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID)
  1288. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1289. c.Assert(strings.TrimSpace(out), checker.Equals, n1.ID)
  1290. // Name works if it is unique
  1291. out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", name)
  1292. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1293. c.Assert(strings.TrimSpace(out), checker.Equals, n1.ID)
  1294. n2, err := cli.NetworkCreate(context.Background(), name, options)
  1295. c.Assert(err, checker.IsNil)
  1296. // Full ID always works
  1297. out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID)
  1298. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1299. c.Assert(strings.TrimSpace(out), checker.Equals, n1.ID)
  1300. out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n2.ID)
  1301. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1302. c.Assert(strings.TrimSpace(out), checker.Equals, n2.ID)
  1303. // Name with duplicates
  1304. out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", name)
  1305. c.Assert(err, checker.NotNil, check.Commentf("%s", out))
  1306. c.Assert(out, checker.Contains, "2 matches found based on name")
  1307. out, err = d.Cmd("network", "rm", n2.ID)
  1308. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1309. // Duplicates with name but with different driver
  1310. options.Driver = "overlay"
  1311. n2, err = cli.NetworkCreate(context.Background(), name, options)
  1312. c.Assert(err, checker.IsNil)
  1313. // Full ID always works
  1314. out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID)
  1315. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1316. c.Assert(strings.TrimSpace(out), checker.Equals, n1.ID)
  1317. out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n2.ID)
  1318. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1319. c.Assert(strings.TrimSpace(out), checker.Equals, n2.ID)
  1320. // Name with duplicates
  1321. out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", name)
  1322. c.Assert(err, checker.NotNil, check.Commentf("%s", out))
  1323. c.Assert(out, checker.Contains, "2 matches found based on name")
  1324. }
  1325. func (s *DockerSwarmSuite) TestSwarmStopSignal(c *check.C) {
  1326. testRequires(c, DaemonIsLinux, UserNamespaceROMount)
  1327. d := s.AddDaemon(c, true, true)
  1328. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "top", "--stop-signal=SIGHUP", "busybox", "top")
  1329. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1330. // make sure task has been deployed.
  1331. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  1332. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.StopSignal }}", "top")
  1333. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1334. c.Assert(strings.TrimSpace(out), checker.Equals, "SIGHUP")
  1335. containers := d.ActiveContainers(c)
  1336. out, err = d.Cmd("inspect", "--type", "container", "--format", "{{.Config.StopSignal}}", containers[0])
  1337. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1338. c.Assert(strings.TrimSpace(out), checker.Equals, "SIGHUP")
  1339. out, err = d.Cmd("service", "update", "--detach", "--stop-signal=SIGUSR1", "top")
  1340. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1341. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.StopSignal }}", "top")
  1342. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1343. c.Assert(strings.TrimSpace(out), checker.Equals, "SIGUSR1")
  1344. }
  1345. func (s *DockerSwarmSuite) TestSwarmServiceLsFilterMode(c *check.C) {
  1346. d := s.AddDaemon(c, true, true)
  1347. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "top1", "busybox", "top")
  1348. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1349. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  1350. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "top2", "--mode=global", "busybox", "top")
  1351. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1352. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  1353. // make sure task has been deployed.
  1354. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 2)
  1355. out, err = d.Cmd("service", "ls")
  1356. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1357. c.Assert(out, checker.Contains, "top1")
  1358. c.Assert(out, checker.Contains, "top2")
  1359. c.Assert(out, checker.Not(checker.Contains), "localnet")
  1360. out, err = d.Cmd("service", "ls", "--filter", "mode=global")
  1361. c.Assert(out, checker.Not(checker.Contains), "top1")
  1362. c.Assert(out, checker.Contains, "top2")
  1363. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1364. out, err = d.Cmd("service", "ls", "--filter", "mode=replicated")
  1365. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1366. c.Assert(out, checker.Contains, "top1")
  1367. c.Assert(out, checker.Not(checker.Contains), "top2")
  1368. }
  1369. func (s *DockerSwarmSuite) TestSwarmInitUnspecifiedDataPathAddr(c *check.C) {
  1370. d := s.AddDaemon(c, false, false)
  1371. out, err := d.Cmd("swarm", "init", "--data-path-addr", "0.0.0.0")
  1372. c.Assert(err, checker.NotNil)
  1373. c.Assert(out, checker.Contains, "data path address must be a non-zero IP")
  1374. out, err = d.Cmd("swarm", "init", "--data-path-addr", "0.0.0.0:2000")
  1375. c.Assert(err, checker.NotNil)
  1376. c.Assert(out, checker.Contains, "data path address must be a non-zero IP")
  1377. }
  1378. func (s *DockerSwarmSuite) TestSwarmJoinLeave(c *check.C) {
  1379. d := s.AddDaemon(c, true, true)
  1380. out, err := d.Cmd("swarm", "join-token", "-q", "worker")
  1381. c.Assert(err, checker.IsNil)
  1382. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  1383. token := strings.TrimSpace(out)
  1384. // Verify that back to back join/leave does not cause panics
  1385. d1 := s.AddDaemon(c, false, false)
  1386. for i := 0; i < 10; i++ {
  1387. out, err = d1.Cmd("swarm", "join", "--token", token, d.SwarmListenAddr())
  1388. c.Assert(err, checker.IsNil)
  1389. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  1390. _, err = d1.Cmd("swarm", "leave")
  1391. c.Assert(err, checker.IsNil)
  1392. }
  1393. }
  1394. const defaultRetryCount = 10
  1395. func waitForEvent(c *check.C, d *daemon.Daemon, since string, filter string, event string, retry int) string {
  1396. if retry < 1 {
  1397. c.Fatalf("retry count %d is invalid. It should be no less than 1", retry)
  1398. return ""
  1399. }
  1400. var out string
  1401. for i := 0; i < retry; i++ {
  1402. until := daemonUnixTime(c)
  1403. var err error
  1404. if len(filter) > 0 {
  1405. out, err = d.Cmd("events", "--since", since, "--until", until, filter)
  1406. } else {
  1407. out, err = d.Cmd("events", "--since", since, "--until", until)
  1408. }
  1409. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1410. if strings.Contains(out, event) {
  1411. return strings.TrimSpace(out)
  1412. }
  1413. // no need to sleep after last retry
  1414. if i < retry-1 {
  1415. time.Sleep(200 * time.Millisecond)
  1416. }
  1417. }
  1418. c.Fatalf("docker events output '%s' doesn't contain event '%s'", out, event)
  1419. return ""
  1420. }
  1421. func (s *DockerSwarmSuite) TestSwarmClusterEventsSource(c *check.C) {
  1422. d1 := s.AddDaemon(c, true, true)
  1423. d2 := s.AddDaemon(c, true, true)
  1424. d3 := s.AddDaemon(c, true, false)
  1425. // create a network
  1426. out, err := d1.Cmd("network", "create", "--attachable", "-d", "overlay", "foo")
  1427. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1428. networkID := strings.TrimSpace(out)
  1429. c.Assert(networkID, checker.Not(checker.Equals), "")
  1430. // d1, d2 are managers that can get swarm events
  1431. waitForEvent(c, d1, "0", "-f scope=swarm", "network create "+networkID, defaultRetryCount)
  1432. waitForEvent(c, d2, "0", "-f scope=swarm", "network create "+networkID, defaultRetryCount)
  1433. // d3 is a worker, not able to get cluster events
  1434. out = waitForEvent(c, d3, "0", "-f scope=swarm", "", 1)
  1435. c.Assert(out, checker.Not(checker.Contains), "network create ")
  1436. }
  1437. func (s *DockerSwarmSuite) TestSwarmClusterEventsScope(c *check.C) {
  1438. d := s.AddDaemon(c, true, true)
  1439. // create a service
  1440. out, err := d.Cmd("service", "create", "--no-resolve-image", "--name", "test", "--detach=false", "busybox", "top")
  1441. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1442. serviceID := strings.Split(out, "\n")[0]
  1443. // scope swarm filters cluster events
  1444. out = waitForEvent(c, d, "0", "-f scope=swarm", "service create "+serviceID, defaultRetryCount)
  1445. c.Assert(out, checker.Not(checker.Contains), "container create ")
  1446. // all events are returned if scope is not specified
  1447. waitForEvent(c, d, "0", "", "service create "+serviceID, 1)
  1448. waitForEvent(c, d, "0", "", "container create ", defaultRetryCount)
  1449. // scope local only shows non-cluster events
  1450. out = waitForEvent(c, d, "0", "-f scope=local", "container create ", 1)
  1451. c.Assert(out, checker.Not(checker.Contains), "service create ")
  1452. }
  1453. func (s *DockerSwarmSuite) TestSwarmClusterEventsType(c *check.C) {
  1454. d := s.AddDaemon(c, true, true)
  1455. // create a service
  1456. out, err := d.Cmd("service", "create", "--no-resolve-image", "--name", "test", "--detach=false", "busybox", "top")
  1457. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1458. serviceID := strings.Split(out, "\n")[0]
  1459. // create a network
  1460. out, err = d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo")
  1461. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1462. networkID := strings.TrimSpace(out)
  1463. c.Assert(networkID, checker.Not(checker.Equals), "")
  1464. // filter by service
  1465. out = waitForEvent(c, d, "0", "-f type=service", "service create "+serviceID, defaultRetryCount)
  1466. c.Assert(out, checker.Not(checker.Contains), "network create")
  1467. // filter by network
  1468. out = waitForEvent(c, d, "0", "-f type=network", "network create "+networkID, defaultRetryCount)
  1469. c.Assert(out, checker.Not(checker.Contains), "service create")
  1470. }
  1471. func (s *DockerSwarmSuite) TestSwarmClusterEventsService(c *check.C) {
  1472. d := s.AddDaemon(c, true, true)
  1473. // create a service
  1474. out, err := d.Cmd("service", "create", "--no-resolve-image", "--name", "test", "--detach=false", "busybox", "top")
  1475. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1476. serviceID := strings.Split(out, "\n")[0]
  1477. // validate service create event
  1478. waitForEvent(c, d, "0", "-f scope=swarm", "service create "+serviceID, defaultRetryCount)
  1479. t1 := daemonUnixTime(c)
  1480. out, err = d.Cmd("service", "update", "--force", "--detach=false", "test")
  1481. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1482. // wait for service update start
  1483. out = waitForEvent(c, d, t1, "-f scope=swarm", "service update "+serviceID, defaultRetryCount)
  1484. c.Assert(out, checker.Contains, "updatestate.new=updating")
  1485. // allow service update complete. This is a service with 1 instance
  1486. time.Sleep(400 * time.Millisecond)
  1487. out = waitForEvent(c, d, t1, "-f scope=swarm", "service update "+serviceID, defaultRetryCount)
  1488. c.Assert(out, checker.Contains, "updatestate.new=completed, updatestate.old=updating")
  1489. // scale service
  1490. t2 := daemonUnixTime(c)
  1491. out, err = d.Cmd("service", "scale", "test=3")
  1492. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1493. out = waitForEvent(c, d, t2, "-f scope=swarm", "service update "+serviceID, defaultRetryCount)
  1494. c.Assert(out, checker.Contains, "replicas.new=3, replicas.old=1")
  1495. // remove service
  1496. t3 := daemonUnixTime(c)
  1497. out, err = d.Cmd("service", "rm", "test")
  1498. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1499. waitForEvent(c, d, t3, "-f scope=swarm", "service remove "+serviceID, defaultRetryCount)
  1500. }
  1501. func (s *DockerSwarmSuite) TestSwarmClusterEventsNode(c *check.C) {
  1502. d1 := s.AddDaemon(c, true, true)
  1503. s.AddDaemon(c, true, true)
  1504. d3 := s.AddDaemon(c, true, true)
  1505. d3ID := d3.NodeID()
  1506. waitForEvent(c, d1, "0", "-f scope=swarm", "node create "+d3ID, defaultRetryCount)
  1507. t1 := daemonUnixTime(c)
  1508. out, err := d1.Cmd("node", "update", "--availability=pause", d3ID)
  1509. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1510. // filter by type
  1511. out = waitForEvent(c, d1, t1, "-f type=node", "node update "+d3ID, defaultRetryCount)
  1512. c.Assert(out, checker.Contains, "availability.new=pause, availability.old=active")
  1513. t2 := daemonUnixTime(c)
  1514. out, err = d1.Cmd("node", "demote", d3ID)
  1515. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1516. waitForEvent(c, d1, t2, "-f type=node", "node update "+d3ID, defaultRetryCount)
  1517. t3 := daemonUnixTime(c)
  1518. out, err = d1.Cmd("node", "rm", "-f", d3ID)
  1519. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1520. // filter by scope
  1521. waitForEvent(c, d1, t3, "-f scope=swarm", "node remove "+d3ID, defaultRetryCount)
  1522. }
  1523. func (s *DockerSwarmSuite) TestSwarmClusterEventsNetwork(c *check.C) {
  1524. d := s.AddDaemon(c, true, true)
  1525. // create a network
  1526. out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo")
  1527. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1528. networkID := strings.TrimSpace(out)
  1529. waitForEvent(c, d, "0", "-f scope=swarm", "network create "+networkID, defaultRetryCount)
  1530. // remove network
  1531. t1 := daemonUnixTime(c)
  1532. out, err = d.Cmd("network", "rm", "foo")
  1533. c.Assert(err, checker.IsNil, check.Commentf("%s", out))
  1534. // filtered by network
  1535. waitForEvent(c, d, t1, "-f type=network", "network remove "+networkID, defaultRetryCount)
  1536. }
  1537. func (s *DockerSwarmSuite) TestSwarmClusterEventsSecret(c *check.C) {
  1538. d := s.AddDaemon(c, true, true)
  1539. testName := "test_secret"
  1540. id := d.CreateSecret(c, swarm.SecretSpec{
  1541. Annotations: swarm.Annotations{
  1542. Name: testName,
  1543. },
  1544. Data: []byte("TESTINGDATA"),
  1545. })
  1546. c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("secrets: %s", id))
  1547. waitForEvent(c, d, "0", "-f scope=swarm", "secret create "+id, defaultRetryCount)
  1548. t1 := daemonUnixTime(c)
  1549. d.DeleteSecret(c, id)
  1550. // filtered by secret
  1551. waitForEvent(c, d, t1, "-f type=secret", "secret remove "+id, defaultRetryCount)
  1552. }
  1553. func (s *DockerSwarmSuite) TestSwarmClusterEventsConfig(c *check.C) {
  1554. d := s.AddDaemon(c, true, true)
  1555. testName := "test_config"
  1556. id := d.CreateConfig(c, swarm.ConfigSpec{
  1557. Annotations: swarm.Annotations{
  1558. Name: testName,
  1559. },
  1560. Data: []byte("TESTINGDATA"),
  1561. })
  1562. c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("configs: %s", id))
  1563. waitForEvent(c, d, "0", "-f scope=swarm", "config create "+id, defaultRetryCount)
  1564. t1 := daemonUnixTime(c)
  1565. d.DeleteConfig(c, id)
  1566. // filtered by config
  1567. waitForEvent(c, d, t1, "-f type=config", "config remove "+id, defaultRetryCount)
  1568. }
  1569. func getUnlockKey(d *daemon.Daemon, c *check.C, autolockOutput string) string {
  1570. unlockKey, err := d.Cmd("swarm", "unlock-key", "-q")
  1571. c.Assert(err, checker.IsNil, check.Commentf("%s", unlockKey))
  1572. unlockKey = strings.TrimSuffix(unlockKey, "\n")
  1573. // Check that "docker swarm init --autolock" or "docker swarm update --autolock"
  1574. // contains all the expected strings, including the unlock key
  1575. c.Assert(autolockOutput, checker.Contains, "docker swarm unlock")
  1576. c.Assert(autolockOutput, checker.Contains, unlockKey)
  1577. return unlockKey
  1578. }