docker_cli_swarm_test.go 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  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/swarm"
  15. "github.com/docker/docker/integration-cli/daemon"
  16. "github.com/docker/docker/pkg/integration/checker"
  17. "github.com/docker/libnetwork/driverapi"
  18. "github.com/docker/libnetwork/ipamapi"
  19. remoteipam "github.com/docker/libnetwork/ipams/remote/api"
  20. "github.com/go-check/check"
  21. "github.com/vishvananda/netlink"
  22. )
  23. func (s *DockerSwarmSuite) TestSwarmUpdate(c *check.C) {
  24. d := s.AddDaemon(c, true, true)
  25. getSpec := func() swarm.Spec {
  26. sw := d.GetSwarm(c)
  27. return sw.Spec
  28. }
  29. out, err := d.Cmd("swarm", "update", "--cert-expiry", "30h", "--dispatcher-heartbeat", "11s")
  30. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  31. spec := getSpec()
  32. c.Assert(spec.CAConfig.NodeCertExpiry, checker.Equals, 30*time.Hour)
  33. c.Assert(spec.Dispatcher.HeartbeatPeriod, checker.Equals, 11*time.Second)
  34. // setting anything under 30m for cert-expiry is not allowed
  35. out, err = d.Cmd("swarm", "update", "--cert-expiry", "15m")
  36. c.Assert(err, checker.NotNil)
  37. c.Assert(out, checker.Contains, "minimum certificate expiry time")
  38. spec = getSpec()
  39. c.Assert(spec.CAConfig.NodeCertExpiry, checker.Equals, 30*time.Hour)
  40. }
  41. func (s *DockerSwarmSuite) TestSwarmInit(c *check.C) {
  42. d := s.AddDaemon(c, false, false)
  43. getSpec := func() swarm.Spec {
  44. sw := d.GetSwarm(c)
  45. return sw.Spec
  46. }
  47. out, err := d.Cmd("swarm", "init", "--cert-expiry", "30h", "--dispatcher-heartbeat", "11s")
  48. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  49. spec := getSpec()
  50. c.Assert(spec.CAConfig.NodeCertExpiry, checker.Equals, 30*time.Hour)
  51. c.Assert(spec.Dispatcher.HeartbeatPeriod, checker.Equals, 11*time.Second)
  52. c.Assert(d.Leave(true), checker.IsNil)
  53. time.Sleep(500 * time.Millisecond) // https://github.com/docker/swarmkit/issues/1421
  54. out, err = d.Cmd("swarm", "init")
  55. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  56. spec = getSpec()
  57. c.Assert(spec.CAConfig.NodeCertExpiry, checker.Equals, 90*24*time.Hour)
  58. c.Assert(spec.Dispatcher.HeartbeatPeriod, checker.Equals, 5*time.Second)
  59. }
  60. func (s *DockerSwarmSuite) TestSwarmInitIPv6(c *check.C) {
  61. testRequires(c, IPv6)
  62. d1 := s.AddDaemon(c, false, false)
  63. out, err := d1.Cmd("swarm", "init", "--listen-addr", "::1")
  64. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  65. d2 := s.AddDaemon(c, false, false)
  66. out, err = d2.Cmd("swarm", "join", "::1")
  67. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  68. out, err = d2.Cmd("info")
  69. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  70. c.Assert(out, checker.Contains, "Swarm: active")
  71. }
  72. func (s *DockerSwarmSuite) TestSwarmInitUnspecifiedAdvertiseAddr(c *check.C) {
  73. d := s.AddDaemon(c, false, false)
  74. out, err := d.Cmd("swarm", "init", "--advertise-addr", "0.0.0.0")
  75. c.Assert(err, checker.NotNil)
  76. c.Assert(out, checker.Contains, "advertise address must be a non-zero IP address")
  77. }
  78. func (s *DockerSwarmSuite) TestSwarmIncompatibleDaemon(c *check.C) {
  79. // init swarm mode and stop a daemon
  80. d := s.AddDaemon(c, true, true)
  81. info, err := d.SwarmInfo()
  82. c.Assert(err, checker.IsNil)
  83. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive)
  84. c.Assert(d.Stop(), checker.IsNil)
  85. // start a daemon with --cluster-store and --cluster-advertise
  86. err = d.Start("--cluster-store=consul://consuladdr:consulport/some/path", "--cluster-advertise=1.1.1.1:2375")
  87. c.Assert(err, checker.NotNil)
  88. content, err := d.ReadLogFile()
  89. c.Assert(err, checker.IsNil)
  90. c.Assert(string(content), checker.Contains, "--cluster-store and --cluster-advertise daemon configurations are incompatible with swarm mode")
  91. // start a daemon with --live-restore
  92. err = d.Start("--live-restore")
  93. c.Assert(err, checker.NotNil)
  94. content, err = d.ReadLogFile()
  95. c.Assert(err, checker.IsNil)
  96. c.Assert(string(content), checker.Contains, "--live-restore daemon configuration is incompatible with swarm mode")
  97. // restart for teardown
  98. c.Assert(d.Start(), checker.IsNil)
  99. }
  100. // Test case for #24090
  101. func (s *DockerSwarmSuite) TestSwarmNodeListHostname(c *check.C) {
  102. d := s.AddDaemon(c, true, true)
  103. // The first line should contain "HOSTNAME"
  104. out, err := d.Cmd("node", "ls")
  105. c.Assert(err, checker.IsNil)
  106. c.Assert(strings.Split(out, "\n")[0], checker.Contains, "HOSTNAME")
  107. }
  108. func (s *DockerSwarmSuite) TestSwarmServiceTemplatingHostname(c *check.C) {
  109. d := s.AddDaemon(c, true, true)
  110. out, err := d.Cmd("service", "create", "--name", "test", "--hostname", "{{.Service.Name}}-{{.Task.Slot}}", "busybox", "top")
  111. c.Assert(err, checker.IsNil, check.Commentf(out))
  112. // make sure task has been deployed.
  113. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  114. containers := d.ActiveContainers()
  115. out, err = d.Cmd("inspect", "--type", "container", "--format", "{{.Config.Hostname}}", containers[0])
  116. c.Assert(err, checker.IsNil, check.Commentf(out))
  117. c.Assert(strings.Split(out, "\n")[0], checker.Equals, "test-1", check.Commentf("hostname with templating invalid"))
  118. }
  119. // Test case for #24270
  120. func (s *DockerSwarmSuite) TestSwarmServiceListFilter(c *check.C) {
  121. d := s.AddDaemon(c, true, true)
  122. name1 := "redis-cluster-md5"
  123. name2 := "redis-cluster"
  124. name3 := "other-cluster"
  125. out, err := d.Cmd("service", "create", "--name", name1, "busybox", "top")
  126. c.Assert(err, checker.IsNil)
  127. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  128. out, err = d.Cmd("service", "create", "--name", name2, "busybox", "top")
  129. c.Assert(err, checker.IsNil)
  130. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  131. out, err = d.Cmd("service", "create", "--name", name3, "busybox", "top")
  132. c.Assert(err, checker.IsNil)
  133. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  134. filter1 := "name=redis-cluster-md5"
  135. filter2 := "name=redis-cluster"
  136. // We search checker.Contains with `name+" "` to prevent prefix only.
  137. out, err = d.Cmd("service", "ls", "--filter", filter1)
  138. c.Assert(err, checker.IsNil)
  139. c.Assert(out, checker.Contains, name1+" ")
  140. c.Assert(out, checker.Not(checker.Contains), name2+" ")
  141. c.Assert(out, checker.Not(checker.Contains), name3+" ")
  142. out, err = d.Cmd("service", "ls", "--filter", filter2)
  143. c.Assert(err, checker.IsNil)
  144. c.Assert(out, checker.Contains, name1+" ")
  145. c.Assert(out, checker.Contains, name2+" ")
  146. c.Assert(out, checker.Not(checker.Contains), name3+" ")
  147. out, err = d.Cmd("service", "ls")
  148. c.Assert(err, checker.IsNil)
  149. c.Assert(out, checker.Contains, name1+" ")
  150. c.Assert(out, checker.Contains, name2+" ")
  151. c.Assert(out, checker.Contains, name3+" ")
  152. }
  153. func (s *DockerSwarmSuite) TestSwarmNodeListFilter(c *check.C) {
  154. d := s.AddDaemon(c, true, true)
  155. out, err := d.Cmd("node", "inspect", "--format", "{{ .Description.Hostname }}", "self")
  156. c.Assert(err, checker.IsNil)
  157. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  158. name := strings.TrimSpace(out)
  159. filter := "name=" + name[:4]
  160. out, err = d.Cmd("node", "ls", "--filter", filter)
  161. c.Assert(err, checker.IsNil)
  162. c.Assert(out, checker.Contains, name)
  163. out, err = d.Cmd("node", "ls", "--filter", "name=none")
  164. c.Assert(err, checker.IsNil)
  165. c.Assert(out, checker.Not(checker.Contains), name)
  166. }
  167. func (s *DockerSwarmSuite) TestSwarmNodeTaskListFilter(c *check.C) {
  168. d := s.AddDaemon(c, true, true)
  169. name := "redis-cluster-md5"
  170. out, err := d.Cmd("service", "create", "--name", name, "--replicas=3", "busybox", "top")
  171. c.Assert(err, checker.IsNil)
  172. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  173. // make sure task has been deployed.
  174. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 3)
  175. filter := "name=redis-cluster"
  176. out, err = d.Cmd("node", "ps", "--filter", filter, "self")
  177. c.Assert(err, checker.IsNil)
  178. c.Assert(out, checker.Contains, name+".1")
  179. c.Assert(out, checker.Contains, name+".2")
  180. c.Assert(out, checker.Contains, name+".3")
  181. out, err = d.Cmd("node", "ps", "--filter", "name=none", "self")
  182. c.Assert(err, checker.IsNil)
  183. c.Assert(out, checker.Not(checker.Contains), name+".1")
  184. c.Assert(out, checker.Not(checker.Contains), name+".2")
  185. c.Assert(out, checker.Not(checker.Contains), name+".3")
  186. }
  187. // Test case for #25375
  188. func (s *DockerSwarmSuite) TestSwarmPublishAdd(c *check.C) {
  189. d := s.AddDaemon(c, true, true)
  190. testCases := []struct {
  191. name string
  192. publishAdd []string
  193. ports string
  194. }{
  195. {
  196. name: "simple-syntax",
  197. publishAdd: []string{
  198. "80:80",
  199. "80:80",
  200. "80:80",
  201. "80:20",
  202. },
  203. ports: "[{ tcp 80 80 ingress}]",
  204. },
  205. {
  206. name: "complex-syntax",
  207. publishAdd: []string{
  208. "target=90,published=90,protocol=tcp,mode=ingress",
  209. "target=90,published=90,protocol=tcp,mode=ingress",
  210. "target=90,published=90,protocol=tcp,mode=ingress",
  211. "target=30,published=90,protocol=tcp,mode=ingress",
  212. },
  213. ports: "[{ tcp 90 90 ingress}]",
  214. },
  215. }
  216. for _, tc := range testCases {
  217. out, err := d.Cmd("service", "create", "--name", tc.name, "--label", "x=y", "busybox", "top")
  218. c.Assert(err, checker.IsNil, check.Commentf(out))
  219. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  220. out, err = d.CmdRetryOutOfSequence("service", "update", "--publish-add", tc.publishAdd[0], tc.name)
  221. c.Assert(err, checker.IsNil, check.Commentf(out))
  222. out, err = d.CmdRetryOutOfSequence("service", "update", "--publish-add", tc.publishAdd[1], tc.name)
  223. c.Assert(err, checker.IsNil, check.Commentf(out))
  224. out, err = d.CmdRetryOutOfSequence("service", "update", "--publish-add", tc.publishAdd[2], "--publish-add", tc.publishAdd[3], tc.name)
  225. c.Assert(err, checker.NotNil, check.Commentf(out))
  226. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.EndpointSpec.Ports }}", tc.name)
  227. c.Assert(err, checker.IsNil)
  228. c.Assert(strings.TrimSpace(out), checker.Equals, tc.ports)
  229. }
  230. }
  231. func (s *DockerSwarmSuite) TestSwarmServiceWithGroup(c *check.C) {
  232. d := s.AddDaemon(c, true, true)
  233. name := "top"
  234. out, err := d.Cmd("service", "create", "--name", name, "--user", "root:root", "--group", "wheel", "--group", "audio", "--group", "staff", "--group", "777", "busybox", "top")
  235. c.Assert(err, checker.IsNil)
  236. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  237. // make sure task has been deployed.
  238. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  239. out, err = d.Cmd("ps", "-q")
  240. c.Assert(err, checker.IsNil)
  241. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  242. container := strings.TrimSpace(out)
  243. out, err = d.Cmd("exec", container, "id")
  244. c.Assert(err, checker.IsNil)
  245. c.Assert(strings.TrimSpace(out), checker.Equals, "uid=0(root) gid=0(root) groups=10(wheel),29(audio),50(staff),777")
  246. }
  247. func (s *DockerSwarmSuite) TestSwarmContainerAutoStart(c *check.C) {
  248. d := s.AddDaemon(c, true, true)
  249. out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo")
  250. c.Assert(err, checker.IsNil)
  251. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  252. out, err = d.Cmd("run", "-id", "--restart=always", "--net=foo", "--name=test", "busybox", "top")
  253. c.Assert(err, checker.IsNil, check.Commentf(out))
  254. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  255. out, err = d.Cmd("ps", "-q")
  256. c.Assert(err, checker.IsNil, check.Commentf(out))
  257. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  258. d.Restart()
  259. out, err = d.Cmd("ps", "-q")
  260. c.Assert(err, checker.IsNil, check.Commentf(out))
  261. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  262. }
  263. func (s *DockerSwarmSuite) TestSwarmContainerEndpointOptions(c *check.C) {
  264. d := s.AddDaemon(c, true, true)
  265. out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo")
  266. c.Assert(err, checker.IsNil, check.Commentf(out))
  267. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  268. _, err = d.Cmd("run", "-d", "--net=foo", "--name=first", "--net-alias=first-alias", "busybox", "top")
  269. c.Assert(err, checker.IsNil, check.Commentf(out))
  270. _, err = d.Cmd("run", "-d", "--net=foo", "--name=second", "busybox", "top")
  271. c.Assert(err, checker.IsNil, check.Commentf(out))
  272. // ping first container and its alias
  273. _, err = d.Cmd("exec", "second", "ping", "-c", "1", "first")
  274. c.Assert(err, check.IsNil, check.Commentf(out))
  275. _, err = d.Cmd("exec", "second", "ping", "-c", "1", "first-alias")
  276. c.Assert(err, check.IsNil, check.Commentf(out))
  277. }
  278. func (s *DockerSwarmSuite) TestSwarmContainerAttachByNetworkId(c *check.C) {
  279. d := s.AddDaemon(c, true, true)
  280. out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "testnet")
  281. c.Assert(err, checker.IsNil)
  282. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  283. networkID := strings.TrimSpace(out)
  284. out, err = d.Cmd("run", "-d", "--net", networkID, "busybox", "top")
  285. c.Assert(err, checker.IsNil)
  286. cID := strings.TrimSpace(out)
  287. d.WaitRun(cID)
  288. _, err = d.Cmd("rm", "-f", cID)
  289. c.Assert(err, checker.IsNil)
  290. out, err = d.Cmd("network", "rm", "testnet")
  291. c.Assert(err, checker.IsNil)
  292. checkNetwork := func(*check.C) (interface{}, check.CommentInterface) {
  293. out, err := d.Cmd("network", "ls")
  294. c.Assert(err, checker.IsNil)
  295. return out, nil
  296. }
  297. waitAndAssert(c, 3*time.Second, checkNetwork, checker.Not(checker.Contains), "testnet")
  298. }
  299. func (s *DockerSwarmSuite) TestOverlayAttachable(c *check.C) {
  300. d := s.AddDaemon(c, true, true)
  301. out, err := d.Cmd("network", "create", "-d", "overlay", "--attachable", "ovnet")
  302. c.Assert(err, checker.IsNil, check.Commentf(out))
  303. // validate attachable
  304. out, err = d.Cmd("network", "inspect", "--format", "{{json .Attachable}}", "ovnet")
  305. c.Assert(err, checker.IsNil, check.Commentf(out))
  306. c.Assert(strings.TrimSpace(out), checker.Equals, "true")
  307. // validate containers can attache to this overlay network
  308. out, err = d.Cmd("run", "-d", "--network", "ovnet", "--name", "c1", "busybox", "top")
  309. c.Assert(err, checker.IsNil, check.Commentf(out))
  310. // redo validation, there was a bug that the value of attachable changes after
  311. // containers attach to the network
  312. out, err = d.Cmd("network", "inspect", "--format", "{{json .Attachable}}", "ovnet")
  313. c.Assert(err, checker.IsNil, check.Commentf(out))
  314. c.Assert(strings.TrimSpace(out), checker.Equals, "true")
  315. }
  316. func (s *DockerSwarmSuite) TestSwarmRemoveInternalNetwork(c *check.C) {
  317. d := s.AddDaemon(c, true, true)
  318. name := "ingress"
  319. out, err := d.Cmd("network", "rm", name)
  320. c.Assert(err, checker.NotNil)
  321. c.Assert(strings.TrimSpace(out), checker.Contains, name)
  322. c.Assert(strings.TrimSpace(out), checker.Contains, "is a pre-defined network and cannot be removed")
  323. }
  324. // Test case for #24108, also the case from:
  325. // https://github.com/docker/docker/pull/24620#issuecomment-233715656
  326. func (s *DockerSwarmSuite) TestSwarmTaskListFilter(c *check.C) {
  327. d := s.AddDaemon(c, true, true)
  328. name := "redis-cluster-md5"
  329. out, err := d.Cmd("service", "create", "--name", name, "--replicas=3", "busybox", "top")
  330. c.Assert(err, checker.IsNil)
  331. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  332. filter := "name=redis-cluster"
  333. checkNumTasks := func(*check.C) (interface{}, check.CommentInterface) {
  334. out, err := d.Cmd("service", "ps", "--filter", filter, name)
  335. c.Assert(err, checker.IsNil)
  336. return len(strings.Split(out, "\n")) - 2, nil // includes header and nl in last line
  337. }
  338. // wait until all tasks have been created
  339. waitAndAssert(c, defaultReconciliationTimeout, checkNumTasks, checker.Equals, 3)
  340. out, err = d.Cmd("service", "ps", "--filter", filter, name)
  341. c.Assert(err, checker.IsNil)
  342. c.Assert(out, checker.Contains, name+".1")
  343. c.Assert(out, checker.Contains, name+".2")
  344. c.Assert(out, checker.Contains, name+".3")
  345. out, err = d.Cmd("service", "ps", "--filter", "name="+name+".1", name)
  346. c.Assert(err, checker.IsNil)
  347. c.Assert(out, checker.Contains, name+".1")
  348. c.Assert(out, checker.Not(checker.Contains), name+".2")
  349. c.Assert(out, checker.Not(checker.Contains), name+".3")
  350. out, err = d.Cmd("service", "ps", "--filter", "name=none", name)
  351. c.Assert(err, checker.IsNil)
  352. c.Assert(out, checker.Not(checker.Contains), name+".1")
  353. c.Assert(out, checker.Not(checker.Contains), name+".2")
  354. c.Assert(out, checker.Not(checker.Contains), name+".3")
  355. name = "redis-cluster-sha1"
  356. out, err = d.Cmd("service", "create", "--name", name, "--mode=global", "busybox", "top")
  357. c.Assert(err, checker.IsNil)
  358. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  359. waitAndAssert(c, defaultReconciliationTimeout, checkNumTasks, checker.Equals, 1)
  360. filter = "name=redis-cluster"
  361. out, err = d.Cmd("service", "ps", "--filter", filter, name)
  362. c.Assert(err, checker.IsNil)
  363. c.Assert(out, checker.Contains, name)
  364. out, err = d.Cmd("service", "ps", "--filter", "name="+name, name)
  365. c.Assert(err, checker.IsNil)
  366. c.Assert(out, checker.Contains, name)
  367. out, err = d.Cmd("service", "ps", "--filter", "name=none", name)
  368. c.Assert(err, checker.IsNil)
  369. c.Assert(out, checker.Not(checker.Contains), name)
  370. }
  371. func (s *DockerSwarmSuite) TestPsListContainersFilterIsTask(c *check.C) {
  372. d := s.AddDaemon(c, true, true)
  373. // Create a bare container
  374. out, err := d.Cmd("run", "-d", "--name=bare-container", "busybox", "top")
  375. c.Assert(err, checker.IsNil)
  376. bareID := strings.TrimSpace(out)[:12]
  377. // Create a service
  378. name := "busybox-top"
  379. out, err = d.Cmd("service", "create", "--name", name, "busybox", "top")
  380. c.Assert(err, checker.IsNil)
  381. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  382. // make sure task has been deployed.
  383. waitAndAssert(c, defaultReconciliationTimeout, d.CheckServiceRunningTasks(name), checker.Equals, 1)
  384. // Filter non-tasks
  385. out, err = d.Cmd("ps", "-a", "-q", "--filter=is-task=false")
  386. c.Assert(err, checker.IsNil)
  387. psOut := strings.TrimSpace(out)
  388. c.Assert(psOut, checker.Equals, bareID, check.Commentf("Expected id %s, got %s for is-task label, output %q", bareID, psOut, out))
  389. // Filter tasks
  390. out, err = d.Cmd("ps", "-a", "-q", "--filter=is-task=true")
  391. c.Assert(err, checker.IsNil)
  392. lines := strings.Split(strings.Trim(out, "\n "), "\n")
  393. c.Assert(lines, checker.HasLen, 1)
  394. 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))
  395. }
  396. const globalNetworkPlugin = "global-network-plugin"
  397. const globalIPAMPlugin = "global-ipam-plugin"
  398. func (s *DockerSwarmSuite) SetUpSuite(c *check.C) {
  399. mux := http.NewServeMux()
  400. s.server = httptest.NewServer(mux)
  401. c.Assert(s.server, check.NotNil, check.Commentf("Failed to start an HTTP Server"))
  402. setupRemoteGlobalNetworkPlugin(c, mux, s.server.URL, globalNetworkPlugin, globalIPAMPlugin)
  403. }
  404. func setupRemoteGlobalNetworkPlugin(c *check.C, mux *http.ServeMux, url, netDrv, ipamDrv string) {
  405. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  406. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  407. fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
  408. })
  409. // Network driver implementation
  410. mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  411. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  412. fmt.Fprintf(w, `{"Scope":"global"}`)
  413. })
  414. mux.HandleFunc(fmt.Sprintf("/%s.AllocateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  415. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  416. if err != nil {
  417. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  418. return
  419. }
  420. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  421. fmt.Fprintf(w, "null")
  422. })
  423. mux.HandleFunc(fmt.Sprintf("/%s.FreeNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  424. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  425. fmt.Fprintf(w, "null")
  426. })
  427. mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  428. err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
  429. if err != nil {
  430. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  431. return
  432. }
  433. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  434. fmt.Fprintf(w, "null")
  435. })
  436. mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  437. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  438. fmt.Fprintf(w, "null")
  439. })
  440. mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  441. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  442. fmt.Fprintf(w, `{"Interface":{"MacAddress":"a0:b1:c2:d3:e4:f5"}}`)
  443. })
  444. mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  445. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  446. veth := &netlink.Veth{
  447. LinkAttrs: netlink.LinkAttrs{Name: "randomIfName", TxQLen: 0}, PeerName: "cnt0"}
  448. if err := netlink.LinkAdd(veth); err != nil {
  449. fmt.Fprintf(w, `{"Error":"failed to add veth pair: `+err.Error()+`"}`)
  450. } else {
  451. fmt.Fprintf(w, `{"InterfaceName":{ "SrcName":"cnt0", "DstPrefix":"veth"}}`)
  452. }
  453. })
  454. mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  455. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  456. fmt.Fprintf(w, "null")
  457. })
  458. mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  459. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  460. if link, err := netlink.LinkByName("cnt0"); err == nil {
  461. netlink.LinkDel(link)
  462. }
  463. fmt.Fprintf(w, "null")
  464. })
  465. // IPAM Driver implementation
  466. var (
  467. poolRequest remoteipam.RequestPoolRequest
  468. poolReleaseReq remoteipam.ReleasePoolRequest
  469. addressRequest remoteipam.RequestAddressRequest
  470. addressReleaseReq remoteipam.ReleaseAddressRequest
  471. lAS = "localAS"
  472. gAS = "globalAS"
  473. pool = "172.28.0.0/16"
  474. poolID = lAS + "/" + pool
  475. gw = "172.28.255.254/16"
  476. )
  477. mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  478. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  479. fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
  480. })
  481. mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  482. err := json.NewDecoder(r.Body).Decode(&poolRequest)
  483. if err != nil {
  484. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  485. return
  486. }
  487. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  488. if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
  489. fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
  490. } else if poolRequest.Pool != "" && poolRequest.Pool != pool {
  491. fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
  492. } else {
  493. fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
  494. }
  495. })
  496. mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  497. err := json.NewDecoder(r.Body).Decode(&addressRequest)
  498. if err != nil {
  499. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  500. return
  501. }
  502. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  503. // make sure libnetwork is now querying on the expected pool id
  504. if addressRequest.PoolID != poolID {
  505. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  506. } else if addressRequest.Address != "" {
  507. fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
  508. } else {
  509. fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
  510. }
  511. })
  512. mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  513. err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
  514. if err != nil {
  515. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  516. return
  517. }
  518. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  519. // make sure libnetwork is now asking to release the expected address from the expected poolid
  520. if addressRequest.PoolID != poolID {
  521. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  522. } else if addressReleaseReq.Address != gw {
  523. fmt.Fprintf(w, `{"Error":"unknown address"}`)
  524. } else {
  525. fmt.Fprintf(w, "null")
  526. }
  527. })
  528. mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
  529. err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
  530. if err != nil {
  531. http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
  532. return
  533. }
  534. w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
  535. // make sure libnetwork is now asking to release the expected poolid
  536. if addressRequest.PoolID != poolID {
  537. fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
  538. } else {
  539. fmt.Fprintf(w, "null")
  540. }
  541. })
  542. err := os.MkdirAll("/etc/docker/plugins", 0755)
  543. c.Assert(err, checker.IsNil)
  544. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", netDrv)
  545. err = ioutil.WriteFile(fileName, []byte(url), 0644)
  546. c.Assert(err, checker.IsNil)
  547. ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", ipamDrv)
  548. err = ioutil.WriteFile(ipamFileName, []byte(url), 0644)
  549. c.Assert(err, checker.IsNil)
  550. }
  551. func (s *DockerSwarmSuite) TestSwarmNetworkPlugin(c *check.C) {
  552. d := s.AddDaemon(c, true, true)
  553. out, err := d.Cmd("network", "create", "-d", globalNetworkPlugin, "foo")
  554. c.Assert(err, checker.IsNil)
  555. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  556. name := "top"
  557. out, err = d.Cmd("service", "create", "--name", name, "--network", "foo", "busybox", "top")
  558. c.Assert(err, checker.IsNil)
  559. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  560. out, err = d.Cmd("service", "inspect", "--format", "{{range .Spec.Networks}}{{.Target}}{{end}}", name)
  561. c.Assert(err, checker.IsNil)
  562. c.Assert(strings.TrimSpace(out), checker.Equals, "foo")
  563. }
  564. // Test case for #24712
  565. func (s *DockerSwarmSuite) TestSwarmServiceEnvFile(c *check.C) {
  566. d := s.AddDaemon(c, true, true)
  567. path := filepath.Join(d.Folder, "env.txt")
  568. err := ioutil.WriteFile(path, []byte("VAR1=A\nVAR2=A\n"), 0644)
  569. c.Assert(err, checker.IsNil)
  570. name := "worker"
  571. out, err := d.Cmd("service", "create", "--env-file", path, "--env", "VAR1=B", "--env", "VAR1=C", "--env", "VAR2=", "--env", "VAR2", "--name", name, "busybox", "top")
  572. c.Assert(err, checker.IsNil)
  573. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  574. // The complete env is [VAR1=A VAR2=A VAR1=B VAR1=C VAR2= VAR2] and duplicates will be removed => [VAR1=C VAR2]
  575. out, err = d.Cmd("inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.Env }}", name)
  576. c.Assert(err, checker.IsNil)
  577. c.Assert(out, checker.Contains, "[VAR1=C VAR2]")
  578. }
  579. func (s *DockerSwarmSuite) TestSwarmServiceTTY(c *check.C) {
  580. d := s.AddDaemon(c, true, true)
  581. name := "top"
  582. ttyCheck := "if [ -t 0 ]; then echo TTY > /status && top; else echo none > /status && top; fi"
  583. // Without --tty
  584. expectedOutput := "none"
  585. out, err := d.Cmd("service", "create", "--name", name, "busybox", "sh", "-c", ttyCheck)
  586. c.Assert(err, checker.IsNil)
  587. // Make sure task has been deployed.
  588. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  589. // We need to get the container id.
  590. out, err = d.Cmd("ps", "-a", "-q", "--no-trunc")
  591. c.Assert(err, checker.IsNil)
  592. id := strings.TrimSpace(out)
  593. out, err = d.Cmd("exec", id, "cat", "/status")
  594. c.Assert(err, checker.IsNil)
  595. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  596. // Remove service
  597. out, err = d.Cmd("service", "rm", name)
  598. c.Assert(err, checker.IsNil)
  599. // Make sure container has been destroyed.
  600. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 0)
  601. // With --tty
  602. expectedOutput = "TTY"
  603. out, err = d.Cmd("service", "create", "--name", name, "--tty", "busybox", "sh", "-c", ttyCheck)
  604. c.Assert(err, checker.IsNil)
  605. // Make sure task has been deployed.
  606. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  607. // We need to get the container id.
  608. out, err = d.Cmd("ps", "-a", "-q", "--no-trunc")
  609. c.Assert(err, checker.IsNil)
  610. id = strings.TrimSpace(out)
  611. out, err = d.Cmd("exec", id, "cat", "/status")
  612. c.Assert(err, checker.IsNil)
  613. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  614. }
  615. func (s *DockerSwarmSuite) TestSwarmServiceTTYUpdate(c *check.C) {
  616. d := s.AddDaemon(c, true, true)
  617. // Create a service
  618. name := "top"
  619. _, err := d.Cmd("service", "create", "--name", name, "busybox", "top")
  620. c.Assert(err, checker.IsNil)
  621. // Make sure task has been deployed.
  622. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  623. out, err := d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.TTY }}", name)
  624. c.Assert(err, checker.IsNil)
  625. c.Assert(strings.TrimSpace(out), checker.Equals, "false")
  626. _, err = d.Cmd("service", "update", "--tty", name)
  627. c.Assert(err, checker.IsNil)
  628. out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.TTY }}", name)
  629. c.Assert(err, checker.IsNil)
  630. c.Assert(strings.TrimSpace(out), checker.Equals, "true")
  631. }
  632. func (s *DockerSwarmSuite) TestDNSConfig(c *check.C) {
  633. d := s.AddDaemon(c, true, true)
  634. // Create a service
  635. name := "top"
  636. _, err := d.Cmd("service", "create", "--name", name, "--dns=1.2.3.4", "--dns-search=example.com", "--dns-option=timeout:3", "busybox", "top")
  637. c.Assert(err, checker.IsNil)
  638. // Make sure task has been deployed.
  639. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  640. // We need to get the container id.
  641. out, err := d.Cmd("ps", "-a", "-q", "--no-trunc")
  642. c.Assert(err, checker.IsNil)
  643. id := strings.TrimSpace(out)
  644. // Compare against expected output.
  645. expectedOutput1 := "nameserver 1.2.3.4"
  646. expectedOutput2 := "search example.com"
  647. expectedOutput3 := "options timeout:3"
  648. out, err = d.Cmd("exec", id, "cat", "/etc/resolv.conf")
  649. c.Assert(err, checker.IsNil)
  650. c.Assert(out, checker.Contains, expectedOutput1, check.Commentf("Expected '%s', but got %q", expectedOutput1, out))
  651. c.Assert(out, checker.Contains, expectedOutput2, check.Commentf("Expected '%s', but got %q", expectedOutput2, out))
  652. c.Assert(out, checker.Contains, expectedOutput3, check.Commentf("Expected '%s', but got %q", expectedOutput3, out))
  653. }
  654. func (s *DockerSwarmSuite) TestDNSConfigUpdate(c *check.C) {
  655. d := s.AddDaemon(c, true, true)
  656. // Create a service
  657. name := "top"
  658. _, err := d.Cmd("service", "create", "--name", name, "busybox", "top")
  659. c.Assert(err, checker.IsNil)
  660. // Make sure task has been deployed.
  661. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  662. _, err = d.Cmd("service", "update", "--dns-add=1.2.3.4", "--dns-search-add=example.com", "--dns-option-add=timeout:3", name)
  663. c.Assert(err, checker.IsNil)
  664. out, err := d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.DNSConfig }}", name)
  665. c.Assert(err, checker.IsNil)
  666. c.Assert(strings.TrimSpace(out), checker.Equals, "{[1.2.3.4] [example.com] [timeout:3]}")
  667. }
  668. func getNodeStatus(c *check.C, d *daemon.Swarm) swarm.LocalNodeState {
  669. info, err := d.SwarmInfo()
  670. c.Assert(err, checker.IsNil)
  671. return info.LocalNodeState
  672. }
  673. func checkSwarmLockedToUnlocked(c *check.C, d *daemon.Swarm, unlockKey string) {
  674. c.Assert(d.Restart(), checker.IsNil)
  675. status := getNodeStatus(c, d)
  676. if status == swarm.LocalNodeStateLocked {
  677. // it must not have updated to be unlocked in time - unlock, wait 3 seconds, and try again
  678. cmd := d.Command("swarm", "unlock")
  679. cmd.Stdin = bytes.NewBufferString(unlockKey)
  680. out, err := cmd.CombinedOutput()
  681. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  682. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  683. time.Sleep(3 * time.Second)
  684. c.Assert(d.Restart(), checker.IsNil)
  685. }
  686. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  687. }
  688. func checkSwarmUnlockedToLocked(c *check.C, d *daemon.Swarm) {
  689. c.Assert(d.Restart(), checker.IsNil)
  690. status := getNodeStatus(c, d)
  691. if status == swarm.LocalNodeStateActive {
  692. // it must not have updated to be unlocked in time - wait 3 seconds, and try again
  693. time.Sleep(3 * time.Second)
  694. c.Assert(d.Restart(), checker.IsNil)
  695. }
  696. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  697. }
  698. func (s *DockerSwarmSuite) TestSwarmInitLocked(c *check.C) {
  699. d := s.AddDaemon(c, false, false)
  700. outs, err := d.Cmd("swarm", "init", "--autolock")
  701. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  702. c.Assert(outs, checker.Contains, "docker swarm unlock")
  703. var unlockKey string
  704. for _, line := range strings.Split(outs, "\n") {
  705. if strings.Contains(line, "SWMKEY") {
  706. unlockKey = strings.TrimSpace(line)
  707. break
  708. }
  709. }
  710. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  711. outs, err = d.Cmd("swarm", "unlock-key", "-q")
  712. c.Assert(outs, checker.Equals, unlockKey+"\n")
  713. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  714. // It starts off locked
  715. c.Assert(d.Restart(), checker.IsNil)
  716. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  717. cmd := d.Command("swarm", "unlock")
  718. cmd.Stdin = bytes.NewBufferString("wrong-secret-key")
  719. out, err := cmd.CombinedOutput()
  720. c.Assert(err, checker.NotNil, check.Commentf("out: %v", string(out)))
  721. c.Assert(string(out), checker.Contains, "invalid key")
  722. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  723. cmd = d.Command("swarm", "unlock")
  724. cmd.Stdin = bytes.NewBufferString(unlockKey)
  725. out, err = cmd.CombinedOutput()
  726. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  727. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  728. outs, err = d.Cmd("node", "ls")
  729. c.Assert(err, checker.IsNil)
  730. c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked")
  731. outs, err = d.Cmd("swarm", "update", "--autolock=false")
  732. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  733. checkSwarmLockedToUnlocked(c, d, unlockKey)
  734. outs, err = d.Cmd("node", "ls")
  735. c.Assert(err, checker.IsNil)
  736. c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked")
  737. }
  738. func (s *DockerSwarmSuite) TestSwarmLeaveLocked(c *check.C) {
  739. d := s.AddDaemon(c, false, false)
  740. outs, err := d.Cmd("swarm", "init", "--autolock")
  741. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  742. // It starts off locked
  743. c.Assert(d.Restart("--swarm-default-advertise-addr=lo"), checker.IsNil)
  744. info, err := d.SwarmInfo()
  745. c.Assert(err, checker.IsNil)
  746. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateLocked)
  747. outs, _ = d.Cmd("node", "ls")
  748. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  749. // `docker swarm leave` a locked swarm without --force will return an error
  750. outs, _ = d.Cmd("swarm", "leave")
  751. c.Assert(outs, checker.Contains, "Swarm is encrypted and locked.")
  752. // It is OK for user to leave a locked swarm with --force
  753. outs, err = d.Cmd("swarm", "leave", "--force")
  754. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  755. info, err = d.SwarmInfo()
  756. c.Assert(err, checker.IsNil)
  757. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive)
  758. outs, err = d.Cmd("swarm", "init")
  759. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  760. info, err = d.SwarmInfo()
  761. c.Assert(err, checker.IsNil)
  762. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive)
  763. }
  764. func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) {
  765. d1 := s.AddDaemon(c, true, true)
  766. d2 := s.AddDaemon(c, true, true)
  767. d3 := s.AddDaemon(c, true, true)
  768. // they start off unlocked
  769. c.Assert(d2.Restart(), checker.IsNil)
  770. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
  771. // stop this one so it does not get autolock info
  772. c.Assert(d2.Stop(), checker.IsNil)
  773. // enable autolock
  774. outs, err := d1.Cmd("swarm", "update", "--autolock")
  775. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  776. c.Assert(outs, checker.Contains, "docker swarm unlock")
  777. var unlockKey string
  778. for _, line := range strings.Split(outs, "\n") {
  779. if strings.Contains(line, "SWMKEY") {
  780. unlockKey = strings.TrimSpace(line)
  781. break
  782. }
  783. }
  784. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  785. outs, err = d1.Cmd("swarm", "unlock-key", "-q")
  786. c.Assert(outs, checker.Equals, unlockKey+"\n")
  787. // The ones that got the cluster update should be set to locked
  788. for _, d := range []*daemon.Swarm{d1, d3} {
  789. checkSwarmUnlockedToLocked(c, d)
  790. cmd := d.Command("swarm", "unlock")
  791. cmd.Stdin = bytes.NewBufferString(unlockKey)
  792. out, err := cmd.CombinedOutput()
  793. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  794. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  795. }
  796. // d2 never got the cluster update, so it is still set to unlocked
  797. c.Assert(d2.Start(), checker.IsNil)
  798. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
  799. // d2 is now set to lock
  800. checkSwarmUnlockedToLocked(c, d2)
  801. // leave it locked, and set the cluster to no longer autolock
  802. outs, err = d1.Cmd("swarm", "update", "--autolock=false")
  803. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  804. // the ones that got the update are now set to unlocked
  805. for _, d := range []*daemon.Swarm{d1, d3} {
  806. checkSwarmLockedToUnlocked(c, d, unlockKey)
  807. }
  808. // d2 still locked
  809. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateLocked)
  810. // unlock it
  811. cmd := d2.Command("swarm", "unlock")
  812. cmd.Stdin = bytes.NewBufferString(unlockKey)
  813. out, err := cmd.CombinedOutput()
  814. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  815. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
  816. // once it's caught up, d2 is set to not be locked
  817. checkSwarmLockedToUnlocked(c, d2, unlockKey)
  818. // managers who join now are never set to locked in the first place
  819. d4 := s.AddDaemon(c, true, true)
  820. c.Assert(d4.Restart(), checker.IsNil)
  821. c.Assert(getNodeStatus(c, d4), checker.Equals, swarm.LocalNodeStateActive)
  822. }
  823. func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) {
  824. d1 := s.AddDaemon(c, true, true)
  825. // enable autolock
  826. outs, err := d1.Cmd("swarm", "update", "--autolock")
  827. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  828. c.Assert(outs, checker.Contains, "docker swarm unlock")
  829. var unlockKey string
  830. for _, line := range strings.Split(outs, "\n") {
  831. if strings.Contains(line, "SWMKEY") {
  832. unlockKey = strings.TrimSpace(line)
  833. break
  834. }
  835. }
  836. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  837. outs, err = d1.Cmd("swarm", "unlock-key", "-q")
  838. c.Assert(outs, checker.Equals, unlockKey+"\n")
  839. // joined workers start off unlocked
  840. d2 := s.AddDaemon(c, true, false)
  841. c.Assert(d2.Restart(), checker.IsNil)
  842. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
  843. // promote worker
  844. outs, err = d1.Cmd("node", "promote", d2.Info.NodeID)
  845. c.Assert(err, checker.IsNil)
  846. c.Assert(outs, checker.Contains, "promoted to a manager in the swarm")
  847. // join new manager node
  848. d3 := s.AddDaemon(c, true, true)
  849. // both new nodes are locked
  850. for _, d := range []*daemon.Swarm{d2, d3} {
  851. checkSwarmUnlockedToLocked(c, d)
  852. cmd := d.Command("swarm", "unlock")
  853. cmd.Stdin = bytes.NewBufferString(unlockKey)
  854. out, err := cmd.CombinedOutput()
  855. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  856. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  857. }
  858. // get d3's cert
  859. d3cert, err := ioutil.ReadFile(filepath.Join(d3.Folder, "root", "swarm", "certificates", "swarm-node.crt"))
  860. c.Assert(err, checker.IsNil)
  861. // demote manager back to worker - workers are not locked
  862. outs, err = d1.Cmd("node", "demote", d3.Info.NodeID)
  863. c.Assert(err, checker.IsNil)
  864. c.Assert(outs, checker.Contains, "demoted in the swarm")
  865. // Wait for it to actually be demoted, for the key and cert to be replaced.
  866. // Then restart and assert that the node is not locked. If we don't wait for the cert
  867. // to be replaced, then the node still has the manager TLS key which is still locked
  868. // (because we never want a manager TLS key to be on disk unencrypted if the cluster
  869. // is set to autolock)
  870. waitAndAssert(c, defaultReconciliationTimeout, d3.CheckControlAvailable, checker.False)
  871. waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) {
  872. cert, err := ioutil.ReadFile(filepath.Join(d3.Folder, "root", "swarm", "certificates", "swarm-node.crt"))
  873. if err != nil {
  874. return "", check.Commentf("error: %v", err)
  875. }
  876. return string(cert), check.Commentf("cert: %v", string(cert))
  877. }, checker.Not(checker.Equals), string(d3cert))
  878. // by now, it should *never* be locked on restart
  879. c.Assert(d3.Restart(), checker.IsNil)
  880. c.Assert(getNodeStatus(c, d3), checker.Equals, swarm.LocalNodeStateActive)
  881. }
  882. func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *check.C) {
  883. d := s.AddDaemon(c, true, true)
  884. outs, err := d.Cmd("swarm", "update", "--autolock")
  885. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  886. c.Assert(outs, checker.Contains, "docker swarm unlock")
  887. var unlockKey string
  888. for _, line := range strings.Split(outs, "\n") {
  889. if strings.Contains(line, "SWMKEY") {
  890. unlockKey = strings.TrimSpace(line)
  891. break
  892. }
  893. }
  894. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  895. outs, err = d.Cmd("swarm", "unlock-key", "-q")
  896. c.Assert(outs, checker.Equals, unlockKey+"\n")
  897. // Rotate multiple times
  898. for i := 0; i != 3; i++ {
  899. outs, err = d.Cmd("swarm", "unlock-key", "-q", "--rotate")
  900. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  901. // Strip \n
  902. newUnlockKey := outs[:len(outs)-1]
  903. c.Assert(newUnlockKey, checker.Not(checker.Equals), "")
  904. c.Assert(newUnlockKey, checker.Not(checker.Equals), unlockKey)
  905. c.Assert(d.Restart(), checker.IsNil)
  906. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  907. outs, _ = d.Cmd("node", "ls")
  908. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  909. cmd := d.Command("swarm", "unlock")
  910. cmd.Stdin = bytes.NewBufferString(unlockKey)
  911. out, err := cmd.CombinedOutput()
  912. if err == nil {
  913. // On occasion, the daemon may not have finished
  914. // rotating the KEK before restarting. The test is
  915. // intentionally written to explore this behavior.
  916. // When this happens, unlocking with the old key will
  917. // succeed. If we wait for the rotation to happen and
  918. // restart again, the new key should be required this
  919. // time.
  920. time.Sleep(3 * time.Second)
  921. c.Assert(d.Restart(), checker.IsNil)
  922. cmd = d.Command("swarm", "unlock")
  923. cmd.Stdin = bytes.NewBufferString(unlockKey)
  924. out, err = cmd.CombinedOutput()
  925. }
  926. c.Assert(err, checker.NotNil, check.Commentf("out: %v", string(out)))
  927. c.Assert(string(out), checker.Contains, "invalid key")
  928. outs, _ = d.Cmd("node", "ls")
  929. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  930. cmd = d.Command("swarm", "unlock")
  931. cmd.Stdin = bytes.NewBufferString(newUnlockKey)
  932. out, err = cmd.CombinedOutput()
  933. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  934. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  935. outs, err = d.Cmd("node", "ls")
  936. c.Assert(err, checker.IsNil)
  937. c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked")
  938. unlockKey = newUnlockKey
  939. }
  940. }
  941. // This differs from `TestSwarmRotateUnlockKey` because that one rotates a single node, which is the leader.
  942. // This one keeps the leader up, and asserts that other manager nodes in the cluster also have their unlock
  943. // key rotated.
  944. func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *check.C) {
  945. d1 := s.AddDaemon(c, true, true) // leader - don't restart this one, we don't want leader election delays
  946. d2 := s.AddDaemon(c, true, true)
  947. d3 := s.AddDaemon(c, true, true)
  948. outs, err := d1.Cmd("swarm", "update", "--autolock")
  949. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  950. c.Assert(outs, checker.Contains, "docker swarm unlock")
  951. var unlockKey string
  952. for _, line := range strings.Split(outs, "\n") {
  953. if strings.Contains(line, "SWMKEY") {
  954. unlockKey = strings.TrimSpace(line)
  955. break
  956. }
  957. }
  958. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  959. outs, err = d1.Cmd("swarm", "unlock-key", "-q")
  960. c.Assert(outs, checker.Equals, unlockKey+"\n")
  961. // Rotate multiple times
  962. for i := 0; i != 3; i++ {
  963. outs, err = d1.Cmd("swarm", "unlock-key", "-q", "--rotate")
  964. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  965. // Strip \n
  966. newUnlockKey := outs[:len(outs)-1]
  967. c.Assert(newUnlockKey, checker.Not(checker.Equals), "")
  968. c.Assert(newUnlockKey, checker.Not(checker.Equals), unlockKey)
  969. c.Assert(d2.Restart(), checker.IsNil)
  970. c.Assert(d3.Restart(), checker.IsNil)
  971. for _, d := range []*daemon.Swarm{d2, d3} {
  972. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  973. outs, _ := d.Cmd("node", "ls")
  974. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  975. cmd := d.Command("swarm", "unlock")
  976. cmd.Stdin = bytes.NewBufferString(unlockKey)
  977. out, err := cmd.CombinedOutput()
  978. if err == nil {
  979. // On occasion, the daemon may not have finished
  980. // rotating the KEK before restarting. The test is
  981. // intentionally written to explore this behavior.
  982. // When this happens, unlocking with the old key will
  983. // succeed. If we wait for the rotation to happen and
  984. // restart again, the new key should be required this
  985. // time.
  986. time.Sleep(3 * time.Second)
  987. c.Assert(d.Restart(), checker.IsNil)
  988. cmd = d.Command("swarm", "unlock")
  989. cmd.Stdin = bytes.NewBufferString(unlockKey)
  990. out, err = cmd.CombinedOutput()
  991. }
  992. c.Assert(err, checker.NotNil, check.Commentf("out: %v", string(out)))
  993. c.Assert(string(out), checker.Contains, "invalid key")
  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(newUnlockKey)
  998. out, err = cmd.CombinedOutput()
  999. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  1000. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  1001. outs, err = d.Cmd("node", "ls")
  1002. c.Assert(err, checker.IsNil)
  1003. c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked")
  1004. }
  1005. unlockKey = newUnlockKey
  1006. }
  1007. }
  1008. func (s *DockerSwarmSuite) TestSwarmAlternateLockUnlock(c *check.C) {
  1009. d := s.AddDaemon(c, true, true)
  1010. var unlockKey string
  1011. for i := 0; i < 2; i++ {
  1012. // set to lock
  1013. outs, err := d.Cmd("swarm", "update", "--autolock")
  1014. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  1015. c.Assert(outs, checker.Contains, "docker swarm unlock")
  1016. for _, line := range strings.Split(outs, "\n") {
  1017. if strings.Contains(line, "SWMKEY") {
  1018. unlockKey = strings.TrimSpace(line)
  1019. break
  1020. }
  1021. }
  1022. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  1023. checkSwarmUnlockedToLocked(c, d)
  1024. cmd := d.Command("swarm", "unlock")
  1025. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1026. out, err := cmd.CombinedOutput()
  1027. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  1028. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  1029. outs, err = d.Cmd("swarm", "update", "--autolock=false")
  1030. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  1031. checkSwarmLockedToUnlocked(c, d, unlockKey)
  1032. }
  1033. }
  1034. func (s *DockerSwarmSuite) TestExtraHosts(c *check.C) {
  1035. d := s.AddDaemon(c, true, true)
  1036. // Create a service
  1037. name := "top"
  1038. _, err := d.Cmd("service", "create", "--name", name, "--host=example.com:1.2.3.4", "busybox", "top")
  1039. c.Assert(err, checker.IsNil)
  1040. // Make sure task has been deployed.
  1041. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  1042. // We need to get the container id.
  1043. out, err := d.Cmd("ps", "-a", "-q", "--no-trunc")
  1044. c.Assert(err, checker.IsNil)
  1045. id := strings.TrimSpace(out)
  1046. // Compare against expected output.
  1047. expectedOutput := "1.2.3.4\texample.com"
  1048. out, err = d.Cmd("exec", id, "cat", "/etc/hosts")
  1049. c.Assert(err, checker.IsNil)
  1050. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  1051. }
  1052. func (s *DockerSwarmSuite) TestSwarmManagerAddress(c *check.C) {
  1053. d1 := s.AddDaemon(c, true, true)
  1054. d2 := s.AddDaemon(c, true, false)
  1055. d3 := s.AddDaemon(c, true, false)
  1056. // Manager Addresses will always show Node 1's address
  1057. expectedOutput := fmt.Sprintf("Manager Addresses:\n 127.0.0.1:%d\n", d1.Port)
  1058. out, err := d1.Cmd("info")
  1059. c.Assert(err, checker.IsNil)
  1060. c.Assert(out, checker.Contains, expectedOutput)
  1061. out, err = d2.Cmd("info")
  1062. c.Assert(err, checker.IsNil)
  1063. c.Assert(out, checker.Contains, expectedOutput)
  1064. out, err = d3.Cmd("info")
  1065. c.Assert(err, checker.IsNil)
  1066. c.Assert(out, checker.Contains, expectedOutput)
  1067. }
  1068. func (s *DockerSwarmSuite) TestSwarmServiceInspectPretty(c *check.C) {
  1069. d := s.AddDaemon(c, true, true)
  1070. name := "top"
  1071. out, err := d.Cmd("service", "create", "--name", name, "--limit-cpu=0.5", "busybox", "top")
  1072. c.Assert(err, checker.IsNil, check.Commentf(out))
  1073. expectedOutput := `
  1074. Resources:
  1075. Limits:
  1076. CPU: 0.5`
  1077. out, err = d.Cmd("service", "inspect", "--pretty", name)
  1078. c.Assert(err, checker.IsNil, check.Commentf(out))
  1079. c.Assert(out, checker.Contains, expectedOutput, check.Commentf(out))
  1080. }