docker_cli_swarm_test.go 75 KB

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