docker_cli_swarm_test.go 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989
  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. "github.com/moby/swarmkit/v2/ca/keyutils"
  28. "github.com/vishvananda/netlink"
  29. "gotest.tools/v3/assert"
  30. "gotest.tools/v3/fs"
  31. "gotest.tools/v3/icmd"
  32. "gotest.tools/v3/poll"
  33. )
  34. func (s *DockerSwarmSuite) TestSwarmUpdate(c *testing.T) {
  35. d := s.AddDaemon(c, true, true)
  36. getSpec := func() swarm.Spec {
  37. sw := d.GetSwarm(c)
  38. return sw.Spec
  39. }
  40. out, err := d.Cmd("swarm", "update", "--cert-expiry", "30h", "--dispatcher-heartbeat", "11s")
  41. assert.NilError(c, err, out)
  42. spec := getSpec()
  43. assert.Equal(c, spec.CAConfig.NodeCertExpiry, 30*time.Hour)
  44. assert.Equal(c, spec.Dispatcher.HeartbeatPeriod, 11*time.Second)
  45. // setting anything under 30m for cert-expiry is not allowed
  46. out, err = d.Cmd("swarm", "update", "--cert-expiry", "15m")
  47. assert.ErrorContains(c, err, "")
  48. assert.Assert(c, strings.Contains(out, "minimum certificate expiry time"))
  49. spec = getSpec()
  50. assert.Equal(c, spec.CAConfig.NodeCertExpiry, 30*time.Hour)
  51. // passing an external CA (this is without starting a root rotation) does not fail
  52. cli.Docker(cli.Args("swarm", "update", "--external-ca", "protocol=cfssl,url=https://something.org",
  53. "--external-ca", "protocol=cfssl,url=https://somethingelse.org,cacert=fixtures/https/ca.pem"),
  54. cli.Daemon(d)).Assert(c, icmd.Success)
  55. expected, err := os.ReadFile("fixtures/https/ca.pem")
  56. assert.NilError(c, err)
  57. spec = getSpec()
  58. assert.Equal(c, len(spec.CAConfig.ExternalCAs), 2)
  59. assert.Equal(c, spec.CAConfig.ExternalCAs[0].CACert, "")
  60. assert.Equal(c, spec.CAConfig.ExternalCAs[1].CACert, string(expected))
  61. // passing an invalid external CA fails
  62. tempFile := fs.NewFile(c, "testfile", fs.WithContent("fakecert"))
  63. defer tempFile.Remove()
  64. result := cli.Docker(cli.Args("swarm", "update",
  65. "--external-ca", fmt.Sprintf("protocol=cfssl,url=https://something.org,cacert=%s", tempFile.Path())),
  66. cli.Daemon(d))
  67. result.Assert(c, icmd.Expected{
  68. ExitCode: 125,
  69. Err: "must be in PEM format",
  70. })
  71. }
  72. func (s *DockerSwarmSuite) TestSwarmInit(c *testing.T) {
  73. d := s.AddDaemon(c, false, false)
  74. getSpec := func() swarm.Spec {
  75. sw := d.GetSwarm(c)
  76. return sw.Spec
  77. }
  78. // passing an invalid external CA fails
  79. tempFile := fs.NewFile(c, "testfile", fs.WithContent("fakecert"))
  80. defer tempFile.Remove()
  81. result := cli.Docker(cli.Args("swarm", "init", "--cert-expiry", "30h", "--dispatcher-heartbeat", "11s",
  82. "--external-ca", fmt.Sprintf("protocol=cfssl,url=https://somethingelse.org,cacert=%s", tempFile.Path())),
  83. cli.Daemon(d))
  84. result.Assert(c, icmd.Expected{
  85. ExitCode: 125,
  86. Err: "must be in PEM format",
  87. })
  88. cli.Docker(cli.Args("swarm", "init", "--cert-expiry", "30h", "--dispatcher-heartbeat", "11s",
  89. "--external-ca", "protocol=cfssl,url=https://something.org",
  90. "--external-ca", "protocol=cfssl,url=https://somethingelse.org,cacert=fixtures/https/ca.pem"),
  91. cli.Daemon(d)).Assert(c, icmd.Success)
  92. expected, err := os.ReadFile("fixtures/https/ca.pem")
  93. assert.NilError(c, err)
  94. spec := getSpec()
  95. assert.Equal(c, spec.CAConfig.NodeCertExpiry, 30*time.Hour)
  96. assert.Equal(c, spec.Dispatcher.HeartbeatPeriod, 11*time.Second)
  97. assert.Equal(c, len(spec.CAConfig.ExternalCAs), 2)
  98. assert.Equal(c, spec.CAConfig.ExternalCAs[0].CACert, "")
  99. assert.Equal(c, spec.CAConfig.ExternalCAs[1].CACert, string(expected))
  100. assert.Assert(c, d.SwarmLeave(c, true) == nil)
  101. cli.Docker(cli.Args("swarm", "init"), cli.Daemon(d)).Assert(c, icmd.Success)
  102. spec = getSpec()
  103. assert.Equal(c, spec.CAConfig.NodeCertExpiry, 90*24*time.Hour)
  104. assert.Equal(c, spec.Dispatcher.HeartbeatPeriod, 5*time.Second)
  105. }
  106. func (s *DockerSwarmSuite) TestSwarmInitIPv6(c *testing.T) {
  107. testRequires(c, IPv6)
  108. d1 := s.AddDaemon(c, false, false)
  109. cli.Docker(cli.Args("swarm", "init", "--listen-add", "::1"), cli.Daemon(d1)).Assert(c, icmd.Success)
  110. d2 := s.AddDaemon(c, false, false)
  111. cli.Docker(cli.Args("swarm", "join", "::1"), cli.Daemon(d2)).Assert(c, icmd.Success)
  112. out := cli.Docker(cli.Args("info"), cli.Daemon(d2)).Assert(c, icmd.Success).Combined()
  113. assert.Assert(c, strings.Contains(out, "Swarm: active"))
  114. }
  115. func (s *DockerSwarmSuite) TestSwarmInitUnspecifiedAdvertiseAddr(c *testing.T) {
  116. d := s.AddDaemon(c, false, false)
  117. out, err := d.Cmd("swarm", "init", "--advertise-addr", "0.0.0.0")
  118. assert.ErrorContains(c, err, "")
  119. assert.Assert(c, strings.Contains(out, "advertise address must be a non-zero IP address"))
  120. }
  121. func (s *DockerSwarmSuite) TestSwarmIncompatibleDaemon(c *testing.T) {
  122. // init swarm mode and stop a daemon
  123. d := s.AddDaemon(c, true, true)
  124. info := d.SwarmInfo(c)
  125. assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive)
  126. d.Stop(c)
  127. // start a daemon with --live-restore
  128. err := d.StartWithError("--live-restore")
  129. assert.ErrorContains(c, err, "")
  130. content, err := d.ReadLogFile()
  131. assert.NilError(c, err)
  132. assert.Assert(c, strings.Contains(string(content), "--live-restore daemon configuration is incompatible with swarm mode"))
  133. // restart for teardown
  134. d.StartNode(c)
  135. }
  136. func (s *DockerSwarmSuite) TestSwarmServiceTemplatingHostname(c *testing.T) {
  137. d := s.AddDaemon(c, true, true)
  138. hostname, err := d.Cmd("node", "inspect", "--format", "{{.Description.Hostname}}", "self")
  139. assert.Assert(c, err == nil, hostname)
  140. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "test", "--hostname", "{{.Service.Name}}-{{.Task.Slot}}-{{.Node.Hostname}}", "busybox", "top")
  141. assert.NilError(c, err, out)
  142. // make sure task has been deployed.
  143. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  144. containers := d.ActiveContainers(c)
  145. out, err = d.Cmd("inspect", "--type", "container", "--format", "{{.Config.Hostname}}", containers[0])
  146. assert.NilError(c, err, out)
  147. assert.Equal(c, strings.Split(out, "\n")[0], "test-1-"+strings.Split(hostname, "\n")[0], "hostname with templating invalid")
  148. }
  149. // Test case for #24270
  150. func (s *DockerSwarmSuite) TestSwarmServiceListFilter(c *testing.T) {
  151. d := s.AddDaemon(c, true, true)
  152. name1 := "redis-cluster-md5"
  153. name2 := "redis-cluster"
  154. name3 := "other-cluster"
  155. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name1, "busybox", "top")
  156. assert.NilError(c, err, out)
  157. assert.Assert(c, strings.TrimSpace(out) != "")
  158. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name2, "busybox", "top")
  159. assert.NilError(c, err, out)
  160. assert.Assert(c, strings.TrimSpace(out) != "")
  161. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name3, "busybox", "top")
  162. assert.NilError(c, err, out)
  163. assert.Assert(c, strings.TrimSpace(out) != "")
  164. filter1 := "name=redis-cluster-md5"
  165. filter2 := "name=redis-cluster"
  166. // We search checker.Contains with `name+" "` to prevent prefix only.
  167. out, err = d.Cmd("service", "ls", "--filter", filter1)
  168. assert.NilError(c, err, out)
  169. assert.Assert(c, strings.Contains(out, name1+" "), out)
  170. assert.Assert(c, !strings.Contains(out, name2+" "), out)
  171. assert.Assert(c, !strings.Contains(out, name3+" "), out)
  172. out, err = d.Cmd("service", "ls", "--filter", filter2)
  173. assert.NilError(c, err, out)
  174. assert.Assert(c, strings.Contains(out, name1+" "), out)
  175. assert.Assert(c, strings.Contains(out, name2+" "), out)
  176. assert.Assert(c, !strings.Contains(out, name3+" "), out)
  177. out, err = d.Cmd("service", "ls")
  178. assert.NilError(c, err, out)
  179. assert.Assert(c, strings.Contains(out, name1+" "), out)
  180. assert.Assert(c, strings.Contains(out, name2+" "), out)
  181. assert.Assert(c, strings.Contains(out, name3+" "), out)
  182. }
  183. func (s *DockerSwarmSuite) TestSwarmNodeListFilter(c *testing.T) {
  184. d := s.AddDaemon(c, true, true)
  185. out, err := d.Cmd("node", "inspect", "--format", "{{ .Description.Hostname }}", "self")
  186. assert.NilError(c, err, out)
  187. assert.Assert(c, strings.TrimSpace(out) != "")
  188. name := strings.TrimSpace(out)
  189. filter := "name=" + name[:4]
  190. out, err = d.Cmd("node", "ls", "--filter", filter)
  191. assert.NilError(c, err, out)
  192. assert.Assert(c, strings.Contains(out, name), out)
  193. out, err = d.Cmd("node", "ls", "--filter", "name=none")
  194. assert.NilError(c, err, out)
  195. assert.Assert(c, !strings.Contains(out, name), out)
  196. }
  197. func (s *DockerSwarmSuite) TestSwarmNodeTaskListFilter(c *testing.T) {
  198. d := s.AddDaemon(c, true, true)
  199. name := "redis-cluster-md5"
  200. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--replicas=3", "busybox", "top")
  201. assert.NilError(c, err, out)
  202. assert.Assert(c, strings.TrimSpace(out) != "")
  203. // make sure task has been deployed.
  204. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(3)), poll.WithTimeout(defaultReconciliationTimeout))
  205. filter := "name=redis-cluster"
  206. out, err = d.Cmd("node", "ps", "--filter", filter, "self")
  207. assert.NilError(c, err, out)
  208. assert.Assert(c, strings.Contains(out, name+".1"), out)
  209. assert.Assert(c, strings.Contains(out, name+".2"), out)
  210. assert.Assert(c, strings.Contains(out, name+".3"), out)
  211. out, err = d.Cmd("node", "ps", "--filter", "name=none", "self")
  212. assert.NilError(c, err, out)
  213. assert.Assert(c, !strings.Contains(out, name+".1"), out)
  214. assert.Assert(c, !strings.Contains(out, name+".2"), out)
  215. assert.Assert(c, !strings.Contains(out, name+".3"), out)
  216. }
  217. // Test case for #25375
  218. func (s *DockerSwarmSuite) TestSwarmPublishAdd(c *testing.T) {
  219. d := s.AddDaemon(c, true, true)
  220. name := "top"
  221. // this first command does not have to be retried because service creates
  222. // don't return out of sequence errors.
  223. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--label", "x=y", "busybox", "top")
  224. assert.NilError(c, err, out)
  225. assert.Assert(c, strings.TrimSpace(out) != "")
  226. out, err = d.CmdRetryOutOfSequence("service", "update", "--detach", "--publish-add", "80:80", name)
  227. assert.NilError(c, err, out)
  228. out, err = d.CmdRetryOutOfSequence("service", "update", "--detach", "--publish-add", "80:80", name)
  229. assert.NilError(c, err, out)
  230. _, err = d.CmdRetryOutOfSequence("service", "update", "--detach", "--publish-add", "80:80", "--publish-add", "80:20", name)
  231. assert.ErrorContains(c, err, "")
  232. // this last command does not have to be retried because service inspect
  233. // does not return out of sequence errors.
  234. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.EndpointSpec.Ports }}", name)
  235. assert.NilError(c, err, out)
  236. assert.Equal(c, strings.TrimSpace(out), "[{ tcp 80 80 ingress}]")
  237. }
  238. func (s *DockerSwarmSuite) TestSwarmServiceWithGroup(c *testing.T) {
  239. d := s.AddDaemon(c, true, true)
  240. name := "top"
  241. 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")
  242. assert.NilError(c, err, out)
  243. assert.Assert(c, strings.TrimSpace(out) != "")
  244. // make sure task has been deployed.
  245. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  246. out, err = d.Cmd("ps", "-q")
  247. assert.NilError(c, err, out)
  248. assert.Assert(c, strings.TrimSpace(out) != "")
  249. container := strings.TrimSpace(out)
  250. out, err = d.Cmd("exec", container, "id")
  251. assert.NilError(c, err, out)
  252. assert.Equal(c, strings.TrimSpace(out), "uid=0(root) gid=0(root) groups=0(root),10(wheel),29(audio),50(staff),777")
  253. }
  254. func (s *DockerSwarmSuite) TestSwarmContainerAutoStart(c *testing.T) {
  255. d := s.AddDaemon(c, true, true)
  256. out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo")
  257. assert.NilError(c, err, out)
  258. assert.Assert(c, strings.TrimSpace(out) != "")
  259. out, err = d.Cmd("run", "-id", "--restart=always", "--net=foo", "--name=test", "busybox", "top")
  260. assert.NilError(c, err, out)
  261. assert.Assert(c, strings.TrimSpace(out) != "")
  262. out, err = d.Cmd("ps", "-q")
  263. assert.NilError(c, err, out)
  264. assert.Assert(c, strings.TrimSpace(out) != "")
  265. d.RestartNode(c)
  266. out, err = d.Cmd("ps", "-q")
  267. assert.NilError(c, err, out)
  268. assert.Assert(c, strings.TrimSpace(out) != "")
  269. }
  270. func (s *DockerSwarmSuite) TestSwarmContainerEndpointOptions(c *testing.T) {
  271. d := s.AddDaemon(c, true, true)
  272. out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo")
  273. assert.NilError(c, err, out)
  274. assert.Assert(c, strings.TrimSpace(out) != "")
  275. out, err = d.Cmd("run", "-d", "--net=foo", "--name=first", "--net-alias=first-alias", "busybox:glibc", "top")
  276. assert.NilError(c, err, out)
  277. out, err = d.Cmd("run", "-d", "--net=foo", "--name=second", "busybox:glibc", "top")
  278. assert.NilError(c, err, out)
  279. out, err = d.Cmd("run", "-d", "--net=foo", "--net-alias=third-alias", "busybox:glibc", "top")
  280. assert.NilError(c, err, out)
  281. // ping first container and its alias, also ping third and anonymous container by its alias
  282. out, err = d.Cmd("exec", "second", "ping", "-c", "1", "first")
  283. assert.NilError(c, err, out)
  284. out, err = d.Cmd("exec", "second", "ping", "-c", "1", "first-alias")
  285. assert.NilError(c, err, out)
  286. out, err = d.Cmd("exec", "second", "ping", "-c", "1", "third-alias")
  287. assert.NilError(c, err, out)
  288. }
  289. func (s *DockerSwarmSuite) TestSwarmContainerAttachByNetworkId(c *testing.T) {
  290. d := s.AddDaemon(c, true, true)
  291. out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "testnet")
  292. assert.NilError(c, err, out)
  293. assert.Assert(c, strings.TrimSpace(out) != "")
  294. networkID := strings.TrimSpace(out)
  295. out, err = d.Cmd("run", "-d", "--net", networkID, "busybox", "top")
  296. assert.NilError(c, err, out)
  297. cID := strings.TrimSpace(out)
  298. d.WaitRun(cID)
  299. out, err = d.Cmd("rm", "-f", cID)
  300. assert.NilError(c, err, out)
  301. out, err = d.Cmd("network", "rm", "testnet")
  302. assert.NilError(c, err, out)
  303. checkNetwork := func(*testing.T) (interface{}, string) {
  304. out, err := d.Cmd("network", "ls")
  305. assert.NilError(c, err)
  306. return out, ""
  307. }
  308. poll.WaitOn(c, pollCheck(c, checkNetwork, checker.Not(checker.Contains("testnet"))), poll.WithTimeout(3*time.Second))
  309. }
  310. func (s *DockerSwarmSuite) TestOverlayAttachable(c *testing.T) {
  311. d := s.AddDaemon(c, true, true)
  312. out, err := d.Cmd("network", "create", "-d", "overlay", "--attachable", "ovnet")
  313. assert.NilError(c, err, out)
  314. // validate attachable
  315. out, err = d.Cmd("network", "inspect", "--format", "{{json .Attachable}}", "ovnet")
  316. assert.NilError(c, err, out)
  317. assert.Equal(c, strings.TrimSpace(out), "true")
  318. // validate containers can attach to this overlay network
  319. out, err = d.Cmd("run", "-d", "--network", "ovnet", "--name", "c1", "busybox", "top")
  320. assert.NilError(c, err, out)
  321. // redo validation, there was a bug that the value of attachable changes after
  322. // containers attach to the network
  323. out, err = d.Cmd("network", "inspect", "--format", "{{json .Attachable}}", "ovnet")
  324. assert.NilError(c, err, out)
  325. assert.Equal(c, strings.TrimSpace(out), "true")
  326. }
  327. func (s *DockerSwarmSuite) TestOverlayAttachableOnSwarmLeave(c *testing.T) {
  328. d := s.AddDaemon(c, true, true)
  329. // Create an attachable swarm network
  330. nwName := "attovl"
  331. out, err := d.Cmd("network", "create", "-d", "overlay", "--attachable", nwName)
  332. assert.NilError(c, err, out)
  333. // Connect a container to the network
  334. out, err = d.Cmd("run", "-d", "--network", nwName, "--name", "c1", "busybox", "top")
  335. assert.NilError(c, err, out)
  336. // Leave the swarm
  337. assert.Assert(c, d.SwarmLeave(c, true) == nil)
  338. // Check the container is disconnected
  339. out, err = d.Cmd("inspect", "c1", "--format", "{{.NetworkSettings.Networks."+nwName+"}}")
  340. assert.NilError(c, err, out)
  341. assert.Equal(c, strings.TrimSpace(out), "<no value>")
  342. // Check the network is gone
  343. out, err = d.Cmd("network", "ls", "--format", "{{.Name}}")
  344. assert.NilError(c, err, out)
  345. assert.Assert(c, !strings.Contains(out, nwName), out)
  346. }
  347. func (s *DockerSwarmSuite) TestOverlayAttachableReleaseResourcesOnFailure(c *testing.T) {
  348. d := s.AddDaemon(c, true, true)
  349. // Create attachable network
  350. out, err := d.Cmd("network", "create", "-d", "overlay", "--attachable", "--subnet", "10.10.9.0/24", "ovnet")
  351. assert.NilError(c, err, out)
  352. // Attach a container with specific IP
  353. out, err = d.Cmd("run", "-d", "--network", "ovnet", "--name", "c1", "--ip", "10.10.9.33", "busybox", "top")
  354. assert.NilError(c, err, out)
  355. // Attempt to attach another container with same IP, must fail
  356. out, err = d.Cmd("run", "-d", "--network", "ovnet", "--name", "c2", "--ip", "10.10.9.33", "busybox", "top")
  357. assert.ErrorContains(c, err, "", out)
  358. // Remove first container
  359. out, err = d.Cmd("rm", "-f", "c1")
  360. assert.NilError(c, err, out)
  361. // Verify the network can be removed, no phantom network attachment task left over
  362. out, err = d.Cmd("network", "rm", "ovnet")
  363. assert.NilError(c, err, out)
  364. }
  365. func (s *DockerSwarmSuite) TestSwarmIngressNetwork(c *testing.T) {
  366. d := s.AddDaemon(c, true, true)
  367. // Ingress network can be removed
  368. removeNetwork := func(name string) *icmd.Result {
  369. return cli.Docker(
  370. cli.Args("-H", d.Sock(), "network", "rm", name),
  371. cli.WithStdin(strings.NewReader("Y")))
  372. }
  373. result := removeNetwork("ingress")
  374. result.Assert(c, icmd.Success)
  375. // And recreated
  376. out, err := d.Cmd("network", "create", "-d", "overlay", "--ingress", "new-ingress")
  377. assert.NilError(c, err, out)
  378. // But only one is allowed
  379. out, err = d.Cmd("network", "create", "-d", "overlay", "--ingress", "another-ingress")
  380. assert.ErrorContains(c, err, "")
  381. assert.Assert(c, strings.Contains(strings.TrimSpace(out), "is already present"), out)
  382. // It cannot be removed if it is being used
  383. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv1", "-p", "9000:8000", "busybox", "top")
  384. assert.NilError(c, err, out)
  385. result = removeNetwork("new-ingress")
  386. result.Assert(c, icmd.Expected{
  387. ExitCode: 1,
  388. Err: "ingress network cannot be removed because service",
  389. })
  390. // But it can be removed once no more services depend on it
  391. out, err = d.Cmd("service", "update", "--detach", "--publish-rm", "9000:8000", "srv1")
  392. assert.NilError(c, err, out)
  393. result = removeNetwork("new-ingress")
  394. result.Assert(c, icmd.Success)
  395. // A service which needs the ingress network cannot be created if no ingress is present
  396. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv2", "-p", "500:500", "busybox", "top")
  397. assert.ErrorContains(c, err, "")
  398. assert.Assert(c, strings.Contains(strings.TrimSpace(out), "no ingress network is present"), out)
  399. // An existing service cannot be updated to use the ingress nw if the nw is not present
  400. out, err = d.Cmd("service", "update", "--detach", "--publish-add", "9000:8000", "srv1")
  401. assert.ErrorContains(c, err, "")
  402. assert.Assert(c, strings.Contains(strings.TrimSpace(out), "no ingress network is present"), out)
  403. // But services which do not need routing mesh can be created regardless
  404. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv3", "--endpoint-mode", "dnsrr", "busybox", "top")
  405. assert.NilError(c, err, out)
  406. }
  407. func (s *DockerSwarmSuite) TestSwarmCreateServiceWithNoIngressNetwork(c *testing.T) {
  408. d := s.AddDaemon(c, true, true)
  409. // Remove ingress network
  410. result := cli.Docker(
  411. cli.Args("-H", d.Sock(), "network", "rm", "ingress"),
  412. cli.WithStdin(strings.NewReader("Y")))
  413. result.Assert(c, icmd.Success)
  414. // Create a overlay network and launch a service on it
  415. // Make sure nothing panics because ingress network is missing
  416. out, err := d.Cmd("network", "create", "-d", "overlay", "another-network")
  417. assert.NilError(c, err, out)
  418. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv4", "--network", "another-network", "busybox", "top")
  419. assert.NilError(c, err, out)
  420. }
  421. // Test case for #24108, also the case from:
  422. // https://github.com/docker/docker/pull/24620#issuecomment-233715656
  423. func (s *DockerSwarmSuite) TestSwarmTaskListFilter(c *testing.T) {
  424. d := s.AddDaemon(c, true, true)
  425. name := "redis-cluster-md5"
  426. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--replicas=3", "busybox", "top")
  427. assert.NilError(c, err, out)
  428. assert.Assert(c, strings.TrimSpace(out) != "")
  429. filter := "name=redis-cluster"
  430. checkNumTasks := func(*testing.T) (interface{}, string) {
  431. out, err := d.Cmd("service", "ps", "--filter", filter, name)
  432. assert.NilError(c, err, out)
  433. return len(strings.Split(out, "\n")) - 2, "" // includes header and nl in last line
  434. }
  435. // wait until all tasks have been created
  436. poll.WaitOn(c, pollCheck(c, checkNumTasks, checker.Equals(3)), poll.WithTimeout(defaultReconciliationTimeout))
  437. out, err = d.Cmd("service", "ps", "--filter", filter, name)
  438. assert.NilError(c, err, out)
  439. assert.Assert(c, strings.Contains(out, name+".1"), out)
  440. assert.Assert(c, strings.Contains(out, name+".2"), out)
  441. assert.Assert(c, strings.Contains(out, name+".3"), out)
  442. out, err = d.Cmd("service", "ps", "--filter", "name="+name+".1", name)
  443. assert.NilError(c, err, out)
  444. assert.Assert(c, strings.Contains(out, name+".1"), out)
  445. assert.Assert(c, !strings.Contains(out, name+".2"), out)
  446. assert.Assert(c, !strings.Contains(out, name+".3"), out)
  447. out, err = d.Cmd("service", "ps", "--filter", "name=none", name)
  448. assert.NilError(c, err, out)
  449. assert.Assert(c, !strings.Contains(out, name+".1"), out)
  450. assert.Assert(c, !strings.Contains(out, name+".2"), out)
  451. assert.Assert(c, !strings.Contains(out, name+".3"), out)
  452. name = "redis-cluster-sha1"
  453. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--mode=global", "busybox", "top")
  454. assert.NilError(c, err, out)
  455. assert.Assert(c, strings.TrimSpace(out) != "")
  456. poll.WaitOn(c, pollCheck(c, checkNumTasks, checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  457. filter = "name=redis-cluster"
  458. out, err = d.Cmd("service", "ps", "--filter", filter, name)
  459. assert.NilError(c, err, out)
  460. assert.Assert(c, strings.Contains(out, name), out)
  461. out, err = d.Cmd("service", "ps", "--filter", "name="+name, name)
  462. assert.NilError(c, err, out)
  463. assert.Assert(c, strings.Contains(out, name), out)
  464. out, err = d.Cmd("service", "ps", "--filter", "name=none", name)
  465. assert.NilError(c, err, out)
  466. assert.Assert(c, !strings.Contains(out, name), out)
  467. }
  468. func (s *DockerSwarmSuite) TestPsListContainersFilterIsTask(c *testing.T) {
  469. d := s.AddDaemon(c, true, true)
  470. // Create a bare container
  471. out, err := d.Cmd("run", "-d", "--name=bare-container", "busybox", "top")
  472. assert.NilError(c, err, out)
  473. bareID := strings.TrimSpace(out)[:12]
  474. // Create a service
  475. name := "busybox-top"
  476. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "top")
  477. assert.NilError(c, err, out)
  478. assert.Assert(c, strings.TrimSpace(out) != "")
  479. // make sure task has been deployed.
  480. poll.WaitOn(c, pollCheck(c, d.CheckServiceRunningTasks(name), checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  481. // Filter non-tasks
  482. out, err = d.Cmd("ps", "-a", "-q", "--filter=is-task=false")
  483. assert.NilError(c, err, out)
  484. psOut := strings.TrimSpace(out)
  485. assert.Equal(c, psOut, bareID, fmt.Sprintf("Expected id %s, got %s for is-task label, output %q", bareID, psOut, out))
  486. // Filter tasks
  487. out, err = d.Cmd("ps", "-a", "-q", "--filter=is-task=true")
  488. assert.NilError(c, err, out)
  489. lines := strings.Split(strings.Trim(out, "\n "), "\n")
  490. assert.Equal(c, len(lines), 1)
  491. assert.Assert(c, lines[0] != bareID, "Expected not %s, but got it for is-task label, output %q", bareID, out)
  492. }
  493. const globalNetworkPlugin = "global-network-plugin"
  494. const globalIPAMPlugin = "global-ipam-plugin"
  495. func setupRemoteGlobalNetworkPlugin(c *testing.T, mux *http.ServeMux, url, netDrv, ipamDrv string) {
  496. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  497. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  498. fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
  499. })
  500. // Network driver implementation
  501. mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  502. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  503. fmt.Fprintf(w, `{"Scope":"global"}`)
  504. })
  505. mux.HandleFunc(fmt.Sprintf("/%s.AllocateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  506. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  507. if err != nil {
  508. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  509. return
  510. }
  511. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  512. fmt.Fprintf(w, "null")
  513. })
  514. mux.HandleFunc(fmt.Sprintf("/%s.FreeNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  515. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  516. fmt.Fprintf(w, "null")
  517. })
  518. mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  519. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  520. if err != nil {
  521. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  522. return
  523. }
  524. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  525. fmt.Fprintf(w, "null")
  526. })
  527. mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  528. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  529. fmt.Fprintf(w, "null")
  530. })
  531. mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  532. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  533. fmt.Fprintf(w, `{"Interface":{"MacAddress":"a0:b1:c2:d3:e4:f5"}}`)
  534. })
  535. mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  536. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  537. veth := &netlink.Veth{
  538. LinkAttrs: netlink.LinkAttrs{Name: "randomIfName", TxQLen: 0}, PeerName: "cnt0"}
  539. if err := netlink.LinkAdd(veth); err != nil {
  540. fmt.Fprintf(w, `{"Error":"failed to add veth pair: `+err.Error()+`"}`)
  541. } else {
  542. fmt.Fprintf(w, `{"InterfaceName":{ "SrcName":"cnt0", "DstPrefix":"veth"}}`)
  543. }
  544. })
  545. mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  546. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  547. fmt.Fprintf(w, "null")
  548. })
  549. mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  550. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  551. if link, err := netlink.LinkByName("cnt0"); err == nil {
  552. netlink.LinkDel(link)
  553. }
  554. fmt.Fprintf(w, "null")
  555. })
  556. // IPAM Driver implementation
  557. var (
  558. poolRequest remoteipam.RequestPoolRequest
  559. poolReleaseReq remoteipam.ReleasePoolRequest
  560. addressRequest remoteipam.RequestAddressRequest
  561. addressReleaseReq remoteipam.ReleaseAddressRequest
  562. lAS = "localAS"
  563. gAS = "globalAS"
  564. pool = "172.28.0.0/16"
  565. poolID = lAS + "/" + pool
  566. gw = "172.28.255.254/16"
  567. )
  568. mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  569. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  570. fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
  571. })
  572. mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  573. err := json.NewDecoder(r.Body).Decode(&poolRequest)
  574. if err != nil {
  575. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  576. return
  577. }
  578. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  579. if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
  580. fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
  581. } else if poolRequest.Pool != "" && poolRequest.Pool != pool {
  582. fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
  583. } else {
  584. fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
  585. }
  586. })
  587. mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  588. err := json.NewDecoder(r.Body).Decode(&addressRequest)
  589. if err != nil {
  590. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  591. return
  592. }
  593. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  594. // make sure libnetwork is now querying on the expected pool id
  595. if addressRequest.PoolID != poolID {
  596. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  597. } else if addressRequest.Address != "" {
  598. fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
  599. } else {
  600. fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
  601. }
  602. })
  603. mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  604. err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
  605. if err != nil {
  606. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  607. return
  608. }
  609. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  610. // make sure libnetwork is now asking to release the expected address from the expected poolid
  611. if addressRequest.PoolID != poolID {
  612. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  613. } else if addressReleaseReq.Address != gw {
  614. fmt.Fprintf(w, `{"Error":"unknown address"}`)
  615. } else {
  616. fmt.Fprintf(w, "null")
  617. }
  618. })
  619. mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  620. err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
  621. if err != nil {
  622. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  623. return
  624. }
  625. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  626. // make sure libnetwork is now asking to release the expected poolid
  627. if addressRequest.PoolID != poolID {
  628. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  629. } else {
  630. fmt.Fprintf(w, "null")
  631. }
  632. })
  633. err := os.MkdirAll("/etc/docker/plugins", 0755)
  634. assert.NilError(c, err)
  635. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", netDrv)
  636. err = os.WriteFile(fileName, []byte(url), 0644)
  637. assert.NilError(c, err)
  638. ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", ipamDrv)
  639. err = os.WriteFile(ipamFileName, []byte(url), 0644)
  640. assert.NilError(c, err)
  641. }
  642. func (s *DockerSwarmSuite) TestSwarmNetworkPlugin(c *testing.T) {
  643. mux := http.NewServeMux()
  644. s.server = httptest.NewServer(mux)
  645. assert.Assert(c, s.server != nil) // check that HTTP server has started
  646. setupRemoteGlobalNetworkPlugin(c, mux, s.server.URL, globalNetworkPlugin, globalIPAMPlugin)
  647. defer func() {
  648. s.server.Close()
  649. err := os.RemoveAll("/etc/docker/plugins")
  650. assert.NilError(c, err)
  651. }()
  652. d := s.AddDaemon(c, true, true)
  653. out, err := d.Cmd("network", "create", "-d", globalNetworkPlugin, "foo")
  654. assert.ErrorContains(c, err, "", out)
  655. assert.Assert(c, strings.Contains(out, "not supported in swarm mode"), out)
  656. }
  657. // Test case for #24712
  658. func (s *DockerSwarmSuite) TestSwarmServiceEnvFile(c *testing.T) {
  659. d := s.AddDaemon(c, true, true)
  660. path := filepath.Join(d.Folder, "env.txt")
  661. err := os.WriteFile(path, []byte("VAR1=A\nVAR2=A\n"), 0644)
  662. assert.NilError(c, err)
  663. name := "worker"
  664. 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")
  665. assert.NilError(c, err, out)
  666. assert.Assert(c, strings.TrimSpace(out) != "")
  667. // The complete env is [VAR1=A VAR2=A VAR1=B VAR1=C VAR2= VAR2] and duplicates will be removed => [VAR1=C VAR2]
  668. out, err = d.Cmd("inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.Env }}", name)
  669. assert.NilError(c, err, out)
  670. assert.Assert(c, strings.Contains(out, "[VAR1=C VAR2]"), out)
  671. }
  672. func (s *DockerSwarmSuite) TestSwarmServiceTTY(c *testing.T) {
  673. d := s.AddDaemon(c, true, true)
  674. name := "top"
  675. ttyCheck := "if [ -t 0 ]; then echo TTY > /status; else echo none > /status; fi; exec top"
  676. // Without --tty
  677. expectedOutput := "none"
  678. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", ttyCheck)
  679. assert.NilError(c, err, out)
  680. // Make sure task has been deployed.
  681. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  682. // We need to get the container id.
  683. out, err = d.Cmd("ps", "-q", "--no-trunc")
  684. assert.NilError(c, err, out)
  685. id := strings.TrimSpace(out)
  686. out, err = d.Cmd("exec", id, "cat", "/status")
  687. assert.NilError(c, err, out)
  688. assert.Assert(c, strings.Contains(out, expectedOutput), "Expected '%s', but got %q", expectedOutput, out)
  689. // Remove service
  690. out, err = d.Cmd("service", "rm", name)
  691. assert.NilError(c, err, out)
  692. // Make sure container has been destroyed.
  693. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(0)), poll.WithTimeout(defaultReconciliationTimeout))
  694. // With --tty
  695. expectedOutput = "TTY"
  696. out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--tty", "busybox", "sh", "-c", ttyCheck)
  697. assert.NilError(c, err, out)
  698. // Make sure task has been deployed.
  699. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  700. // We need to get the container id.
  701. out, err = d.Cmd("ps", "-q", "--no-trunc")
  702. assert.NilError(c, err, out)
  703. id = strings.TrimSpace(out)
  704. out, err = d.Cmd("exec", id, "cat", "/status")
  705. assert.NilError(c, err, out)
  706. assert.Assert(c, strings.Contains(out, expectedOutput), "Expected '%s', but got %q", expectedOutput, out)
  707. }
  708. func (s *DockerSwarmSuite) TestSwarmServiceTTYUpdate(c *testing.T) {
  709. d := s.AddDaemon(c, true, true)
  710. // Create a service
  711. name := "top"
  712. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "top")
  713. assert.NilError(c, err, out)
  714. // Make sure task has been deployed.
  715. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  716. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.TTY }}", name)
  717. assert.NilError(c, err, out)
  718. assert.Equal(c, strings.TrimSpace(out), "false")
  719. out, err = d.Cmd("service", "update", "--detach", "--tty", name)
  720. assert.NilError(c, err, out)
  721. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.TTY }}", name)
  722. assert.NilError(c, err, out)
  723. assert.Equal(c, strings.TrimSpace(out), "true")
  724. }
  725. func (s *DockerSwarmSuite) TestSwarmServiceNetworkUpdate(c *testing.T) {
  726. d := s.AddDaemon(c, true, true)
  727. result := icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "foo"))
  728. result.Assert(c, icmd.Success)
  729. fooNetwork := strings.TrimSpace(result.Combined())
  730. result = icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "bar"))
  731. result.Assert(c, icmd.Success)
  732. barNetwork := strings.TrimSpace(result.Combined())
  733. result = icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "baz"))
  734. result.Assert(c, icmd.Success)
  735. bazNetwork := strings.TrimSpace(result.Combined())
  736. // Create a service
  737. name := "top"
  738. result = icmd.RunCmd(d.Command("service", "create", "--detach", "--no-resolve-image", "--network", "foo", "--network", "bar", "--name", name, "busybox", "top"))
  739. result.Assert(c, icmd.Success)
  740. // Make sure task has been deployed.
  741. poll.WaitOn(c, pollCheck(c, d.CheckRunningTaskNetworks, checker.DeepEquals(map[string]int{fooNetwork: 1, barNetwork: 1})), poll.WithTimeout(defaultReconciliationTimeout))
  742. // Remove a network
  743. result = icmd.RunCmd(d.Command("service", "update", "--detach", "--network-rm", "foo", name))
  744. result.Assert(c, icmd.Success)
  745. poll.WaitOn(c, pollCheck(c, d.CheckRunningTaskNetworks, checker.DeepEquals(map[string]int{barNetwork: 1})), poll.WithTimeout(defaultReconciliationTimeout))
  746. // Add a network
  747. result = icmd.RunCmd(d.Command("service", "update", "--detach", "--network-add", "baz", name))
  748. result.Assert(c, icmd.Success)
  749. poll.WaitOn(c, pollCheck(c, d.CheckRunningTaskNetworks, checker.DeepEquals(map[string]int{barNetwork: 1, bazNetwork: 1})), poll.WithTimeout(defaultReconciliationTimeout))
  750. }
  751. func (s *DockerSwarmSuite) TestDNSConfig(c *testing.T) {
  752. d := s.AddDaemon(c, true, true)
  753. // Create a service
  754. name := "top"
  755. 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")
  756. assert.NilError(c, err, out)
  757. // Make sure task has been deployed.
  758. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  759. // We need to get the container id.
  760. out, err = d.Cmd("ps", "-a", "-q", "--no-trunc")
  761. assert.NilError(c, err, out)
  762. id := strings.TrimSpace(out)
  763. // Compare against expected output.
  764. expectedOutput1 := "nameserver 1.2.3.4"
  765. expectedOutput2 := "search example.com"
  766. expectedOutput3 := "options timeout:3"
  767. out, err = d.Cmd("exec", id, "cat", "/etc/resolv.conf")
  768. assert.NilError(c, err, out)
  769. assert.Assert(c, strings.Contains(out, expectedOutput1), "Expected '%s', but got %q", expectedOutput1, out)
  770. assert.Assert(c, strings.Contains(out, expectedOutput2), "Expected '%s', but got %q", expectedOutput2, out)
  771. assert.Assert(c, strings.Contains(out, expectedOutput3), "Expected '%s', but got %q", expectedOutput3, out)
  772. }
  773. func (s *DockerSwarmSuite) TestDNSConfigUpdate(c *testing.T) {
  774. d := s.AddDaemon(c, true, true)
  775. // Create a service
  776. name := "top"
  777. out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "top")
  778. assert.NilError(c, err, out)
  779. // Make sure task has been deployed.
  780. poll.WaitOn(c, pollCheck(c, d.CheckActiveContainerCount, checker.Equals(1)), poll.WithTimeout(defaultReconciliationTimeout))
  781. out, err = d.Cmd("service", "update", "--detach", "--dns-add=1.2.3.4", "--dns-search-add=example.com", "--dns-option-add=timeout:3", name)
  782. assert.NilError(c, err, out)
  783. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.DNSConfig }}", name)
  784. assert.NilError(c, err, out)
  785. assert.Equal(c, strings.TrimSpace(out), "{[1.2.3.4] [example.com] [timeout:3]}")
  786. }
  787. func getNodeStatus(c *testing.T, d *daemon.Daemon) swarm.LocalNodeState {
  788. info := d.SwarmInfo(c)
  789. return info.LocalNodeState
  790. }
  791. func checkKeyIsEncrypted(d *daemon.Daemon) func(*testing.T) (interface{}, string) {
  792. return func(c *testing.T) (interface{}, string) {
  793. keyBytes, err := os.ReadFile(filepath.Join(d.Folder, "root", "swarm", "certificates", "swarm-node.key"))
  794. if err != nil {
  795. return fmt.Errorf("error reading key: %v", err), ""
  796. }
  797. keyBlock, _ := pem.Decode(keyBytes)
  798. if keyBlock == nil {
  799. return fmt.Errorf("invalid PEM-encoded private key"), ""
  800. }
  801. return keyutils.IsEncryptedPEMBlock(keyBlock), ""
  802. }
  803. }
  804. func checkSwarmLockedToUnlocked(c *testing.T, d *daemon.Daemon) {
  805. // Wait for the PEM file to become unencrypted
  806. poll.WaitOn(c, pollCheck(c, checkKeyIsEncrypted(d), checker.Equals(false)), poll.WithTimeout(defaultReconciliationTimeout))
  807. d.RestartNode(c)
  808. poll.WaitOn(c, pollCheck(c, d.CheckLocalNodeState, checker.Equals(swarm.LocalNodeStateActive)), poll.WithTimeout(time.Second))
  809. }
  810. func checkSwarmUnlockedToLocked(c *testing.T, d *daemon.Daemon) {
  811. // Wait for the PEM file to become encrypted
  812. poll.WaitOn(c, pollCheck(c, checkKeyIsEncrypted(d), checker.Equals(true)), poll.WithTimeout(defaultReconciliationTimeout))
  813. d.RestartNode(c)
  814. poll.WaitOn(c, pollCheck(c, d.CheckLocalNodeState, checker.Equals(swarm.LocalNodeStateLocked)), poll.WithTimeout(time.Second))
  815. }
  816. func (s *DockerSwarmSuite) TestUnlockEngineAndUnlockedSwarm(c *testing.T) {
  817. d := s.AddDaemon(c, false, false)
  818. // unlocking a normal engine should return an error - it does not even ask for the key
  819. cmd := d.Command("swarm", "unlock")
  820. result := icmd.RunCmd(cmd)
  821. result.Assert(c, icmd.Expected{
  822. ExitCode: 1,
  823. })
  824. out := result.Combined()
  825. assert.Assert(c, strings.Contains(result.Combined(), "Error: This node is not part of a swarm"), out)
  826. assert.Assert(c, !strings.Contains(result.Combined(), "Please enter unlock key"), out)
  827. out, err := d.Cmd("swarm", "init")
  828. assert.NilError(c, err, out)
  829. // unlocking an unlocked swarm should return an error - it does not even ask for the key
  830. cmd = d.Command("swarm", "unlock")
  831. result = icmd.RunCmd(cmd)
  832. result.Assert(c, icmd.Expected{
  833. ExitCode: 1,
  834. })
  835. out = result.Combined()
  836. assert.Assert(c, strings.Contains(result.Combined(), "Error: swarm is not locked"), out)
  837. assert.Assert(c, !strings.Contains(result.Combined(), "Please enter unlock key"), out)
  838. }
  839. func (s *DockerSwarmSuite) TestSwarmInitLocked(c *testing.T) {
  840. d := s.AddDaemon(c, false, false)
  841. outs, err := d.Cmd("swarm", "init", "--autolock")
  842. assert.Assert(c, err == nil, outs)
  843. unlockKey := getUnlockKey(d, c, outs)
  844. assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateActive)
  845. // It starts off locked
  846. d.RestartNode(c)
  847. assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateLocked)
  848. cmd := d.Command("swarm", "unlock")
  849. cmd.Stdin = bytes.NewBufferString("wrong-secret-key")
  850. icmd.RunCmd(cmd).Assert(c, icmd.Expected{
  851. ExitCode: 1,
  852. Err: "invalid key",
  853. })
  854. assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateLocked)
  855. cmd = d.Command("swarm", "unlock")
  856. cmd.Stdin = bytes.NewBufferString(unlockKey)
  857. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  858. assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateActive)
  859. outs, err = d.Cmd("node", "ls")
  860. assert.Assert(c, err == nil, outs)
  861. assert.Assert(c, !strings.Contains(outs, "Swarm is encrypted and needs to be unlocked"), outs)
  862. outs, err = d.Cmd("swarm", "update", "--autolock=false")
  863. assert.Assert(c, err == nil, outs)
  864. checkSwarmLockedToUnlocked(c, d)
  865. outs, err = d.Cmd("node", "ls")
  866. assert.Assert(c, err == nil, outs)
  867. assert.Assert(c, !strings.Contains(outs, "Swarm is encrypted and needs to be unlocked"), outs)
  868. }
  869. func (s *DockerSwarmSuite) TestSwarmLeaveLocked(c *testing.T) {
  870. d := s.AddDaemon(c, false, false)
  871. outs, err := d.Cmd("swarm", "init", "--autolock")
  872. assert.Assert(c, err == nil, outs)
  873. // It starts off locked
  874. d.RestartNode(c)
  875. info := d.SwarmInfo(c)
  876. assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateLocked)
  877. outs, _ = d.Cmd("node", "ls")
  878. assert.Assert(c, strings.Contains(outs, "Swarm is encrypted and needs to be unlocked"), outs)
  879. // `docker swarm leave` a locked swarm without --force will return an error
  880. outs, _ = d.Cmd("swarm", "leave")
  881. assert.Assert(c, strings.Contains(outs, "Swarm is encrypted and locked."), outs)
  882. // It is OK for user to leave a locked swarm with --force
  883. outs, err = d.Cmd("swarm", "leave", "--force")
  884. assert.Assert(c, err == nil, outs)
  885. info = d.SwarmInfo(c)
  886. assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive)
  887. outs, err = d.Cmd("swarm", "init")
  888. assert.Assert(c, err == nil, outs)
  889. info = d.SwarmInfo(c)
  890. assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive)
  891. }
  892. func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *testing.T) {
  893. d1 := s.AddDaemon(c, true, true)
  894. d2 := s.AddDaemon(c, true, true)
  895. d3 := s.AddDaemon(c, true, true)
  896. // they start off unlocked
  897. d2.RestartNode(c)
  898. assert.Equal(c, getNodeStatus(c, d2), swarm.LocalNodeStateActive)
  899. // stop this one so it does not get autolock info
  900. d2.Stop(c)
  901. // enable autolock
  902. outs, err := d1.Cmd("swarm", "update", "--autolock")
  903. assert.Assert(c, err == nil, outs)
  904. unlockKey := getUnlockKey(d1, c, outs)
  905. // The ones that got the cluster update should be set to locked
  906. for _, d := range []*daemon.Daemon{d1, d3} {
  907. checkSwarmUnlockedToLocked(c, d)
  908. cmd := d.Command("swarm", "unlock")
  909. cmd.Stdin = bytes.NewBufferString(unlockKey)
  910. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  911. assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateActive)
  912. }
  913. // d2 never got the cluster update, so it is still set to unlocked
  914. d2.StartNode(c)
  915. assert.Equal(c, getNodeStatus(c, d2), swarm.LocalNodeStateActive)
  916. // d2 is now set to lock
  917. checkSwarmUnlockedToLocked(c, d2)
  918. // leave it locked, and set the cluster to no longer autolock
  919. outs, err = d1.Cmd("swarm", "update", "--autolock=false")
  920. assert.Assert(c, err == nil, "out: %v", outs)
  921. // the ones that got the update are now set to unlocked
  922. for _, d := range []*daemon.Daemon{d1, d3} {
  923. checkSwarmLockedToUnlocked(c, d)
  924. }
  925. // d2 still locked
  926. assert.Equal(c, getNodeStatus(c, d2), swarm.LocalNodeStateLocked)
  927. // unlock it
  928. cmd := d2.Command("swarm", "unlock")
  929. cmd.Stdin = bytes.NewBufferString(unlockKey)
  930. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  931. assert.Equal(c, getNodeStatus(c, d2), swarm.LocalNodeStateActive)
  932. // once it's caught up, d2 is set to not be locked
  933. checkSwarmLockedToUnlocked(c, d2)
  934. // managers who join now are never set to locked in the first place
  935. d4 := s.AddDaemon(c, true, true)
  936. d4.RestartNode(c)
  937. assert.Equal(c, getNodeStatus(c, d4), swarm.LocalNodeStateActive)
  938. }
  939. func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *testing.T) {
  940. d1 := s.AddDaemon(c, true, true)
  941. // enable autolock
  942. outs, err := d1.Cmd("swarm", "update", "--autolock")
  943. assert.Assert(c, err == nil, "out: %v", outs)
  944. unlockKey := getUnlockKey(d1, c, outs)
  945. // joined workers start off unlocked
  946. d2 := s.AddDaemon(c, true, false)
  947. d2.RestartNode(c)
  948. poll.WaitOn(c, pollCheck(c, d2.CheckLocalNodeState, checker.Equals(swarm.LocalNodeStateActive)), poll.WithTimeout(time.Second))
  949. // promote worker
  950. outs, err = d1.Cmd("node", "promote", d2.NodeID())
  951. assert.NilError(c, err)
  952. assert.Assert(c, strings.Contains(outs, "promoted to a manager in the swarm"), outs)
  953. // join new manager node
  954. d3 := s.AddDaemon(c, true, true)
  955. // both new nodes are locked
  956. for _, d := range []*daemon.Daemon{d2, d3} {
  957. checkSwarmUnlockedToLocked(c, d)
  958. cmd := d.Command("swarm", "unlock")
  959. cmd.Stdin = bytes.NewBufferString(unlockKey)
  960. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  961. assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateActive)
  962. }
  963. // demote manager back to worker - workers are not locked
  964. outs, err = d1.Cmd("node", "demote", d3.NodeID())
  965. assert.NilError(c, err)
  966. assert.Assert(c, strings.Contains(outs, "demoted in the swarm"), outs)
  967. // Wait for it to actually be demoted, for the key and cert to be replaced.
  968. // Then restart and assert that the node is not locked. If we don't wait for the cert
  969. // to be replaced, then the node still has the manager TLS key which is still locked
  970. // (because we never want a manager TLS key to be on disk unencrypted if the cluster
  971. // is set to autolock)
  972. poll.WaitOn(c, pollCheck(c, d3.CheckControlAvailable, checker.False()), poll.WithTimeout(defaultReconciliationTimeout))
  973. poll.WaitOn(c, pollCheck(c, func(c *testing.T) (interface{}, string) {
  974. certBytes, err := os.ReadFile(filepath.Join(d3.Folder, "root", "swarm", "certificates", "swarm-node.crt"))
  975. if err != nil {
  976. return "", fmt.Sprintf("error: %v", err)
  977. }
  978. certs, err := helpers.ParseCertificatesPEM(certBytes)
  979. if err == nil && len(certs) > 0 && len(certs[0].Subject.OrganizationalUnit) > 0 {
  980. return certs[0].Subject.OrganizationalUnit[0], ""
  981. }
  982. return "", "could not get organizational unit from certificate"
  983. }, checker.Equals("swarm-worker")), poll.WithTimeout(defaultReconciliationTimeout))
  984. // by now, it should *never* be locked on restart
  985. d3.RestartNode(c)
  986. poll.WaitOn(c, pollCheck(c, d3.CheckLocalNodeState, checker.Equals(swarm.LocalNodeStateActive)), poll.WithTimeout(time.Second))
  987. }
  988. func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *testing.T) {
  989. d := s.AddDaemon(c, true, true)
  990. outs, err := d.Cmd("swarm", "update", "--autolock")
  991. assert.Assert(c, err == nil, "out: %v", outs)
  992. unlockKey := getUnlockKey(d, c, outs)
  993. // Rotate multiple times
  994. for i := 0; i != 3; i++ {
  995. outs, err = d.Cmd("swarm", "unlock-key", "-q", "--rotate")
  996. assert.Assert(c, err == nil, "out: %v", outs)
  997. // Strip \n
  998. newUnlockKey := outs[:len(outs)-1]
  999. assert.Assert(c, newUnlockKey != "")
  1000. assert.Assert(c, newUnlockKey != unlockKey)
  1001. d.RestartNode(c)
  1002. assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateLocked)
  1003. outs, _ = d.Cmd("node", "ls")
  1004. assert.Assert(c, strings.Contains(outs, "Swarm is encrypted and needs to be unlocked"), outs)
  1005. cmd := d.Command("swarm", "unlock")
  1006. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1007. result := icmd.RunCmd(cmd)
  1008. if result.Error == nil {
  1009. // On occasion, the daemon may not have finished
  1010. // rotating the KEK before restarting. The test is
  1011. // intentionally written to explore this behavior.
  1012. // When this happens, unlocking with the old key will
  1013. // succeed. If we wait for the rotation to happen and
  1014. // restart again, the new key should be required this
  1015. // time.
  1016. time.Sleep(3 * time.Second)
  1017. d.RestartNode(c)
  1018. cmd = d.Command("swarm", "unlock")
  1019. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1020. result = icmd.RunCmd(cmd)
  1021. }
  1022. result.Assert(c, icmd.Expected{
  1023. ExitCode: 1,
  1024. Err: "invalid key",
  1025. })
  1026. outs, _ = d.Cmd("node", "ls")
  1027. assert.Assert(c, strings.Contains(outs, "Swarm is encrypted and needs to be unlocked"), outs)
  1028. cmd = d.Command("swarm", "unlock")
  1029. cmd.Stdin = bytes.NewBufferString(newUnlockKey)
  1030. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  1031. assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateActive)
  1032. retry := 0
  1033. for {
  1034. // an issue sometimes prevents leader to be available right away
  1035. outs, err = d.Cmd("node", "ls")
  1036. if err != nil && retry < 5 {
  1037. if strings.Contains(outs, "swarm does not have a leader") {
  1038. retry++
  1039. time.Sleep(3 * time.Second)
  1040. continue
  1041. }
  1042. }
  1043. assert.NilError(c, err)
  1044. assert.Assert(c, !strings.Contains(outs, "Swarm is encrypted and needs to be unlocked"), outs)
  1045. break
  1046. }
  1047. unlockKey = newUnlockKey
  1048. }
  1049. }
  1050. // This differs from `TestSwarmRotateUnlockKey` because that one rotates a single node, which is the leader.
  1051. // This one keeps the leader up, and asserts that other manager nodes in the cluster also have their unlock
  1052. // key rotated.
  1053. func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *testing.T) {
  1054. if runtime.GOARCH == "s390x" {
  1055. c.Skip("Disabled on s390x")
  1056. }
  1057. if runtime.GOARCH == "ppc64le" {
  1058. c.Skip("Disabled on ppc64le")
  1059. }
  1060. d1 := s.AddDaemon(c, true, true) // leader - don't restart this one, we don't want leader election delays
  1061. d2 := s.AddDaemon(c, true, true)
  1062. d3 := s.AddDaemon(c, true, true)
  1063. outs, err := d1.Cmd("swarm", "update", "--autolock")
  1064. assert.Assert(c, err == nil, outs)
  1065. unlockKey := getUnlockKey(d1, c, outs)
  1066. // Rotate multiple times
  1067. for i := 0; i != 3; i++ {
  1068. outs, err = d1.Cmd("swarm", "unlock-key", "-q", "--rotate")
  1069. assert.Assert(c, err == nil, outs)
  1070. // Strip \n
  1071. newUnlockKey := outs[:len(outs)-1]
  1072. assert.Assert(c, newUnlockKey != "")
  1073. assert.Assert(c, newUnlockKey != unlockKey)
  1074. d2.RestartNode(c)
  1075. d3.RestartNode(c)
  1076. for _, d := range []*daemon.Daemon{d2, d3} {
  1077. assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateLocked)
  1078. outs, _ := d.Cmd("node", "ls")
  1079. assert.Assert(c, strings.Contains(outs, "Swarm is encrypted and needs to be unlocked"), outs)
  1080. cmd := d.Command("swarm", "unlock")
  1081. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1082. result := icmd.RunCmd(cmd)
  1083. if result.Error == nil {
  1084. // On occasion, the daemon may not have finished
  1085. // rotating the KEK before restarting. The test is
  1086. // intentionally written to explore this behavior.
  1087. // When this happens, unlocking with the old key will
  1088. // succeed. If we wait for the rotation to happen and
  1089. // restart again, the new key should be required this
  1090. // time.
  1091. time.Sleep(3 * time.Second)
  1092. d.RestartNode(c)
  1093. cmd = d.Command("swarm", "unlock")
  1094. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1095. result = icmd.RunCmd(cmd)
  1096. }
  1097. result.Assert(c, icmd.Expected{
  1098. ExitCode: 1,
  1099. Err: "invalid key",
  1100. })
  1101. outs, _ = d.Cmd("node", "ls")
  1102. assert.Assert(c, strings.Contains(outs, "Swarm is encrypted and needs to be unlocked"), outs)
  1103. cmd = d.Command("swarm", "unlock")
  1104. cmd.Stdin = bytes.NewBufferString(newUnlockKey)
  1105. icmd.RunCmd(cmd).Assert(c, icmd.Success)
  1106. assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateActive)
  1107. retry := 0
  1108. for {
  1109. // an issue sometimes prevents leader to be available right away
  1110. outs, err = d.Cmd("node", "ls")
  1111. if err != nil && retry < 5 {
  1112. if strings.Contains(outs, "swarm does not have a leader") {
  1113. retry++
  1114. c.Logf("[%s] got 'swarm does not have a leader'. retrying (attempt %d/5)", d.ID(), retry)
  1115. time.Sleep(3 * time.Second)
  1116. continue
  1117. } else {
  1118. c.Logf("[%s] gave error: '%v'. retrying (attempt %d/5): %s", d.ID(), err, retry, outs)
  1119. }
  1120. }
  1121. assert.NilError(c, err, "[%s] failed after %d retries: %v (%s)", d.ID(), retry, err, outs)
  1122. assert.Assert(c, !strings.Contains(outs, "Swarm is encrypted and needs to be unlocked"), outs)
  1123. break
  1124. }
  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. }