member.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Copyright 2015 CoreOS, Inc.
  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 etcdserver
  15. import (
  16. "crypto/sha1"
  17. "encoding/binary"
  18. "encoding/json"
  19. "fmt"
  20. "io/ioutil"
  21. "log"
  22. "math/rand"
  23. "net/http"
  24. "path"
  25. "sort"
  26. "time"
  27. "github.com/coreos/etcd/pkg/types"
  28. "github.com/coreos/etcd/store"
  29. "github.com/coreos/etcd/version"
  30. )
  31. // RaftAttributes represents the raft related attributes of an etcd member.
  32. type RaftAttributes struct {
  33. // TODO(philips): ensure these are URLs
  34. PeerURLs []string `json:"peerURLs"`
  35. }
  36. // Attributes represents all the non-raft related attributes of an etcd member.
  37. type Attributes struct {
  38. Name string `json:"name,omitempty"`
  39. ClientURLs []string `json:"clientURLs,omitempty"`
  40. }
  41. type Member struct {
  42. ID types.ID `json:"id"`
  43. RaftAttributes
  44. Attributes
  45. }
  46. // NewMember creates a Member without an ID and generates one based on the
  47. // name, peer URLs. This is used for bootstrapping/adding new member.
  48. func NewMember(name string, peerURLs types.URLs, clusterName string, now *time.Time) *Member {
  49. m := &Member{
  50. RaftAttributes: RaftAttributes{PeerURLs: peerURLs.StringSlice()},
  51. Attributes: Attributes{Name: name},
  52. }
  53. var b []byte
  54. sort.Strings(m.PeerURLs)
  55. for _, p := range m.PeerURLs {
  56. b = append(b, []byte(p)...)
  57. }
  58. b = append(b, []byte(clusterName)...)
  59. if now != nil {
  60. b = append(b, []byte(fmt.Sprintf("%d", now.Unix()))...)
  61. }
  62. hash := sha1.Sum(b)
  63. m.ID = types.ID(binary.BigEndian.Uint64(hash[:8]))
  64. return m
  65. }
  66. // PickPeerURL chooses a random address from a given Member's PeerURLs.
  67. // It will panic if there is no PeerURLs available in Member.
  68. func (m *Member) PickPeerURL() string {
  69. if len(m.PeerURLs) == 0 {
  70. log.Panicf("member should always have some peer url")
  71. }
  72. return m.PeerURLs[rand.Intn(len(m.PeerURLs))]
  73. }
  74. func (m *Member) Clone() *Member {
  75. if m == nil {
  76. return nil
  77. }
  78. mm := &Member{
  79. ID: m.ID,
  80. Attributes: Attributes{
  81. Name: m.Name,
  82. },
  83. }
  84. if m.PeerURLs != nil {
  85. mm.PeerURLs = make([]string, len(m.PeerURLs))
  86. copy(mm.PeerURLs, m.PeerURLs)
  87. }
  88. if m.ClientURLs != nil {
  89. mm.ClientURLs = make([]string, len(m.ClientURLs))
  90. copy(mm.ClientURLs, m.ClientURLs)
  91. }
  92. return mm
  93. }
  94. func memberStoreKey(id types.ID) string {
  95. return path.Join(storeMembersPrefix, id.String())
  96. }
  97. func MemberAttributesStorePath(id types.ID) string {
  98. return path.Join(memberStoreKey(id), attributesSuffix)
  99. }
  100. func mustParseMemberIDFromKey(key string) types.ID {
  101. id, err := types.IDFromString(path.Base(key))
  102. if err != nil {
  103. log.Panicf("unexpected parse member id error: %v", err)
  104. }
  105. return id
  106. }
  107. func removedMemberStoreKey(id types.ID) string {
  108. return path.Join(storeRemovedMembersPrefix, id.String())
  109. }
  110. // nodeToMember builds member from a key value node.
  111. // the child nodes of the given node MUST be sorted by key.
  112. func nodeToMember(n *store.NodeExtern) (*Member, error) {
  113. m := &Member{ID: mustParseMemberIDFromKey(n.Key)}
  114. attrs := make(map[string][]byte)
  115. raftAttrKey := path.Join(n.Key, raftAttributesSuffix)
  116. attrKey := path.Join(n.Key, attributesSuffix)
  117. for _, nn := range n.Nodes {
  118. if nn.Key != raftAttrKey && nn.Key != attrKey {
  119. return nil, fmt.Errorf("unknown key %q", nn.Key)
  120. }
  121. attrs[nn.Key] = []byte(*nn.Value)
  122. }
  123. if data := attrs[raftAttrKey]; data != nil {
  124. if err := json.Unmarshal(data, &m.RaftAttributes); err != nil {
  125. return nil, fmt.Errorf("unmarshal raftAttributes error: %v", err)
  126. }
  127. } else {
  128. return nil, fmt.Errorf("raftAttributes key doesn't exist")
  129. }
  130. if data := attrs[attrKey]; data != nil {
  131. if err := json.Unmarshal(data, &m.Attributes); err != nil {
  132. return m, fmt.Errorf("unmarshal attributes error: %v", err)
  133. }
  134. }
  135. return m, nil
  136. }
  137. // getVersion returns the version of the given member via its
  138. // peerURLs. Returns the last error if it fails to get the version.
  139. func getVersion(m *Member, tr *http.Transport) (string, error) {
  140. cc := &http.Client{
  141. Transport: tr,
  142. Timeout: time.Second,
  143. }
  144. var (
  145. err error
  146. resp *http.Response
  147. )
  148. for _, u := range m.PeerURLs {
  149. resp, err = cc.Get(u + "/version")
  150. if err != nil {
  151. continue
  152. }
  153. b, err := ioutil.ReadAll(resp.Body)
  154. resp.Body.Close()
  155. if err != nil {
  156. continue
  157. }
  158. var vers version.Versions
  159. if err := json.Unmarshal(b, &vers); err != nil {
  160. continue
  161. }
  162. return vers.Server, nil
  163. }
  164. return "", err
  165. }
  166. // implement sort by ID interface
  167. type SortableMemberSlice []*Member
  168. func (s SortableMemberSlice) Len() int { return len(s) }
  169. func (s SortableMemberSlice) Less(i, j int) bool { return s[i].ID < s[j].ID }
  170. func (s SortableMemberSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  171. // implement sort by peer urls interface
  172. type SortableMemberSliceByPeerURLs []*Member
  173. func (p SortableMemberSliceByPeerURLs) Len() int { return len(p) }
  174. func (p SortableMemberSliceByPeerURLs) Less(i, j int) bool {
  175. return p[i].PeerURLs[0] < p[j].PeerURLs[0]
  176. }
  177. func (p SortableMemberSliceByPeerURLs) Swap(i, j int) { p[i], p[j] = p[j], p[i] }