docker_cli_swarm_test.go 76 KB

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