-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathconsistent.go
274 lines (234 loc) · 5.46 KB
/
consistent.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// An implementation of Consistent Hashing and
// Consistent Hashing With Bounded Loads.
//
// https://en.wikipedia.org/wiki/Consistent_hashing
//
// https://research.googleblog.com/2017/04/consistent-hashing-with-bounded-loads.html
package consistent
import (
"encoding/binary"
"errors"
"fmt"
"math"
"sort"
"sync"
"sync/atomic"
blake2b "github.com/minio/blake2b-simd"
)
const replicationFactor = 10
var ErrNoHosts = errors.New("no hosts added")
type Host struct {
Name string
Load int64
}
type Consistent struct {
hosts map[uint64]string
sortedSet []uint64
loadMap map[string]*Host
totalLoad int64
sync.RWMutex
}
func New() *Consistent {
return &Consistent{
hosts: map[uint64]string{},
sortedSet: []uint64{},
loadMap: map[string]*Host{},
}
}
func (c *Consistent) Add(host string) {
c.Lock()
defer c.Unlock()
if _, ok := c.loadMap[host]; ok {
return
}
c.loadMap[host] = &Host{Name: host, Load: 0}
for i := 0; i < replicationFactor; i++ {
h := c.hash(fmt.Sprintf("%s%d", host, i))
c.hosts[h] = host
c.sortedSet = append(c.sortedSet, h)
}
// sort hashes ascendingly
sort.Slice(c.sortedSet, func(i int, j int) bool {
if c.sortedSet[i] < c.sortedSet[j] {
return true
}
return false
})
}
// Returns the host that owns `key`.
//
// As described in https://en.wikipedia.org/wiki/Consistent_hashing
//
// It returns ErrNoHosts if the ring has no hosts in it.
func (c *Consistent) Get(key string) (string, error) {
c.RLock()
defer c.RUnlock()
if len(c.hosts) == 0 {
return "", ErrNoHosts
}
h := c.hash(key)
idx := c.search(h)
return c.hosts[c.sortedSet[idx]], nil
}
// It uses Consistent Hashing With Bounded loads
//
// https://research.googleblog.com/2017/04/consistent-hashing-with-bounded-loads.html
//
// to pick the least loaded host that can serve the key
//
// It returns ErrNoHosts if the ring has no hosts in it.
//
func (c *Consistent) GetLeast(key string) (string, error) {
c.RLock()
defer c.RUnlock()
if len(c.hosts) == 0 {
return "", ErrNoHosts
}
h := c.hash(key)
idx := c.search(h)
i := idx
for {
host := c.hosts[c.sortedSet[i]]
if c.loadOK(host) {
return host, nil
}
i++
if i >= len(c.hosts) {
i = 0
}
}
}
func (c *Consistent) search(key uint64) int {
idx := sort.Search(len(c.sortedSet), func(i int) bool {
return c.sortedSet[i] >= key
})
if idx >= len(c.sortedSet) {
idx = 0
}
return idx
}
// Sets the load of `host` to the given `load`
func (c *Consistent) UpdateLoad(host string, load int64) {
c.Lock()
defer c.Unlock()
if _, ok := c.loadMap[host]; !ok {
return
}
c.totalLoad -= c.loadMap[host].Load
c.loadMap[host].Load = load
c.totalLoad += load
}
// Increments the load of host by 1
//
// should only be used with if you obtained a host with GetLeast
func (c *Consistent) Inc(host string) {
c.Lock()
defer c.Unlock()
if _, ok := c.loadMap[host]; !ok {
return
}
atomic.AddInt64(&c.loadMap[host].Load, 1)
atomic.AddInt64(&c.totalLoad, 1)
}
// Decrements the load of host by 1
//
// should only be used with if you obtained a host with GetLeast
func (c *Consistent) Done(host string) {
c.Lock()
defer c.Unlock()
if _, ok := c.loadMap[host]; !ok {
return
}
atomic.AddInt64(&c.loadMap[host].Load, -1)
atomic.AddInt64(&c.totalLoad, -1)
}
// Deletes host from the ring
func (c *Consistent) Remove(host string) bool {
c.Lock()
defer c.Unlock()
for i := 0; i < replicationFactor; i++ {
h := c.hash(fmt.Sprintf("%s%d", host, i))
delete(c.hosts, h)
c.delSlice(h)
}
delete(c.loadMap, host)
return true
}
// Return the list of hosts in the ring
func (c *Consistent) Hosts() (hosts []string) {
c.RLock()
defer c.RUnlock()
for k, _ := range c.loadMap {
hosts = append(hosts, k)
}
return hosts
}
// Returns the loads of all the hosts
func (c *Consistent) GetLoads() map[string]int64 {
loads := map[string]int64{}
for k, v := range c.loadMap {
loads[k] = v.Load
}
return loads
}
// Returns the maximum load of the single host
// which is:
// (total_load/number_of_hosts)*1.25
// total_load = is the total number of active requests served by hosts
// for more info:
// https://research.googleblog.com/2017/04/consistent-hashing-with-bounded-loads.html
func (c *Consistent) MaxLoad() int64 {
if c.totalLoad == 0 {
c.totalLoad = 1
}
var avgLoadPerNode float64
avgLoadPerNode = float64(c.totalLoad / int64(len(c.loadMap)))
if avgLoadPerNode == 0 {
avgLoadPerNode = 1
}
avgLoadPerNode = math.Ceil(avgLoadPerNode * 1.25)
return int64(avgLoadPerNode)
}
func (c *Consistent) loadOK(host string) bool {
// a safety check if someone performed c.Done more than needed
if c.totalLoad < 0 {
c.totalLoad = 0
}
var avgLoadPerNode float64
avgLoadPerNode = float64((c.totalLoad + 1) / int64(len(c.loadMap)))
if avgLoadPerNode == 0 {
avgLoadPerNode = 1
}
avgLoadPerNode = math.Ceil(avgLoadPerNode * 1.25)
bhost, ok := c.loadMap[host]
if !ok {
panic(fmt.Sprintf("given host(%s) not in loadsMap", bhost.Name))
}
if float64(bhost.Load)+1 <= avgLoadPerNode {
return true
}
return false
}
func (c *Consistent) delSlice(val uint64) {
idx := -1
l := 0
r := len(c.sortedSet) - 1
for l <= r {
m := (l + r) / 2
if c.sortedSet[m] == val {
idx = m
break
} else if c.sortedSet[m] < val {
l = m + 1
} else if c.sortedSet[m] > val {
r = m - 1
}
}
if idx != -1 {
c.sortedSet = append(c.sortedSet[:idx], c.sortedSet[idx+1:]...)
}
}
func (c *Consistent) hash(key string) uint64 {
out := blake2b.Sum512([]byte(key))
return binary.LittleEndian.Uint64(out[:])
}