-
Notifications
You must be signed in to change notification settings - Fork 18
/
rolodex_client.go
100 lines (80 loc) · 1.8 KB
/
rolodex_client.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
package meshboi
import (
"encoding/json"
"net"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
type RolodexCallback func(member NetworkMap)
type RolodexClient struct {
networkName string
conn net.Conn
sendRate time.Duration
callback RolodexCallback
quit chan bool
wg *sync.WaitGroup
}
func NewRolodexClient(networkName string, conn net.Conn, sendRate time.Duration, callback RolodexCallback) RolodexClient {
client := RolodexClient{
networkName: networkName,
conn: conn,
sendRate: sendRate,
callback: callback,
quit: make(chan bool),
wg: &sync.WaitGroup{},
}
return client
}
func (c *RolodexClient) Run() {
go c.readLoop()
go c.sendLoop()
c.wg.Add(2)
c.wg.Wait()
}
func (c *RolodexClient) readLoop() {
defer c.wg.Done()
buf := make([]byte, 65535)
for {
n, err := c.conn.Read(buf)
if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
log.Warn("Temporary error reading from rolloConn: ", nerr)
continue
}
if err != nil {
log.Error("Unrecoverable error: ", err)
break
}
var members NetworkMap
if err := json.Unmarshal(buf[:n], &members); err != nil {
log.Error("Error unmarshalling incoming message: ", err.Error())
continue
}
c.callback(members)
}
}
func (c *RolodexClient) sendLoop() {
defer c.wg.Done()
ticker := time.NewTicker(c.sendRate)
for {
heartbeat := HeartbeatMessage{NetworkName: c.networkName}
b, err := json.Marshal(heartbeat)
if err != nil {
log.Fatalln("Error marshalling JSON heartbeat message: ", err)
}
_, err = c.conn.Write(b)
if err != nil {
log.Error("Error sending heartbeat over the rollo conn: ", err)
}
select {
case <-c.quit:
return
case <-ticker.C:
break
}
}
}
func (c *RolodexClient) Stop() {
c.conn.Close()
c.quit <- true
}