2014-07-07 20:03:50 -07:00
|
|
|
package p2p
|
2014-06-18 20:48:32 -07:00
|
|
|
|
|
|
|
import (
|
2014-07-03 13:44:19 -07:00
|
|
|
"bufio"
|
2014-07-01 14:50:24 -07:00
|
|
|
"fmt"
|
2014-07-28 01:41:25 -07:00
|
|
|
"io"
|
|
|
|
"math"
|
2014-07-01 14:50:24 -07:00
|
|
|
"net"
|
2014-10-25 01:30:35 -07:00
|
|
|
"runtime/debug"
|
2014-07-01 14:50:24 -07:00
|
|
|
"sync/atomic"
|
|
|
|
"time"
|
2014-07-02 16:03:04 -07:00
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
flow "code.google.com/p/mxk/go1/flowcontrol"
|
2015-01-13 18:06:32 -08:00
|
|
|
"github.com/tendermint/log15"
|
2015-01-14 20:34:53 -08:00
|
|
|
"github.com/tendermint/tendermint/binary"
|
2014-07-02 16:03:04 -07:00
|
|
|
. "github.com/tendermint/tendermint/common"
|
2014-06-18 20:48:32 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2014-12-09 18:49:04 -08:00
|
|
|
numBatchMsgPackets = 10
|
2014-10-04 19:16:49 -07:00
|
|
|
minReadBufferSize = 1024
|
|
|
|
minWriteBufferSize = 1024
|
|
|
|
flushThrottleMS = 50
|
|
|
|
idleTimeoutMinutes = 5
|
|
|
|
updateStatsSeconds = 2
|
|
|
|
pingTimeoutMinutes = 2
|
|
|
|
defaultSendRate = 51200 // 5Kb/s
|
|
|
|
defaultRecvRate = 51200 // 5Kb/s
|
|
|
|
defaultSendQueueCapacity = 1
|
|
|
|
defaultRecvBufferCapacity = 4096
|
2014-06-18 20:48:32 -07:00
|
|
|
)
|
|
|
|
|
2014-09-14 15:37:32 -07:00
|
|
|
type receiveCbFunc func(chId byte, msgBytes []byte)
|
|
|
|
type errorCbFunc func(interface{})
|
|
|
|
|
2014-07-04 14:29:27 -07:00
|
|
|
/*
|
2014-12-23 19:31:24 -08:00
|
|
|
Each peer has one `MConnection` (multiplex connection) instance.
|
|
|
|
|
|
|
|
__multiplex__ *noun* a system or signal involving simultaneous transmission of
|
|
|
|
several messages along a single channel of communication.
|
|
|
|
|
|
|
|
Each `MConnection` handles message transmission on multiple abstract communication
|
|
|
|
`Channel`s. Each channel has a globally unique byte id.
|
|
|
|
The byte id and the relative priorities of each `Channel` are configured upon
|
|
|
|
initialization of the connection.
|
|
|
|
|
|
|
|
There are two methods for sending messages:
|
|
|
|
func (m MConnection) Send(chId byte, msg interface{}) bool {}
|
|
|
|
func (m MConnection) TrySend(chId byte, msg interface{}) bool {}
|
|
|
|
|
|
|
|
`Send(chId, msg)` is a blocking call that waits until `msg` is successfully queued
|
|
|
|
for the channel with the given id byte `chId`. The message `msg` is serialized
|
|
|
|
using the `tendermint/binary` submodule's `WriteBinary()` reflection routine.
|
|
|
|
|
|
|
|
`TrySend(chId, msg)` is a nonblocking call that returns false if the channel's
|
|
|
|
queue is full.
|
|
|
|
|
2014-09-14 15:37:32 -07:00
|
|
|
Inbound message bytes are handled with an onReceive callback function.
|
2014-07-04 14:29:27 -07:00
|
|
|
*/
|
2014-07-28 01:41:25 -07:00
|
|
|
type MConnection struct {
|
|
|
|
conn net.Conn
|
|
|
|
bufReader *bufio.Reader
|
|
|
|
bufWriter *bufio.Writer
|
|
|
|
sendMonitor *flow.Monitor
|
|
|
|
recvMonitor *flow.Monitor
|
|
|
|
sendRate int64
|
|
|
|
recvRate int64
|
|
|
|
flushTimer *ThrottleTimer // flush writes as necessary but throttled.
|
2014-08-03 15:50:28 -07:00
|
|
|
send chan struct{}
|
2014-07-28 01:41:25 -07:00
|
|
|
quit chan struct{}
|
|
|
|
pingTimer *RepeatTimer // send pings periodically
|
|
|
|
pong chan struct{}
|
|
|
|
chStatsTimer *RepeatTimer // update channel stats periodically
|
|
|
|
channels []*Channel
|
|
|
|
channelsIdx map[byte]*Channel
|
2014-09-14 15:37:32 -07:00
|
|
|
onReceive receiveCbFunc
|
|
|
|
onError errorCbFunc
|
2014-07-28 01:41:25 -07:00
|
|
|
started uint32
|
|
|
|
stopped uint32
|
|
|
|
errored uint32
|
|
|
|
|
2014-07-29 23:53:35 -07:00
|
|
|
LocalAddress *NetAddress
|
|
|
|
RemoteAddress *NetAddress
|
2014-06-18 20:48:32 -07:00
|
|
|
}
|
|
|
|
|
2014-09-14 15:37:32 -07:00
|
|
|
func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection {
|
2014-07-28 01:41:25 -07:00
|
|
|
|
|
|
|
mconn := &MConnection{
|
2014-07-29 23:53:35 -07:00
|
|
|
conn: conn,
|
|
|
|
bufReader: bufio.NewReaderSize(conn, minReadBufferSize),
|
|
|
|
bufWriter: bufio.NewWriterSize(conn, minWriteBufferSize),
|
|
|
|
sendMonitor: flow.New(0, 0),
|
|
|
|
recvMonitor: flow.New(0, 0),
|
|
|
|
sendRate: defaultSendRate,
|
|
|
|
recvRate: defaultRecvRate,
|
2015-01-16 00:31:34 -08:00
|
|
|
flushTimer: NewThrottleTimer("flush", flushThrottleMS*time.Millisecond),
|
2014-08-03 15:50:28 -07:00
|
|
|
send: make(chan struct{}, 1),
|
2014-07-29 23:53:35 -07:00
|
|
|
quit: make(chan struct{}),
|
2015-01-16 00:31:34 -08:00
|
|
|
pingTimer: NewRepeatTimer("ping", pingTimeoutMinutes*time.Minute),
|
2014-07-29 23:53:35 -07:00
|
|
|
pong: make(chan struct{}),
|
2015-01-16 00:31:34 -08:00
|
|
|
chStatsTimer: NewRepeatTimer("chStats", updateStatsSeconds*time.Second),
|
2014-09-14 15:37:32 -07:00
|
|
|
onReceive: onReceive,
|
2014-07-29 23:53:35 -07:00
|
|
|
onError: onError,
|
|
|
|
LocalAddress: NewNetAddress(conn.LocalAddr()),
|
|
|
|
RemoteAddress: NewNetAddress(conn.RemoteAddr()),
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// Create channels
|
|
|
|
var channelsIdx = map[byte]*Channel{}
|
|
|
|
var channels = []*Channel{}
|
2014-06-18 20:48:32 -07:00
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
for _, desc := range chDescs {
|
|
|
|
channel := newChannel(mconn, desc)
|
|
|
|
channelsIdx[channel.id] = channel
|
|
|
|
channels = append(channels, channel)
|
2014-07-01 14:50:24 -07:00
|
|
|
}
|
2014-07-28 01:41:25 -07:00
|
|
|
mconn.channels = channels
|
|
|
|
mconn.channelsIdx = channelsIdx
|
|
|
|
|
|
|
|
return mconn
|
2014-06-18 20:48:32 -07:00
|
|
|
}
|
|
|
|
|
2014-07-04 14:29:27 -07:00
|
|
|
// .Start() begins multiplexing packets to and from "channels".
|
2014-07-28 01:41:25 -07:00
|
|
|
func (c *MConnection) Start() {
|
2014-07-04 14:29:27 -07:00
|
|
|
if atomic.CompareAndSwapUint32(&c.started, 0, 1) {
|
2014-12-29 18:39:19 -08:00
|
|
|
log.Debug("Starting MConnection", "connection", c)
|
2014-08-10 16:35:08 -07:00
|
|
|
go c.sendRoutine()
|
|
|
|
go c.recvRoutine()
|
2014-07-04 14:29:27 -07:00
|
|
|
}
|
2014-06-18 20:48:32 -07:00
|
|
|
}
|
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
func (c *MConnection) Stop() {
|
2014-07-01 14:50:24 -07:00
|
|
|
if atomic.CompareAndSwapUint32(&c.stopped, 0, 1) {
|
2014-12-29 18:39:19 -08:00
|
|
|
log.Debug("Stopping MConnection", "connection", c)
|
2014-07-01 14:50:24 -07:00
|
|
|
close(c.quit)
|
|
|
|
c.conn.Close()
|
2014-07-28 01:41:25 -07:00
|
|
|
c.flushTimer.Stop()
|
|
|
|
c.chStatsTimer.Stop()
|
|
|
|
c.pingTimer.Stop()
|
2014-07-01 14:50:24 -07:00
|
|
|
// We can't close pong safely here because
|
2014-08-10 16:35:08 -07:00
|
|
|
// recvRoutine may write to it after we've stopped.
|
2014-07-01 14:50:24 -07:00
|
|
|
// Though it doesn't need to get closed at all,
|
2014-08-10 16:35:08 -07:00
|
|
|
// we close it @ recvRoutine.
|
2014-07-01 14:50:24 -07:00
|
|
|
// close(c.pong)
|
|
|
|
}
|
2014-06-24 17:28:40 -07:00
|
|
|
}
|
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
func (c *MConnection) String() string {
|
2014-10-25 14:27:53 -07:00
|
|
|
return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr())
|
2014-06-29 00:35:16 -07:00
|
|
|
}
|
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
func (c *MConnection) flush() {
|
2014-07-03 14:39:45 -07:00
|
|
|
err := c.bufWriter.Flush()
|
|
|
|
if err != nil {
|
|
|
|
if atomic.LoadUint32(&c.stopped) != 1 {
|
2014-12-29 18:39:19 -08:00
|
|
|
log.Warn("MConnection flush failed", "error", err)
|
2014-07-03 14:39:45 -07:00
|
|
|
}
|
|
|
|
}
|
2014-06-18 20:48:32 -07:00
|
|
|
}
|
|
|
|
|
2014-07-04 14:29:27 -07:00
|
|
|
// Catch panics, usually caused by remote disconnects.
|
2014-07-28 01:41:25 -07:00
|
|
|
func (c *MConnection) _recover() {
|
2014-07-04 14:29:27 -07:00
|
|
|
if r := recover(); r != nil {
|
2014-10-25 01:30:35 -07:00
|
|
|
stack := debug.Stack()
|
|
|
|
err := StackError{r, stack}
|
|
|
|
c.stopForError(err)
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *MConnection) stopForError(r interface{}) {
|
|
|
|
c.Stop()
|
|
|
|
if atomic.CompareAndSwapUint32(&c.errored, 0, 1) {
|
|
|
|
if c.onError != nil {
|
|
|
|
c.onError(r)
|
2014-07-04 14:29:27 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
// Queues a message to be sent to channel.
|
2014-12-09 18:49:04 -08:00
|
|
|
func (c *MConnection) Send(chId byte, msg interface{}) bool {
|
2014-08-03 15:50:28 -07:00
|
|
|
if atomic.LoadUint32(&c.stopped) == 1 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2015-01-14 20:34:53 -08:00
|
|
|
log.Debug("Send", "channel", chId, "connection", c, "msg", msg, "bytes", binary.BinaryBytes(msg))
|
2014-10-25 14:27:53 -07:00
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
// Send message to channel.
|
|
|
|
channel, ok := c.channelsIdx[chId]
|
|
|
|
if !ok {
|
2014-12-29 18:09:06 -08:00
|
|
|
log.Error(Fmt("Cannot send bytes, unknown channel %X", chId))
|
2014-07-28 01:41:25 -07:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2015-01-14 20:34:53 -08:00
|
|
|
channel.sendBytes(binary.BinaryBytes(msg))
|
2014-07-28 01:41:25 -07:00
|
|
|
|
2014-08-10 16:35:08 -07:00
|
|
|
// Wake up sendRoutine if necessary
|
2014-07-28 01:41:25 -07:00
|
|
|
select {
|
2014-08-03 15:50:28 -07:00
|
|
|
case c.send <- struct{}{}:
|
2014-07-28 01:41:25 -07:00
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Queues a message to be sent to channel.
|
|
|
|
// Nonblocking, returns true if successful.
|
2014-12-09 18:49:04 -08:00
|
|
|
func (c *MConnection) TrySend(chId byte, msg interface{}) bool {
|
2014-08-03 15:50:28 -07:00
|
|
|
if atomic.LoadUint32(&c.stopped) == 1 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2014-12-29 18:39:19 -08:00
|
|
|
log.Debug("TrySend", "channel", chId, "connection", c, "msg", msg)
|
2014-10-25 14:27:53 -07:00
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
// Send message to channel.
|
|
|
|
channel, ok := c.channelsIdx[chId]
|
|
|
|
if !ok {
|
2014-12-29 18:09:06 -08:00
|
|
|
log.Error(Fmt("Cannot send bytes, unknown channel %X", chId))
|
2014-07-28 01:41:25 -07:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2015-01-14 20:34:53 -08:00
|
|
|
ok = channel.trySendBytes(binary.BinaryBytes(msg))
|
2014-07-28 01:41:25 -07:00
|
|
|
if ok {
|
2014-08-10 16:35:08 -07:00
|
|
|
// Wake up sendRoutine if necessary
|
2014-07-28 01:41:25 -07:00
|
|
|
select {
|
2014-08-03 15:50:28 -07:00
|
|
|
case c.send <- struct{}{}:
|
2014-07-28 01:41:25 -07:00
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
2014-08-03 15:50:28 -07:00
|
|
|
func (c *MConnection) CanSend(chId byte) bool {
|
|
|
|
if atomic.LoadUint32(&c.stopped) == 1 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
channel, ok := c.channelsIdx[chId]
|
|
|
|
if !ok {
|
2014-12-29 18:09:06 -08:00
|
|
|
log.Error(Fmt("Unknown channel %X", chId))
|
2014-08-10 16:35:08 -07:00
|
|
|
return false
|
2014-08-03 15:50:28 -07:00
|
|
|
}
|
|
|
|
return channel.canSend()
|
|
|
|
}
|
|
|
|
|
2014-08-10 16:35:08 -07:00
|
|
|
// sendRoutine polls for packets to send from channels.
|
|
|
|
func (c *MConnection) sendRoutine() {
|
2014-07-04 14:29:27 -07:00
|
|
|
defer c._recover()
|
2014-07-01 14:50:24 -07:00
|
|
|
|
|
|
|
FOR_LOOP:
|
|
|
|
for {
|
2014-09-03 20:41:57 -07:00
|
|
|
var n int64
|
2014-07-01 14:50:24 -07:00
|
|
|
var err error
|
|
|
|
select {
|
2014-07-28 01:41:25 -07:00
|
|
|
case <-c.flushTimer.Ch:
|
|
|
|
// NOTE: flushTimer.Set() must be called every time
|
|
|
|
// something is written to .bufWriter.
|
2014-07-03 14:39:45 -07:00
|
|
|
c.flush()
|
2014-07-28 01:41:25 -07:00
|
|
|
case <-c.chStatsTimer.Ch:
|
|
|
|
for _, channel := range c.channels {
|
|
|
|
channel.updateStats()
|
|
|
|
}
|
|
|
|
case <-c.pingTimer.Ch:
|
2015-01-13 18:06:32 -08:00
|
|
|
log.Debug("Send Ping")
|
2015-01-14 20:34:53 -08:00
|
|
|
binary.WriteByte(packetTypePing, c.bufWriter, &n, &err)
|
2014-07-28 01:41:25 -07:00
|
|
|
c.sendMonitor.Update(int(n))
|
2014-07-03 14:39:45 -07:00
|
|
|
c.flush()
|
2014-07-01 14:50:24 -07:00
|
|
|
case <-c.pong:
|
2015-01-13 18:06:32 -08:00
|
|
|
log.Debug("Send Pong")
|
2015-01-14 20:34:53 -08:00
|
|
|
binary.WriteByte(packetTypePong, c.bufWriter, &n, &err)
|
2014-07-28 01:41:25 -07:00
|
|
|
c.sendMonitor.Update(int(n))
|
2014-07-03 14:39:45 -07:00
|
|
|
c.flush()
|
2014-07-01 14:50:24 -07:00
|
|
|
case <-c.quit:
|
|
|
|
break FOR_LOOP
|
2014-08-03 15:50:28 -07:00
|
|
|
case <-c.send:
|
2014-12-09 18:49:04 -08:00
|
|
|
// Send some msgPackets
|
|
|
|
eof := c.sendSomeMsgPackets()
|
2014-07-28 01:41:25 -07:00
|
|
|
if !eof {
|
2014-08-10 16:35:08 -07:00
|
|
|
// Keep sendRoutine awake.
|
2014-07-28 01:41:25 -07:00
|
|
|
select {
|
2014-08-03 15:50:28 -07:00
|
|
|
case c.send <- struct{}{}:
|
2014-07-28 01:41:25 -07:00
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
2014-07-01 14:50:24 -07:00
|
|
|
}
|
|
|
|
|
2014-07-02 16:03:04 -07:00
|
|
|
if atomic.LoadUint32(&c.stopped) == 1 {
|
|
|
|
break FOR_LOOP
|
|
|
|
}
|
2014-07-01 14:50:24 -07:00
|
|
|
if err != nil {
|
2014-12-29 18:39:19 -08:00
|
|
|
log.Warn("Connection failed @ sendRoutine", "connection", c, "error", err)
|
2014-12-30 16:49:23 -08:00
|
|
|
c.stopForError(err)
|
2014-07-01 14:50:24 -07:00
|
|
|
break FOR_LOOP
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-07-16 21:13:02 -07:00
|
|
|
// Cleanup
|
2014-06-18 20:48:32 -07:00
|
|
|
}
|
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
// Returns true if messages from channels were exhausted.
|
|
|
|
// Blocks in accordance to .sendMonitor throttling.
|
2014-12-09 18:49:04 -08:00
|
|
|
func (c *MConnection) sendSomeMsgPackets() bool {
|
2014-07-28 01:41:25 -07:00
|
|
|
// Block until .sendMonitor says we can write.
|
|
|
|
// Once we're ready we send more than we asked for,
|
|
|
|
// but amortized it should even out.
|
2014-12-09 18:49:04 -08:00
|
|
|
c.sendMonitor.Limit(maxMsgPacketSize, atomic.LoadInt64(&c.sendRate), true)
|
2014-07-28 01:41:25 -07:00
|
|
|
|
2014-12-09 18:49:04 -08:00
|
|
|
// Now send some msgPackets.
|
|
|
|
for i := 0; i < numBatchMsgPackets; i++ {
|
|
|
|
if c.sendMsgPacket() {
|
2014-07-28 01:41:25 -07:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns true if messages from channels were exhausted.
|
2014-12-09 18:49:04 -08:00
|
|
|
func (c *MConnection) sendMsgPacket() bool {
|
|
|
|
// Choose a channel to create a msgPacket from.
|
2014-07-28 01:41:25 -07:00
|
|
|
// The chosen channel will be the one whose recentlySent/priority is the least.
|
|
|
|
var leastRatio float32 = math.MaxFloat32
|
|
|
|
var leastChannel *Channel
|
|
|
|
for _, channel := range c.channels {
|
|
|
|
// If nothing to send, skip this channel
|
2014-09-14 15:37:32 -07:00
|
|
|
if !channel.isSendPending() {
|
2014-07-28 01:41:25 -07:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
// Get ratio, and keep track of lowest ratio.
|
|
|
|
ratio := float32(channel.recentlySent) / float32(channel.priority)
|
|
|
|
if ratio < leastRatio {
|
|
|
|
leastRatio = ratio
|
|
|
|
leastChannel = channel
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Nothing to send?
|
|
|
|
if leastChannel == nil {
|
|
|
|
return true
|
|
|
|
} else {
|
2014-12-09 18:49:04 -08:00
|
|
|
// log.Debug("Found a msgPacket to send")
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
|
2014-12-09 18:49:04 -08:00
|
|
|
// Make & send a msgPacket from this channel
|
|
|
|
n, err := leastChannel.writeMsgPacketTo(c.bufWriter)
|
2014-07-28 01:41:25 -07:00
|
|
|
if err != nil {
|
2014-12-29 18:39:19 -08:00
|
|
|
log.Warn("Failed to write msgPacket", "error", err)
|
2014-07-28 01:41:25 -07:00
|
|
|
c.stopForError(err)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
c.sendMonitor.Update(int(n))
|
|
|
|
c.flushTimer.Set()
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2014-12-09 18:49:04 -08:00
|
|
|
// recvRoutine reads msgPackets and reconstructs the message using the channels' "recving" buffer.
|
2014-09-14 15:37:32 -07:00
|
|
|
// After a whole message has been assembled, it's pushed to onReceive().
|
2014-07-28 01:41:25 -07:00
|
|
|
// Blocks depending on how the connection is throttled.
|
2014-08-10 16:35:08 -07:00
|
|
|
func (c *MConnection) recvRoutine() {
|
2014-07-04 14:29:27 -07:00
|
|
|
defer c._recover()
|
2014-07-01 14:50:24 -07:00
|
|
|
|
|
|
|
FOR_LOOP:
|
|
|
|
for {
|
2014-07-28 01:41:25 -07:00
|
|
|
// Block until .recvMonitor says we can read.
|
2014-12-09 18:49:04 -08:00
|
|
|
c.recvMonitor.Limit(maxMsgPacketSize, atomic.LoadInt64(&c.recvRate), true)
|
2014-07-28 01:41:25 -07:00
|
|
|
|
2014-12-29 18:39:19 -08:00
|
|
|
// Peek into bufReader for debugging
|
2014-12-29 19:59:06 -08:00
|
|
|
if numBytes := c.bufReader.Buffered(); numBytes > 0 {
|
2015-01-13 18:06:32 -08:00
|
|
|
log.Debug("Peek connection buffer", "numBytes", numBytes, "bytes", log15.Lazy{func() []byte {
|
2014-12-29 19:59:06 -08:00
|
|
|
bytes, err := c.bufReader.Peek(MinInt(numBytes, 100))
|
|
|
|
if err == nil {
|
|
|
|
return bytes
|
|
|
|
} else {
|
|
|
|
log.Warn("Error peeking connection buffer", "error", err)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}})
|
|
|
|
}
|
2014-12-29 18:39:19 -08:00
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
// Read packet type
|
2014-09-03 20:41:57 -07:00
|
|
|
var n int64
|
|
|
|
var err error
|
2015-01-14 20:34:53 -08:00
|
|
|
pktType := binary.ReadByte(c.bufReader, &n, &err)
|
2014-07-28 01:41:25 -07:00
|
|
|
c.recvMonitor.Update(int(n))
|
2014-07-01 14:50:24 -07:00
|
|
|
if err != nil {
|
|
|
|
if atomic.LoadUint32(&c.stopped) != 1 {
|
2014-12-29 18:39:19 -08:00
|
|
|
log.Warn("Connection failed @ recvRoutine", "connection", c, "error", err)
|
2014-12-30 16:49:23 -08:00
|
|
|
c.stopForError(err)
|
2014-07-01 14:50:24 -07:00
|
|
|
}
|
|
|
|
break FOR_LOOP
|
|
|
|
}
|
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
// Read more depending on packet type.
|
2014-07-01 14:50:24 -07:00
|
|
|
switch pktType {
|
2014-07-09 14:32:45 -07:00
|
|
|
case packetTypePing:
|
2014-07-28 01:41:25 -07:00
|
|
|
// TODO: prevent abuse, as they cause flush()'s.
|
2015-01-13 18:06:32 -08:00
|
|
|
log.Debug("Receive Ping")
|
2014-07-01 14:50:24 -07:00
|
|
|
c.pong <- struct{}{}
|
2014-07-09 14:32:45 -07:00
|
|
|
case packetTypePong:
|
2014-07-01 14:50:24 -07:00
|
|
|
// do nothing
|
2015-01-13 18:06:32 -08:00
|
|
|
log.Debug("Receive Pong")
|
2014-12-09 18:49:04 -08:00
|
|
|
case packetTypeMsg:
|
|
|
|
pkt, n, err := msgPacket{}, new(int64), new(error)
|
2015-01-14 20:34:53 -08:00
|
|
|
binary.ReadBinary(&pkt, c.bufReader, n, err)
|
2014-12-09 18:49:04 -08:00
|
|
|
c.recvMonitor.Update(int(*n))
|
|
|
|
if *err != nil {
|
2014-07-01 14:50:24 -07:00
|
|
|
if atomic.LoadUint32(&c.stopped) != 1 {
|
2014-12-30 16:49:23 -08:00
|
|
|
log.Warn("Connection failed @ recvRoutine", "connection", c, "error", *err)
|
|
|
|
c.stopForError(*err)
|
2014-07-01 14:50:24 -07:00
|
|
|
}
|
|
|
|
break FOR_LOOP
|
|
|
|
}
|
2014-10-25 01:30:35 -07:00
|
|
|
channel, ok := c.channelsIdx[pkt.ChannelId]
|
|
|
|
if !ok || channel == nil {
|
2014-12-29 18:09:06 -08:00
|
|
|
panic(Fmt("Unknown channel %X", pkt.ChannelId))
|
2014-07-01 14:50:24 -07:00
|
|
|
}
|
2014-12-09 18:49:04 -08:00
|
|
|
msgBytes := channel.recvMsgPacket(pkt)
|
2014-09-14 15:37:32 -07:00
|
|
|
if msgBytes != nil {
|
|
|
|
c.onReceive(pkt.ChannelId, msgBytes)
|
|
|
|
}
|
2014-07-01 14:50:24 -07:00
|
|
|
default:
|
2014-12-29 18:09:06 -08:00
|
|
|
panic(Fmt("Unknown message type %X", pktType))
|
2014-07-01 14:50:24 -07:00
|
|
|
}
|
|
|
|
|
2014-08-10 16:35:08 -07:00
|
|
|
// TODO: shouldn't this go in the sendRoutine?
|
2014-12-09 18:49:04 -08:00
|
|
|
// Better to send a ping packet when *we* haven't sent anything for a while.
|
2014-07-28 01:41:25 -07:00
|
|
|
c.pingTimer.Reset()
|
2014-07-01 14:50:24 -07:00
|
|
|
}
|
|
|
|
|
2014-07-16 21:13:02 -07:00
|
|
|
// Cleanup
|
2014-07-01 14:50:24 -07:00
|
|
|
close(c.pong)
|
|
|
|
for _ = range c.pong {
|
2014-07-16 21:13:02 -07:00
|
|
|
// Drain
|
2014-07-01 14:50:24 -07:00
|
|
|
}
|
2014-06-18 20:48:32 -07:00
|
|
|
}
|
|
|
|
|
2014-07-28 01:41:25 -07:00
|
|
|
//-----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
type ChannelDescriptor struct {
|
2014-10-04 19:16:49 -07:00
|
|
|
Id byte
|
|
|
|
Priority uint
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: lowercase.
|
|
|
|
// NOTE: not goroutine-safe.
|
|
|
|
type Channel struct {
|
2014-08-03 15:50:28 -07:00
|
|
|
conn *MConnection
|
|
|
|
desc *ChannelDescriptor
|
|
|
|
id byte
|
2014-09-03 20:41:57 -07:00
|
|
|
sendQueue chan []byte
|
2014-08-03 15:50:28 -07:00
|
|
|
sendQueueSize uint32
|
2014-09-03 20:41:57 -07:00
|
|
|
recving []byte
|
|
|
|
sending []byte
|
2014-08-03 15:50:28 -07:00
|
|
|
priority uint
|
|
|
|
recentlySent int64 // exponential moving average
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func newChannel(conn *MConnection, desc *ChannelDescriptor) *Channel {
|
2014-10-04 19:16:49 -07:00
|
|
|
if desc.Priority <= 0 {
|
2014-07-28 01:41:25 -07:00
|
|
|
panic("Channel default priority must be a postive integer")
|
|
|
|
}
|
|
|
|
return &Channel{
|
|
|
|
conn: conn,
|
|
|
|
desc: desc,
|
|
|
|
id: desc.Id,
|
2014-10-04 19:16:49 -07:00
|
|
|
sendQueue: make(chan []byte, defaultSendQueueCapacity),
|
|
|
|
recving: make([]byte, 0, defaultRecvBufferCapacity),
|
|
|
|
priority: desc.Priority,
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Queues message to send to this channel.
|
2014-08-03 15:50:28 -07:00
|
|
|
// Goroutine-safe
|
2014-09-03 20:41:57 -07:00
|
|
|
func (ch *Channel) sendBytes(bytes []byte) {
|
2014-07-28 01:41:25 -07:00
|
|
|
ch.sendQueue <- bytes
|
2014-08-03 15:50:28 -07:00
|
|
|
atomic.AddUint32(&ch.sendQueueSize, 1)
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// Queues message to send to this channel.
|
|
|
|
// Nonblocking, returns true if successful.
|
2014-08-03 15:50:28 -07:00
|
|
|
// Goroutine-safe
|
2014-09-03 20:41:57 -07:00
|
|
|
func (ch *Channel) trySendBytes(bytes []byte) bool {
|
2014-07-28 01:41:25 -07:00
|
|
|
select {
|
|
|
|
case ch.sendQueue <- bytes:
|
2014-08-03 15:50:28 -07:00
|
|
|
atomic.AddUint32(&ch.sendQueueSize, 1)
|
2014-07-28 01:41:25 -07:00
|
|
|
return true
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-08-03 15:50:28 -07:00
|
|
|
// Goroutine-safe
|
2014-08-10 16:35:08 -07:00
|
|
|
func (ch *Channel) loadSendQueueSize() (size int) {
|
2014-08-03 15:50:28 -07:00
|
|
|
return int(atomic.LoadUint32(&ch.sendQueueSize))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Goroutine-safe
|
|
|
|
// Use only as a heuristic.
|
|
|
|
func (ch *Channel) canSend() bool {
|
2014-10-04 19:16:49 -07:00
|
|
|
return ch.loadSendQueueSize() < defaultSendQueueCapacity
|
2014-08-03 15:50:28 -07:00
|
|
|
}
|
|
|
|
|
2014-12-09 18:49:04 -08:00
|
|
|
// Returns true if any msgPackets are pending to be sent.
|
|
|
|
// Call before calling nextMsgPacket()
|
2014-08-03 15:50:28 -07:00
|
|
|
// Goroutine-safe
|
2014-09-14 15:37:32 -07:00
|
|
|
func (ch *Channel) isSendPending() bool {
|
2014-07-28 01:41:25 -07:00
|
|
|
if len(ch.sending) == 0 {
|
|
|
|
if len(ch.sendQueue) == 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
ch.sending = <-ch.sendQueue
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2014-12-09 18:49:04 -08:00
|
|
|
// Creates a new msgPacket to send.
|
2014-08-03 15:50:28 -07:00
|
|
|
// Not goroutine-safe
|
2014-12-09 18:49:04 -08:00
|
|
|
func (ch *Channel) nextMsgPacket() msgPacket {
|
|
|
|
packet := msgPacket{}
|
2014-09-03 20:41:57 -07:00
|
|
|
packet.ChannelId = byte(ch.id)
|
2014-12-09 18:49:04 -08:00
|
|
|
packet.Bytes = ch.sending[:MinInt(maxMsgPacketSize, len(ch.sending))]
|
|
|
|
if len(ch.sending) <= maxMsgPacketSize {
|
2014-09-03 20:41:57 -07:00
|
|
|
packet.EOF = byte(0x01)
|
2014-07-28 01:41:25 -07:00
|
|
|
ch.sending = nil
|
2014-08-03 15:50:28 -07:00
|
|
|
atomic.AddUint32(&ch.sendQueueSize, ^uint32(0)) // decrement sendQueueSize
|
2014-07-28 01:41:25 -07:00
|
|
|
} else {
|
2014-09-03 20:41:57 -07:00
|
|
|
packet.EOF = byte(0x00)
|
2014-12-09 18:49:04 -08:00
|
|
|
ch.sending = ch.sending[MinInt(maxMsgPacketSize, len(ch.sending)):]
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
return packet
|
|
|
|
}
|
|
|
|
|
2014-12-09 18:49:04 -08:00
|
|
|
// Writes next msgPacket to w.
|
2014-08-03 15:50:28 -07:00
|
|
|
// Not goroutine-safe
|
2014-12-09 18:49:04 -08:00
|
|
|
func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int64, err error) {
|
|
|
|
packet := ch.nextMsgPacket()
|
2015-01-14 20:34:53 -08:00
|
|
|
binary.WriteByte(packetTypeMsg, w, &n, &err)
|
|
|
|
binary.WriteBinary(packet, w, &n, &err)
|
2014-07-28 01:41:25 -07:00
|
|
|
if err != nil {
|
|
|
|
ch.recentlySent += n
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-12-09 18:49:04 -08:00
|
|
|
// Handles incoming msgPackets. Returns a msg bytes if msg is complete.
|
2014-08-03 15:50:28 -07:00
|
|
|
// Not goroutine-safe
|
2014-12-09 18:49:04 -08:00
|
|
|
func (ch *Channel) recvMsgPacket(pkt msgPacket) []byte {
|
2014-07-28 01:41:25 -07:00
|
|
|
ch.recving = append(ch.recving, pkt.Bytes...)
|
2014-09-03 20:41:57 -07:00
|
|
|
if pkt.EOF == byte(0x01) {
|
2014-09-14 15:37:32 -07:00
|
|
|
msgBytes := ch.recving
|
2014-10-04 19:16:49 -07:00
|
|
|
ch.recving = make([]byte, 0, defaultRecvBufferCapacity)
|
2014-09-14 15:37:32 -07:00
|
|
|
return msgBytes
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
2014-09-14 15:37:32 -07:00
|
|
|
return nil
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// Call this periodically to update stats for throttling purposes.
|
2014-08-03 15:50:28 -07:00
|
|
|
// Not goroutine-safe
|
2014-07-28 01:41:25 -07:00
|
|
|
func (ch *Channel) updateStats() {
|
|
|
|
// Exponential decay of stats.
|
|
|
|
// TODO: optimize.
|
|
|
|
ch.recentlySent = int64(float64(ch.recentlySent) * 0.5)
|
|
|
|
}
|
|
|
|
|
|
|
|
//-----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
const (
|
2014-12-09 18:49:04 -08:00
|
|
|
maxMsgPacketSize = 1024
|
|
|
|
packetTypePing = byte(0x00)
|
|
|
|
packetTypePong = byte(0x01)
|
|
|
|
packetTypeMsg = byte(0x10)
|
2014-07-28 01:41:25 -07:00
|
|
|
)
|
|
|
|
|
2014-12-09 18:49:04 -08:00
|
|
|
// Messages in channels are chopped into smaller msgPackets for multiplexing.
|
|
|
|
type msgPacket struct {
|
2014-09-03 20:41:57 -07:00
|
|
|
ChannelId byte
|
|
|
|
EOF byte // 1 means message ends here.
|
|
|
|
Bytes []byte
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
|
2014-12-09 18:49:04 -08:00
|
|
|
func (p msgPacket) String() string {
|
|
|
|
return fmt.Sprintf("MsgPacket{%X:%X}", p.ChannelId, p.Bytes)
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
//-----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
// Convenience struct for writing typed messages.
|
2014-09-03 20:41:57 -07:00
|
|
|
// Reading requires a custom decoder that switches on the first type byte of a byteslice.
|
2014-07-28 01:41:25 -07:00
|
|
|
type TypedMessage struct {
|
2014-09-03 20:41:57 -07:00
|
|
|
Type byte
|
2014-12-09 18:49:04 -08:00
|
|
|
Msg interface{}
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (tm TypedMessage) String() string {
|
2014-10-25 14:27:53 -07:00
|
|
|
return fmt.Sprintf("TMsg{%X:%v}", tm.Type, tm.Msg)
|
2014-07-28 01:41:25 -07:00
|
|
|
}
|