You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

726 lines
20 KiB

9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package p2p
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "math"
  7. "net"
  8. "runtime/debug"
  9. "sync/atomic"
  10. "time"
  11. wire "github.com/tendermint/go-wire"
  12. tmlegacy "github.com/tendermint/go-wire/nowriter/tmlegacy"
  13. cmn "github.com/tendermint/tmlibs/common"
  14. flow "github.com/tendermint/tmlibs/flowrate"
  15. "github.com/tendermint/tmlibs/log"
  16. )
  17. var legacy = tmlegacy.TMEncoderLegacy{}
  18. const (
  19. numBatchMsgPackets = 10
  20. minReadBufferSize = 1024
  21. minWriteBufferSize = 65536
  22. updateStats = 2 * time.Second
  23. pingTimeout = 40 * time.Second
  24. // some of these defaults are written in the user config
  25. // flushThrottle, sendRate, recvRate
  26. // TODO: remove values present in config
  27. defaultFlushThrottle = 100 * time.Millisecond
  28. defaultSendQueueCapacity = 1
  29. defaultRecvBufferCapacity = 4096
  30. defaultRecvMessageCapacity = 22020096 // 21MB
  31. defaultSendRate = int64(512000) // 500KB/s
  32. defaultRecvRate = int64(512000) // 500KB/s
  33. defaultSendTimeout = 10 * time.Second
  34. )
  35. type receiveCbFunc func(chID byte, msgBytes []byte)
  36. type errorCbFunc func(interface{})
  37. /*
  38. Each peer has one `MConnection` (multiplex connection) instance.
  39. __multiplex__ *noun* a system or signal involving simultaneous transmission of
  40. several messages along a single channel of communication.
  41. Each `MConnection` handles message transmission on multiple abstract communication
  42. `Channel`s. Each channel has a globally unique byte id.
  43. The byte id and the relative priorities of each `Channel` are configured upon
  44. initialization of the connection.
  45. There are two methods for sending messages:
  46. func (m MConnection) Send(chID byte, msg interface{}) bool {}
  47. func (m MConnection) TrySend(chID byte, msg interface{}) bool {}
  48. `Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued
  49. for the channel with the given id byte `chID`, or until the request times out.
  50. The message `msg` is serialized using the `tendermint/wire` submodule's
  51. `WriteBinary()` reflection routine.
  52. `TrySend(chID, msg)` is a nonblocking call that returns false if the channel's
  53. queue is full.
  54. Inbound message bytes are handled with an onReceive callback function.
  55. */
  56. type MConnection struct {
  57. cmn.BaseService
  58. conn net.Conn
  59. bufReader *bufio.Reader
  60. bufWriter *bufio.Writer
  61. sendMonitor *flow.Monitor
  62. recvMonitor *flow.Monitor
  63. send chan struct{}
  64. pong chan struct{}
  65. channels []*Channel
  66. channelsIdx map[byte]*Channel
  67. onReceive receiveCbFunc
  68. onError errorCbFunc
  69. errored uint32
  70. config *MConnConfig
  71. quit chan struct{}
  72. flushTimer *cmn.ThrottleTimer // flush writes as necessary but throttled.
  73. pingTimer *cmn.RepeatTimer // send pings periodically
  74. chStatsTimer *cmn.RepeatTimer // update channel stats periodically
  75. }
  76. // MConnConfig is a MConnection configuration.
  77. type MConnConfig struct {
  78. SendRate int64 `mapstructure:"send_rate"`
  79. RecvRate int64 `mapstructure:"recv_rate"`
  80. maxMsgPacketPayloadSize int
  81. flushThrottle time.Duration
  82. }
  83. func (cfg *MConnConfig) maxMsgPacketTotalSize() int {
  84. return cfg.maxMsgPacketPayloadSize + maxMsgPacketOverheadSize
  85. }
  86. // DefaultMConnConfig returns the default config.
  87. func DefaultMConnConfig() *MConnConfig {
  88. return &MConnConfig{
  89. SendRate: defaultSendRate,
  90. RecvRate: defaultRecvRate,
  91. maxMsgPacketPayloadSize: defaultMaxMsgPacketPayloadSize,
  92. flushThrottle: defaultFlushThrottle,
  93. }
  94. }
  95. // NewMConnection wraps net.Conn and creates multiplex connection
  96. func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection {
  97. return NewMConnectionWithConfig(
  98. conn,
  99. chDescs,
  100. onReceive,
  101. onError,
  102. DefaultMConnConfig())
  103. }
  104. // NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config
  105. func NewMConnectionWithConfig(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc, config *MConnConfig) *MConnection {
  106. mconn := &MConnection{
  107. conn: conn,
  108. bufReader: bufio.NewReaderSize(conn, minReadBufferSize),
  109. bufWriter: bufio.NewWriterSize(conn, minWriteBufferSize),
  110. sendMonitor: flow.New(0, 0),
  111. recvMonitor: flow.New(0, 0),
  112. send: make(chan struct{}, 1),
  113. pong: make(chan struct{}),
  114. onReceive: onReceive,
  115. onError: onError,
  116. config: config,
  117. }
  118. // Create channels
  119. var channelsIdx = map[byte]*Channel{}
  120. var channels = []*Channel{}
  121. for _, desc := range chDescs {
  122. channel := newChannel(mconn, *desc)
  123. channelsIdx[channel.desc.ID] = channel
  124. channels = append(channels, channel)
  125. }
  126. mconn.channels = channels
  127. mconn.channelsIdx = channelsIdx
  128. mconn.BaseService = *cmn.NewBaseService(nil, "MConnection", mconn)
  129. return mconn
  130. }
  131. func (c *MConnection) SetLogger(l log.Logger) {
  132. c.BaseService.SetLogger(l)
  133. for _, ch := range c.channels {
  134. ch.SetLogger(l)
  135. }
  136. }
  137. // OnStart implements BaseService
  138. func (c *MConnection) OnStart() error {
  139. if err := c.BaseService.OnStart(); err != nil {
  140. return err
  141. }
  142. c.quit = make(chan struct{})
  143. c.flushTimer = cmn.NewThrottleTimer("flush", c.config.flushThrottle)
  144. c.pingTimer = cmn.NewRepeatTimer("ping", pingTimeout)
  145. c.chStatsTimer = cmn.NewRepeatTimer("chStats", updateStats)
  146. go c.sendRoutine()
  147. go c.recvRoutine()
  148. return nil
  149. }
  150. // OnStop implements BaseService
  151. func (c *MConnection) OnStop() {
  152. c.BaseService.OnStop()
  153. c.flushTimer.Stop()
  154. c.pingTimer.Stop()
  155. c.chStatsTimer.Stop()
  156. if c.quit != nil {
  157. close(c.quit)
  158. }
  159. c.conn.Close() // nolint: errcheck
  160. // We can't close pong safely here because
  161. // recvRoutine may write to it after we've stopped.
  162. // Though it doesn't need to get closed at all,
  163. // we close it @ recvRoutine.
  164. // close(c.pong)
  165. }
  166. func (c *MConnection) String() string {
  167. return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr())
  168. }
  169. func (c *MConnection) flush() {
  170. c.Logger.Debug("Flush", "conn", c)
  171. err := c.bufWriter.Flush()
  172. if err != nil {
  173. c.Logger.Error("MConnection flush failed", "err", err)
  174. }
  175. }
  176. // Catch panics, usually caused by remote disconnects.
  177. func (c *MConnection) _recover() {
  178. if r := recover(); r != nil {
  179. stack := debug.Stack()
  180. err := cmn.StackError{r, stack}
  181. c.stopForError(err)
  182. }
  183. }
  184. func (c *MConnection) stopForError(r interface{}) {
  185. c.Stop()
  186. if atomic.CompareAndSwapUint32(&c.errored, 0, 1) {
  187. if c.onError != nil {
  188. c.onError(r)
  189. }
  190. }
  191. }
  192. // Queues a message to be sent to channel.
  193. func (c *MConnection) Send(chID byte, msg interface{}) bool {
  194. if !c.IsRunning() {
  195. return false
  196. }
  197. c.Logger.Debug("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg))
  198. // Send message to channel.
  199. channel, ok := c.channelsIdx[chID]
  200. if !ok {
  201. c.Logger.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID))
  202. return false
  203. }
  204. success := channel.sendBytes(wire.BinaryBytes(msg))
  205. if success {
  206. // Wake up sendRoutine if necessary
  207. select {
  208. case c.send <- struct{}{}:
  209. default:
  210. }
  211. } else {
  212. c.Logger.Error("Send failed", "channel", chID, "conn", c, "msg", msg)
  213. }
  214. return success
  215. }
  216. // Queues a message to be sent to channel.
  217. // Nonblocking, returns true if successful.
  218. func (c *MConnection) TrySend(chID byte, msg interface{}) bool {
  219. if !c.IsRunning() {
  220. return false
  221. }
  222. c.Logger.Debug("TrySend", "channel", chID, "conn", c, "msg", msg)
  223. // Send message to channel.
  224. channel, ok := c.channelsIdx[chID]
  225. if !ok {
  226. c.Logger.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID))
  227. return false
  228. }
  229. ok = channel.trySendBytes(wire.BinaryBytes(msg))
  230. if ok {
  231. // Wake up sendRoutine if necessary
  232. select {
  233. case c.send <- struct{}{}:
  234. default:
  235. }
  236. }
  237. return ok
  238. }
  239. // CanSend returns true if you can send more data onto the chID, false
  240. // otherwise. Use only as a heuristic.
  241. func (c *MConnection) CanSend(chID byte) bool {
  242. if !c.IsRunning() {
  243. return false
  244. }
  245. channel, ok := c.channelsIdx[chID]
  246. if !ok {
  247. c.Logger.Error(cmn.Fmt("Unknown channel %X", chID))
  248. return false
  249. }
  250. return channel.canSend()
  251. }
  252. // sendRoutine polls for packets to send from channels.
  253. func (c *MConnection) sendRoutine() {
  254. defer c._recover()
  255. FOR_LOOP:
  256. for {
  257. var n int
  258. var err error
  259. select {
  260. case <-c.flushTimer.Ch:
  261. // NOTE: flushTimer.Set() must be called every time
  262. // something is written to .bufWriter.
  263. c.flush()
  264. case <-c.chStatsTimer.Chan():
  265. for _, channel := range c.channels {
  266. channel.updateStats()
  267. }
  268. case <-c.pingTimer.Chan():
  269. c.Logger.Debug("Send Ping")
  270. legacy.WriteOctet(packetTypePing, c.bufWriter, &n, &err)
  271. c.sendMonitor.Update(int(n))
  272. c.flush()
  273. case <-c.pong:
  274. c.Logger.Debug("Send Pong")
  275. legacy.WriteOctet(packetTypePong, c.bufWriter, &n, &err)
  276. c.sendMonitor.Update(int(n))
  277. c.flush()
  278. case <-c.quit:
  279. break FOR_LOOP
  280. case <-c.send:
  281. // Send some msgPackets
  282. eof := c.sendSomeMsgPackets()
  283. if !eof {
  284. // Keep sendRoutine awake.
  285. select {
  286. case c.send <- struct{}{}:
  287. default:
  288. }
  289. }
  290. }
  291. if !c.IsRunning() {
  292. break FOR_LOOP
  293. }
  294. if err != nil {
  295. c.Logger.Error("Connection failed @ sendRoutine", "conn", c, "err", err)
  296. c.stopForError(err)
  297. break FOR_LOOP
  298. }
  299. }
  300. // Cleanup
  301. }
  302. // Returns true if messages from channels were exhausted.
  303. // Blocks in accordance to .sendMonitor throttling.
  304. func (c *MConnection) sendSomeMsgPackets() bool {
  305. // Block until .sendMonitor says we can write.
  306. // Once we're ready we send more than we asked for,
  307. // but amortized it should even out.
  308. c.sendMonitor.Limit(c.config.maxMsgPacketTotalSize(), atomic.LoadInt64(&c.config.SendRate), true)
  309. // Now send some msgPackets.
  310. for i := 0; i < numBatchMsgPackets; i++ {
  311. if c.sendMsgPacket() {
  312. return true
  313. }
  314. }
  315. return false
  316. }
  317. // Returns true if messages from channels were exhausted.
  318. func (c *MConnection) sendMsgPacket() bool {
  319. // Choose a channel to create a msgPacket from.
  320. // The chosen channel will be the one whose recentlySent/priority is the least.
  321. var leastRatio float32 = math.MaxFloat32
  322. var leastChannel *Channel
  323. for _, channel := range c.channels {
  324. // If nothing to send, skip this channel
  325. if !channel.isSendPending() {
  326. continue
  327. }
  328. // Get ratio, and keep track of lowest ratio.
  329. ratio := float32(channel.recentlySent) / float32(channel.desc.Priority)
  330. if ratio < leastRatio {
  331. leastRatio = ratio
  332. leastChannel = channel
  333. }
  334. }
  335. // Nothing to send?
  336. if leastChannel == nil {
  337. return true
  338. } else {
  339. // c.Logger.Info("Found a msgPacket to send")
  340. }
  341. // Make & send a msgPacket from this channel
  342. n, err := leastChannel.writeMsgPacketTo(c.bufWriter)
  343. if err != nil {
  344. c.Logger.Error("Failed to write msgPacket", "err", err)
  345. c.stopForError(err)
  346. return true
  347. }
  348. c.sendMonitor.Update(int(n))
  349. c.flushTimer.Set()
  350. return false
  351. }
  352. // recvRoutine reads msgPackets and reconstructs the message using the channels' "recving" buffer.
  353. // After a whole message has been assembled, it's pushed to onReceive().
  354. // Blocks depending on how the connection is throttled.
  355. func (c *MConnection) recvRoutine() {
  356. defer c._recover()
  357. FOR_LOOP:
  358. for {
  359. // Block until .recvMonitor says we can read.
  360. c.recvMonitor.Limit(c.config.maxMsgPacketTotalSize(), atomic.LoadInt64(&c.config.RecvRate), true)
  361. /*
  362. // Peek into bufReader for debugging
  363. if numBytes := c.bufReader.Buffered(); numBytes > 0 {
  364. log.Info("Peek connection buffer", "numBytes", numBytes, "bytes", log15.Lazy{func() []byte {
  365. bytes, err := c.bufReader.Peek(cmn.MinInt(numBytes, 100))
  366. if err == nil {
  367. return bytes
  368. } else {
  369. log.Warn("Error peeking connection buffer", "err", err)
  370. return nil
  371. }
  372. }})
  373. }
  374. */
  375. // Read packet type
  376. var n int
  377. var err error
  378. pktType := wire.ReadByte(c.bufReader, &n, &err)
  379. c.recvMonitor.Update(int(n))
  380. if err != nil {
  381. if c.IsRunning() {
  382. c.Logger.Error("Connection failed @ recvRoutine (reading byte)", "conn", c, "err", err)
  383. c.stopForError(err)
  384. }
  385. break FOR_LOOP
  386. }
  387. // Read more depending on packet type.
  388. switch pktType {
  389. case packetTypePing:
  390. // TODO: prevent abuse, as they cause flush()'s.
  391. c.Logger.Debug("Receive Ping")
  392. c.pong <- struct{}{}
  393. case packetTypePong:
  394. // do nothing
  395. c.Logger.Debug("Receive Pong")
  396. case packetTypeMsg:
  397. pkt, n, err := msgPacket{}, int(0), error(nil)
  398. wire.ReadBinaryPtr(&pkt, c.bufReader, c.config.maxMsgPacketTotalSize(), &n, &err)
  399. c.recvMonitor.Update(int(n))
  400. if err != nil {
  401. if c.IsRunning() {
  402. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  403. c.stopForError(err)
  404. }
  405. break FOR_LOOP
  406. }
  407. channel, ok := c.channelsIdx[pkt.ChannelID]
  408. if !ok || channel == nil {
  409. err := fmt.Errorf("Unknown channel %X", pkt.ChannelID)
  410. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  411. c.stopForError(err)
  412. }
  413. msgBytes, err := channel.recvMsgPacket(pkt)
  414. if err != nil {
  415. if c.IsRunning() {
  416. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  417. c.stopForError(err)
  418. }
  419. break FOR_LOOP
  420. }
  421. if msgBytes != nil {
  422. c.Logger.Debug("Received bytes", "chID", pkt.ChannelID, "msgBytes", msgBytes)
  423. // NOTE: This means the reactor.Receive runs in the same thread as the p2p recv routine
  424. c.onReceive(pkt.ChannelID, msgBytes)
  425. }
  426. default:
  427. err := fmt.Errorf("Unknown message type %X", pktType)
  428. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  429. c.stopForError(err)
  430. }
  431. // TODO: shouldn't this go in the sendRoutine?
  432. // Better to send a ping packet when *we* haven't sent anything for a while.
  433. c.pingTimer.Reset()
  434. }
  435. // Cleanup
  436. close(c.pong)
  437. for range c.pong {
  438. // Drain
  439. }
  440. }
  441. type ConnectionStatus struct {
  442. SendMonitor flow.Status
  443. RecvMonitor flow.Status
  444. Channels []ChannelStatus
  445. }
  446. type ChannelStatus struct {
  447. ID byte
  448. SendQueueCapacity int
  449. SendQueueSize int
  450. Priority int
  451. RecentlySent int64
  452. }
  453. func (c *MConnection) Status() ConnectionStatus {
  454. var status ConnectionStatus
  455. status.SendMonitor = c.sendMonitor.Status()
  456. status.RecvMonitor = c.recvMonitor.Status()
  457. status.Channels = make([]ChannelStatus, len(c.channels))
  458. for i, channel := range c.channels {
  459. status.Channels[i] = ChannelStatus{
  460. ID: channel.desc.ID,
  461. SendQueueCapacity: cap(channel.sendQueue),
  462. SendQueueSize: int(channel.sendQueueSize), // TODO use atomic
  463. Priority: channel.desc.Priority,
  464. RecentlySent: channel.recentlySent,
  465. }
  466. }
  467. return status
  468. }
  469. //-----------------------------------------------------------------------------
  470. type ChannelDescriptor struct {
  471. ID byte
  472. Priority int
  473. SendQueueCapacity int
  474. RecvBufferCapacity int
  475. RecvMessageCapacity int
  476. }
  477. func (chDesc ChannelDescriptor) FillDefaults() (filled ChannelDescriptor) {
  478. if chDesc.SendQueueCapacity == 0 {
  479. chDesc.SendQueueCapacity = defaultSendQueueCapacity
  480. }
  481. if chDesc.RecvBufferCapacity == 0 {
  482. chDesc.RecvBufferCapacity = defaultRecvBufferCapacity
  483. }
  484. if chDesc.RecvMessageCapacity == 0 {
  485. chDesc.RecvMessageCapacity = defaultRecvMessageCapacity
  486. }
  487. filled = chDesc
  488. return
  489. }
  490. // TODO: lowercase.
  491. // NOTE: not goroutine-safe.
  492. type Channel struct {
  493. conn *MConnection
  494. desc ChannelDescriptor
  495. sendQueue chan []byte
  496. sendQueueSize int32 // atomic.
  497. recving []byte
  498. sending []byte
  499. recentlySent int64 // exponential moving average
  500. maxMsgPacketPayloadSize int
  501. Logger log.Logger
  502. }
  503. func newChannel(conn *MConnection, desc ChannelDescriptor) *Channel {
  504. desc = desc.FillDefaults()
  505. if desc.Priority <= 0 {
  506. cmn.PanicSanity("Channel default priority must be a positive integer")
  507. }
  508. return &Channel{
  509. conn: conn,
  510. desc: desc,
  511. sendQueue: make(chan []byte, desc.SendQueueCapacity),
  512. recving: make([]byte, 0, desc.RecvBufferCapacity),
  513. maxMsgPacketPayloadSize: conn.config.maxMsgPacketPayloadSize,
  514. }
  515. }
  516. func (ch *Channel) SetLogger(l log.Logger) {
  517. ch.Logger = l
  518. }
  519. // Queues message to send to this channel.
  520. // Goroutine-safe
  521. // Times out (and returns false) after defaultSendTimeout
  522. func (ch *Channel) sendBytes(bytes []byte) bool {
  523. select {
  524. case ch.sendQueue <- bytes:
  525. atomic.AddInt32(&ch.sendQueueSize, 1)
  526. return true
  527. case <-time.After(defaultSendTimeout):
  528. return false
  529. }
  530. }
  531. // Queues message to send to this channel.
  532. // Nonblocking, returns true if successful.
  533. // Goroutine-safe
  534. func (ch *Channel) trySendBytes(bytes []byte) bool {
  535. select {
  536. case ch.sendQueue <- bytes:
  537. atomic.AddInt32(&ch.sendQueueSize, 1)
  538. return true
  539. default:
  540. return false
  541. }
  542. }
  543. // Goroutine-safe
  544. func (ch *Channel) loadSendQueueSize() (size int) {
  545. return int(atomic.LoadInt32(&ch.sendQueueSize))
  546. }
  547. // Goroutine-safe
  548. // Use only as a heuristic.
  549. func (ch *Channel) canSend() bool {
  550. return ch.loadSendQueueSize() < defaultSendQueueCapacity
  551. }
  552. // Returns true if any msgPackets are pending to be sent.
  553. // Call before calling nextMsgPacket()
  554. // Goroutine-safe
  555. func (ch *Channel) isSendPending() bool {
  556. if len(ch.sending) == 0 {
  557. if len(ch.sendQueue) == 0 {
  558. return false
  559. }
  560. ch.sending = <-ch.sendQueue
  561. }
  562. return true
  563. }
  564. // Creates a new msgPacket to send.
  565. // Not goroutine-safe
  566. func (ch *Channel) nextMsgPacket() msgPacket {
  567. packet := msgPacket{}
  568. packet.ChannelID = byte(ch.desc.ID)
  569. maxSize := ch.maxMsgPacketPayloadSize
  570. packet.Bytes = ch.sending[:cmn.MinInt(maxSize, len(ch.sending))]
  571. if len(ch.sending) <= maxSize {
  572. packet.EOF = byte(0x01)
  573. ch.sending = nil
  574. atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize
  575. } else {
  576. packet.EOF = byte(0x00)
  577. ch.sending = ch.sending[cmn.MinInt(maxSize, len(ch.sending)):]
  578. }
  579. return packet
  580. }
  581. // Writes next msgPacket to w.
  582. // Not goroutine-safe
  583. func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int, err error) {
  584. packet := ch.nextMsgPacket()
  585. ch.Logger.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet)
  586. writeMsgPacketTo(packet, w, &n, &err)
  587. if err == nil {
  588. ch.recentlySent += int64(n)
  589. }
  590. return
  591. }
  592. func writeMsgPacketTo(packet msgPacket, w io.Writer, n *int, err *error) {
  593. legacy.WriteOctet(packetTypeMsg, w, n, err)
  594. wire.WriteBinary(packet, w, n, err)
  595. }
  596. // Handles incoming msgPackets. Returns a msg bytes if msg is complete.
  597. // Not goroutine-safe
  598. func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) {
  599. ch.Logger.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet)
  600. if ch.desc.RecvMessageCapacity < len(ch.recving)+len(packet.Bytes) {
  601. return nil, wire.ErrBinaryReadOverflow
  602. }
  603. ch.recving = append(ch.recving, packet.Bytes...)
  604. if packet.EOF == byte(0x01) {
  605. msgBytes := ch.recving
  606. // clear the slice without re-allocating.
  607. // http://stackoverflow.com/questions/16971741/how-do-you-clear-a-slice-in-go
  608. // suggests this could be a memory leak, but we might as well keep the memory for the channel until it closes,
  609. // at which point the recving slice stops being used and should be garbage collected
  610. ch.recving = ch.recving[:0] // make([]byte, 0, ch.desc.RecvBufferCapacity)
  611. return msgBytes, nil
  612. }
  613. return nil, nil
  614. }
  615. // Call this periodically to update stats for throttling purposes.
  616. // Not goroutine-safe
  617. func (ch *Channel) updateStats() {
  618. // Exponential decay of stats.
  619. // TODO: optimize.
  620. ch.recentlySent = int64(float64(ch.recentlySent) * 0.8)
  621. }
  622. //-----------------------------------------------------------------------------
  623. const (
  624. defaultMaxMsgPacketPayloadSize = 1024
  625. maxMsgPacketOverheadSize = 10 // It's actually lower but good enough
  626. packetTypePing = byte(0x01)
  627. packetTypePong = byte(0x02)
  628. packetTypeMsg = byte(0x03)
  629. )
  630. // Messages in channels are chopped into smaller msgPackets for multiplexing.
  631. type msgPacket struct {
  632. ChannelID byte
  633. EOF byte // 1 means message ends here.
  634. Bytes []byte
  635. }
  636. func (p msgPacket) String() string {
  637. return fmt.Sprintf("MsgPacket{%X:%X T:%X}", p.ChannelID, p.Bytes, p.EOF)
  638. }