cluster.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "math/rand"
  18. "net"
  19. "strings"
  20. "time"
  21. "golang.org/x/net/context"
  22. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  23. "github.com/coreos/etcd/tools/functional-tester/etcd-agent/client"
  24. "google.golang.org/grpc"
  25. )
  26. // agentConfig holds information needed to interact/configure an agent and its etcd process
  27. type agentConfig struct {
  28. endpoint string
  29. clientPort int
  30. peerPort int
  31. failpointPort int
  32. }
  33. type cluster struct {
  34. agents []agentConfig
  35. Size int
  36. Members []*member
  37. }
  38. type ClusterStatus struct {
  39. AgentStatuses map[string]client.Status
  40. }
  41. func (c *cluster) bootstrap() error {
  42. size := len(c.agents)
  43. members := make([]*member, size)
  44. memberNameURLs := make([]string, size)
  45. for i, a := range c.agents {
  46. agent, err := client.NewAgent(a.endpoint)
  47. if err != nil {
  48. return err
  49. }
  50. host, _, err := net.SplitHostPort(a.endpoint)
  51. if err != nil {
  52. return err
  53. }
  54. members[i] = &member{
  55. Agent: agent,
  56. Endpoint: a.endpoint,
  57. Name: fmt.Sprintf("etcd-%d", i),
  58. ClientURL: fmt.Sprintf("http://%s:%d", host, a.clientPort),
  59. PeerURL: fmt.Sprintf("http://%s:%d", host, a.peerPort),
  60. FailpointURL: fmt.Sprintf("http://%s:%d", host, a.failpointPort),
  61. }
  62. memberNameURLs[i] = members[i].ClusterEntry()
  63. }
  64. clusterStr := strings.Join(memberNameURLs, ",")
  65. token := fmt.Sprint(rand.Int())
  66. for i, m := range members {
  67. flags := append(
  68. m.Flags(),
  69. "--initial-cluster-token", token,
  70. "--initial-cluster", clusterStr,
  71. "--snapshot-count", "10000")
  72. if _, err := m.Agent.Start(flags...); err != nil {
  73. // cleanup
  74. for _, m := range members[:i] {
  75. m.Agent.Terminate()
  76. }
  77. return err
  78. }
  79. }
  80. c.Size = size
  81. c.Members = members
  82. return nil
  83. }
  84. func (c *cluster) Reset() error { return c.bootstrap() }
  85. func (c *cluster) WaitHealth() error {
  86. var err error
  87. // wait 60s to check cluster health.
  88. // TODO: set it to a reasonable value. It is set that high because
  89. // follower may use long time to catch up the leader when reboot under
  90. // reasonable workload (https://github.com/coreos/etcd/issues/2698)
  91. for i := 0; i < 60; i++ {
  92. for _, m := range c.Members {
  93. if err = m.SetHealthKeyV3(); err != nil {
  94. break
  95. }
  96. }
  97. if err == nil {
  98. return nil
  99. }
  100. plog.Warningf("#%d setHealthKey error (%v)", i, err)
  101. time.Sleep(time.Second)
  102. }
  103. return err
  104. }
  105. // GetLeader returns the index of leader and error if any.
  106. func (c *cluster) GetLeader() (int, error) {
  107. for i, m := range c.Members {
  108. isLeader, err := m.IsLeader()
  109. if isLeader || err != nil {
  110. return i, err
  111. }
  112. }
  113. return 0, fmt.Errorf("no leader found")
  114. }
  115. func (c *cluster) Cleanup() error {
  116. var lasterr error
  117. for _, m := range c.Members {
  118. if err := m.Agent.Cleanup(); err != nil {
  119. lasterr = err
  120. }
  121. }
  122. return lasterr
  123. }
  124. func (c *cluster) Terminate() {
  125. for _, m := range c.Members {
  126. m.Agent.Terminate()
  127. }
  128. }
  129. func (c *cluster) Status() ClusterStatus {
  130. cs := ClusterStatus{
  131. AgentStatuses: make(map[string]client.Status),
  132. }
  133. for _, m := range c.Members {
  134. s, err := m.Agent.Status()
  135. // TODO: add a.Desc() as a key of the map
  136. desc := m.Endpoint
  137. if err != nil {
  138. cs.AgentStatuses[desc] = client.Status{State: "unknown"}
  139. plog.Printf("failed to get the status of agent [%s]", desc)
  140. }
  141. cs.AgentStatuses[desc] = s
  142. }
  143. return cs
  144. }
  145. // maxRev returns the maximum revision found on the cluster.
  146. func (c *cluster) maxRev() (rev int64, err error) {
  147. ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
  148. defer cancel()
  149. revc, errc := make(chan int64, len(c.Members)), make(chan error, len(c.Members))
  150. for i := range c.Members {
  151. go func(m *member) {
  152. mrev, merr := m.Rev(ctx)
  153. revc <- mrev
  154. errc <- merr
  155. }(c.Members[i])
  156. }
  157. for i := 0; i < len(c.Members); i++ {
  158. if merr := <-errc; merr != nil {
  159. err = merr
  160. }
  161. if mrev := <-revc; mrev > rev {
  162. rev = mrev
  163. }
  164. }
  165. return rev, err
  166. }
  167. func (c *cluster) getRevisionHash() (map[string]int64, map[string]int64, error) {
  168. revs := make(map[string]int64)
  169. hashes := make(map[string]int64)
  170. for _, m := range c.Members {
  171. rev, hash, err := m.RevHash()
  172. if err != nil {
  173. return nil, nil, err
  174. }
  175. revs[m.ClientURL] = rev
  176. hashes[m.ClientURL] = hash
  177. }
  178. return revs, hashes, nil
  179. }
  180. func (c *cluster) compactKV(rev int64, timeout time.Duration) (err error) {
  181. if rev <= 0 {
  182. return nil
  183. }
  184. for i, m := range c.Members {
  185. u := m.ClientURL
  186. conn, derr := m.dialGRPC()
  187. if derr != nil {
  188. plog.Printf("[compact kv #%d] dial error %v (endpoint %s)", i, derr, u)
  189. err = derr
  190. continue
  191. }
  192. kvc := pb.NewKVClient(conn)
  193. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  194. plog.Printf("[compact kv #%d] starting (endpoint %s)", i, u)
  195. _, cerr := kvc.Compact(ctx, &pb.CompactionRequest{Revision: rev, Physical: true}, grpc.FailFast(false))
  196. cancel()
  197. conn.Close()
  198. succeed := true
  199. if cerr != nil {
  200. if strings.Contains(cerr.Error(), "required revision has been compacted") && i > 0 {
  201. plog.Printf("[compact kv #%d] already compacted (endpoint %s)", i, u)
  202. } else {
  203. plog.Warningf("[compact kv #%d] error %v (endpoint %s)", i, cerr, u)
  204. err = cerr
  205. succeed = false
  206. }
  207. }
  208. if succeed {
  209. plog.Printf("[compact kv #%d] done (endpoint %s)", i, u)
  210. }
  211. }
  212. return err
  213. }
  214. func (c *cluster) checkCompact(rev int64) error {
  215. if rev == 0 {
  216. return nil
  217. }
  218. for _, m := range c.Members {
  219. if err := m.CheckCompact(rev); err != nil {
  220. return err
  221. }
  222. }
  223. return nil
  224. }
  225. func (c *cluster) defrag() error {
  226. for _, m := range c.Members {
  227. if err := m.Defrag(); err != nil {
  228. return err
  229. }
  230. }
  231. return nil
  232. }