member.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. "log"
  21. "math/rand"
  22. "path"
  23. "sort"
  24. "time"
  25. "github.com/coreos/etcd/pkg/types"
  26. "github.com/coreos/etcd/store"
  27. )
  28. var (
  29. storeMembersPrefix = path.Join(StoreClusterPrefix, "members")
  30. storeRemovedMembersPrefix = path.Join(StoreClusterPrefix, "removed_members")
  31. )
  32. // RaftAttributes represents the raft related attributes of an etcd member.
  33. type RaftAttributes struct {
  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. // name, peer URLs. 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. log.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 memberStoreKey(id types.ID) string {
  96. return path.Join(storeMembersPrefix, id.String())
  97. }
  98. func MemberAttributesStorePath(id types.ID) string {
  99. return path.Join(memberStoreKey(id), attributesSuffix)
  100. }
  101. func mustParseMemberIDFromKey(key string) types.ID {
  102. id, err := types.IDFromString(path.Base(key))
  103. if err != nil {
  104. log.Panicf("unexpected parse member id error: %v", err)
  105. }
  106. return id
  107. }
  108. func removedMemberStoreKey(id types.ID) string {
  109. return path.Join(storeRemovedMembersPrefix, id.String())
  110. }
  111. // nodeToMember builds member from a key value node.
  112. // the child nodes of the given node MUST be sorted by key.
  113. func nodeToMember(n *store.NodeExtern) (*Member, error) {
  114. m := &Member{ID: mustParseMemberIDFromKey(n.Key)}
  115. attrs := make(map[string][]byte)
  116. raftAttrKey := path.Join(n.Key, raftAttributesSuffix)
  117. attrKey := path.Join(n.Key, attributesSuffix)
  118. for _, nn := range n.Nodes {
  119. if nn.Key != raftAttrKey && nn.Key != attrKey {
  120. return nil, fmt.Errorf("unknown key %q", nn.Key)
  121. }
  122. attrs[nn.Key] = []byte(*nn.Value)
  123. }
  124. if data := attrs[raftAttrKey]; data != nil {
  125. if err := json.Unmarshal(data, &m.RaftAttributes); err != nil {
  126. return nil, fmt.Errorf("unmarshal raftAttributes error: %v", err)
  127. }
  128. } else {
  129. return nil, fmt.Errorf("raftAttributes key doesn't exist")
  130. }
  131. if data := attrs[attrKey]; data != nil {
  132. if err := json.Unmarshal(data, &m.Attributes); err != nil {
  133. return m, fmt.Errorf("unmarshal attributes error: %v", err)
  134. }
  135. }
  136. return m, nil
  137. }
  138. // implement sort by ID interface
  139. type MembersByID []*Member
  140. func (ms MembersByID) Len() int { return len(ms) }
  141. func (ms MembersByID) Less(i, j int) bool { return ms[i].ID < ms[j].ID }
  142. func (ms MembersByID) Swap(i, j int) { ms[i], ms[j] = ms[j], ms[i] }
  143. // implement sort by peer urls interface
  144. type MembersByPeerURLs []*Member
  145. func (ms MembersByPeerURLs) Len() int { return len(ms) }
  146. func (ms MembersByPeerURLs) Less(i, j int) bool {
  147. return ms[i].PeerURLs[0] < ms[j].PeerURLs[0]
  148. }
  149. func (ms MembersByPeerURLs) Swap(i, j int) { ms[i], ms[j] = ms[j], ms[i] }