docker_cli_swarm_test.go 67 KB

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