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.

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