docker_cli_swarm_test.go 76 KB

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