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.

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