docker_cli_swarm_test.go 78 KB

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