docker_cli_swarm_test.go 66 KB

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