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.

578 lines
15 KiB

blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
  1. package v0
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. bc "github.com/tendermint/tendermint/internal/blockchain"
  7. "github.com/tendermint/tendermint/internal/p2p"
  8. "github.com/tendermint/tendermint/libs/log"
  9. "github.com/tendermint/tendermint/libs/service"
  10. bcproto "github.com/tendermint/tendermint/proto/tendermint/blockchain"
  11. sm "github.com/tendermint/tendermint/state"
  12. "github.com/tendermint/tendermint/store"
  13. "github.com/tendermint/tendermint/types"
  14. )
  15. var (
  16. _ service.Service = (*Reactor)(nil)
  17. // ChannelShims contains a map of ChannelDescriptorShim objects, where each
  18. // object wraps a reference to a legacy p2p ChannelDescriptor and the corresponding
  19. // p2p proto.Message the new p2p Channel is responsible for handling.
  20. //
  21. //
  22. // TODO: Remove once p2p refactor is complete.
  23. // ref: https://github.com/tendermint/tendermint/issues/5670
  24. ChannelShims = map[p2p.ChannelID]*p2p.ChannelDescriptorShim{
  25. BlockchainChannel: {
  26. MsgType: new(bcproto.Message),
  27. Descriptor: &p2p.ChannelDescriptor{
  28. ID: byte(BlockchainChannel),
  29. Priority: 5,
  30. SendQueueCapacity: 1000,
  31. RecvBufferCapacity: 50 * 4096,
  32. RecvMessageCapacity: bc.MaxMsgSize,
  33. MaxSendBytes: 100,
  34. },
  35. },
  36. }
  37. )
  38. const (
  39. // BlockchainChannel is a channel for blocks and status updates
  40. BlockchainChannel = p2p.ChannelID(0x40)
  41. trySyncIntervalMS = 10
  42. // ask for best height every 10s
  43. statusUpdateIntervalSeconds = 10
  44. // check if we should switch to consensus reactor
  45. switchToConsensusIntervalSeconds = 1
  46. // switch to consensus after this duration of inactivity
  47. syncTimeout = 60 * time.Second
  48. )
  49. type consensusReactor interface {
  50. // For when we switch from blockchain reactor and fast sync to the consensus
  51. // machine.
  52. SwitchToConsensus(state sm.State, skipWAL bool)
  53. }
  54. type peerError struct {
  55. err error
  56. peerID p2p.NodeID
  57. }
  58. func (e peerError) Error() string {
  59. return fmt.Sprintf("error with peer %v: %s", e.peerID, e.err.Error())
  60. }
  61. // BlockchainReactor handles long-term catchup syncing.
  62. type Reactor struct {
  63. service.BaseService
  64. // immutable
  65. initialState sm.State
  66. blockExec *sm.BlockExecutor
  67. store *store.BlockStore
  68. pool *BlockPool
  69. consReactor consensusReactor
  70. fastSync bool
  71. blockchainCh *p2p.Channel
  72. peerUpdates *p2p.PeerUpdates
  73. closeCh chan struct{}
  74. requestsCh <-chan BlockRequest
  75. errorsCh <-chan peerError
  76. // poolWG is used to synchronize the graceful shutdown of the poolRoutine and
  77. // requestRoutine spawned goroutines when stopping the reactor and before
  78. // stopping the p2p Channel(s).
  79. poolWG sync.WaitGroup
  80. }
  81. // NewReactor returns new reactor instance.
  82. func NewReactor(
  83. logger log.Logger,
  84. state sm.State,
  85. blockExec *sm.BlockExecutor,
  86. store *store.BlockStore,
  87. consReactor consensusReactor,
  88. blockchainCh *p2p.Channel,
  89. peerUpdates *p2p.PeerUpdates,
  90. fastSync bool,
  91. ) (*Reactor, error) {
  92. if state.LastBlockHeight != store.Height() {
  93. return nil, fmt.Errorf("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height())
  94. }
  95. startHeight := store.Height() + 1
  96. if startHeight == 1 {
  97. startHeight = state.InitialHeight
  98. }
  99. requestsCh := make(chan BlockRequest, maxTotalRequesters)
  100. errorsCh := make(chan peerError, maxPeerErrBuffer) // NOTE: The capacity should be larger than the peer count.
  101. r := &Reactor{
  102. initialState: state,
  103. blockExec: blockExec,
  104. store: store,
  105. pool: NewBlockPool(startHeight, requestsCh, errorsCh),
  106. consReactor: consReactor,
  107. fastSync: fastSync,
  108. requestsCh: requestsCh,
  109. errorsCh: errorsCh,
  110. blockchainCh: blockchainCh,
  111. peerUpdates: peerUpdates,
  112. closeCh: make(chan struct{}),
  113. }
  114. r.BaseService = *service.NewBaseService(logger, "Blockchain", r)
  115. return r, nil
  116. }
  117. // OnStart starts separate go routines for each p2p Channel and listens for
  118. // envelopes on each. In addition, it also listens for peer updates and handles
  119. // messages on that p2p channel accordingly. The caller must be sure to execute
  120. // OnStop to ensure the outbound p2p Channels are closed.
  121. //
  122. // If fastSync is enabled, we also start the pool and the pool processing
  123. // goroutine. If the pool fails to start, an error is returned.
  124. func (r *Reactor) OnStart() error {
  125. if r.fastSync {
  126. if err := r.pool.Start(); err != nil {
  127. return err
  128. }
  129. r.poolWG.Add(1)
  130. go r.poolRoutine(false)
  131. }
  132. go r.processBlockchainCh()
  133. go r.processPeerUpdates()
  134. return nil
  135. }
  136. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  137. // blocking until they all exit.
  138. func (r *Reactor) OnStop() {
  139. if r.fastSync {
  140. if err := r.pool.Stop(); err != nil {
  141. r.Logger.Error("failed to stop pool", "err", err)
  142. }
  143. }
  144. // wait for the poolRoutine and requestRoutine goroutines to gracefully exit
  145. r.poolWG.Wait()
  146. // Close closeCh to signal to all spawned goroutines to gracefully exit. All
  147. // p2p Channels should execute Close().
  148. close(r.closeCh)
  149. // Wait for all p2p Channels to be closed before returning. This ensures we
  150. // can easily reason about synchronization of all p2p Channels and ensure no
  151. // panics will occur.
  152. <-r.blockchainCh.Done()
  153. <-r.peerUpdates.Done()
  154. }
  155. // respondToPeer loads a block and sends it to the requesting peer, if we have it.
  156. // Otherwise, we'll respond saying we do not have it.
  157. func (r *Reactor) respondToPeer(msg *bcproto.BlockRequest, peerID p2p.NodeID) {
  158. block := r.store.LoadBlock(msg.Height)
  159. if block != nil {
  160. blockProto, err := block.ToProto()
  161. if err != nil {
  162. r.Logger.Error("failed to convert msg to protobuf", "err", err)
  163. return
  164. }
  165. r.blockchainCh.Out <- p2p.Envelope{
  166. To: peerID,
  167. Message: &bcproto.BlockResponse{Block: blockProto},
  168. }
  169. return
  170. }
  171. r.Logger.Info("peer requesting a block we do not have", "peer", peerID, "height", msg.Height)
  172. r.blockchainCh.Out <- p2p.Envelope{
  173. To: peerID,
  174. Message: &bcproto.NoBlockResponse{Height: msg.Height},
  175. }
  176. }
  177. // handleBlockchainMessage handles envelopes sent from peers on the
  178. // BlockchainChannel. It returns an error only if the Envelope.Message is unknown
  179. // for this channel. This should never be called outside of handleMessage.
  180. func (r *Reactor) handleBlockchainMessage(envelope p2p.Envelope) error {
  181. logger := r.Logger.With("peer", envelope.From)
  182. switch msg := envelope.Message.(type) {
  183. case *bcproto.BlockRequest:
  184. r.respondToPeer(msg, envelope.From)
  185. case *bcproto.BlockResponse:
  186. block, err := types.BlockFromProto(msg.Block)
  187. if err != nil {
  188. logger.Error("failed to convert block from proto", "err", err)
  189. return err
  190. }
  191. r.pool.AddBlock(envelope.From, block, block.Size())
  192. case *bcproto.StatusRequest:
  193. r.blockchainCh.Out <- p2p.Envelope{
  194. To: envelope.From,
  195. Message: &bcproto.StatusResponse{
  196. Height: r.store.Height(),
  197. Base: r.store.Base(),
  198. },
  199. }
  200. case *bcproto.StatusResponse:
  201. r.pool.SetPeerRange(envelope.From, msg.Base, msg.Height)
  202. case *bcproto.NoBlockResponse:
  203. logger.Debug("peer does not have the requested block", "height", msg.Height)
  204. default:
  205. return fmt.Errorf("received unknown message: %T", msg)
  206. }
  207. return nil
  208. }
  209. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  210. // It will handle errors and any possible panics gracefully. A caller can handle
  211. // any error returned by sending a PeerError on the respective channel.
  212. func (r *Reactor) handleMessage(chID p2p.ChannelID, envelope p2p.Envelope) (err error) {
  213. defer func() {
  214. if e := recover(); e != nil {
  215. err = fmt.Errorf("panic in processing message: %v", e)
  216. r.Logger.Error("recovering from processing message panic", "err", err)
  217. }
  218. }()
  219. r.Logger.Debug("received message", "message", envelope.Message, "peer", envelope.From)
  220. switch chID {
  221. case BlockchainChannel:
  222. err = r.handleBlockchainMessage(envelope)
  223. default:
  224. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  225. }
  226. return err
  227. }
  228. // processBlockchainCh initiates a blocking process where we listen for and handle
  229. // envelopes on the BlockchainChannel. Any error encountered during message
  230. // execution will result in a PeerError being sent on the BlockchainChannel. When
  231. // the reactor is stopped, we will catch the signal and close the p2p Channel
  232. // gracefully.
  233. func (r *Reactor) processBlockchainCh() {
  234. defer r.blockchainCh.Close()
  235. for {
  236. select {
  237. case envelope := <-r.blockchainCh.In:
  238. if err := r.handleMessage(r.blockchainCh.ID, envelope); err != nil {
  239. r.Logger.Error("failed to process message", "ch_id", r.blockchainCh.ID, "envelope", envelope, "err", err)
  240. r.blockchainCh.Error <- p2p.PeerError{
  241. NodeID: envelope.From,
  242. Err: err,
  243. }
  244. }
  245. case <-r.closeCh:
  246. r.Logger.Debug("stopped listening on blockchain channel; closing...")
  247. return
  248. }
  249. }
  250. }
  251. // processPeerUpdate processes a PeerUpdate.
  252. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  253. r.Logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  254. // XXX: Pool#RedoRequest can sometimes give us an empty peer.
  255. if len(peerUpdate.NodeID) == 0 {
  256. return
  257. }
  258. switch peerUpdate.Status {
  259. case p2p.PeerStatusUp:
  260. // send a status update the newly added peer
  261. r.blockchainCh.Out <- p2p.Envelope{
  262. To: peerUpdate.NodeID,
  263. Message: &bcproto.StatusResponse{
  264. Base: r.store.Base(),
  265. Height: r.store.Height(),
  266. },
  267. }
  268. case p2p.PeerStatusDown:
  269. r.pool.RemovePeer(peerUpdate.NodeID)
  270. }
  271. }
  272. // processPeerUpdates initiates a blocking process where we listen for and handle
  273. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  274. // close the p2p PeerUpdatesCh gracefully.
  275. func (r *Reactor) processPeerUpdates() {
  276. defer r.peerUpdates.Close()
  277. for {
  278. select {
  279. case peerUpdate := <-r.peerUpdates.Updates():
  280. r.processPeerUpdate(peerUpdate)
  281. case <-r.closeCh:
  282. r.Logger.Debug("stopped listening on peer updates channel; closing...")
  283. return
  284. }
  285. }
  286. }
  287. // SwitchToFastSync is called by the state sync reactor when switching to fast
  288. // sync.
  289. func (r *Reactor) SwitchToFastSync(state sm.State) error {
  290. r.fastSync = true
  291. r.initialState = state
  292. r.pool.height = state.LastBlockHeight + 1
  293. if err := r.pool.Start(); err != nil {
  294. return err
  295. }
  296. r.poolWG.Add(1)
  297. go r.poolRoutine(true)
  298. return nil
  299. }
  300. func (r *Reactor) requestRoutine() {
  301. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  302. defer statusUpdateTicker.Stop()
  303. r.poolWG.Add(1)
  304. defer r.poolWG.Done()
  305. for {
  306. select {
  307. case <-r.closeCh:
  308. return
  309. case <-r.pool.Quit():
  310. return
  311. case request := <-r.requestsCh:
  312. r.blockchainCh.Out <- p2p.Envelope{
  313. To: request.PeerID,
  314. Message: &bcproto.BlockRequest{Height: request.Height},
  315. }
  316. case pErr := <-r.errorsCh:
  317. r.blockchainCh.Error <- p2p.PeerError{
  318. NodeID: pErr.peerID,
  319. Err: pErr.err,
  320. }
  321. case <-statusUpdateTicker.C:
  322. r.poolWG.Add(1)
  323. go func() {
  324. defer r.poolWG.Done()
  325. r.blockchainCh.Out <- p2p.Envelope{
  326. Broadcast: true,
  327. Message: &bcproto.StatusRequest{},
  328. }
  329. }()
  330. }
  331. }
  332. }
  333. // poolRoutine handles messages from the poolReactor telling the reactor what to
  334. // do.
  335. //
  336. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  337. func (r *Reactor) poolRoutine(stateSynced bool) {
  338. var (
  339. trySyncTicker = time.NewTicker(trySyncIntervalMS * time.Millisecond)
  340. switchToConsensusTicker = time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  341. blocksSynced = uint64(0)
  342. chainID = r.initialState.ChainID
  343. state = r.initialState
  344. lastHundred = time.Now()
  345. lastRate = 0.0
  346. didProcessCh = make(chan struct{}, 1)
  347. )
  348. defer trySyncTicker.Stop()
  349. defer switchToConsensusTicker.Stop()
  350. go r.requestRoutine()
  351. defer r.poolWG.Done()
  352. FOR_LOOP:
  353. for {
  354. select {
  355. case <-switchToConsensusTicker.C:
  356. var (
  357. height, numPending, lenRequesters = r.pool.GetStatus()
  358. lastAdvance = r.pool.LastAdvance()
  359. )
  360. r.Logger.Debug(
  361. "consensus ticker",
  362. "num_pending", numPending,
  363. "total", lenRequesters,
  364. "height", height,
  365. )
  366. switch {
  367. case r.pool.IsCaughtUp():
  368. r.Logger.Info("switching to consensus reactor", "height", height)
  369. case time.Since(lastAdvance) > syncTimeout:
  370. r.Logger.Error("no progress since last advance", "last_advance", lastAdvance)
  371. default:
  372. r.Logger.Info(
  373. "not caught up yet",
  374. "height", height,
  375. "max_peer_height", r.pool.MaxPeerHeight(),
  376. "timeout_in", syncTimeout-time.Since(lastAdvance),
  377. )
  378. continue
  379. }
  380. if err := r.pool.Stop(); err != nil {
  381. r.Logger.Error("failed to stop pool", "err", err)
  382. }
  383. if r.consReactor != nil {
  384. r.consReactor.SwitchToConsensus(state, blocksSynced > 0 || stateSynced)
  385. }
  386. break FOR_LOOP
  387. case <-trySyncTicker.C:
  388. select {
  389. case didProcessCh <- struct{}{}:
  390. default:
  391. }
  392. case <-didProcessCh:
  393. // NOTE: It is a subtle mistake to process more than a single block at a
  394. // time (e.g. 10) here, because we only send one BlockRequest per loop
  395. // iteration. The ratio mismatch can result in starving of blocks, i.e. a
  396. // sudden burst of requests and responses, and repeat. Consequently, it is
  397. // better to split these routines rather than coupling them as it is
  398. // written here.
  399. //
  400. // TODO: Uncouple from request routine.
  401. // see if there are any blocks to sync
  402. first, second := r.pool.PeekTwoBlocks()
  403. if first == nil || second == nil {
  404. // we need both to sync the first block
  405. continue FOR_LOOP
  406. } else {
  407. // try again quickly next loop
  408. didProcessCh <- struct{}{}
  409. }
  410. var (
  411. firstParts = first.MakePartSet(types.BlockPartSizeBytes)
  412. firstPartSetHeader = firstParts.Header()
  413. firstID = types.BlockID{Hash: first.Hash(), PartSetHeader: firstPartSetHeader}
  414. )
  415. // Finally, verify the first block using the second's commit.
  416. //
  417. // NOTE: We can probably make this more efficient, but note that calling
  418. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  419. // currently necessary.
  420. err := state.Validators.VerifyCommitLight(chainID, firstID, first.Height, second.LastCommit)
  421. if err != nil {
  422. err = fmt.Errorf("invalid last commit: %w", err)
  423. r.Logger.Error(
  424. err.Error(),
  425. "last_commit", second.LastCommit,
  426. "block_id", firstID,
  427. "height", first.Height,
  428. )
  429. // NOTE: We've already removed the peer's request, but we still need
  430. // to clean up the rest.
  431. peerID := r.pool.RedoRequest(first.Height)
  432. r.blockchainCh.Error <- p2p.PeerError{
  433. NodeID: peerID,
  434. Err: err,
  435. }
  436. peerID2 := r.pool.RedoRequest(second.Height)
  437. if peerID2 != peerID {
  438. r.blockchainCh.Error <- p2p.PeerError{
  439. NodeID: peerID2,
  440. Err: err,
  441. }
  442. }
  443. continue FOR_LOOP
  444. } else {
  445. r.pool.PopRequest()
  446. // TODO: batch saves so we do not persist to disk every block
  447. r.store.SaveBlock(first, firstParts, second.LastCommit)
  448. var err error
  449. // TODO: Same thing for app - but we would need a way to get the hash
  450. // without persisting the state.
  451. state, _, err = r.blockExec.ApplyBlock(state, firstID, first)
  452. if err != nil {
  453. // TODO: This is bad, are we zombie?
  454. panic(fmt.Sprintf("failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  455. }
  456. blocksSynced++
  457. if blocksSynced%100 == 0 {
  458. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  459. r.Logger.Info(
  460. "fast sync rate",
  461. "height", r.pool.height,
  462. "max_peer_height", r.pool.MaxPeerHeight(),
  463. "blocks/s", lastRate,
  464. )
  465. lastHundred = time.Now()
  466. }
  467. }
  468. continue FOR_LOOP
  469. case <-r.closeCh:
  470. break FOR_LOOP
  471. }
  472. }
  473. }