-
Notifications
You must be signed in to change notification settings - Fork 12
/
routing_table.go
92 lines (76 loc) · 2 KB
/
routing_table.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
package routing
import (
"errors"
"math/rand"
"github.com/benbjohnson/jmphash"
"github.com/cespare/xxhash"
)
type Lookup func(hashKey string) []int
// RoutingTable makes decisions for where a item should be routed.
type RoutingTable struct {
localNode int
addresses map[string]int
replicationFactor uint
hasher *jmphash.Hasher
table []hostRange
}
// NewRoutingTable returns a new RoutingTable.
func NewRoutingTable(localNode int, addrs []string, replicationFactor uint) (*RoutingTable, error) {
if replicationFactor == 0 {
return nil, errors.New("replication factor must be greater than 0")
}
if replicationFactor > uint(len(addrs)) {
return nil, errors.New("replication factor cannot exceed number of available hosts")
}
addresses := make(map[string]int)
for i, addr := range addrs {
addresses[addr] = i
}
t := &RoutingTable{
localNode: localNode,
addresses: addresses,
replicationFactor: replicationFactor,
hasher: jmphash.NewHasher(len(addrs)),
}
return t, nil
}
// Lookup takes a item, hash it and determine what node(s) it should be
// routed to.
func (t *RoutingTable) Lookup(item string) []int {
hashValue := xxhash.Sum64String(item)
node := t.hasher.Hash(hashValue)
var result []int
for n := 0; n < int(t.replicationFactor); n++ {
result = append(result, (node+n)%len(t.addresses))
}
for _, r := range t.table {
if hashValue >= r.start && hashValue <= r.end {
result = append(result, r.hostIndex)
}
}
return result
}
func (t *RoutingTable) IsLocal(metricName string) bool {
clientIndexes := t.Lookup(metricName)
for _, clientIndex := range clientIndexes {
if clientIndex == t.localNode {
return true
}
}
return false
}
func Shuffle(elements []int) {
if len(elements) > 1 {
rand.Shuffle(len(elements), func(i, j int) {
elements[i], elements[j] = elements[j], elements[i]
})
}
}
type rangeInfo struct {
start uint64
end uint64
}
type hostRange struct {
hostIndex int
rangeInfo
}