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.

1099 lines
31 KiB

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