docker_cli_swarm_test.go 75 KB

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