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.

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