docker_cli_swarm_test.go 77 KB

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