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.

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