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.

639 lines
16 KiB

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