token.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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(int64(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 []byte
  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([]byte(str))
  59. }
  60. func (o orderedToken) String() string {
  61. return string([]byte(o))
  62. }
  63. func (o orderedToken) Less(token token) bool {
  64. return -1 == bytes.Compare(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. // a data structure for organizing the relationship between tokens and hosts
  96. type tokenRing struct {
  97. partitioner partitioner
  98. tokens []token
  99. hosts []*HostInfo
  100. }
  101. func newTokenRing(partitioner string, hosts []*HostInfo) (*tokenRing, error) {
  102. tokenRing := &tokenRing{
  103. tokens: []token{},
  104. hosts: []*HostInfo{},
  105. }
  106. if strings.HasSuffix(partitioner, "Murmur3Partitioner") {
  107. tokenRing.partitioner = murmur3Partitioner{}
  108. } else if strings.HasSuffix(partitioner, "OrderedPartitioner") {
  109. tokenRing.partitioner = orderedPartitioner{}
  110. } else if strings.HasSuffix(partitioner, "RandomPartitioner") {
  111. tokenRing.partitioner = randomPartitioner{}
  112. } else {
  113. return nil, fmt.Errorf("Unsupported partitioner '%s'", partitioner)
  114. }
  115. for _, host := range hosts {
  116. for _, strToken := range host.Tokens() {
  117. token := tokenRing.partitioner.ParseString(strToken)
  118. tokenRing.tokens = append(tokenRing.tokens, token)
  119. tokenRing.hosts = append(tokenRing.hosts, host)
  120. }
  121. }
  122. sort.Sort(tokenRing)
  123. return tokenRing, nil
  124. }
  125. func (t *tokenRing) Len() int {
  126. return len(t.tokens)
  127. }
  128. func (t *tokenRing) Less(i, j int) bool {
  129. return t.tokens[i].Less(t.tokens[j])
  130. }
  131. func (t *tokenRing) Swap(i, j int) {
  132. t.tokens[i], t.hosts[i], t.tokens[j], t.hosts[j] =
  133. t.tokens[j], t.hosts[j], t.tokens[i], t.hosts[i]
  134. }
  135. func (t *tokenRing) String() string {
  136. buf := &bytes.Buffer{}
  137. buf.WriteString("TokenRing(")
  138. if t.partitioner != nil {
  139. buf.WriteString(t.partitioner.Name())
  140. }
  141. buf.WriteString("){")
  142. sep := ""
  143. for i := range t.tokens {
  144. buf.WriteString(sep)
  145. sep = ","
  146. buf.WriteString("\n\t[")
  147. buf.WriteString(strconv.Itoa(i))
  148. buf.WriteString("]")
  149. buf.WriteString(t.tokens[i].String())
  150. buf.WriteString(":")
  151. buf.WriteString(t.hosts[i].ConnectAddress().String())
  152. }
  153. buf.WriteString("\n}")
  154. return string(buf.Bytes())
  155. }
  156. func (t *tokenRing) GetHostForPartitionKey(partitionKey []byte) *HostInfo {
  157. if t == nil {
  158. return nil
  159. }
  160. token := t.partitioner.Hash(partitionKey)
  161. return t.GetHostForToken(token)
  162. }
  163. func (t *tokenRing) GetHostForToken(token token) *HostInfo {
  164. if t == nil {
  165. return nil
  166. }
  167. l := len(t.tokens)
  168. // no host tokens, no available hosts
  169. if l == 0 {
  170. return nil
  171. }
  172. // find the primary replica
  173. ringIndex := sort.Search(
  174. l,
  175. func(i int) bool {
  176. return !t.tokens[i].Less(token)
  177. },
  178. )
  179. if ringIndex == l {
  180. // wrap around to the first in the ring
  181. ringIndex = 0
  182. }
  183. host := t.hosts[ringIndex]
  184. return host
  185. }