docker_cli_swarm_test.go 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  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. d.Stop(c)
  85. // start a daemon with --cluster-store and --cluster-advertise
  86. err = d.StartWithError("--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.StartWithError("--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. d.Start(c)
  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(c)
  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. d.Restart(c)
  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. d.Restart(c)
  685. }
  686. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  687. }
  688. func checkSwarmUnlockedToLocked(c *check.C, d *daemon.Swarm) {
  689. d.Restart(c)
  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. d.Restart(c)
  695. }
  696. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  697. }
  698. func (s *DockerSwarmSuite) TestUnlockEngineAndUnlockedSwarm(c *check.C) {
  699. d := s.AddDaemon(c, false, false)
  700. // unlocking a normal engine should return an error
  701. cmd := d.Command("swarm", "unlock")
  702. cmd.Stdin = bytes.NewBufferString("wrong-secret-key")
  703. outs, err := cmd.CombinedOutput()
  704. c.Assert(err, checker.NotNil, check.Commentf("out: %v", string(outs)))
  705. c.Assert(string(outs), checker.Contains, "This node is not a swarm manager.")
  706. _, err = d.Cmd("swarm", "init")
  707. c.Assert(err, checker.IsNil)
  708. // unlocking an unlocked swarm should return an error
  709. cmd = d.Command("swarm", "unlock")
  710. cmd.Stdin = bytes.NewBufferString("wrong-secret-key")
  711. outs, err = cmd.CombinedOutput()
  712. c.Assert(err, checker.NotNil, check.Commentf("out: %v", string(outs)))
  713. c.Assert(string(outs), checker.Contains, "swarm is not locked")
  714. }
  715. func (s *DockerSwarmSuite) TestSwarmInitLocked(c *check.C) {
  716. d := s.AddDaemon(c, false, false)
  717. outs, err := d.Cmd("swarm", "init", "--autolock")
  718. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  719. c.Assert(outs, checker.Contains, "docker swarm unlock")
  720. var unlockKey string
  721. for _, line := range strings.Split(outs, "\n") {
  722. if strings.Contains(line, "SWMKEY") {
  723. unlockKey = strings.TrimSpace(line)
  724. break
  725. }
  726. }
  727. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  728. outs, err = d.Cmd("swarm", "unlock-key", "-q")
  729. c.Assert(outs, checker.Equals, unlockKey+"\n")
  730. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  731. // It starts off locked
  732. d.Restart(c)
  733. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  734. cmd := d.Command("swarm", "unlock")
  735. cmd.Stdin = bytes.NewBufferString("wrong-secret-key")
  736. out, err := cmd.CombinedOutput()
  737. c.Assert(err, checker.NotNil, check.Commentf("out: %v", string(out)))
  738. c.Assert(string(out), checker.Contains, "invalid key")
  739. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  740. cmd = d.Command("swarm", "unlock")
  741. cmd.Stdin = bytes.NewBufferString(unlockKey)
  742. out, err = cmd.CombinedOutput()
  743. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  744. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  745. outs, err = d.Cmd("node", "ls")
  746. c.Assert(err, checker.IsNil)
  747. c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked")
  748. outs, err = d.Cmd("swarm", "update", "--autolock=false")
  749. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  750. checkSwarmLockedToUnlocked(c, d, unlockKey)
  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. }
  755. func (s *DockerSwarmSuite) TestSwarmLeaveLocked(c *check.C) {
  756. d := s.AddDaemon(c, false, false)
  757. outs, err := d.Cmd("swarm", "init", "--autolock")
  758. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  759. // It starts off locked
  760. d.Restart(c, "--swarm-default-advertise-addr=lo")
  761. info, err := d.SwarmInfo()
  762. c.Assert(err, checker.IsNil)
  763. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateLocked)
  764. outs, _ = d.Cmd("node", "ls")
  765. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  766. // `docker swarm leave` a locked swarm without --force will return an error
  767. outs, _ = d.Cmd("swarm", "leave")
  768. c.Assert(outs, checker.Contains, "Swarm is encrypted and locked.")
  769. // It is OK for user to leave a locked swarm with --force
  770. outs, err = d.Cmd("swarm", "leave", "--force")
  771. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  772. info, err = d.SwarmInfo()
  773. c.Assert(err, checker.IsNil)
  774. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive)
  775. outs, err = d.Cmd("swarm", "init")
  776. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  777. info, err = d.SwarmInfo()
  778. c.Assert(err, checker.IsNil)
  779. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive)
  780. }
  781. func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) {
  782. d1 := s.AddDaemon(c, true, true)
  783. d2 := s.AddDaemon(c, true, true)
  784. d3 := s.AddDaemon(c, true, true)
  785. // they start off unlocked
  786. d2.Restart(c)
  787. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
  788. // stop this one so it does not get autolock info
  789. d2.Stop(c)
  790. // enable autolock
  791. outs, err := d1.Cmd("swarm", "update", "--autolock")
  792. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  793. c.Assert(outs, checker.Contains, "docker swarm unlock")
  794. var unlockKey string
  795. for _, line := range strings.Split(outs, "\n") {
  796. if strings.Contains(line, "SWMKEY") {
  797. unlockKey = strings.TrimSpace(line)
  798. break
  799. }
  800. }
  801. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  802. outs, err = d1.Cmd("swarm", "unlock-key", "-q")
  803. c.Assert(outs, checker.Equals, unlockKey+"\n")
  804. // The ones that got the cluster update should be set to locked
  805. for _, d := range []*daemon.Swarm{d1, d3} {
  806. checkSwarmUnlockedToLocked(c, d)
  807. cmd := d.Command("swarm", "unlock")
  808. cmd.Stdin = bytes.NewBufferString(unlockKey)
  809. out, err := cmd.CombinedOutput()
  810. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  811. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  812. }
  813. // d2 never got the cluster update, so it is still set to unlocked
  814. d2.Start(c)
  815. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
  816. // d2 is now set to lock
  817. checkSwarmUnlockedToLocked(c, d2)
  818. // leave it locked, and set the cluster to no longer autolock
  819. outs, err = d1.Cmd("swarm", "update", "--autolock=false")
  820. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  821. // the ones that got the update are now set to unlocked
  822. for _, d := range []*daemon.Swarm{d1, d3} {
  823. checkSwarmLockedToUnlocked(c, d, unlockKey)
  824. }
  825. // d2 still locked
  826. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateLocked)
  827. // unlock it
  828. cmd := d2.Command("swarm", "unlock")
  829. cmd.Stdin = bytes.NewBufferString(unlockKey)
  830. out, err := cmd.CombinedOutput()
  831. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  832. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
  833. // once it's caught up, d2 is set to not be locked
  834. checkSwarmLockedToUnlocked(c, d2, unlockKey)
  835. // managers who join now are never set to locked in the first place
  836. d4 := s.AddDaemon(c, true, true)
  837. d4.Restart(c)
  838. c.Assert(getNodeStatus(c, d4), checker.Equals, swarm.LocalNodeStateActive)
  839. }
  840. func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) {
  841. d1 := s.AddDaemon(c, true, true)
  842. // enable autolock
  843. outs, err := d1.Cmd("swarm", "update", "--autolock")
  844. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  845. c.Assert(outs, checker.Contains, "docker swarm unlock")
  846. var unlockKey string
  847. for _, line := range strings.Split(outs, "\n") {
  848. if strings.Contains(line, "SWMKEY") {
  849. unlockKey = strings.TrimSpace(line)
  850. break
  851. }
  852. }
  853. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  854. outs, err = d1.Cmd("swarm", "unlock-key", "-q")
  855. c.Assert(outs, checker.Equals, unlockKey+"\n")
  856. // joined workers start off unlocked
  857. d2 := s.AddDaemon(c, true, false)
  858. d2.Restart(c)
  859. c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive)
  860. // promote worker
  861. outs, err = d1.Cmd("node", "promote", d2.Info.NodeID)
  862. c.Assert(err, checker.IsNil)
  863. c.Assert(outs, checker.Contains, "promoted to a manager in the swarm")
  864. // join new manager node
  865. d3 := s.AddDaemon(c, true, true)
  866. // both new nodes are locked
  867. for _, d := range []*daemon.Swarm{d2, d3} {
  868. checkSwarmUnlockedToLocked(c, d)
  869. cmd := d.Command("swarm", "unlock")
  870. cmd.Stdin = bytes.NewBufferString(unlockKey)
  871. out, err := cmd.CombinedOutput()
  872. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  873. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  874. }
  875. // get d3's cert
  876. d3cert, err := ioutil.ReadFile(filepath.Join(d3.Folder, "root", "swarm", "certificates", "swarm-node.crt"))
  877. c.Assert(err, checker.IsNil)
  878. // demote manager back to worker - workers are not locked
  879. outs, err = d1.Cmd("node", "demote", d3.Info.NodeID)
  880. c.Assert(err, checker.IsNil)
  881. c.Assert(outs, checker.Contains, "demoted in the swarm")
  882. // Wait for it to actually be demoted, for the key and cert to be replaced.
  883. // Then restart and assert that the node is not locked. If we don't wait for the cert
  884. // to be replaced, then the node still has the manager TLS key which is still locked
  885. // (because we never want a manager TLS key to be on disk unencrypted if the cluster
  886. // is set to autolock)
  887. waitAndAssert(c, defaultReconciliationTimeout, d3.CheckControlAvailable, checker.False)
  888. waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) {
  889. cert, err := ioutil.ReadFile(filepath.Join(d3.Folder, "root", "swarm", "certificates", "swarm-node.crt"))
  890. if err != nil {
  891. return "", check.Commentf("error: %v", err)
  892. }
  893. return string(cert), check.Commentf("cert: %v", string(cert))
  894. }, checker.Not(checker.Equals), string(d3cert))
  895. // by now, it should *never* be locked on restart
  896. d3.Restart(c)
  897. c.Assert(getNodeStatus(c, d3), checker.Equals, swarm.LocalNodeStateActive)
  898. }
  899. func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *check.C) {
  900. d := s.AddDaemon(c, true, true)
  901. outs, err := d.Cmd("swarm", "update", "--autolock")
  902. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  903. c.Assert(outs, checker.Contains, "docker swarm unlock")
  904. var unlockKey string
  905. for _, line := range strings.Split(outs, "\n") {
  906. if strings.Contains(line, "SWMKEY") {
  907. unlockKey = strings.TrimSpace(line)
  908. break
  909. }
  910. }
  911. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  912. outs, err = d.Cmd("swarm", "unlock-key", "-q")
  913. c.Assert(outs, checker.Equals, unlockKey+"\n")
  914. // Rotate multiple times
  915. for i := 0; i != 3; i++ {
  916. outs, err = d.Cmd("swarm", "unlock-key", "-q", "--rotate")
  917. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  918. // Strip \n
  919. newUnlockKey := outs[:len(outs)-1]
  920. c.Assert(newUnlockKey, checker.Not(checker.Equals), "")
  921. c.Assert(newUnlockKey, checker.Not(checker.Equals), unlockKey)
  922. d.Restart(c)
  923. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  924. outs, _ = d.Cmd("node", "ls")
  925. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  926. cmd := d.Command("swarm", "unlock")
  927. cmd.Stdin = bytes.NewBufferString(unlockKey)
  928. out, err := cmd.CombinedOutput()
  929. if err == nil {
  930. // On occasion, the daemon may not have finished
  931. // rotating the KEK before restarting. The test is
  932. // intentionally written to explore this behavior.
  933. // When this happens, unlocking with the old key will
  934. // succeed. If we wait for the rotation to happen and
  935. // restart again, the new key should be required this
  936. // time.
  937. time.Sleep(3 * time.Second)
  938. d.Restart(c)
  939. cmd = d.Command("swarm", "unlock")
  940. cmd.Stdin = bytes.NewBufferString(unlockKey)
  941. out, err = cmd.CombinedOutput()
  942. }
  943. c.Assert(err, checker.NotNil, check.Commentf("out: %v", string(out)))
  944. c.Assert(string(out), checker.Contains, "invalid key")
  945. outs, _ = d.Cmd("node", "ls")
  946. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  947. cmd = d.Command("swarm", "unlock")
  948. cmd.Stdin = bytes.NewBufferString(newUnlockKey)
  949. out, err = cmd.CombinedOutput()
  950. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  951. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  952. outs, err = d.Cmd("node", "ls")
  953. c.Assert(err, checker.IsNil)
  954. c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked")
  955. unlockKey = newUnlockKey
  956. }
  957. }
  958. // This differs from `TestSwarmRotateUnlockKey` because that one rotates a single node, which is the leader.
  959. // This one keeps the leader up, and asserts that other manager nodes in the cluster also have their unlock
  960. // key rotated.
  961. func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *check.C) {
  962. d1 := s.AddDaemon(c, true, true) // leader - don't restart this one, we don't want leader election delays
  963. d2 := s.AddDaemon(c, true, true)
  964. d3 := s.AddDaemon(c, true, true)
  965. outs, err := d1.Cmd("swarm", "update", "--autolock")
  966. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  967. c.Assert(outs, checker.Contains, "docker swarm unlock")
  968. var unlockKey string
  969. for _, line := range strings.Split(outs, "\n") {
  970. if strings.Contains(line, "SWMKEY") {
  971. unlockKey = strings.TrimSpace(line)
  972. break
  973. }
  974. }
  975. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  976. outs, err = d1.Cmd("swarm", "unlock-key", "-q")
  977. c.Assert(outs, checker.Equals, unlockKey+"\n")
  978. // Rotate multiple times
  979. for i := 0; i != 3; i++ {
  980. outs, err = d1.Cmd("swarm", "unlock-key", "-q", "--rotate")
  981. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  982. // Strip \n
  983. newUnlockKey := outs[:len(outs)-1]
  984. c.Assert(newUnlockKey, checker.Not(checker.Equals), "")
  985. c.Assert(newUnlockKey, checker.Not(checker.Equals), unlockKey)
  986. d2.Restart(c)
  987. d3.Restart(c)
  988. for _, d := range []*daemon.Swarm{d2, d3} {
  989. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked)
  990. outs, _ := d.Cmd("node", "ls")
  991. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  992. cmd := d.Command("swarm", "unlock")
  993. cmd.Stdin = bytes.NewBufferString(unlockKey)
  994. out, err := cmd.CombinedOutput()
  995. if err == nil {
  996. // On occasion, the daemon may not have finished
  997. // rotating the KEK before restarting. The test is
  998. // intentionally written to explore this behavior.
  999. // When this happens, unlocking with the old key will
  1000. // succeed. If we wait for the rotation to happen and
  1001. // restart again, the new key should be required this
  1002. // time.
  1003. time.Sleep(3 * time.Second)
  1004. d.Restart(c)
  1005. cmd = d.Command("swarm", "unlock")
  1006. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1007. out, err = cmd.CombinedOutput()
  1008. }
  1009. c.Assert(err, checker.NotNil, check.Commentf("out: %v", string(out)))
  1010. c.Assert(string(out), checker.Contains, "invalid key")
  1011. outs, _ = d.Cmd("node", "ls")
  1012. c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked")
  1013. cmd = d.Command("swarm", "unlock")
  1014. cmd.Stdin = bytes.NewBufferString(newUnlockKey)
  1015. out, err = cmd.CombinedOutput()
  1016. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  1017. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  1018. outs, err = d.Cmd("node", "ls")
  1019. c.Assert(err, checker.IsNil)
  1020. c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked")
  1021. }
  1022. unlockKey = newUnlockKey
  1023. }
  1024. }
  1025. func (s *DockerSwarmSuite) TestSwarmAlternateLockUnlock(c *check.C) {
  1026. d := s.AddDaemon(c, true, true)
  1027. var unlockKey string
  1028. for i := 0; i < 2; i++ {
  1029. // set to lock
  1030. outs, err := d.Cmd("swarm", "update", "--autolock")
  1031. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  1032. c.Assert(outs, checker.Contains, "docker swarm unlock")
  1033. for _, line := range strings.Split(outs, "\n") {
  1034. if strings.Contains(line, "SWMKEY") {
  1035. unlockKey = strings.TrimSpace(line)
  1036. break
  1037. }
  1038. }
  1039. c.Assert(unlockKey, checker.Not(checker.Equals), "")
  1040. checkSwarmUnlockedToLocked(c, d)
  1041. cmd := d.Command("swarm", "unlock")
  1042. cmd.Stdin = bytes.NewBufferString(unlockKey)
  1043. out, err := cmd.CombinedOutput()
  1044. c.Assert(err, checker.IsNil, check.Commentf("out: %v", string(out)))
  1045. c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive)
  1046. outs, err = d.Cmd("swarm", "update", "--autolock=false")
  1047. c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs))
  1048. checkSwarmLockedToUnlocked(c, d, unlockKey)
  1049. }
  1050. }
  1051. func (s *DockerSwarmSuite) TestExtraHosts(c *check.C) {
  1052. d := s.AddDaemon(c, true, true)
  1053. // Create a service
  1054. name := "top"
  1055. _, err := d.Cmd("service", "create", "--name", name, "--host=example.com:1.2.3.4", "busybox", "top")
  1056. c.Assert(err, checker.IsNil)
  1057. // Make sure task has been deployed.
  1058. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  1059. // We need to get the container id.
  1060. out, err := d.Cmd("ps", "-a", "-q", "--no-trunc")
  1061. c.Assert(err, checker.IsNil)
  1062. id := strings.TrimSpace(out)
  1063. // Compare against expected output.
  1064. expectedOutput := "1.2.3.4\texample.com"
  1065. out, err = d.Cmd("exec", id, "cat", "/etc/hosts")
  1066. c.Assert(err, checker.IsNil)
  1067. c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  1068. }
  1069. func (s *DockerSwarmSuite) TestSwarmManagerAddress(c *check.C) {
  1070. d1 := s.AddDaemon(c, true, true)
  1071. d2 := s.AddDaemon(c, true, false)
  1072. d3 := s.AddDaemon(c, true, false)
  1073. // Manager Addresses will always show Node 1's address
  1074. expectedOutput := fmt.Sprintf("Manager Addresses:\n 127.0.0.1:%d\n", d1.Port)
  1075. out, err := d1.Cmd("info")
  1076. c.Assert(err, checker.IsNil)
  1077. c.Assert(out, checker.Contains, expectedOutput)
  1078. out, err = d2.Cmd("info")
  1079. c.Assert(err, checker.IsNil)
  1080. c.Assert(out, checker.Contains, expectedOutput)
  1081. out, err = d3.Cmd("info")
  1082. c.Assert(err, checker.IsNil)
  1083. c.Assert(out, checker.Contains, expectedOutput)
  1084. }
  1085. func (s *DockerSwarmSuite) TestSwarmServiceInspectPretty(c *check.C) {
  1086. d := s.AddDaemon(c, true, true)
  1087. name := "top"
  1088. out, err := d.Cmd("service", "create", "--name", name, "--limit-cpu=0.5", "busybox", "top")
  1089. c.Assert(err, checker.IsNil, check.Commentf(out))
  1090. expectedOutput := `
  1091. Resources:
  1092. Limits:
  1093. CPU: 0.5`
  1094. out, err = d.Cmd("service", "inspect", "--pretty", name)
  1095. c.Assert(err, checker.IsNil, check.Commentf(out))
  1096. c.Assert(out, checker.Contains, expectedOutput, check.Commentf(out))
  1097. }
  1098. func (s *DockerSwarmSuite) TestSwarmNetworkIPAMOptions(c *check.C) {
  1099. d := s.AddDaemon(c, true, true)
  1100. out, err := d.Cmd("network", "create", "-d", "overlay", "--ipam-opt", "foo=bar", "foo")
  1101. c.Assert(err, checker.IsNil, check.Commentf(out))
  1102. c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
  1103. out, err = d.Cmd("network", "inspect", "--format", "{{.IPAM.Options}}", "foo")
  1104. c.Assert(err, checker.IsNil, check.Commentf(out))
  1105. c.Assert(strings.TrimSpace(out), checker.Equals, "map[foo:bar]")
  1106. out, err = d.Cmd("service", "create", "--network=foo", "--name", "top", "busybox", "top")
  1107. c.Assert(err, checker.IsNil, check.Commentf(out))
  1108. // make sure task has been deployed.
  1109. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
  1110. out, err = d.Cmd("network", "inspect", "--format", "{{.IPAM.Options}}", "foo")
  1111. c.Assert(err, checker.IsNil, check.Commentf(out))
  1112. c.Assert(strings.TrimSpace(out), checker.Equals, "map[foo:bar]")
  1113. }
  1114. // TODO: migrate to a unit test
  1115. // This test could be migrated to unit test and save costly integration test,
  1116. // once PR #29143 is merged.
  1117. func (s *DockerSwarmSuite) TestSwarmUpdateWithoutArgs(c *check.C) {
  1118. d := s.AddDaemon(c, true, true)
  1119. expectedOutput := `
  1120. Usage: docker swarm update [OPTIONS]
  1121. Update the swarm
  1122. Options:`
  1123. out, err := d.Cmd("swarm", "update")
  1124. c.Assert(err, checker.IsNil, check.Commentf("out: %v", out))
  1125. c.Assert(out, checker.Contains, expectedOutput, check.Commentf(out))
  1126. }