member.go 4.7 KB

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