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.

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