docker_cli_swarm_test.go 75 KB

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