cluster_store.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. package etcdserver
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "net/http"
  8. "strconv"
  9. "time"
  10. etcdErr "github.com/coreos/etcd/error"
  11. "github.com/coreos/etcd/etcdserver/stats"
  12. "github.com/coreos/etcd/raft/raftpb"
  13. "github.com/coreos/etcd/store"
  14. )
  15. const (
  16. raftPrefix = "/raft"
  17. raftAttributesSuffix = "/raftAttributes"
  18. attributesSuffix = "/attributes"
  19. )
  20. type ClusterStore interface {
  21. Add(m Member)
  22. Get() Cluster
  23. Remove(id uint64)
  24. }
  25. type clusterStore struct {
  26. Store store.Store
  27. }
  28. // Add puts a new Member into the store.
  29. // A Member with a matching id must not exist.
  30. func (s *clusterStore) Add(m Member) {
  31. b, err := json.Marshal(m.RaftAttributes)
  32. if err != nil {
  33. log.Panicf("marshal error: %v", err)
  34. }
  35. if _, err := s.Store.Create(m.storeKey()+raftAttributesSuffix, false, string(b), false, store.Permanent); err != nil {
  36. log.Panicf("add raftAttributes should never fail: %v", err)
  37. }
  38. b, err = json.Marshal(m.Attributes)
  39. if err != nil {
  40. log.Panicf("marshal error: %v", err)
  41. }
  42. if _, err := s.Store.Create(m.storeKey()+attributesSuffix, false, string(b), false, store.Permanent); err != nil {
  43. log.Panicf("add attributes should never fail: %v", err)
  44. }
  45. }
  46. // TODO(philips): keep the latest copy without going to the store to avoid the
  47. // lock here.
  48. func (s *clusterStore) Get() Cluster {
  49. c := &Cluster{}
  50. e, err := s.Store.Get(membersKVPrefix, true, true)
  51. if err != nil {
  52. if v, ok := err.(*etcdErr.Error); ok && v.ErrorCode == etcdErr.EcodeKeyNotFound {
  53. return *c
  54. }
  55. log.Panicf("get member should never fail: %v", err)
  56. }
  57. for _, n := range e.Node.Nodes {
  58. m, err := nodeToMember(n)
  59. if err != nil {
  60. log.Panicf("unexpected nodeToMember error: %v", err)
  61. }
  62. if err := c.Add(m); err != nil {
  63. log.Panicf("add member to cluster should never fail: %v", err)
  64. }
  65. }
  66. return *c
  67. }
  68. // nodeToMember builds member through a store node.
  69. // the child nodes of the given node should be sorted by key.
  70. func nodeToMember(n *store.NodeExtern) (Member, error) {
  71. m := Member{ID: parseMemberID(n.Key)}
  72. if len(n.Nodes) != 2 {
  73. return m, fmt.Errorf("len(nodes) = %d, want 2", len(n.Nodes))
  74. }
  75. if w := n.Key + attributesSuffix; n.Nodes[0].Key != w {
  76. return m, fmt.Errorf("key = %v, want %v", n.Nodes[0].Key, w)
  77. }
  78. if err := json.Unmarshal([]byte(*n.Nodes[0].Value), &m.Attributes); err != nil {
  79. return m, fmt.Errorf("unmarshal attributes error: %v", err)
  80. }
  81. if w := n.Key + raftAttributesSuffix; n.Nodes[1].Key != w {
  82. return m, fmt.Errorf("key = %v, want %v", n.Nodes[1].Key, w)
  83. }
  84. if err := json.Unmarshal([]byte(*n.Nodes[1].Value), &m.RaftAttributes); err != nil {
  85. return m, fmt.Errorf("unmarshal raftAttributes error: %v", err)
  86. }
  87. return m, nil
  88. }
  89. // Remove removes a member from the store.
  90. // The given id MUST exist.
  91. func (s *clusterStore) Remove(id uint64) {
  92. p := s.Get().FindID(id).storeKey()
  93. if _, err := s.Store.Delete(p, true, true); err != nil {
  94. log.Panicf("delete peer should never fail: %v", err)
  95. }
  96. }
  97. // Sender creates the default production sender used to transport raft messages
  98. // in the cluster. The returned sender will update the given ServerStats and
  99. // LeaderStats appropriately.
  100. func Sender(t *http.Transport, cls ClusterStore, ss *stats.ServerStats, ls *stats.LeaderStats) func(msgs []raftpb.Message) {
  101. c := &http.Client{Transport: t}
  102. return func(msgs []raftpb.Message) {
  103. for _, m := range msgs {
  104. // TODO: reuse go routines
  105. // limit the number of outgoing connections for the same receiver
  106. go send(c, cls, m, ss, ls)
  107. }
  108. }
  109. }
  110. // send uses the given client to send a message to a member in the given
  111. // ClusterStore, retrying up to 3 times for each message. The given
  112. // ServerStats and LeaderStats are updated appropriately
  113. func send(c *http.Client, cls ClusterStore, m raftpb.Message, ss *stats.ServerStats, ls *stats.LeaderStats) {
  114. // TODO (xiangli): reasonable retry logic
  115. for i := 0; i < 3; i++ {
  116. u := cls.Get().Pick(m.To)
  117. if u == "" {
  118. // TODO: unknown peer id.. what do we do? I
  119. // don't think his should ever happen, need to
  120. // look into this further.
  121. log.Printf("etcdhttp: no addr for %d", m.To)
  122. return
  123. }
  124. u = fmt.Sprintf("%s%s", u, raftPrefix)
  125. // TODO: don't block. we should be able to have 1000s
  126. // of messages out at a time.
  127. data, err := m.Marshal()
  128. if err != nil {
  129. log.Println("etcdhttp: dropping message:", err)
  130. return // drop bad message
  131. }
  132. if m.Type == raftpb.MsgApp {
  133. ss.SendAppendReq(len(data))
  134. }
  135. to := strconv.FormatUint(m.To, 16)
  136. fs, ok := ls.Followers[to]
  137. if !ok {
  138. fs = &stats.FollowerStats{}
  139. fs.Latency.Minimum = 1 << 63
  140. ls.Followers[to] = fs
  141. }
  142. start := time.Now()
  143. sent := httpPost(c, u, data)
  144. end := time.Now()
  145. if sent {
  146. fs.Succ(end.Sub(start))
  147. return
  148. }
  149. fs.Fail()
  150. // TODO: backoff
  151. }
  152. }
  153. // httpPost POSTs a data payload to a url using the given client. Returns true
  154. // if the POST succeeds, false on any failure.
  155. func httpPost(c *http.Client, url string, data []byte) bool {
  156. resp, err := c.Post(url, "application/protobuf", bytes.NewBuffer(data))
  157. if err != nil {
  158. // TODO: log the error?
  159. return false
  160. }
  161. resp.Body.Close()
  162. if resp.StatusCode != http.StatusNoContent {
  163. // TODO: log the error?
  164. return false
  165. }
  166. return true
  167. }