-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathxring.go
226 lines (185 loc) · 3.85 KB
/
xring.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
package xring
import (
"errors"
"fmt"
hash1 "github.com/OneOfOne/xxhash"
"github.com/arriqaaq/rbt"
"math"
"sync"
"sync/atomic"
)
var (
ERR_EMPTY_RING = errors.New("empty ring")
ERR_KEY_NOT_FOUND = errors.New("key not found")
ERR_HEAVY_LOAD = errors.New("servers under heavy load")
)
type hasher interface {
hash(string) int64
}
func newXXHash() hasher {
return xxHash{}
}
// https://cyan4973.github.io/xxHash/
type xxHash struct {
}
func (x xxHash) hash(data string) int64 {
h := hash1.New32()
h.Write([]byte(data))
r := h.Sum32()
h.Reset()
return int64(r)
}
func newNode(name string) *node {
return &node{
name: name,
active: true,
load: 0,
}
}
type node struct {
name string
active bool
load int64
}
func (n *node) Load() {}
type Config struct {
VirtualNodes int
LoadFactor float64
}
type Ring struct {
store *rbt.Tree
nodeMap map[string]*node
hashfn hasher
virtualNodes int
loadFactor float64
totalLoad int64
mu sync.RWMutex
}
func New() *Ring {
r := &Ring{
store: rbt.NewTree(),
nodeMap: make(map[string]*node),
hashfn: newXXHash(),
}
return r
}
func NewRing(nodes []string, cnf *Config) *Ring {
r := &Ring{
store: rbt.NewTree(),
nodeMap: make(map[string]*node),
virtualNodes: cnf.VirtualNodes,
loadFactor: cnf.LoadFactor,
hashfn: newXXHash(),
}
if r.loadFactor <= 0 {
r.loadFactor = 1
}
for _, node := range nodes {
r.Add(node)
}
return r
}
func (r *Ring) hash(val string) int64 {
return r.hashfn.hash(val)
}
func (r *Ring) Add(node string) {
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.nodeMap[node]; ok {
return
}
r.nodeMap[node] = newNode(node)
hashKey := r.hash(node)
r.store.Insert(hashKey, node)
for i := 0; i < r.virtualNodes; i++ {
vNodeKey := fmt.Sprintf("%s-%d", node, i)
r.nodeMap[vNodeKey] = newNode(vNodeKey)
hashKey := r.hash(vNodeKey)
r.store.Insert(hashKey, node)
}
}
func (r *Ring) Remove(node string) {
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.nodeMap[node]; !ok {
return
}
hashKey := r.hash(node)
r.store.Delete(hashKey)
for i := 0; i < r.virtualNodes; i++ {
vNodeKey := fmt.Sprintf("%s-%d", node, i)
hashKey := r.hash(vNodeKey)
r.store.Delete(hashKey)
delete(r.nodeMap, vNodeKey)
}
delete(r.nodeMap, node)
}
func (r *Ring) Get(key string) (string, error) {
r.mu.RLock()
defer r.mu.RUnlock()
if r.store.Size() == 0 {
return "", ERR_EMPTY_RING
}
var q *rbt.Node
hashKey := r.hash(key)
q = r.store.Nearest(hashKey)
var count int
for {
// Avoid infinite recursion if all the servers are under heavy load
// and if user forgot to call the Done() method
if count >= r.store.Size() {
return "", ERR_HEAVY_LOAD
}
if hashKey > q.GetKey() {
g := rbt.FindSuccessor(q)
if g != nil {
q = g
} else {
// If no successor found, return root(wrap around)
q = r.store.Root()
}
}
if r.loadOK(q.GetValue()) {
break
}
count++
h := rbt.FindSuccessor(q)
if h == nil {
//rewind to start of tree
q = r.store.Minimum()
} else {
q = h
}
}
atomic.AddInt64(&r.nodeMap[q.GetValue()].load, 1)
atomic.AddInt64(&r.totalLoad, 1)
return q.GetValue(), nil
}
func (r *Ring) loadOK(node string) bool {
// a safety check if someone performed r.Done more than needed
if r.totalLoad < 0 {
r.totalLoad = 0
}
var avgLoadPerNode float64
avgLoadPerNode = float64(int(r.totalLoad+1) / (len(r.nodeMap)))
if avgLoadPerNode == 0 {
avgLoadPerNode = 1
}
avgLoadPerNode = math.Ceil(avgLoadPerNode * r.loadFactor)
vnode, ok := r.nodeMap[node]
if !ok {
fmt.Printf("given host(%s) not in loadsMap\n", vnode.name)
return false
}
if float64(vnode.load)+1 <= avgLoadPerNode {
return true
}
return false
}
func (r *Ring) Done(node string) {
if _, ok := r.nodeMap[node]; !ok {
return
}
atomic.AddInt64(&r.nodeMap[node].load, -1)
atomic.AddInt64(&r.totalLoad, -1)
}