2015-10-25 18:21:51 -07:00
|
|
|
package p2p
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"math"
|
|
|
|
"net"
|
|
|
|
"runtime/debug"
|
|
|
|
"sync/atomic"
|
|
|
|
"time"
|
|
|
|
|
2017-04-04 08:28:28 -07:00
|
|
|
cmn "github.com/tendermint/go-common"
|
2016-05-08 14:59:27 -07:00
|
|
|
cfg "github.com/tendermint/go-config"
|
2016-12-04 18:20:18 -08:00
|
|
|
flow "github.com/tendermint/go-flowrate/flowrate"
|
2017-04-04 08:28:28 -07:00
|
|
|
wire "github.com/tendermint/go-wire"
|
2015-10-25 18:21:51 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2016-05-08 14:59:27 -07:00
|
|
|
numBatchMsgPackets = 10
|
|
|
|
minReadBufferSize = 1024
|
|
|
|
minWriteBufferSize = 65536
|
2017-04-04 13:14:24 -07:00
|
|
|
updateState = 2 * time.Second
|
|
|
|
pingTimeout = 40 * time.Second
|
|
|
|
flushThrottle = 100 * time.Millisecond
|
2016-05-08 14:59:27 -07:00
|
|
|
|
2015-11-10 12:29:43 -08:00
|
|
|
defaultSendQueueCapacity = 1
|
|
|
|
defaultRecvBufferCapacity = 4096
|
|
|
|
defaultRecvMessageCapacity = 22020096 // 21MB
|
2017-04-04 13:14:24 -07:00
|
|
|
defaultSendTimeout = 10 * time.Second
|
2015-10-25 18:21:51 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
type receiveCbFunc func(chID byte, msgBytes []byte)
|
|
|
|
type errorCbFunc func(interface{})
|
|
|
|
|
|
|
|
/*
|
|
|
|
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`, or until the request times out.
|
|
|
|
The message `msg` is serialized using the `tendermint/wire` submodule's
|
|
|
|
`WriteBinary()` reflection routine.
|
|
|
|
|
|
|
|
`TrySend(chID, msg)` is a nonblocking call that returns false if the channel's
|
|
|
|
queue is full.
|
|
|
|
|
|
|
|
Inbound message bytes are handled with an onReceive callback function.
|
|
|
|
*/
|
|
|
|
type MConnection struct {
|
2017-04-04 08:28:28 -07:00
|
|
|
cmn.BaseService
|
2015-10-25 18:21:51 -07:00
|
|
|
|
|
|
|
conn net.Conn
|
|
|
|
bufReader *bufio.Reader
|
|
|
|
bufWriter *bufio.Writer
|
|
|
|
sendMonitor *flow.Monitor
|
|
|
|
recvMonitor *flow.Monitor
|
|
|
|
sendRate int64
|
|
|
|
recvRate int64
|
|
|
|
send chan struct{}
|
|
|
|
pong chan struct{}
|
|
|
|
channels []*Channel
|
|
|
|
channelsIdx map[byte]*Channel
|
|
|
|
onReceive receiveCbFunc
|
|
|
|
onError errorCbFunc
|
|
|
|
errored uint32
|
|
|
|
|
|
|
|
quit chan struct{}
|
2017-04-04 08:28:28 -07:00
|
|
|
flushTimer *cmn.ThrottleTimer // flush writes as necessary but throttled.
|
|
|
|
pingTimer *cmn.RepeatTimer // send pings periodically
|
|
|
|
chStatsTimer *cmn.RepeatTimer // update channel stats periodically
|
2015-10-25 18:21:51 -07:00
|
|
|
|
|
|
|
LocalAddress *NetAddress
|
|
|
|
RemoteAddress *NetAddress
|
|
|
|
}
|
|
|
|
|
2016-05-08 14:59:27 -07:00
|
|
|
func NewMConnection(config cfg.Config, conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection {
|
2015-10-25 18:21:51 -07:00
|
|
|
mconn := &MConnection{
|
|
|
|
conn: conn,
|
|
|
|
bufReader: bufio.NewReaderSize(conn, minReadBufferSize),
|
|
|
|
bufWriter: bufio.NewWriterSize(conn, minWriteBufferSize),
|
|
|
|
sendMonitor: flow.New(0, 0),
|
|
|
|
recvMonitor: flow.New(0, 0),
|
2016-05-08 14:59:27 -07:00
|
|
|
sendRate: int64(config.GetInt(configKeySendRate)),
|
|
|
|
recvRate: int64(config.GetInt(configKeyRecvRate)),
|
2015-10-25 18:21:51 -07:00
|
|
|
send: make(chan struct{}, 1),
|
|
|
|
pong: make(chan struct{}),
|
|
|
|
onReceive: onReceive,
|
|
|
|
onError: onError,
|
|
|
|
|
|
|
|
// Initialized in Start()
|
|
|
|
quit: nil,
|
|
|
|
flushTimer: nil,
|
|
|
|
pingTimer: nil,
|
|
|
|
chStatsTimer: nil,
|
|
|
|
|
|
|
|
LocalAddress: NewNetAddress(conn.LocalAddr()),
|
|
|
|
RemoteAddress: NewNetAddress(conn.RemoteAddr()),
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create channels
|
|
|
|
var channelsIdx = map[byte]*Channel{}
|
|
|
|
var channels = []*Channel{}
|
|
|
|
|
|
|
|
for _, desc := range chDescs {
|
2016-06-25 21:34:34 -07:00
|
|
|
descCopy := *desc // copy the desc else unsafe access across connections
|
|
|
|
channel := newChannel(mconn, &descCopy)
|
2015-10-25 18:21:51 -07:00
|
|
|
channelsIdx[channel.id] = channel
|
|
|
|
channels = append(channels, channel)
|
|
|
|
}
|
|
|
|
mconn.channels = channels
|
|
|
|
mconn.channelsIdx = channelsIdx
|
|
|
|
|
2017-04-04 08:28:28 -07:00
|
|
|
mconn.BaseService = *cmn.NewBaseService(log, "MConnection", mconn)
|
2015-10-25 18:21:51 -07:00
|
|
|
|
|
|
|
return mconn
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *MConnection) OnStart() error {
|
|
|
|
c.BaseService.OnStart()
|
|
|
|
c.quit = make(chan struct{})
|
2017-04-04 13:14:24 -07:00
|
|
|
c.flushTimer = cmn.NewThrottleTimer("flush", flushThrottle)
|
|
|
|
c.pingTimer = cmn.NewRepeatTimer("ping", pingTimeout)
|
|
|
|
c.chStatsTimer = cmn.NewRepeatTimer("chStats", updateState)
|
2015-10-25 18:21:51 -07:00
|
|
|
go c.sendRoutine()
|
|
|
|
go c.recvRoutine()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *MConnection) OnStop() {
|
|
|
|
c.BaseService.OnStop()
|
|
|
|
c.flushTimer.Stop()
|
|
|
|
c.pingTimer.Stop()
|
|
|
|
c.chStatsTimer.Stop()
|
|
|
|
if c.quit != nil {
|
|
|
|
close(c.quit)
|
|
|
|
}
|
|
|
|
c.conn.Close()
|
|
|
|
// We can't close pong safely here because
|
|
|
|
// recvRoutine may write to it after we've stopped.
|
|
|
|
// Though it doesn't need to get closed at all,
|
|
|
|
// we close it @ recvRoutine.
|
|
|
|
// close(c.pong)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *MConnection) String() string {
|
|
|
|
return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *MConnection) flush() {
|
|
|
|
log.Debug("Flush", "conn", c)
|
|
|
|
err := c.bufWriter.Flush()
|
|
|
|
if err != nil {
|
|
|
|
log.Warn("MConnection flush failed", "error", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Catch panics, usually caused by remote disconnects.
|
|
|
|
func (c *MConnection) _recover() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
stack := debug.Stack()
|
2017-04-04 08:28:28 -07:00
|
|
|
err := cmn.StackError{r, stack}
|
2015-10-25 18:21:51 -07:00
|
|
|
c.stopForError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *MConnection) stopForError(r interface{}) {
|
|
|
|
c.Stop()
|
|
|
|
if atomic.CompareAndSwapUint32(&c.errored, 0, 1) {
|
|
|
|
if c.onError != nil {
|
|
|
|
c.onError(r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Queues a message to be sent to channel.
|
|
|
|
func (c *MConnection) Send(chID byte, msg interface{}) bool {
|
|
|
|
if !c.IsRunning() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2016-03-29 11:37:29 -07:00
|
|
|
log.Debug("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg))
|
2015-10-25 18:21:51 -07:00
|
|
|
|
|
|
|
// Send message to channel.
|
|
|
|
channel, ok := c.channelsIdx[chID]
|
|
|
|
if !ok {
|
2017-04-04 08:28:28 -07:00
|
|
|
log.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID))
|
2015-10-25 18:21:51 -07:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
success := channel.sendBytes(wire.BinaryBytes(msg))
|
|
|
|
if success {
|
|
|
|
// Wake up sendRoutine if necessary
|
|
|
|
select {
|
|
|
|
case c.send <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
log.Warn("Send failed", "channel", chID, "conn", c, "msg", msg)
|
|
|
|
}
|
|
|
|
return success
|
|
|
|
}
|
|
|
|
|
|
|
|
// Queues a message to be sent to channel.
|
|
|
|
// Nonblocking, returns true if successful.
|
|
|
|
func (c *MConnection) TrySend(chID byte, msg interface{}) bool {
|
|
|
|
if !c.IsRunning() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2016-03-29 11:37:29 -07:00
|
|
|
log.Debug("TrySend", "channel", chID, "conn", c, "msg", msg)
|
2015-10-25 18:21:51 -07:00
|
|
|
|
|
|
|
// Send message to channel.
|
|
|
|
channel, ok := c.channelsIdx[chID]
|
|
|
|
if !ok {
|
2017-04-04 08:28:28 -07:00
|
|
|
log.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID))
|
2015-10-25 18:21:51 -07:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
ok = channel.trySendBytes(wire.BinaryBytes(msg))
|
|
|
|
if ok {
|
|
|
|
// Wake up sendRoutine if necessary
|
|
|
|
select {
|
|
|
|
case c.send <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *MConnection) CanSend(chID byte) bool {
|
|
|
|
if !c.IsRunning() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
channel, ok := c.channelsIdx[chID]
|
|
|
|
if !ok {
|
2017-04-04 08:28:28 -07:00
|
|
|
log.Error(cmn.Fmt("Unknown channel %X", chID))
|
2015-10-25 18:21:51 -07:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return channel.canSend()
|
|
|
|
}
|
|
|
|
|
|
|
|
// sendRoutine polls for packets to send from channels.
|
|
|
|
func (c *MConnection) sendRoutine() {
|
|
|
|
defer c._recover()
|
|
|
|
|
|
|
|
FOR_LOOP:
|
|
|
|
for {
|
2015-11-10 12:29:43 -08:00
|
|
|
var n int
|
2015-10-25 18:21:51 -07:00
|
|
|
var err error
|
|
|
|
select {
|
|
|
|
case <-c.flushTimer.Ch:
|
|
|
|
// NOTE: flushTimer.Set() must be called every time
|
|
|
|
// something is written to .bufWriter.
|
|
|
|
c.flush()
|
|
|
|
case <-c.chStatsTimer.Ch:
|
|
|
|
for _, channel := range c.channels {
|
|
|
|
channel.updateStats()
|
|
|
|
}
|
|
|
|
case <-c.pingTimer.Ch:
|
2016-03-29 11:37:29 -07:00
|
|
|
log.Debug("Send Ping")
|
2015-10-25 18:21:51 -07:00
|
|
|
wire.WriteByte(packetTypePing, c.bufWriter, &n, &err)
|
|
|
|
c.sendMonitor.Update(int(n))
|
|
|
|
c.flush()
|
|
|
|
case <-c.pong:
|
2016-03-29 11:37:29 -07:00
|
|
|
log.Debug("Send Pong")
|
2015-10-25 18:21:51 -07:00
|
|
|
wire.WriteByte(packetTypePong, c.bufWriter, &n, &err)
|
|
|
|
c.sendMonitor.Update(int(n))
|
|
|
|
c.flush()
|
|
|
|
case <-c.quit:
|
|
|
|
break FOR_LOOP
|
|
|
|
case <-c.send:
|
|
|
|
// Send some msgPackets
|
|
|
|
eof := c.sendSomeMsgPackets()
|
|
|
|
if !eof {
|
|
|
|
// Keep sendRoutine awake.
|
|
|
|
select {
|
|
|
|
case c.send <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !c.IsRunning() {
|
|
|
|
break FOR_LOOP
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
log.Warn("Connection failed @ sendRoutine", "conn", c, "error", err)
|
|
|
|
c.stopForError(err)
|
|
|
|
break FOR_LOOP
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Cleanup
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns true if messages from channels were exhausted.
|
|
|
|
// Blocks in accordance to .sendMonitor throttling.
|
|
|
|
func (c *MConnection) sendSomeMsgPackets() bool {
|
|
|
|
// Block until .sendMonitor says we can write.
|
|
|
|
// Once we're ready we send more than we asked for,
|
|
|
|
// but amortized it should even out.
|
2016-05-08 14:59:27 -07:00
|
|
|
c.sendMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.sendRate), true)
|
2015-10-25 18:21:51 -07:00
|
|
|
|
|
|
|
// Now send some msgPackets.
|
|
|
|
for i := 0; i < numBatchMsgPackets; i++ {
|
|
|
|
if c.sendMsgPacket() {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns true if messages from channels were exhausted.
|
|
|
|
func (c *MConnection) sendMsgPacket() bool {
|
|
|
|
// Choose a channel to create a msgPacket from.
|
|
|
|
// 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
|
|
|
|
if !channel.isSendPending() {
|
|
|
|
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 {
|
|
|
|
// log.Info("Found a msgPacket to send")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make & send a msgPacket from this channel
|
|
|
|
n, err := leastChannel.writeMsgPacketTo(c.bufWriter)
|
|
|
|
if err != nil {
|
|
|
|
log.Warn("Failed to write msgPacket", "error", err)
|
|
|
|
c.stopForError(err)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
c.sendMonitor.Update(int(n))
|
|
|
|
c.flushTimer.Set()
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// recvRoutine reads msgPackets and reconstructs the message using the channels' "recving" buffer.
|
|
|
|
// After a whole message has been assembled, it's pushed to onReceive().
|
|
|
|
// Blocks depending on how the connection is throttled.
|
|
|
|
func (c *MConnection) recvRoutine() {
|
|
|
|
defer c._recover()
|
|
|
|
|
|
|
|
FOR_LOOP:
|
|
|
|
for {
|
|
|
|
// Block until .recvMonitor says we can read.
|
2016-05-08 14:59:27 -07:00
|
|
|
c.recvMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.recvRate), true)
|
2015-10-25 18:21:51 -07:00
|
|
|
|
|
|
|
/*
|
|
|
|
// Peek into bufReader for debugging
|
|
|
|
if numBytes := c.bufReader.Buffered(); numBytes > 0 {
|
|
|
|
log.Info("Peek connection buffer", "numBytes", numBytes, "bytes", log15.Lazy{func() []byte {
|
|
|
|
bytes, err := c.bufReader.Peek(MinInt(numBytes, 100))
|
|
|
|
if err == nil {
|
|
|
|
return bytes
|
|
|
|
} else {
|
|
|
|
log.Warn("Error peeking connection buffer", "error", err)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}})
|
|
|
|
}
|
|
|
|
*/
|
|
|
|
|
|
|
|
// Read packet type
|
2015-11-10 12:29:43 -08:00
|
|
|
var n int
|
2015-10-25 18:21:51 -07:00
|
|
|
var err error
|
|
|
|
pktType := wire.ReadByte(c.bufReader, &n, &err)
|
|
|
|
c.recvMonitor.Update(int(n))
|
|
|
|
if err != nil {
|
|
|
|
if c.IsRunning() {
|
|
|
|
log.Warn("Connection failed @ recvRoutine (reading byte)", "conn", c, "error", err)
|
|
|
|
c.stopForError(err)
|
|
|
|
}
|
|
|
|
break FOR_LOOP
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read more depending on packet type.
|
|
|
|
switch pktType {
|
|
|
|
case packetTypePing:
|
|
|
|
// TODO: prevent abuse, as they cause flush()'s.
|
2016-03-29 11:37:29 -07:00
|
|
|
log.Debug("Receive Ping")
|
2015-10-25 18:21:51 -07:00
|
|
|
c.pong <- struct{}{}
|
|
|
|
case packetTypePong:
|
|
|
|
// do nothing
|
2016-03-29 11:37:29 -07:00
|
|
|
log.Debug("Receive Pong")
|
2015-10-25 18:21:51 -07:00
|
|
|
case packetTypeMsg:
|
2015-11-10 12:29:43 -08:00
|
|
|
pkt, n, err := msgPacket{}, int(0), error(nil)
|
2016-05-08 14:59:27 -07:00
|
|
|
wire.ReadBinaryPtr(&pkt, c.bufReader, maxMsgPacketTotalSize, &n, &err)
|
2015-10-25 18:21:51 -07:00
|
|
|
c.recvMonitor.Update(int(n))
|
|
|
|
if err != nil {
|
|
|
|
if c.IsRunning() {
|
|
|
|
log.Warn("Connection failed @ recvRoutine", "conn", c, "error", err)
|
|
|
|
c.stopForError(err)
|
|
|
|
}
|
|
|
|
break FOR_LOOP
|
|
|
|
}
|
|
|
|
channel, ok := c.channelsIdx[pkt.ChannelID]
|
|
|
|
if !ok || channel == nil {
|
2017-04-04 08:28:28 -07:00
|
|
|
cmn.PanicQ(cmn.Fmt("Unknown channel %X", pkt.ChannelID))
|
2015-10-25 18:21:51 -07:00
|
|
|
}
|
|
|
|
msgBytes, err := channel.recvMsgPacket(pkt)
|
|
|
|
if err != nil {
|
|
|
|
if c.IsRunning() {
|
|
|
|
log.Warn("Connection failed @ recvRoutine", "conn", c, "error", err)
|
|
|
|
c.stopForError(err)
|
|
|
|
}
|
|
|
|
break FOR_LOOP
|
|
|
|
}
|
|
|
|
if msgBytes != nil {
|
|
|
|
log.Debug("Received bytes", "chID", pkt.ChannelID, "msgBytes", msgBytes)
|
|
|
|
c.onReceive(pkt.ChannelID, msgBytes)
|
|
|
|
}
|
|
|
|
default:
|
2017-04-04 08:28:28 -07:00
|
|
|
cmn.PanicSanity(cmn.Fmt("Unknown message type %X", pktType))
|
2015-10-25 18:21:51 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: shouldn't this go in the sendRoutine?
|
|
|
|
// Better to send a ping packet when *we* haven't sent anything for a while.
|
|
|
|
c.pingTimer.Reset()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Cleanup
|
|
|
|
close(c.pong)
|
|
|
|
for _ = range c.pong {
|
|
|
|
// Drain
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-03 06:20:18 -08:00
|
|
|
type ConnectionStatus struct {
|
|
|
|
SendMonitor flow.Status
|
|
|
|
RecvMonitor flow.Status
|
|
|
|
Channels []ChannelStatus
|
|
|
|
}
|
2016-01-02 20:53:10 -08:00
|
|
|
|
2016-01-03 06:20:18 -08:00
|
|
|
type ChannelStatus struct {
|
|
|
|
ID byte
|
|
|
|
SendQueueCapacity int
|
|
|
|
SendQueueSize int
|
|
|
|
Priority int
|
|
|
|
RecentlySent int64
|
|
|
|
}
|
2016-01-02 20:53:10 -08:00
|
|
|
|
2016-01-03 06:20:18 -08:00
|
|
|
func (c *MConnection) Status() ConnectionStatus {
|
|
|
|
var status ConnectionStatus
|
|
|
|
status.SendMonitor = c.sendMonitor.Status()
|
|
|
|
status.RecvMonitor = c.recvMonitor.Status()
|
|
|
|
status.Channels = make([]ChannelStatus, len(c.channels))
|
|
|
|
for i, channel := range c.channels {
|
|
|
|
status.Channels[i] = ChannelStatus{
|
|
|
|
ID: channel.id,
|
2016-01-02 20:53:10 -08:00
|
|
|
SendQueueCapacity: cap(channel.sendQueue),
|
|
|
|
SendQueueSize: int(channel.sendQueueSize), // TODO use atomic
|
|
|
|
Priority: channel.priority,
|
|
|
|
RecentlySent: channel.recentlySent,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return status
|
|
|
|
}
|
|
|
|
|
2015-10-25 18:21:51 -07:00
|
|
|
//-----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
type ChannelDescriptor struct {
|
2015-11-10 12:29:43 -08:00
|
|
|
ID byte
|
|
|
|
Priority int
|
|
|
|
SendQueueCapacity int
|
|
|
|
RecvBufferCapacity int
|
|
|
|
RecvMessageCapacity int
|
2015-10-25 18:21:51 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (chDesc *ChannelDescriptor) FillDefaults() {
|
|
|
|
if chDesc.SendQueueCapacity == 0 {
|
|
|
|
chDesc.SendQueueCapacity = defaultSendQueueCapacity
|
|
|
|
}
|
|
|
|
if chDesc.RecvBufferCapacity == 0 {
|
|
|
|
chDesc.RecvBufferCapacity = defaultRecvBufferCapacity
|
|
|
|
}
|
2015-11-10 12:29:43 -08:00
|
|
|
if chDesc.RecvMessageCapacity == 0 {
|
|
|
|
chDesc.RecvMessageCapacity = defaultRecvMessageCapacity
|
|
|
|
}
|
2015-10-25 18:21:51 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: lowercase.
|
|
|
|
// NOTE: not goroutine-safe.
|
|
|
|
type Channel struct {
|
|
|
|
conn *MConnection
|
|
|
|
desc *ChannelDescriptor
|
|
|
|
id byte
|
|
|
|
sendQueue chan []byte
|
|
|
|
sendQueueSize int32 // atomic.
|
|
|
|
recving []byte
|
|
|
|
sending []byte
|
|
|
|
priority int
|
|
|
|
recentlySent int64 // exponential moving average
|
|
|
|
}
|
|
|
|
|
|
|
|
func newChannel(conn *MConnection, desc *ChannelDescriptor) *Channel {
|
|
|
|
desc.FillDefaults()
|
|
|
|
if desc.Priority <= 0 {
|
2017-04-04 08:28:28 -07:00
|
|
|
cmn.PanicSanity("Channel default priority must be a postive integer")
|
2015-10-25 18:21:51 -07:00
|
|
|
}
|
|
|
|
return &Channel{
|
|
|
|
conn: conn,
|
|
|
|
desc: desc,
|
|
|
|
id: desc.ID,
|
|
|
|
sendQueue: make(chan []byte, desc.SendQueueCapacity),
|
|
|
|
recving: make([]byte, 0, desc.RecvBufferCapacity),
|
|
|
|
priority: desc.Priority,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Queues message to send to this channel.
|
|
|
|
// Goroutine-safe
|
2017-04-04 13:14:24 -07:00
|
|
|
// Times out (and returns false) after defaultSendTimeout
|
2015-10-25 18:21:51 -07:00
|
|
|
func (ch *Channel) sendBytes(bytes []byte) bool {
|
2017-04-04 13:14:24 -07:00
|
|
|
timeout := time.NewTimer(defaultSendTimeout)
|
2015-10-25 18:21:51 -07:00
|
|
|
select {
|
|
|
|
case <-timeout.C:
|
|
|
|
// timeout
|
|
|
|
return false
|
|
|
|
case ch.sendQueue <- bytes:
|
|
|
|
atomic.AddInt32(&ch.sendQueueSize, 1)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Queues message to send to this channel.
|
|
|
|
// Nonblocking, returns true if successful.
|
|
|
|
// Goroutine-safe
|
|
|
|
func (ch *Channel) trySendBytes(bytes []byte) bool {
|
|
|
|
select {
|
|
|
|
case ch.sendQueue <- bytes:
|
|
|
|
atomic.AddInt32(&ch.sendQueueSize, 1)
|
|
|
|
return true
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Goroutine-safe
|
|
|
|
func (ch *Channel) loadSendQueueSize() (size int) {
|
|
|
|
return int(atomic.LoadInt32(&ch.sendQueueSize))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Goroutine-safe
|
|
|
|
// Use only as a heuristic.
|
|
|
|
func (ch *Channel) canSend() bool {
|
|
|
|
return ch.loadSendQueueSize() < defaultSendQueueCapacity
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns true if any msgPackets are pending to be sent.
|
|
|
|
// Call before calling nextMsgPacket()
|
|
|
|
// Goroutine-safe
|
|
|
|
func (ch *Channel) isSendPending() bool {
|
|
|
|
if len(ch.sending) == 0 {
|
|
|
|
if len(ch.sendQueue) == 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
ch.sending = <-ch.sendQueue
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Creates a new msgPacket to send.
|
|
|
|
// Not goroutine-safe
|
|
|
|
func (ch *Channel) nextMsgPacket() msgPacket {
|
|
|
|
packet := msgPacket{}
|
|
|
|
packet.ChannelID = byte(ch.id)
|
2017-04-04 08:28:28 -07:00
|
|
|
packet.Bytes = ch.sending[:cmn.MinInt(maxMsgPacketPayloadSize, len(ch.sending))]
|
2016-05-08 14:59:27 -07:00
|
|
|
if len(ch.sending) <= maxMsgPacketPayloadSize {
|
2015-10-25 18:21:51 -07:00
|
|
|
packet.EOF = byte(0x01)
|
|
|
|
ch.sending = nil
|
|
|
|
atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize
|
|
|
|
} else {
|
|
|
|
packet.EOF = byte(0x00)
|
2017-04-04 08:28:28 -07:00
|
|
|
ch.sending = ch.sending[cmn.MinInt(maxMsgPacketPayloadSize, len(ch.sending)):]
|
2015-10-25 18:21:51 -07:00
|
|
|
}
|
|
|
|
return packet
|
|
|
|
}
|
|
|
|
|
|
|
|
// Writes next msgPacket to w.
|
|
|
|
// Not goroutine-safe
|
2015-11-10 12:29:43 -08:00
|
|
|
func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int, err error) {
|
2015-10-25 18:21:51 -07:00
|
|
|
packet := ch.nextMsgPacket()
|
|
|
|
log.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet)
|
|
|
|
wire.WriteByte(packetTypeMsg, w, &n, &err)
|
|
|
|
wire.WriteBinary(packet, w, &n, &err)
|
2016-01-03 06:20:18 -08:00
|
|
|
if err == nil {
|
2015-11-10 12:29:43 -08:00
|
|
|
ch.recentlySent += int64(n)
|
2015-10-25 18:21:51 -07:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handles incoming msgPackets. Returns a msg bytes if msg is complete.
|
|
|
|
// Not goroutine-safe
|
|
|
|
func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) {
|
|
|
|
// log.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet)
|
2015-11-10 12:29:43 -08:00
|
|
|
if ch.desc.RecvMessageCapacity < len(ch.recving)+len(packet.Bytes) {
|
2016-01-17 21:30:06 -08:00
|
|
|
return nil, wire.ErrBinaryReadOverflow
|
2015-10-25 18:21:51 -07:00
|
|
|
}
|
|
|
|
ch.recving = append(ch.recving, packet.Bytes...)
|
|
|
|
if packet.EOF == byte(0x01) {
|
|
|
|
msgBytes := ch.recving
|
2016-03-11 22:04:27 -08:00
|
|
|
// clear the slice without re-allocating.
|
|
|
|
// http://stackoverflow.com/questions/16971741/how-do-you-clear-a-slice-in-go
|
|
|
|
// suggests this could be a memory leak, but we might as well keep the memory for the channel until it closes,
|
|
|
|
// at which point the recving slice stops being used and should be garbage collected
|
|
|
|
ch.recving = ch.recving[:0] // make([]byte, 0, ch.desc.RecvBufferCapacity)
|
2015-10-25 18:21:51 -07:00
|
|
|
return msgBytes, nil
|
|
|
|
}
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Call this periodically to update stats for throttling purposes.
|
|
|
|
// Not goroutine-safe
|
|
|
|
func (ch *Channel) updateStats() {
|
|
|
|
// Exponential decay of stats.
|
|
|
|
// TODO: optimize.
|
2015-12-09 13:53:50 -08:00
|
|
|
ch.recentlySent = int64(float64(ch.recentlySent) * 0.8)
|
2015-10-25 18:21:51 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
//-----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
const (
|
2016-05-08 14:59:27 -07:00
|
|
|
maxMsgPacketPayloadSize = 1024
|
2015-11-10 12:29:43 -08:00
|
|
|
maxMsgPacketOverheadSize = 10 // It's actually lower but good enough
|
2016-05-08 14:59:27 -07:00
|
|
|
maxMsgPacketTotalSize = maxMsgPacketPayloadSize + maxMsgPacketOverheadSize
|
2015-11-10 12:29:43 -08:00
|
|
|
packetTypePing = byte(0x01)
|
|
|
|
packetTypePong = byte(0x02)
|
|
|
|
packetTypeMsg = byte(0x03)
|
2015-10-25 18:21:51 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
// Messages in channels are chopped into smaller msgPackets for multiplexing.
|
|
|
|
type msgPacket struct {
|
|
|
|
ChannelID byte
|
|
|
|
EOF byte // 1 means message ends here.
|
|
|
|
Bytes []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p msgPacket) String() string {
|
|
|
|
return fmt.Sprintf("MsgPacket{%X:%X T:%X}", p.ChannelID, p.Bytes, p.EOF)
|
|
|
|
}
|