docker_cli_swarm_test.go 61 KB

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