daemon_swarm.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. package daemon
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/docker/docker/api/types"
  9. "github.com/docker/docker/api/types/filters"
  10. "github.com/docker/docker/api/types/swarm"
  11. "github.com/docker/docker/integration-cli/checker"
  12. "github.com/go-check/check"
  13. "github.com/pkg/errors"
  14. )
  15. // Swarm is a test daemon with helpers for participating in a swarm.
  16. type Swarm struct {
  17. *Daemon
  18. swarm.Info
  19. Port int
  20. ListenAddr string
  21. }
  22. // Init initializes a new swarm cluster.
  23. func (d *Swarm) Init(req swarm.InitRequest) error {
  24. if req.ListenAddr == "" {
  25. req.ListenAddr = d.ListenAddr
  26. }
  27. status, out, err := d.SockRequest("POST", "/swarm/init", req)
  28. if status != http.StatusOK {
  29. return fmt.Errorf("initializing swarm: invalid statuscode %v, %q", status, out)
  30. }
  31. if err != nil {
  32. return fmt.Errorf("initializing swarm: %v", err)
  33. }
  34. info, err := d.SwarmInfo()
  35. if err != nil {
  36. return err
  37. }
  38. d.Info = info
  39. return nil
  40. }
  41. // Join joins a daemon to an existing cluster.
  42. func (d *Swarm) Join(req swarm.JoinRequest) error {
  43. if req.ListenAddr == "" {
  44. req.ListenAddr = d.ListenAddr
  45. }
  46. status, out, err := d.SockRequest("POST", "/swarm/join", req)
  47. if status != http.StatusOK {
  48. return fmt.Errorf("joining swarm: invalid statuscode %v, %q", status, out)
  49. }
  50. if err != nil {
  51. return fmt.Errorf("joining swarm: %v", err)
  52. }
  53. info, err := d.SwarmInfo()
  54. if err != nil {
  55. return err
  56. }
  57. d.Info = info
  58. return nil
  59. }
  60. // Leave forces daemon to leave current cluster.
  61. func (d *Swarm) Leave(force bool) error {
  62. url := "/swarm/leave"
  63. if force {
  64. url += "?force=1"
  65. }
  66. status, out, err := d.SockRequest("POST", url, nil)
  67. if status != http.StatusOK {
  68. return fmt.Errorf("leaving swarm: invalid statuscode %v, %q", status, out)
  69. }
  70. if err != nil {
  71. err = fmt.Errorf("leaving swarm: %v", err)
  72. }
  73. return err
  74. }
  75. // SwarmInfo returns the swarm information of the daemon
  76. func (d *Swarm) SwarmInfo() (swarm.Info, error) {
  77. var info struct {
  78. Swarm swarm.Info
  79. }
  80. status, dt, err := d.SockRequest("GET", "/info", nil)
  81. if status != http.StatusOK {
  82. return info.Swarm, fmt.Errorf("get swarm info: invalid statuscode %v", status)
  83. }
  84. if err != nil {
  85. return info.Swarm, fmt.Errorf("get swarm info: %v", err)
  86. }
  87. if err := json.Unmarshal(dt, &info); err != nil {
  88. return info.Swarm, err
  89. }
  90. return info.Swarm, nil
  91. }
  92. // Unlock tries to unlock a locked swarm
  93. func (d *Swarm) Unlock(req swarm.UnlockRequest) error {
  94. status, out, err := d.SockRequest("POST", "/swarm/unlock", req)
  95. if status != http.StatusOK {
  96. return fmt.Errorf("unlocking swarm: invalid statuscode %v, %q", status, out)
  97. }
  98. if err != nil {
  99. err = errors.Wrap(err, "unlocking swarm")
  100. }
  101. return err
  102. }
  103. // ServiceConstructor defines a swarm service constructor function
  104. type ServiceConstructor func(*swarm.Service)
  105. // NodeConstructor defines a swarm node constructor
  106. type NodeConstructor func(*swarm.Node)
  107. // SpecConstructor defines a swarm spec constructor
  108. type SpecConstructor func(*swarm.Spec)
  109. // CreateService creates a swarm service given the specified service constructor
  110. func (d *Swarm) CreateService(c *check.C, f ...ServiceConstructor) string {
  111. var service swarm.Service
  112. for _, fn := range f {
  113. fn(&service)
  114. }
  115. status, out, err := d.SockRequest("POST", "/services/create", service.Spec)
  116. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  117. c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf("output: %q", string(out)))
  118. var scr types.ServiceCreateResponse
  119. c.Assert(json.Unmarshal(out, &scr), checker.IsNil)
  120. return scr.ID
  121. }
  122. // GetService returns the swarm service corresponding to the specified id
  123. func (d *Swarm) GetService(c *check.C, id string) *swarm.Service {
  124. var service swarm.Service
  125. status, out, err := d.SockRequest("GET", "/services/"+id, nil)
  126. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  127. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  128. c.Assert(json.Unmarshal(out, &service), checker.IsNil)
  129. return &service
  130. }
  131. // GetServiceTasks returns the swarm tasks for the specified service
  132. func (d *Swarm) GetServiceTasks(c *check.C, service string) []swarm.Task {
  133. var tasks []swarm.Task
  134. filterArgs := filters.NewArgs()
  135. filterArgs.Add("desired-state", "running")
  136. filterArgs.Add("service", service)
  137. filters, err := filters.ToParam(filterArgs)
  138. c.Assert(err, checker.IsNil)
  139. status, out, err := d.SockRequest("GET", "/tasks?filters="+filters, nil)
  140. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  141. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  142. c.Assert(json.Unmarshal(out, &tasks), checker.IsNil)
  143. return tasks
  144. }
  145. // CheckServiceTasksInState returns the number of tasks with a matching state,
  146. // and optional message substring.
  147. func (d *Swarm) CheckServiceTasksInState(service string, state swarm.TaskState, message string) func(*check.C) (interface{}, check.CommentInterface) {
  148. return func(c *check.C) (interface{}, check.CommentInterface) {
  149. tasks := d.GetServiceTasks(c, service)
  150. var count int
  151. for _, task := range tasks {
  152. if task.Status.State == state {
  153. if message == "" || strings.Contains(task.Status.Message, message) {
  154. count++
  155. }
  156. }
  157. }
  158. return count, nil
  159. }
  160. }
  161. // CheckServiceRunningTasks returns the number of running tasks for the specified service
  162. func (d *Swarm) CheckServiceRunningTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
  163. return d.CheckServiceTasksInState(service, swarm.TaskStateRunning, "")
  164. }
  165. // CheckServiceUpdateState returns the current update state for the specified service
  166. func (d *Swarm) CheckServiceUpdateState(service string) func(*check.C) (interface{}, check.CommentInterface) {
  167. return func(c *check.C) (interface{}, check.CommentInterface) {
  168. service := d.GetService(c, service)
  169. if service.UpdateStatus == nil {
  170. return "", nil
  171. }
  172. return service.UpdateStatus.State, nil
  173. }
  174. }
  175. // CheckServiceTasks returns the number of tasks for the specified service
  176. func (d *Swarm) CheckServiceTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
  177. return func(c *check.C) (interface{}, check.CommentInterface) {
  178. tasks := d.GetServiceTasks(c, service)
  179. return len(tasks), nil
  180. }
  181. }
  182. // CheckRunningTaskImages returns the number of different images attached to a running task
  183. func (d *Swarm) CheckRunningTaskImages(c *check.C) (interface{}, check.CommentInterface) {
  184. var tasks []swarm.Task
  185. filterArgs := filters.NewArgs()
  186. filterArgs.Add("desired-state", "running")
  187. filters, err := filters.ToParam(filterArgs)
  188. c.Assert(err, checker.IsNil)
  189. status, out, err := d.SockRequest("GET", "/tasks?filters="+filters, nil)
  190. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  191. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  192. c.Assert(json.Unmarshal(out, &tasks), checker.IsNil)
  193. result := make(map[string]int)
  194. for _, task := range tasks {
  195. if task.Status.State == swarm.TaskStateRunning {
  196. result[task.Spec.ContainerSpec.Image]++
  197. }
  198. }
  199. return result, nil
  200. }
  201. // CheckNodeReadyCount returns the number of ready node on the swarm
  202. func (d *Swarm) CheckNodeReadyCount(c *check.C) (interface{}, check.CommentInterface) {
  203. nodes := d.ListNodes(c)
  204. var readyCount int
  205. for _, node := range nodes {
  206. if node.Status.State == swarm.NodeStateReady {
  207. readyCount++
  208. }
  209. }
  210. return readyCount, nil
  211. }
  212. // GetTask returns the swarm task identified by the specified id
  213. func (d *Swarm) GetTask(c *check.C, id string) swarm.Task {
  214. var task swarm.Task
  215. status, out, err := d.SockRequest("GET", "/tasks/"+id, nil)
  216. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  217. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  218. c.Assert(json.Unmarshal(out, &task), checker.IsNil)
  219. return task
  220. }
  221. // UpdateService updates a swarm service with the specified service constructor
  222. func (d *Swarm) UpdateService(c *check.C, service *swarm.Service, f ...ServiceConstructor) {
  223. for _, fn := range f {
  224. fn(service)
  225. }
  226. url := fmt.Sprintf("/services/%s/update?version=%d", service.ID, service.Version.Index)
  227. status, out, err := d.SockRequest("POST", url, service.Spec)
  228. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  229. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  230. }
  231. // RemoveService removes the specified service
  232. func (d *Swarm) RemoveService(c *check.C, id string) {
  233. status, out, err := d.SockRequest("DELETE", "/services/"+id, nil)
  234. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  235. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  236. }
  237. // GetNode returns a swarm node identified by the specified id
  238. func (d *Swarm) GetNode(c *check.C, id string) *swarm.Node {
  239. var node swarm.Node
  240. status, out, err := d.SockRequest("GET", "/nodes/"+id, nil)
  241. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  242. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  243. c.Assert(json.Unmarshal(out, &node), checker.IsNil)
  244. c.Assert(node.ID, checker.Equals, id)
  245. return &node
  246. }
  247. // RemoveNode removes the specified node
  248. func (d *Swarm) RemoveNode(c *check.C, id string, force bool) {
  249. url := "/nodes/" + id
  250. if force {
  251. url += "?force=1"
  252. }
  253. status, out, err := d.SockRequest("DELETE", url, nil)
  254. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  255. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  256. }
  257. // UpdateNode updates a swarm node with the specified node constructor
  258. func (d *Swarm) UpdateNode(c *check.C, id string, f ...NodeConstructor) {
  259. for i := 0; ; i++ {
  260. node := d.GetNode(c, id)
  261. for _, fn := range f {
  262. fn(node)
  263. }
  264. url := fmt.Sprintf("/nodes/%s/update?version=%d", node.ID, node.Version.Index)
  265. status, out, err := d.SockRequest("POST", url, node.Spec)
  266. if i < 10 && strings.Contains(string(out), "update out of sequence") {
  267. time.Sleep(100 * time.Millisecond)
  268. continue
  269. }
  270. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  271. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  272. return
  273. }
  274. }
  275. // ListNodes returns the list of the current swarm nodes
  276. func (d *Swarm) ListNodes(c *check.C) []swarm.Node {
  277. status, out, err := d.SockRequest("GET", "/nodes", nil)
  278. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  279. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  280. nodes := []swarm.Node{}
  281. c.Assert(json.Unmarshal(out, &nodes), checker.IsNil)
  282. return nodes
  283. }
  284. // ListServices return the list of the current swarm services
  285. func (d *Swarm) ListServices(c *check.C) []swarm.Service {
  286. status, out, err := d.SockRequest("GET", "/services", nil)
  287. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  288. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  289. services := []swarm.Service{}
  290. c.Assert(json.Unmarshal(out, &services), checker.IsNil)
  291. return services
  292. }
  293. // CreateSecret creates a secret given the specified spec
  294. func (d *Swarm) CreateSecret(c *check.C, secretSpec swarm.SecretSpec) string {
  295. status, out, err := d.SockRequest("POST", "/secrets/create", secretSpec)
  296. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  297. c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf("output: %q", string(out)))
  298. var scr types.SecretCreateResponse
  299. c.Assert(json.Unmarshal(out, &scr), checker.IsNil)
  300. return scr.ID
  301. }
  302. // ListSecrets returns the list of the current swarm secrets
  303. func (d *Swarm) ListSecrets(c *check.C) []swarm.Secret {
  304. status, out, err := d.SockRequest("GET", "/secrets", nil)
  305. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  306. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  307. secrets := []swarm.Secret{}
  308. c.Assert(json.Unmarshal(out, &secrets), checker.IsNil)
  309. return secrets
  310. }
  311. // GetSecret returns a swarm secret identified by the specified id
  312. func (d *Swarm) GetSecret(c *check.C, id string) *swarm.Secret {
  313. var secret swarm.Secret
  314. status, out, err := d.SockRequest("GET", "/secrets/"+id, nil)
  315. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  316. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  317. c.Assert(json.Unmarshal(out, &secret), checker.IsNil)
  318. return &secret
  319. }
  320. // DeleteSecret removes the swarm secret identified by the specified id
  321. func (d *Swarm) DeleteSecret(c *check.C, id string) {
  322. status, out, err := d.SockRequest("DELETE", "/secrets/"+id, nil)
  323. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  324. c.Assert(status, checker.Equals, http.StatusNoContent, check.Commentf("output: %q", string(out)))
  325. }
  326. // GetSwarm return the current swarm object
  327. func (d *Swarm) GetSwarm(c *check.C) swarm.Swarm {
  328. var sw swarm.Swarm
  329. status, out, err := d.SockRequest("GET", "/swarm", nil)
  330. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  331. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  332. c.Assert(json.Unmarshal(out, &sw), checker.IsNil)
  333. return sw
  334. }
  335. // UpdateSwarm updates the current swarm object with the specified spec constructors
  336. func (d *Swarm) UpdateSwarm(c *check.C, f ...SpecConstructor) {
  337. sw := d.GetSwarm(c)
  338. for _, fn := range f {
  339. fn(&sw.Spec)
  340. }
  341. url := fmt.Sprintf("/swarm/update?version=%d", sw.Version.Index)
  342. status, out, err := d.SockRequest("POST", url, sw.Spec)
  343. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  344. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  345. }
  346. // RotateTokens update the swarm to rotate tokens
  347. func (d *Swarm) RotateTokens(c *check.C) {
  348. var sw swarm.Swarm
  349. status, out, err := d.SockRequest("GET", "/swarm", nil)
  350. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  351. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  352. c.Assert(json.Unmarshal(out, &sw), checker.IsNil)
  353. url := fmt.Sprintf("/swarm/update?version=%d&rotateWorkerToken=true&rotateManagerToken=true", sw.Version.Index)
  354. status, out, err = d.SockRequest("POST", url, sw.Spec)
  355. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  356. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  357. }
  358. // JoinTokens returns the current swarm join tokens
  359. func (d *Swarm) JoinTokens(c *check.C) swarm.JoinTokens {
  360. var sw swarm.Swarm
  361. status, out, err := d.SockRequest("GET", "/swarm", nil)
  362. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  363. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  364. c.Assert(json.Unmarshal(out, &sw), checker.IsNil)
  365. return sw.JoinTokens
  366. }
  367. // CheckLocalNodeState returns the current swarm node state
  368. func (d *Swarm) CheckLocalNodeState(c *check.C) (interface{}, check.CommentInterface) {
  369. info, err := d.SwarmInfo()
  370. c.Assert(err, checker.IsNil)
  371. return info.LocalNodeState, nil
  372. }
  373. // CheckControlAvailable returns the current swarm control available
  374. func (d *Swarm) CheckControlAvailable(c *check.C) (interface{}, check.CommentInterface) {
  375. info, err := d.SwarmInfo()
  376. c.Assert(err, checker.IsNil)
  377. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive)
  378. return info.ControlAvailable, nil
  379. }
  380. // CheckLeader returns whether there is a leader on the swarm or not
  381. func (d *Swarm) CheckLeader(c *check.C) (interface{}, check.CommentInterface) {
  382. errList := check.Commentf("could not get node list")
  383. status, out, err := d.SockRequest("GET", "/nodes", nil)
  384. if err != nil {
  385. return err, errList
  386. }
  387. if status != http.StatusOK {
  388. return fmt.Errorf("expected http status OK, got: %d", status), errList
  389. }
  390. var ls []swarm.Node
  391. if err := json.Unmarshal(out, &ls); err != nil {
  392. return err, errList
  393. }
  394. for _, node := range ls {
  395. if node.ManagerStatus != nil && node.ManagerStatus.Leader {
  396. return nil, nil
  397. }
  398. }
  399. return fmt.Errorf("no leader"), check.Commentf("could not find leader")
  400. }
  401. // CmdRetryOutOfSequence tries the specified command against the current daemon for 10 times
  402. func (d *Swarm) CmdRetryOutOfSequence(args ...string) (string, error) {
  403. for i := 0; ; i++ {
  404. out, err := d.Cmd(args...)
  405. if err != nil {
  406. if strings.Contains(out, "update out of sequence") {
  407. if i < 10 {
  408. continue
  409. }
  410. }
  411. }
  412. return out, err
  413. }
  414. }