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.

995 lines
28 KiB

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