token.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. "unsafe"
  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 := murmur3H1(partitionKey)
  34. return murmur3Token(int64(h1))
  35. }
  36. // murmur3 little-endian, 128-bit hash, but returns only h1
  37. func murmur3H1(data []byte) uint64 {
  38. length := len(data)
  39. var h1, h2, k1, k2 uint64
  40. const (
  41. c1 = 0x87c37b91114253d5
  42. c2 = 0x4cf5ad432745937f
  43. )
  44. // body
  45. nBlocks := length / 16
  46. for i := 0; i < nBlocks; i++ {
  47. block := (*[2]uint64)(unsafe.Pointer(&data[i*16]))
  48. k1 = block[0]
  49. k2 = block[1]
  50. k1 *= c1
  51. k1 = (k1 << 31) | (k1 >> 33) // ROTL64(k1, 31)
  52. k1 *= c2
  53. h1 ^= k1
  54. h1 = (h1 << 27) | (h1 >> 37) // ROTL64(h1, 27)
  55. h1 += h2
  56. h1 = h1*5 + 0x52dce729
  57. k2 *= c2
  58. k2 = (k2 << 33) | (k2 >> 31) // ROTL64(k2, 33)
  59. k2 *= c1
  60. h2 ^= k2
  61. h2 = (h2 << 31) | (h2 >> 33) // ROTL64(h2, 31)
  62. h2 += h1
  63. h2 = h2*5 + 0x38495ab5
  64. }
  65. // tail
  66. tail := data[nBlocks*16:]
  67. k1 = 0
  68. k2 = 0
  69. switch length & 15 {
  70. case 15:
  71. k2 ^= uint64(tail[14]) << 48
  72. fallthrough
  73. case 14:
  74. k2 ^= uint64(tail[13]) << 40
  75. fallthrough
  76. case 13:
  77. k2 ^= uint64(tail[12]) << 32
  78. fallthrough
  79. case 12:
  80. k2 ^= uint64(tail[11]) << 24
  81. fallthrough
  82. case 11:
  83. k2 ^= uint64(tail[10]) << 16
  84. fallthrough
  85. case 10:
  86. k2 ^= uint64(tail[9]) << 8
  87. fallthrough
  88. case 9:
  89. k2 ^= uint64(tail[8])
  90. k2 *= c2
  91. k2 = (k2 << 33) | (k2 >> 31) // ROTL64(k2, 33)
  92. k2 *= c1
  93. h2 ^= k2
  94. fallthrough
  95. case 8:
  96. k1 ^= uint64(tail[7]) << 56
  97. fallthrough
  98. case 7:
  99. k1 ^= uint64(tail[6]) << 48
  100. fallthrough
  101. case 6:
  102. k1 ^= uint64(tail[5]) << 40
  103. fallthrough
  104. case 5:
  105. k1 ^= uint64(tail[4]) << 32
  106. fallthrough
  107. case 4:
  108. k1 ^= uint64(tail[3]) << 24
  109. fallthrough
  110. case 3:
  111. k1 ^= uint64(tail[2]) << 16
  112. fallthrough
  113. case 2:
  114. k1 ^= uint64(tail[1]) << 8
  115. fallthrough
  116. case 1:
  117. k1 ^= uint64(tail[0])
  118. k1 *= c1
  119. k1 = (k1 << 31) | (k1 >> 33) // ROTL64(k1, 31)
  120. k1 *= c2
  121. h1 ^= k1
  122. }
  123. h1 ^= uint64(length)
  124. h2 ^= uint64(length)
  125. h1 += h2
  126. h2 += h1
  127. // finalizer
  128. const (
  129. fmix1 = 0xff51afd7ed558ccd
  130. fmix2 = 0xc4ceb9fe1a85ec53
  131. )
  132. // fmix64(h1)
  133. h1 ^= h1 >> 33
  134. h1 *= fmix1
  135. h1 ^= h1 >> 33
  136. h1 *= fmix2
  137. h1 ^= h1 >> 33
  138. // fmix64(h2)
  139. h2 ^= h2 >> 33
  140. h2 *= fmix1
  141. h2 ^= h2 >> 33
  142. h2 *= fmix2
  143. h2 ^= h2 >> 33
  144. h1 += h2
  145. // the following is extraneous since h2 is discarded
  146. // h2 += h1
  147. return h1
  148. }
  149. func (p murmur3Partitioner) ParseString(str string) token {
  150. val, _ := strconv.ParseInt(str, 10, 64)
  151. return murmur3Token(val)
  152. }
  153. func (m murmur3Token) String() string {
  154. return strconv.FormatInt(int64(m), 10)
  155. }
  156. func (m murmur3Token) Less(token token) bool {
  157. return m < token.(murmur3Token)
  158. }
  159. // order preserving partitioner and token
  160. type orderedPartitioner struct{}
  161. type orderedToken []byte
  162. func (p orderedPartitioner) Name() string {
  163. return "OrderedPartitioner"
  164. }
  165. func (p orderedPartitioner) Hash(partitionKey []byte) token {
  166. // the partition key is the token
  167. return orderedToken(partitionKey)
  168. }
  169. func (p orderedPartitioner) ParseString(str string) token {
  170. return orderedToken([]byte(str))
  171. }
  172. func (o orderedToken) String() string {
  173. return string([]byte(o))
  174. }
  175. func (o orderedToken) Less(token token) bool {
  176. return -1 == bytes.Compare(o, token.(orderedToken))
  177. }
  178. // random partitioner and token
  179. type randomPartitioner struct{}
  180. type randomToken big.Int
  181. func (r randomPartitioner) Name() string {
  182. return "RandomPartitioner"
  183. }
  184. func (p randomPartitioner) Hash(partitionKey []byte) token {
  185. hash := md5.New()
  186. sum := hash.Sum(partitionKey)
  187. val := new(big.Int)
  188. val = val.SetBytes(sum)
  189. val = val.Abs(val)
  190. return (*randomToken)(val)
  191. }
  192. func (p randomPartitioner) ParseString(str string) token {
  193. val := new(big.Int)
  194. val.SetString(str, 10)
  195. return (*randomToken)(val)
  196. }
  197. func (r *randomToken) String() string {
  198. return (*big.Int)(r).String()
  199. }
  200. func (r *randomToken) Less(token token) bool {
  201. return -1 == (*big.Int)(r).Cmp((*big.Int)(token.(*randomToken)))
  202. }
  203. // a data structure for organizing the relationship between tokens and hosts
  204. type tokenRing struct {
  205. partitioner partitioner
  206. tokens []token
  207. hosts []*HostInfo
  208. }
  209. func newTokenRing(partitioner string, hosts []HostInfo) (*tokenRing, error) {
  210. tokenRing := &tokenRing{
  211. tokens: []token{},
  212. hosts: []*HostInfo{},
  213. }
  214. if strings.HasSuffix(partitioner, "Murmur3Partitioner") {
  215. tokenRing.partitioner = murmur3Partitioner{}
  216. } else if strings.HasSuffix(partitioner, "OrderedPartitioner") {
  217. tokenRing.partitioner = orderedPartitioner{}
  218. } else if strings.HasSuffix(partitioner, "RandomPartitioner") {
  219. tokenRing.partitioner = randomPartitioner{}
  220. } else {
  221. return nil, fmt.Errorf("Unsupported partitioner '%s'", partitioner)
  222. }
  223. for i := range hosts {
  224. host := &hosts[i]
  225. for _, strToken := range host.Tokens {
  226. token := tokenRing.partitioner.ParseString(strToken)
  227. tokenRing.tokens = append(tokenRing.tokens, token)
  228. tokenRing.hosts = append(tokenRing.hosts, host)
  229. }
  230. }
  231. sort.Sort(tokenRing)
  232. return tokenRing, nil
  233. }
  234. func (t *tokenRing) Len() int {
  235. return len(t.tokens)
  236. }
  237. func (t *tokenRing) Less(i, j int) bool {
  238. return t.tokens[i].Less(t.tokens[j])
  239. }
  240. func (t *tokenRing) Swap(i, j int) {
  241. t.tokens[i], t.hosts[i], t.tokens[j], t.hosts[j] =
  242. t.tokens[j], t.hosts[j], t.tokens[i], t.hosts[i]
  243. }
  244. func (t *tokenRing) String() string {
  245. buf := &bytes.Buffer{}
  246. buf.WriteString("TokenRing(")
  247. if t.partitioner != nil {
  248. buf.WriteString(t.partitioner.Name())
  249. }
  250. buf.WriteString("){")
  251. sep := ""
  252. for i := range t.tokens {
  253. buf.WriteString(sep)
  254. sep = ","
  255. buf.WriteString("\n\t[")
  256. buf.WriteString(strconv.Itoa(i))
  257. buf.WriteString("]")
  258. buf.WriteString(t.tokens[i].String())
  259. buf.WriteString(":")
  260. buf.WriteString(t.hosts[i].Peer)
  261. }
  262. buf.WriteString("\n}")
  263. return string(buf.Bytes())
  264. }
  265. func (t *tokenRing) GetHostForPartitionKey(partitionKey []byte) *HostInfo {
  266. if t == nil {
  267. return nil
  268. }
  269. token := t.partitioner.Hash(partitionKey)
  270. return t.GetHostForToken(token)
  271. }
  272. func (t *tokenRing) GetHostForToken(token token) *HostInfo {
  273. if t == nil {
  274. return nil
  275. }
  276. // find the primary replica
  277. ringIndex := sort.Search(
  278. len(t.tokens),
  279. func(i int) bool {
  280. return !t.tokens[i].Less(token)
  281. },
  282. )
  283. if ringIndex == len(t.tokens) {
  284. // wrap around to the first in the ring
  285. ringIndex = 0
  286. }
  287. host := t.hosts[ringIndex]
  288. return host
  289. }