docker_cli_swarm_test.go 60 KB

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