-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode.go
208 lines (179 loc) · 4.94 KB
/
node.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package gossip
import (
context "context"
"errors"
"fmt"
"log"
"math/rand"
"net"
"time"
codes "google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/grpc"
)
const bufferCap = 256
const neighborListCap = 256
const gossipFanout = 16
const discoveryFanout = 8
const broadcastFanout = neighborListCap
type NodeId string
func NewNodeId(str string) NodeId {
return NodeId(str)
}
func (id NodeId) Dial() (*grpc.ClientConn, error) {
return grpc.Dial(string(id), grpc.WithInsecure())
}
func (id NodeId) String() string {
return string(id)
}
type Node struct {
topic string
nodeId NodeId
neighbors *NeighborList
msgFilter *Filter
msgChan chan []byte
}
func New(nodeId NodeId, topic string) *Node {
node := &Node{
topic: topic,
nodeId: nodeId,
neighbors: NewNeighborList(neighborListCap),
msgChan: make(chan []byte, bufferCap),
msgFilter: NewFilter(60),
}
node.neighbors.AddBlackList(nodeId)
return node
}
func (node *Node) Listen() error {
lis, err := net.Listen("tcp", node.nodeId.String())
if err != nil {
return errors.New(fmt.Sprintf("[gossip] Cannot listen on %s: %s", node.nodeId.String(), err.Error()))
}
grpcServer := grpc.NewServer()
RegisterGossipServer(grpcServer, node)
grpcServer.Serve(lis)
return nil
}
func (node *Node) Register(grpcServer *grpc.Server) {
RegisterGossipServer(grpcServer, node)
}
func (node *Node) GetPeers(ctx context.Context, req *NeighborReq) (*NeighborRes, error) {
if req.Topic != node.topic {
return nil, status.Errorf(codes.NotFound, "[From %s] topic does not match", node.nodeId.String())
}
nodeId := NewNodeId(req.NodeId)
node.neighbors.Update(nodeId)
samples := node.neighbors.SampleIdString(int(req.MaxNum))
res := &NeighborRes{
Topic: node.topic,
NodeId: node.nodeId.String(),
Neighbors: samples,
}
return res, nil
}
func (node *Node) SendData(ctx context.Context, data *GossipData) (*Empty, error) {
if data.Topic != node.topic {
return nil, status.Errorf(codes.NotFound, "[From %s] topic does not match", node.nodeId.String())
}
nodeId := NewNodeId(data.NodeId)
node.neighbors.Update(nodeId)
// check redundancy and store in buffer
if !node.msgFilter.Check(data.Hash()) {
return nil, status.Errorf(codes.NotFound, "[From %s] already received the same message", node.nodeId.String())
}
node.msgChan <- data.Payload
//gossip to other nodes
node.gossipToPeers(data, gossipFanout)
return &Empty{}, nil
}
func (node *Node) gossipToPeers(data *GossipData, fanout int) {
nodeIds := node.neighbors.SampleNodeId(fanout)
for i := range nodeIds {
go func(nodeId NodeId) {
conn, err := node.neighbors.GetConn(nodeId)
if err != nil {
log.Printf("[gossip] Connection to %s is closed", nodeId.String())
return
}
client := NewGossipClient(conn)
_, err = client.SendData(context.Background(), data)
if err != nil && status.Convert(err).Code() != codes.NotFound {
log.Printf("[gossip] Cannot send data to node %s: %s", nodeId.String(), err.Error())
node.neighbors.Reconnect(nodeId)
}
}(nodeIds[i])
}
}
func (node *Node) Join(bootnodes []NodeId) error {
// add to neighbor list
for i := range bootnodes {
node.neighbors.Update(bootnodes[i])
}
go func() {
// run discovery forever
for {
// whether not enough peers
if node.neighbors.Len() >= neighborListCap {
time.Sleep(5 * time.Second)
continue
}
// how many peers to ask
fanout := discoveryFanout
if fanout > node.neighbors.Len() {
fanout = node.neighbors.Len()
}
// construct request
avgReqests := int(float32(neighborListCap-node.neighbors.Len()) / float32(fanout) * 1.2)
req := &NeighborReq{
Topic: node.topic,
NodeId: node.nodeId.String(),
MaxNum: int32(avgReqests),
}
nodeIds := node.neighbors.SampleNodeId(fanout)
for i := range nodeIds {
go func(nodeId NodeId) {
conn, err := node.neighbors.GetConn(nodeId)
if err != nil {
log.Printf("[gossip] connection to %s is closed", nodeId.String())
return
}
client := NewGossipClient(conn)
res, err := client.GetPeers(context.Background(), req)
if err != nil {
log.Printf("[gossip] node %s cannot call GetPeer: %s", nodeId.String(), err.Error())
node.neighbors.Reconnect(nodeId)
return
}
for j := range res.Neighbors {
node.neighbors.Update(NewNodeId(res.Neighbors[j]))
}
}(nodeIds[i])
}
time.Sleep(5 * time.Second)
}
}()
return nil
}
func (node *Node) Gossip(data []byte) {
nonce := rand.Uint64()
gossipData := &GossipData{
Topic: node.topic,
NodeId: node.nodeId.String(),
Nonce: nonce,
Payload: data,
}
// gossip to self
if node.msgFilter.Check(gossipData.Hash()) {
node.msgChan <- data
}
node.gossipToPeers(gossipData, broadcastFanout)
}
func (node *Node) GetMsgChan() chan []byte {
return node.msgChan
}
func (node *Node) PrintPeers() {
node.neighbors.Print()
}
func (node *Node) GetNeighborList() *NeighborList {
return node.neighbors
}