docker_cli_swarm_test.go 63 KB

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