token.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Copyright (c) 2015 The gocql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gocql
  5. import (
  6. "bytes"
  7. "crypto/md5"
  8. "fmt"
  9. "math/big"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "github.com/gocql/gocql/internal/murmur"
  14. )
  15. // a token partitioner
  16. type partitioner interface {
  17. Name() string
  18. Hash([]byte) token
  19. ParseString(string) token
  20. }
  21. // a token
  22. type token interface {
  23. fmt.Stringer
  24. Less(token) bool
  25. }
  26. // murmur3 partitioner and token
  27. type murmur3Partitioner struct{}
  28. type murmur3Token int64
  29. func (p murmur3Partitioner) Name() string {
  30. return "Murmur3Partitioner"
  31. }
  32. func (p murmur3Partitioner) Hash(partitionKey []byte) token {
  33. h1 := murmur.Murmur3H1(partitionKey)
  34. return murmur3Token(h1)
  35. }
  36. // murmur3 little-endian, 128-bit hash, but returns only h1
  37. func (p murmur3Partitioner) ParseString(str string) token {
  38. val, _ := strconv.ParseInt(str, 10, 64)
  39. return murmur3Token(val)
  40. }
  41. func (m murmur3Token) String() string {
  42. return strconv.FormatInt(int64(m), 10)
  43. }
  44. func (m murmur3Token) Less(token token) bool {
  45. return m < token.(murmur3Token)
  46. }
  47. // order preserving partitioner and token
  48. type orderedPartitioner struct{}
  49. type orderedToken string
  50. func (p orderedPartitioner) Name() string {
  51. return "OrderedPartitioner"
  52. }
  53. func (p orderedPartitioner) Hash(partitionKey []byte) token {
  54. // the partition key is the token
  55. return orderedToken(partitionKey)
  56. }
  57. func (p orderedPartitioner) ParseString(str string) token {
  58. return orderedToken(str)
  59. }
  60. func (o orderedToken) String() string {
  61. return string(o)
  62. }
  63. func (o orderedToken) Less(token token) bool {
  64. return o < token.(orderedToken)
  65. }
  66. // random partitioner and token
  67. type randomPartitioner struct{}
  68. type randomToken big.Int
  69. func (r randomPartitioner) Name() string {
  70. return "RandomPartitioner"
  71. }
  72. // 2 ** 128
  73. var maxHashInt, _ = new(big.Int).SetString("340282366920938463463374607431768211456", 10)
  74. func (p randomPartitioner) Hash(partitionKey []byte) token {
  75. sum := md5.Sum(partitionKey)
  76. val := new(big.Int)
  77. val.SetBytes(sum[:])
  78. if sum[0] > 127 {
  79. val.Sub(val, maxHashInt)
  80. val.Abs(val)
  81. }
  82. return (*randomToken)(val)
  83. }
  84. func (p randomPartitioner) ParseString(str string) token {
  85. val := new(big.Int)
  86. val.SetString(str, 10)
  87. return (*randomToken)(val)
  88. }
  89. func (r *randomToken) String() string {
  90. return (*big.Int)(r).String()
  91. }
  92. func (r *randomToken) Less(token token) bool {
  93. return -1 == (*big.Int)(r).Cmp((*big.Int)(token.(*randomToken)))
  94. }
  95. type hostToken struct {
  96. token token
  97. host *HostInfo
  98. }
  99. func (ht hostToken) String() string {
  100. return fmt.Sprintf("{token=%v host=%v}", ht.token, ht.host.HostID())
  101. }
  102. // a data structure for organizing the relationship between tokens and hosts
  103. type tokenRing struct {
  104. partitioner partitioner
  105. // tokens map token range to primary replica.
  106. // The elements in tokens are sorted by token ascending.
  107. // The range for a given item in tokens starts after preceding range and ends with the token specified in
  108. // token. The end token is part of the range.
  109. // The lowest (i.e. index 0) range wraps around the ring (its preceding range is the one with largest index).
  110. tokens []hostToken
  111. hosts []*HostInfo
  112. }
  113. func newTokenRing(partitioner string, hosts []*HostInfo) (*tokenRing, error) {
  114. tokenRing := &tokenRing{
  115. hosts: hosts,
  116. }
  117. if strings.HasSuffix(partitioner, "Murmur3Partitioner") {
  118. tokenRing.partitioner = murmur3Partitioner{}
  119. } else if strings.HasSuffix(partitioner, "OrderedPartitioner") {
  120. tokenRing.partitioner = orderedPartitioner{}
  121. } else if strings.HasSuffix(partitioner, "RandomPartitioner") {
  122. tokenRing.partitioner = randomPartitioner{}
  123. } else {
  124. return nil, fmt.Errorf("Unsupported partitioner '%s'", partitioner)
  125. }
  126. for _, host := range hosts {
  127. for _, strToken := range host.Tokens() {
  128. token := tokenRing.partitioner.ParseString(strToken)
  129. tokenRing.tokens = append(tokenRing.tokens, hostToken{token, host})
  130. }
  131. }
  132. sort.Sort(tokenRing)
  133. return tokenRing, nil
  134. }
  135. func (t *tokenRing) Len() int {
  136. return len(t.tokens)
  137. }
  138. func (t *tokenRing) Less(i, j int) bool {
  139. return t.tokens[i].token.Less(t.tokens[j].token)
  140. }
  141. func (t *tokenRing) Swap(i, j int) {
  142. t.tokens[i], t.tokens[j] = t.tokens[j], t.tokens[i]
  143. }
  144. func (t *tokenRing) String() string {
  145. buf := &bytes.Buffer{}
  146. buf.WriteString("TokenRing(")
  147. if t.partitioner != nil {
  148. buf.WriteString(t.partitioner.Name())
  149. }
  150. buf.WriteString("){")
  151. sep := ""
  152. for i, th := range t.tokens {
  153. buf.WriteString(sep)
  154. sep = ","
  155. buf.WriteString("\n\t[")
  156. buf.WriteString(strconv.Itoa(i))
  157. buf.WriteString("]")
  158. buf.WriteString(th.token.String())
  159. buf.WriteString(":")
  160. buf.WriteString(th.host.ConnectAddress().String())
  161. }
  162. buf.WriteString("\n}")
  163. return string(buf.Bytes())
  164. }
  165. func (t *tokenRing) GetHostForToken(token token) (host *HostInfo, endToken token) {
  166. if t == nil || len(t.tokens) == 0 {
  167. return nil, nil
  168. }
  169. // find the primary replica
  170. p := sort.Search(len(t.tokens), func(i int) bool {
  171. return !t.tokens[i].token.Less(token)
  172. })
  173. if p == len(t.tokens) {
  174. // wrap around to the first in the ring
  175. p = 0
  176. }
  177. v := t.tokens[p]
  178. return v.host, v.token
  179. }