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.

792 lines
21 KiB

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