-
Notifications
You must be signed in to change notification settings - Fork 0
/
ring.go
126 lines (111 loc) · 2.48 KB
/
ring.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
// Copyright 2017 ibelie, Chen Jie, Joungtao. All rights reserved.
// Use of this source code is governed by The MIT License
// that can be found in the LICENSE file.
package ruid
import (
"crypto/md5"
"fmt"
"log"
"sort"
)
const (
VIRTUAL_NODES = 50
DEFAULT_WEIGHT = 1
)
type Ring struct {
ident Ident
sorted []ID
weights map[string]int
ring map[ID]string
}
func RingKey(ident Ident, node string) ID {
bytes := md5.Sum([]byte(node))
for _, key := range ident.GetIDs(bytes[:]) {
return key
}
return nil
}
func NewRing(ident Ident, nodes ...string) *Ring {
ring := &Ring{ident: ident, weights: make(map[string]int)}
for _, node := range nodes {
ring.weights[node] = DEFAULT_WEIGHT
}
ring.circle()
return ring
}
func WeightedRing(ident Ident, weights map[string]int) *Ring {
ring := &Ring{ident: ident, weights: weights}
ring.circle()
return ring
}
func (r *Ring) Update(weights map[string]int) {
changed := false
for node, weight := range weights {
if w, ok := r.weights[node]; !ok || w != weight {
r.weights[node] = weight
changed = true
}
}
if changed {
r.circle()
}
}
func (r *Ring) Append(nodes ...string) {
for _, node := range nodes {
r.weights[node] = DEFAULT_WEIGHT
}
r.circle()
}
func (r *Ring) Remove(nodes ...string) {
for _, node := range nodes {
delete(r.weights, node)
}
r.circle()
}
func (r *Ring) Get(key ID) (node string, ok bool) {
if len(r.ring) <= 0 {
return "", false
}
hash := key.Hash()
pos := sort.Search(len(r.sorted), func(i int) bool { return r.sorted[i].Ge(hash) })
if pos == len(r.sorted) {
pos = 0
}
return r.ring[r.sorted[pos]], true
}
func (r *Ring) circle() {
virtual := VIRTUAL_NODES
total := 0
for _, weight := range r.weights {
total += weight
if virtual < weight {
virtual = weight
}
}
r.ring = make(map[ID]string)
for node, weight := range r.weights {
for i := 0; i < int(len(r.weights)*weight*virtual/total); i++ {
bytes := md5.Sum([]byte(fmt.Sprintf("%s-%d", node, i)))
for _, key := range r.ident.GetIDs(bytes[:]) {
r.ring[key] = node
}
}
}
conflict := make(map[ID]string)
for node, _ := range r.weights {
hash := RingKey(r.ident, node).Hash()
if n, ok := conflict[hash]; ok {
log.Fatalf("[RUID] Ring nodes conflict: %q %q", n, node)
} else {
conflict[hash] = node
r.ring[hash] = node
}
}
r.sorted = nil
for key, _ := range r.ring {
r.sorted = append(r.sorted, key)
}
sort.Slice(r.sorted, func(i int, j int) bool {
return r.sorted[i].Lt(r.sorted[j])
})
}