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.

580 lines
16 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/blockchain"
  7. "github.com/tendermint/tendermint/libs/log"
  8. "github.com/tendermint/tendermint/libs/service"
  9. "github.com/tendermint/tendermint/p2p"
  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. },
  34. },
  35. }
  36. )
  37. const (
  38. // BlockchainChannel is a channel for blocks and status updates
  39. BlockchainChannel = p2p.ChannelID(0x40)
  40. trySyncIntervalMS = 10
  41. // ask for best height every 10s
  42. statusUpdateIntervalSeconds = 10
  43. // check if we should switch to consensus reactor
  44. switchToConsensusIntervalSeconds = 1
  45. // switch to consensus after this duration of inactivity
  46. syncTimeout = 60 * time.Second
  47. )
  48. type consensusReactor interface {
  49. // For when we switch from blockchain reactor and fast sync to the consensus
  50. // machine.
  51. SwitchToConsensus(state sm.State, skipWAL bool)
  52. }
  53. type peerError struct {
  54. err error
  55. peerID p2p.NodeID
  56. }
  57. func (e peerError) Error() string {
  58. return fmt.Sprintf("error with peer %v: %s", e.peerID, e.err.Error())
  59. }
  60. // BlockchainReactor handles long-term catchup syncing.
  61. type Reactor struct {
  62. service.BaseService
  63. // immutable
  64. initialState sm.State
  65. blockExec *sm.BlockExecutor
  66. store *store.BlockStore
  67. pool *BlockPool
  68. consReactor consensusReactor
  69. fastSync bool
  70. blockchainCh *p2p.Channel
  71. peerUpdates *p2p.PeerUpdatesCh
  72. closeCh chan struct{}
  73. requestsCh <-chan BlockRequest
  74. errorsCh <-chan peerError
  75. // poolWG is used to synchronize the graceful shutdown of the poolRoutine and
  76. // requestRoutine spawned goroutines when stopping the reactor and before
  77. // stopping the p2p Channel(s).
  78. poolWG sync.WaitGroup
  79. }
  80. // NewReactor returns new reactor instance.
  81. func NewReactor(
  82. logger log.Logger,
  83. state sm.State,
  84. blockExec *sm.BlockExecutor,
  85. store *store.BlockStore,
  86. consReactor consensusReactor,
  87. blockchainCh *p2p.Channel,
  88. peerUpdates *p2p.PeerUpdatesCh,
  89. fastSync bool,
  90. ) (*Reactor, error) {
  91. if state.LastBlockHeight != store.Height() {
  92. return nil, fmt.Errorf("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height())
  93. }
  94. startHeight := store.Height() + 1
  95. if startHeight == 1 {
  96. startHeight = state.InitialHeight
  97. }
  98. requestsCh := make(chan BlockRequest, maxTotalRequesters)
  99. errorsCh := make(chan peerError, maxPeerErrBuffer) // NOTE: The capacity should be larger than the peer count.
  100. r := &Reactor{
  101. initialState: state,
  102. blockExec: blockExec,
  103. store: store,
  104. pool: NewBlockPool(startHeight, requestsCh, errorsCh),
  105. consReactor: consReactor,
  106. fastSync: fastSync,
  107. requestsCh: requestsCh,
  108. errorsCh: errorsCh,
  109. blockchainCh: blockchainCh,
  110. peerUpdates: peerUpdates,
  111. closeCh: make(chan struct{}),
  112. }
  113. r.BaseService = *service.NewBaseService(logger, "Blockchain", r)
  114. return r, nil
  115. }
  116. // OnStart starts separate go routines for each p2p Channel and listens for
  117. // envelopes on each. In addition, it also listens for peer updates and handles
  118. // messages on that p2p channel accordingly. The caller must be sure to execute
  119. // OnStop to ensure the outbound p2p Channels are closed.
  120. //
  121. // If fastSync is enabled, we also start the pool and the pool processing
  122. // goroutine. If the pool fails to start, an error is returned.
  123. func (r *Reactor) OnStart() error {
  124. if r.fastSync {
  125. if err := r.pool.Start(); err != nil {
  126. return err
  127. }
  128. r.poolWG.Add(1)
  129. go r.poolRoutine(false)
  130. }
  131. go r.processBlockchainCh()
  132. go r.processPeerUpdates()
  133. return nil
  134. }
  135. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  136. // blocking until they all exit.
  137. func (r *Reactor) OnStop() {
  138. if r.fastSync {
  139. if err := r.pool.Stop(); err != nil {
  140. r.Logger.Error("failed to stop pool", "err", err)
  141. }
  142. }
  143. // wait for the poolRoutine and requestRoutine goroutines to gracefully exit
  144. r.poolWG.Wait()
  145. // Close closeCh to signal to all spawned goroutines to gracefully exit. All
  146. // p2p Channels should execute Close().
  147. close(r.closeCh)
  148. // Wait for all p2p Channels to be closed before returning. This ensures we
  149. // can easily reason about synchronization of all p2p Channels and ensure no
  150. // panics will occur.
  151. <-r.blockchainCh.Done()
  152. <-r.peerUpdates.Done()
  153. }
  154. // respondToPeer loads a block and sends it to the requesting peer, if we have it.
  155. // Otherwise, we'll respond saying we do not have it.
  156. func (r *Reactor) respondToPeer(msg *bcproto.BlockRequest, peerID p2p.NodeID) {
  157. block := r.store.LoadBlock(msg.Height)
  158. if block != nil {
  159. blockProto, err := block.ToProto()
  160. if err != nil {
  161. r.Logger.Error("failed to convert msg to protobuf", "err", err)
  162. return
  163. }
  164. r.blockchainCh.Out() <- p2p.Envelope{
  165. To: peerID,
  166. Message: &bcproto.BlockResponse{Block: blockProto},
  167. }
  168. return
  169. }
  170. r.Logger.Info("peer requesting a block we do not have", "peer", peerID, "height", msg.Height)
  171. r.blockchainCh.Out() <- p2p.Envelope{
  172. To: peerID,
  173. Message: &bcproto.NoBlockResponse{Height: msg.Height},
  174. }
  175. }
  176. // handleBlockchainMessage handles envelopes sent from peers on the
  177. // BlockchainChannel. It returns an error only if the Envelope.Message is unknown
  178. // for this channel. This should never be called outside of handleMessage.
  179. func (r *Reactor) handleBlockchainMessage(envelope p2p.Envelope) error {
  180. logger := r.Logger.With("peer", envelope.From)
  181. switch msg := envelope.Message.(type) {
  182. case *bcproto.BlockRequest:
  183. r.respondToPeer(msg, envelope.From)
  184. case *bcproto.BlockResponse:
  185. block, err := types.BlockFromProto(msg.Block)
  186. if err != nil {
  187. logger.Error("failed to convert block from proto", "err", err)
  188. return err
  189. }
  190. r.pool.AddBlock(envelope.From, block, block.Size())
  191. case *bcproto.StatusRequest:
  192. r.blockchainCh.Out() <- p2p.Envelope{
  193. To: envelope.From,
  194. Message: &bcproto.StatusResponse{
  195. Height: r.store.Height(),
  196. Base: r.store.Base(),
  197. },
  198. }
  199. case *bcproto.StatusResponse:
  200. r.pool.SetPeerRange(envelope.From, msg.Base, msg.Height)
  201. case *bcproto.NoBlockResponse:
  202. logger.Debug("peer does not have the requested block", "height", msg.Height)
  203. default:
  204. return fmt.Errorf("received unknown message: %T", msg)
  205. }
  206. return nil
  207. }
  208. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  209. // It will handle errors and any possible panics gracefully. A caller can handle
  210. // any error returned by sending a PeerError on the respective channel.
  211. func (r *Reactor) handleMessage(chID p2p.ChannelID, envelope p2p.Envelope) (err error) {
  212. defer func() {
  213. if e := recover(); e != nil {
  214. err = fmt.Errorf("panic in processing message: %v", e)
  215. r.Logger.Error("recovering from processing message panic", "err", err)
  216. }
  217. }()
  218. r.Logger.Debug("received message", "message", envelope.Message, "peer", envelope.From)
  219. switch chID {
  220. case BlockchainChannel:
  221. err = r.handleBlockchainMessage(envelope)
  222. default:
  223. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  224. }
  225. return err
  226. }
  227. // processBlockchainCh initiates a blocking process where we listen for and handle
  228. // envelopes on the BlockchainChannel. Any error encountered during message
  229. // execution will result in a PeerError being sent on the BlockchainChannel. When
  230. // the reactor is stopped, we will catch the signal and close the p2p Channel
  231. // gracefully.
  232. func (r *Reactor) processBlockchainCh() {
  233. defer r.blockchainCh.Close()
  234. for {
  235. select {
  236. case envelope := <-r.blockchainCh.In():
  237. if err := r.handleMessage(r.blockchainCh.ID(), envelope); err != nil {
  238. r.Logger.Error("failed to process message", "ch_id", r.blockchainCh.ID(), "envelope", envelope, "err", err)
  239. r.blockchainCh.Error() <- p2p.PeerError{
  240. PeerID: envelope.From,
  241. Err: err,
  242. Severity: p2p.PeerErrorSeverityLow,
  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.PeerID, "status", peerUpdate.Status)
  254. // XXX: Pool#RedoRequest can sometimes give us an empty peer.
  255. if len(peerUpdate.PeerID) == 0 {
  256. return
  257. }
  258. switch peerUpdate.Status {
  259. case p2p.PeerStatusNew, p2p.PeerStatusUp:
  260. // send a status update the newly added peer
  261. r.blockchainCh.Out() <- p2p.Envelope{
  262. To: peerUpdate.PeerID,
  263. Message: &bcproto.StatusResponse{
  264. Base: r.store.Base(),
  265. Height: r.store.Height(),
  266. },
  267. }
  268. case p2p.PeerStatusDown, p2p.PeerStatusRemoved, p2p.PeerStatusBanned:
  269. r.pool.RemovePeer(peerUpdate.PeerID)
  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. PeerID: pErr.peerID,
  319. Err: pErr.err,
  320. Severity: p2p.PeerErrorSeverityLow,
  321. }
  322. case <-statusUpdateTicker.C:
  323. r.poolWG.Add(1)
  324. go func() {
  325. defer r.poolWG.Done()
  326. r.blockchainCh.Out() <- p2p.Envelope{
  327. Broadcast: true,
  328. Message: &bcproto.StatusRequest{},
  329. }
  330. }()
  331. }
  332. }
  333. }
  334. // poolRoutine handles messages from the poolReactor telling the reactor what to
  335. // do.
  336. //
  337. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  338. func (r *Reactor) poolRoutine(stateSynced bool) {
  339. var (
  340. trySyncTicker = time.NewTicker(trySyncIntervalMS * time.Millisecond)
  341. switchToConsensusTicker = time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  342. blocksSynced = uint64(0)
  343. chainID = r.initialState.ChainID
  344. state = r.initialState
  345. lastHundred = time.Now()
  346. lastRate = 0.0
  347. didProcessCh = make(chan struct{}, 1)
  348. )
  349. defer trySyncTicker.Stop()
  350. defer switchToConsensusTicker.Stop()
  351. go r.requestRoutine()
  352. defer r.poolWG.Done()
  353. FOR_LOOP:
  354. for {
  355. select {
  356. case <-switchToConsensusTicker.C:
  357. var (
  358. height, numPending, lenRequesters = r.pool.GetStatus()
  359. lastAdvance = r.pool.LastAdvance()
  360. )
  361. r.Logger.Debug(
  362. "consensus ticker",
  363. "num_pending", numPending,
  364. "total", lenRequesters,
  365. "height", height,
  366. )
  367. switch {
  368. case r.pool.IsCaughtUp():
  369. r.Logger.Info("switching to consensus reactor", "height", height)
  370. case time.Since(lastAdvance) > syncTimeout:
  371. r.Logger.Error("no progress since last advance", "last_advance", lastAdvance)
  372. default:
  373. r.Logger.Info(
  374. "not caught up yet",
  375. "height", height,
  376. "max_peer_height", r.pool.MaxPeerHeight(),
  377. "timeout_in", syncTimeout-time.Since(lastAdvance),
  378. )
  379. continue
  380. }
  381. if err := r.pool.Stop(); err != nil {
  382. r.Logger.Error("failed to stop pool", "err", err)
  383. }
  384. if r.consReactor != nil {
  385. r.consReactor.SwitchToConsensus(state, blocksSynced > 0 || stateSynced)
  386. }
  387. break FOR_LOOP
  388. case <-trySyncTicker.C:
  389. select {
  390. case didProcessCh <- struct{}{}:
  391. default:
  392. }
  393. case <-didProcessCh:
  394. // NOTE: It is a subtle mistake to process more than a single block at a
  395. // time (e.g. 10) here, because we only send one BlockRequest per loop
  396. // iteration. The ratio mismatch can result in starving of blocks, i.e. a
  397. // sudden burst of requests and responses, and repeat. Consequently, it is
  398. // better to split these routines rather than coupling them as it is
  399. // written here.
  400. //
  401. // TODO: Uncouple from request routine.
  402. // see if there are any blocks to sync
  403. first, second := r.pool.PeekTwoBlocks()
  404. if first == nil || second == nil {
  405. // we need both to sync the first block
  406. continue FOR_LOOP
  407. } else {
  408. // try again quickly next loop
  409. didProcessCh <- struct{}{}
  410. }
  411. var (
  412. firstParts = first.MakePartSet(types.BlockPartSizeBytes)
  413. firstPartSetHeader = firstParts.Header()
  414. firstID = types.BlockID{Hash: first.Hash(), PartSetHeader: firstPartSetHeader}
  415. )
  416. // Finally, verify the first block using the second's commit.
  417. //
  418. // NOTE: We can probably make this more efficient, but note that calling
  419. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  420. // currently necessary.
  421. err := state.Validators.VerifyCommitLight(chainID, firstID, first.Height, second.LastCommit)
  422. if err != nil {
  423. err = fmt.Errorf("invalid last commit: %w", err)
  424. r.Logger.Error(
  425. err.Error(),
  426. "last_commit", second.LastCommit,
  427. "block_id", firstID,
  428. "height", first.Height,
  429. )
  430. // NOTE: We've already removed the peer's request, but we still need
  431. // to clean up the rest.
  432. peerID := r.pool.RedoRequest(first.Height)
  433. r.blockchainCh.Error() <- p2p.PeerError{
  434. PeerID: peerID,
  435. Err: err,
  436. Severity: p2p.PeerErrorSeverityLow,
  437. }
  438. peerID2 := r.pool.RedoRequest(second.Height)
  439. if peerID2 != peerID {
  440. r.blockchainCh.Error() <- p2p.PeerError{
  441. PeerID: peerID2,
  442. Err: err,
  443. Severity: p2p.PeerErrorSeverityLow,
  444. }
  445. }
  446. continue FOR_LOOP
  447. } else {
  448. r.pool.PopRequest()
  449. // TODO: batch saves so we do not persist to disk every block
  450. r.store.SaveBlock(first, firstParts, second.LastCommit)
  451. var err error
  452. // TODO: Same thing for app - but we would need a way to get the hash
  453. // without persisting the state.
  454. state, _, err = r.blockExec.ApplyBlock(state, firstID, first)
  455. if err != nil {
  456. // TODO: This is bad, are we zombie?
  457. panic(fmt.Sprintf("failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  458. }
  459. blocksSynced++
  460. if blocksSynced%100 == 0 {
  461. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  462. r.Logger.Info(
  463. "fast sync rate",
  464. "height", r.pool.height,
  465. "max_peer_height", r.pool.MaxPeerHeight(),
  466. "blocks/s", lastRate,
  467. )
  468. lastHundred = time.Now()
  469. }
  470. }
  471. continue FOR_LOOP
  472. case <-r.closeCh:
  473. break FOR_LOOP
  474. }
  475. }
  476. }