-
Notifications
You must be signed in to change notification settings - Fork 76
/
util.go
86 lines (75 loc) · 1.32 KB
/
util.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
package paxi
import (
"encoding/gob"
"fmt"
"net"
"time"
"github.com/ailidani/paxi/log"
)
// Max of two int
func Max(a, b int) int {
if a < b {
return b
}
return a
}
// VMax of a vector
func VMax(v ...int) int {
max := v[0]
for _, i := range v {
if max < i {
max = i
}
}
return max
}
// Retry function f sleep time between attempts
func Retry(f func() error, attempts int, sleep time.Duration) error {
var err error
for i := 0; ; i++ {
err = f()
if err == nil {
return nil
}
if i >= attempts-1 {
break
}
// exponential delay
time.Sleep(sleep * time.Duration(i+1))
}
return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
}
// Schedule repeatedly call function with intervals
func Schedule(f func(), delay time.Duration) chan bool {
stop := make(chan bool)
go func() {
for {
f()
select {
case <-time.After(delay):
case <-stop:
return
}
}
}()
return stop
}
// ConnectToMaster connects to master node and set global Config
func ConnectToMaster(addr string, client bool, id ID) {
conn, err := net.Dial("tcp", addr)
if err != nil {
log.Fatal(err)
}
dec := gob.NewDecoder(conn)
enc := gob.NewEncoder(conn)
msg := &Register{
ID: id,
Client: client,
Addr: "",
}
enc.Encode(msg)
err = dec.Decode(&config)
if err != nil {
log.Fatal(err)
}
}