-
Notifications
You must be signed in to change notification settings - Fork 508
/
consistenthash_new.go
228 lines (203 loc) · 5.67 KB
/
consistenthash_new.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package consistenthash
import (
"crypto/md5"
"errors"
"fmt"
"sort"
"sync"
"unsafe"
"github.com/TarsCloud/TarsGo/tars/selector"
"github.com/TarsCloud/TarsGo/tars/util/endpoint"
)
// ConsistentHash consistent hash map
type ConsistentHash struct {
sync.RWMutex
hash hash
enableWeight bool
replicates int
mapValues map[string]struct{}
hashRing map[uint32]endpoint.Endpoint
sortedKeys []uint32
}
var _ selector.Selector = (*ConsistentHash)(nil)
type HashAlgorithmType int
const (
KetamaHash HashAlgorithmType = 0
DefaultHash HashAlgorithmType = 1
)
type hash interface {
Hash(key string) uint32
GetHashType() HashAlgorithmType
}
type KetamaHashAlg struct {
}
func (k KetamaHashAlg) Hash(key string) uint32 {
p := md5.Sum([]byte(key))
h := uint32(p[3]&0xFF)<<24 | uint32(p[2]&0xFF)<<16 | uint32(p[1]&0xFF)<<8 | uint32(p[0]&0xFF)
return h
}
func (k KetamaHashAlg) GetHashType() HashAlgorithmType {
return KetamaHash
}
type DefaultHashAlg struct {
}
func (k DefaultHashAlg) Hash(key string) uint32 {
p := md5.Sum([]byte(key))
h := *((*uint32)(unsafe.Pointer(&p))) ^ *((*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&p)) + 4))) ^ *((*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&p)) + 8))) ^ *((*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&p)) + 12)))
return h
}
func (k DefaultHashAlg) GetHashType() HashAlgorithmType {
return DefaultHash
}
// New create a ConsistentHash which has replicates of virtual endpoint.Endpoint.
func New(enableWeight bool, hashType HashAlgorithmType) *ConsistentHash {
var h hash
if hashType == KetamaHash {
h = KetamaHashAlg{}
} else {
h = DefaultHashAlg{}
}
return &ConsistentHash{
hash: h,
enableWeight: enableWeight,
replicates: selector.ConHashVirtualNodes,
mapValues: make(map[string]struct{}),
hashRing: make(map[uint32]endpoint.Endpoint),
}
}
func (c *ConsistentHash) Select(msg selector.Message) (ep endpoint.Endpoint, err error) {
var ok bool
ep, ok = c.FindInt32(msg.HashCode())
if !ok {
return ep, errors.New("consistenthash: no such endpoint.Endpoint")
}
return ep, nil
}
// Find finds a endpoint.Endpoint to put the string key
func (c *ConsistentHash) Find(key string) (endpoint.Endpoint, bool) {
c.RLock()
defer c.RUnlock()
var point endpoint.Endpoint
if len(c.sortedKeys) == 0 {
return point, false
}
hashKey := c.hash.Hash(key)
index := sort.Search(len(c.sortedKeys), func(x int) bool {
return c.sortedKeys[x] >= hashKey
})
if index >= len(c.sortedKeys) {
index = 0
}
return c.hashRing[c.sortedKeys[index]], true
}
// FindInt32 finds a endpoint.Endpoint to put the uint32 key
func (c *ConsistentHash) FindInt32(key uint32) (endpoint.Endpoint, bool) {
c.RLock()
defer c.RUnlock()
var point endpoint.Endpoint
if len(c.sortedKeys) == 0 {
return point, false
}
index := sort.Search(len(c.sortedKeys), func(x int) bool {
return c.sortedKeys[x] >= key
})
if index >= len(c.sortedKeys) {
index = 0
}
return c.hashRing[c.sortedKeys[index]], true
}
func (c *ConsistentHash) Refresh(eps []endpoint.Endpoint) {
c.Lock()
defer c.Unlock()
c.mapValues = make(map[string]struct{}, len(eps))
c.hashRing = make(map[uint32]endpoint.Endpoint, len(eps))
c.sortedKeys = nil
for _, ep := range eps {
c.addLocked(ep)
}
sort.Slice(c.sortedKeys, func(x int, y int) bool {
return c.sortedKeys[x] < c.sortedKeys[y]
})
}
// Add : add the ep to the hash ring
func (c *ConsistentHash) Add(ep endpoint.Endpoint) error {
c.Lock()
defer c.Unlock()
if err := c.addLocked(ep); err != nil {
return err
}
sort.Slice(c.sortedKeys, func(x int, y int) bool {
return c.sortedKeys[x] < c.sortedKeys[y]
})
return nil
}
func (c *ConsistentHash) addLocked(ep endpoint.Endpoint) error {
if _, ok := c.mapValues[ep.HashKey()]; ok {
return fmt.Errorf("consistenthash: endpoint %+v already exists", ep)
}
weight := c.weight(ep.Weight)
for i := 0; i < weight; i++ {
virtualHost := fmt.Sprintf("%s_%d", ep.HashKey(), i)
if c.hash.GetHashType() == KetamaHash {
p := md5.Sum([]byte(virtualHost))
for k := 0; k < 4; k++ {
virtualKey := uint32(p[4*k+3]&0xFF)<<24 | uint32(p[4*k+2]&0xFF)<<16 | uint32(p[4*k+1]&0xFF)<<8 | uint32(p[4*k+0]&0xFF)
c.hashRing[virtualKey] = ep
c.sortedKeys = append(c.sortedKeys, virtualKey)
}
} else {
virtualKey := c.hash.Hash(virtualHost)
c.hashRing[virtualKey] = ep
c.sortedKeys = append(c.sortedKeys, virtualKey)
}
}
c.mapValues[ep.HashKey()] = struct{}{}
return nil
}
// Remove the ep and all the virtual eps from the key
func (c *ConsistentHash) Remove(ep endpoint.Endpoint) error {
c.Lock()
defer c.Unlock()
if _, ok := c.mapValues[ep.HashKey()]; !ok {
return fmt.Errorf("consistenthash: endpoint %+v already removed", ep)
}
delete(c.mapValues, ep.HashKey())
weight := c.weight(ep.Weight)
for i := 0; i < weight; i++ {
virtualHost := fmt.Sprintf("%s_%d", ep.HashKey(), i)
if c.hash.GetHashType() == KetamaHash {
p := md5.Sum([]byte(virtualHost))
for k := 0; k < 4; k++ {
virtualKey := uint32(p[4*k+3]&0xFF)<<24 | uint32(p[4*k+2]&0xFF)<<16 | uint32(p[4*k+1]&0xFF)<<8 | uint32(p[4*k+0]&0xFF)
delete(c.hashRing, virtualKey)
}
} else {
virtualKey := c.hash.Hash(virtualHost)
delete(c.hashRing, virtualKey)
}
}
c.reBuildHashRingLocked()
return nil
}
func (c *ConsistentHash) weight(w int32) int {
weight := c.replicates
if c.enableWeight {
weight = int(w)
}
if weight > 0 {
weight /= 4
if weight == 0 {
weight = 1
}
}
return weight
}
func (c *ConsistentHash) reBuildHashRingLocked() {
c.sortedKeys = make([]uint32, 0, len(c.hashRing))
for vk := range c.hashRing {
c.sortedKeys = append(c.sortedKeys, vk)
}
sort.Slice(c.sortedKeys, func(x, y int) bool {
return c.sortedKeys[x] < c.sortedKeys[y]
})
}