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.

779 lines
24 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
  1. package p2p
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "sync"
  8. "time"
  9. "github.com/gogo/protobuf/proto"
  10. "github.com/tendermint/tendermint/crypto"
  11. "github.com/tendermint/tendermint/libs/log"
  12. "github.com/tendermint/tendermint/libs/service"
  13. )
  14. // ChannelID is an arbitrary channel ID.
  15. type ChannelID uint16
  16. // Envelope contains a message with sender/receiver routing info.
  17. type Envelope struct {
  18. From NodeID // sender (empty if outbound)
  19. To NodeID // receiver (empty if inbound)
  20. Broadcast bool // send to all connected peers (ignores To)
  21. Message proto.Message // message payload
  22. // channelID is for internal Router use, set on outbound messages to inform
  23. // the sendPeer() goroutine which transport channel to use.
  24. //
  25. // FIXME: If we migrate the Transport API to a byte-oriented multi-stream
  26. // API, this will no longer be necessary since each channel will be mapped
  27. // onto a stream during channel/peer setup. See:
  28. // https://github.com/tendermint/spec/pull/227
  29. channelID ChannelID
  30. }
  31. // PeerError is a peer error reported via Channel.Error.
  32. //
  33. // FIXME: This currently just disconnects the peer, which is too simplistic.
  34. // For example, some errors should be logged, some should cause disconnects,
  35. // and some should ban the peer.
  36. //
  37. // FIXME: This should probably be replaced by a more general PeerBehavior
  38. // concept that can mark good and bad behavior and contributes to peer scoring.
  39. // It should possibly also allow reactors to request explicit actions, e.g.
  40. // disconnection or banning, in addition to doing this based on aggregates.
  41. type PeerError struct {
  42. NodeID NodeID
  43. Err error
  44. }
  45. // Channel is a bidirectional channel to exchange Protobuf messages with peers,
  46. // wrapped in Envelope to specify routing info (i.e. sender/receiver).
  47. type Channel struct {
  48. ID ChannelID
  49. In <-chan Envelope // inbound messages (peers to reactors)
  50. Out chan<- Envelope // outbound messages (reactors to peers)
  51. Error chan<- PeerError // peer error reporting
  52. messageType proto.Message // the channel's message type, used for unmarshaling
  53. closeCh chan struct{}
  54. closeOnce sync.Once
  55. }
  56. // NewChannel creates a new channel. It is primarily for internal and test
  57. // use, reactors should use Router.OpenChannel().
  58. func NewChannel(
  59. id ChannelID,
  60. messageType proto.Message,
  61. inCh <-chan Envelope,
  62. outCh chan<- Envelope,
  63. errCh chan<- PeerError,
  64. ) *Channel {
  65. return &Channel{
  66. ID: id,
  67. messageType: messageType,
  68. In: inCh,
  69. Out: outCh,
  70. Error: errCh,
  71. closeCh: make(chan struct{}),
  72. }
  73. }
  74. // Close closes the channel. Future sends on Out and Error will panic. The In
  75. // channel remains open to avoid having to synchronize Router senders, which
  76. // should use Done() to detect channel closure instead.
  77. func (c *Channel) Close() {
  78. c.closeOnce.Do(func() {
  79. close(c.closeCh)
  80. close(c.Out)
  81. close(c.Error)
  82. })
  83. }
  84. // Done returns a channel that's closed when Channel.Close() is called.
  85. func (c *Channel) Done() <-chan struct{} {
  86. return c.closeCh
  87. }
  88. // Wrapper is a Protobuf message that can contain a variety of inner messages
  89. // (e.g. via oneof fields). If a Channel's message type implements Wrapper, the
  90. // Router will automatically wrap outbound messages and unwrap inbound messages,
  91. // such that reactors do not have to do this themselves.
  92. type Wrapper interface {
  93. proto.Message
  94. // Wrap will take a message and wrap it in this one if possible.
  95. Wrap(proto.Message) error
  96. // Unwrap will unwrap the inner message contained in this message.
  97. Unwrap() (proto.Message, error)
  98. }
  99. // RouterOptions specifies options for a Router.
  100. type RouterOptions struct {
  101. // ResolveTimeout is the timeout for resolving NodeAddress URLs.
  102. // 0 means no timeout.
  103. ResolveTimeout time.Duration
  104. // DialTimeout is the timeout for dialing a peer. 0 means no timeout.
  105. DialTimeout time.Duration
  106. // HandshakeTimeout is the timeout for handshaking with a peer. 0 means
  107. // no timeout.
  108. HandshakeTimeout time.Duration
  109. }
  110. // Validate validates router options.
  111. func (o *RouterOptions) Validate() error {
  112. return nil
  113. }
  114. // Router manages peer connections and routes messages between peers and reactor
  115. // channels. It takes a PeerManager for peer lifecycle management (e.g. which
  116. // peers to dial and when) and a set of Transports for connecting and
  117. // communicating with peers.
  118. //
  119. // On startup, three main goroutines are spawned to maintain peer connections:
  120. //
  121. // dialPeers(): in a loop, calls PeerManager.DialNext() to get the next peer
  122. // address to dial and spawns a goroutine that dials the peer, handshakes
  123. // with it, and begins to route messages if successful.
  124. //
  125. // acceptPeers(): in a loop, waits for an inbound connection via
  126. // Transport.Accept() and spawns a goroutine that handshakes with it and
  127. // begins to route messages if successful.
  128. //
  129. // evictPeers(): in a loop, calls PeerManager.EvictNext() to get the next
  130. // peer to evict, and disconnects it by closing its message queue.
  131. //
  132. // When a peer is connected, an outbound peer message queue is registered in
  133. // peerQueues, and routePeer() is called to spawn off two additional goroutines:
  134. //
  135. // sendPeer(): waits for an outbound message from the peerQueues queue,
  136. // marshals it, and passes it to the peer transport which delivers it.
  137. //
  138. // receivePeer(): waits for an inbound message from the peer transport,
  139. // unmarshals it, and passes it to the appropriate inbound channel queue
  140. // in channelQueues.
  141. //
  142. // When a reactor opens a channel via OpenChannel, an inbound channel message
  143. // queue is registered in channelQueues, and a channel goroutine is spawned:
  144. //
  145. // routeChannel(): waits for an outbound message from the channel, looks
  146. // up the recipient peer's outbound message queue in peerQueues, and submits
  147. // the message to it.
  148. //
  149. // All channel sends in the router are blocking. It is the responsibility of the
  150. // queue interface in peerQueues and channelQueues to prioritize and drop
  151. // messages as appropriate during contention to prevent stalls and ensure good
  152. // quality of service.
  153. type Router struct {
  154. *service.BaseService
  155. logger log.Logger
  156. options RouterOptions
  157. nodeInfo NodeInfo
  158. privKey crypto.PrivKey
  159. peerManager *PeerManager
  160. transports []Transport
  161. protocolTransports map[Protocol]Transport
  162. stopCh chan struct{} // signals Router shutdown
  163. peerMtx sync.RWMutex
  164. peerQueues map[NodeID]queue
  165. // FIXME: We don't strictly need to use a mutex for this if we seal the
  166. // channels on router start. This depends on whether we want to allow
  167. // dynamic channels in the future.
  168. channelMtx sync.RWMutex
  169. channelQueues map[ChannelID]queue
  170. channelMessages map[ChannelID]proto.Message
  171. }
  172. // NewRouter creates a new Router. The given Transports must already be
  173. // listening on appropriate interfaces, and will be closed by the Router when it
  174. // stops.
  175. func NewRouter(
  176. logger log.Logger,
  177. nodeInfo NodeInfo,
  178. privKey crypto.PrivKey,
  179. peerManager *PeerManager,
  180. transports []Transport,
  181. options RouterOptions,
  182. ) (*Router, error) {
  183. if err := options.Validate(); err != nil {
  184. return nil, err
  185. }
  186. router := &Router{
  187. logger: logger,
  188. nodeInfo: nodeInfo,
  189. privKey: privKey,
  190. transports: transports,
  191. protocolTransports: map[Protocol]Transport{},
  192. peerManager: peerManager,
  193. options: options,
  194. stopCh: make(chan struct{}),
  195. channelQueues: map[ChannelID]queue{},
  196. channelMessages: map[ChannelID]proto.Message{},
  197. peerQueues: map[NodeID]queue{},
  198. }
  199. router.BaseService = service.NewBaseService(logger, "router", router)
  200. for _, transport := range transports {
  201. for _, protocol := range transport.Protocols() {
  202. if _, ok := router.protocolTransports[protocol]; !ok {
  203. router.protocolTransports[protocol] = transport
  204. }
  205. }
  206. }
  207. return router, nil
  208. }
  209. // OpenChannel opens a new channel for the given message type. The caller must
  210. // close the channel when done, before stopping the Router. messageType is the
  211. // type of message passed through the channel (used for unmarshaling), which can
  212. // implement Wrapper to automatically (un)wrap multiple message types in a
  213. // wrapper message. The caller may provide a size to make the channel buffered,
  214. // which internally makes the inbound, outbound, and error channel buffered.
  215. func (r *Router) OpenChannel(id ChannelID, messageType proto.Message, size int) (*Channel, error) {
  216. queue := newFIFOQueue(size)
  217. outCh := make(chan Envelope, size)
  218. errCh := make(chan PeerError, size)
  219. channel := NewChannel(id, messageType, queue.dequeue(), outCh, errCh)
  220. var wrapper Wrapper
  221. if w, ok := messageType.(Wrapper); ok {
  222. wrapper = w
  223. }
  224. r.channelMtx.Lock()
  225. defer r.channelMtx.Unlock()
  226. if _, ok := r.channelQueues[id]; ok {
  227. return nil, fmt.Errorf("channel %v already exists", id)
  228. }
  229. r.channelQueues[id] = queue
  230. r.channelMessages[id] = messageType
  231. go func() {
  232. defer func() {
  233. r.channelMtx.Lock()
  234. delete(r.channelQueues, id)
  235. delete(r.channelMessages, id)
  236. r.channelMtx.Unlock()
  237. queue.close()
  238. }()
  239. r.routeChannel(id, outCh, errCh, wrapper)
  240. }()
  241. return channel, nil
  242. }
  243. // routeChannel receives outbound channel messages and routes them to the
  244. // appropriate peer. It also receives peer errors and reports them to the peer
  245. // manager. It returns when either the outbound channel or error channel is
  246. // closed, or the Router is stopped. wrapper is an optional message wrapper
  247. // for messages, see Wrapper for details.
  248. func (r *Router) routeChannel(
  249. chID ChannelID,
  250. outCh <-chan Envelope,
  251. errCh <-chan PeerError,
  252. wrapper Wrapper,
  253. ) {
  254. for {
  255. select {
  256. case envelope, ok := <-outCh:
  257. if !ok {
  258. return
  259. }
  260. // Mark the envelope with the channel ID to allow sendPeer() to pass
  261. // it on to Transport.SendMessage().
  262. envelope.channelID = chID
  263. // Wrap the message in a wrapper message, if requested.
  264. if wrapper != nil {
  265. msg := proto.Clone(wrapper)
  266. if err := msg.(Wrapper).Wrap(envelope.Message); err != nil {
  267. r.Logger.Error("failed to wrap message", "channel", chID, "err", err)
  268. continue
  269. }
  270. envelope.Message = msg
  271. }
  272. // Collect peer queues to pass the message via.
  273. var queues []queue
  274. if envelope.Broadcast {
  275. r.peerMtx.RLock()
  276. queues = make([]queue, 0, len(r.peerQueues))
  277. for _, q := range r.peerQueues {
  278. queues = append(queues, q)
  279. }
  280. r.peerMtx.RUnlock()
  281. } else {
  282. r.peerMtx.RLock()
  283. q, ok := r.peerQueues[envelope.To]
  284. r.peerMtx.RUnlock()
  285. if !ok {
  286. r.logger.Debug("dropping message for unconnected peer",
  287. "peer", envelope.To, "channel", chID)
  288. continue
  289. }
  290. queues = []queue{q}
  291. }
  292. // Send message to peers.
  293. for _, q := range queues {
  294. select {
  295. case q.enqueue() <- envelope:
  296. case <-q.closed():
  297. r.logger.Debug("dropping message for unconnected peer",
  298. "peer", envelope.To, "channel", chID)
  299. case <-r.stopCh:
  300. return
  301. }
  302. }
  303. case peerError, ok := <-errCh:
  304. if !ok {
  305. return
  306. }
  307. r.logger.Error("peer error, evicting", "peer", peerError.NodeID, "err", peerError.Err)
  308. if err := r.peerManager.Errored(peerError.NodeID, peerError.Err); err != nil {
  309. r.logger.Error("failed to report peer error", "peer", peerError.NodeID, "err", err)
  310. }
  311. case <-r.stopCh:
  312. return
  313. }
  314. }
  315. }
  316. // acceptPeers accepts inbound connections from peers on the given transport,
  317. // and spawns goroutines that route messages to/from them.
  318. func (r *Router) acceptPeers(transport Transport) {
  319. r.logger.Debug("starting accept routine", "transport", transport)
  320. ctx := r.stopCtx()
  321. for {
  322. // FIXME: We may need transports to enforce some sort of rate limiting
  323. // here (e.g. by IP address), or alternatively have PeerManager.Accepted()
  324. // do it for us.
  325. //
  326. // FIXME: Even though PeerManager enforces MaxConnected, we may want to
  327. // limit the maximum number of active connections here too, since e.g.
  328. // an adversary can open a ton of connections and then just hang during
  329. // the handshake, taking up TCP socket descriptors.
  330. //
  331. // FIXME: The old P2P stack rejected multiple connections for the same IP
  332. // unless P2PConfig.AllowDuplicateIP is true -- it's better to limit this
  333. // by peer ID rather than IP address, so this hasn't been implemented and
  334. // probably shouldn't (?).
  335. //
  336. // FIXME: The old P2P stack supported ABCI-based IP address filtering via
  337. // /p2p/filter/addr/<ip> queries, do we want to implement this here as well?
  338. // Filtering by node ID is probably better.
  339. conn, err := transport.Accept()
  340. switch err {
  341. case nil:
  342. case io.EOF:
  343. r.logger.Debug("stopping accept routine", "transport", transport)
  344. return
  345. default:
  346. r.logger.Error("failed to accept connection", "transport", transport, "err", err)
  347. return
  348. }
  349. // Spawn a goroutine for the handshake, to avoid head-of-line blocking.
  350. go func() {
  351. defer conn.Close()
  352. // FIXME: The peer manager may reject the peer during Accepted()
  353. // after we've handshaked with the peer (to find out which peer it
  354. // is). However, because the handshake has no ack, the remote peer
  355. // will think the handshake was successful and start sending us
  356. // messages.
  357. //
  358. // This can cause problems in tests, where a disconnection can cause
  359. // the local node to immediately redial, while the remote node may
  360. // not have completed the disconnection yet and therefore reject the
  361. // reconnection attempt (since it thinks we're still connected from
  362. // before).
  363. //
  364. // The Router should do the handshake and have a final ack/fail
  365. // message to make sure both ends have accepted the connection, such
  366. // that it can be coordinated with the peer manager.
  367. peerInfo, _, err := r.handshakePeer(ctx, conn, "")
  368. switch {
  369. case errors.Is(err, context.Canceled):
  370. return
  371. case err != nil:
  372. r.logger.Error("peer handshake failed", "endpoint", conn, "err", err)
  373. return
  374. }
  375. if err := r.peerManager.Accepted(peerInfo.NodeID); err != nil {
  376. r.logger.Error("failed to accept connection", "peer", peerInfo.NodeID, "err", err)
  377. return
  378. }
  379. queue := newFIFOQueue(0)
  380. r.peerMtx.Lock()
  381. r.peerQueues[peerInfo.NodeID] = queue
  382. r.peerMtx.Unlock()
  383. defer func() {
  384. r.peerMtx.Lock()
  385. delete(r.peerQueues, peerInfo.NodeID)
  386. r.peerMtx.Unlock()
  387. queue.close()
  388. if err := r.peerManager.Disconnected(peerInfo.NodeID); err != nil {
  389. r.logger.Error("failed to disconnect peer", "peer", peerInfo.NodeID, "err", err)
  390. }
  391. }()
  392. if err := r.peerManager.Ready(peerInfo.NodeID); err != nil {
  393. r.logger.Error("failed to mark peer as ready", "peer", peerInfo.NodeID, "err", err)
  394. return
  395. }
  396. r.routePeer(peerInfo.NodeID, conn, queue)
  397. }()
  398. }
  399. }
  400. // dialPeers maintains outbound connections to peers by dialing them.
  401. func (r *Router) dialPeers() {
  402. r.logger.Debug("starting dial routine")
  403. ctx := r.stopCtx()
  404. for {
  405. address, err := r.peerManager.DialNext(ctx)
  406. switch {
  407. case errors.Is(err, context.Canceled):
  408. r.logger.Debug("stopping dial routine")
  409. return
  410. case err != nil:
  411. r.logger.Error("failed to find next peer to dial", "err", err)
  412. return
  413. }
  414. // Spawn off a goroutine to actually dial the peer, so that we can
  415. // dial multiple peers in parallel.
  416. go func() {
  417. conn, err := r.dialPeer(ctx, address)
  418. switch {
  419. case errors.Is(err, context.Canceled):
  420. return
  421. case err != nil:
  422. r.logger.Error("failed to dial peer", "peer", address, "err", err)
  423. if err = r.peerManager.DialFailed(address); err != nil {
  424. r.logger.Error("failed to report dial failure", "peer", address, "err", err)
  425. }
  426. return
  427. }
  428. defer conn.Close()
  429. peerID := address.NodeID
  430. _, _, err = r.handshakePeer(ctx, conn, peerID)
  431. switch {
  432. case errors.Is(err, context.Canceled):
  433. return
  434. case err != nil:
  435. r.logger.Error("failed to handshake with peer", "peer", address, "err", err)
  436. if err = r.peerManager.DialFailed(address); err != nil {
  437. r.logger.Error("failed to report dial failure", "peer", address, "err", err)
  438. }
  439. return
  440. }
  441. if err = r.peerManager.Dialed(address); err != nil {
  442. r.logger.Error("failed to dial peer", "peer", address, "err", err)
  443. return
  444. }
  445. queue := newFIFOQueue(0)
  446. r.peerMtx.Lock()
  447. r.peerQueues[peerID] = queue
  448. r.peerMtx.Unlock()
  449. defer func() {
  450. r.peerMtx.Lock()
  451. delete(r.peerQueues, peerID)
  452. r.peerMtx.Unlock()
  453. queue.close()
  454. if err := r.peerManager.Disconnected(peerID); err != nil {
  455. r.logger.Error("failed to disconnect peer", "peer", address, "err", err)
  456. }
  457. }()
  458. if err := r.peerManager.Ready(peerID); err != nil {
  459. r.logger.Error("failed to mark peer as ready", "peer", address, "err", err)
  460. return
  461. }
  462. r.routePeer(peerID, conn, queue)
  463. }()
  464. }
  465. }
  466. // dialPeer connects to a peer by dialing it.
  467. func (r *Router) dialPeer(ctx context.Context, address NodeAddress) (Connection, error) {
  468. resolveCtx := ctx
  469. if r.options.ResolveTimeout > 0 {
  470. var cancel context.CancelFunc
  471. resolveCtx, cancel = context.WithTimeout(resolveCtx, r.options.ResolveTimeout)
  472. defer cancel()
  473. }
  474. r.logger.Debug("resolving peer address", "peer", address)
  475. endpoints, err := address.Resolve(resolveCtx)
  476. switch {
  477. case err != nil:
  478. return nil, fmt.Errorf("failed to resolve address %q: %w", address, err)
  479. case len(endpoints) == 0:
  480. return nil, fmt.Errorf("address %q did not resolve to any endpoints", address)
  481. }
  482. for _, endpoint := range endpoints {
  483. transport, ok := r.protocolTransports[endpoint.Protocol]
  484. if !ok {
  485. r.logger.Error("no transport found for protocol", "endpoint", endpoint)
  486. continue
  487. }
  488. dialCtx := ctx
  489. if r.options.DialTimeout > 0 {
  490. var cancel context.CancelFunc
  491. dialCtx, cancel = context.WithTimeout(dialCtx, r.options.DialTimeout)
  492. defer cancel()
  493. }
  494. // FIXME: When we dial and handshake the peer, we should pass it
  495. // appropriate address(es) it can use to dial us back. It can't use our
  496. // remote endpoint, since TCP uses different port numbers for outbound
  497. // connections than it does for inbound. Also, we may need to vary this
  498. // by the peer's endpoint, since e.g. a peer on 192.168.0.0 can reach us
  499. // on a private address on this endpoint, but a peer on the public
  500. // Internet can't and needs a different public address.
  501. conn, err := transport.Dial(dialCtx, endpoint)
  502. if err != nil {
  503. r.logger.Error("failed to dial endpoint", "peer", address.NodeID, "endpoint", endpoint, "err", err)
  504. } else {
  505. r.logger.Debug("dialed peer", "peer", address.NodeID, "endpoint", endpoint)
  506. return conn, nil
  507. }
  508. }
  509. return nil, errors.New("all endpoints failed")
  510. }
  511. // handshakePeer handshakes with a peer, validating the peer's information. If
  512. // expectID is given, we check that the peer's info matches it.
  513. func (r *Router) handshakePeer(ctx context.Context, conn Connection, expectID NodeID) (NodeInfo, crypto.PubKey, error) {
  514. if r.options.HandshakeTimeout > 0 {
  515. var cancel context.CancelFunc
  516. ctx, cancel = context.WithTimeout(ctx, r.options.HandshakeTimeout)
  517. defer cancel()
  518. }
  519. peerInfo, peerKey, err := conn.Handshake(ctx, r.nodeInfo, r.privKey)
  520. if err != nil {
  521. return peerInfo, peerKey, err
  522. }
  523. if err = peerInfo.Validate(); err != nil {
  524. return peerInfo, peerKey, fmt.Errorf("invalid handshake NodeInfo: %w", err)
  525. }
  526. if NodeIDFromPubKey(peerKey) != peerInfo.NodeID {
  527. return peerInfo, peerKey, fmt.Errorf("peer's public key did not match its node ID %q (expected %q)",
  528. peerInfo.NodeID, NodeIDFromPubKey(peerKey))
  529. }
  530. if expectID != "" && expectID != peerInfo.NodeID {
  531. return peerInfo, peerKey, fmt.Errorf("expected to connect with peer %q, got %q",
  532. expectID, peerInfo.NodeID)
  533. }
  534. return peerInfo, peerKey, nil
  535. }
  536. // routePeer routes inbound and outbound messages between a peer and the reactor
  537. // channels. It will close the given connection and send queue when done, or if
  538. // they are closed elsewhere it will cause this method to shut down and return.
  539. func (r *Router) routePeer(peerID NodeID, conn Connection, sendQueue queue) {
  540. r.logger.Info("peer connected", "peer", peerID, "endpoint", conn)
  541. errCh := make(chan error, 2)
  542. go func() {
  543. errCh <- r.receivePeer(peerID, conn)
  544. }()
  545. go func() {
  546. errCh <- r.sendPeer(peerID, conn, sendQueue)
  547. }()
  548. err := <-errCh
  549. _ = conn.Close()
  550. sendQueue.close()
  551. if e := <-errCh; err == nil {
  552. // The first err was nil, so we update it with the second err, which may
  553. // or may not be nil.
  554. err = e
  555. }
  556. switch err {
  557. case nil, io.EOF:
  558. r.logger.Info("peer disconnected", "peer", peerID, "endpoint", conn)
  559. default:
  560. r.logger.Error("peer failure", "peer", peerID, "endpoint", conn, "err", err)
  561. }
  562. }
  563. // receivePeer receives inbound messages from a peer, deserializes them and
  564. // passes them on to the appropriate channel.
  565. func (r *Router) receivePeer(peerID NodeID, conn Connection) error {
  566. for {
  567. chID, bz, err := conn.ReceiveMessage()
  568. if err != nil {
  569. return err
  570. }
  571. r.channelMtx.RLock()
  572. queue, ok := r.channelQueues[chID]
  573. messageType := r.channelMessages[chID]
  574. r.channelMtx.RUnlock()
  575. if !ok {
  576. r.logger.Debug("dropping message for unknown channel", "peer", peerID, "channel", chID)
  577. continue
  578. }
  579. msg := proto.Clone(messageType)
  580. if err := proto.Unmarshal(bz, msg); err != nil {
  581. r.logger.Error("message decoding failed, dropping message", "peer", peerID, "err", err)
  582. continue
  583. }
  584. if wrapper, ok := msg.(Wrapper); ok {
  585. msg, err = wrapper.Unwrap()
  586. if err != nil {
  587. r.logger.Error("failed to unwrap message", "err", err)
  588. continue
  589. }
  590. }
  591. select {
  592. case queue.enqueue() <- Envelope{From: peerID, Message: msg}:
  593. r.logger.Debug("received message", "peer", peerID, "message", msg)
  594. case <-queue.closed():
  595. r.logger.Debug("channel closed, dropping message", "peer", peerID, "channel", chID)
  596. case <-r.stopCh:
  597. return nil
  598. }
  599. }
  600. }
  601. // sendPeer sends queued messages to a peer.
  602. func (r *Router) sendPeer(peerID NodeID, conn Connection, queue queue) error {
  603. for {
  604. select {
  605. case envelope := <-queue.dequeue():
  606. if envelope.Message == nil {
  607. r.logger.Error("dropping nil message", "peer", peerID)
  608. continue
  609. }
  610. bz, err := proto.Marshal(envelope.Message)
  611. if err != nil {
  612. r.logger.Error("failed to marshal message", "peer", peerID, "err", err)
  613. continue
  614. }
  615. _, err = conn.SendMessage(envelope.channelID, bz)
  616. if err != nil {
  617. return err
  618. }
  619. r.logger.Debug("sent message", "peer", envelope.To, "message", envelope.Message)
  620. case <-queue.closed():
  621. return nil
  622. case <-r.stopCh:
  623. return nil
  624. }
  625. }
  626. }
  627. // evictPeers evicts connected peers as requested by the peer manager.
  628. func (r *Router) evictPeers() {
  629. r.logger.Debug("starting evict routine")
  630. ctx := r.stopCtx()
  631. for {
  632. peerID, err := r.peerManager.EvictNext(ctx)
  633. switch {
  634. case errors.Is(err, context.Canceled):
  635. r.logger.Debug("stopping evict routine")
  636. return
  637. case err != nil:
  638. r.logger.Error("failed to find next peer to evict", "err", err)
  639. return
  640. }
  641. r.logger.Info("evicting peer", "peer", peerID)
  642. r.peerMtx.RLock()
  643. queue, ok := r.peerQueues[peerID]
  644. r.peerMtx.RUnlock()
  645. if ok {
  646. queue.close()
  647. }
  648. }
  649. }
  650. // OnStart implements service.Service.
  651. func (r *Router) OnStart() error {
  652. go r.dialPeers()
  653. go r.evictPeers()
  654. for _, transport := range r.transports {
  655. go r.acceptPeers(transport)
  656. }
  657. return nil
  658. }
  659. // OnStop implements service.Service.
  660. //
  661. // All channels must be closed by OpenChannel() callers before stopping the
  662. // router, to prevent blocked channel sends in reactors. Channels are not closed
  663. // here, since that would cause any reactor senders to panic, so it is the
  664. // sender's responsibility.
  665. func (r *Router) OnStop() {
  666. // Signal router shutdown.
  667. close(r.stopCh)
  668. // Close transport listeners (unblocks Accept calls).
  669. for _, transport := range r.transports {
  670. if err := transport.Close(); err != nil {
  671. r.logger.Error("failed to close transport", "transport", transport, "err", err)
  672. }
  673. }
  674. // Collect all remaining queues, and wait for them to close.
  675. queues := []queue{}
  676. r.channelMtx.RLock()
  677. for _, q := range r.channelQueues {
  678. queues = append(queues, q)
  679. }
  680. r.channelMtx.RUnlock()
  681. r.peerMtx.RLock()
  682. for _, q := range r.peerQueues {
  683. queues = append(queues, q)
  684. }
  685. r.peerMtx.RUnlock()
  686. for _, q := range queues {
  687. <-q.closed()
  688. }
  689. }
  690. // stopCtx returns a new context that is canceled when the router stops.
  691. func (r *Router) stopCtx() context.Context {
  692. ctx, cancel := context.WithCancel(context.Background())
  693. go func() {
  694. <-r.stopCh
  695. cancel()
  696. }()
  697. return ctx
  698. }