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.

783 lines
21 KiB

p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
3 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
3 years ago
  1. package conn
  2. import (
  3. "bufio"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math"
  9. "net"
  10. "reflect"
  11. "runtime/debug"
  12. "sync"
  13. "sync/atomic"
  14. "time"
  15. "github.com/gogo/protobuf/proto"
  16. "github.com/tendermint/tendermint/internal/libs/flowrate"
  17. "github.com/tendermint/tendermint/internal/libs/protoio"
  18. "github.com/tendermint/tendermint/internal/libs/timer"
  19. "github.com/tendermint/tendermint/libs/log"
  20. tmmath "github.com/tendermint/tendermint/libs/math"
  21. "github.com/tendermint/tendermint/libs/service"
  22. tmp2p "github.com/tendermint/tendermint/proto/tendermint/p2p"
  23. )
  24. const (
  25. // mirrors MaxPacketMsgPayloadSize from config/config.go
  26. defaultMaxPacketMsgPayloadSize = 1400
  27. numBatchPacketMsgs = 10
  28. minReadBufferSize = 1024
  29. minWriteBufferSize = 65536
  30. updateStats = 2 * time.Second
  31. // some of these defaults are written in the user config
  32. // flushThrottle, sendRate, recvRate
  33. // TODO: remove values present in config
  34. defaultFlushThrottle = 100 * time.Millisecond
  35. defaultSendQueueCapacity = 1
  36. defaultRecvBufferCapacity = 4096
  37. defaultRecvMessageCapacity = 22020096 // 21MB
  38. defaultSendRate = int64(512000) // 500KB/s
  39. defaultRecvRate = int64(512000) // 500KB/s
  40. defaultSendTimeout = 10 * time.Second
  41. defaultPingInterval = 60 * time.Second
  42. defaultPongTimeout = 45 * time.Second
  43. )
  44. type receiveCbFunc func(ctx context.Context, chID ChannelID, msgBytes []byte)
  45. type errorCbFunc func(context.Context, interface{})
  46. /*
  47. Each peer has one `MConnection` (multiplex connection) instance.
  48. __multiplex__ *noun* a system or signal involving simultaneous transmission of
  49. several messages along a single channel of communication.
  50. Each `MConnection` handles message transmission on multiple abstract communication
  51. `Channel`s. Each channel has a globally unique byte id.
  52. The byte id and the relative priorities of each `Channel` are configured upon
  53. initialization of the connection.
  54. There are two methods for sending messages:
  55. func (m MConnection) Send(chID byte, msgBytes []byte) bool {}
  56. `Send(chID, msgBytes)` is a blocking call that waits until `msg` is
  57. successfully queued for the channel with the given id byte `chID`, or until the
  58. request times out. The message `msg` is serialized using Protobuf.
  59. Inbound message bytes are handled with an onReceive callback function.
  60. */
  61. type MConnection struct {
  62. service.BaseService
  63. logger log.Logger
  64. conn net.Conn
  65. bufConnReader *bufio.Reader
  66. bufConnWriter *bufio.Writer
  67. sendMonitor *flowrate.Monitor
  68. recvMonitor *flowrate.Monitor
  69. send chan struct{}
  70. pong chan struct{}
  71. channels []*channel
  72. channelsIdx map[ChannelID]*channel
  73. onReceive receiveCbFunc
  74. onError errorCbFunc
  75. errored uint32
  76. config MConnConfig
  77. // Closing quitSendRoutine will cause the sendRoutine to eventually quit.
  78. // doneSendRoutine is closed when the sendRoutine actually quits.
  79. quitSendRoutine chan struct{}
  80. doneSendRoutine chan struct{}
  81. // Closing quitRecvRouting will cause the recvRouting to eventually quit.
  82. quitRecvRoutine chan struct{}
  83. // used to ensure FlushStop and OnStop
  84. // are safe to call concurrently.
  85. stopMtx sync.Mutex
  86. cancel context.CancelFunc
  87. flushTimer *timer.ThrottleTimer // flush writes as necessary but throttled.
  88. pingTimer *time.Ticker // send pings periodically
  89. // close conn if pong is not received in pongTimeout
  90. pongTimer *time.Timer
  91. pongTimeoutCh chan bool // true - timeout, false - peer sent pong
  92. chStatsTimer *time.Ticker // update channel stats periodically
  93. created time.Time // time of creation
  94. _maxPacketMsgSize int
  95. }
  96. // MConnConfig is a MConnection configuration.
  97. type MConnConfig struct {
  98. SendRate int64 `mapstructure:"send_rate"`
  99. RecvRate int64 `mapstructure:"recv_rate"`
  100. // Maximum payload size
  101. MaxPacketMsgPayloadSize int `mapstructure:"max_packet_msg_payload_size"`
  102. // Interval to flush writes (throttled)
  103. FlushThrottle time.Duration `mapstructure:"flush_throttle"`
  104. // Interval to send pings
  105. PingInterval time.Duration `mapstructure:"ping_interval"`
  106. // Maximum wait time for pongs
  107. PongTimeout time.Duration `mapstructure:"pong_timeout"`
  108. }
  109. // DefaultMConnConfig returns the default config.
  110. func DefaultMConnConfig() MConnConfig {
  111. return MConnConfig{
  112. SendRate: defaultSendRate,
  113. RecvRate: defaultRecvRate,
  114. MaxPacketMsgPayloadSize: defaultMaxPacketMsgPayloadSize,
  115. FlushThrottle: defaultFlushThrottle,
  116. PingInterval: defaultPingInterval,
  117. PongTimeout: defaultPongTimeout,
  118. }
  119. }
  120. // NewMConnection wraps net.Conn and creates multiplex connection
  121. func NewMConnection(
  122. logger log.Logger,
  123. conn net.Conn,
  124. chDescs []*ChannelDescriptor,
  125. onReceive receiveCbFunc,
  126. onError errorCbFunc,
  127. ) *MConnection {
  128. return NewMConnectionWithConfig(
  129. logger,
  130. conn,
  131. chDescs,
  132. onReceive,
  133. onError,
  134. DefaultMConnConfig())
  135. }
  136. // NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config
  137. func NewMConnectionWithConfig(
  138. logger log.Logger,
  139. conn net.Conn,
  140. chDescs []*ChannelDescriptor,
  141. onReceive receiveCbFunc,
  142. onError errorCbFunc,
  143. config MConnConfig,
  144. ) *MConnection {
  145. if config.PongTimeout >= config.PingInterval {
  146. panic("pongTimeout must be less than pingInterval (otherwise, next ping will reset pong timer)")
  147. }
  148. mconn := &MConnection{
  149. logger: logger,
  150. conn: conn,
  151. bufConnReader: bufio.NewReaderSize(conn, minReadBufferSize),
  152. bufConnWriter: bufio.NewWriterSize(conn, minWriteBufferSize),
  153. sendMonitor: flowrate.New(0, 0),
  154. recvMonitor: flowrate.New(0, 0),
  155. send: make(chan struct{}, 1),
  156. pong: make(chan struct{}, 1),
  157. onReceive: onReceive,
  158. onError: onError,
  159. config: config,
  160. created: time.Now(),
  161. cancel: func() {},
  162. }
  163. mconn.BaseService = *service.NewBaseService(logger, "MConnection", mconn)
  164. // Create channels
  165. var channelsIdx = map[ChannelID]*channel{}
  166. var channels = []*channel{}
  167. for _, desc := range chDescs {
  168. channel := newChannel(mconn, *desc)
  169. channelsIdx[channel.desc.ID] = channel
  170. channels = append(channels, channel)
  171. }
  172. mconn.channels = channels
  173. mconn.channelsIdx = channelsIdx
  174. // maxPacketMsgSize() is a bit heavy, so call just once
  175. mconn._maxPacketMsgSize = mconn.maxPacketMsgSize()
  176. return mconn
  177. }
  178. // OnStart implements BaseService
  179. func (c *MConnection) OnStart(ctx context.Context) error {
  180. c.flushTimer = timer.NewThrottleTimer("flush", c.config.FlushThrottle)
  181. c.pingTimer = time.NewTicker(c.config.PingInterval)
  182. c.pongTimeoutCh = make(chan bool, 1)
  183. c.chStatsTimer = time.NewTicker(updateStats)
  184. c.quitSendRoutine = make(chan struct{})
  185. c.doneSendRoutine = make(chan struct{})
  186. c.quitRecvRoutine = make(chan struct{})
  187. go c.sendRoutine(ctx)
  188. go c.recvRoutine(ctx)
  189. return nil
  190. }
  191. // stopServices stops the BaseService and timers and closes the quitSendRoutine.
  192. // if the quitSendRoutine was already closed, it returns true, otherwise it returns false.
  193. // It uses the stopMtx to ensure only one of FlushStop and OnStop can do this at a time.
  194. func (c *MConnection) stopServices() (alreadyStopped bool) {
  195. c.stopMtx.Lock()
  196. defer c.stopMtx.Unlock()
  197. select {
  198. case <-c.quitSendRoutine:
  199. // already quit
  200. return true
  201. default:
  202. }
  203. select {
  204. case <-c.quitRecvRoutine:
  205. // already quit
  206. return true
  207. default:
  208. }
  209. c.flushTimer.Stop()
  210. c.pingTimer.Stop()
  211. c.chStatsTimer.Stop()
  212. // inform the recvRouting that we are shutting down
  213. close(c.quitRecvRoutine)
  214. close(c.quitSendRoutine)
  215. return false
  216. }
  217. // OnStop implements BaseService
  218. func (c *MConnection) OnStop() {
  219. if c.stopServices() {
  220. return
  221. }
  222. c.conn.Close()
  223. // We can't close pong safely here because
  224. // recvRoutine may write to it after we've stopped.
  225. // Though it doesn't need to get closed at all,
  226. // we close it @ recvRoutine.
  227. }
  228. func (c *MConnection) String() string {
  229. return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr())
  230. }
  231. func (c *MConnection) flush() {
  232. c.logger.Debug("Flush", "conn", c)
  233. err := c.bufConnWriter.Flush()
  234. if err != nil {
  235. c.logger.Debug("MConnection flush failed", "err", err)
  236. }
  237. }
  238. // Catch panics, usually caused by remote disconnects.
  239. func (c *MConnection) _recover(ctx context.Context) {
  240. if r := recover(); r != nil {
  241. c.logger.Error("MConnection panicked", "err", r, "stack", string(debug.Stack()))
  242. c.stopForError(ctx, fmt.Errorf("recovered from panic: %v", r))
  243. }
  244. }
  245. func (c *MConnection) stopForError(ctx context.Context, r interface{}) {
  246. c.Stop()
  247. if atomic.CompareAndSwapUint32(&c.errored, 0, 1) {
  248. if c.onError != nil {
  249. c.onError(ctx, r)
  250. }
  251. }
  252. }
  253. // Queues a message to be sent to channel.
  254. func (c *MConnection) Send(chID ChannelID, msgBytes []byte) bool {
  255. if !c.IsRunning() {
  256. return false
  257. }
  258. c.logger.Debug("Send", "channel", chID, "conn", c, "msgBytes", msgBytes)
  259. // Send message to channel.
  260. channel, ok := c.channelsIdx[chID]
  261. if !ok {
  262. c.logger.Error(fmt.Sprintf("Cannot send bytes, unknown channel %X", chID))
  263. return false
  264. }
  265. success := channel.sendBytes(msgBytes)
  266. if success {
  267. // Wake up sendRoutine if necessary
  268. select {
  269. case c.send <- struct{}{}:
  270. default:
  271. }
  272. } else {
  273. c.logger.Debug("Send failed", "channel", chID, "conn", c, "msgBytes", msgBytes)
  274. }
  275. return success
  276. }
  277. // sendRoutine polls for packets to send from channels.
  278. func (c *MConnection) sendRoutine(ctx context.Context) {
  279. defer c._recover(ctx)
  280. protoWriter := protoio.NewDelimitedWriter(c.bufConnWriter)
  281. FOR_LOOP:
  282. for {
  283. var _n int
  284. var err error
  285. SELECTION:
  286. select {
  287. case <-c.flushTimer.Ch:
  288. // NOTE: flushTimer.Set() must be called every time
  289. // something is written to .bufConnWriter.
  290. c.flush()
  291. case <-c.chStatsTimer.C:
  292. for _, channel := range c.channels {
  293. channel.updateStats()
  294. }
  295. case <-c.pingTimer.C:
  296. _n, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPing{}))
  297. if err != nil {
  298. c.logger.Error("Failed to send PacketPing", "err", err)
  299. break SELECTION
  300. }
  301. c.sendMonitor.Update(_n)
  302. c.logger.Debug("Starting pong timer", "dur", c.config.PongTimeout)
  303. c.pongTimer = time.AfterFunc(c.config.PongTimeout, func() {
  304. select {
  305. case c.pongTimeoutCh <- true:
  306. default:
  307. }
  308. })
  309. c.flush()
  310. case timeout := <-c.pongTimeoutCh:
  311. if timeout {
  312. err = errors.New("pong timeout")
  313. } else {
  314. c.stopPongTimer()
  315. }
  316. case <-c.pong:
  317. _n, err = protoWriter.WriteMsg(mustWrapPacket(&tmp2p.PacketPong{}))
  318. if err != nil {
  319. c.logger.Error("Failed to send PacketPong", "err", err)
  320. break SELECTION
  321. }
  322. c.sendMonitor.Update(_n)
  323. c.flush()
  324. case <-ctx.Done():
  325. break FOR_LOOP
  326. case <-c.quitSendRoutine:
  327. break FOR_LOOP
  328. case <-c.send:
  329. // Send some PacketMsgs
  330. eof := c.sendSomePacketMsgs(ctx)
  331. if !eof {
  332. // Keep sendRoutine awake.
  333. select {
  334. case c.send <- struct{}{}:
  335. default:
  336. }
  337. }
  338. }
  339. if !c.IsRunning() {
  340. break FOR_LOOP
  341. }
  342. if err != nil {
  343. c.logger.Error("Connection failed @ sendRoutine", "conn", c, "err", err)
  344. c.stopForError(ctx, err)
  345. break FOR_LOOP
  346. }
  347. }
  348. // Cleanup
  349. c.stopPongTimer()
  350. close(c.doneSendRoutine)
  351. }
  352. // Returns true if messages from channels were exhausted.
  353. // Blocks in accordance to .sendMonitor throttling.
  354. func (c *MConnection) sendSomePacketMsgs(ctx context.Context) bool {
  355. // Block until .sendMonitor says we can write.
  356. // Once we're ready we send more than we asked for,
  357. // but amortized it should even out.
  358. c.sendMonitor.Limit(c._maxPacketMsgSize, atomic.LoadInt64(&c.config.SendRate), true)
  359. // Now send some PacketMsgs.
  360. for i := 0; i < numBatchPacketMsgs; i++ {
  361. if c.sendPacketMsg(ctx) {
  362. return true
  363. }
  364. }
  365. return false
  366. }
  367. // Returns true if messages from channels were exhausted.
  368. func (c *MConnection) sendPacketMsg(ctx context.Context) bool {
  369. // Choose a channel to create a PacketMsg from.
  370. // The chosen channel will be the one whose recentlySent/priority is the least.
  371. var leastRatio float32 = math.MaxFloat32
  372. var leastChannel *channel
  373. for _, channel := range c.channels {
  374. // If nothing to send, skip this channel
  375. if !channel.isSendPending() {
  376. continue
  377. }
  378. // Get ratio, and keep track of lowest ratio.
  379. ratio := float32(channel.recentlySent) / float32(channel.desc.Priority)
  380. if ratio < leastRatio {
  381. leastRatio = ratio
  382. leastChannel = channel
  383. }
  384. }
  385. // Nothing to send?
  386. if leastChannel == nil {
  387. return true
  388. }
  389. // c.logger.Info("Found a msgPacket to send")
  390. // Make & send a PacketMsg from this channel
  391. _n, err := leastChannel.writePacketMsgTo(c.bufConnWriter)
  392. if err != nil {
  393. c.logger.Error("Failed to write PacketMsg", "err", err)
  394. c.stopForError(ctx, err)
  395. return true
  396. }
  397. c.sendMonitor.Update(_n)
  398. c.flushTimer.Set()
  399. return false
  400. }
  401. // recvRoutine reads PacketMsgs and reconstructs the message using the channels' "recving" buffer.
  402. // After a whole message has been assembled, it's pushed to onReceive().
  403. // Blocks depending on how the connection is throttled.
  404. // Otherwise, it never blocks.
  405. func (c *MConnection) recvRoutine(ctx context.Context) {
  406. defer c._recover(ctx)
  407. protoReader := protoio.NewDelimitedReader(c.bufConnReader, c._maxPacketMsgSize)
  408. FOR_LOOP:
  409. for {
  410. // Block until .recvMonitor says we can read.
  411. c.recvMonitor.Limit(c._maxPacketMsgSize, atomic.LoadInt64(&c.config.RecvRate), true)
  412. // Peek into bufConnReader for debugging
  413. /*
  414. if numBytes := c.bufConnReader.Buffered(); numBytes > 0 {
  415. bz, err := c.bufConnReader.Peek(tmmath.MinInt(numBytes, 100))
  416. if err == nil {
  417. // return
  418. } else {
  419. c.logger.Debug("error peeking connection buffer", "err", err)
  420. // return nil
  421. }
  422. c.logger.Info("Peek connection buffer", "numBytes", numBytes, "bz", bz)
  423. }
  424. */
  425. // Read packet type
  426. var packet tmp2p.Packet
  427. _n, err := protoReader.ReadMsg(&packet)
  428. c.recvMonitor.Update(_n)
  429. if err != nil {
  430. // stopServices was invoked and we are shutting down
  431. // receiving is excpected to fail since we will close the connection
  432. select {
  433. case <-ctx.Done():
  434. case <-c.quitRecvRoutine:
  435. break FOR_LOOP
  436. default:
  437. }
  438. if c.IsRunning() {
  439. if err == io.EOF {
  440. c.logger.Info("Connection is closed @ recvRoutine (likely by the other side)", "conn", c)
  441. } else {
  442. c.logger.Debug("Connection failed @ recvRoutine (reading byte)", "conn", c, "err", err)
  443. }
  444. c.stopForError(ctx, err)
  445. }
  446. break FOR_LOOP
  447. }
  448. // Read more depending on packet type.
  449. switch pkt := packet.Sum.(type) {
  450. case *tmp2p.Packet_PacketPing:
  451. // TODO: prevent abuse, as they cause flush()'s.
  452. // https://github.com/tendermint/tendermint/issues/1190
  453. select {
  454. case c.pong <- struct{}{}:
  455. default:
  456. // never block
  457. }
  458. case *tmp2p.Packet_PacketPong:
  459. select {
  460. case c.pongTimeoutCh <- false:
  461. default:
  462. // never block
  463. }
  464. case *tmp2p.Packet_PacketMsg:
  465. channelID := ChannelID(pkt.PacketMsg.ChannelID)
  466. channel, ok := c.channelsIdx[channelID]
  467. if pkt.PacketMsg.ChannelID < 0 || pkt.PacketMsg.ChannelID > math.MaxUint8 || !ok || channel == nil {
  468. err := fmt.Errorf("unknown channel %X", pkt.PacketMsg.ChannelID)
  469. c.logger.Debug("Connection failed @ recvRoutine", "conn", c, "err", err)
  470. c.stopForError(ctx, err)
  471. break FOR_LOOP
  472. }
  473. msgBytes, err := channel.recvPacketMsg(*pkt.PacketMsg)
  474. if err != nil {
  475. if c.IsRunning() {
  476. c.logger.Debug("Connection failed @ recvRoutine", "conn", c, "err", err)
  477. c.stopForError(ctx, err)
  478. }
  479. break FOR_LOOP
  480. }
  481. if msgBytes != nil {
  482. c.logger.Debug("Received bytes", "chID", channelID, "msgBytes", msgBytes)
  483. // NOTE: This means the reactor.Receive runs in the same thread as the p2p recv routine
  484. c.onReceive(ctx, channelID, msgBytes)
  485. }
  486. default:
  487. err := fmt.Errorf("unknown message type %v", reflect.TypeOf(packet))
  488. c.logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  489. c.stopForError(ctx, err)
  490. break FOR_LOOP
  491. }
  492. }
  493. // Cleanup
  494. close(c.pong)
  495. for range c.pong {
  496. // Drain
  497. }
  498. }
  499. // not goroutine-safe
  500. func (c *MConnection) stopPongTimer() {
  501. if c.pongTimer != nil {
  502. _ = c.pongTimer.Stop()
  503. c.pongTimer = nil
  504. }
  505. }
  506. // maxPacketMsgSize returns a maximum size of PacketMsg
  507. func (c *MConnection) maxPacketMsgSize() int {
  508. bz, err := proto.Marshal(mustWrapPacket(&tmp2p.PacketMsg{
  509. ChannelID: 0x01,
  510. EOF: true,
  511. Data: make([]byte, c.config.MaxPacketMsgPayloadSize),
  512. }))
  513. if err != nil {
  514. panic(err)
  515. }
  516. return len(bz)
  517. }
  518. type ChannelStatus struct {
  519. ID byte
  520. SendQueueCapacity int
  521. SendQueueSize int
  522. Priority int
  523. RecentlySent int64
  524. }
  525. //-----------------------------------------------------------------------------
  526. // ChannelID is an arbitrary channel ID.
  527. type ChannelID uint16
  528. type ChannelDescriptor struct {
  529. ID ChannelID
  530. Priority int
  531. MessageType proto.Message
  532. // TODO: Remove once p2p refactor is complete.
  533. SendQueueCapacity int
  534. RecvMessageCapacity int
  535. // RecvBufferCapacity defines the max buffer size of inbound messages for a
  536. // given p2p Channel queue.
  537. RecvBufferCapacity int
  538. }
  539. func (chDesc ChannelDescriptor) FillDefaults() (filled ChannelDescriptor) {
  540. if chDesc.SendQueueCapacity == 0 {
  541. chDesc.SendQueueCapacity = defaultSendQueueCapacity
  542. }
  543. if chDesc.RecvBufferCapacity == 0 {
  544. chDesc.RecvBufferCapacity = defaultRecvBufferCapacity
  545. }
  546. if chDesc.RecvMessageCapacity == 0 {
  547. chDesc.RecvMessageCapacity = defaultRecvMessageCapacity
  548. }
  549. filled = chDesc
  550. return
  551. }
  552. // NOTE: not goroutine-safe.
  553. type channel struct {
  554. // Exponential moving average.
  555. // This field must be accessed atomically.
  556. // It is first in the struct to ensure correct alignment.
  557. // See https://github.com/tendermint/tendermint/issues/7000.
  558. recentlySent int64
  559. conn *MConnection
  560. desc ChannelDescriptor
  561. sendQueue chan []byte
  562. sendQueueSize int32 // atomic.
  563. recving []byte
  564. sending []byte
  565. maxPacketMsgPayloadSize int
  566. logger log.Logger
  567. }
  568. func newChannel(conn *MConnection, desc ChannelDescriptor) *channel {
  569. desc = desc.FillDefaults()
  570. if desc.Priority <= 0 {
  571. panic("Channel default priority must be a positive integer")
  572. }
  573. return &channel{
  574. conn: conn,
  575. desc: desc,
  576. sendQueue: make(chan []byte, desc.SendQueueCapacity),
  577. recving: make([]byte, 0, desc.RecvBufferCapacity),
  578. maxPacketMsgPayloadSize: conn.config.MaxPacketMsgPayloadSize,
  579. logger: conn.logger,
  580. }
  581. }
  582. // Queues message to send to this channel.
  583. // Goroutine-safe
  584. // Times out (and returns false) after defaultSendTimeout
  585. func (ch *channel) sendBytes(bytes []byte) bool {
  586. select {
  587. case ch.sendQueue <- bytes:
  588. atomic.AddInt32(&ch.sendQueueSize, 1)
  589. return true
  590. case <-time.After(defaultSendTimeout):
  591. return false
  592. }
  593. }
  594. // Returns true if any PacketMsgs are pending to be sent.
  595. // Call before calling nextPacketMsg()
  596. // Goroutine-safe
  597. func (ch *channel) isSendPending() bool {
  598. if len(ch.sending) == 0 {
  599. if len(ch.sendQueue) == 0 {
  600. return false
  601. }
  602. ch.sending = <-ch.sendQueue
  603. }
  604. return true
  605. }
  606. // Creates a new PacketMsg to send.
  607. // Not goroutine-safe
  608. func (ch *channel) nextPacketMsg() tmp2p.PacketMsg {
  609. packet := tmp2p.PacketMsg{ChannelID: int32(ch.desc.ID)}
  610. maxSize := ch.maxPacketMsgPayloadSize
  611. packet.Data = ch.sending[:tmmath.MinInt(maxSize, len(ch.sending))]
  612. if len(ch.sending) <= maxSize {
  613. packet.EOF = true
  614. ch.sending = nil
  615. atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize
  616. } else {
  617. packet.EOF = false
  618. ch.sending = ch.sending[tmmath.MinInt(maxSize, len(ch.sending)):]
  619. }
  620. return packet
  621. }
  622. // Writes next PacketMsg to w and updates c.recentlySent.
  623. // Not goroutine-safe
  624. func (ch *channel) writePacketMsgTo(w io.Writer) (n int, err error) {
  625. packet := ch.nextPacketMsg()
  626. n, err = protoio.NewDelimitedWriter(w).WriteMsg(mustWrapPacket(&packet))
  627. atomic.AddInt64(&ch.recentlySent, int64(n))
  628. return
  629. }
  630. // Handles incoming PacketMsgs. It returns a message bytes if message is
  631. // complete, which is owned by the caller and will not be modified.
  632. // Not goroutine-safe
  633. func (ch *channel) recvPacketMsg(packet tmp2p.PacketMsg) ([]byte, error) {
  634. ch.logger.Debug("Read PacketMsg", "conn", ch.conn, "packet", packet)
  635. var recvCap, recvReceived = ch.desc.RecvMessageCapacity, len(ch.recving) + len(packet.Data)
  636. if recvCap < recvReceived {
  637. return nil, fmt.Errorf("received message exceeds available capacity: %v < %v", recvCap, recvReceived)
  638. }
  639. ch.recving = append(ch.recving, packet.Data...)
  640. if packet.EOF {
  641. msgBytes := ch.recving
  642. ch.recving = make([]byte, 0, ch.desc.RecvBufferCapacity)
  643. return msgBytes, nil
  644. }
  645. return nil, nil
  646. }
  647. // Call this periodically to update stats for throttling purposes.
  648. // Not goroutine-safe
  649. func (ch *channel) updateStats() {
  650. // Exponential decay of stats.
  651. // TODO: optimize.
  652. atomic.StoreInt64(&ch.recentlySent, int64(float64(atomic.LoadInt64(&ch.recentlySent))*0.8))
  653. }
  654. //----------------------------------------
  655. // Packet
  656. // mustWrapPacket takes a packet kind (oneof) and wraps it in a tmp2p.Packet message.
  657. func mustWrapPacket(pb proto.Message) *tmp2p.Packet {
  658. var msg tmp2p.Packet
  659. switch pb := pb.(type) {
  660. case *tmp2p.Packet: // already a packet
  661. msg = *pb
  662. case *tmp2p.PacketPing:
  663. msg = tmp2p.Packet{
  664. Sum: &tmp2p.Packet_PacketPing{
  665. PacketPing: pb,
  666. },
  667. }
  668. case *tmp2p.PacketPong:
  669. msg = tmp2p.Packet{
  670. Sum: &tmp2p.Packet_PacketPong{
  671. PacketPong: pb,
  672. },
  673. }
  674. case *tmp2p.PacketMsg:
  675. msg = tmp2p.Packet{
  676. Sum: &tmp2p.Packet_PacketMsg{
  677. PacketMsg: pb,
  678. },
  679. }
  680. default:
  681. panic(fmt.Errorf("unknown packet type %T", pb))
  682. }
  683. return &msg
  684. }