docker_cli_swarm_test.go 75 KB

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