docker_cli_swarm_test.go 75 KB

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