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.

576 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
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/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.PeerUpdates
  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.PeerUpdates,
  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. NodeID: envelope.From,
  241. Err: err,
  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.NodeID, "status", peerUpdate.Status)
  253. // XXX: Pool#RedoRequest can sometimes give us an empty peer.
  254. if len(peerUpdate.NodeID) == 0 {
  255. return
  256. }
  257. switch peerUpdate.Status {
  258. case p2p.PeerStatusUp:
  259. // send a status update the newly added peer
  260. r.blockchainCh.Out <- p2p.Envelope{
  261. To: peerUpdate.NodeID,
  262. Message: &bcproto.StatusResponse{
  263. Base: r.store.Base(),
  264. Height: r.store.Height(),
  265. },
  266. }
  267. case p2p.PeerStatusDown:
  268. r.pool.RemovePeer(peerUpdate.NodeID)
  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. r.poolWG.Add(1)
  296. go r.poolRoutine(true)
  297. return nil
  298. }
  299. func (r *Reactor) requestRoutine() {
  300. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  301. defer statusUpdateTicker.Stop()
  302. r.poolWG.Add(1)
  303. defer r.poolWG.Done()
  304. for {
  305. select {
  306. case <-r.closeCh:
  307. return
  308. case <-r.pool.Quit():
  309. return
  310. case request := <-r.requestsCh:
  311. r.blockchainCh.Out <- p2p.Envelope{
  312. To: request.PeerID,
  313. Message: &bcproto.BlockRequest{Height: request.Height},
  314. }
  315. case pErr := <-r.errorsCh:
  316. r.blockchainCh.Error <- p2p.PeerError{
  317. NodeID: pErr.peerID,
  318. Err: pErr.err,
  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. defer r.poolWG.Done()
  351. FOR_LOOP:
  352. for {
  353. select {
  354. case <-switchToConsensusTicker.C:
  355. var (
  356. height, numPending, lenRequesters = r.pool.GetStatus()
  357. lastAdvance = r.pool.LastAdvance()
  358. )
  359. r.Logger.Debug(
  360. "consensus ticker",
  361. "num_pending", numPending,
  362. "total", lenRequesters,
  363. "height", height,
  364. )
  365. switch {
  366. case r.pool.IsCaughtUp():
  367. r.Logger.Info("switching to consensus reactor", "height", height)
  368. case time.Since(lastAdvance) > syncTimeout:
  369. r.Logger.Error("no progress since last advance", "last_advance", lastAdvance)
  370. default:
  371. r.Logger.Info(
  372. "not caught up yet",
  373. "height", height,
  374. "max_peer_height", r.pool.MaxPeerHeight(),
  375. "timeout_in", syncTimeout-time.Since(lastAdvance),
  376. )
  377. continue
  378. }
  379. if err := r.pool.Stop(); err != nil {
  380. r.Logger.Error("failed to stop pool", "err", err)
  381. }
  382. if r.consReactor != nil {
  383. r.consReactor.SwitchToConsensus(state, blocksSynced > 0 || stateSynced)
  384. }
  385. break FOR_LOOP
  386. case <-trySyncTicker.C:
  387. select {
  388. case didProcessCh <- struct{}{}:
  389. default:
  390. }
  391. case <-didProcessCh:
  392. // NOTE: It is a subtle mistake to process more than a single block at a
  393. // time (e.g. 10) here, because we only send one BlockRequest per loop
  394. // iteration. The ratio mismatch can result in starving of blocks, i.e. a
  395. // sudden burst of requests and responses, and repeat. Consequently, it is
  396. // better to split these routines rather than coupling them as it is
  397. // written here.
  398. //
  399. // TODO: Uncouple from request routine.
  400. // see if there are any blocks to sync
  401. first, second := r.pool.PeekTwoBlocks()
  402. if first == nil || second == nil {
  403. // we need both to sync the first block
  404. continue FOR_LOOP
  405. } else {
  406. // try again quickly next loop
  407. didProcessCh <- struct{}{}
  408. }
  409. var (
  410. firstParts = first.MakePartSet(types.BlockPartSizeBytes)
  411. firstPartSetHeader = firstParts.Header()
  412. firstID = types.BlockID{Hash: first.Hash(), PartSetHeader: firstPartSetHeader}
  413. )
  414. // Finally, verify the first block using the second's commit.
  415. //
  416. // NOTE: We can probably make this more efficient, but note that calling
  417. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  418. // currently necessary.
  419. err := state.Validators.VerifyCommitLight(chainID, firstID, first.Height, second.LastCommit)
  420. if err != nil {
  421. err = fmt.Errorf("invalid last commit: %w", err)
  422. r.Logger.Error(
  423. err.Error(),
  424. "last_commit", second.LastCommit,
  425. "block_id", firstID,
  426. "height", first.Height,
  427. )
  428. // NOTE: We've already removed the peer's request, but we still need
  429. // to clean up the rest.
  430. peerID := r.pool.RedoRequest(first.Height)
  431. r.blockchainCh.Error <- p2p.PeerError{
  432. NodeID: peerID,
  433. Err: err,
  434. }
  435. peerID2 := r.pool.RedoRequest(second.Height)
  436. if peerID2 != peerID {
  437. r.blockchainCh.Error <- p2p.PeerError{
  438. NodeID: peerID2,
  439. Err: err,
  440. }
  441. }
  442. continue FOR_LOOP
  443. } else {
  444. r.pool.PopRequest()
  445. // TODO: batch saves so we do not persist to disk every block
  446. r.store.SaveBlock(first, firstParts, second.LastCommit)
  447. var err error
  448. // TODO: Same thing for app - but we would need a way to get the hash
  449. // without persisting the state.
  450. state, _, err = r.blockExec.ApplyBlock(state, firstID, first)
  451. if err != nil {
  452. // TODO: This is bad, are we zombie?
  453. panic(fmt.Sprintf("failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  454. }
  455. blocksSynced++
  456. if blocksSynced%100 == 0 {
  457. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  458. r.Logger.Info(
  459. "fast sync rate",
  460. "height", r.pool.height,
  461. "max_peer_height", r.pool.MaxPeerHeight(),
  462. "blocks/s", lastRate,
  463. )
  464. lastHundred = time.Now()
  465. }
  466. }
  467. continue FOR_LOOP
  468. case <-r.closeCh:
  469. break FOR_LOOP
  470. }
  471. }
  472. }