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.

646 lines
18 KiB

cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
blocksync: fix shutdown deadlock issue (#7030) When shutting down blocksync, it is observed that the process can hang completely. A dump of running goroutines reveals that this is due to goroutines not listening on the correct shutdown signal. Namely, the `poolRoutine` goroutine does not wait on `pool.Quit`. The `poolRoutine` does not receive any other shutdown signal during `OnStop` becuase it must stop before the `r.closeCh` is closed. Currently the `poolRoutine` listens in the `closeCh` which will not close until the `poolRoutine` stops and calls `poolWG.Done()`. This change also puts the `requestRoutine()` in the `OnStart` method to make it more visible since it does not rely on anything that is spawned in the `poolRoutine`. ``` goroutine 183 [semacquire]: sync.runtime_Semacquire(0xc0000d3bd8) runtime/sema.go:56 +0x45 sync.(*WaitGroup).Wait(0xc0000d3bd0) sync/waitgroup.go:130 +0x65 github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStop(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:193 +0x47 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0000d3a00, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc00052c000) github.com/tendermint/tendermint/node/node.go:758 +0xc62 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00052c000, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/cmd/tendermint/commands.NewRunNodeCmd.func1.1() github.com/tendermint/tendermint/cmd/tendermint/commands/run_node.go:143 +0x62 github.com/tendermint/tendermint/libs/os.TrapSignal.func1(0xc000df6d20, 0x7f04a68da900, 0xc0004a8930, 0xc0005a72d8) github.com/tendermint/tendermint/libs/os/os.go:26 +0x102 created by github.com/tendermint/tendermint/libs/os.TrapSignal github.com/tendermint/tendermint/libs/os/os.go:22 +0xe6 goroutine 161 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).poolRoutine(0xc0000d3a00, 0x0) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:464 +0x2b3 created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:174 +0xf1 goroutine 162 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).processBlockSyncCh(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:310 +0x151 created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:177 +0x54 goroutine 163 [select]: github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).processPeerUpdates(0xc0000d3a00) github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:363 +0x12b created by github.com/tendermint/tendermint/internal/blocksync/v0.(*Reactor).OnStart github.com/tendermint/tendermint/internal/blocksync/v0/reactor.go:178 +0x76 ```
3 years ago
  1. package blocksync
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "runtime/debug"
  7. "sync/atomic"
  8. "time"
  9. "github.com/tendermint/tendermint/internal/consensus"
  10. "github.com/tendermint/tendermint/internal/eventbus"
  11. "github.com/tendermint/tendermint/internal/p2p"
  12. sm "github.com/tendermint/tendermint/internal/state"
  13. "github.com/tendermint/tendermint/internal/store"
  14. "github.com/tendermint/tendermint/libs/log"
  15. "github.com/tendermint/tendermint/libs/service"
  16. bcproto "github.com/tendermint/tendermint/proto/tendermint/blocksync"
  17. "github.com/tendermint/tendermint/types"
  18. )
  19. var _ service.Service = (*Reactor)(nil)
  20. const (
  21. // BlockSyncChannel is a channel for blocks and status updates
  22. BlockSyncChannel = p2p.ChannelID(0x40)
  23. trySyncIntervalMS = 10
  24. // ask for best height every 10s
  25. statusUpdateIntervalSeconds = 10
  26. // check if we should switch to consensus reactor
  27. switchToConsensusIntervalSeconds = 1
  28. // switch to consensus after this duration of inactivity
  29. syncTimeout = 60 * time.Second
  30. )
  31. func GetChannelDescriptor() *p2p.ChannelDescriptor {
  32. return &p2p.ChannelDescriptor{
  33. ID: BlockSyncChannel,
  34. MessageType: new(bcproto.Message),
  35. Priority: 5,
  36. SendQueueCapacity: 1000,
  37. RecvBufferCapacity: 1024,
  38. RecvMessageCapacity: MaxMsgSize,
  39. }
  40. }
  41. type consensusReactor interface {
  42. // For when we switch from block sync reactor to the consensus
  43. // machine.
  44. SwitchToConsensus(ctx context.Context, state sm.State, skipWAL bool)
  45. }
  46. type peerError struct {
  47. err error
  48. peerID types.NodeID
  49. }
  50. func (e peerError) Error() string {
  51. return fmt.Sprintf("error with peer %v: %s", e.peerID, e.err.Error())
  52. }
  53. // Reactor handles long-term catchup syncing.
  54. type Reactor struct {
  55. service.BaseService
  56. logger log.Logger
  57. // immutable
  58. initialState sm.State
  59. blockExec *sm.BlockExecutor
  60. store *store.BlockStore
  61. pool *BlockPool
  62. consReactor consensusReactor
  63. blockSync *atomicBool
  64. blockSyncCh *p2p.Channel
  65. // blockSyncOutBridgeCh defines a channel that acts as a bridge between sending Envelope
  66. // messages that the reactor will consume in processBlockSyncCh and receiving messages
  67. // from the peer updates channel and other goroutines. We do this instead of directly
  68. // sending on blockSyncCh.Out to avoid race conditions in the case where other goroutines
  69. // send Envelopes directly to the to blockSyncCh.Out channel, since processBlockSyncCh
  70. // may close the blockSyncCh.Out channel at the same time that other goroutines send to
  71. // blockSyncCh.Out.
  72. blockSyncOutBridgeCh chan p2p.Envelope
  73. peerUpdates *p2p.PeerUpdates
  74. requestsCh <-chan BlockRequest
  75. errorsCh <-chan peerError
  76. metrics *consensus.Metrics
  77. eventBus *eventbus.EventBus
  78. syncStartTime time.Time
  79. }
  80. // NewReactor returns new reactor instance.
  81. func NewReactor(
  82. ctx context.Context,
  83. logger log.Logger,
  84. state sm.State,
  85. blockExec *sm.BlockExecutor,
  86. store *store.BlockStore,
  87. consReactor consensusReactor,
  88. channelCreator p2p.ChannelCreator,
  89. peerUpdates *p2p.PeerUpdates,
  90. blockSync bool,
  91. metrics *consensus.Metrics,
  92. eventBus *eventbus.EventBus,
  93. ) (*Reactor, error) {
  94. if state.LastBlockHeight != store.Height() {
  95. return nil, fmt.Errorf("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height())
  96. }
  97. startHeight := store.Height() + 1
  98. if startHeight == 1 {
  99. startHeight = state.InitialHeight
  100. }
  101. requestsCh := make(chan BlockRequest, maxTotalRequesters)
  102. errorsCh := make(chan peerError, maxPeerErrBuffer) // NOTE: The capacity should be larger than the peer count.
  103. blockSyncCh, err := channelCreator(ctx, GetChannelDescriptor())
  104. if err != nil {
  105. return nil, err
  106. }
  107. r := &Reactor{
  108. logger: logger,
  109. initialState: state,
  110. blockExec: blockExec,
  111. store: store,
  112. pool: NewBlockPool(logger, startHeight, requestsCh, errorsCh),
  113. consReactor: consReactor,
  114. blockSync: newAtomicBool(blockSync),
  115. requestsCh: requestsCh,
  116. errorsCh: errorsCh,
  117. blockSyncCh: blockSyncCh,
  118. blockSyncOutBridgeCh: make(chan p2p.Envelope),
  119. peerUpdates: peerUpdates,
  120. metrics: metrics,
  121. eventBus: eventBus,
  122. syncStartTime: time.Time{},
  123. }
  124. r.BaseService = *service.NewBaseService(logger, "BlockSync", r)
  125. return r, nil
  126. }
  127. // OnStart starts separate go routines for each p2p Channel and listens for
  128. // envelopes on each. In addition, it also listens for peer updates and handles
  129. // messages on that p2p channel accordingly. The caller must be sure to execute
  130. // OnStop to ensure the outbound p2p Channels are closed.
  131. //
  132. // If blockSync is enabled, we also start the pool and the pool processing
  133. // goroutine. If the pool fails to start, an error is returned.
  134. func (r *Reactor) OnStart(ctx context.Context) error {
  135. if r.blockSync.IsSet() {
  136. if err := r.pool.Start(ctx); err != nil {
  137. return err
  138. }
  139. go r.requestRoutine(ctx)
  140. go r.poolRoutine(ctx, false)
  141. }
  142. go r.processBlockSyncCh(ctx)
  143. go r.processBlockSyncBridge(ctx)
  144. go r.processPeerUpdates(ctx)
  145. return nil
  146. }
  147. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  148. // blocking until they all exit.
  149. func (r *Reactor) OnStop() {
  150. if r.blockSync.IsSet() {
  151. r.pool.Stop()
  152. }
  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(ctx context.Context, msg *bcproto.BlockRequest, peerID types.NodeID) error {
  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 err
  163. }
  164. return r.blockSyncCh.Send(ctx, p2p.Envelope{
  165. To: peerID,
  166. Message: &bcproto.BlockResponse{Block: blockProto},
  167. })
  168. }
  169. r.logger.Info("peer requesting a block we do not have", "peer", peerID, "height", msg.Height)
  170. return r.blockSyncCh.Send(ctx, p2p.Envelope{
  171. To: peerID,
  172. Message: &bcproto.NoBlockResponse{Height: msg.Height},
  173. })
  174. }
  175. // handleBlockSyncMessage handles envelopes sent from peers on the
  176. // BlockSyncChannel. 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) handleBlockSyncMessage(ctx context.Context, envelope *p2p.Envelope) error {
  179. logger := r.logger.With("peer", envelope.From)
  180. switch msg := envelope.Message.(type) {
  181. case *bcproto.BlockRequest:
  182. return r.respondToPeer(ctx, 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. return r.blockSyncCh.Send(ctx, 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(ctx context.Context, 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(
  215. "recovering from processing message panic",
  216. "err", err,
  217. "stack", string(debug.Stack()),
  218. )
  219. }
  220. }()
  221. r.logger.Debug("received message", "message", envelope.Message, "peer", envelope.From)
  222. switch chID {
  223. case BlockSyncChannel:
  224. err = r.handleBlockSyncMessage(ctx, envelope)
  225. default:
  226. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  227. }
  228. return err
  229. }
  230. // processBlockSyncCh initiates a blocking process where we listen for and handle
  231. // envelopes on the BlockSyncChannel and blockSyncOutBridgeCh. Any error encountered during
  232. // message execution will result in a PeerError being sent on the BlockSyncChannel.
  233. // When the reactor is stopped, we will catch the signal and close the p2p Channel
  234. // gracefully.
  235. func (r *Reactor) processBlockSyncCh(ctx context.Context) {
  236. iter := r.blockSyncCh.Receive(ctx)
  237. for iter.Next(ctx) {
  238. envelope := iter.Envelope()
  239. if err := r.handleMessage(ctx, r.blockSyncCh.ID, envelope); err != nil {
  240. if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
  241. return
  242. }
  243. r.logger.Error("failed to process message", "ch_id", r.blockSyncCh.ID, "envelope", envelope, "err", err)
  244. if serr := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  245. NodeID: envelope.From,
  246. Err: err,
  247. }); serr != nil {
  248. return
  249. }
  250. }
  251. }
  252. }
  253. func (r *Reactor) processBlockSyncBridge(ctx context.Context) {
  254. for {
  255. select {
  256. case <-ctx.Done():
  257. return
  258. case envelope := <-r.blockSyncOutBridgeCh:
  259. if err := r.blockSyncCh.Send(ctx, envelope); err != nil {
  260. return
  261. }
  262. }
  263. }
  264. }
  265. // processPeerUpdate processes a PeerUpdate.
  266. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  267. r.logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  268. // XXX: Pool#RedoRequest can sometimes give us an empty peer.
  269. if len(peerUpdate.NodeID) == 0 {
  270. return
  271. }
  272. switch peerUpdate.Status {
  273. case p2p.PeerStatusUp:
  274. // send a status update the newly added peer
  275. r.blockSyncOutBridgeCh <- p2p.Envelope{
  276. To: peerUpdate.NodeID,
  277. Message: &bcproto.StatusResponse{
  278. Base: r.store.Base(),
  279. Height: r.store.Height(),
  280. },
  281. }
  282. case p2p.PeerStatusDown:
  283. r.pool.RemovePeer(peerUpdate.NodeID)
  284. }
  285. }
  286. // processPeerUpdates initiates a blocking process where we listen for and handle
  287. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  288. // close the p2p PeerUpdatesCh gracefully.
  289. func (r *Reactor) processPeerUpdates(ctx context.Context) {
  290. for {
  291. select {
  292. case <-ctx.Done():
  293. return
  294. case peerUpdate := <-r.peerUpdates.Updates():
  295. r.processPeerUpdate(peerUpdate)
  296. }
  297. }
  298. }
  299. // SwitchToBlockSync is called by the state sync reactor when switching to fast
  300. // sync.
  301. func (r *Reactor) SwitchToBlockSync(ctx context.Context, state sm.State) error {
  302. r.blockSync.Set()
  303. r.initialState = state
  304. r.pool.height = state.LastBlockHeight + 1
  305. if err := r.pool.Start(ctx); err != nil {
  306. return err
  307. }
  308. r.syncStartTime = time.Now()
  309. go r.requestRoutine(ctx)
  310. go r.poolRoutine(ctx, true)
  311. return nil
  312. }
  313. func (r *Reactor) requestRoutine(ctx context.Context) {
  314. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  315. defer statusUpdateTicker.Stop()
  316. for {
  317. select {
  318. case <-ctx.Done():
  319. return
  320. case request := <-r.requestsCh:
  321. select {
  322. case <-ctx.Done():
  323. return
  324. case r.blockSyncOutBridgeCh <- p2p.Envelope{
  325. To: request.PeerID,
  326. Message: &bcproto.BlockRequest{Height: request.Height},
  327. }:
  328. }
  329. case pErr := <-r.errorsCh:
  330. if err := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  331. NodeID: pErr.peerID,
  332. Err: pErr.err,
  333. }); err != nil {
  334. return
  335. }
  336. case <-statusUpdateTicker.C:
  337. go func() {
  338. select {
  339. case <-ctx.Done():
  340. return
  341. case r.blockSyncOutBridgeCh <- p2p.Envelope{
  342. Broadcast: true,
  343. Message: &bcproto.StatusRequest{},
  344. }:
  345. }
  346. }()
  347. }
  348. }
  349. }
  350. // poolRoutine handles messages from the poolReactor telling the reactor what to
  351. // do.
  352. //
  353. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  354. func (r *Reactor) poolRoutine(ctx context.Context, stateSynced bool) {
  355. var (
  356. trySyncTicker = time.NewTicker(trySyncIntervalMS * time.Millisecond)
  357. switchToConsensusTicker = time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  358. blocksSynced = uint64(0)
  359. chainID = r.initialState.ChainID
  360. state = r.initialState
  361. lastHundred = time.Now()
  362. lastRate = 0.0
  363. didProcessCh = make(chan struct{}, 1)
  364. )
  365. defer trySyncTicker.Stop()
  366. defer switchToConsensusTicker.Stop()
  367. for {
  368. select {
  369. case <-ctx.Done():
  370. return
  371. case <-r.pool.exitedCh:
  372. return
  373. case <-switchToConsensusTicker.C:
  374. var (
  375. height, numPending, lenRequesters = r.pool.GetStatus()
  376. lastAdvance = r.pool.LastAdvance()
  377. )
  378. r.logger.Debug(
  379. "consensus ticker",
  380. "num_pending", numPending,
  381. "total", lenRequesters,
  382. "height", height,
  383. )
  384. switch {
  385. case r.pool.IsCaughtUp():
  386. r.logger.Info("switching to consensus reactor", "height", height)
  387. case time.Since(lastAdvance) > syncTimeout:
  388. r.logger.Error("no progress since last advance", "last_advance", lastAdvance)
  389. default:
  390. r.logger.Info(
  391. "not caught up yet",
  392. "height", height,
  393. "max_peer_height", r.pool.MaxPeerHeight(),
  394. "timeout_in", syncTimeout-time.Since(lastAdvance),
  395. )
  396. continue
  397. }
  398. r.pool.Stop()
  399. r.blockSync.UnSet()
  400. if r.consReactor != nil {
  401. r.consReactor.SwitchToConsensus(ctx, state, blocksSynced > 0 || stateSynced)
  402. }
  403. return
  404. case <-trySyncTicker.C:
  405. select {
  406. case didProcessCh <- struct{}{}:
  407. default:
  408. }
  409. case <-didProcessCh:
  410. // NOTE: It is a subtle mistake to process more than a single block at a
  411. // time (e.g. 10) here, because we only send one BlockRequest per loop
  412. // iteration. The ratio mismatch can result in starving of blocks, i.e. a
  413. // sudden burst of requests and responses, and repeat. Consequently, it is
  414. // better to split these routines rather than coupling them as it is
  415. // written here.
  416. //
  417. // TODO: Uncouple from request routine.
  418. // see if there are any blocks to sync
  419. first, second := r.pool.PeekTwoBlocks()
  420. if first == nil || second == nil {
  421. // we need both to sync the first block
  422. continue
  423. } else {
  424. // try again quickly next loop
  425. didProcessCh <- struct{}{}
  426. }
  427. firstParts, err := first.MakePartSet(types.BlockPartSizeBytes)
  428. if err != nil {
  429. r.logger.Error("failed to make ",
  430. "height", first.Height,
  431. "err", err.Error())
  432. return
  433. }
  434. var (
  435. firstPartSetHeader = firstParts.Header()
  436. firstID = types.BlockID{Hash: first.Hash(), PartSetHeader: firstPartSetHeader}
  437. )
  438. // Finally, verify the first block using the second's commit.
  439. //
  440. // NOTE: We can probably make this more efficient, but note that calling
  441. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  442. // currently necessary.
  443. if err = state.Validators.VerifyCommitLight(chainID, firstID, first.Height, second.LastCommit); err != nil {
  444. err = fmt.Errorf("invalid last commit: %w", err)
  445. r.logger.Error(
  446. err.Error(),
  447. "last_commit", second.LastCommit,
  448. "block_id", firstID,
  449. "height", first.Height,
  450. )
  451. // NOTE: We've already removed the peer's request, but we still need
  452. // to clean up the rest.
  453. peerID := r.pool.RedoRequest(first.Height)
  454. if serr := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  455. NodeID: peerID,
  456. Err: err,
  457. }); serr != nil {
  458. return
  459. }
  460. peerID2 := r.pool.RedoRequest(second.Height)
  461. if peerID2 != peerID {
  462. if serr := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  463. NodeID: peerID2,
  464. Err: err,
  465. }); serr != nil {
  466. return
  467. }
  468. }
  469. } else {
  470. r.pool.PopRequest()
  471. // TODO: batch saves so we do not persist to disk every block
  472. r.store.SaveBlock(first, firstParts, second.LastCommit)
  473. var err error
  474. // TODO: Same thing for app - but we would need a way to get the hash
  475. // without persisting the state.
  476. state, err = r.blockExec.ApplyBlock(ctx, state, firstID, first)
  477. if err != nil {
  478. // TODO: This is bad, are we zombie?
  479. panic(fmt.Sprintf("failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  480. }
  481. r.metrics.RecordConsMetrics(first)
  482. blocksSynced++
  483. if blocksSynced%100 == 0 {
  484. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  485. r.logger.Info(
  486. "block sync rate",
  487. "height", r.pool.height,
  488. "max_peer_height", r.pool.MaxPeerHeight(),
  489. "blocks/s", lastRate,
  490. )
  491. lastHundred = time.Now()
  492. }
  493. }
  494. }
  495. }
  496. }
  497. func (r *Reactor) GetMaxPeerBlockHeight() int64 {
  498. return r.pool.MaxPeerHeight()
  499. }
  500. func (r *Reactor) GetTotalSyncedTime() time.Duration {
  501. if !r.blockSync.IsSet() || r.syncStartTime.IsZero() {
  502. return time.Duration(0)
  503. }
  504. return time.Since(r.syncStartTime)
  505. }
  506. func (r *Reactor) GetRemainingSyncTime() time.Duration {
  507. if !r.blockSync.IsSet() {
  508. return time.Duration(0)
  509. }
  510. targetSyncs := r.pool.targetSyncBlocks()
  511. currentSyncs := r.store.Height() - r.pool.startHeight + 1
  512. lastSyncRate := r.pool.getLastSyncRate()
  513. if currentSyncs < 0 || lastSyncRate < 0.001 {
  514. return time.Duration(0)
  515. }
  516. remain := float64(targetSyncs-currentSyncs) / lastSyncRate
  517. return time.Duration(int64(remain * float64(time.Second)))
  518. }
  519. func (r *Reactor) PublishStatus(ctx context.Context, event types.EventDataBlockSyncStatus) error {
  520. if r.eventBus == nil {
  521. return errors.New("event bus is not configured")
  522. }
  523. return r.eventBus.PublishEventBlockSyncStatus(ctx, event)
  524. }
  525. // atomicBool is an atomic Boolean, safe for concurrent use by multiple
  526. // goroutines.
  527. type atomicBool int32
  528. // newAtomicBool creates an atomicBool with given initial value.
  529. func newAtomicBool(ok bool) *atomicBool {
  530. ab := new(atomicBool)
  531. if ok {
  532. ab.Set()
  533. }
  534. return ab
  535. }
  536. // Set sets the Boolean to true.
  537. func (ab *atomicBool) Set() { atomic.StoreInt32((*int32)(ab), 1) }
  538. // UnSet sets the Boolean to false.
  539. func (ab *atomicBool) UnSet() { atomic.StoreInt32((*int32)(ab), 0) }
  540. // IsSet returns whether the Boolean is true.
  541. func (ab *atomicBool) IsSet() bool { return atomic.LoadInt32((*int32)(ab))&1 == 1 }