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.

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