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.

604 lines
16 KiB

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