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.

618 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
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
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
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
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
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`, or until the request times out.
  45. The message `msg` is serialized using the `tendermint/binary` submodule's
  46. `WriteBinary()` reflection routine.
  47. `TrySend(chId, msg)` is a nonblocking call that returns false if the channel's
  48. queue is full.
  49. Inbound message bytes are handled with an onReceive callback function.
  50. */
  51. type MConnection struct {
  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. flushTimer *ThrottleTimer // flush writes as necessary but throttled.
  60. send chan struct{}
  61. quit chan struct{}
  62. pingTimer *RepeatTimer // send pings periodically
  63. pong chan struct{}
  64. chStatsTimer *RepeatTimer // update channel stats periodically
  65. channels []*Channel
  66. channelsIdx map[byte]*Channel
  67. onReceive receiveCbFunc
  68. onError errorCbFunc
  69. started uint32
  70. stopped uint32
  71. errored uint32
  72. LocalAddress *NetAddress
  73. RemoteAddress *NetAddress
  74. }
  75. func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection {
  76. mconn := &MConnection{
  77. conn: conn,
  78. bufReader: bufio.NewReaderSize(conn, minReadBufferSize),
  79. bufWriter: bufio.NewWriterSize(conn, minWriteBufferSize),
  80. sendMonitor: flow.New(0, 0),
  81. recvMonitor: flow.New(0, 0),
  82. sendRate: defaultSendRate,
  83. recvRate: defaultRecvRate,
  84. flushTimer: NewThrottleTimer("flush", flushThrottleMS*time.Millisecond),
  85. send: make(chan struct{}, 1),
  86. quit: make(chan struct{}),
  87. pingTimer: NewRepeatTimer("ping", pingTimeoutMinutes*time.Minute),
  88. pong: make(chan struct{}),
  89. chStatsTimer: NewRepeatTimer("chStats", updateStatsSeconds*time.Second),
  90. onReceive: onReceive,
  91. onError: onError,
  92. LocalAddress: NewNetAddress(conn.LocalAddr()),
  93. RemoteAddress: NewNetAddress(conn.RemoteAddr()),
  94. }
  95. // Create channels
  96. var channelsIdx = map[byte]*Channel{}
  97. var channels = []*Channel{}
  98. for _, desc := range chDescs {
  99. channel := newChannel(mconn, desc)
  100. channelsIdx[channel.id] = channel
  101. channels = append(channels, channel)
  102. }
  103. mconn.channels = channels
  104. mconn.channelsIdx = channelsIdx
  105. return mconn
  106. }
  107. // .Start() begins multiplexing packets to and from "channels".
  108. func (c *MConnection) Start() {
  109. if atomic.CompareAndSwapUint32(&c.started, 0, 1) {
  110. log.Debug("Starting MConnection", "connection", c)
  111. go c.sendRoutine()
  112. go c.recvRoutine()
  113. }
  114. }
  115. func (c *MConnection) Stop() {
  116. if atomic.CompareAndSwapUint32(&c.stopped, 0, 1) {
  117. log.Debug("Stopping MConnection", "connection", c)
  118. close(c.quit)
  119. c.conn.Close()
  120. c.flushTimer.Stop()
  121. c.chStatsTimer.Stop()
  122. c.pingTimer.Stop()
  123. // We can't close pong safely here because
  124. // recvRoutine may write to it after we've stopped.
  125. // Though it doesn't need to get closed at all,
  126. // we close it @ recvRoutine.
  127. // close(c.pong)
  128. }
  129. }
  130. func (c *MConnection) String() string {
  131. return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr())
  132. }
  133. func (c *MConnection) flush() {
  134. err := c.bufWriter.Flush()
  135. if err != nil {
  136. log.Warn("MConnection flush failed", "error", err)
  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", binary.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. success := channel.sendBytes(binary.BinaryBytes(msg))
  168. // Wake up sendRoutine if necessary
  169. select {
  170. case c.send <- struct{}{}:
  171. default:
  172. }
  173. return success
  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(binary.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. binary.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. binary.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. /*
  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. */
  332. // Read packet type
  333. var n int64
  334. var err error
  335. pktType := binary.ReadByte(c.bufReader, &n, &err)
  336. c.recvMonitor.Update(int(n))
  337. if err != nil {
  338. if atomic.LoadUint32(&c.stopped) != 1 {
  339. log.Warn("Connection failed @ recvRoutine (reading byte)", "connection", c, "error", err)
  340. c.stopForError(err)
  341. }
  342. break FOR_LOOP
  343. }
  344. // Read more depending on packet type.
  345. switch pktType {
  346. case packetTypePing:
  347. // TODO: prevent abuse, as they cause flush()'s.
  348. log.Debug("Receive Ping")
  349. c.pong <- struct{}{}
  350. case packetTypePong:
  351. // do nothing
  352. log.Debug("Receive Pong")
  353. case packetTypeMsg:
  354. pkt, n, err := msgPacket{}, new(int64), new(error)
  355. binary.ReadBinary(&pkt, c.bufReader, n, err)
  356. c.recvMonitor.Update(int(*n))
  357. if *err != nil {
  358. if atomic.LoadUint32(&c.stopped) != 1 {
  359. log.Warn("Connection failed @ recvRoutine", "connection", c, "error", *err)
  360. c.stopForError(*err)
  361. }
  362. break FOR_LOOP
  363. }
  364. channel, ok := c.channelsIdx[pkt.ChannelId]
  365. if !ok || channel == nil {
  366. panic(Fmt("Unknown channel %X", pkt.ChannelId))
  367. }
  368. msgBytes := channel.recvMsgPacket(pkt)
  369. if msgBytes != nil {
  370. //log.Debug("Received bytes", "chId", pkt.ChannelId, "msgBytes", msgBytes)
  371. c.onReceive(pkt.ChannelId, msgBytes)
  372. }
  373. default:
  374. panic(Fmt("Unknown message type %X", pktType))
  375. }
  376. // TODO: shouldn't this go in the sendRoutine?
  377. // Better to send a ping packet when *we* haven't sent anything for a while.
  378. c.pingTimer.Reset()
  379. }
  380. // Cleanup
  381. close(c.pong)
  382. for _ = range c.pong {
  383. // Drain
  384. }
  385. }
  386. //-----------------------------------------------------------------------------
  387. type ChannelDescriptor struct {
  388. Id byte
  389. Priority uint
  390. SendQueueCapacity uint
  391. RecvBufferCapacity uint
  392. }
  393. func (chDesc *ChannelDescriptor) FillDefaults() {
  394. if chDesc.SendQueueCapacity == 0 {
  395. chDesc.SendQueueCapacity = defaultSendQueueCapacity
  396. }
  397. if chDesc.RecvBufferCapacity == 0 {
  398. chDesc.RecvBufferCapacity = defaultRecvBufferCapacity
  399. }
  400. }
  401. // TODO: lowercase.
  402. // NOTE: not goroutine-safe.
  403. type Channel struct {
  404. conn *MConnection
  405. desc *ChannelDescriptor
  406. id byte
  407. sendQueue chan []byte
  408. sendQueueSize uint32 // atomic.
  409. recving []byte
  410. sending []byte
  411. priority uint
  412. recentlySent int64 // exponential moving average
  413. }
  414. func newChannel(conn *MConnection, desc *ChannelDescriptor) *Channel {
  415. desc.FillDefaults()
  416. if desc.Priority <= 0 {
  417. panic("Channel default priority must be a postive integer")
  418. }
  419. return &Channel{
  420. conn: conn,
  421. desc: desc,
  422. id: desc.Id,
  423. sendQueue: make(chan []byte, desc.SendQueueCapacity),
  424. recving: make([]byte, 0, desc.RecvBufferCapacity),
  425. priority: desc.Priority,
  426. }
  427. }
  428. // Queues message to send to this channel.
  429. // Goroutine-safe
  430. // Times out (and returns false) after defaultSendTimeoutSeconds
  431. func (ch *Channel) sendBytes(bytes []byte) bool {
  432. sendTicker := time.NewTicker(defaultSendTimeoutSeconds * time.Second)
  433. select {
  434. case <-sendTicker.C:
  435. // timeout
  436. return false
  437. case ch.sendQueue <- bytes:
  438. atomic.AddUint32(&ch.sendQueueSize, 1)
  439. return true
  440. }
  441. }
  442. // Queues message to send to this channel.
  443. // Nonblocking, returns true if successful.
  444. // Goroutine-safe
  445. func (ch *Channel) trySendBytes(bytes []byte) bool {
  446. select {
  447. case ch.sendQueue <- bytes:
  448. atomic.AddUint32(&ch.sendQueueSize, 1)
  449. return true
  450. default:
  451. return false
  452. }
  453. }
  454. // Goroutine-safe
  455. func (ch *Channel) loadSendQueueSize() (size int) {
  456. return int(atomic.LoadUint32(&ch.sendQueueSize))
  457. }
  458. // Goroutine-safe
  459. // Use only as a heuristic.
  460. func (ch *Channel) canSend() bool {
  461. return ch.loadSendQueueSize() < defaultSendQueueCapacity
  462. }
  463. // Returns true if any msgPackets are pending to be sent.
  464. // Call before calling nextMsgPacket()
  465. // Goroutine-safe
  466. func (ch *Channel) isSendPending() bool {
  467. if len(ch.sending) == 0 {
  468. if len(ch.sendQueue) == 0 {
  469. return false
  470. }
  471. ch.sending = <-ch.sendQueue
  472. }
  473. return true
  474. }
  475. // Creates a new msgPacket to send.
  476. // Not goroutine-safe
  477. func (ch *Channel) nextMsgPacket() msgPacket {
  478. packet := msgPacket{}
  479. packet.ChannelId = byte(ch.id)
  480. packet.Bytes = ch.sending[:MinInt(maxMsgPacketSize, len(ch.sending))]
  481. if len(ch.sending) <= maxMsgPacketSize {
  482. packet.EOF = byte(0x01)
  483. ch.sending = nil
  484. atomic.AddUint32(&ch.sendQueueSize, ^uint32(0)) // decrement sendQueueSize
  485. } else {
  486. packet.EOF = byte(0x00)
  487. ch.sending = ch.sending[MinInt(maxMsgPacketSize, len(ch.sending)):]
  488. }
  489. return packet
  490. }
  491. // Writes next msgPacket to w.
  492. // Not goroutine-safe
  493. func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int64, err error) {
  494. packet := ch.nextMsgPacket()
  495. binary.WriteByte(packetTypeMsg, w, &n, &err)
  496. binary.WriteBinary(packet, w, &n, &err)
  497. if err != nil {
  498. ch.recentlySent += n
  499. }
  500. return
  501. }
  502. // Handles incoming msgPackets. Returns a msg bytes if msg is complete.
  503. // Not goroutine-safe
  504. func (ch *Channel) recvMsgPacket(pkt msgPacket) []byte {
  505. ch.recving = append(ch.recving, pkt.Bytes...)
  506. if pkt.EOF == byte(0x01) {
  507. msgBytes := ch.recving
  508. ch.recving = make([]byte, 0, defaultRecvBufferCapacity)
  509. return msgBytes
  510. }
  511. return nil
  512. }
  513. // Call this periodically to update stats for throttling purposes.
  514. // Not goroutine-safe
  515. func (ch *Channel) updateStats() {
  516. // Exponential decay of stats.
  517. // TODO: optimize.
  518. ch.recentlySent = int64(float64(ch.recentlySent) * 0.5)
  519. }
  520. //-----------------------------------------------------------------------------
  521. const (
  522. maxMsgPacketSize = 1024
  523. packetTypePing = byte(0x01)
  524. packetTypePong = byte(0x02)
  525. packetTypeMsg = byte(0x03)
  526. )
  527. // Messages in channels are chopped into smaller msgPackets for multiplexing.
  528. type msgPacket struct {
  529. ChannelId byte
  530. EOF byte // 1 means message ends here.
  531. Bytes []byte
  532. }
  533. func (p msgPacket) String() string {
  534. return fmt.Sprintf("MsgPacket{%X:%X}", p.ChannelId, p.Bytes)
  535. }
  536. //-----------------------------------------------------------------------------
  537. // Convenience struct for writing typed messages.
  538. // Reading requires a custom decoder that switches on the first type byte of a byteslice.
  539. type TypedMessage struct {
  540. Type byte
  541. Msg interface{}
  542. }
  543. func (tm TypedMessage) String() string {
  544. return fmt.Sprintf("TMsg{%X:%v}", tm.Type, tm.Msg)
  545. }