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.

561 lines
18 KiB

  1. package statesync
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "time"
  8. abci "github.com/tendermint/tendermint/abci/types"
  9. "github.com/tendermint/tendermint/config"
  10. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  11. "github.com/tendermint/tendermint/internal/p2p"
  12. "github.com/tendermint/tendermint/internal/proxy"
  13. sm "github.com/tendermint/tendermint/internal/state"
  14. "github.com/tendermint/tendermint/libs/log"
  15. "github.com/tendermint/tendermint/light"
  16. ssproto "github.com/tendermint/tendermint/proto/tendermint/statesync"
  17. "github.com/tendermint/tendermint/types"
  18. )
  19. const (
  20. // chunkTimeout is the timeout while waiting for the next chunk from the chunk queue.
  21. chunkTimeout = 2 * time.Minute
  22. // minimumDiscoveryTime is the lowest allowable time for a
  23. // SyncAny discovery time.
  24. minimumDiscoveryTime = 5 * time.Second
  25. )
  26. var (
  27. // errAbort is returned by Sync() when snapshot restoration is aborted.
  28. errAbort = errors.New("state sync aborted")
  29. // errRetrySnapshot is returned by Sync() when the snapshot should be retried.
  30. errRetrySnapshot = errors.New("retry snapshot")
  31. // errRejectSnapshot is returned by Sync() when the snapshot is rejected.
  32. errRejectSnapshot = errors.New("snapshot was rejected")
  33. // errRejectFormat is returned by Sync() when the snapshot format is rejected.
  34. errRejectFormat = errors.New("snapshot format was rejected")
  35. // errRejectSender is returned by Sync() when the snapshot sender is rejected.
  36. errRejectSender = errors.New("snapshot sender was rejected")
  37. // errVerifyFailed is returned by Sync() when app hash or last height
  38. // verification fails.
  39. errVerifyFailed = errors.New("verification with app failed")
  40. // errTimeout is returned by Sync() when we've waited too long to receive a chunk.
  41. errTimeout = errors.New("timed out waiting for chunk")
  42. // errNoSnapshots is returned by SyncAny() if no snapshots are found and discovery is disabled.
  43. errNoSnapshots = errors.New("no suitable snapshots found")
  44. )
  45. // syncer runs a state sync against an ABCI app. Use either SyncAny() to automatically attempt to
  46. // sync all snapshots in the pool (pausing to discover new ones), or Sync() to sync a specific
  47. // snapshot. Snapshots and chunks are fed via AddSnapshot() and AddChunk() as appropriate.
  48. type syncer struct {
  49. logger log.Logger
  50. stateProvider StateProvider
  51. conn proxy.AppConnSnapshot
  52. connQuery proxy.AppConnQuery
  53. snapshots *snapshotPool
  54. snapshotCh chan<- p2p.Envelope
  55. chunkCh chan<- p2p.Envelope
  56. tempDir string
  57. fetchers int32
  58. retryTimeout time.Duration
  59. mtx tmsync.RWMutex
  60. chunks *chunkQueue
  61. metrics *Metrics
  62. avgChunkTime int64
  63. lastSyncedSnapshotHeight int64
  64. processingSnapshot *snapshot
  65. }
  66. // newSyncer creates a new syncer.
  67. func newSyncer(
  68. cfg config.StateSyncConfig,
  69. logger log.Logger,
  70. conn proxy.AppConnSnapshot,
  71. connQuery proxy.AppConnQuery,
  72. stateProvider StateProvider,
  73. snapshotCh, chunkCh chan<- p2p.Envelope,
  74. tempDir string,
  75. metrics *Metrics,
  76. ) *syncer {
  77. return &syncer{
  78. logger: logger,
  79. stateProvider: stateProvider,
  80. conn: conn,
  81. connQuery: connQuery,
  82. snapshots: newSnapshotPool(),
  83. snapshotCh: snapshotCh,
  84. chunkCh: chunkCh,
  85. tempDir: tempDir,
  86. fetchers: cfg.Fetchers,
  87. retryTimeout: cfg.ChunkRequestTimeout,
  88. metrics: metrics,
  89. }
  90. }
  91. // AddChunk adds a chunk to the chunk queue, if any. It returns false if the chunk has already
  92. // been added to the queue, or an error if there's no sync in progress.
  93. func (s *syncer) AddChunk(chunk *chunk) (bool, error) {
  94. s.mtx.RLock()
  95. defer s.mtx.RUnlock()
  96. if s.chunks == nil {
  97. return false, errors.New("no state sync in progress")
  98. }
  99. added, err := s.chunks.Add(chunk)
  100. if err != nil {
  101. return false, err
  102. }
  103. if added {
  104. s.logger.Debug("Added chunk to queue", "height", chunk.Height, "format", chunk.Format,
  105. "chunk", chunk.Index)
  106. } else {
  107. s.logger.Debug("Ignoring duplicate chunk in queue", "height", chunk.Height, "format", chunk.Format,
  108. "chunk", chunk.Index)
  109. }
  110. return added, nil
  111. }
  112. // AddSnapshot adds a snapshot to the snapshot pool. It returns true if a new, previously unseen
  113. // snapshot was accepted and added.
  114. func (s *syncer) AddSnapshot(peerID types.NodeID, snapshot *snapshot) (bool, error) {
  115. added, err := s.snapshots.Add(peerID, snapshot)
  116. if err != nil {
  117. return false, err
  118. }
  119. if added {
  120. s.metrics.TotalSnapshots.Add(1)
  121. s.logger.Info("Discovered new snapshot", "height", snapshot.Height, "format", snapshot.Format,
  122. "hash", snapshot.Hash)
  123. }
  124. return added, nil
  125. }
  126. // AddPeer adds a peer to the pool. For now we just keep it simple and send a
  127. // single request to discover snapshots, later we may want to do retries and stuff.
  128. func (s *syncer) AddPeer(peerID types.NodeID) {
  129. s.logger.Debug("Requesting snapshots from peer", "peer", peerID)
  130. s.snapshotCh <- p2p.Envelope{
  131. To: peerID,
  132. Message: &ssproto.SnapshotsRequest{},
  133. }
  134. }
  135. // RemovePeer removes a peer from the pool.
  136. func (s *syncer) RemovePeer(peerID types.NodeID) {
  137. s.logger.Debug("Removing peer from sync", "peer", peerID)
  138. s.snapshots.RemovePeer(peerID)
  139. }
  140. // SyncAny tries to sync any of the snapshots in the snapshot pool, waiting to discover further
  141. // snapshots if none were found and discoveryTime > 0. It returns the latest state and block commit
  142. // which the caller must use to bootstrap the node.
  143. func (s *syncer) SyncAny(
  144. ctx context.Context,
  145. discoveryTime time.Duration,
  146. requestSnapshots func(),
  147. ) (sm.State, *types.Commit, error) {
  148. if discoveryTime != 0 && discoveryTime < minimumDiscoveryTime {
  149. discoveryTime = minimumDiscoveryTime
  150. }
  151. if discoveryTime > 0 {
  152. requestSnapshots()
  153. s.logger.Info(fmt.Sprintf("Discovering snapshots for %v", discoveryTime))
  154. time.Sleep(discoveryTime)
  155. }
  156. // The app may ask us to retry a snapshot restoration, in which case we need to reuse
  157. // the snapshot and chunk queue from the previous loop iteration.
  158. var (
  159. snapshot *snapshot
  160. chunks *chunkQueue
  161. err error
  162. )
  163. for {
  164. // If not nil, we're going to retry restoration of the same snapshot.
  165. if snapshot == nil {
  166. snapshot = s.snapshots.Best()
  167. chunks = nil
  168. }
  169. if snapshot == nil {
  170. if discoveryTime == 0 {
  171. return sm.State{}, nil, errNoSnapshots
  172. }
  173. s.logger.Info(fmt.Sprintf("Discovering snapshots for %v", discoveryTime))
  174. time.Sleep(discoveryTime)
  175. continue
  176. }
  177. if chunks == nil {
  178. chunks, err = newChunkQueue(snapshot, s.tempDir)
  179. if err != nil {
  180. return sm.State{}, nil, fmt.Errorf("failed to create chunk queue: %w", err)
  181. }
  182. defer chunks.Close() // in case we forget to close it elsewhere
  183. }
  184. s.processingSnapshot = snapshot
  185. s.metrics.SnapshotChunkTotal.Set(float64(snapshot.Chunks))
  186. newState, commit, err := s.Sync(ctx, snapshot, chunks)
  187. switch {
  188. case err == nil:
  189. s.metrics.SnapshotHeight.Set(float64(snapshot.Height))
  190. s.lastSyncedSnapshotHeight = int64(snapshot.Height)
  191. return newState, commit, nil
  192. case errors.Is(err, errAbort):
  193. return sm.State{}, nil, err
  194. case errors.Is(err, errRetrySnapshot):
  195. chunks.RetryAll()
  196. s.logger.Info("Retrying snapshot", "height", snapshot.Height, "format", snapshot.Format,
  197. "hash", snapshot.Hash)
  198. continue
  199. case errors.Is(err, errTimeout):
  200. s.snapshots.Reject(snapshot)
  201. s.logger.Error("Timed out waiting for snapshot chunks, rejected snapshot",
  202. "height", snapshot.Height, "format", snapshot.Format, "hash", snapshot.Hash)
  203. case errors.Is(err, errRejectSnapshot):
  204. s.snapshots.Reject(snapshot)
  205. s.logger.Info("Snapshot rejected", "height", snapshot.Height, "format", snapshot.Format,
  206. "hash", snapshot.Hash)
  207. case errors.Is(err, errRejectFormat):
  208. s.snapshots.RejectFormat(snapshot.Format)
  209. s.logger.Info("Snapshot format rejected", "format", snapshot.Format)
  210. case errors.Is(err, errRejectSender):
  211. s.logger.Info("Snapshot senders rejected", "height", snapshot.Height, "format", snapshot.Format,
  212. "hash", snapshot.Hash)
  213. for _, peer := range s.snapshots.GetPeers(snapshot) {
  214. s.snapshots.RejectPeer(peer)
  215. s.logger.Info("Snapshot sender rejected", "peer", peer)
  216. }
  217. default:
  218. return sm.State{}, nil, fmt.Errorf("snapshot restoration failed: %w", err)
  219. }
  220. // Discard snapshot and chunks for next iteration
  221. err = chunks.Close()
  222. if err != nil {
  223. s.logger.Error("Failed to clean up chunk queue", "err", err)
  224. }
  225. snapshot = nil
  226. chunks = nil
  227. s.processingSnapshot = nil
  228. }
  229. }
  230. // Sync executes a sync for a specific snapshot, returning the latest state and block commit which
  231. // the caller must use to bootstrap the node.
  232. func (s *syncer) Sync(ctx context.Context, snapshot *snapshot, chunks *chunkQueue) (sm.State, *types.Commit, error) {
  233. s.mtx.Lock()
  234. if s.chunks != nil {
  235. s.mtx.Unlock()
  236. return sm.State{}, nil, errors.New("a state sync is already in progress")
  237. }
  238. s.chunks = chunks
  239. s.mtx.Unlock()
  240. defer func() {
  241. s.mtx.Lock()
  242. s.chunks = nil
  243. s.mtx.Unlock()
  244. }()
  245. hctx, hcancel := context.WithTimeout(ctx, 30*time.Second)
  246. defer hcancel()
  247. // Fetch the app hash corresponding to the snapshot
  248. appHash, err := s.stateProvider.AppHash(hctx, snapshot.Height)
  249. if err != nil {
  250. // check if the main context was triggered
  251. if ctx.Err() != nil {
  252. return sm.State{}, nil, ctx.Err()
  253. }
  254. // catch the case where all the light client providers have been exhausted
  255. if err == light.ErrNoWitnesses {
  256. return sm.State{}, nil,
  257. fmt.Errorf("failed to get app hash at height %d. No witnesses remaining", snapshot.Height)
  258. }
  259. s.logger.Info("failed to get and verify tendermint state. Dropping snapshot and trying again",
  260. "err", err, "height", snapshot.Height)
  261. return sm.State{}, nil, errRejectSnapshot
  262. }
  263. snapshot.trustedAppHash = appHash
  264. // Offer snapshot to ABCI app.
  265. err = s.offerSnapshot(ctx, snapshot)
  266. if err != nil {
  267. return sm.State{}, nil, err
  268. }
  269. // Spawn chunk fetchers. They will terminate when the chunk queue is closed or context canceled.
  270. fetchCtx, cancel := context.WithCancel(ctx)
  271. defer cancel()
  272. fetchStartTime := time.Now()
  273. for i := int32(0); i < s.fetchers; i++ {
  274. go s.fetchChunks(fetchCtx, snapshot, chunks)
  275. }
  276. pctx, pcancel := context.WithTimeout(ctx, 1*time.Minute)
  277. defer pcancel()
  278. // Optimistically build new state, so we don't discover any light client failures at the end.
  279. state, err := s.stateProvider.State(pctx, snapshot.Height)
  280. if err != nil {
  281. // check if the main context was triggered
  282. if ctx.Err() != nil {
  283. return sm.State{}, nil, ctx.Err()
  284. }
  285. if err == light.ErrNoWitnesses {
  286. return sm.State{}, nil,
  287. fmt.Errorf("failed to get tendermint state at height %d. No witnesses remaining", snapshot.Height)
  288. }
  289. s.logger.Info("failed to get and verify tendermint state. Dropping snapshot and trying again",
  290. "err", err, "height", snapshot.Height)
  291. return sm.State{}, nil, errRejectSnapshot
  292. }
  293. commit, err := s.stateProvider.Commit(pctx, snapshot.Height)
  294. if err != nil {
  295. // check if the provider context exceeded the 10 second deadline
  296. if ctx.Err() != nil {
  297. return sm.State{}, nil, ctx.Err()
  298. }
  299. if err == light.ErrNoWitnesses {
  300. return sm.State{}, nil,
  301. fmt.Errorf("failed to get commit at height %d. No witnesses remaining", snapshot.Height)
  302. }
  303. s.logger.Info("failed to get and verify commit. Dropping snapshot and trying again",
  304. "err", err, "height", snapshot.Height)
  305. return sm.State{}, nil, errRejectSnapshot
  306. }
  307. // Restore snapshot
  308. err = s.applyChunks(ctx, chunks, fetchStartTime)
  309. if err != nil {
  310. return sm.State{}, nil, err
  311. }
  312. // Verify app and update app version
  313. appVersion, err := s.verifyApp(snapshot)
  314. if err != nil {
  315. return sm.State{}, nil, err
  316. }
  317. state.Version.Consensus.App = appVersion
  318. // Done! 🎉
  319. s.logger.Info("Snapshot restored", "height", snapshot.Height, "format", snapshot.Format,
  320. "hash", snapshot.Hash)
  321. return state, commit, nil
  322. }
  323. // offerSnapshot offers a snapshot to the app. It returns various errors depending on the app's
  324. // response, or nil if the snapshot was accepted.
  325. func (s *syncer) offerSnapshot(ctx context.Context, snapshot *snapshot) error {
  326. s.logger.Info("Offering snapshot to ABCI app", "height", snapshot.Height,
  327. "format", snapshot.Format, "hash", snapshot.Hash)
  328. resp, err := s.conn.OfferSnapshotSync(ctx, abci.RequestOfferSnapshot{
  329. Snapshot: &abci.Snapshot{
  330. Height: snapshot.Height,
  331. Format: snapshot.Format,
  332. Chunks: snapshot.Chunks,
  333. Hash: snapshot.Hash,
  334. Metadata: snapshot.Metadata,
  335. },
  336. AppHash: snapshot.trustedAppHash,
  337. })
  338. if err != nil {
  339. return fmt.Errorf("failed to offer snapshot: %w", err)
  340. }
  341. switch resp.Result {
  342. case abci.ResponseOfferSnapshot_ACCEPT:
  343. s.logger.Info("Snapshot accepted, restoring", "height", snapshot.Height,
  344. "format", snapshot.Format, "hash", snapshot.Hash)
  345. return nil
  346. case abci.ResponseOfferSnapshot_ABORT:
  347. return errAbort
  348. case abci.ResponseOfferSnapshot_REJECT:
  349. return errRejectSnapshot
  350. case abci.ResponseOfferSnapshot_REJECT_FORMAT:
  351. return errRejectFormat
  352. case abci.ResponseOfferSnapshot_REJECT_SENDER:
  353. return errRejectSender
  354. default:
  355. return fmt.Errorf("unknown ResponseOfferSnapshot result %v", resp.Result)
  356. }
  357. }
  358. // applyChunks applies chunks to the app. It returns various errors depending on the app's
  359. // response, or nil once the snapshot is fully restored.
  360. func (s *syncer) applyChunks(ctx context.Context, chunks *chunkQueue, start time.Time) error {
  361. for {
  362. chunk, err := chunks.Next()
  363. if err == errDone {
  364. return nil
  365. } else if err != nil {
  366. return fmt.Errorf("failed to fetch chunk: %w", err)
  367. }
  368. resp, err := s.conn.ApplySnapshotChunkSync(ctx, abci.RequestApplySnapshotChunk{
  369. Index: chunk.Index,
  370. Chunk: chunk.Chunk,
  371. Sender: string(chunk.Sender),
  372. })
  373. if err != nil {
  374. return fmt.Errorf("failed to apply chunk %v: %w", chunk.Index, err)
  375. }
  376. s.logger.Info("Applied snapshot chunk to ABCI app", "height", chunk.Height,
  377. "format", chunk.Format, "chunk", chunk.Index, "total", chunks.Size())
  378. // Discard and refetch any chunks as requested by the app
  379. for _, index := range resp.RefetchChunks {
  380. err := chunks.Discard(index)
  381. if err != nil {
  382. return fmt.Errorf("failed to discard chunk %v: %w", index, err)
  383. }
  384. }
  385. // Reject any senders as requested by the app
  386. for _, sender := range resp.RejectSenders {
  387. if sender != "" {
  388. peerID := types.NodeID(sender)
  389. s.snapshots.RejectPeer(peerID)
  390. if err := chunks.DiscardSender(peerID); err != nil {
  391. return fmt.Errorf("failed to reject sender: %w", err)
  392. }
  393. }
  394. }
  395. switch resp.Result {
  396. case abci.ResponseApplySnapshotChunk_ACCEPT:
  397. s.metrics.SnapshotChunk.Add(1)
  398. s.avgChunkTime = time.Since(start).Nanoseconds() / int64(chunks.numChunksReturned())
  399. s.metrics.ChunkProcessAvgTime.Set(float64(s.avgChunkTime))
  400. case abci.ResponseApplySnapshotChunk_ABORT:
  401. return errAbort
  402. case abci.ResponseApplySnapshotChunk_RETRY:
  403. chunks.Retry(chunk.Index)
  404. case abci.ResponseApplySnapshotChunk_RETRY_SNAPSHOT:
  405. return errRetrySnapshot
  406. case abci.ResponseApplySnapshotChunk_REJECT_SNAPSHOT:
  407. return errRejectSnapshot
  408. default:
  409. return fmt.Errorf("unknown ResponseApplySnapshotChunk result %v", resp.Result)
  410. }
  411. }
  412. }
  413. // fetchChunks requests chunks from peers, receiving allocations from the chunk queue. Chunks
  414. // will be received from the reactor via syncer.AddChunks() to chunkQueue.Add().
  415. func (s *syncer) fetchChunks(ctx context.Context, snapshot *snapshot, chunks *chunkQueue) {
  416. var (
  417. next = true
  418. index uint32
  419. err error
  420. )
  421. for {
  422. if next {
  423. index, err = chunks.Allocate()
  424. if errors.Is(err, errDone) {
  425. // Keep checking until the context is canceled (restore is done), in case any
  426. // chunks need to be refetched.
  427. select {
  428. case <-ctx.Done():
  429. return
  430. case <-time.After(2 * time.Second):
  431. continue
  432. }
  433. }
  434. if err != nil {
  435. s.logger.Error("Failed to allocate chunk from queue", "err", err)
  436. return
  437. }
  438. }
  439. s.logger.Info("Fetching snapshot chunk", "height", snapshot.Height,
  440. "format", snapshot.Format, "chunk", index, "total", chunks.Size())
  441. ticker := time.NewTicker(s.retryTimeout)
  442. defer ticker.Stop()
  443. s.requestChunk(snapshot, index)
  444. select {
  445. case <-chunks.WaitFor(index):
  446. next = true
  447. case <-ticker.C:
  448. next = false
  449. case <-ctx.Done():
  450. return
  451. }
  452. ticker.Stop()
  453. }
  454. }
  455. // requestChunk requests a chunk from a peer.
  456. func (s *syncer) requestChunk(snapshot *snapshot, chunk uint32) {
  457. peer := s.snapshots.GetPeer(snapshot)
  458. if peer == "" {
  459. s.logger.Error("No valid peers found for snapshot", "height", snapshot.Height,
  460. "format", snapshot.Format, "hash", snapshot.Hash)
  461. return
  462. }
  463. s.logger.Debug(
  464. "Requesting snapshot chunk",
  465. "height", snapshot.Height,
  466. "format", snapshot.Format,
  467. "chunk", chunk,
  468. "peer", peer,
  469. )
  470. s.chunkCh <- p2p.Envelope{
  471. To: peer,
  472. Message: &ssproto.ChunkRequest{
  473. Height: snapshot.Height,
  474. Format: snapshot.Format,
  475. Index: chunk,
  476. },
  477. }
  478. }
  479. // verifyApp verifies the sync, checking the app hash and last block height. It returns the
  480. // app version, which should be returned as part of the initial state.
  481. func (s *syncer) verifyApp(snapshot *snapshot) (uint64, error) {
  482. resp, err := s.connQuery.InfoSync(context.Background(), proxy.RequestInfo)
  483. if err != nil {
  484. return 0, fmt.Errorf("failed to query ABCI app for appHash: %w", err)
  485. }
  486. if !bytes.Equal(snapshot.trustedAppHash, resp.LastBlockAppHash) {
  487. s.logger.Error("appHash verification failed",
  488. "expected", snapshot.trustedAppHash,
  489. "actual", resp.LastBlockAppHash)
  490. return 0, errVerifyFailed
  491. }
  492. if uint64(resp.LastBlockHeight) != snapshot.Height {
  493. s.logger.Error(
  494. "ABCI app reported unexpected last block height",
  495. "expected", snapshot.Height,
  496. "actual", resp.LastBlockHeight,
  497. )
  498. return 0, errVerifyFailed
  499. }
  500. s.logger.Info("Verified ABCI app", "height", snapshot.Height, "appHash", snapshot.trustedAppHash)
  501. return resp.AppVersion, nil
  502. }