-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathpeer.go
203 lines (186 loc) · 3.78 KB
/
peer.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
package p2p
import (
"bytes"
"github.com/xfs-network/xlibp2p/discover"
"github.com/xfs-network/xlibp2p/log"
"io"
"net"
"time"
)
const pingloopinterval = 1
const aliveloopinterval = 10
const alivemaxinterval = 30
type encoder interface {
Encode(obj interface{}) ([]byte, error)
}
type Peer interface {
Is(flag int) bool
ID() discover.NodeId
Close()
Run()
CloseCh() chan struct{}
Read(bs []byte) (int, error)
WriteMessage(mType uint8, data []byte) error
WriteMessageObj(mType uint8, data interface{}) error
GetProtocolMsgCh() chan MessageReader
}
type peer struct {
id discover.NodeId
conn *peerConn
rw net.Conn
close chan struct{}
lastTime int64
readBuf bytes.Buffer
ps []Protocol
quit chan struct{}
psCh chan MessageReader
encoder encoder
logger log.Logger
}
// create peer [Peer to peer connection session,Network protocol]
func newPeer(conn *peerConn, ps []Protocol, en encoder) Peer {
p := &peer{
conn: conn,
id: conn.id,
rw: conn.rw,
logger: conn.logger,
ps: ps,
close: make(chan struct{}),
psCh: make(chan MessageReader),
encoder: en,
}
now := time.Now()
p.lastTime = now.Unix()
return p
}
func (p *peer) ID() discover.NodeId {
return p.id
}
func (p *peer) CloseCh() chan struct{} {
return p.close
}
func (p *peer) Is(flag int) bool {
return p.conn.flag & flag != 0
}
// Read heartbeat message
func (p *peer) readLoop() {
for {
select {
case <-p.close:
return
default:
}
msg, err := ReadMessage(p.rw)
if err != nil {
return
}
p.handle(msg)
}
}
func (p *peer) handle(msg MessageReader) {
data, err := msg.ReadAll()
if err != nil {
return
}
//p.logger.Infof("peer handle message type %d, data: %s", msg.Type(), string(data))
switch msg.Type() {
case typePingMsg:
p.logger.Debugln("receive heartbeat request")
err = p.conn.writeMessage(typePongMsg, []byte("hello"))
if err != nil {
p.Close()
}
case typePongMsg:
p.logger.Debugln("receive response of heartbeat and update alive time")
now := time.Now()
p.lastTime = now.Unix()
default:
bodyBs := msg.RawReader()
cpy := &messageReader{
raw: bodyBs,
mType: msg.Type(),
data: bytes.NewReader(data),
}
p.psCh <- cpy
_, _ = io.Copy(&p.readBuf, bodyBs)
}
}
func (p *peer) Read(bs []byte) (int, error) {
return p.readBuf.Read(bs)
}
func (p *peer) GetProtocolMsgCh() chan MessageReader {
return p.psCh
}
func (p *peer) WriteMessage(mType uint8, bs []byte) error {
return p.conn.writeMessage(mType, bs)
}
func (p *peer) WriteMessageObj(mType uint8, obj interface{}) error {
bs, err := p.encoder.Encode(obj)
if err != nil {
return err
}
p.logger.Debugln("peer write message type: %d, data: %x, obj: %v", mType, bs, obj)
return p.WriteMessage(mType, bs)
}
func (p *peer) pingLoop() {
ping := time.NewTicker(pingloopinterval * time.Second)
defer ping.Stop()
for {
select {
case <-ping.C:
if err := p.conn.writeMessage(typePingMsg, []byte("hello")); err != nil {
p.Close()
return
}
case <-p.close:
return
}
}
}
func (p *peer) suicide(timout chan struct{}) {
defer close(timout)
for {
select {
case <-p.close:
return
default:
}
now := time.Now()
nowTime := now.Unix()
interval := nowTime - p.lastTime
// 10s
if interval > alivemaxinterval {
p.logger.Debugln("peer stop running because of timeout")
p.Close()
break
}
time.Sleep(aliveloopinterval * time.Second)
}
}
func (p *peer) Run() {
go p.readLoop()
go p.pingLoop()
runProtocol := func() {
for _, item := range p.ps {
go func(p *peer, item Protocol) {
err := item.Run(p)
if err != nil {
p.Close()
}
}(p, item)
}
}
runProtocol()
timout := make(chan struct{})
go p.suicide(timout)
loop:
for {
select {
case <-timout:
break loop
}
}
}
func (p *peer) Close() {
close(p.close)
}