docker_cli_swarm_test.go 75 KB

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