cluster_store.go 5.6 KB

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