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.

962 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. // OpenChannel opens a new channel for the given message type. The caller must
  300. // close the channel when done, before stopping the Router. messageType is the
  301. // type of message passed through the channel (used for unmarshaling), which can
  302. // implement Wrapper to automatically (un)wrap multiple message types in a
  303. // wrapper message. The caller may provide a size to make the channel buffered,
  304. // which internally makes the inbound, outbound, and error channel buffered.
  305. func (r *Router) OpenChannel(chDesc ChannelDescriptor, messageType proto.Message, size int) (*Channel, error) {
  306. if size == 0 {
  307. size = queueBufferDefault
  308. }
  309. r.channelMtx.Lock()
  310. defer r.channelMtx.Unlock()
  311. id := ChannelID(chDesc.ID)
  312. if _, ok := r.channelQueues[id]; ok {
  313. return nil, fmt.Errorf("channel %v already exists", id)
  314. }
  315. r.chDescs = append(r.chDescs, chDesc)
  316. queue := r.queueFactory(size)
  317. outCh := make(chan Envelope, size)
  318. errCh := make(chan PeerError, size)
  319. channel := NewChannel(id, messageType, queue.dequeue(), outCh, errCh)
  320. var wrapper Wrapper
  321. if w, ok := messageType.(Wrapper); ok {
  322. wrapper = w
  323. }
  324. r.channelQueues[id] = queue
  325. r.channelMessages[id] = messageType
  326. go func() {
  327. defer func() {
  328. r.channelMtx.Lock()
  329. delete(r.channelQueues, id)
  330. delete(r.channelMessages, id)
  331. r.channelMtx.Unlock()
  332. queue.close()
  333. }()
  334. r.routeChannel(id, outCh, errCh, wrapper)
  335. }()
  336. return channel, nil
  337. }
  338. // routeChannel receives outbound channel messages and routes them to the
  339. // appropriate peer. It also receives peer errors and reports them to the peer
  340. // manager. It returns when either the outbound channel or error channel is
  341. // closed, or the Router is stopped. wrapper is an optional message wrapper
  342. // for messages, see Wrapper for details.
  343. func (r *Router) routeChannel(
  344. chID ChannelID,
  345. outCh <-chan Envelope,
  346. errCh <-chan PeerError,
  347. wrapper Wrapper,
  348. ) {
  349. for {
  350. select {
  351. case envelope, ok := <-outCh:
  352. if !ok {
  353. return
  354. }
  355. // Mark the envelope with the channel ID to allow sendPeer() to pass
  356. // it on to Transport.SendMessage().
  357. envelope.channelID = chID
  358. // wrap the message in a wrapper message, if requested
  359. if wrapper != nil {
  360. msg := proto.Clone(wrapper)
  361. if err := msg.(Wrapper).Wrap(envelope.Message); err != nil {
  362. r.Logger.Error("failed to wrap message", "channel", chID, "err", err)
  363. continue
  364. }
  365. envelope.Message = msg
  366. }
  367. // collect peer queues to pass the message via
  368. var queues []queue
  369. if envelope.Broadcast {
  370. r.peerMtx.RLock()
  371. queues = make([]queue, 0, len(r.peerQueues))
  372. for _, q := range r.peerQueues {
  373. queues = append(queues, q)
  374. }
  375. r.peerMtx.RUnlock()
  376. } else {
  377. r.peerMtx.RLock()
  378. q, ok := r.peerQueues[envelope.To]
  379. r.peerMtx.RUnlock()
  380. if !ok {
  381. r.logger.Debug("dropping message for unconnected peer", "peer", envelope.To, "channel", chID)
  382. continue
  383. }
  384. queues = []queue{q}
  385. }
  386. // send message to peers
  387. for _, q := range queues {
  388. start := time.Now().UTC()
  389. select {
  390. case q.enqueue() <- envelope:
  391. r.metrics.RouterPeerQueueSend.Observe(time.Since(start).Seconds())
  392. case <-q.closed():
  393. r.logger.Debug("dropping message for unconnected peer", "peer", envelope.To, "channel", chID)
  394. case <-r.stopCh:
  395. return
  396. }
  397. }
  398. case peerError, ok := <-errCh:
  399. if !ok {
  400. return
  401. }
  402. r.logger.Error("peer error, evicting", "peer", peerError.NodeID, "err", peerError.Err)
  403. r.peerManager.Errored(peerError.NodeID, peerError.Err)
  404. case <-r.stopCh:
  405. return
  406. }
  407. }
  408. }
  409. func (r *Router) filterPeersIP(ctx context.Context, ip net.IP, port uint16) error {
  410. if r.options.FilterPeerByIP == nil {
  411. return nil
  412. }
  413. return r.options.FilterPeerByIP(ctx, ip, port)
  414. }
  415. func (r *Router) filterPeersID(ctx context.Context, id NodeID) error {
  416. if r.options.FilterPeerByID == nil {
  417. return nil
  418. }
  419. return r.options.FilterPeerByID(ctx, id)
  420. }
  421. // acceptPeers accepts inbound connections from peers on the given transport,
  422. // and spawns goroutines that route messages to/from them.
  423. func (r *Router) acceptPeers(transport Transport) {
  424. r.logger.Debug("starting accept routine", "transport", transport)
  425. ctx := r.stopCtx()
  426. for {
  427. conn, err := transport.Accept()
  428. switch err {
  429. case nil:
  430. case io.EOF:
  431. r.logger.Debug("stopping accept routine", "transport", transport)
  432. return
  433. default:
  434. r.logger.Error("failed to accept connection", "transport", transport, "err", err)
  435. return
  436. }
  437. incomingIP := conn.RemoteEndpoint().IP
  438. if err := r.connTracker.AddConn(incomingIP); err != nil {
  439. closeErr := conn.Close()
  440. r.logger.Debug("rate limiting incoming peer",
  441. "err", err,
  442. "ip", incomingIP.String(),
  443. "close_err", closeErr,
  444. )
  445. return
  446. }
  447. // Spawn a goroutine for the handshake, to avoid head-of-line blocking.
  448. go r.openConnection(ctx, conn)
  449. }
  450. }
  451. func (r *Router) openConnection(ctx context.Context, conn Connection) {
  452. defer conn.Close()
  453. defer r.connTracker.RemoveConn(conn.RemoteEndpoint().IP)
  454. re := conn.RemoteEndpoint()
  455. incomingIP := re.IP
  456. if err := r.filterPeersIP(ctx, incomingIP, re.Port); err != nil {
  457. r.logger.Debug("peer filtered by IP", "ip", incomingIP.String(), "err", err)
  458. return
  459. }
  460. // FIXME: The peer manager may reject the peer during Accepted()
  461. // after we've handshaked with the peer (to find out which peer it
  462. // is). However, because the handshake has no ack, the remote peer
  463. // will think the handshake was successful and start sending us
  464. // messages.
  465. //
  466. // This can cause problems in tests, where a disconnection can cause
  467. // the local node to immediately redial, while the remote node may
  468. // not have completed the disconnection yet and therefore reject the
  469. // reconnection attempt (since it thinks we're still connected from
  470. // before).
  471. //
  472. // The Router should do the handshake and have a final ack/fail
  473. // message to make sure both ends have accepted the connection, such
  474. // that it can be coordinated with the peer manager.
  475. peerInfo, _, err := r.handshakePeer(ctx, conn, "")
  476. switch {
  477. case errors.Is(err, context.Canceled):
  478. return
  479. case err != nil:
  480. r.logger.Error("peer handshake failed", "endpoint", conn, "err", err)
  481. return
  482. }
  483. if err := r.filterPeersID(ctx, peerInfo.NodeID); err != nil {
  484. r.logger.Debug("peer filtered by node ID", "node", peerInfo.NodeID, "err", err)
  485. return
  486. }
  487. if err := r.runWithPeerMutex(func() error { return r.peerManager.Accepted(peerInfo.NodeID) }); err != nil {
  488. r.logger.Error("failed to accept connection",
  489. "op", "incoming/accepted", "peer", peerInfo.NodeID, "err", err)
  490. return
  491. }
  492. r.routePeer(peerInfo.NodeID, conn)
  493. }
  494. // dialPeers maintains outbound connections to peers by dialing them.
  495. func (r *Router) dialPeers() {
  496. r.logger.Debug("starting dial routine")
  497. ctx := r.stopCtx()
  498. for {
  499. address, err := r.peerManager.DialNext(ctx)
  500. switch {
  501. case errors.Is(err, context.Canceled):
  502. r.logger.Debug("stopping dial routine")
  503. return
  504. case err != nil:
  505. r.logger.Error("failed to find next peer to dial", "err", err)
  506. return
  507. }
  508. // Spawn off a goroutine to actually dial the peer, so that we can
  509. // dial multiple peers in parallel.
  510. go func() {
  511. conn, err := r.dialPeer(ctx, address)
  512. switch {
  513. case errors.Is(err, context.Canceled):
  514. return
  515. case err != nil:
  516. r.logger.Error("failed to dial peer", "peer", address, "err", err)
  517. if err = r.peerManager.DialFailed(address); err != nil {
  518. r.logger.Error("failed to report dial failure", "peer", address, "err", err)
  519. }
  520. return
  521. }
  522. defer conn.Close()
  523. peerID := address.NodeID
  524. _, _, err = r.handshakePeer(ctx, conn, peerID)
  525. switch {
  526. case errors.Is(err, context.Canceled):
  527. return
  528. case err != nil:
  529. r.logger.Error("failed to handshake with peer", "peer", address, "err", err)
  530. if err = r.peerManager.DialFailed(address); err != nil {
  531. r.logger.Error("failed to report dial failure", "peer", address, "err", err)
  532. }
  533. return
  534. }
  535. if err := r.runWithPeerMutex(func() error { return r.peerManager.Dialed(address) }); err != nil {
  536. r.logger.Error("failed to accept connection",
  537. "op", "outgoing/dialing", "peer", address.NodeID, "err", err)
  538. return
  539. }
  540. r.routePeer(peerID, conn)
  541. }()
  542. }
  543. }
  544. func (r *Router) getOrMakeQueue(peerID NodeID) queue {
  545. r.peerMtx.Lock()
  546. defer r.peerMtx.Unlock()
  547. if peerQueue, ok := r.peerQueues[peerID]; ok {
  548. return peerQueue
  549. }
  550. peerQueue := r.queueFactory(queueBufferDefault)
  551. r.peerQueues[peerID] = peerQueue
  552. return peerQueue
  553. }
  554. // dialPeer connects to a peer by dialing it.
  555. func (r *Router) dialPeer(ctx context.Context, address NodeAddress) (Connection, error) {
  556. resolveCtx := ctx
  557. if r.options.ResolveTimeout > 0 {
  558. var cancel context.CancelFunc
  559. resolveCtx, cancel = context.WithTimeout(resolveCtx, r.options.ResolveTimeout)
  560. defer cancel()
  561. }
  562. r.logger.Debug("resolving peer address", "peer", address)
  563. endpoints, err := address.Resolve(resolveCtx)
  564. switch {
  565. case err != nil:
  566. return nil, fmt.Errorf("failed to resolve address %q: %w", address, err)
  567. case len(endpoints) == 0:
  568. return nil, fmt.Errorf("address %q did not resolve to any endpoints", address)
  569. }
  570. for _, endpoint := range endpoints {
  571. transport, ok := r.protocolTransports[endpoint.Protocol]
  572. if !ok {
  573. r.logger.Error("no transport found for protocol", "endpoint", endpoint)
  574. continue
  575. }
  576. dialCtx := ctx
  577. if r.options.DialTimeout > 0 {
  578. var cancel context.CancelFunc
  579. dialCtx, cancel = context.WithTimeout(dialCtx, r.options.DialTimeout)
  580. defer cancel()
  581. }
  582. // FIXME: When we dial and handshake the peer, we should pass it
  583. // appropriate address(es) it can use to dial us back. It can't use our
  584. // remote endpoint, since TCP uses different port numbers for outbound
  585. // connections than it does for inbound. Also, we may need to vary this
  586. // by the peer's endpoint, since e.g. a peer on 192.168.0.0 can reach us
  587. // on a private address on this endpoint, but a peer on the public
  588. // Internet can't and needs a different public address.
  589. conn, err := transport.Dial(dialCtx, endpoint)
  590. if err != nil {
  591. r.logger.Error("failed to dial endpoint", "peer", address.NodeID, "endpoint", endpoint, "err", err)
  592. } else {
  593. r.logger.Debug("dialed peer", "peer", address.NodeID, "endpoint", endpoint)
  594. return conn, nil
  595. }
  596. }
  597. return nil, errors.New("all endpoints failed")
  598. }
  599. // handshakePeer handshakes with a peer, validating the peer's information. If
  600. // expectID is given, we check that the peer's info matches it.
  601. func (r *Router) handshakePeer(ctx context.Context, conn Connection, expectID NodeID) (NodeInfo, crypto.PubKey, error) {
  602. if r.options.HandshakeTimeout > 0 {
  603. var cancel context.CancelFunc
  604. ctx, cancel = context.WithTimeout(ctx, r.options.HandshakeTimeout)
  605. defer cancel()
  606. }
  607. peerInfo, peerKey, err := conn.Handshake(ctx, r.nodeInfo, r.privKey)
  608. if err != nil {
  609. return peerInfo, peerKey, err
  610. }
  611. if err = peerInfo.Validate(); err != nil {
  612. return peerInfo, peerKey, fmt.Errorf("invalid handshake NodeInfo: %w", err)
  613. }
  614. if NodeIDFromPubKey(peerKey) != peerInfo.NodeID {
  615. return peerInfo, peerKey, fmt.Errorf("peer's public key did not match its node ID %q (expected %q)",
  616. peerInfo.NodeID, NodeIDFromPubKey(peerKey))
  617. }
  618. if expectID != "" && expectID != peerInfo.NodeID {
  619. return peerInfo, peerKey, fmt.Errorf("expected to connect with peer %q, got %q",
  620. expectID, peerInfo.NodeID)
  621. }
  622. return peerInfo, peerKey, nil
  623. }
  624. func (r *Router) runWithPeerMutex(fn func() error) error {
  625. r.peerMtx.Lock()
  626. defer r.peerMtx.Unlock()
  627. return fn()
  628. }
  629. // routePeer routes inbound and outbound messages between a peer and the reactor
  630. // channels. It will close the given connection and send queue when done, or if
  631. // they are closed elsewhere it will cause this method to shut down and return.
  632. func (r *Router) routePeer(peerID NodeID, conn Connection) {
  633. r.metrics.Peers.Add(1)
  634. r.peerManager.Ready(peerID)
  635. sendQueue := r.getOrMakeQueue(peerID)
  636. defer func() {
  637. r.peerMtx.Lock()
  638. delete(r.peerQueues, peerID)
  639. r.peerMtx.Unlock()
  640. sendQueue.close()
  641. r.peerManager.Disconnected(peerID)
  642. r.metrics.Peers.Add(-1)
  643. }()
  644. r.logger.Info("peer connected", "peer", peerID, "endpoint", conn)
  645. errCh := make(chan error, 2)
  646. go func() {
  647. errCh <- r.receivePeer(peerID, conn)
  648. }()
  649. go func() {
  650. errCh <- r.sendPeer(peerID, conn, sendQueue)
  651. }()
  652. err := <-errCh
  653. _ = conn.Close()
  654. sendQueue.close()
  655. if e := <-errCh; err == nil {
  656. // The first err was nil, so we update it with the second err, which may
  657. // or may not be nil.
  658. err = e
  659. }
  660. switch err {
  661. case nil, io.EOF:
  662. r.logger.Info("peer disconnected", "peer", peerID, "endpoint", conn)
  663. default:
  664. r.logger.Error("peer failure", "peer", peerID, "endpoint", conn, "err", err)
  665. }
  666. }
  667. // receivePeer receives inbound messages from a peer, deserializes them and
  668. // passes them on to the appropriate channel.
  669. func (r *Router) receivePeer(peerID NodeID, conn Connection) error {
  670. for {
  671. chID, bz, err := conn.ReceiveMessage()
  672. if err != nil {
  673. return err
  674. }
  675. r.channelMtx.RLock()
  676. queue, ok := r.channelQueues[chID]
  677. messageType := r.channelMessages[chID]
  678. r.channelMtx.RUnlock()
  679. if !ok {
  680. r.logger.Debug("dropping message for unknown channel", "peer", peerID, "channel", chID)
  681. continue
  682. }
  683. msg := proto.Clone(messageType)
  684. if err := proto.Unmarshal(bz, msg); err != nil {
  685. r.logger.Error("message decoding failed, dropping message", "peer", peerID, "err", err)
  686. continue
  687. }
  688. if wrapper, ok := msg.(Wrapper); ok {
  689. msg, err = wrapper.Unwrap()
  690. if err != nil {
  691. r.logger.Error("failed to unwrap message", "err", err)
  692. continue
  693. }
  694. }
  695. start := time.Now().UTC()
  696. select {
  697. case queue.enqueue() <- Envelope{From: peerID, Message: msg}:
  698. r.metrics.PeerReceiveBytesTotal.With(
  699. "chID", fmt.Sprint(chID),
  700. "peer_id", string(peerID)).Add(float64(proto.Size(msg)))
  701. r.metrics.RouterChannelQueueSend.Observe(time.Since(start).Seconds())
  702. r.logger.Debug("received message", "peer", peerID, "message", msg)
  703. case <-queue.closed():
  704. r.logger.Debug("channel closed, dropping message", "peer", peerID, "channel", chID)
  705. case <-r.stopCh:
  706. return nil
  707. }
  708. }
  709. }
  710. // sendPeer sends queued messages to a peer.
  711. func (r *Router) sendPeer(peerID NodeID, conn Connection, peerQueue queue) error {
  712. for {
  713. start := time.Now().UTC()
  714. select {
  715. case envelope := <-peerQueue.dequeue():
  716. r.metrics.RouterPeerQueueRecv.Observe(time.Since(start).Seconds())
  717. if envelope.Message == nil {
  718. r.logger.Error("dropping nil message", "peer", peerID)
  719. continue
  720. }
  721. bz, err := proto.Marshal(envelope.Message)
  722. if err != nil {
  723. r.logger.Error("failed to marshal message", "peer", peerID, "err", err)
  724. continue
  725. }
  726. _, err = conn.SendMessage(envelope.channelID, bz)
  727. if err != nil {
  728. return err
  729. }
  730. r.logger.Debug("sent message", "peer", envelope.To, "message", envelope.Message)
  731. case <-peerQueue.closed():
  732. return nil
  733. case <-r.stopCh:
  734. return nil
  735. }
  736. }
  737. }
  738. // evictPeers evicts connected peers as requested by the peer manager.
  739. func (r *Router) evictPeers() {
  740. r.logger.Debug("starting evict routine")
  741. ctx := r.stopCtx()
  742. for {
  743. peerID, err := r.peerManager.EvictNext(ctx)
  744. switch {
  745. case errors.Is(err, context.Canceled):
  746. r.logger.Debug("stopping evict routine")
  747. return
  748. case err != nil:
  749. r.logger.Error("failed to find next peer to evict", "err", err)
  750. return
  751. }
  752. r.logger.Info("evicting peer", "peer", peerID)
  753. r.peerMtx.RLock()
  754. queue, ok := r.peerQueues[peerID]
  755. r.peerMtx.RUnlock()
  756. if ok {
  757. queue.close()
  758. }
  759. }
  760. }
  761. // OnStart implements service.Service.
  762. func (r *Router) OnStart() error {
  763. go r.dialPeers()
  764. go r.evictPeers()
  765. for _, transport := range r.transports {
  766. go r.acceptPeers(transport)
  767. }
  768. return nil
  769. }
  770. // OnStop implements service.Service.
  771. //
  772. // All channels must be closed by OpenChannel() callers before stopping the
  773. // router, to prevent blocked channel sends in reactors. Channels are not closed
  774. // here, since that would cause any reactor senders to panic, so it is the
  775. // sender's responsibility.
  776. func (r *Router) OnStop() {
  777. // Signal router shutdown.
  778. close(r.stopCh)
  779. // Close transport listeners (unblocks Accept calls).
  780. for _, transport := range r.transports {
  781. if err := transport.Close(); err != nil {
  782. r.logger.Error("failed to close transport", "transport", transport, "err", err)
  783. }
  784. }
  785. // Collect all remaining queues, and wait for them to close.
  786. queues := []queue{}
  787. r.channelMtx.RLock()
  788. for _, q := range r.channelQueues {
  789. queues = append(queues, q)
  790. }
  791. r.channelMtx.RUnlock()
  792. r.peerMtx.RLock()
  793. for _, q := range r.peerQueues {
  794. queues = append(queues, q)
  795. }
  796. r.peerMtx.RUnlock()
  797. for _, q := range queues {
  798. <-q.closed()
  799. }
  800. }
  801. // stopCtx returns a new context that is canceled when the router stops.
  802. func (r *Router) stopCtx() context.Context {
  803. ctx, cancel := context.WithCancel(context.Background())
  804. go func() {
  805. <-r.stopCh
  806. cancel()
  807. }()
  808. return ctx
  809. }