token.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. func (p randomPartitioner) Hash(partitionKey []byte) token {
  73. // 2 ** 128
  74. maxInt := new(big.Int)
  75. maxInt.SetString("340282366920938463463374607431768211456", 10)
  76. sum := md5.Sum(partitionKey)
  77. val := new(big.Int)
  78. val.SetBytes(sum[:])
  79. if sum[0] > 127 {
  80. val.Sub(val, maxInt)
  81. val.Abs(val)
  82. }
  83. return (*randomToken)(val)
  84. }
  85. func (p randomPartitioner) ParseString(str string) token {
  86. val := new(big.Int)
  87. val.SetString(str, 10)
  88. return (*randomToken)(val)
  89. }
  90. func (r *randomToken) String() string {
  91. return (*big.Int)(r).String()
  92. }
  93. func (r *randomToken) Less(token token) bool {
  94. return -1 == (*big.Int)(r).Cmp((*big.Int)(token.(*randomToken)))
  95. }
  96. // a data structure for organizing the relationship between tokens and hosts
  97. type tokenRing struct {
  98. partitioner partitioner
  99. tokens []token
  100. hosts []*HostInfo
  101. }
  102. func newTokenRing(partitioner string, hosts []*HostInfo) (*tokenRing, error) {
  103. tokenRing := &tokenRing{
  104. tokens: []token{},
  105. hosts: []*HostInfo{},
  106. }
  107. if strings.HasSuffix(partitioner, "Murmur3Partitioner") {
  108. tokenRing.partitioner = murmur3Partitioner{}
  109. } else if strings.HasSuffix(partitioner, "OrderedPartitioner") {
  110. tokenRing.partitioner = orderedPartitioner{}
  111. } else if strings.HasSuffix(partitioner, "RandomPartitioner") {
  112. tokenRing.partitioner = randomPartitioner{}
  113. } else {
  114. return nil, fmt.Errorf("Unsupported partitioner '%s'", partitioner)
  115. }
  116. for _, host := range hosts {
  117. for _, strToken := range host.Tokens() {
  118. token := tokenRing.partitioner.ParseString(strToken)
  119. tokenRing.tokens = append(tokenRing.tokens, token)
  120. tokenRing.hosts = append(tokenRing.hosts, host)
  121. }
  122. }
  123. sort.Sort(tokenRing)
  124. return tokenRing, nil
  125. }
  126. func (t *tokenRing) Len() int {
  127. return len(t.tokens)
  128. }
  129. func (t *tokenRing) Less(i, j int) bool {
  130. return t.tokens[i].Less(t.tokens[j])
  131. }
  132. func (t *tokenRing) Swap(i, j int) {
  133. t.tokens[i], t.hosts[i], t.tokens[j], t.hosts[j] =
  134. t.tokens[j], t.hosts[j], t.tokens[i], t.hosts[i]
  135. }
  136. func (t *tokenRing) String() string {
  137. buf := &bytes.Buffer{}
  138. buf.WriteString("TokenRing(")
  139. if t.partitioner != nil {
  140. buf.WriteString(t.partitioner.Name())
  141. }
  142. buf.WriteString("){")
  143. sep := ""
  144. for i := range t.tokens {
  145. buf.WriteString(sep)
  146. sep = ","
  147. buf.WriteString("\n\t[")
  148. buf.WriteString(strconv.Itoa(i))
  149. buf.WriteString("]")
  150. buf.WriteString(t.tokens[i].String())
  151. buf.WriteString(":")
  152. buf.WriteString(t.hosts[i].Peer())
  153. }
  154. buf.WriteString("\n}")
  155. return string(buf.Bytes())
  156. }
  157. func (t *tokenRing) GetHostForPartitionKey(partitionKey []byte) *HostInfo {
  158. if t == nil {
  159. return nil
  160. }
  161. token := t.partitioner.Hash(partitionKey)
  162. return t.GetHostForToken(token)
  163. }
  164. func (t *tokenRing) GetHostForToken(token token) *HostInfo {
  165. if t == nil {
  166. return nil
  167. }
  168. // find the primary replica
  169. ringIndex := sort.Search(
  170. len(t.tokens),
  171. func(i int) bool {
  172. return !t.tokens[i].Less(token)
  173. },
  174. )
  175. if ringIndex == len(t.tokens) {
  176. // wrap around to the first in the ring
  177. ringIndex = 0
  178. }
  179. host := t.hosts[ringIndex]
  180. return host
  181. }