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
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. go r.poolRoutine(false)
  129. }
  130. go r.processBlockchainCh()
  131. go r.processPeerUpdates()
  132. return nil
  133. }
  134. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  135. // blocking until they all exit.
  136. func (r *Reactor) OnStop() {
  137. if r.fastSync {
  138. if err := r.pool.Stop(); err != nil {
  139. r.Logger.Error("failed to stop pool", "err", err)
  140. }
  141. }
  142. // wait for the poolRoutine and requestRoutine goroutines to gracefully exit
  143. r.poolWG.Wait()
  144. // Close closeCh to signal to all spawned goroutines to gracefully exit. All
  145. // p2p Channels should execute Close().
  146. close(r.closeCh)
  147. // Wait for all p2p Channels to be closed before returning. This ensures we
  148. // can easily reason about synchronization of all p2p Channels and ensure no
  149. // panics will occur.
  150. <-r.blockchainCh.Done()
  151. <-r.peerUpdates.Done()
  152. }
  153. // respondToPeer loads a block and sends it to the requesting peer, if we have it.
  154. // Otherwise, we'll respond saying we do not have it.
  155. func (r *Reactor) respondToPeer(msg *bcproto.BlockRequest, peerID p2p.NodeID) {
  156. block := r.store.LoadBlock(msg.Height)
  157. if block != nil {
  158. blockProto, err := block.ToProto()
  159. if err != nil {
  160. r.Logger.Error("failed to convert msg to protobuf", "err", err)
  161. return
  162. }
  163. r.blockchainCh.Out() <- p2p.Envelope{
  164. To: peerID,
  165. Message: &bcproto.BlockResponse{Block: blockProto},
  166. }
  167. return
  168. }
  169. r.Logger.Info("peer requesting a block we do not have", "peer", peerID, "height", msg.Height)
  170. r.blockchainCh.Out() <- p2p.Envelope{
  171. To: peerID,
  172. Message: &bcproto.NoBlockResponse{Height: msg.Height},
  173. }
  174. }
  175. // handleBlockchainMessage handles envelopes sent from peers on the
  176. // BlockchainChannel. It returns an error only if the Envelope.Message is unknown
  177. // for this channel. This should never be called outside of handleMessage.
  178. func (r *Reactor) handleBlockchainMessage(envelope p2p.Envelope) error {
  179. logger := r.Logger.With("peer", envelope.From)
  180. switch msg := envelope.Message.(type) {
  181. case *bcproto.BlockRequest:
  182. r.respondToPeer(msg, envelope.From)
  183. case *bcproto.BlockResponse:
  184. block, err := types.BlockFromProto(msg.Block)
  185. if err != nil {
  186. logger.Error("failed to convert block from proto", "err", err)
  187. return err
  188. }
  189. r.pool.AddBlock(envelope.From, block, block.Size())
  190. case *bcproto.StatusRequest:
  191. r.blockchainCh.Out() <- p2p.Envelope{
  192. To: envelope.From,
  193. Message: &bcproto.StatusResponse{
  194. Height: r.store.Height(),
  195. Base: r.store.Base(),
  196. },
  197. }
  198. case *bcproto.StatusResponse:
  199. r.pool.SetPeerRange(envelope.From, msg.Base, msg.Height)
  200. case *bcproto.NoBlockResponse:
  201. logger.Debug("peer does not have the requested block", "height", msg.Height)
  202. default:
  203. return fmt.Errorf("received unknown message: %T", msg)
  204. }
  205. return nil
  206. }
  207. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  208. // It will handle errors and any possible panics gracefully. A caller can handle
  209. // any error returned by sending a PeerError on the respective channel.
  210. func (r *Reactor) handleMessage(chID p2p.ChannelID, envelope p2p.Envelope) (err error) {
  211. defer func() {
  212. if e := recover(); e != nil {
  213. err = fmt.Errorf("panic in processing message: %v", e)
  214. r.Logger.Error("recovering from processing message panic", "err", err)
  215. }
  216. }()
  217. r.Logger.Debug("received message", "message", envelope.Message, "peer", envelope.From)
  218. switch chID {
  219. case BlockchainChannel:
  220. err = r.handleBlockchainMessage(envelope)
  221. default:
  222. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  223. }
  224. return err
  225. }
  226. // processBlockchainCh initiates a blocking process where we listen for and handle
  227. // envelopes on the BlockchainChannel. Any error encountered during message
  228. // execution will result in a PeerError being sent on the BlockchainChannel. When
  229. // the reactor is stopped, we will catch the signal and close the p2p Channel
  230. // gracefully.
  231. func (r *Reactor) processBlockchainCh() {
  232. defer r.blockchainCh.Close()
  233. for {
  234. select {
  235. case envelope := <-r.blockchainCh.In():
  236. if err := r.handleMessage(r.blockchainCh.ID(), envelope); err != nil {
  237. r.Logger.Error("failed to process message", "ch_id", r.blockchainCh.ID(), "envelope", envelope, "err", err)
  238. r.blockchainCh.Error() <- p2p.PeerError{
  239. PeerID: envelope.From,
  240. Err: err,
  241. Severity: p2p.PeerErrorSeverityLow,
  242. }
  243. }
  244. case <-r.closeCh:
  245. r.Logger.Debug("stopped listening on blockchain channel; closing...")
  246. return
  247. }
  248. }
  249. }
  250. // processPeerUpdate processes a PeerUpdate.
  251. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  252. r.Logger.Debug("received peer update", "peer", peerUpdate.PeerID, "status", peerUpdate.Status)
  253. // XXX: Pool#RedoRequest can sometimes give us an empty peer.
  254. if len(peerUpdate.PeerID) == 0 {
  255. return
  256. }
  257. switch peerUpdate.Status {
  258. case p2p.PeerStatusNew, p2p.PeerStatusUp:
  259. // send a status update the newly added peer
  260. r.blockchainCh.Out() <- p2p.Envelope{
  261. To: peerUpdate.PeerID,
  262. Message: &bcproto.StatusResponse{
  263. Base: r.store.Base(),
  264. Height: r.store.Height(),
  265. },
  266. }
  267. case p2p.PeerStatusDown, p2p.PeerStatusRemoved, p2p.PeerStatusBanned:
  268. r.pool.RemovePeer(peerUpdate.PeerID)
  269. }
  270. }
  271. // processPeerUpdates initiates a blocking process where we listen for and handle
  272. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  273. // close the p2p PeerUpdatesCh gracefully.
  274. func (r *Reactor) processPeerUpdates() {
  275. defer r.peerUpdates.Close()
  276. for {
  277. select {
  278. case peerUpdate := <-r.peerUpdates.Updates():
  279. r.processPeerUpdate(peerUpdate)
  280. case <-r.closeCh:
  281. r.Logger.Debug("stopped listening on peer updates channel; closing...")
  282. return
  283. }
  284. }
  285. }
  286. // SwitchToFastSync is called by the state sync reactor when switching to fast
  287. // sync.
  288. func (r *Reactor) SwitchToFastSync(state sm.State) error {
  289. r.fastSync = true
  290. r.initialState = state
  291. r.pool.height = state.LastBlockHeight + 1
  292. if err := r.pool.Start(); err != nil {
  293. return err
  294. }
  295. go r.poolRoutine(true)
  296. return nil
  297. }
  298. func (r *Reactor) requestRoutine() {
  299. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  300. defer statusUpdateTicker.Stop()
  301. r.poolWG.Add(1)
  302. defer r.poolWG.Done()
  303. for {
  304. select {
  305. case <-r.closeCh:
  306. return
  307. case <-r.pool.Quit():
  308. return
  309. case request := <-r.requestsCh:
  310. r.blockchainCh.Out() <- p2p.Envelope{
  311. To: request.PeerID,
  312. Message: &bcproto.BlockRequest{Height: request.Height},
  313. }
  314. case pErr := <-r.errorsCh:
  315. r.blockchainCh.Error() <- p2p.PeerError{
  316. PeerID: pErr.peerID,
  317. Err: pErr.err,
  318. Severity: p2p.PeerErrorSeverityLow,
  319. }
  320. case <-statusUpdateTicker.C:
  321. r.poolWG.Add(1)
  322. go func() {
  323. defer r.poolWG.Done()
  324. r.blockchainCh.Out() <- p2p.Envelope{
  325. Broadcast: true,
  326. Message: &bcproto.StatusRequest{},
  327. }
  328. }()
  329. }
  330. }
  331. }
  332. // poolRoutine handles messages from the poolReactor telling the reactor what to
  333. // do.
  334. //
  335. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  336. func (r *Reactor) poolRoutine(stateSynced bool) {
  337. var (
  338. trySyncTicker = time.NewTicker(trySyncIntervalMS * time.Millisecond)
  339. switchToConsensusTicker = time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  340. blocksSynced = uint64(0)
  341. chainID = r.initialState.ChainID
  342. state = r.initialState
  343. lastHundred = time.Now()
  344. lastRate = 0.0
  345. didProcessCh = make(chan struct{}, 1)
  346. )
  347. defer trySyncTicker.Stop()
  348. defer switchToConsensusTicker.Stop()
  349. go r.requestRoutine()
  350. r.poolWG.Add(1)
  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. PeerID: peerID,
  434. Err: err,
  435. Severity: p2p.PeerErrorSeverityLow,
  436. }
  437. peerID2 := r.pool.RedoRequest(second.Height)
  438. if peerID2 != peerID {
  439. r.blockchainCh.Error() <- p2p.PeerError{
  440. PeerID: peerID2,
  441. Err: err,
  442. Severity: p2p.PeerErrorSeverityLow,
  443. }
  444. }
  445. continue FOR_LOOP
  446. } else {
  447. r.pool.PopRequest()
  448. // TODO: batch saves so we do not persist to disk every block
  449. r.store.SaveBlock(first, firstParts, second.LastCommit)
  450. var err error
  451. // TODO: Same thing for app - but we would need a way to get the hash
  452. // without persisting the state.
  453. state, _, err = r.blockExec.ApplyBlock(state, firstID, first)
  454. if err != nil {
  455. // TODO: This is bad, are we zombie?
  456. panic(fmt.Sprintf("failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  457. }
  458. blocksSynced++
  459. if blocksSynced%100 == 0 {
  460. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  461. r.Logger.Info(
  462. "fast sync rate",
  463. "height", r.pool.height,
  464. "max_peer_height", r.pool.MaxPeerHeight(),
  465. "blocks/s", lastRate,
  466. )
  467. lastHundred = time.Now()
  468. }
  469. }
  470. continue FOR_LOOP
  471. case <-r.closeCh:
  472. break FOR_LOOP
  473. }
  474. }
  475. }