OSDN Git Service

edit the connection
[bytom/bytom.git] / p2p / connection / connection.go
1 package connection
2
3 import (
4         "bufio"
5         "fmt"
6         "math"
7         "net"
8         "runtime/debug"
9         "sync/atomic"
10         "time"
11
12         log "github.com/sirupsen/logrus"
13         wire "github.com/tendermint/go-wire"
14         cmn "github.com/tendermint/tmlibs/common"
15         flow "github.com/tendermint/tmlibs/flowrate"
16 )
17
18 const (
19         packetTypePing           = byte(0x01)
20         packetTypePong           = byte(0x02)
21         packetTypeMsg            = byte(0x03)
22         maxMsgPacketPayloadSize  = 1024
23         maxMsgPacketOverheadSize = 10 // It's actually lower but good enough
24         maxMsgPacketTotalSize    = maxMsgPacketPayloadSize + maxMsgPacketOverheadSize
25
26         numBatchMsgPackets = 10
27         minReadBufferSize  = 1024
28         minWriteBufferSize = 65536
29         updateState        = 2 * time.Second
30         pingTimeout        = 40 * time.Second
31         flushThrottle      = 100 * time.Millisecond
32
33         defaultSendQueueCapacity   = 1
34         defaultSendRate            = int64(512000) // 500KB/s
35         defaultRecvBufferCapacity  = 4096
36         defaultRecvMessageCapacity = 22020096      // 21MB
37         defaultRecvRate            = int64(512000) // 500KB/s
38         defaultSendTimeout         = 10 * time.Second
39 )
40
41 type receiveCbFunc func(chID byte, msgBytes []byte)
42 type errorCbFunc func(interface{})
43
44 // Messages in channels are chopped into smaller msgPackets for multiplexing.
45 type msgPacket struct {
46         ChannelID byte
47         EOF       byte // 1 means message ends here.
48         Bytes     []byte
49 }
50
51 func (p msgPacket) String() string {
52         return fmt.Sprintf("MsgPacket{%X:%X T:%X}", p.ChannelID, p.Bytes, p.EOF)
53 }
54
55 /*
56 MConnection handles message transmission on multiple abstract communication
57 `Channel`s.  Each channel has a globally unique byte id.
58 The byte id and the relative priorities of each `Channel` are configured upon
59 initialization of the connection.
60
61 There are two methods for sending messages:
62         func (m MConnection) Send(chID byte, msg interface{}) bool {}
63         func (m MConnection) TrySend(chID byte, msg interface{}) bool {}
64
65 `Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued
66 for the channel with the given id byte `chID`, or until the request times out.
67 The message `msg` is serialized using the `tendermint/wire` submodule's
68 `WriteBinary()` reflection routine.
69
70 `TrySend(chID, msg)` is a nonblocking call that returns false if the channel's
71 queue is full.
72
73 Inbound message bytes are handled with an onReceive callback function.
74 */
75 type MConnection struct {
76         cmn.BaseService
77
78         conn        net.Conn
79         bufReader   *bufio.Reader
80         bufWriter   *bufio.Writer
81         sendMonitor *flow.Monitor
82         recvMonitor *flow.Monitor
83         send        chan struct{}
84         pong        chan struct{}
85         channels    []*channel
86         channelsIdx map[byte]*channel
87         onReceive   receiveCbFunc
88         onError     errorCbFunc
89         errored     uint32
90         config      *MConnConfig
91
92         quit         chan struct{}
93         flushTimer   *cmn.ThrottleTimer // flush writes as necessary but throttled.
94         pingTimer    *time.Ticker       // send pings periodically
95         chStatsTimer *time.Ticker       // update channel stats periodically
96 }
97
98 // MConnConfig is a MConnection configuration.
99 type MConnConfig struct {
100         SendRate int64 `mapstructure:"send_rate"`
101         RecvRate int64 `mapstructure:"recv_rate"`
102 }
103
104 // DefaultMConnConfig returns the default config.
105 func DefaultMConnConfig() *MConnConfig {
106         return &MConnConfig{
107                 SendRate: defaultSendRate,
108                 RecvRate: defaultRecvRate,
109         }
110 }
111
112 // NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config
113 func NewMConnectionWithConfig(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc, config *MConnConfig) *MConnection {
114         mconn := &MConnection{
115                 conn:        conn,
116                 bufReader:   bufio.NewReaderSize(conn, minReadBufferSize),
117                 bufWriter:   bufio.NewWriterSize(conn, minWriteBufferSize),
118                 sendMonitor: flow.New(0, 0),
119                 recvMonitor: flow.New(0, 0),
120                 send:        make(chan struct{}, 1),
121                 pong:        make(chan struct{}),
122                 channelsIdx: map[byte]*channel{},
123                 channels:    []*channel{},
124                 onReceive:   onReceive,
125                 onError:     onError,
126                 config:      config,
127
128                 pingTimer:    time.NewTicker(pingTimeout),
129                 chStatsTimer: time.NewTicker(updateState),
130         }
131
132         for _, desc := range chDescs {
133                 descCopy := *desc // copy the desc else unsafe access across connections
134                 channel := newChannel(mconn, &descCopy)
135                 mconn.channelsIdx[channel.id] = channel
136                 mconn.channels = append(mconn.channels, channel)
137         }
138         mconn.BaseService = *cmn.NewBaseService(nil, "MConnection", mconn)
139         return mconn
140 }
141
142 // OnStart implements BaseService
143 func (c *MConnection) OnStart() error {
144         c.BaseService.OnStart()
145         c.quit = make(chan struct{})
146         c.flushTimer = cmn.NewThrottleTimer("flush", flushThrottle)
147         go c.sendRoutine()
148         go c.recvRoutine()
149         return nil
150 }
151
152 // OnStop implements BaseService
153 func (c *MConnection) OnStop() {
154         c.BaseService.OnStop()
155         c.flushTimer.Stop()
156         if c.quit != nil {
157                 close(c.quit)
158         }
159         c.conn.Close()
160         // We can't close pong safely here because recvRoutine may write to it after we've
161         // stopped. Though it doesn't need to get closed at all, we close it @ recvRoutine.
162 }
163
164 // CanSend returns true if you can send more data onto the chID, false otherwise
165 func (c *MConnection) CanSend(chID byte) bool {
166         if !c.IsRunning() {
167                 return false
168         }
169
170         channel, ok := c.channelsIdx[chID]
171         if !ok {
172                 return false
173         }
174         return channel.canSend()
175 }
176
177 // Send will queues a message to be sent to channel(blocking).
178 func (c *MConnection) Send(chID byte, msg interface{}) bool {
179         if !c.IsRunning() {
180                 return false
181         }
182
183         channel, ok := c.channelsIdx[chID]
184         if !ok {
185                 log.WithField("chID", chID).Error("cannot send bytes due to unknown channel")
186                 return false
187         }
188
189         if !channel.sendBytes(wire.BinaryBytes(msg)) {
190                 log.WithFields(log.Fields{"chID": chID, "conn": c, "msg": msg}).Error("MConnection send failed")
191                 return false
192         }
193
194         select {
195         case c.send <- struct{}{}:
196         default:
197         }
198         return true
199 }
200
201 // TrySend queues a message to be sent to channel(Nonblocking).
202 func (c *MConnection) TrySend(chID byte, msg interface{}) bool {
203         if !c.IsRunning() {
204                 return false
205         }
206
207         channel, ok := c.channelsIdx[chID]
208         if !ok {
209                 log.WithField("chID", chID).Error("cannot send bytes due to unknown channel")
210                 return false
211         }
212
213         ok = channel.trySendBytes(wire.BinaryBytes(msg))
214         if ok {
215                 select {
216                 case c.send <- struct{}{}:
217                 default:
218                 }
219         }
220         return ok
221 }
222
223 func (c *MConnection) String() string {
224         return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr())
225 }
226
227 func (c *MConnection) flush() {
228         if err := c.bufWriter.Flush(); err != nil {
229                 log.WithField("error", err).Error("MConnection flush failed")
230         }
231 }
232
233 // Catch panics, usually caused by remote disconnects.
234 func (c *MConnection) _recover() {
235         if r := recover(); r != nil {
236                 stack := debug.Stack()
237                 err := cmn.StackError{r, stack}
238                 c.stopForError(err)
239         }
240 }
241
242 // recvRoutine reads msgPackets and reconstructs the message using the channels' "recving" buffer.
243 // After a whole message has been assembled, it's pushed to onReceive().
244 // Blocks depending on how the connection is throttled.
245 func (c *MConnection) recvRoutine() {
246         defer c._recover()
247         defer close(c.pong)
248
249         for {
250                 // Block until .recvMonitor says we can read.
251                 c.recvMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.config.RecvRate), true)
252
253                 // Read packet type
254                 var n int
255                 var err error
256                 pktType := wire.ReadByte(c.bufReader, &n, &err)
257                 c.recvMonitor.Update(int(n))
258                 if err != nil {
259                         if c.IsRunning() {
260                                 log.WithFields(log.Fields{"conn": c, "error": err}).Error("Connection failed @ recvRoutine (reading byte)")
261                                 c.conn.Close()
262                                 c.stopForError(err)
263                         }
264                         return
265                 }
266
267                 // Read more depending on packet type.
268                 switch pktType {
269                 case packetTypePing:
270                         log.Debug("receive Ping")
271                         c.pong <- struct{}{}
272
273                 case packetTypePong:
274                         log.Debug("receive Pong")
275
276                 case packetTypeMsg:
277                         pkt, n, err := msgPacket{}, int(0), error(nil)
278                         wire.ReadBinaryPtr(&pkt, c.bufReader, maxMsgPacketTotalSize, &n, &err)
279                         c.recvMonitor.Update(int(n))
280                         if err != nil {
281                                 if c.IsRunning() {
282                                         log.WithFields(log.Fields{"conn": c, "error": err}).Error("failed on recvRoutine")
283                                         c.stopForError(err)
284                                 }
285                                 return
286                         }
287
288                         channel, ok := c.channelsIdx[pkt.ChannelID]
289                         if !ok || channel == nil {
290                                 cmn.PanicQ(cmn.Fmt("Unknown channel %X", pkt.ChannelID))
291                         }
292
293                         msgBytes, err := channel.recvMsgPacket(pkt)
294                         if err != nil {
295                                 if c.IsRunning() {
296                                         log.WithFields(log.Fields{"conn": c, "error": err}).Error("failed on recvRoutine")
297                                         c.stopForError(err)
298                                 }
299                                 return
300                         }
301
302                         if msgBytes != nil {
303                                 c.onReceive(pkt.ChannelID, msgBytes)
304                         }
305
306                 default:
307                         cmn.PanicSanity(cmn.Fmt("Unknown message type %X", pktType))
308                 }
309         }
310 }
311
312 // Returns true if messages from channels were exhausted.
313 func (c *MConnection) sendMsgPacket() bool {
314         var leastRatio float32 = math.MaxFloat32
315         var leastChannel *channel
316         for _, channel := range c.channels {
317                 if !channel.isSendPending() {
318                         continue
319                 }
320                 if ratio := float32(channel.recentlySent) / float32(channel.priority); ratio < leastRatio {
321                         leastRatio = ratio
322                         leastChannel = channel
323                 }
324         }
325         if leastChannel == nil {
326                 return true
327         }
328
329         n, err := leastChannel.writeMsgPacketTo(c.bufWriter)
330         if err != nil {
331                 log.WithField("error", err).Error("failed to write msgPacket")
332                 c.stopForError(err)
333                 return true
334         }
335         c.sendMonitor.Update(int(n))
336         c.flushTimer.Set()
337         return false
338 }
339
340 // sendRoutine polls for packets to send from channels.
341 func (c *MConnection) sendRoutine() {
342         defer c._recover()
343
344         for {
345                 var n int
346                 var err error
347                 select {
348                 case <-c.flushTimer.Ch:
349                         c.flush()
350                 case <-c.chStatsTimer.C:
351                         for _, channel := range c.channels {
352                                 channel.updateStats()
353                         }
354                 case <-c.pingTimer.C:
355                         log.Debug("send Ping")
356                         wire.WriteByte(packetTypePing, c.bufWriter, &n, &err)
357                         c.sendMonitor.Update(int(n))
358                         c.flush()
359                 case <-c.pong:
360                         log.Debug("send Pong")
361                         wire.WriteByte(packetTypePong, c.bufWriter, &n, &err)
362                         c.sendMonitor.Update(int(n))
363                         c.flush()
364                 case <-c.quit:
365                         return
366                 case <-c.send:
367                         if eof := c.sendSomeMsgPackets(); !eof {
368                                 select {
369                                 case c.send <- struct{}{}:
370                                 default:
371                                 }
372                         }
373                 }
374
375                 if !c.IsRunning() {
376                         return
377                 }
378                 if err != nil {
379                         log.WithFields(log.Fields{"conn": c, "error": err}).Error("Connection failed @ sendRoutine")
380                         c.stopForError(err)
381                         return
382                 }
383         }
384 }
385
386 // Returns true if messages from channels were exhausted.
387 func (c *MConnection) sendSomeMsgPackets() bool {
388         // Block until .sendMonitor says we can write.
389         // Once we're ready we send more than we asked for,
390         // but amortized it should even out.
391         c.sendMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.config.SendRate), true)
392         for i := 0; i < numBatchMsgPackets; i++ {
393                 if c.sendMsgPacket() {
394                         return true
395                 }
396         }
397         return false
398 }
399
400 func (c *MConnection) stopForError(r interface{}) {
401         c.Stop()
402         if atomic.CompareAndSwapUint32(&c.errored, 0, 1) && c.onError != nil {
403                 c.onError(r)
404         }
405 }