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.

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