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.

652 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. // store
  60. stateStore sm.Store
  61. blockExec *sm.BlockExecutor
  62. store *store.BlockStore
  63. pool *BlockPool
  64. consReactor consensusReactor
  65. blockSync *atomicBool
  66. blockSyncCh *p2p.Channel
  67. // blockSyncOutBridgeCh defines a channel that acts as a bridge between sending Envelope
  68. // messages that the reactor will consume in processBlockSyncCh and receiving messages
  69. // from the peer updates channel and other goroutines. We do this instead of directly
  70. // sending on blockSyncCh.Out to avoid race conditions in the case where other goroutines
  71. // send Envelopes directly to the to blockSyncCh.Out channel, since processBlockSyncCh
  72. // may close the blockSyncCh.Out channel at the same time that other goroutines send to
  73. // blockSyncCh.Out.
  74. blockSyncOutBridgeCh chan p2p.Envelope
  75. peerUpdates *p2p.PeerUpdates
  76. requestsCh <-chan BlockRequest
  77. errorsCh <-chan peerError
  78. metrics *consensus.Metrics
  79. eventBus *eventbus.EventBus
  80. syncStartTime time.Time
  81. }
  82. // NewReactor returns new reactor instance.
  83. func NewReactor(
  84. ctx context.Context,
  85. logger log.Logger,
  86. stateStore sm.Store,
  87. blockExec *sm.BlockExecutor,
  88. store *store.BlockStore,
  89. consReactor consensusReactor,
  90. channelCreator p2p.ChannelCreator,
  91. peerUpdates *p2p.PeerUpdates,
  92. blockSync bool,
  93. metrics *consensus.Metrics,
  94. eventBus *eventbus.EventBus,
  95. ) (*Reactor, error) {
  96. blockSyncCh, err := channelCreator(ctx, GetChannelDescriptor())
  97. if err != nil {
  98. return nil, err
  99. }
  100. r := &Reactor{
  101. logger: logger,
  102. stateStore: stateStore,
  103. blockExec: blockExec,
  104. store: store,
  105. consReactor: consReactor,
  106. blockSync: newAtomicBool(blockSync),
  107. blockSyncCh: blockSyncCh,
  108. blockSyncOutBridgeCh: make(chan p2p.Envelope),
  109. peerUpdates: peerUpdates,
  110. metrics: metrics,
  111. eventBus: eventBus,
  112. }
  113. r.BaseService = *service.NewBaseService(logger, "BlockSync", 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 blockSync 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(ctx context.Context) error {
  124. state, err := r.stateStore.Load()
  125. if err != nil {
  126. return err
  127. }
  128. r.initialState = state
  129. if state.LastBlockHeight != r.store.Height() {
  130. return fmt.Errorf("state (%v) and store (%v) height mismatch", state.LastBlockHeight, r.store.Height())
  131. }
  132. startHeight := r.store.Height() + 1
  133. if startHeight == 1 {
  134. startHeight = state.InitialHeight
  135. }
  136. requestsCh := make(chan BlockRequest, maxTotalRequesters)
  137. errorsCh := make(chan peerError, maxPeerErrBuffer) // NOTE: The capacity should be larger than the peer count.
  138. r.pool = NewBlockPool(r.logger, startHeight, requestsCh, errorsCh)
  139. r.requestsCh = requestsCh
  140. r.errorsCh = errorsCh
  141. if r.blockSync.IsSet() {
  142. if err := r.pool.Start(ctx); err != nil {
  143. return err
  144. }
  145. go r.requestRoutine(ctx)
  146. go r.poolRoutine(ctx, false)
  147. }
  148. go r.processBlockSyncCh(ctx)
  149. go r.processBlockSyncBridge(ctx)
  150. go r.processPeerUpdates(ctx)
  151. return nil
  152. }
  153. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  154. // blocking until they all exit.
  155. func (r *Reactor) OnStop() {
  156. if r.blockSync.IsSet() {
  157. r.pool.Stop()
  158. }
  159. }
  160. // respondToPeer loads a block and sends it to the requesting peer, if we have it.
  161. // Otherwise, we'll respond saying we do not have it.
  162. func (r *Reactor) respondToPeer(ctx context.Context, msg *bcproto.BlockRequest, peerID types.NodeID) error {
  163. block := r.store.LoadBlock(msg.Height)
  164. if block != nil {
  165. blockProto, err := block.ToProto()
  166. if err != nil {
  167. r.logger.Error("failed to convert msg to protobuf", "err", err)
  168. return err
  169. }
  170. return r.blockSyncCh.Send(ctx, p2p.Envelope{
  171. To: peerID,
  172. Message: &bcproto.BlockResponse{Block: blockProto},
  173. })
  174. }
  175. r.logger.Info("peer requesting a block we do not have", "peer", peerID, "height", msg.Height)
  176. return r.blockSyncCh.Send(ctx, p2p.Envelope{
  177. To: peerID,
  178. Message: &bcproto.NoBlockResponse{Height: msg.Height},
  179. })
  180. }
  181. // handleBlockSyncMessage handles envelopes sent from peers on the
  182. // BlockSyncChannel. It returns an error only if the Envelope.Message is unknown
  183. // for this channel. This should never be called outside of handleMessage.
  184. func (r *Reactor) handleBlockSyncMessage(ctx context.Context, envelope *p2p.Envelope) error {
  185. logger := r.logger.With("peer", envelope.From)
  186. switch msg := envelope.Message.(type) {
  187. case *bcproto.BlockRequest:
  188. return r.respondToPeer(ctx, msg, envelope.From)
  189. case *bcproto.BlockResponse:
  190. block, err := types.BlockFromProto(msg.Block)
  191. if err != nil {
  192. logger.Error("failed to convert block from proto", "err", err)
  193. return err
  194. }
  195. r.pool.AddBlock(envelope.From, block, block.Size())
  196. case *bcproto.StatusRequest:
  197. return r.blockSyncCh.Send(ctx, p2p.Envelope{
  198. To: envelope.From,
  199. Message: &bcproto.StatusResponse{
  200. Height: r.store.Height(),
  201. Base: r.store.Base(),
  202. },
  203. })
  204. case *bcproto.StatusResponse:
  205. r.pool.SetPeerRange(envelope.From, msg.Base, msg.Height)
  206. case *bcproto.NoBlockResponse:
  207. logger.Debug("peer does not have the requested block", "height", msg.Height)
  208. default:
  209. return fmt.Errorf("received unknown message: %T", msg)
  210. }
  211. return nil
  212. }
  213. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  214. // It will handle errors and any possible panics gracefully. A caller can handle
  215. // any error returned by sending a PeerError on the respective channel.
  216. func (r *Reactor) handleMessage(ctx context.Context, chID p2p.ChannelID, envelope *p2p.Envelope) (err error) {
  217. defer func() {
  218. if e := recover(); e != nil {
  219. err = fmt.Errorf("panic in processing message: %v", e)
  220. r.logger.Error(
  221. "recovering from processing message panic",
  222. "err", err,
  223. "stack", string(debug.Stack()),
  224. )
  225. }
  226. }()
  227. r.logger.Debug("received message", "message", envelope.Message, "peer", envelope.From)
  228. switch chID {
  229. case BlockSyncChannel:
  230. err = r.handleBlockSyncMessage(ctx, envelope)
  231. default:
  232. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  233. }
  234. return err
  235. }
  236. // processBlockSyncCh initiates a blocking process where we listen for and handle
  237. // envelopes on the BlockSyncChannel and blockSyncOutBridgeCh. Any error encountered during
  238. // message execution will result in a PeerError being sent on the BlockSyncChannel.
  239. // When the reactor is stopped, we will catch the signal and close the p2p Channel
  240. // gracefully.
  241. func (r *Reactor) processBlockSyncCh(ctx context.Context) {
  242. iter := r.blockSyncCh.Receive(ctx)
  243. for iter.Next(ctx) {
  244. envelope := iter.Envelope()
  245. if err := r.handleMessage(ctx, r.blockSyncCh.ID, envelope); err != nil {
  246. if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
  247. return
  248. }
  249. r.logger.Error("failed to process message", "ch_id", r.blockSyncCh.ID, "envelope", envelope, "err", err)
  250. if serr := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  251. NodeID: envelope.From,
  252. Err: err,
  253. }); serr != nil {
  254. return
  255. }
  256. }
  257. }
  258. }
  259. func (r *Reactor) processBlockSyncBridge(ctx context.Context) {
  260. for {
  261. select {
  262. case <-ctx.Done():
  263. return
  264. case envelope := <-r.blockSyncOutBridgeCh:
  265. if err := r.blockSyncCh.Send(ctx, envelope); err != nil {
  266. return
  267. }
  268. }
  269. }
  270. }
  271. // processPeerUpdate processes a PeerUpdate.
  272. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  273. r.logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  274. // XXX: Pool#RedoRequest can sometimes give us an empty peer.
  275. if len(peerUpdate.NodeID) == 0 {
  276. return
  277. }
  278. switch peerUpdate.Status {
  279. case p2p.PeerStatusUp:
  280. // send a status update the newly added peer
  281. r.blockSyncOutBridgeCh <- p2p.Envelope{
  282. To: peerUpdate.NodeID,
  283. Message: &bcproto.StatusResponse{
  284. Base: r.store.Base(),
  285. Height: r.store.Height(),
  286. },
  287. }
  288. case p2p.PeerStatusDown:
  289. r.pool.RemovePeer(peerUpdate.NodeID)
  290. }
  291. }
  292. // processPeerUpdates initiates a blocking process where we listen for and handle
  293. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  294. // close the p2p PeerUpdatesCh gracefully.
  295. func (r *Reactor) processPeerUpdates(ctx context.Context) {
  296. for {
  297. select {
  298. case <-ctx.Done():
  299. return
  300. case peerUpdate := <-r.peerUpdates.Updates():
  301. r.processPeerUpdate(peerUpdate)
  302. }
  303. }
  304. }
  305. // SwitchToBlockSync is called by the state sync reactor when switching to fast
  306. // sync.
  307. func (r *Reactor) SwitchToBlockSync(ctx context.Context, state sm.State) error {
  308. r.blockSync.Set()
  309. r.initialState = state
  310. r.pool.height = state.LastBlockHeight + 1
  311. if err := r.pool.Start(ctx); err != nil {
  312. return err
  313. }
  314. r.syncStartTime = time.Now()
  315. go r.requestRoutine(ctx)
  316. go r.poolRoutine(ctx, true)
  317. return nil
  318. }
  319. func (r *Reactor) requestRoutine(ctx context.Context) {
  320. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  321. defer statusUpdateTicker.Stop()
  322. for {
  323. select {
  324. case <-ctx.Done():
  325. return
  326. case request := <-r.requestsCh:
  327. select {
  328. case <-ctx.Done():
  329. return
  330. case r.blockSyncOutBridgeCh <- p2p.Envelope{
  331. To: request.PeerID,
  332. Message: &bcproto.BlockRequest{Height: request.Height},
  333. }:
  334. }
  335. case pErr := <-r.errorsCh:
  336. if err := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  337. NodeID: pErr.peerID,
  338. Err: pErr.err,
  339. }); err != nil {
  340. return
  341. }
  342. case <-statusUpdateTicker.C:
  343. go func() {
  344. select {
  345. case <-ctx.Done():
  346. return
  347. case r.blockSyncOutBridgeCh <- p2p.Envelope{
  348. Broadcast: true,
  349. Message: &bcproto.StatusRequest{},
  350. }:
  351. }
  352. }()
  353. }
  354. }
  355. }
  356. // poolRoutine handles messages from the poolReactor telling the reactor what to
  357. // do.
  358. //
  359. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  360. func (r *Reactor) poolRoutine(ctx context.Context, stateSynced bool) {
  361. var (
  362. trySyncTicker = time.NewTicker(trySyncIntervalMS * time.Millisecond)
  363. switchToConsensusTicker = time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  364. blocksSynced = uint64(0)
  365. chainID = r.initialState.ChainID
  366. state = r.initialState
  367. lastHundred = time.Now()
  368. lastRate = 0.0
  369. didProcessCh = make(chan struct{}, 1)
  370. )
  371. defer trySyncTicker.Stop()
  372. defer switchToConsensusTicker.Stop()
  373. for {
  374. select {
  375. case <-ctx.Done():
  376. return
  377. case <-r.pool.exitedCh:
  378. return
  379. case <-switchToConsensusTicker.C:
  380. var (
  381. height, numPending, lenRequesters = r.pool.GetStatus()
  382. lastAdvance = r.pool.LastAdvance()
  383. )
  384. r.logger.Debug(
  385. "consensus ticker",
  386. "num_pending", numPending,
  387. "total", lenRequesters,
  388. "height", height,
  389. )
  390. switch {
  391. case r.pool.IsCaughtUp():
  392. r.logger.Info("switching to consensus reactor", "height", height)
  393. case time.Since(lastAdvance) > syncTimeout:
  394. r.logger.Error("no progress since last advance", "last_advance", lastAdvance)
  395. default:
  396. r.logger.Info(
  397. "not caught up yet",
  398. "height", height,
  399. "max_peer_height", r.pool.MaxPeerHeight(),
  400. "timeout_in", syncTimeout-time.Since(lastAdvance),
  401. )
  402. continue
  403. }
  404. r.pool.Stop()
  405. r.blockSync.UnSet()
  406. if r.consReactor != nil {
  407. r.consReactor.SwitchToConsensus(ctx, state, blocksSynced > 0 || stateSynced)
  408. }
  409. return
  410. case <-trySyncTicker.C:
  411. select {
  412. case didProcessCh <- struct{}{}:
  413. default:
  414. }
  415. case <-didProcessCh:
  416. // NOTE: It is a subtle mistake to process more than a single block at a
  417. // time (e.g. 10) here, because we only send one BlockRequest per loop
  418. // iteration. The ratio mismatch can result in starving of blocks, i.e. a
  419. // sudden burst of requests and responses, and repeat. Consequently, it is
  420. // better to split these routines rather than coupling them as it is
  421. // written here.
  422. //
  423. // TODO: Uncouple from request routine.
  424. // see if there are any blocks to sync
  425. first, second := r.pool.PeekTwoBlocks()
  426. if first == nil || second == nil {
  427. // we need both to sync the first block
  428. continue
  429. } else {
  430. // try again quickly next loop
  431. didProcessCh <- struct{}{}
  432. }
  433. firstParts, err := first.MakePartSet(types.BlockPartSizeBytes)
  434. if err != nil {
  435. r.logger.Error("failed to make ",
  436. "height", first.Height,
  437. "err", err.Error())
  438. return
  439. }
  440. var (
  441. firstPartSetHeader = firstParts.Header()
  442. firstID = types.BlockID{Hash: first.Hash(), PartSetHeader: firstPartSetHeader}
  443. )
  444. // Finally, verify the first block using the second's commit.
  445. //
  446. // NOTE: We can probably make this more efficient, but note that calling
  447. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  448. // currently necessary.
  449. if err = state.Validators.VerifyCommitLight(chainID, firstID, first.Height, second.LastCommit); err != nil {
  450. err = fmt.Errorf("invalid last commit: %w", err)
  451. r.logger.Error(
  452. err.Error(),
  453. "last_commit", second.LastCommit,
  454. "block_id", firstID,
  455. "height", first.Height,
  456. )
  457. // NOTE: We've already removed the peer's request, but we still need
  458. // to clean up the rest.
  459. peerID := r.pool.RedoRequest(first.Height)
  460. if serr := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  461. NodeID: peerID,
  462. Err: err,
  463. }); serr != nil {
  464. return
  465. }
  466. peerID2 := r.pool.RedoRequest(second.Height)
  467. if peerID2 != peerID {
  468. if serr := r.blockSyncCh.SendError(ctx, p2p.PeerError{
  469. NodeID: peerID2,
  470. Err: err,
  471. }); serr != nil {
  472. return
  473. }
  474. }
  475. } else {
  476. r.pool.PopRequest()
  477. // TODO: batch saves so we do not persist to disk every block
  478. r.store.SaveBlock(first, firstParts, second.LastCommit)
  479. var err error
  480. // TODO: Same thing for app - but we would need a way to get the hash
  481. // without persisting the state.
  482. state, err = r.blockExec.ApplyBlock(ctx, state, firstID, first)
  483. if err != nil {
  484. // TODO: This is bad, are we zombie?
  485. panic(fmt.Sprintf("failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  486. }
  487. r.metrics.RecordConsMetrics(first)
  488. blocksSynced++
  489. if blocksSynced%100 == 0 {
  490. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  491. r.logger.Info(
  492. "block sync rate",
  493. "height", r.pool.height,
  494. "max_peer_height", r.pool.MaxPeerHeight(),
  495. "blocks/s", lastRate,
  496. )
  497. lastHundred = time.Now()
  498. }
  499. }
  500. }
  501. }
  502. }
  503. func (r *Reactor) GetMaxPeerBlockHeight() int64 {
  504. return r.pool.MaxPeerHeight()
  505. }
  506. func (r *Reactor) GetTotalSyncedTime() time.Duration {
  507. if !r.blockSync.IsSet() || r.syncStartTime.IsZero() {
  508. return time.Duration(0)
  509. }
  510. return time.Since(r.syncStartTime)
  511. }
  512. func (r *Reactor) GetRemainingSyncTime() time.Duration {
  513. if !r.blockSync.IsSet() {
  514. return time.Duration(0)
  515. }
  516. targetSyncs := r.pool.targetSyncBlocks()
  517. currentSyncs := r.store.Height() - r.pool.startHeight + 1
  518. lastSyncRate := r.pool.getLastSyncRate()
  519. if currentSyncs < 0 || lastSyncRate < 0.001 {
  520. return time.Duration(0)
  521. }
  522. remain := float64(targetSyncs-currentSyncs) / lastSyncRate
  523. return time.Duration(int64(remain * float64(time.Second)))
  524. }
  525. func (r *Reactor) PublishStatus(ctx context.Context, event types.EventDataBlockSyncStatus) error {
  526. if r.eventBus == nil {
  527. return errors.New("event bus is not configured")
  528. }
  529. return r.eventBus.PublishEventBlockSyncStatus(ctx, event)
  530. }
  531. // atomicBool is an atomic Boolean, safe for concurrent use by multiple
  532. // goroutines.
  533. type atomicBool int32
  534. // newAtomicBool creates an atomicBool with given initial value.
  535. func newAtomicBool(ok bool) *atomicBool {
  536. ab := new(atomicBool)
  537. if ok {
  538. ab.Set()
  539. }
  540. return ab
  541. }
  542. // Set sets the Boolean to true.
  543. func (ab *atomicBool) Set() { atomic.StoreInt32((*int32)(ab), 1) }
  544. // UnSet sets the Boolean to false.
  545. func (ab *atomicBool) UnSet() { atomic.StoreInt32((*int32)(ab), 0) }
  546. // IsSet returns whether the Boolean is true.
  547. func (ab *atomicBool) IsSet() bool { return atomic.LoadInt32((*int32)(ab))&1 == 1 }