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.

844 lines
23 KiB

  1. package conn
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "math"
  8. "net"
  9. "reflect"
  10. "sync/atomic"
  11. "time"
  12. amino "github.com/tendermint/go-amino"
  13. cmn "github.com/tendermint/tendermint/libs/common"
  14. flow "github.com/tendermint/tendermint/libs/flowrate"
  15. "github.com/tendermint/tendermint/libs/log"
  16. )
  17. const (
  18. defaultMaxPacketMsgPayloadSize = 1024
  19. numBatchPacketMsgs = 10
  20. minReadBufferSize = 1024
  21. minWriteBufferSize = 65536
  22. updateStats = 2 * time.Second
  23. // some of these defaults are written in the user config
  24. // flushThrottle, sendRate, recvRate
  25. // TODO: remove values present in config
  26. defaultFlushThrottle = 100 * time.Millisecond
  27. defaultSendQueueCapacity = 1
  28. defaultRecvBufferCapacity = 4096
  29. defaultRecvMessageCapacity = 22020096 // 21MB
  30. defaultSendRate = int64(512000) // 500KB/s
  31. defaultRecvRate = int64(512000) // 500KB/s
  32. defaultSendTimeout = 10 * time.Second
  33. defaultPingInterval = 60 * time.Second
  34. defaultPongTimeout = 45 * time.Second
  35. )
  36. type receiveCbFunc func(chID byte, msgBytes []byte)
  37. type errorCbFunc func(interface{})
  38. /*
  39. Each peer has one `MConnection` (multiplex connection) instance.
  40. __multiplex__ *noun* a system or signal involving simultaneous transmission of
  41. several messages along a single channel of communication.
  42. Each `MConnection` handles message transmission on multiple abstract communication
  43. `Channel`s. Each channel has a globally unique byte id.
  44. The byte id and the relative priorities of each `Channel` are configured upon
  45. initialization of the connection.
  46. There are two methods for sending messages:
  47. func (m MConnection) Send(chID byte, msgBytes []byte) bool {}
  48. func (m MConnection) TrySend(chID byte, msgBytes []byte}) bool {}
  49. `Send(chID, msgBytes)` is a blocking call that waits until `msg` is
  50. successfully queued for the channel with the given id byte `chID`, or until the
  51. request times out. The message `msg` is serialized using Go-Amino.
  52. `TrySend(chID, msgBytes)` is a nonblocking call that returns false if the
  53. channel's 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. bufConnReader *bufio.Reader
  60. bufConnWriter *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. // Closing quitSendRoutine will cause
  72. // doneSendRoutine to close.
  73. quitSendRoutine chan struct{}
  74. doneSendRoutine chan struct{}
  75. flushTimer *cmn.ThrottleTimer // flush writes as necessary but throttled.
  76. pingTimer *cmn.RepeatTimer // send pings periodically
  77. // close conn if pong is not received in pongTimeout
  78. pongTimer *time.Timer
  79. pongTimeoutCh chan bool // true - timeout, false - peer sent pong
  80. chStatsTimer *cmn.RepeatTimer // update channel stats periodically
  81. created time.Time // time of creation
  82. _maxPacketMsgSize int
  83. }
  84. // MConnConfig is a MConnection configuration.
  85. type MConnConfig struct {
  86. SendRate int64 `mapstructure:"send_rate"`
  87. RecvRate int64 `mapstructure:"recv_rate"`
  88. // Maximum payload size
  89. MaxPacketMsgPayloadSize int `mapstructure:"max_packet_msg_payload_size"`
  90. // Interval to flush writes (throttled)
  91. FlushThrottle time.Duration `mapstructure:"flush_throttle"`
  92. // Interval to send pings
  93. PingInterval time.Duration `mapstructure:"ping_interval"`
  94. // Maximum wait time for pongs
  95. PongTimeout time.Duration `mapstructure:"pong_timeout"`
  96. }
  97. // DefaultMConnConfig returns the default config.
  98. func DefaultMConnConfig() MConnConfig {
  99. return MConnConfig{
  100. SendRate: defaultSendRate,
  101. RecvRate: defaultRecvRate,
  102. MaxPacketMsgPayloadSize: defaultMaxPacketMsgPayloadSize,
  103. FlushThrottle: defaultFlushThrottle,
  104. PingInterval: defaultPingInterval,
  105. PongTimeout: defaultPongTimeout,
  106. }
  107. }
  108. // NewMConnection wraps net.Conn and creates multiplex connection
  109. func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection {
  110. return NewMConnectionWithConfig(
  111. conn,
  112. chDescs,
  113. onReceive,
  114. onError,
  115. DefaultMConnConfig())
  116. }
  117. // NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config
  118. func NewMConnectionWithConfig(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc, config MConnConfig) *MConnection {
  119. if config.PongTimeout >= config.PingInterval {
  120. panic("pongTimeout must be less than pingInterval (otherwise, next ping will reset pong timer)")
  121. }
  122. mconn := &MConnection{
  123. conn: conn,
  124. bufConnReader: bufio.NewReaderSize(conn, minReadBufferSize),
  125. bufConnWriter: bufio.NewWriterSize(conn, minWriteBufferSize),
  126. sendMonitor: flow.New(0, 0),
  127. recvMonitor: flow.New(0, 0),
  128. send: make(chan struct{}, 1),
  129. pong: make(chan struct{}, 1),
  130. onReceive: onReceive,
  131. onError: onError,
  132. config: config,
  133. }
  134. // Create channels
  135. var channelsIdx = map[byte]*Channel{}
  136. var channels = []*Channel{}
  137. for _, desc := range chDescs {
  138. channel := newChannel(mconn, *desc)
  139. channelsIdx[channel.desc.ID] = channel
  140. channels = append(channels, channel)
  141. }
  142. mconn.channels = channels
  143. mconn.channelsIdx = channelsIdx
  144. mconn.BaseService = *cmn.NewBaseService(nil, "MConnection", mconn)
  145. // maxPacketMsgSize() is a bit heavy, so call just once
  146. mconn._maxPacketMsgSize = mconn.maxPacketMsgSize()
  147. return mconn
  148. }
  149. func (c *MConnection) SetLogger(l log.Logger) {
  150. c.BaseService.SetLogger(l)
  151. for _, ch := range c.channels {
  152. ch.SetLogger(l)
  153. }
  154. }
  155. // OnStart implements BaseService
  156. func (c *MConnection) OnStart() error {
  157. if err := c.BaseService.OnStart(); err != nil {
  158. return err
  159. }
  160. c.quitSendRoutine = make(chan struct{})
  161. c.doneSendRoutine = make(chan struct{})
  162. c.flushTimer = cmn.NewThrottleTimer("flush", c.config.FlushThrottle)
  163. c.pingTimer = cmn.NewRepeatTimer("ping", c.config.PingInterval)
  164. c.pongTimeoutCh = make(chan bool, 1)
  165. c.chStatsTimer = cmn.NewRepeatTimer("chStats", updateStats)
  166. go c.sendRoutine()
  167. go c.recvRoutine()
  168. return nil
  169. }
  170. // FlushStop replicates the logic of OnStop.
  171. // It additionally ensures that all successful
  172. // .Send() calls will get flushed before closing
  173. // the connection.
  174. // NOTE: it is not safe to call this method more than once.
  175. func (c *MConnection) FlushStop() {
  176. c.BaseService.OnStop()
  177. c.flushTimer.Stop()
  178. c.pingTimer.Stop()
  179. c.chStatsTimer.Stop()
  180. if c.quitSendRoutine != nil {
  181. close(c.quitSendRoutine)
  182. // wait until the sendRoutine exits
  183. // so we dont race on calling sendSomePacketMsgs
  184. <-c.doneSendRoutine
  185. }
  186. // Send and flush all pending msgs.
  187. // By now, IsRunning == false,
  188. // so any concurrent attempts to send will fail.
  189. // Since sendRoutine has exited, we can call this
  190. // safely
  191. eof := c.sendSomePacketMsgs()
  192. for !eof {
  193. eof = c.sendSomePacketMsgs()
  194. }
  195. c.flush()
  196. // Now we can close the connection
  197. c.conn.Close() // nolint: errcheck
  198. // We can't close pong safely here because
  199. // recvRoutine may write to it after we've stopped.
  200. // Though it doesn't need to get closed at all,
  201. // we close it @ recvRoutine.
  202. // c.Stop()
  203. }
  204. // OnStop implements BaseService
  205. func (c *MConnection) OnStop() {
  206. select {
  207. case <-c.quitSendRoutine:
  208. // already quit via FlushStop
  209. return
  210. default:
  211. }
  212. c.BaseService.OnStop()
  213. c.flushTimer.Stop()
  214. c.pingTimer.Stop()
  215. c.chStatsTimer.Stop()
  216. close(c.quitSendRoutine)
  217. c.conn.Close() // nolint: errcheck
  218. // We can't close pong safely here because
  219. // recvRoutine may write to it after we've stopped.
  220. // Though it doesn't need to get closed at all,
  221. // we close it @ recvRoutine.
  222. }
  223. func (c *MConnection) String() string {
  224. return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr())
  225. }
  226. func (c *MConnection) flush() {
  227. c.Logger.Debug("Flush", "conn", c)
  228. err := c.bufConnWriter.Flush()
  229. if err != nil {
  230. c.Logger.Error("MConnection flush failed", "err", err)
  231. }
  232. }
  233. // Catch panics, usually caused by remote disconnects.
  234. func (c *MConnection) _recover() {
  235. if r := recover(); r != nil {
  236. err := cmn.ErrorWrap(r, "recovered panic in MConnection")
  237. c.stopForError(err)
  238. }
  239. }
  240. func (c *MConnection) stopForError(r interface{}) {
  241. c.Stop()
  242. if atomic.CompareAndSwapUint32(&c.errored, 0, 1) {
  243. if c.onError != nil {
  244. c.onError(r)
  245. }
  246. }
  247. }
  248. // Queues a message to be sent to channel.
  249. func (c *MConnection) Send(chID byte, msgBytes []byte) bool {
  250. if !c.IsRunning() {
  251. return false
  252. }
  253. c.Logger.Debug("Send", "channel", chID, "conn", c, "msgBytes", fmt.Sprintf("%X", msgBytes))
  254. // Send message to channel.
  255. channel, ok := c.channelsIdx[chID]
  256. if !ok {
  257. c.Logger.Error(fmt.Sprintf("Cannot send bytes, unknown channel %X", chID))
  258. return false
  259. }
  260. success := channel.sendBytes(msgBytes)
  261. if success {
  262. // Wake up sendRoutine if necessary
  263. select {
  264. case c.send <- struct{}{}:
  265. default:
  266. }
  267. } else {
  268. c.Logger.Debug("Send failed", "channel", chID, "conn", c, "msgBytes", fmt.Sprintf("%X", msgBytes))
  269. }
  270. return success
  271. }
  272. // Queues a message to be sent to channel.
  273. // Nonblocking, returns true if successful.
  274. func (c *MConnection) TrySend(chID byte, msgBytes []byte) bool {
  275. if !c.IsRunning() {
  276. return false
  277. }
  278. c.Logger.Debug("TrySend", "channel", chID, "conn", c, "msgBytes", fmt.Sprintf("%X", msgBytes))
  279. // Send message to channel.
  280. channel, ok := c.channelsIdx[chID]
  281. if !ok {
  282. c.Logger.Error(fmt.Sprintf("Cannot send bytes, unknown channel %X", chID))
  283. return false
  284. }
  285. ok = channel.trySendBytes(msgBytes)
  286. if ok {
  287. // Wake up sendRoutine if necessary
  288. select {
  289. case c.send <- struct{}{}:
  290. default:
  291. }
  292. }
  293. return ok
  294. }
  295. // CanSend returns true if you can send more data onto the chID, false
  296. // otherwise. Use only as a heuristic.
  297. func (c *MConnection) CanSend(chID byte) bool {
  298. if !c.IsRunning() {
  299. return false
  300. }
  301. channel, ok := c.channelsIdx[chID]
  302. if !ok {
  303. c.Logger.Error(fmt.Sprintf("Unknown channel %X", chID))
  304. return false
  305. }
  306. return channel.canSend()
  307. }
  308. // sendRoutine polls for packets to send from channels.
  309. func (c *MConnection) sendRoutine() {
  310. defer c._recover()
  311. FOR_LOOP:
  312. for {
  313. var _n int64
  314. var err error
  315. SELECTION:
  316. select {
  317. case <-c.flushTimer.Ch:
  318. // NOTE: flushTimer.Set() must be called every time
  319. // something is written to .bufConnWriter.
  320. c.flush()
  321. case <-c.chStatsTimer.Chan():
  322. for _, channel := range c.channels {
  323. channel.updateStats()
  324. }
  325. case <-c.pingTimer.Chan():
  326. c.Logger.Debug("Send Ping")
  327. _n, err = cdc.MarshalBinaryLengthPrefixedWriter(c.bufConnWriter, PacketPing{})
  328. if err != nil {
  329. break SELECTION
  330. }
  331. c.sendMonitor.Update(int(_n))
  332. c.Logger.Debug("Starting pong timer", "dur", c.config.PongTimeout)
  333. c.pongTimer = time.AfterFunc(c.config.PongTimeout, func() {
  334. select {
  335. case c.pongTimeoutCh <- true:
  336. default:
  337. }
  338. })
  339. c.flush()
  340. case timeout := <-c.pongTimeoutCh:
  341. if timeout {
  342. c.Logger.Debug("Pong timeout")
  343. err = errors.New("pong timeout")
  344. } else {
  345. c.stopPongTimer()
  346. }
  347. case <-c.pong:
  348. c.Logger.Debug("Send Pong")
  349. _n, err = cdc.MarshalBinaryLengthPrefixedWriter(c.bufConnWriter, PacketPong{})
  350. if err != nil {
  351. break SELECTION
  352. }
  353. c.sendMonitor.Update(int(_n))
  354. c.flush()
  355. case <-c.quitSendRoutine:
  356. close(c.doneSendRoutine)
  357. break FOR_LOOP
  358. case <-c.send:
  359. // Send some PacketMsgs
  360. eof := c.sendSomePacketMsgs()
  361. if !eof {
  362. // Keep sendRoutine awake.
  363. select {
  364. case c.send <- struct{}{}:
  365. default:
  366. }
  367. }
  368. }
  369. if !c.IsRunning() {
  370. break FOR_LOOP
  371. }
  372. if err != nil {
  373. c.Logger.Error("Connection failed @ sendRoutine", "conn", c, "err", err)
  374. c.stopForError(err)
  375. break FOR_LOOP
  376. }
  377. }
  378. // Cleanup
  379. c.stopPongTimer()
  380. }
  381. // Returns true if messages from channels were exhausted.
  382. // Blocks in accordance to .sendMonitor throttling.
  383. func (c *MConnection) sendSomePacketMsgs() bool {
  384. // Block until .sendMonitor says we can write.
  385. // Once we're ready we send more than we asked for,
  386. // but amortized it should even out.
  387. c.sendMonitor.Limit(c._maxPacketMsgSize, atomic.LoadInt64(&c.config.SendRate), true)
  388. // Now send some PacketMsgs.
  389. for i := 0; i < numBatchPacketMsgs; i++ {
  390. if c.sendPacketMsg() {
  391. return true
  392. }
  393. }
  394. return false
  395. }
  396. // Returns true if messages from channels were exhausted.
  397. func (c *MConnection) sendPacketMsg() bool {
  398. // Choose a channel to create a PacketMsg from.
  399. // The chosen channel will be the one whose recentlySent/priority is the least.
  400. var leastRatio float32 = math.MaxFloat32
  401. var leastChannel *Channel
  402. for _, channel := range c.channels {
  403. // If nothing to send, skip this channel
  404. if !channel.isSendPending() {
  405. continue
  406. }
  407. // Get ratio, and keep track of lowest ratio.
  408. ratio := float32(channel.recentlySent) / float32(channel.desc.Priority)
  409. if ratio < leastRatio {
  410. leastRatio = ratio
  411. leastChannel = channel
  412. }
  413. }
  414. // Nothing to send?
  415. if leastChannel == nil {
  416. return true
  417. }
  418. // c.Logger.Info("Found a msgPacket to send")
  419. // Make & send a PacketMsg from this channel
  420. _n, err := leastChannel.writePacketMsgTo(c.bufConnWriter)
  421. if err != nil {
  422. c.Logger.Error("Failed to write PacketMsg", "err", err)
  423. c.stopForError(err)
  424. return true
  425. }
  426. c.sendMonitor.Update(int(_n))
  427. c.flushTimer.Set()
  428. return false
  429. }
  430. // recvRoutine reads PacketMsgs and reconstructs the message using the channels' "recving" buffer.
  431. // After a whole message has been assembled, it's pushed to onReceive().
  432. // Blocks depending on how the connection is throttled.
  433. // Otherwise, it never blocks.
  434. func (c *MConnection) recvRoutine() {
  435. defer c._recover()
  436. FOR_LOOP:
  437. for {
  438. // Block until .recvMonitor says we can read.
  439. c.recvMonitor.Limit(c._maxPacketMsgSize, atomic.LoadInt64(&c.config.RecvRate), true)
  440. // Peek into bufConnReader for debugging
  441. /*
  442. if numBytes := c.bufConnReader.Buffered(); numBytes > 0 {
  443. bz, err := c.bufConnReader.Peek(cmn.MinInt(numBytes, 100))
  444. if err == nil {
  445. // return
  446. } else {
  447. c.Logger.Debug("Error peeking connection buffer", "err", err)
  448. // return nil
  449. }
  450. c.Logger.Info("Peek connection buffer", "numBytes", numBytes, "bz", bz)
  451. }
  452. */
  453. // Read packet type
  454. var packet Packet
  455. var _n int64
  456. var err error
  457. _n, err = cdc.UnmarshalBinaryLengthPrefixedReader(c.bufConnReader, &packet, int64(c._maxPacketMsgSize))
  458. c.recvMonitor.Update(int(_n))
  459. if err != nil {
  460. if c.IsRunning() {
  461. c.Logger.Error("Connection failed @ recvRoutine (reading byte)", "conn", c, "err", err)
  462. c.stopForError(err)
  463. }
  464. break FOR_LOOP
  465. }
  466. // Read more depending on packet type.
  467. switch pkt := packet.(type) {
  468. case PacketPing:
  469. // TODO: prevent abuse, as they cause flush()'s.
  470. // https://github.com/tendermint/tendermint/issues/1190
  471. c.Logger.Debug("Receive Ping")
  472. select {
  473. case c.pong <- struct{}{}:
  474. default:
  475. // never block
  476. }
  477. case PacketPong:
  478. c.Logger.Debug("Receive Pong")
  479. select {
  480. case c.pongTimeoutCh <- false:
  481. default:
  482. // never block
  483. }
  484. case PacketMsg:
  485. channel, ok := c.channelsIdx[pkt.ChannelID]
  486. if !ok || channel == nil {
  487. err := fmt.Errorf("Unknown channel %X", pkt.ChannelID)
  488. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  489. c.stopForError(err)
  490. break FOR_LOOP
  491. }
  492. msgBytes, err := channel.recvPacketMsg(pkt)
  493. if err != nil {
  494. if c.IsRunning() {
  495. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  496. c.stopForError(err)
  497. }
  498. break FOR_LOOP
  499. }
  500. if msgBytes != nil {
  501. c.Logger.Debug("Received bytes", "chID", pkt.ChannelID, "msgBytes", fmt.Sprintf("%X", msgBytes))
  502. // NOTE: This means the reactor.Receive runs in the same thread as the p2p recv routine
  503. c.onReceive(pkt.ChannelID, msgBytes)
  504. }
  505. default:
  506. err := fmt.Errorf("Unknown message type %v", reflect.TypeOf(packet))
  507. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  508. c.stopForError(err)
  509. break FOR_LOOP
  510. }
  511. }
  512. // Cleanup
  513. close(c.pong)
  514. for range c.pong {
  515. // Drain
  516. }
  517. }
  518. // not goroutine-safe
  519. func (c *MConnection) stopPongTimer() {
  520. if c.pongTimer != nil {
  521. _ = c.pongTimer.Stop()
  522. c.pongTimer = nil
  523. }
  524. }
  525. // maxPacketMsgSize returns a maximum size of PacketMsg, including the overhead
  526. // of amino encoding.
  527. func (c *MConnection) maxPacketMsgSize() int {
  528. return len(cdc.MustMarshalBinaryLengthPrefixed(PacketMsg{
  529. ChannelID: 0x01,
  530. EOF: 1,
  531. Bytes: make([]byte, c.config.MaxPacketMsgPayloadSize),
  532. })) + 10 // leave room for changes in amino
  533. }
  534. type ConnectionStatus struct {
  535. Duration time.Duration
  536. SendMonitor flow.Status
  537. RecvMonitor flow.Status
  538. Channels []ChannelStatus
  539. }
  540. type ChannelStatus struct {
  541. ID byte
  542. SendQueueCapacity int
  543. SendQueueSize int
  544. Priority int
  545. RecentlySent int64
  546. }
  547. func (c *MConnection) Status() ConnectionStatus {
  548. var status ConnectionStatus
  549. status.Duration = time.Since(c.created)
  550. status.SendMonitor = c.sendMonitor.Status()
  551. status.RecvMonitor = c.recvMonitor.Status()
  552. status.Channels = make([]ChannelStatus, len(c.channels))
  553. for i, channel := range c.channels {
  554. status.Channels[i] = ChannelStatus{
  555. ID: channel.desc.ID,
  556. SendQueueCapacity: cap(channel.sendQueue),
  557. SendQueueSize: int(atomic.LoadInt32(&channel.sendQueueSize)),
  558. Priority: channel.desc.Priority,
  559. RecentlySent: atomic.LoadInt64(&channel.recentlySent),
  560. }
  561. }
  562. return status
  563. }
  564. //-----------------------------------------------------------------------------
  565. type ChannelDescriptor struct {
  566. ID byte
  567. Priority int
  568. SendQueueCapacity int
  569. RecvBufferCapacity int
  570. RecvMessageCapacity int
  571. }
  572. func (chDesc ChannelDescriptor) FillDefaults() (filled ChannelDescriptor) {
  573. if chDesc.SendQueueCapacity == 0 {
  574. chDesc.SendQueueCapacity = defaultSendQueueCapacity
  575. }
  576. if chDesc.RecvBufferCapacity == 0 {
  577. chDesc.RecvBufferCapacity = defaultRecvBufferCapacity
  578. }
  579. if chDesc.RecvMessageCapacity == 0 {
  580. chDesc.RecvMessageCapacity = defaultRecvMessageCapacity
  581. }
  582. filled = chDesc
  583. return
  584. }
  585. // TODO: lowercase.
  586. // NOTE: not goroutine-safe.
  587. type Channel struct {
  588. conn *MConnection
  589. desc ChannelDescriptor
  590. sendQueue chan []byte
  591. sendQueueSize int32 // atomic.
  592. recving []byte
  593. sending []byte
  594. recentlySent int64 // exponential moving average
  595. maxPacketMsgPayloadSize int
  596. Logger log.Logger
  597. }
  598. func newChannel(conn *MConnection, desc ChannelDescriptor) *Channel {
  599. desc = desc.FillDefaults()
  600. if desc.Priority <= 0 {
  601. cmn.PanicSanity("Channel default priority must be a positive integer")
  602. }
  603. return &Channel{
  604. conn: conn,
  605. desc: desc,
  606. sendQueue: make(chan []byte, desc.SendQueueCapacity),
  607. recving: make([]byte, 0, desc.RecvBufferCapacity),
  608. maxPacketMsgPayloadSize: conn.config.MaxPacketMsgPayloadSize,
  609. }
  610. }
  611. func (ch *Channel) SetLogger(l log.Logger) {
  612. ch.Logger = l
  613. }
  614. // Queues message to send to this channel.
  615. // Goroutine-safe
  616. // Times out (and returns false) after defaultSendTimeout
  617. func (ch *Channel) sendBytes(bytes []byte) bool {
  618. select {
  619. case ch.sendQueue <- bytes:
  620. atomic.AddInt32(&ch.sendQueueSize, 1)
  621. return true
  622. case <-time.After(defaultSendTimeout):
  623. return false
  624. }
  625. }
  626. // Queues message to send to this channel.
  627. // Nonblocking, returns true if successful.
  628. // Goroutine-safe
  629. func (ch *Channel) trySendBytes(bytes []byte) bool {
  630. select {
  631. case ch.sendQueue <- bytes:
  632. atomic.AddInt32(&ch.sendQueueSize, 1)
  633. return true
  634. default:
  635. return false
  636. }
  637. }
  638. // Goroutine-safe
  639. func (ch *Channel) loadSendQueueSize() (size int) {
  640. return int(atomic.LoadInt32(&ch.sendQueueSize))
  641. }
  642. // Goroutine-safe
  643. // Use only as a heuristic.
  644. func (ch *Channel) canSend() bool {
  645. return ch.loadSendQueueSize() < defaultSendQueueCapacity
  646. }
  647. // Returns true if any PacketMsgs are pending to be sent.
  648. // Call before calling nextPacketMsg()
  649. // Goroutine-safe
  650. func (ch *Channel) isSendPending() bool {
  651. if len(ch.sending) == 0 {
  652. if len(ch.sendQueue) == 0 {
  653. return false
  654. }
  655. ch.sending = <-ch.sendQueue
  656. }
  657. return true
  658. }
  659. // Creates a new PacketMsg to send.
  660. // Not goroutine-safe
  661. func (ch *Channel) nextPacketMsg() PacketMsg {
  662. packet := PacketMsg{}
  663. packet.ChannelID = byte(ch.desc.ID)
  664. maxSize := ch.maxPacketMsgPayloadSize
  665. packet.Bytes = ch.sending[:cmn.MinInt(maxSize, len(ch.sending))]
  666. if len(ch.sending) <= maxSize {
  667. packet.EOF = byte(0x01)
  668. ch.sending = nil
  669. atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize
  670. } else {
  671. packet.EOF = byte(0x00)
  672. ch.sending = ch.sending[cmn.MinInt(maxSize, len(ch.sending)):]
  673. }
  674. return packet
  675. }
  676. // Writes next PacketMsg to w and updates c.recentlySent.
  677. // Not goroutine-safe
  678. func (ch *Channel) writePacketMsgTo(w io.Writer) (n int64, err error) {
  679. var packet = ch.nextPacketMsg()
  680. n, err = cdc.MarshalBinaryLengthPrefixedWriter(w, packet)
  681. atomic.AddInt64(&ch.recentlySent, n)
  682. return
  683. }
  684. // Handles incoming PacketMsgs. It returns a message bytes if message is
  685. // complete. NOTE message bytes may change on next call to recvPacketMsg.
  686. // Not goroutine-safe
  687. func (ch *Channel) recvPacketMsg(packet PacketMsg) ([]byte, error) {
  688. ch.Logger.Debug("Read PacketMsg", "conn", ch.conn, "packet", packet)
  689. var recvCap, recvReceived = ch.desc.RecvMessageCapacity, len(ch.recving) + len(packet.Bytes)
  690. if recvCap < recvReceived {
  691. return nil, fmt.Errorf("Received message exceeds available capacity: %v < %v", recvCap, recvReceived)
  692. }
  693. ch.recving = append(ch.recving, packet.Bytes...)
  694. if packet.EOF == byte(0x01) {
  695. msgBytes := ch.recving
  696. // clear the slice without re-allocating.
  697. // http://stackoverflow.com/questions/16971741/how-do-you-clear-a-slice-in-go
  698. // suggests this could be a memory leak, but we might as well keep the memory for the channel until it closes,
  699. // at which point the recving slice stops being used and should be garbage collected
  700. ch.recving = ch.recving[:0] // make([]byte, 0, ch.desc.RecvBufferCapacity)
  701. return msgBytes, nil
  702. }
  703. return nil, nil
  704. }
  705. // Call this periodically to update stats for throttling purposes.
  706. // Not goroutine-safe
  707. func (ch *Channel) updateStats() {
  708. // Exponential decay of stats.
  709. // TODO: optimize.
  710. atomic.StoreInt64(&ch.recentlySent, int64(float64(atomic.LoadInt64(&ch.recentlySent))*0.8))
  711. }
  712. //----------------------------------------
  713. // Packet
  714. type Packet interface {
  715. AssertIsPacket()
  716. }
  717. func RegisterPacket(cdc *amino.Codec) {
  718. cdc.RegisterInterface((*Packet)(nil), nil)
  719. cdc.RegisterConcrete(PacketPing{}, "tendermint/p2p/PacketPing", nil)
  720. cdc.RegisterConcrete(PacketPong{}, "tendermint/p2p/PacketPong", nil)
  721. cdc.RegisterConcrete(PacketMsg{}, "tendermint/p2p/PacketMsg", nil)
  722. }
  723. func (_ PacketPing) AssertIsPacket() {}
  724. func (_ PacketPong) AssertIsPacket() {}
  725. func (_ PacketMsg) AssertIsPacket() {}
  726. type PacketPing struct {
  727. }
  728. type PacketPong struct {
  729. }
  730. type PacketMsg struct {
  731. ChannelID byte
  732. EOF byte // 1 means message ends here.
  733. Bytes []byte
  734. }
  735. func (mp PacketMsg) String() string {
  736. return fmt.Sprintf("PacketMsg{%X:%X T:%X}", mp.ChannelID, mp.Bytes, mp.EOF)
  737. }