This repository has been archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
peers.go
210 lines (186 loc) · 4.85 KB
/
peers.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
209
210
package net
import (
"bufio"
"net"
"strconv"
"strings"
"time"
"github.com/heidi-ann/ios/config"
"github.com/heidi-ann/ios/msgs"
"github.com/golang/glog"
)
type peerHandler struct {
id int
peers []config.NetAddress
failures *msgs.FailureNotifier
net *msgs.PeerNet
}
// iterative through peers and check if there is a handler for each
// try to create one if not, report failure if not possible
func (ph *peerHandler) checkPeer() {
for i := range ph.peers {
if !ph.failures.IsConnected(i) {
cn, err := net.Dial("tcp", ph.peers[i].ToString())
if err == nil {
go ph.handlePeer(cn, true)
} else {
go ph.net.OutgoingUnicast[i].Discard()
}
}
}
}
// handlePeer handles a peer connection until closed
func (ph *peerHandler) handlePeer(cn net.Conn, init bool) {
addr := cn.RemoteAddr().String()
if init {
glog.Info("Outgoing peer connection to ", addr)
} else {
glog.Info("Incoming peer connection from ", addr)
}
defer cn.Close()
defer glog.Warningf("Connection closed from %s ", addr)
// handle requests
reader := bufio.NewReader(cn)
writer := bufio.NewWriter(cn)
// exchange peer ID's via handshake
shake := strconv.Itoa(ph.id) + "\n"
n, err := writer.WriteString(shake)
if err != nil {
glog.Warning(err)
}
if n != len(shake) {
glog.Warning("Short write")
}
err = writer.Flush()
if err != nil {
glog.Warning(err)
}
text, err := reader.ReadString('\n')
if err != nil {
glog.Warning(err)
}
glog.V(1).Info("Received ", text)
peerID, err := strconv.Atoi(strings.Trim(text, "\n"))
if err != nil {
glog.Warning(err)
return
}
// check ID is expected
if peerID < 0 || peerID >= len(ph.peers) || peerID == ph.id {
glog.Warning("Unexpected peer ID ", peerID)
return
}
// check IP address is as expected
// TODO: allow dynamic changes of IP
actualAddr := strings.Split(addr, ":")[0]
if ph.peers[peerID].Address != actualAddr {
glog.Warning("Peer ID ", peerID, " has connected from an unexpected address ", actualAddr,
" expected ", ph.peers[peerID].Address)
return
}
glog.Infof("Ready to handle traffic from peer %d at %s ", peerID, addr)
err = ph.failures.NowConnected(peerID)
if err != nil {
glog.Warning(err)
}
closeErr := make(chan error)
go func() {
for {
// read request
glog.V(1).Infof("Ready for next message from %d", peerID)
text, err := reader.ReadBytes(byte('\n'))
if err != nil {
glog.Warning(err)
closeErr <- err
break
}
glog.V(1).Infof("Read from peer %d: ", peerID, string(text))
err = ph.net.Incoming.BytesToProtoMsg(text)
if err != nil {
glog.Warning(err)
}
}
}()
go func() {
for {
// send reply
glog.V(1).Infof("Ready to send message to %d", peerID)
b, err := ph.net.OutgoingUnicast[peerID].ProtoMsgToBytes()
if err != nil {
glog.Fatal("Could not marshal message")
}
glog.V(1).Infof("Sending to %d: %s", peerID, string(b))
_, err = writer.Write(b)
if err != nil {
glog.Warning(err)
// return packet for retry
ph.net.OutgoingUnicast[peerID].BytesToProtoMsg(b)
closeErr <- err
break
}
_, err = writer.Write([]byte("\n"))
if err != nil {
glog.Warning(err)
// return packet for retry
ph.net.OutgoingUnicast[peerID].BytesToProtoMsg(b)
closeErr <- err
break
}
// TODO: BUG need to retry packet
err = writer.Flush()
if err != nil {
glog.Warning(err)
// return packet for retry
ph.net.OutgoingUnicast[peerID].BytesToProtoMsg(b)
closeErr <- err
break
}
glog.V(1).Info("Sent")
}
}()
// block until connection fails
<-closeErr
// tidy up
glog.Warningf("No longer able to handle traffic from peer %d at %s ", peerID, addr)
ph.failures.NowDisconnected(peerID)
}
// SetupPeers is an async function to handle/start peer connections
// TODO: switch to sync function
func SetupPeers(localId int, addresses []config.NetAddress, peerNet *msgs.PeerNet, fail *msgs.FailureNotifier) error {
peerHandler := peerHandler{
id: localId,
peers: addresses,
failures: fail,
net: peerNet,
}
//set up peer server
glog.Info("Starting up peer server on ", addresses[peerHandler.id].Port)
listeningPort := ":" + strconv.Itoa(addresses[peerHandler.id].Port)
lnPeers, err := net.Listen("tcp", listeningPort)
if err != nil {
glog.Info("Unable to start listen for peers")
return err
}
// handle local peer (without sending network traffic)
peerHandler.failures.NowConnected(peerHandler.id)
from := &(peerHandler.net.Incoming)
go from.Forward(peerHandler.net.OutgoingUnicast[peerHandler.id])
// handle for incoming peers
go func() {
for {
conn, err := lnPeers.Accept()
if err != nil {
glog.Fatal(err)
}
go (&peerHandler).handlePeer(conn, false)
}
}()
// regularly check if all peers are connected and retry if not
go func() {
for {
(&peerHandler).checkPeer()
time.Sleep(500 * time.Millisecond)
}
}()
return nil
}