docker_cli_swarm_test.go 76 KB

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