member.go 4.7 KB

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