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.

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