cluster_store.go 6.1 KB

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