docker_cli_swarm_test.go 66 KB

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