member.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. "math/rand"
  21. "path"
  22. "sort"
  23. "time"
  24. "github.com/coreos/etcd/pkg/types"
  25. "github.com/coreos/etcd/store"
  26. )
  27. var (
  28. storeMembersPrefix = path.Join(StoreClusterPrefix, "members")
  29. storeRemovedMembersPrefix = path.Join(StoreClusterPrefix, "removed_members")
  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. plog.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. plog.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. // implement sort by ID interface
  138. type MembersByID []*Member
  139. func (ms MembersByID) Len() int { return len(ms) }
  140. func (ms MembersByID) Less(i, j int) bool { return ms[i].ID < ms[j].ID }
  141. func (ms MembersByID) Swap(i, j int) { ms[i], ms[j] = ms[j], ms[i] }
  142. // implement sort by peer urls interface
  143. type MembersByPeerURLs []*Member
  144. func (ms MembersByPeerURLs) Len() int { return len(ms) }
  145. func (ms MembersByPeerURLs) Less(i, j int) bool {
  146. return ms[i].PeerURLs[0] < ms[j].PeerURLs[0]
  147. }
  148. func (ms MembersByPeerURLs) Swap(i, j int) { ms[i], ms[j] = ms[j], ms[i] }