member.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. // PeerURLs is the list of peers in the raft cluster.
  34. // TODO(philips): ensure these are URLs
  35. PeerURLs []string `json:"peerURLs"`
  36. }
  37. // Attributes represents all the non-raft related attributes of an etcd member.
  38. type Attributes struct {
  39. Name string `json:"name,omitempty"`
  40. ClientURLs []string `json:"clientURLs,omitempty"`
  41. }
  42. type Member struct {
  43. ID types.ID `json:"id"`
  44. RaftAttributes
  45. Attributes
  46. }
  47. // NewMember creates a Member without an ID and generates one based on the
  48. // cluster name, peer URLs, and time. This is used for bootstrapping/adding new member.
  49. func NewMember(name string, peerURLs types.URLs, clusterName string, now *time.Time) *Member {
  50. m := &Member{
  51. RaftAttributes: RaftAttributes{PeerURLs: peerURLs.StringSlice()},
  52. Attributes: Attributes{Name: name},
  53. }
  54. var b []byte
  55. sort.Strings(m.PeerURLs)
  56. for _, p := range m.PeerURLs {
  57. b = append(b, []byte(p)...)
  58. }
  59. b = append(b, []byte(clusterName)...)
  60. if now != nil {
  61. b = append(b, []byte(fmt.Sprintf("%d", now.Unix()))...)
  62. }
  63. hash := sha1.Sum(b)
  64. m.ID = types.ID(binary.BigEndian.Uint64(hash[:8]))
  65. return m
  66. }
  67. // PickPeerURL chooses a random address from a given Member's PeerURLs.
  68. // It will panic if there is no PeerURLs available in Member.
  69. func (m *Member) PickPeerURL() string {
  70. if len(m.PeerURLs) == 0 {
  71. plog.Panicf("member should always have some peer url")
  72. }
  73. return m.PeerURLs[rand.Intn(len(m.PeerURLs))]
  74. }
  75. func (m *Member) Clone() *Member {
  76. if m == nil {
  77. return nil
  78. }
  79. mm := &Member{
  80. ID: m.ID,
  81. Attributes: Attributes{
  82. Name: m.Name,
  83. },
  84. }
  85. if m.PeerURLs != nil {
  86. mm.PeerURLs = make([]string, len(m.PeerURLs))
  87. copy(mm.PeerURLs, m.PeerURLs)
  88. }
  89. if m.ClientURLs != nil {
  90. mm.ClientURLs = make([]string, len(m.ClientURLs))
  91. copy(mm.ClientURLs, m.ClientURLs)
  92. }
  93. return mm
  94. }
  95. func (m *Member) IsStarted() bool {
  96. return len(m.Name) != 0
  97. }
  98. func memberStoreKey(id types.ID) string {
  99. return path.Join(storeMembersPrefix, id.String())
  100. }
  101. func MemberAttributesStorePath(id types.ID) string {
  102. return path.Join(memberStoreKey(id), attributesSuffix)
  103. }
  104. func mustParseMemberIDFromKey(key string) types.ID {
  105. id, err := types.IDFromString(path.Base(key))
  106. if err != nil {
  107. plog.Panicf("unexpected parse member id error: %v", err)
  108. }
  109. return id
  110. }
  111. func removedMemberStoreKey(id types.ID) string {
  112. return path.Join(storeRemovedMembersPrefix, id.String())
  113. }
  114. // nodeToMember builds member from a key value node.
  115. // the child nodes of the given node MUST be sorted by key.
  116. func nodeToMember(n *store.NodeExtern) (*Member, error) {
  117. m := &Member{ID: mustParseMemberIDFromKey(n.Key)}
  118. attrs := make(map[string][]byte)
  119. raftAttrKey := path.Join(n.Key, raftAttributesSuffix)
  120. attrKey := path.Join(n.Key, attributesSuffix)
  121. for _, nn := range n.Nodes {
  122. if nn.Key != raftAttrKey && nn.Key != attrKey {
  123. return nil, fmt.Errorf("unknown key %q", nn.Key)
  124. }
  125. attrs[nn.Key] = []byte(*nn.Value)
  126. }
  127. if data := attrs[raftAttrKey]; data != nil {
  128. if err := json.Unmarshal(data, &m.RaftAttributes); err != nil {
  129. return nil, fmt.Errorf("unmarshal raftAttributes error: %v", err)
  130. }
  131. } else {
  132. return nil, fmt.Errorf("raftAttributes key doesn't exist")
  133. }
  134. if data := attrs[attrKey]; data != nil {
  135. if err := json.Unmarshal(data, &m.Attributes); err != nil {
  136. return m, fmt.Errorf("unmarshal attributes error: %v", err)
  137. }
  138. }
  139. return m, nil
  140. }
  141. // MembersByID implements sort by ID interface
  142. type MembersByID []*Member
  143. func (ms MembersByID) Len() int { return len(ms) }
  144. func (ms MembersByID) Less(i, j int) bool { return ms[i].ID < ms[j].ID }
  145. func (ms MembersByID) Swap(i, j int) { ms[i], ms[j] = ms[j], ms[i] }
  146. // MembersByPeerURLs implements sort by peer urls interface
  147. type MembersByPeerURLs []*Member
  148. func (ms MembersByPeerURLs) Len() int { return len(ms) }
  149. func (ms MembersByPeerURLs) Less(i, j int) bool {
  150. return ms[i].PeerURLs[0] < ms[j].PeerURLs[0]
  151. }
  152. func (ms MembersByPeerURLs) Swap(i, j int) { ms[i], ms[j] = ms[j], ms[i] }