daemon_swarm.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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/pkg/integration/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. // CheckServiceRunningTasks returns the number of running tasks for the specified service
  146. func (d *Swarm) CheckServiceRunningTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
  147. return func(c *check.C) (interface{}, check.CommentInterface) {
  148. tasks := d.GetServiceTasks(c, service)
  149. var runningCount int
  150. for _, task := range tasks {
  151. if task.Status.State == swarm.TaskStateRunning {
  152. runningCount++
  153. }
  154. }
  155. return runningCount, nil
  156. }
  157. }
  158. // CheckServiceUpdateState returns the current update state for the specified service
  159. func (d *Swarm) CheckServiceUpdateState(service string) func(*check.C) (interface{}, check.CommentInterface) {
  160. return func(c *check.C) (interface{}, check.CommentInterface) {
  161. service := d.GetService(c, service)
  162. if service.UpdateStatus == nil {
  163. return "", nil
  164. }
  165. return service.UpdateStatus.State, nil
  166. }
  167. }
  168. // CheckServiceTasks returns the number of tasks for the specified service
  169. func (d *Swarm) CheckServiceTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
  170. return func(c *check.C) (interface{}, check.CommentInterface) {
  171. tasks := d.GetServiceTasks(c, service)
  172. return len(tasks), nil
  173. }
  174. }
  175. // CheckRunningTaskImages returns the number of different images attached to a running task
  176. func (d *Swarm) CheckRunningTaskImages(c *check.C) (interface{}, check.CommentInterface) {
  177. var tasks []swarm.Task
  178. filterArgs := filters.NewArgs()
  179. filterArgs.Add("desired-state", "running")
  180. filters, err := filters.ToParam(filterArgs)
  181. c.Assert(err, checker.IsNil)
  182. status, out, err := d.SockRequest("GET", "/tasks?filters="+filters, nil)
  183. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  184. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  185. c.Assert(json.Unmarshal(out, &tasks), checker.IsNil)
  186. result := make(map[string]int)
  187. for _, task := range tasks {
  188. if task.Status.State == swarm.TaskStateRunning {
  189. result[task.Spec.ContainerSpec.Image]++
  190. }
  191. }
  192. return result, nil
  193. }
  194. // CheckNodeReadyCount returns the number of ready node on the swarm
  195. func (d *Swarm) CheckNodeReadyCount(c *check.C) (interface{}, check.CommentInterface) {
  196. nodes := d.ListNodes(c)
  197. var readyCount int
  198. for _, node := range nodes {
  199. if node.Status.State == swarm.NodeStateReady {
  200. readyCount++
  201. }
  202. }
  203. return readyCount, nil
  204. }
  205. // GetTask returns the swarm task identified by the specified id
  206. func (d *Swarm) GetTask(c *check.C, id string) swarm.Task {
  207. var task swarm.Task
  208. status, out, err := d.SockRequest("GET", "/tasks/"+id, nil)
  209. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  210. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  211. c.Assert(json.Unmarshal(out, &task), checker.IsNil)
  212. return task
  213. }
  214. // UpdateService updates a swarm service with the specified service constructor
  215. func (d *Swarm) UpdateService(c *check.C, service *swarm.Service, f ...ServiceConstructor) {
  216. for _, fn := range f {
  217. fn(service)
  218. }
  219. url := fmt.Sprintf("/services/%s/update?version=%d", service.ID, service.Version.Index)
  220. status, out, err := d.SockRequest("POST", url, service.Spec)
  221. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  222. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  223. }
  224. // RemoveService removes the specified service
  225. func (d *Swarm) RemoveService(c *check.C, id string) {
  226. status, out, err := d.SockRequest("DELETE", "/services/"+id, nil)
  227. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  228. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  229. }
  230. // GetNode returns a swarm node identified by the specified id
  231. func (d *Swarm) GetNode(c *check.C, id string) *swarm.Node {
  232. var node swarm.Node
  233. status, out, err := d.SockRequest("GET", "/nodes/"+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. c.Assert(json.Unmarshal(out, &node), checker.IsNil)
  237. c.Assert(node.ID, checker.Equals, id)
  238. return &node
  239. }
  240. // RemoveNode removes the specified node
  241. func (d *Swarm) RemoveNode(c *check.C, id string, force bool) {
  242. url := "/nodes/" + id
  243. if force {
  244. url += "?force=1"
  245. }
  246. status, out, err := d.SockRequest("DELETE", url, nil)
  247. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  248. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  249. }
  250. // UpdateNode updates a swarm node with the specified node constructor
  251. func (d *Swarm) UpdateNode(c *check.C, id string, f ...NodeConstructor) {
  252. for i := 0; ; i++ {
  253. node := d.GetNode(c, id)
  254. for _, fn := range f {
  255. fn(node)
  256. }
  257. url := fmt.Sprintf("/nodes/%s/update?version=%d", node.ID, node.Version.Index)
  258. status, out, err := d.SockRequest("POST", url, node.Spec)
  259. if i < 10 && strings.Contains(string(out), "update out of sequence") {
  260. time.Sleep(100 * time.Millisecond)
  261. continue
  262. }
  263. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  264. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  265. return
  266. }
  267. }
  268. // ListNodes returns the list of the current swarm nodes
  269. func (d *Swarm) ListNodes(c *check.C) []swarm.Node {
  270. status, out, err := d.SockRequest("GET", "/nodes", nil)
  271. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  272. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  273. nodes := []swarm.Node{}
  274. c.Assert(json.Unmarshal(out, &nodes), checker.IsNil)
  275. return nodes
  276. }
  277. // ListServices return the list of the current swarm services
  278. func (d *Swarm) ListServices(c *check.C) []swarm.Service {
  279. status, out, err := d.SockRequest("GET", "/services", nil)
  280. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  281. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  282. services := []swarm.Service{}
  283. c.Assert(json.Unmarshal(out, &services), checker.IsNil)
  284. return services
  285. }
  286. // CreateSecret creates a secret given the specified spec
  287. func (d *Swarm) CreateSecret(c *check.C, secretSpec swarm.SecretSpec) string {
  288. status, out, err := d.SockRequest("POST", "/secrets/create", secretSpec)
  289. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  290. c.Assert(status, checker.Equals, http.StatusCreated, check.Commentf("output: %q", string(out)))
  291. var scr types.SecretCreateResponse
  292. c.Assert(json.Unmarshal(out, &scr), checker.IsNil)
  293. return scr.ID
  294. }
  295. // ListSecrets returns the list of the current swarm secrets
  296. func (d *Swarm) ListSecrets(c *check.C) []swarm.Secret {
  297. status, out, err := d.SockRequest("GET", "/secrets", nil)
  298. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  299. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  300. secrets := []swarm.Secret{}
  301. c.Assert(json.Unmarshal(out, &secrets), checker.IsNil)
  302. return secrets
  303. }
  304. // GetSecret returns a swarm secret identified by the specified id
  305. func (d *Swarm) GetSecret(c *check.C, id string) *swarm.Secret {
  306. var secret swarm.Secret
  307. status, out, err := d.SockRequest("GET", "/secrets/"+id, nil)
  308. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  309. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  310. c.Assert(json.Unmarshal(out, &secret), checker.IsNil)
  311. return &secret
  312. }
  313. // DeleteSecret removes the swarm secret identified by the specified id
  314. func (d *Swarm) DeleteSecret(c *check.C, id string) {
  315. status, out, err := d.SockRequest("DELETE", "/secrets/"+id, nil)
  316. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  317. c.Assert(status, checker.Equals, http.StatusNoContent, check.Commentf("output: %q", string(out)))
  318. }
  319. // GetSwarm return the current swarm object
  320. func (d *Swarm) GetSwarm(c *check.C) swarm.Swarm {
  321. var sw swarm.Swarm
  322. status, out, err := d.SockRequest("GET", "/swarm", nil)
  323. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  324. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  325. c.Assert(json.Unmarshal(out, &sw), checker.IsNil)
  326. return sw
  327. }
  328. // UpdateSwarm updates the current swarm object with the specified spec constructors
  329. func (d *Swarm) UpdateSwarm(c *check.C, f ...SpecConstructor) {
  330. sw := d.GetSwarm(c)
  331. for _, fn := range f {
  332. fn(&sw.Spec)
  333. }
  334. url := fmt.Sprintf("/swarm/update?version=%d", sw.Version.Index)
  335. status, out, err := d.SockRequest("POST", url, sw.Spec)
  336. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  337. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  338. }
  339. // RotateTokens update the swarm to rotate tokens
  340. func (d *Swarm) RotateTokens(c *check.C) {
  341. var sw swarm.Swarm
  342. status, out, err := d.SockRequest("GET", "/swarm", nil)
  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. c.Assert(json.Unmarshal(out, &sw), checker.IsNil)
  346. url := fmt.Sprintf("/swarm/update?version=%d&rotateWorkerToken=true&rotateManagerToken=true", sw.Version.Index)
  347. status, out, err = d.SockRequest("POST", url, sw.Spec)
  348. c.Assert(err, checker.IsNil, check.Commentf(string(out)))
  349. c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out)))
  350. }
  351. // JoinTokens returns the current swarm join tokens
  352. func (d *Swarm) JoinTokens(c *check.C) swarm.JoinTokens {
  353. var sw swarm.Swarm
  354. status, out, err := d.SockRequest("GET", "/swarm", nil)
  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. c.Assert(json.Unmarshal(out, &sw), checker.IsNil)
  358. return sw.JoinTokens
  359. }
  360. // CheckLocalNodeState returns the current swarm node state
  361. func (d *Swarm) CheckLocalNodeState(c *check.C) (interface{}, check.CommentInterface) {
  362. info, err := d.SwarmInfo()
  363. c.Assert(err, checker.IsNil)
  364. return info.LocalNodeState, nil
  365. }
  366. // CheckControlAvailable returns the current swarm control available
  367. func (d *Swarm) CheckControlAvailable(c *check.C) (interface{}, check.CommentInterface) {
  368. info, err := d.SwarmInfo()
  369. c.Assert(err, checker.IsNil)
  370. c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive)
  371. return info.ControlAvailable, nil
  372. }
  373. // CheckLeader returns whether there is a leader on the swarm or not
  374. func (d *Swarm) CheckLeader(c *check.C) (interface{}, check.CommentInterface) {
  375. errList := check.Commentf("could not get node list")
  376. status, out, err := d.SockRequest("GET", "/nodes", nil)
  377. if err != nil {
  378. return err, errList
  379. }
  380. if status != http.StatusOK {
  381. return fmt.Errorf("expected http status OK, got: %d", status), errList
  382. }
  383. var ls []swarm.Node
  384. if err := json.Unmarshal(out, &ls); err != nil {
  385. return err, errList
  386. }
  387. for _, node := range ls {
  388. if node.ManagerStatus != nil && node.ManagerStatus.Leader {
  389. return nil, nil
  390. }
  391. }
  392. return fmt.Errorf("no leader"), check.Commentf("could not find leader")
  393. }
  394. // CmdRetryOutOfSequence tries the specified command against the current daemon for 10 times
  395. func (d *Swarm) CmdRetryOutOfSequence(args ...string) (string, error) {
  396. for i := 0; ; i++ {
  397. out, err := d.Cmd(args...)
  398. if err != nil {
  399. if strings.Contains(out, "update out of sequence") {
  400. if i < 10 {
  401. continue
  402. }
  403. }
  404. }
  405. return out, err
  406. }
  407. }