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.

923 lines
27 KiB

p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
3 years ago
p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
3 years ago
p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
3 years ago
p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
3 years ago
p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
3 years ago
p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
3 years ago
p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
3 years ago
p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
3 years ago
p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
3 years ago
p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
3 years ago
p2p: make PeerManager.DialNext() and EvictNext() block (#5947) See #5936 and #5938 for background. The plan was initially to have `DialNext()` and `EvictNext()` return a channel. However, implementing this became unnecessarily complicated and error-prone. As an example, the channel would be both consumed and populated (via method calls) by the same driving method (e.g. `Router.dialPeers()`) which could easily cause deadlocks where a method call blocked while sending on the channel that the caller itself was responsible for consuming (but couldn't since it was busy making the method call). It would also require a set of goroutines in the peer manager that would interact with the goroutines in the router in non-obvious ways, and fully populating the channel on startup could cause deadlocks with other startup tasks. Several issues like these made the solution hard to reason about. I therefore simply made `DialNext()` and `EvictNext()` block until the next peer was available, using internal triggers to wake these methods up in a non-blocking fashion when any relevant state changes occurred. This proved much simpler to reason about, since there are no goroutines in the peer manager (except for trivial retry timers), nor any blocking channel sends, and it instead relies entirely on the existing goroutine structure of the router for concurrency. This also happens to be the same pattern used by the `Transport.Accept()` API, following Go stdlib conventions, so all router goroutines end up using a consistent pattern as well.
3 years ago
  1. package p2p
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "sync"
  8. "time"
  9. "github.com/gogo/protobuf/proto"
  10. "github.com/tendermint/tendermint/crypto"
  11. "github.com/tendermint/tendermint/libs/log"
  12. "github.com/tendermint/tendermint/libs/service"
  13. )
  14. const queueBufferDefault = 4096
  15. // ChannelID is an arbitrary channel ID.
  16. type ChannelID uint16
  17. // Envelope contains a message with sender/receiver routing info.
  18. type Envelope struct {
  19. From NodeID // sender (empty if outbound)
  20. To NodeID // receiver (empty if inbound)
  21. Broadcast bool // send to all connected peers (ignores To)
  22. Message proto.Message // message payload
  23. // channelID is for internal Router use, set on outbound messages to inform
  24. // the sendPeer() goroutine which transport channel to use.
  25. //
  26. // FIXME: If we migrate the Transport API to a byte-oriented multi-stream
  27. // API, this will no longer be necessary since each channel will be mapped
  28. // onto a stream during channel/peer setup. See:
  29. // https://github.com/tendermint/spec/pull/227
  30. channelID ChannelID
  31. }
  32. // PeerError is a peer error reported via Channel.Error.
  33. //
  34. // FIXME: This currently just disconnects the peer, which is too simplistic.
  35. // For example, some errors should be logged, some should cause disconnects,
  36. // and some should ban the peer.
  37. //
  38. // FIXME: This should probably be replaced by a more general PeerBehavior
  39. // concept that can mark good and bad behavior and contributes to peer scoring.
  40. // It should possibly also allow reactors to request explicit actions, e.g.
  41. // disconnection or banning, in addition to doing this based on aggregates.
  42. type PeerError struct {
  43. NodeID NodeID
  44. Err error
  45. }
  46. // Channel is a bidirectional channel to exchange Protobuf messages with peers,
  47. // wrapped in Envelope to specify routing info (i.e. sender/receiver).
  48. type Channel struct {
  49. ID ChannelID
  50. In <-chan Envelope // inbound messages (peers to reactors)
  51. Out chan<- Envelope // outbound messages (reactors to peers)
  52. Error chan<- PeerError // peer error reporting
  53. messageType proto.Message // the channel's message type, used for unmarshaling
  54. closeCh chan struct{}
  55. closeOnce sync.Once
  56. }
  57. // NewChannel creates a new channel. It is primarily for internal and test
  58. // use, reactors should use Router.OpenChannel().
  59. func NewChannel(
  60. id ChannelID,
  61. messageType proto.Message,
  62. inCh <-chan Envelope,
  63. outCh chan<- Envelope,
  64. errCh chan<- PeerError,
  65. ) *Channel {
  66. return &Channel{
  67. ID: id,
  68. messageType: messageType,
  69. In: inCh,
  70. Out: outCh,
  71. Error: errCh,
  72. closeCh: make(chan struct{}),
  73. }
  74. }
  75. // Close closes the channel. Future sends on Out and Error will panic. The In
  76. // channel remains open to avoid having to synchronize Router senders, which
  77. // should use Done() to detect channel closure instead.
  78. func (c *Channel) Close() {
  79. c.closeOnce.Do(func() {
  80. close(c.closeCh)
  81. close(c.Out)
  82. close(c.Error)
  83. })
  84. }
  85. // Done returns a channel that's closed when Channel.Close() is called.
  86. func (c *Channel) Done() <-chan struct{} {
  87. return c.closeCh
  88. }
  89. // Wrapper is a Protobuf message that can contain a variety of inner messages
  90. // (e.g. via oneof fields). If a Channel's message type implements Wrapper, the
  91. // Router will automatically wrap outbound messages and unwrap inbound messages,
  92. // such that reactors do not have to do this themselves.
  93. type Wrapper interface {
  94. proto.Message
  95. // Wrap will take a message and wrap it in this one if possible.
  96. Wrap(proto.Message) error
  97. // Unwrap will unwrap the inner message contained in this message.
  98. Unwrap() (proto.Message, error)
  99. }
  100. // RouterOptions specifies options for a Router.
  101. type RouterOptions struct {
  102. // ResolveTimeout is the timeout for resolving NodeAddress URLs.
  103. // 0 means no timeout.
  104. ResolveTimeout time.Duration
  105. // DialTimeout is the timeout for dialing a peer. 0 means no timeout.
  106. DialTimeout time.Duration
  107. // HandshakeTimeout is the timeout for handshaking with a peer. 0 means
  108. // no timeout.
  109. HandshakeTimeout time.Duration
  110. // QueueType must be "wdrr" (Weighed Deficit Round Robin),
  111. // "priority", or FIFO. Defaults to FIFO.
  112. QueueType string
  113. }
  114. const (
  115. queueTypeFifo = "fifo"
  116. queueTypePriority = "priority"
  117. queueTypeWDRR = "wdrr"
  118. )
  119. // Validate validates router options.
  120. func (o *RouterOptions) Validate() error {
  121. switch o.QueueType {
  122. case "":
  123. o.QueueType = queueTypeFifo
  124. case queueTypeFifo, queueTypeWDRR, queueTypePriority:
  125. // pass
  126. default:
  127. return fmt.Errorf("queue type %q is not supported", o.QueueType)
  128. }
  129. return nil
  130. }
  131. // Router manages peer connections and routes messages between peers and reactor
  132. // channels. It takes a PeerManager for peer lifecycle management (e.g. which
  133. // peers to dial and when) and a set of Transports for connecting and
  134. // communicating with peers.
  135. //
  136. // On startup, three main goroutines are spawned to maintain peer connections:
  137. //
  138. // dialPeers(): in a loop, calls PeerManager.DialNext() to get the next peer
  139. // address to dial and spawns a goroutine that dials the peer, handshakes
  140. // with it, and begins to route messages if successful.
  141. //
  142. // acceptPeers(): in a loop, waits for an inbound connection via
  143. // Transport.Accept() and spawns a goroutine that handshakes with it and
  144. // begins to route messages if successful.
  145. //
  146. // evictPeers(): in a loop, calls PeerManager.EvictNext() to get the next
  147. // peer to evict, and disconnects it by closing its message queue.
  148. //
  149. // When a peer is connected, an outbound peer message queue is registered in
  150. // peerQueues, and routePeer() is called to spawn off two additional goroutines:
  151. //
  152. // sendPeer(): waits for an outbound message from the peerQueues queue,
  153. // marshals it, and passes it to the peer transport which delivers it.
  154. //
  155. // receivePeer(): waits for an inbound message from the peer transport,
  156. // unmarshals it, and passes it to the appropriate inbound channel queue
  157. // in channelQueues.
  158. //
  159. // When a reactor opens a channel via OpenChannel, an inbound channel message
  160. // queue is registered in channelQueues, and a channel goroutine is spawned:
  161. //
  162. // routeChannel(): waits for an outbound message from the channel, looks
  163. // up the recipient peer's outbound message queue in peerQueues, and submits
  164. // the message to it.
  165. //
  166. // All channel sends in the router are blocking. It is the responsibility of the
  167. // queue interface in peerQueues and channelQueues to prioritize and drop
  168. // messages as appropriate during contention to prevent stalls and ensure good
  169. // quality of service.
  170. type Router struct {
  171. *service.BaseService
  172. logger log.Logger
  173. metrics *Metrics
  174. options RouterOptions
  175. nodeInfo NodeInfo
  176. privKey crypto.PrivKey
  177. peerManager *PeerManager
  178. chDescs []ChannelDescriptor
  179. transports []Transport
  180. protocolTransports map[Protocol]Transport
  181. stopCh chan struct{} // signals Router shutdown
  182. peerMtx sync.RWMutex
  183. peerQueues map[NodeID]queue // outbound messages per peer for all channels
  184. queueFactory func(int) queue
  185. // FIXME: We don't strictly need to use a mutex for this if we seal the
  186. // channels on router start. This depends on whether we want to allow
  187. // dynamic channels in the future.
  188. channelMtx sync.RWMutex
  189. channelQueues map[ChannelID]queue // inbound messages from all peers to a single channel
  190. channelMessages map[ChannelID]proto.Message
  191. }
  192. // NewRouter creates a new Router. The given Transports must already be
  193. // listening on appropriate interfaces, and will be closed by the Router when it
  194. // stops.
  195. func NewRouter(
  196. logger log.Logger,
  197. metrics *Metrics,
  198. nodeInfo NodeInfo,
  199. privKey crypto.PrivKey,
  200. peerManager *PeerManager,
  201. transports []Transport,
  202. options RouterOptions,
  203. ) (*Router, error) {
  204. if err := options.Validate(); err != nil {
  205. return nil, err
  206. }
  207. router := &Router{
  208. logger: logger,
  209. metrics: metrics,
  210. nodeInfo: nodeInfo,
  211. privKey: privKey,
  212. chDescs: make([]ChannelDescriptor, 0),
  213. transports: transports,
  214. protocolTransports: map[Protocol]Transport{},
  215. peerManager: peerManager,
  216. options: options,
  217. stopCh: make(chan struct{}),
  218. channelQueues: map[ChannelID]queue{},
  219. channelMessages: map[ChannelID]proto.Message{},
  220. peerQueues: map[NodeID]queue{},
  221. }
  222. router.BaseService = service.NewBaseService(logger, "router", router)
  223. qf, err := router.createQueueFactory()
  224. if err != nil {
  225. return nil, err
  226. }
  227. router.queueFactory = qf
  228. for _, transport := range transports {
  229. for _, protocol := range transport.Protocols() {
  230. if _, ok := router.protocolTransports[protocol]; !ok {
  231. router.protocolTransports[protocol] = transport
  232. }
  233. }
  234. }
  235. return router, nil
  236. }
  237. func (r *Router) createQueueFactory() (func(int) queue, error) {
  238. switch r.options.QueueType {
  239. case queueTypeFifo:
  240. return newFIFOQueue, nil
  241. case queueTypePriority:
  242. return func(size int) queue {
  243. if size%2 != 0 {
  244. size++
  245. }
  246. q := newPQScheduler(r.logger, r.metrics, r.chDescs, uint(size)/2, uint(size)/2, defaultCapacity)
  247. q.start()
  248. return q
  249. }, nil
  250. case queueTypeWDRR:
  251. return func(size int) queue {
  252. if size%2 != 0 {
  253. size++
  254. }
  255. q := newWDRRScheduler(r.logger, r.metrics, r.chDescs, uint(size)/2, uint(size)/2, defaultCapacity)
  256. q.start()
  257. return q
  258. }, nil
  259. default:
  260. return nil, fmt.Errorf("cannot construct queue of type %q", r.options.QueueType)
  261. }
  262. }
  263. // AddChannelDescriptors adds a set of ChannelDescriptors to the reactor. Note,
  264. // this should be called before the router is started and any connections are made.
  265. func (r *Router) AddChannelDescriptors(chDescs []*ChannelDescriptor) {
  266. for _, chDesc := range chDescs {
  267. r.chDescs = append(r.chDescs, *chDesc)
  268. }
  269. }
  270. // OpenChannel opens a new channel for the given message type. The caller must
  271. // close the channel when done, before stopping the Router. messageType is the
  272. // type of message passed through the channel (used for unmarshaling), which can
  273. // implement Wrapper to automatically (un)wrap multiple message types in a
  274. // wrapper message. The caller may provide a size to make the channel buffered,
  275. // which internally makes the inbound, outbound, and error channel buffered.
  276. func (r *Router) OpenChannel(id ChannelID, messageType proto.Message, size int) (*Channel, error) {
  277. if size == 0 {
  278. size = queueBufferDefault
  279. }
  280. r.channelMtx.Lock()
  281. defer r.channelMtx.Unlock()
  282. if _, ok := r.channelQueues[id]; ok {
  283. return nil, fmt.Errorf("channel %v already exists", id)
  284. }
  285. queue := r.queueFactory(size)
  286. outCh := make(chan Envelope, size)
  287. errCh := make(chan PeerError, size)
  288. channel := NewChannel(id, messageType, queue.dequeue(), outCh, errCh)
  289. var wrapper Wrapper
  290. if w, ok := messageType.(Wrapper); ok {
  291. wrapper = w
  292. }
  293. r.channelQueues[id] = queue
  294. r.channelMessages[id] = messageType
  295. go func() {
  296. defer func() {
  297. r.channelMtx.Lock()
  298. delete(r.channelQueues, id)
  299. delete(r.channelMessages, id)
  300. r.channelMtx.Unlock()
  301. queue.close()
  302. }()
  303. r.routeChannel(id, outCh, errCh, wrapper)
  304. }()
  305. return channel, nil
  306. }
  307. // routeChannel receives outbound channel messages and routes them to the
  308. // appropriate peer. It also receives peer errors and reports them to the peer
  309. // manager. It returns when either the outbound channel or error channel is
  310. // closed, or the Router is stopped. wrapper is an optional message wrapper
  311. // for messages, see Wrapper for details.
  312. func (r *Router) routeChannel(
  313. chID ChannelID,
  314. outCh <-chan Envelope,
  315. errCh <-chan PeerError,
  316. wrapper Wrapper,
  317. ) {
  318. for {
  319. select {
  320. case envelope, ok := <-outCh:
  321. if !ok {
  322. return
  323. }
  324. // Mark the envelope with the channel ID to allow sendPeer() to pass
  325. // it on to Transport.SendMessage().
  326. envelope.channelID = chID
  327. // wrap the message in a wrapper message, if requested
  328. if wrapper != nil {
  329. msg := proto.Clone(wrapper)
  330. if err := msg.(Wrapper).Wrap(envelope.Message); err != nil {
  331. r.Logger.Error("failed to wrap message", "channel", chID, "err", err)
  332. continue
  333. }
  334. envelope.Message = msg
  335. }
  336. // collect peer queues to pass the message via
  337. var queues []queue
  338. if envelope.Broadcast {
  339. r.peerMtx.RLock()
  340. queues = make([]queue, 0, len(r.peerQueues))
  341. for _, q := range r.peerQueues {
  342. queues = append(queues, q)
  343. }
  344. r.peerMtx.RUnlock()
  345. } else {
  346. r.peerMtx.RLock()
  347. q, ok := r.peerQueues[envelope.To]
  348. r.peerMtx.RUnlock()
  349. if !ok {
  350. r.logger.Debug("dropping message for unconnected peer", "peer", envelope.To, "channel", chID)
  351. continue
  352. }
  353. queues = []queue{q}
  354. }
  355. // send message to peers
  356. for _, q := range queues {
  357. start := time.Now().UTC()
  358. select {
  359. case q.enqueue() <- envelope:
  360. r.metrics.RouterPeerQueueSend.Observe(time.Since(start).Seconds())
  361. case <-q.closed():
  362. r.logger.Debug("dropping message for unconnected peer", "peer", envelope.To, "channel", chID)
  363. case <-r.stopCh:
  364. return
  365. }
  366. }
  367. case peerError, ok := <-errCh:
  368. if !ok {
  369. return
  370. }
  371. r.logger.Error("peer error, evicting", "peer", peerError.NodeID, "err", peerError.Err)
  372. if err := r.peerManager.Errored(peerError.NodeID, peerError.Err); err != nil {
  373. r.logger.Error("failed to report peer error", "peer", peerError.NodeID, "err", err)
  374. }
  375. case <-r.stopCh:
  376. return
  377. }
  378. }
  379. }
  380. // acceptPeers accepts inbound connections from peers on the given transport,
  381. // and spawns goroutines that route messages to/from them.
  382. func (r *Router) acceptPeers(transport Transport) {
  383. r.logger.Debug("starting accept routine", "transport", transport)
  384. ctx := r.stopCtx()
  385. for {
  386. // FIXME: We may need transports to enforce some sort of rate limiting
  387. // here (e.g. by IP address), or alternatively have PeerManager.Accepted()
  388. // do it for us.
  389. //
  390. // FIXME: Even though PeerManager enforces MaxConnected, we may want to
  391. // limit the maximum number of active connections here too, since e.g.
  392. // an adversary can open a ton of connections and then just hang during
  393. // the handshake, taking up TCP socket descriptors.
  394. //
  395. // FIXME: The old P2P stack rejected multiple connections for the same IP
  396. // unless P2PConfig.AllowDuplicateIP is true -- it's better to limit this
  397. // by peer ID rather than IP address, so this hasn't been implemented and
  398. // probably shouldn't (?).
  399. //
  400. // FIXME: The old P2P stack supported ABCI-based IP address filtering via
  401. // /p2p/filter/addr/<ip> queries, do we want to implement this here as well?
  402. // Filtering by node ID is probably better.
  403. conn, err := transport.Accept()
  404. switch err {
  405. case nil:
  406. case io.EOF:
  407. r.logger.Debug("stopping accept routine", "transport", transport)
  408. return
  409. default:
  410. r.logger.Error("failed to accept connection", "transport", transport, "err", err)
  411. return
  412. }
  413. // Spawn a goroutine for the handshake, to avoid head-of-line blocking.
  414. go func() {
  415. defer conn.Close()
  416. // FIXME: The peer manager may reject the peer during Accepted()
  417. // after we've handshaked with the peer (to find out which peer it
  418. // is). However, because the handshake has no ack, the remote peer
  419. // will think the handshake was successful and start sending us
  420. // messages.
  421. //
  422. // This can cause problems in tests, where a disconnection can cause
  423. // the local node to immediately redial, while the remote node may
  424. // not have completed the disconnection yet and therefore reject the
  425. // reconnection attempt (since it thinks we're still connected from
  426. // before).
  427. //
  428. // The Router should do the handshake and have a final ack/fail
  429. // message to make sure both ends have accepted the connection, such
  430. // that it can be coordinated with the peer manager.
  431. peerInfo, _, err := r.handshakePeer(ctx, conn, "")
  432. switch {
  433. case errors.Is(err, context.Canceled):
  434. return
  435. case err != nil:
  436. r.logger.Error("peer handshake failed", "endpoint", conn, "err", err)
  437. return
  438. }
  439. if err := r.peerManager.Accepted(peerInfo.NodeID); err != nil {
  440. r.logger.Error("failed to accept connection", "peer", peerInfo.NodeID, "err", err)
  441. return
  442. }
  443. r.metrics.Peers.Add(1)
  444. queue := r.queueFactory(queueBufferDefault)
  445. r.peerMtx.Lock()
  446. r.peerQueues[peerInfo.NodeID] = queue
  447. r.peerMtx.Unlock()
  448. defer func() {
  449. r.peerMtx.Lock()
  450. delete(r.peerQueues, peerInfo.NodeID)
  451. r.peerMtx.Unlock()
  452. queue.close()
  453. if err := r.peerManager.Disconnected(peerInfo.NodeID); err != nil {
  454. r.logger.Error("failed to disconnect peer", "peer", peerInfo.NodeID, "err", err)
  455. } else {
  456. r.metrics.Peers.Add(-1)
  457. }
  458. }()
  459. if err := r.peerManager.Ready(peerInfo.NodeID); err != nil {
  460. r.logger.Error("failed to mark peer as ready", "peer", peerInfo.NodeID, "err", err)
  461. return
  462. }
  463. r.routePeer(peerInfo.NodeID, conn, queue)
  464. }()
  465. }
  466. }
  467. // dialPeers maintains outbound connections to peers by dialing them.
  468. func (r *Router) dialPeers() {
  469. r.logger.Debug("starting dial routine")
  470. ctx := r.stopCtx()
  471. for {
  472. address, err := r.peerManager.DialNext(ctx)
  473. switch {
  474. case errors.Is(err, context.Canceled):
  475. r.logger.Debug("stopping dial routine")
  476. return
  477. case err != nil:
  478. r.logger.Error("failed to find next peer to dial", "err", err)
  479. return
  480. }
  481. // Spawn off a goroutine to actually dial the peer, so that we can
  482. // dial multiple peers in parallel.
  483. go func() {
  484. conn, err := r.dialPeer(ctx, address)
  485. switch {
  486. case errors.Is(err, context.Canceled):
  487. return
  488. case err != nil:
  489. r.logger.Error("failed to dial peer", "peer", address, "err", err)
  490. if err = r.peerManager.DialFailed(address); err != nil {
  491. r.logger.Error("failed to report dial failure", "peer", address, "err", err)
  492. }
  493. return
  494. }
  495. defer conn.Close()
  496. peerID := address.NodeID
  497. _, _, err = r.handshakePeer(ctx, conn, peerID)
  498. switch {
  499. case errors.Is(err, context.Canceled):
  500. return
  501. case err != nil:
  502. r.logger.Error("failed to handshake with peer", "peer", address, "err", err)
  503. if err = r.peerManager.DialFailed(address); err != nil {
  504. r.logger.Error("failed to report dial failure", "peer", address, "err", err)
  505. }
  506. return
  507. }
  508. if err = r.peerManager.Dialed(address); err != nil {
  509. r.logger.Error("failed to dial peer", "peer", address, "err", err)
  510. return
  511. }
  512. r.metrics.Peers.Add(1)
  513. peerQueue := r.getOrMakeQueue(peerID)
  514. defer func() {
  515. r.peerMtx.Lock()
  516. delete(r.peerQueues, peerID)
  517. r.peerMtx.Unlock()
  518. peerQueue.close()
  519. if err := r.peerManager.Disconnected(peerID); err != nil {
  520. r.logger.Error("failed to disconnect peer", "peer", address, "err", err)
  521. } else {
  522. r.metrics.Peers.Add(-1)
  523. }
  524. }()
  525. if err := r.peerManager.Ready(peerID); err != nil {
  526. r.logger.Error("failed to mark peer as ready", "peer", address, "err", err)
  527. return
  528. }
  529. r.routePeer(peerID, conn, peerQueue)
  530. }()
  531. }
  532. }
  533. func (r *Router) getOrMakeQueue(peerID NodeID) queue {
  534. r.peerMtx.Lock()
  535. defer r.peerMtx.Unlock()
  536. if peerQueue, ok := r.peerQueues[peerID]; ok {
  537. return peerQueue
  538. }
  539. peerQueue := r.queueFactory(queueBufferDefault)
  540. r.peerQueues[peerID] = peerQueue
  541. return peerQueue
  542. }
  543. // dialPeer connects to a peer by dialing it.
  544. func (r *Router) dialPeer(ctx context.Context, address NodeAddress) (Connection, error) {
  545. resolveCtx := ctx
  546. if r.options.ResolveTimeout > 0 {
  547. var cancel context.CancelFunc
  548. resolveCtx, cancel = context.WithTimeout(resolveCtx, r.options.ResolveTimeout)
  549. defer cancel()
  550. }
  551. r.logger.Debug("resolving peer address", "peer", address)
  552. endpoints, err := address.Resolve(resolveCtx)
  553. switch {
  554. case err != nil:
  555. return nil, fmt.Errorf("failed to resolve address %q: %w", address, err)
  556. case len(endpoints) == 0:
  557. return nil, fmt.Errorf("address %q did not resolve to any endpoints", address)
  558. }
  559. for _, endpoint := range endpoints {
  560. transport, ok := r.protocolTransports[endpoint.Protocol]
  561. if !ok {
  562. r.logger.Error("no transport found for protocol", "endpoint", endpoint)
  563. continue
  564. }
  565. dialCtx := ctx
  566. if r.options.DialTimeout > 0 {
  567. var cancel context.CancelFunc
  568. dialCtx, cancel = context.WithTimeout(dialCtx, r.options.DialTimeout)
  569. defer cancel()
  570. }
  571. // FIXME: When we dial and handshake the peer, we should pass it
  572. // appropriate address(es) it can use to dial us back. It can't use our
  573. // remote endpoint, since TCP uses different port numbers for outbound
  574. // connections than it does for inbound. Also, we may need to vary this
  575. // by the peer's endpoint, since e.g. a peer on 192.168.0.0 can reach us
  576. // on a private address on this endpoint, but a peer on the public
  577. // Internet can't and needs a different public address.
  578. conn, err := transport.Dial(dialCtx, endpoint)
  579. if err != nil {
  580. r.logger.Error("failed to dial endpoint", "peer", address.NodeID, "endpoint", endpoint, "err", err)
  581. } else {
  582. r.logger.Debug("dialed peer", "peer", address.NodeID, "endpoint", endpoint)
  583. return conn, nil
  584. }
  585. }
  586. return nil, errors.New("all endpoints failed")
  587. }
  588. // handshakePeer handshakes with a peer, validating the peer's information. If
  589. // expectID is given, we check that the peer's info matches it.
  590. func (r *Router) handshakePeer(ctx context.Context, conn Connection, expectID NodeID) (NodeInfo, crypto.PubKey, error) {
  591. if r.options.HandshakeTimeout > 0 {
  592. var cancel context.CancelFunc
  593. ctx, cancel = context.WithTimeout(ctx, r.options.HandshakeTimeout)
  594. defer cancel()
  595. }
  596. peerInfo, peerKey, err := conn.Handshake(ctx, r.nodeInfo, r.privKey)
  597. if err != nil {
  598. return peerInfo, peerKey, err
  599. }
  600. if err = peerInfo.Validate(); err != nil {
  601. return peerInfo, peerKey, fmt.Errorf("invalid handshake NodeInfo: %w", err)
  602. }
  603. if NodeIDFromPubKey(peerKey) != peerInfo.NodeID {
  604. return peerInfo, peerKey, fmt.Errorf("peer's public key did not match its node ID %q (expected %q)",
  605. peerInfo.NodeID, NodeIDFromPubKey(peerKey))
  606. }
  607. if expectID != "" && expectID != peerInfo.NodeID {
  608. return peerInfo, peerKey, fmt.Errorf("expected to connect with peer %q, got %q",
  609. expectID, peerInfo.NodeID)
  610. }
  611. return peerInfo, peerKey, nil
  612. }
  613. // routePeer routes inbound and outbound messages between a peer and the reactor
  614. // channels. It will close the given connection and send queue when done, or if
  615. // they are closed elsewhere it will cause this method to shut down and return.
  616. func (r *Router) routePeer(peerID NodeID, conn Connection, sendQueue queue) {
  617. r.logger.Info("peer connected", "peer", peerID, "endpoint", conn)
  618. errCh := make(chan error, 2)
  619. go func() {
  620. errCh <- r.receivePeer(peerID, conn)
  621. }()
  622. go func() {
  623. errCh <- r.sendPeer(peerID, conn, sendQueue)
  624. }()
  625. err := <-errCh
  626. _ = conn.Close()
  627. sendQueue.close()
  628. if e := <-errCh; err == nil {
  629. // The first err was nil, so we update it with the second err, which may
  630. // or may not be nil.
  631. err = e
  632. }
  633. switch err {
  634. case nil, io.EOF:
  635. r.logger.Info("peer disconnected", "peer", peerID, "endpoint", conn)
  636. default:
  637. r.logger.Error("peer failure", "peer", peerID, "endpoint", conn, "err", err)
  638. }
  639. }
  640. // receivePeer receives inbound messages from a peer, deserializes them and
  641. // passes them on to the appropriate channel.
  642. func (r *Router) receivePeer(peerID NodeID, conn Connection) error {
  643. for {
  644. chID, bz, err := conn.ReceiveMessage()
  645. if err != nil {
  646. return err
  647. }
  648. r.channelMtx.RLock()
  649. queue, ok := r.channelQueues[chID]
  650. messageType := r.channelMessages[chID]
  651. r.channelMtx.RUnlock()
  652. if !ok {
  653. r.logger.Debug("dropping message for unknown channel", "peer", peerID, "channel", chID)
  654. continue
  655. }
  656. msg := proto.Clone(messageType)
  657. if err := proto.Unmarshal(bz, msg); err != nil {
  658. r.logger.Error("message decoding failed, dropping message", "peer", peerID, "err", err)
  659. continue
  660. }
  661. if wrapper, ok := msg.(Wrapper); ok {
  662. msg, err = wrapper.Unwrap()
  663. if err != nil {
  664. r.logger.Error("failed to unwrap message", "err", err)
  665. continue
  666. }
  667. }
  668. start := time.Now().UTC()
  669. select {
  670. case queue.enqueue() <- Envelope{From: peerID, Message: msg}:
  671. r.metrics.PeerReceiveBytesTotal.With("peer_id", string(peerID)).Add(float64(proto.Size(msg)))
  672. r.metrics.RouterChannelQueueSend.Observe(time.Since(start).Seconds())
  673. r.logger.Debug("received message", "peer", peerID, "message", msg)
  674. case <-queue.closed():
  675. r.logger.Debug("channel closed, dropping message", "peer", peerID, "channel", chID)
  676. case <-r.stopCh:
  677. return nil
  678. }
  679. }
  680. }
  681. // sendPeer sends queued messages to a peer.
  682. func (r *Router) sendPeer(peerID NodeID, conn Connection, peerQueue queue) error {
  683. for {
  684. start := time.Now().UTC()
  685. select {
  686. case envelope := <-peerQueue.dequeue():
  687. r.metrics.RouterPeerQueueRecv.Observe(time.Since(start).Seconds())
  688. if envelope.Message == nil {
  689. r.logger.Error("dropping nil message", "peer", peerID)
  690. continue
  691. }
  692. bz, err := proto.Marshal(envelope.Message)
  693. if err != nil {
  694. r.logger.Error("failed to marshal message", "peer", peerID, "err", err)
  695. continue
  696. }
  697. _, err = conn.SendMessage(envelope.channelID, bz)
  698. if err != nil {
  699. return err
  700. }
  701. r.logger.Debug("sent message", "peer", envelope.To, "message", envelope.Message)
  702. case <-peerQueue.closed():
  703. return nil
  704. case <-r.stopCh:
  705. return nil
  706. }
  707. }
  708. }
  709. // evictPeers evicts connected peers as requested by the peer manager.
  710. func (r *Router) evictPeers() {
  711. r.logger.Debug("starting evict routine")
  712. ctx := r.stopCtx()
  713. for {
  714. peerID, err := r.peerManager.EvictNext(ctx)
  715. switch {
  716. case errors.Is(err, context.Canceled):
  717. r.logger.Debug("stopping evict routine")
  718. return
  719. case err != nil:
  720. r.logger.Error("failed to find next peer to evict", "err", err)
  721. return
  722. }
  723. r.logger.Info("evicting peer", "peer", peerID)
  724. r.peerMtx.RLock()
  725. queue, ok := r.peerQueues[peerID]
  726. r.peerMtx.RUnlock()
  727. if ok {
  728. queue.close()
  729. }
  730. }
  731. }
  732. // OnStart implements service.Service.
  733. func (r *Router) OnStart() error {
  734. go r.dialPeers()
  735. go r.evictPeers()
  736. for _, transport := range r.transports {
  737. go r.acceptPeers(transport)
  738. }
  739. return nil
  740. }
  741. // OnStop implements service.Service.
  742. //
  743. // All channels must be closed by OpenChannel() callers before stopping the
  744. // router, to prevent blocked channel sends in reactors. Channels are not closed
  745. // here, since that would cause any reactor senders to panic, so it is the
  746. // sender's responsibility.
  747. func (r *Router) OnStop() {
  748. // Signal router shutdown.
  749. close(r.stopCh)
  750. // Close transport listeners (unblocks Accept calls).
  751. for _, transport := range r.transports {
  752. if err := transport.Close(); err != nil {
  753. r.logger.Error("failed to close transport", "transport", transport, "err", err)
  754. }
  755. }
  756. // Collect all remaining queues, and wait for them to close.
  757. queues := []queue{}
  758. r.channelMtx.RLock()
  759. for _, q := range r.channelQueues {
  760. queues = append(queues, q)
  761. }
  762. r.channelMtx.RUnlock()
  763. r.peerMtx.RLock()
  764. for _, q := range r.peerQueues {
  765. queues = append(queues, q)
  766. }
  767. r.peerMtx.RUnlock()
  768. for _, q := range queues {
  769. <-q.closed()
  770. }
  771. }
  772. // stopCtx returns a new context that is canceled when the router stops.
  773. func (r *Router) stopCtx() context.Context {
  774. ctx, cancel := context.WithCancel(context.Background())
  775. go func() {
  776. <-r.stopCh
  777. cancel()
  778. }()
  779. return ctx
  780. }