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.

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