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.

1072 lines
30 KiB

statesync: remove deadlock on init fail (#7029) When statesync is stopped during shutdown, it has the possibility of deadlocking. A dump of goroutines reveals that this is related to the peerUpdates channel not returning anything on its `Done()` channel when `OnStop` is called. As this is occuring, `processPeerUpdate` is attempting to acquire the reactor lock. It appears that this lock can never be acquired. I looked for the places where the lock may remain locked accidentally and cleaned them up in hopes to eradicate the issue. Dumps of the relevant goroutines may be found below. Note that the line numbers below are relative to the code in the `v0.35.0-rc1` tag. ``` goroutine 36 [chan receive]: github.com/tendermint/tendermint/internal/statesync.(*Reactor).OnStop(0xc00058f200) github.com/tendermint/tendermint/internal/statesync/reactor.go:243 +0x117 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00058f200, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc0001ea240) github.com/tendermint/tendermint/node/node.go:769 +0x132 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0001ea240, 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(0xc000629500, 0x7fdb52f96358, 0xc0002b5030, 0xc00000daa0) 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 188 [semacquire]: sync.runtime_SemacquireMutex(0xc00026b1cc, 0x0, 0x1) runtime/sema.go:71 +0x47 sync.(*Mutex).lockSlow(0xc00026b1c8) sync/mutex.go:138 +0x105 sync.(*Mutex).Lock(...) sync/mutex.go:81 sync.(*RWMutex).Lock(0xc00026b1c8) sync/rwmutex.go:111 +0x90 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdate(0xc00026b080, 0xc000650008, 0x28, 0x124de90, 0x4) github.com/tendermint/tendermint/internal/statesync/reactor.go:849 +0x1a5 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdates(0xc00026b080) github.com/tendermint/tendermint/internal/statesync/reactor.go:883 +0xab created by github.com/tendermint/tendermint/internal/statesync.(*Reactor.OnStart github.com/tendermint/tendermint/internal/statesync/reactor.go:219 +0xcd) ```
3 years ago
statesync: remove deadlock on init fail (#7029) When statesync is stopped during shutdown, it has the possibility of deadlocking. A dump of goroutines reveals that this is related to the peerUpdates channel not returning anything on its `Done()` channel when `OnStop` is called. As this is occuring, `processPeerUpdate` is attempting to acquire the reactor lock. It appears that this lock can never be acquired. I looked for the places where the lock may remain locked accidentally and cleaned them up in hopes to eradicate the issue. Dumps of the relevant goroutines may be found below. Note that the line numbers below are relative to the code in the `v0.35.0-rc1` tag. ``` goroutine 36 [chan receive]: github.com/tendermint/tendermint/internal/statesync.(*Reactor).OnStop(0xc00058f200) github.com/tendermint/tendermint/internal/statesync/reactor.go:243 +0x117 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00058f200, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc0001ea240) github.com/tendermint/tendermint/node/node.go:769 +0x132 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0001ea240, 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(0xc000629500, 0x7fdb52f96358, 0xc0002b5030, 0xc00000daa0) 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 188 [semacquire]: sync.runtime_SemacquireMutex(0xc00026b1cc, 0x0, 0x1) runtime/sema.go:71 +0x47 sync.(*Mutex).lockSlow(0xc00026b1c8) sync/mutex.go:138 +0x105 sync.(*Mutex).Lock(...) sync/mutex.go:81 sync.(*RWMutex).Lock(0xc00026b1c8) sync/rwmutex.go:111 +0x90 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdate(0xc00026b080, 0xc000650008, 0x28, 0x124de90, 0x4) github.com/tendermint/tendermint/internal/statesync/reactor.go:849 +0x1a5 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdates(0xc00026b080) github.com/tendermint/tendermint/internal/statesync/reactor.go:883 +0xab created by github.com/tendermint/tendermint/internal/statesync.(*Reactor.OnStart github.com/tendermint/tendermint/internal/statesync/reactor.go:219 +0xcd) ```
3 years ago
statesync: remove deadlock on init fail (#7029) When statesync is stopped during shutdown, it has the possibility of deadlocking. A dump of goroutines reveals that this is related to the peerUpdates channel not returning anything on its `Done()` channel when `OnStop` is called. As this is occuring, `processPeerUpdate` is attempting to acquire the reactor lock. It appears that this lock can never be acquired. I looked for the places where the lock may remain locked accidentally and cleaned them up in hopes to eradicate the issue. Dumps of the relevant goroutines may be found below. Note that the line numbers below are relative to the code in the `v0.35.0-rc1` tag. ``` goroutine 36 [chan receive]: github.com/tendermint/tendermint/internal/statesync.(*Reactor).OnStop(0xc00058f200) github.com/tendermint/tendermint/internal/statesync/reactor.go:243 +0x117 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00058f200, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc0001ea240) github.com/tendermint/tendermint/node/node.go:769 +0x132 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0001ea240, 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(0xc000629500, 0x7fdb52f96358, 0xc0002b5030, 0xc00000daa0) 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 188 [semacquire]: sync.runtime_SemacquireMutex(0xc00026b1cc, 0x0, 0x1) runtime/sema.go:71 +0x47 sync.(*Mutex).lockSlow(0xc00026b1c8) sync/mutex.go:138 +0x105 sync.(*Mutex).Lock(...) sync/mutex.go:81 sync.(*RWMutex).Lock(0xc00026b1c8) sync/rwmutex.go:111 +0x90 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdate(0xc00026b080, 0xc000650008, 0x28, 0x124de90, 0x4) github.com/tendermint/tendermint/internal/statesync/reactor.go:849 +0x1a5 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdates(0xc00026b080) github.com/tendermint/tendermint/internal/statesync/reactor.go:883 +0xab created by github.com/tendermint/tendermint/internal/statesync.(*Reactor.OnStart github.com/tendermint/tendermint/internal/statesync/reactor.go:219 +0xcd) ```
3 years ago
statesync: remove deadlock on init fail (#7029) When statesync is stopped during shutdown, it has the possibility of deadlocking. A dump of goroutines reveals that this is related to the peerUpdates channel not returning anything on its `Done()` channel when `OnStop` is called. As this is occuring, `processPeerUpdate` is attempting to acquire the reactor lock. It appears that this lock can never be acquired. I looked for the places where the lock may remain locked accidentally and cleaned them up in hopes to eradicate the issue. Dumps of the relevant goroutines may be found below. Note that the line numbers below are relative to the code in the `v0.35.0-rc1` tag. ``` goroutine 36 [chan receive]: github.com/tendermint/tendermint/internal/statesync.(*Reactor).OnStop(0xc00058f200) github.com/tendermint/tendermint/internal/statesync/reactor.go:243 +0x117 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc00058f200, 0x0, 0x0) github.com/tendermint/tendermint/libs/service/service.go:171 +0x323 github.com/tendermint/tendermint/node.(*nodeImpl).OnStop(0xc0001ea240) github.com/tendermint/tendermint/node/node.go:769 +0x132 github.com/tendermint/tendermint/libs/service.(*BaseService).Stop(0xc0001ea240, 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(0xc000629500, 0x7fdb52f96358, 0xc0002b5030, 0xc00000daa0) 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 188 [semacquire]: sync.runtime_SemacquireMutex(0xc00026b1cc, 0x0, 0x1) runtime/sema.go:71 +0x47 sync.(*Mutex).lockSlow(0xc00026b1c8) sync/mutex.go:138 +0x105 sync.(*Mutex).Lock(...) sync/mutex.go:81 sync.(*RWMutex).Lock(0xc00026b1c8) sync/rwmutex.go:111 +0x90 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdate(0xc00026b080, 0xc000650008, 0x28, 0x124de90, 0x4) github.com/tendermint/tendermint/internal/statesync/reactor.go:849 +0x1a5 github.com/tendermint/tendermint/internal/statesync.(*Reactor).processPeerUpdates(0xc00026b080) github.com/tendermint/tendermint/internal/statesync/reactor.go:883 +0xab created by github.com/tendermint/tendermint/internal/statesync.(*Reactor.OnStart github.com/tendermint/tendermint/internal/statesync/reactor.go:219 +0xcd) ```
3 years ago
  1. package statesync
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "reflect"
  8. "runtime/debug"
  9. "sort"
  10. "sync"
  11. "time"
  12. abci "github.com/tendermint/tendermint/abci/types"
  13. "github.com/tendermint/tendermint/config"
  14. "github.com/tendermint/tendermint/internal/p2p"
  15. "github.com/tendermint/tendermint/internal/proxy"
  16. sm "github.com/tendermint/tendermint/internal/state"
  17. "github.com/tendermint/tendermint/internal/store"
  18. "github.com/tendermint/tendermint/libs/log"
  19. "github.com/tendermint/tendermint/libs/service"
  20. "github.com/tendermint/tendermint/light"
  21. "github.com/tendermint/tendermint/light/provider"
  22. ssproto "github.com/tendermint/tendermint/proto/tendermint/statesync"
  23. "github.com/tendermint/tendermint/types"
  24. )
  25. var (
  26. _ service.Service = (*Reactor)(nil)
  27. _ p2p.Wrapper = (*ssproto.Message)(nil)
  28. )
  29. const (
  30. // SnapshotChannel exchanges snapshot metadata
  31. SnapshotChannel = p2p.ChannelID(0x60)
  32. // ChunkChannel exchanges chunk contents
  33. ChunkChannel = p2p.ChannelID(0x61)
  34. // LightBlockChannel exchanges light blocks
  35. LightBlockChannel = p2p.ChannelID(0x62)
  36. // ParamsChannel exchanges consensus params
  37. ParamsChannel = p2p.ChannelID(0x63)
  38. // recentSnapshots is the number of recent snapshots to send and receive per peer.
  39. recentSnapshots = 10
  40. // snapshotMsgSize is the maximum size of a snapshotResponseMessage
  41. snapshotMsgSize = int(4e6) // ~4MB
  42. // chunkMsgSize is the maximum size of a chunkResponseMessage
  43. chunkMsgSize = int(16e6) // ~16MB
  44. // lightBlockMsgSize is the maximum size of a lightBlockResponseMessage
  45. lightBlockMsgSize = int(1e7) // ~1MB
  46. // paramMsgSize is the maximum size of a paramsResponseMessage
  47. paramMsgSize = int(1e5) // ~100kb
  48. // lightBlockResponseTimeout is how long the dispatcher waits for a peer to
  49. // return a light block
  50. lightBlockResponseTimeout = 10 * time.Second
  51. // consensusParamsResponseTimeout is the time the p2p state provider waits
  52. // before performing a secondary call
  53. consensusParamsResponseTimeout = 5 * time.Second
  54. // maxLightBlockRequestRetries is the amount of retries acceptable before
  55. // the backfill process aborts
  56. maxLightBlockRequestRetries = 20
  57. )
  58. func GetChannelDescriptors() []*p2p.ChannelDescriptor {
  59. return []*p2p.ChannelDescriptor{
  60. {
  61. ID: SnapshotChannel,
  62. MessageType: new(ssproto.Message),
  63. Priority: 6,
  64. SendQueueCapacity: 10,
  65. RecvMessageCapacity: snapshotMsgSize,
  66. RecvBufferCapacity: 128,
  67. },
  68. {
  69. ID: ChunkChannel,
  70. Priority: 3,
  71. MessageType: new(ssproto.Message),
  72. SendQueueCapacity: 4,
  73. RecvMessageCapacity: chunkMsgSize,
  74. RecvBufferCapacity: 128,
  75. },
  76. {
  77. ID: LightBlockChannel,
  78. MessageType: new(ssproto.Message),
  79. Priority: 5,
  80. SendQueueCapacity: 10,
  81. RecvMessageCapacity: lightBlockMsgSize,
  82. RecvBufferCapacity: 128,
  83. },
  84. {
  85. ID: ParamsChannel,
  86. MessageType: new(ssproto.Message),
  87. Priority: 2,
  88. SendQueueCapacity: 10,
  89. RecvMessageCapacity: paramMsgSize,
  90. RecvBufferCapacity: 128,
  91. },
  92. }
  93. }
  94. // Metricer defines an interface used for the rpc sync info query, please see statesync.metrics
  95. // for the details.
  96. type Metricer interface {
  97. TotalSnapshots() int64
  98. ChunkProcessAvgTime() time.Duration
  99. SnapshotHeight() int64
  100. SnapshotChunksCount() int64
  101. SnapshotChunksTotal() int64
  102. BackFilledBlocks() int64
  103. BackFillBlocksTotal() int64
  104. }
  105. // Reactor handles state sync, both restoring snapshots for the local node and
  106. // serving snapshots for other nodes.
  107. type Reactor struct {
  108. service.BaseService
  109. logger log.Logger
  110. chainID string
  111. initialHeight int64
  112. cfg config.StateSyncConfig
  113. stateStore sm.Store
  114. blockStore *store.BlockStore
  115. conn proxy.AppConnSnapshot
  116. connQuery proxy.AppConnQuery
  117. tempDir string
  118. snapshotCh *p2p.Channel
  119. chunkCh *p2p.Channel
  120. blockCh *p2p.Channel
  121. paramsCh *p2p.Channel
  122. peerUpdates *p2p.PeerUpdates
  123. // Dispatcher is used to multiplex light block requests and responses over multiple
  124. // peers used by the p2p state provider and in reverse sync.
  125. dispatcher *Dispatcher
  126. peers *peerList
  127. // These will only be set when a state sync is in progress. It is used to feed
  128. // received snapshots and chunks into the syncer and manage incoming and outgoing
  129. // providers.
  130. mtx sync.RWMutex
  131. syncer *syncer
  132. providers map[types.NodeID]*BlockProvider
  133. stateProvider StateProvider
  134. metrics *Metrics
  135. backfillBlockTotal int64
  136. backfilledBlocks int64
  137. }
  138. // NewReactor returns a reference to a new state sync reactor, which implements
  139. // the service.Service interface. It accepts a logger, connections for snapshots
  140. // and querying, references to p2p Channels and a channel to listen for peer
  141. // updates on. Note, the reactor will close all p2p Channels when stopping.
  142. func NewReactor(
  143. chainID string,
  144. initialHeight int64,
  145. cfg config.StateSyncConfig,
  146. logger log.Logger,
  147. conn proxy.AppConnSnapshot,
  148. connQuery proxy.AppConnQuery,
  149. snapshotCh, chunkCh, blockCh, paramsCh *p2p.Channel,
  150. peerUpdates *p2p.PeerUpdates,
  151. stateStore sm.Store,
  152. blockStore *store.BlockStore,
  153. tempDir string,
  154. ssMetrics *Metrics,
  155. ) *Reactor {
  156. r := &Reactor{
  157. logger: logger,
  158. chainID: chainID,
  159. initialHeight: initialHeight,
  160. cfg: cfg,
  161. conn: conn,
  162. connQuery: connQuery,
  163. snapshotCh: snapshotCh,
  164. chunkCh: chunkCh,
  165. blockCh: blockCh,
  166. paramsCh: paramsCh,
  167. peerUpdates: peerUpdates,
  168. tempDir: tempDir,
  169. stateStore: stateStore,
  170. blockStore: blockStore,
  171. peers: newPeerList(),
  172. dispatcher: NewDispatcher(blockCh),
  173. providers: make(map[types.NodeID]*BlockProvider),
  174. metrics: ssMetrics,
  175. }
  176. r.BaseService = *service.NewBaseService(logger, "StateSync", r)
  177. return r
  178. }
  179. // OnStart starts separate go routines for each p2p Channel and listens for
  180. // envelopes on each. In addition, it also listens for peer updates and handles
  181. // messages on that p2p channel accordingly. Note, we do not launch a go-routine to
  182. // handle individual envelopes as to not have to deal with bounding workers or pools.
  183. // The caller must be sure to execute OnStop to ensure the outbound p2p Channels are
  184. // closed. No error is returned.
  185. func (r *Reactor) OnStart(ctx context.Context) error {
  186. go r.processCh(ctx, r.snapshotCh, "snapshot")
  187. go r.processCh(ctx, r.chunkCh, "chunk")
  188. go r.processCh(ctx, r.blockCh, "light block")
  189. go r.processCh(ctx, r.paramsCh, "consensus params")
  190. go r.processPeerUpdates(ctx)
  191. return nil
  192. }
  193. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  194. // blocking until they all exit.
  195. func (r *Reactor) OnStop() {
  196. // tell the dispatcher to stop sending any more requests
  197. r.dispatcher.Close()
  198. }
  199. // Sync runs a state sync, fetching snapshots and providing chunks to the
  200. // application. At the close of the operation, Sync will bootstrap the state
  201. // store and persist the commit at that height so that either consensus or
  202. // blocksync can commence. It will then proceed to backfill the necessary amount
  203. // of historical blocks before participating in consensus
  204. func (r *Reactor) Sync(ctx context.Context) (sm.State, error) {
  205. // We need at least two peers (for cross-referencing of light blocks) before we can
  206. // begin state sync
  207. if err := r.waitForEnoughPeers(ctx, 2); err != nil {
  208. return sm.State{}, err
  209. }
  210. r.mtx.Lock()
  211. if r.syncer != nil {
  212. r.mtx.Unlock()
  213. return sm.State{}, errors.New("a state sync is already in progress")
  214. }
  215. if err := r.initStateProvider(ctx, r.chainID, r.initialHeight); err != nil {
  216. r.mtx.Unlock()
  217. return sm.State{}, err
  218. }
  219. r.syncer = newSyncer(
  220. r.cfg,
  221. r.logger,
  222. r.conn,
  223. r.connQuery,
  224. r.stateProvider,
  225. r.snapshotCh,
  226. r.chunkCh,
  227. r.tempDir,
  228. r.metrics,
  229. )
  230. r.mtx.Unlock()
  231. defer func() {
  232. r.mtx.Lock()
  233. // reset syncing objects at the close of Sync
  234. r.syncer = nil
  235. r.stateProvider = nil
  236. r.mtx.Unlock()
  237. }()
  238. requestSnapshotsHook := func() error {
  239. // request snapshots from all currently connected peers
  240. return r.snapshotCh.Send(ctx, p2p.Envelope{
  241. Broadcast: true,
  242. Message: &ssproto.SnapshotsRequest{},
  243. })
  244. }
  245. state, commit, err := r.syncer.SyncAny(ctx, r.cfg.DiscoveryTime, requestSnapshotsHook)
  246. if err != nil {
  247. return sm.State{}, err
  248. }
  249. err = r.stateStore.Bootstrap(state)
  250. if err != nil {
  251. return sm.State{}, fmt.Errorf("failed to bootstrap node with new state: %w", err)
  252. }
  253. err = r.blockStore.SaveSeenCommit(state.LastBlockHeight, commit)
  254. if err != nil {
  255. return sm.State{}, fmt.Errorf("failed to store last seen commit: %w", err)
  256. }
  257. err = r.Backfill(ctx, state)
  258. if err != nil {
  259. r.logger.Error("backfill failed. Proceeding optimistically...", "err", err)
  260. }
  261. return state, nil
  262. }
  263. // Backfill sequentially fetches, verifies and stores light blocks in reverse
  264. // order. It does not stop verifying blocks until reaching a block with a height
  265. // and time that is less or equal to the stopHeight and stopTime. The
  266. // trustedBlockID should be of the header at startHeight.
  267. func (r *Reactor) Backfill(ctx context.Context, state sm.State) error {
  268. params := state.ConsensusParams.Evidence
  269. stopHeight := state.LastBlockHeight - params.MaxAgeNumBlocks
  270. stopTime := state.LastBlockTime.Add(-params.MaxAgeDuration)
  271. // ensure that stop height doesn't go below the initial height
  272. if stopHeight < state.InitialHeight {
  273. stopHeight = state.InitialHeight
  274. // this essentially makes stop time a void criteria for termination
  275. stopTime = state.LastBlockTime
  276. }
  277. return r.backfill(
  278. ctx,
  279. state.ChainID,
  280. state.LastBlockHeight,
  281. stopHeight,
  282. state.InitialHeight,
  283. state.LastBlockID,
  284. stopTime,
  285. )
  286. }
  287. func (r *Reactor) backfill(
  288. ctx context.Context,
  289. chainID string,
  290. startHeight, stopHeight, initialHeight int64,
  291. trustedBlockID types.BlockID,
  292. stopTime time.Time,
  293. ) error {
  294. r.logger.Info("starting backfill process...", "startHeight", startHeight,
  295. "stopHeight", stopHeight, "stopTime", stopTime, "trustedBlockID", trustedBlockID)
  296. r.backfillBlockTotal = startHeight - stopHeight + 1
  297. r.metrics.BackFillBlocksTotal.Set(float64(r.backfillBlockTotal))
  298. const sleepTime = 1 * time.Second
  299. var (
  300. lastValidatorSet *types.ValidatorSet
  301. lastChangeHeight = startHeight
  302. )
  303. queue := newBlockQueue(startHeight, stopHeight, initialHeight, stopTime, maxLightBlockRequestRetries)
  304. // fetch light blocks across four workers. The aim with deploying concurrent
  305. // workers is to equate the network messaging time with the verification
  306. // time. Ideally we want the verification process to never have to be
  307. // waiting on blocks. If it takes 4s to retrieve a block and 1s to verify
  308. // it, then steady state involves four workers.
  309. for i := 0; i < int(r.cfg.Fetchers); i++ {
  310. ctxWithCancel, cancel := context.WithCancel(ctx)
  311. defer cancel()
  312. go func() {
  313. for {
  314. select {
  315. case <-ctx.Done():
  316. return
  317. case height := <-queue.nextHeight():
  318. // pop the next peer of the list to send a request to
  319. peer := r.peers.Pop(ctx)
  320. r.logger.Debug("fetching next block", "height", height, "peer", peer)
  321. subCtx, cancel := context.WithTimeout(ctxWithCancel, lightBlockResponseTimeout)
  322. defer cancel()
  323. lb, err := func() (*types.LightBlock, error) {
  324. defer cancel()
  325. // request the light block with a timeout
  326. return r.dispatcher.LightBlock(subCtx, height, peer)
  327. }()
  328. // once the peer has returned a value, add it back to the peer list to be used again
  329. r.peers.Append(peer)
  330. if errors.Is(err, context.Canceled) {
  331. return
  332. }
  333. if err != nil {
  334. queue.retry(height)
  335. if errors.Is(err, errNoConnectedPeers) {
  336. r.logger.Info("backfill: no connected peers to fetch light blocks from; sleeping...",
  337. "sleepTime", sleepTime)
  338. time.Sleep(sleepTime)
  339. } else {
  340. // we don't punish the peer as it might just have not responded in time
  341. r.logger.Info("backfill: error with fetching light block",
  342. "height", height, "err", err)
  343. }
  344. continue
  345. }
  346. if lb == nil {
  347. r.logger.Info("backfill: peer didn't have block, fetching from another peer", "height", height)
  348. queue.retry(height)
  349. // As we are fetching blocks backwards, if this node doesn't have the block it likely doesn't
  350. // have any prior ones, thus we remove it from the peer list.
  351. r.peers.Remove(peer)
  352. continue
  353. }
  354. // run a validate basic. This checks the validator set and commit
  355. // hashes line up
  356. err = lb.ValidateBasic(chainID)
  357. if err != nil || lb.Height != height {
  358. r.logger.Info("backfill: fetched light block failed validate basic, removing peer...",
  359. "err", err, "height", height)
  360. queue.retry(height)
  361. if serr := r.blockCh.SendError(ctx, p2p.PeerError{
  362. NodeID: peer,
  363. Err: fmt.Errorf("received invalid light block: %w", err),
  364. }); serr != nil {
  365. return
  366. }
  367. continue
  368. }
  369. // add block to queue to be verified
  370. queue.add(lightBlockResponse{
  371. block: lb,
  372. peer: peer,
  373. })
  374. r.logger.Debug("backfill: added light block to processing queue", "height", height)
  375. case <-queue.done():
  376. return
  377. }
  378. }
  379. }()
  380. }
  381. // verify all light blocks
  382. for {
  383. select {
  384. case <-ctx.Done():
  385. queue.close()
  386. return nil
  387. case resp := <-queue.verifyNext():
  388. // validate the header hash. We take the last block id of the
  389. // previous header (i.e. one height above) as the trusted hash which
  390. // we equate to. ValidatorsHash and CommitHash have already been
  391. // checked in the `ValidateBasic`
  392. if w, g := trustedBlockID.Hash, resp.block.Hash(); !bytes.Equal(w, g) {
  393. r.logger.Info("received invalid light block. header hash doesn't match trusted LastBlockID",
  394. "trustedHash", w, "receivedHash", g, "height", resp.block.Height)
  395. if err := r.blockCh.SendError(ctx, p2p.PeerError{
  396. NodeID: resp.peer,
  397. Err: fmt.Errorf("received invalid light block. Expected hash %v, got: %v", w, g),
  398. }); err != nil {
  399. return nil
  400. }
  401. queue.retry(resp.block.Height)
  402. continue
  403. }
  404. // save the signed headers
  405. if err := r.blockStore.SaveSignedHeader(resp.block.SignedHeader, trustedBlockID); err != nil {
  406. return err
  407. }
  408. // check if there has been a change in the validator set
  409. if lastValidatorSet != nil && !bytes.Equal(resp.block.Header.ValidatorsHash, resp.block.Header.NextValidatorsHash) {
  410. // save all the heights that the last validator set was the same
  411. if err := r.stateStore.SaveValidatorSets(resp.block.Height+1, lastChangeHeight, lastValidatorSet); err != nil {
  412. return err
  413. }
  414. // update the lastChangeHeight
  415. lastChangeHeight = resp.block.Height
  416. }
  417. trustedBlockID = resp.block.LastBlockID
  418. queue.success()
  419. r.logger.Info("backfill: verified and stored light block", "height", resp.block.Height)
  420. lastValidatorSet = resp.block.ValidatorSet
  421. r.backfilledBlocks++
  422. r.metrics.BackFilledBlocks.Add(1)
  423. // The block height might be less than the stopHeight because of the stopTime condition
  424. // hasn't been fulfilled.
  425. if resp.block.Height < stopHeight {
  426. r.backfillBlockTotal++
  427. r.metrics.BackFillBlocksTotal.Set(float64(r.backfillBlockTotal))
  428. }
  429. case <-queue.done():
  430. if err := queue.error(); err != nil {
  431. return err
  432. }
  433. // save the final batch of validators
  434. if err := r.stateStore.SaveValidatorSets(queue.terminal.Height, lastChangeHeight, lastValidatorSet); err != nil {
  435. return err
  436. }
  437. r.logger.Info("successfully completed backfill process", "endHeight", queue.terminal.Height)
  438. return nil
  439. }
  440. }
  441. }
  442. // handleSnapshotMessage handles envelopes sent from peers on the
  443. // SnapshotChannel. It returns an error only if the Envelope.Message is unknown
  444. // for this channel. This should never be called outside of handleMessage.
  445. func (r *Reactor) handleSnapshotMessage(ctx context.Context, envelope *p2p.Envelope) error {
  446. logger := r.logger.With("peer", envelope.From)
  447. switch msg := envelope.Message.(type) {
  448. case *ssproto.SnapshotsRequest:
  449. snapshots, err := r.recentSnapshots(ctx, recentSnapshots)
  450. if err != nil {
  451. logger.Error("failed to fetch snapshots", "err", err)
  452. return nil
  453. }
  454. for _, snapshot := range snapshots {
  455. logger.Info(
  456. "advertising snapshot",
  457. "height", snapshot.Height,
  458. "format", snapshot.Format,
  459. "peer", envelope.From,
  460. )
  461. if err := r.snapshotCh.Send(ctx, p2p.Envelope{
  462. To: envelope.From,
  463. Message: &ssproto.SnapshotsResponse{
  464. Height: snapshot.Height,
  465. Format: snapshot.Format,
  466. Chunks: snapshot.Chunks,
  467. Hash: snapshot.Hash,
  468. Metadata: snapshot.Metadata,
  469. },
  470. }); err != nil {
  471. return err
  472. }
  473. }
  474. case *ssproto.SnapshotsResponse:
  475. r.mtx.RLock()
  476. defer r.mtx.RUnlock()
  477. if r.syncer == nil {
  478. logger.Debug("received unexpected snapshot; no state sync in progress")
  479. return nil
  480. }
  481. logger.Info("received snapshot", "height", msg.Height, "format", msg.Format)
  482. _, err := r.syncer.AddSnapshot(envelope.From, &snapshot{
  483. Height: msg.Height,
  484. Format: msg.Format,
  485. Chunks: msg.Chunks,
  486. Hash: msg.Hash,
  487. Metadata: msg.Metadata,
  488. })
  489. if err != nil {
  490. logger.Error(
  491. "failed to add snapshot",
  492. "height", msg.Height,
  493. "format", msg.Format,
  494. "err", err,
  495. "channel", r.snapshotCh.ID,
  496. )
  497. return nil
  498. }
  499. logger.Info("added snapshot", "height", msg.Height, "format", msg.Format)
  500. default:
  501. return fmt.Errorf("received unknown message: %T", msg)
  502. }
  503. return nil
  504. }
  505. // handleChunkMessage handles envelopes sent from peers on the ChunkChannel.
  506. // It returns an error only if the Envelope.Message is unknown for this channel.
  507. // This should never be called outside of handleMessage.
  508. func (r *Reactor) handleChunkMessage(ctx context.Context, envelope *p2p.Envelope) error {
  509. switch msg := envelope.Message.(type) {
  510. case *ssproto.ChunkRequest:
  511. r.logger.Debug(
  512. "received chunk request",
  513. "height", msg.Height,
  514. "format", msg.Format,
  515. "chunk", msg.Index,
  516. "peer", envelope.From,
  517. )
  518. resp, err := r.conn.LoadSnapshotChunkSync(ctx, abci.RequestLoadSnapshotChunk{
  519. Height: msg.Height,
  520. Format: msg.Format,
  521. Chunk: msg.Index,
  522. })
  523. if err != nil {
  524. r.logger.Error(
  525. "failed to load chunk",
  526. "height", msg.Height,
  527. "format", msg.Format,
  528. "chunk", msg.Index,
  529. "err", err,
  530. "peer", envelope.From,
  531. )
  532. return nil
  533. }
  534. r.logger.Debug(
  535. "sending chunk",
  536. "height", msg.Height,
  537. "format", msg.Format,
  538. "chunk", msg.Index,
  539. "peer", envelope.From,
  540. )
  541. if err := r.chunkCh.Send(ctx, p2p.Envelope{
  542. To: envelope.From,
  543. Message: &ssproto.ChunkResponse{
  544. Height: msg.Height,
  545. Format: msg.Format,
  546. Index: msg.Index,
  547. Chunk: resp.Chunk,
  548. Missing: resp.Chunk == nil,
  549. },
  550. }); err != nil {
  551. return err
  552. }
  553. case *ssproto.ChunkResponse:
  554. r.mtx.RLock()
  555. defer r.mtx.RUnlock()
  556. if r.syncer == nil {
  557. r.logger.Debug("received unexpected chunk; no state sync in progress", "peer", envelope.From)
  558. return nil
  559. }
  560. r.logger.Debug(
  561. "received chunk; adding to sync",
  562. "height", msg.Height,
  563. "format", msg.Format,
  564. "chunk", msg.Index,
  565. "peer", envelope.From,
  566. )
  567. _, err := r.syncer.AddChunk(&chunk{
  568. Height: msg.Height,
  569. Format: msg.Format,
  570. Index: msg.Index,
  571. Chunk: msg.Chunk,
  572. Sender: envelope.From,
  573. })
  574. if err != nil {
  575. r.logger.Error(
  576. "failed to add chunk",
  577. "height", msg.Height,
  578. "format", msg.Format,
  579. "chunk", msg.Index,
  580. "err", err,
  581. "peer", envelope.From,
  582. )
  583. return nil
  584. }
  585. default:
  586. return fmt.Errorf("received unknown message: %T", msg)
  587. }
  588. return nil
  589. }
  590. func (r *Reactor) handleLightBlockMessage(ctx context.Context, envelope *p2p.Envelope) error {
  591. switch msg := envelope.Message.(type) {
  592. case *ssproto.LightBlockRequest:
  593. r.logger.Info("received light block request", "height", msg.Height)
  594. lb, err := r.fetchLightBlock(msg.Height)
  595. if err != nil {
  596. r.logger.Error("failed to retrieve light block", "err", err, "height", msg.Height)
  597. return err
  598. }
  599. if lb == nil {
  600. if err := r.blockCh.Send(ctx, p2p.Envelope{
  601. To: envelope.From,
  602. Message: &ssproto.LightBlockResponse{
  603. LightBlock: nil,
  604. },
  605. }); err != nil {
  606. return err
  607. }
  608. return nil
  609. }
  610. lbproto, err := lb.ToProto()
  611. if err != nil {
  612. r.logger.Error("marshaling light block to proto", "err", err)
  613. return nil
  614. }
  615. // NOTE: If we don't have the light block we will send a nil light block
  616. // back to the requested node, indicating that we don't have it.
  617. if err := r.blockCh.Send(ctx, p2p.Envelope{
  618. To: envelope.From,
  619. Message: &ssproto.LightBlockResponse{
  620. LightBlock: lbproto,
  621. },
  622. }); err != nil {
  623. return err
  624. }
  625. case *ssproto.LightBlockResponse:
  626. var height int64
  627. if msg.LightBlock != nil {
  628. height = msg.LightBlock.SignedHeader.Header.Height
  629. }
  630. r.logger.Info("received light block response", "peer", envelope.From, "height", height)
  631. if err := r.dispatcher.Respond(msg.LightBlock, envelope.From); err != nil {
  632. r.logger.Error("error processing light block response", "err", err, "height", height)
  633. }
  634. default:
  635. return fmt.Errorf("received unknown message: %T", msg)
  636. }
  637. return nil
  638. }
  639. func (r *Reactor) handleParamsMessage(ctx context.Context, envelope *p2p.Envelope) error {
  640. switch msg := envelope.Message.(type) {
  641. case *ssproto.ParamsRequest:
  642. r.logger.Debug("received consensus params request", "height", msg.Height)
  643. cp, err := r.stateStore.LoadConsensusParams(int64(msg.Height))
  644. if err != nil {
  645. r.logger.Error("failed to fetch requested consensus params", "err", err, "height", msg.Height)
  646. return nil
  647. }
  648. cpproto := cp.ToProto()
  649. if err := r.paramsCh.Send(ctx, p2p.Envelope{
  650. To: envelope.From,
  651. Message: &ssproto.ParamsResponse{
  652. Height: msg.Height,
  653. ConsensusParams: cpproto,
  654. },
  655. }); err != nil {
  656. return err
  657. }
  658. case *ssproto.ParamsResponse:
  659. r.mtx.RLock()
  660. defer r.mtx.RUnlock()
  661. r.logger.Debug("received consensus params response", "height", msg.Height)
  662. cp := types.ConsensusParamsFromProto(msg.ConsensusParams)
  663. if sp, ok := r.stateProvider.(*stateProviderP2P); ok {
  664. select {
  665. case sp.paramsRecvCh <- cp:
  666. case <-time.After(time.Second):
  667. return errors.New("failed to send consensus params, stateprovider not ready for response")
  668. }
  669. } else {
  670. r.logger.Debug("received unexpected params response; using RPC state provider", "peer", envelope.From)
  671. }
  672. default:
  673. return fmt.Errorf("received unknown message: %T", msg)
  674. }
  675. return nil
  676. }
  677. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  678. // It will handle errors and any possible panics gracefully. A caller can handle
  679. // any error returned by sending a PeerError on the respective channel.
  680. func (r *Reactor) handleMessage(ctx context.Context, chID p2p.ChannelID, envelope *p2p.Envelope) (err error) {
  681. defer func() {
  682. if e := recover(); e != nil {
  683. err = fmt.Errorf("panic in processing message: %v", e)
  684. r.logger.Error(
  685. "recovering from processing message panic",
  686. "err", err,
  687. "stack", string(debug.Stack()),
  688. )
  689. }
  690. }()
  691. r.logger.Debug("received message", "message", reflect.TypeOf(envelope.Message), "peer", envelope.From)
  692. switch chID {
  693. case SnapshotChannel:
  694. err = r.handleSnapshotMessage(ctx, envelope)
  695. case ChunkChannel:
  696. err = r.handleChunkMessage(ctx, envelope)
  697. case LightBlockChannel:
  698. err = r.handleLightBlockMessage(ctx, envelope)
  699. case ParamsChannel:
  700. err = r.handleParamsMessage(ctx, envelope)
  701. default:
  702. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  703. }
  704. return err
  705. }
  706. // processCh routes state sync messages to their respective handlers. Any error
  707. // encountered during message execution will result in a PeerError being sent on
  708. // the respective channel. When the reactor is stopped, we will catch the signal
  709. // and close the p2p Channel gracefully.
  710. func (r *Reactor) processCh(ctx context.Context, ch *p2p.Channel, chName string) {
  711. iter := ch.Receive(ctx)
  712. for iter.Next(ctx) {
  713. envelope := iter.Envelope()
  714. if err := r.handleMessage(ctx, ch.ID, envelope); err != nil {
  715. r.logger.Error("failed to process message",
  716. "err", err,
  717. "channel", chName,
  718. "ch_id", ch.ID,
  719. "envelope", envelope)
  720. if serr := ch.SendError(ctx, p2p.PeerError{
  721. NodeID: envelope.From,
  722. Err: err,
  723. }); serr != nil {
  724. return
  725. }
  726. }
  727. }
  728. }
  729. // processPeerUpdate processes a PeerUpdate, returning an error upon failing to
  730. // handle the PeerUpdate or if a panic is recovered.
  731. func (r *Reactor) processPeerUpdate(ctx context.Context, peerUpdate p2p.PeerUpdate) {
  732. r.logger.Info("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  733. switch peerUpdate.Status {
  734. case p2p.PeerStatusUp:
  735. r.peers.Append(peerUpdate.NodeID)
  736. case p2p.PeerStatusDown:
  737. r.peers.Remove(peerUpdate.NodeID)
  738. }
  739. r.mtx.Lock()
  740. defer r.mtx.Unlock()
  741. if r.syncer == nil {
  742. return
  743. }
  744. switch peerUpdate.Status {
  745. case p2p.PeerStatusUp:
  746. newProvider := NewBlockProvider(peerUpdate.NodeID, r.chainID, r.dispatcher)
  747. r.providers[peerUpdate.NodeID] = newProvider
  748. err := r.syncer.AddPeer(ctx, peerUpdate.NodeID)
  749. if err != nil {
  750. r.logger.Error("error adding peer to syncer", "error", err)
  751. return
  752. }
  753. if sp, ok := r.stateProvider.(*stateProviderP2P); ok {
  754. // we do this in a separate routine to not block whilst waiting for the light client to finish
  755. // whatever call it's currently executing
  756. go sp.addProvider(newProvider)
  757. }
  758. case p2p.PeerStatusDown:
  759. delete(r.providers, peerUpdate.NodeID)
  760. r.syncer.RemovePeer(peerUpdate.NodeID)
  761. }
  762. r.logger.Info("processed peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  763. }
  764. // processPeerUpdates initiates a blocking process where we listen for and handle
  765. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  766. // close the p2p PeerUpdatesCh gracefully.
  767. func (r *Reactor) processPeerUpdates(ctx context.Context) {
  768. for {
  769. select {
  770. case <-ctx.Done():
  771. r.logger.Debug("stopped listening on peer updates channel; closing...")
  772. return
  773. case peerUpdate := <-r.peerUpdates.Updates():
  774. r.processPeerUpdate(ctx, peerUpdate)
  775. }
  776. }
  777. }
  778. // recentSnapshots fetches the n most recent snapshots from the app
  779. func (r *Reactor) recentSnapshots(ctx context.Context, n uint32) ([]*snapshot, error) {
  780. resp, err := r.conn.ListSnapshotsSync(ctx, abci.RequestListSnapshots{})
  781. if err != nil {
  782. return nil, err
  783. }
  784. sort.Slice(resp.Snapshots, func(i, j int) bool {
  785. a := resp.Snapshots[i]
  786. b := resp.Snapshots[j]
  787. switch {
  788. case a.Height > b.Height:
  789. return true
  790. case a.Height == b.Height && a.Format > b.Format:
  791. return true
  792. default:
  793. return false
  794. }
  795. })
  796. snapshots := make([]*snapshot, 0, n)
  797. for i, s := range resp.Snapshots {
  798. if i >= recentSnapshots {
  799. break
  800. }
  801. snapshots = append(snapshots, &snapshot{
  802. Height: s.Height,
  803. Format: s.Format,
  804. Chunks: s.Chunks,
  805. Hash: s.Hash,
  806. Metadata: s.Metadata,
  807. })
  808. }
  809. return snapshots, nil
  810. }
  811. // fetchLightBlock works out whether the node has a light block at a particular
  812. // height and if so returns it so it can be gossiped to peers
  813. func (r *Reactor) fetchLightBlock(height uint64) (*types.LightBlock, error) {
  814. h := int64(height)
  815. blockMeta := r.blockStore.LoadBlockMeta(h)
  816. if blockMeta == nil {
  817. return nil, nil
  818. }
  819. commit := r.blockStore.LoadBlockCommit(h)
  820. if commit == nil {
  821. return nil, nil
  822. }
  823. vals, err := r.stateStore.LoadValidators(h)
  824. if err != nil {
  825. return nil, err
  826. }
  827. if vals == nil {
  828. return nil, nil
  829. }
  830. return &types.LightBlock{
  831. SignedHeader: &types.SignedHeader{
  832. Header: &blockMeta.Header,
  833. Commit: commit,
  834. },
  835. ValidatorSet: vals,
  836. }, nil
  837. }
  838. func (r *Reactor) waitForEnoughPeers(ctx context.Context, numPeers int) error {
  839. startAt := time.Now()
  840. t := time.NewTicker(100 * time.Millisecond)
  841. defer t.Stop()
  842. logT := time.NewTicker(time.Minute)
  843. defer logT.Stop()
  844. var iter int
  845. for r.peers.Len() < numPeers {
  846. iter++
  847. select {
  848. case <-ctx.Done():
  849. return fmt.Errorf("operation canceled while waiting for peers after %.2fs [%d/%d]",
  850. time.Since(startAt).Seconds(), r.peers.Len(), numPeers)
  851. case <-t.C:
  852. continue
  853. case <-logT.C:
  854. r.logger.Info("waiting for sufficient peers to start statesync",
  855. "duration", time.Since(startAt).String(),
  856. "target", numPeers,
  857. "peers", r.peers.Len(),
  858. "iters", iter,
  859. )
  860. continue
  861. }
  862. }
  863. return nil
  864. }
  865. func (r *Reactor) initStateProvider(ctx context.Context, chainID string, initialHeight int64) error {
  866. var err error
  867. to := light.TrustOptions{
  868. Period: r.cfg.TrustPeriod,
  869. Height: r.cfg.TrustHeight,
  870. Hash: r.cfg.TrustHashBytes(),
  871. }
  872. spLogger := r.logger.With("module", "stateprovider")
  873. spLogger.Info("initializing state provider", "trustPeriod", to.Period,
  874. "trustHeight", to.Height, "useP2P", r.cfg.UseP2P)
  875. if r.cfg.UseP2P {
  876. if err := r.waitForEnoughPeers(ctx, 2); err != nil {
  877. return err
  878. }
  879. peers := r.peers.All()
  880. providers := make([]provider.Provider, len(peers))
  881. for idx, p := range peers {
  882. providers[idx] = NewBlockProvider(p, chainID, r.dispatcher)
  883. }
  884. r.stateProvider, err = NewP2PStateProvider(ctx, chainID, initialHeight, providers, to, r.paramsCh, spLogger)
  885. if err != nil {
  886. return fmt.Errorf("failed to initialize P2P state provider: %w", err)
  887. }
  888. } else {
  889. r.stateProvider, err = NewRPCStateProvider(ctx, chainID, initialHeight, r.cfg.RPCServers, to, spLogger)
  890. if err != nil {
  891. return fmt.Errorf("failed to initialize RPC state provider: %w", err)
  892. }
  893. }
  894. return nil
  895. }
  896. func (r *Reactor) TotalSnapshots() int64 {
  897. r.mtx.RLock()
  898. defer r.mtx.RUnlock()
  899. if r.syncer != nil && r.syncer.snapshots != nil {
  900. return int64(len(r.syncer.snapshots.snapshots))
  901. }
  902. return 0
  903. }
  904. func (r *Reactor) ChunkProcessAvgTime() time.Duration {
  905. r.mtx.RLock()
  906. defer r.mtx.RUnlock()
  907. if r.syncer != nil {
  908. return time.Duration(r.syncer.avgChunkTime)
  909. }
  910. return time.Duration(0)
  911. }
  912. func (r *Reactor) SnapshotHeight() int64 {
  913. r.mtx.RLock()
  914. defer r.mtx.RUnlock()
  915. if r.syncer != nil {
  916. return r.syncer.lastSyncedSnapshotHeight
  917. }
  918. return 0
  919. }
  920. func (r *Reactor) SnapshotChunksCount() int64 {
  921. r.mtx.RLock()
  922. defer r.mtx.RUnlock()
  923. if r.syncer != nil && r.syncer.chunks != nil {
  924. return int64(r.syncer.chunks.numChunksReturned())
  925. }
  926. return 0
  927. }
  928. func (r *Reactor) SnapshotChunksTotal() int64 {
  929. r.mtx.RLock()
  930. defer r.mtx.RUnlock()
  931. if r.syncer != nil && r.syncer.processingSnapshot != nil {
  932. return int64(r.syncer.processingSnapshot.Chunks)
  933. }
  934. return 0
  935. }
  936. func (r *Reactor) BackFilledBlocks() int64 {
  937. r.mtx.RLock()
  938. defer r.mtx.RUnlock()
  939. return r.backfilledBlocks
  940. }
  941. func (r *Reactor) BackFillBlocksTotal() int64 {
  942. r.mtx.RLock()
  943. defer r.mtx.RUnlock()
  944. return r.backfillBlockTotal
  945. }