forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cluster.go
54 lines (46 loc) · 1.12 KB
/
cluster.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
package etcd
import (
"math/rand"
"strings"
"sync"
)
type Cluster struct {
Leader string `json:"leader"`
Machines []string `json:"machines"`
picked int
mu sync.RWMutex
}
func NewCluster(machines []string) *Cluster {
// if an empty slice was sent in then just assume HTTP 4001 on localhost
if len(machines) == 0 {
machines = []string{"http://127.0.0.1:4001"}
}
machines = shuffleStringSlice(machines)
logger.Debug("Shuffle cluster machines", machines)
// default leader and machines
return &Cluster{
Leader: "",
Machines: machines,
picked: rand.Intn(len(machines)),
}
}
func (cl *Cluster) failure() {
cl.mu.Lock()
defer cl.mu.Unlock()
cl.picked = (cl.picked + 1) % len(cl.Machines)
}
func (cl *Cluster) pick() string {
cl.mu.Lock()
defer cl.mu.Unlock()
return cl.Machines[cl.picked]
}
func (cl *Cluster) updateFromStr(machines string) {
cl.mu.Lock()
defer cl.mu.Unlock()
cl.Machines = strings.Split(machines, ",")
for i := range cl.Machines {
cl.Machines[i] = strings.TrimSpace(cl.Machines[i])
}
cl.Machines = shuffleStringSlice(cl.Machines)
cl.picked = rand.Intn(len(cl.Machines))
}