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.

381 lines
12 KiB

  1. package consensus
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "time"
  11. abci "github.com/tendermint/abci/types"
  12. auto "github.com/tendermint/go-autofile"
  13. . "github.com/tendermint/go-common"
  14. cfg "github.com/tendermint/go-config"
  15. "github.com/tendermint/go-wire"
  16. "github.com/tendermint/tendermint/proxy"
  17. sm "github.com/tendermint/tendermint/state"
  18. "github.com/tendermint/tendermint/types"
  19. )
  20. // Functionality to replay blocks and messages on recovery from a crash.
  21. // There are two general failure scenarios: failure during consensus, and failure while applying the block.
  22. // The former is handled by the WAL, the latter by the proxyApp Handshake on restart,
  23. // which ultimately hands off the work to the WAL.
  24. //-----------------------------------------
  25. // recover from failure during consensus
  26. // by replaying messages from the WAL
  27. // Unmarshal and apply a single message to the consensus state
  28. // as if it were received in receiveRoutine
  29. // Lines that start with "#" are ignored.
  30. // NOTE: receiveRoutine should not be running
  31. func (cs *ConsensusState) readReplayMessage(msgBytes []byte, newStepCh chan interface{}) error {
  32. // Skip over empty and meta lines
  33. if len(msgBytes) == 0 || msgBytes[0] == '#' {
  34. return nil
  35. }
  36. var err error
  37. var msg TimedWALMessage
  38. wire.ReadJSON(&msg, msgBytes, &err)
  39. if err != nil {
  40. fmt.Println("MsgBytes:", msgBytes, string(msgBytes))
  41. return fmt.Errorf("Error reading json data: %v", err)
  42. }
  43. // for logging
  44. switch m := msg.Msg.(type) {
  45. case types.EventDataRoundState:
  46. log.Notice("Replay: New Step", "height", m.Height, "round", m.Round, "step", m.Step)
  47. // these are playback checks
  48. ticker := time.After(time.Second * 2)
  49. if newStepCh != nil {
  50. select {
  51. case mi := <-newStepCh:
  52. m2 := mi.(types.EventDataRoundState)
  53. if m.Height != m2.Height || m.Round != m2.Round || m.Step != m2.Step {
  54. return fmt.Errorf("RoundState mismatch. Got %v; Expected %v", m2, m)
  55. }
  56. case <-ticker:
  57. return fmt.Errorf("Failed to read off newStepCh")
  58. }
  59. }
  60. case msgInfo:
  61. peerKey := m.PeerKey
  62. if peerKey == "" {
  63. peerKey = "local"
  64. }
  65. switch msg := m.Msg.(type) {
  66. case *ProposalMessage:
  67. p := msg.Proposal
  68. log.Notice("Replay: Proposal", "height", p.Height, "round", p.Round, "header",
  69. p.BlockPartsHeader, "pol", p.POLRound, "peer", peerKey)
  70. case *BlockPartMessage:
  71. log.Notice("Replay: BlockPart", "height", msg.Height, "round", msg.Round, "peer", peerKey)
  72. case *VoteMessage:
  73. v := msg.Vote
  74. log.Notice("Replay: Vote", "height", v.Height, "round", v.Round, "type", v.Type,
  75. "blockID", v.BlockID, "peer", peerKey)
  76. }
  77. cs.handleMsg(m, cs.RoundState)
  78. case timeoutInfo:
  79. log.Notice("Replay: Timeout", "height", m.Height, "round", m.Round, "step", m.Step, "dur", m.Duration)
  80. cs.handleTimeout(m, cs.RoundState)
  81. default:
  82. return fmt.Errorf("Replay: Unknown TimedWALMessage type: %v", reflect.TypeOf(msg.Msg))
  83. }
  84. return nil
  85. }
  86. // replay only those messages since the last block.
  87. // timeoutRoutine should run concurrently to read off tickChan
  88. func (cs *ConsensusState) catchupReplay(csHeight int) error {
  89. // set replayMode
  90. cs.replayMode = true
  91. defer func() { cs.replayMode = false }()
  92. // Ensure that height+1 doesn't exist
  93. gr, found, err := cs.wal.group.Search("#HEIGHT: ", makeHeightSearchFunc(csHeight+1))
  94. if found {
  95. return errors.New(Fmt("WAL should not contain height %d.", csHeight+1))
  96. }
  97. if gr != nil {
  98. gr.Close()
  99. }
  100. // Search for height marker
  101. gr, found, err = cs.wal.group.Search("#HEIGHT: ", makeHeightSearchFunc(csHeight))
  102. if err == io.EOF {
  103. log.Warn("Replay: wal.group.Search returned EOF", "height", csHeight)
  104. return nil
  105. } else if err != nil {
  106. return err
  107. }
  108. if !found {
  109. return errors.New(Fmt("WAL does not contain height %d.", csHeight))
  110. }
  111. defer gr.Close()
  112. log.Notice("Catchup by replaying consensus messages", "height", csHeight)
  113. for {
  114. line, err := gr.ReadLine()
  115. if err != nil {
  116. if err == io.EOF {
  117. break
  118. } else {
  119. return err
  120. }
  121. }
  122. // NOTE: since the priv key is set when the msgs are received
  123. // it will attempt to eg double sign but we can just ignore it
  124. // since the votes will be replayed and we'll get to the next step
  125. if err := cs.readReplayMessage([]byte(line), nil); err != nil {
  126. return err
  127. }
  128. }
  129. log.Notice("Replay: Done")
  130. return nil
  131. }
  132. //--------------------------------------------------------------------------------
  133. // Parses marker lines of the form:
  134. // #HEIGHT: 12345
  135. func makeHeightSearchFunc(height int) auto.SearchFunc {
  136. return func(line string) (int, error) {
  137. line = strings.TrimRight(line, "\n")
  138. parts := strings.Split(line, " ")
  139. if len(parts) != 2 {
  140. return -1, errors.New("Line did not have 2 parts")
  141. }
  142. i, err := strconv.Atoi(parts[1])
  143. if err != nil {
  144. return -1, errors.New("Failed to parse INFO: " + err.Error())
  145. }
  146. if height < i {
  147. return 1, nil
  148. } else if height == i {
  149. return 0, nil
  150. } else {
  151. return -1, nil
  152. }
  153. }
  154. }
  155. //----------------------------------------------
  156. // Recover from failure during block processing
  157. // by handshaking with the app to figure out where
  158. // we were last and using the WAL to recover there
  159. type Handshaker struct {
  160. config cfg.Config
  161. state *sm.State
  162. store types.BlockStore
  163. nBlocks int // number of blocks applied to the state
  164. }
  165. func NewHandshaker(config cfg.Config, state *sm.State, store types.BlockStore) *Handshaker {
  166. return &Handshaker{config, state, store, 0}
  167. }
  168. func (h *Handshaker) NBlocks() int {
  169. return h.nBlocks
  170. }
  171. var ErrReplayLastBlockTimeout = errors.New("Timed out waiting for last block to be replayed")
  172. // TODO: retry the handshake/replay if it fails ?
  173. func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error {
  174. // handshake is done via info request on the query conn
  175. res, err := proxyApp.Query().InfoSync()
  176. if err != nil {
  177. return errors.New(Fmt("Error calling Info: %v", err))
  178. }
  179. blockHeight := int(res.LastBlockHeight) // XXX: beware overflow
  180. appHash := res.LastBlockAppHash
  181. log.Notice("ABCI Handshake", "appHeight", blockHeight, "appHash", appHash)
  182. // TODO: check version
  183. // replay blocks up to the latest in the blockstore
  184. _, err = h.ReplayBlocks(appHash, blockHeight, proxyApp)
  185. if err == ErrReplayLastBlockTimeout {
  186. log.Warn("Failed to sync via handshake. Trying other means. If they fail, please increase the timeout_handshake parameter")
  187. return nil
  188. } else if err != nil {
  189. return errors.New(Fmt("Error on replay: %v", err))
  190. }
  191. log.Notice("Completed ABCI Handshake - Tendermint and App are synced", "appHeight", blockHeight, "appHash", appHash)
  192. // TODO: (on restart) replay mempool
  193. return nil
  194. }
  195. // Replay all blocks since appBlockHeight and ensure the result matches the current state.
  196. // Returns the final AppHash or an error
  197. func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, proxyApp proxy.AppConns) ([]byte, error) {
  198. storeBlockHeight := h.store.Height()
  199. stateBlockHeight := h.state.LastBlockHeight
  200. log.Notice("ABCI Replay Blocks", "appHeight", appBlockHeight, "storeHeight", storeBlockHeight, "stateHeight", stateBlockHeight)
  201. // First handle edge cases and constraints on the storeBlockHeight
  202. if storeBlockHeight == 0 {
  203. return appHash, h.checkAppHash(appHash)
  204. } else if storeBlockHeight < appBlockHeight {
  205. // the app should never be ahead of the store (but this is under app's control)
  206. return appHash, sm.ErrAppBlockHeightTooHigh{storeBlockHeight, appBlockHeight}
  207. } else if storeBlockHeight < stateBlockHeight {
  208. // the state should never be ahead of the store (this is under tendermint's control)
  209. PanicSanity(Fmt("StateBlockHeight (%d) > StoreBlockHeight (%d)", stateBlockHeight, storeBlockHeight))
  210. } else if storeBlockHeight > stateBlockHeight+1 {
  211. // store should be at most one ahead of the state (this is under tendermint's control)
  212. PanicSanity(Fmt("StoreBlockHeight (%d) > StateBlockHeight + 1 (%d)", storeBlockHeight, stateBlockHeight+1))
  213. }
  214. // Now either store is equal to state, or one ahead.
  215. // For each, consider all cases of where the app could be, given app <= store
  216. if storeBlockHeight == stateBlockHeight {
  217. // Tendermint ran Commit and saved the state.
  218. // Either the app is asking for replay, or we're all synced up.
  219. if appBlockHeight < storeBlockHeight {
  220. // the app is behind, so replay blocks, but no need to go through WAL (state is already synced to store)
  221. return h.replayBlocks(proxyApp, appBlockHeight, storeBlockHeight, false)
  222. } else if appBlockHeight == storeBlockHeight {
  223. // We're good!
  224. return appHash, h.checkAppHash(appHash)
  225. }
  226. } else if storeBlockHeight == stateBlockHeight+1 {
  227. // We saved the block in the store but haven't updated the state,
  228. // so we'll need to replay a block using the WAL.
  229. if appBlockHeight < stateBlockHeight {
  230. // the app is further behind than it should be, so replay blocks
  231. // but leave the last block to go through the WAL
  232. return h.replayBlocks(proxyApp, appBlockHeight, storeBlockHeight, true)
  233. } else if appBlockHeight == stateBlockHeight {
  234. // We haven't run Commit (both the state and app are one block behind),
  235. // so run through consensus with the real app
  236. log.Info("Replay last block using real app")
  237. return h.replayLastBlock(proxyApp.Consensus())
  238. } else if appBlockHeight == storeBlockHeight {
  239. // We ran Commit, but didn't save the state, so run through consensus with mock app
  240. mockApp := newMockProxyApp(appHash)
  241. log.Info("Replay last block using mock app")
  242. return h.replayLastBlock(mockApp)
  243. }
  244. }
  245. PanicSanity("Should never happen")
  246. return nil, nil
  247. }
  248. func (h *Handshaker) replayBlocks(proxyApp proxy.AppConns, appBlockHeight, storeBlockHeight int, useReplayFunc bool) ([]byte, error) {
  249. // App is further behind than it should be, so we need to replay blocks.
  250. // We replay all blocks from appBlockHeight+1 to storeBlockHeight-1,
  251. // and let the final block be replayed through ReplayBlocks.
  252. // Note that we don't have an old version of the state,
  253. // so we by-pass state validation using applyBlock here.
  254. var appHash []byte
  255. var err error
  256. finalBlock := storeBlockHeight
  257. if useReplayFunc {
  258. finalBlock -= 1
  259. }
  260. for i := appBlockHeight + 1; i <= finalBlock; i++ {
  261. log.Info("Applying block", "height", i)
  262. block := h.store.LoadBlock(i)
  263. appHash, err = sm.ApplyBlock(proxyApp.Consensus(), block)
  264. if err != nil {
  265. return nil, err
  266. }
  267. h.nBlocks += 1
  268. }
  269. if useReplayFunc {
  270. // sync the final block
  271. return h.ReplayBlocks(appHash, finalBlock, proxyApp)
  272. }
  273. return appHash, h.checkAppHash(appHash)
  274. }
  275. // Replay the last block through the consensus and return the AppHash from after Commit.
  276. func (h *Handshaker) replayLastBlock(proxyApp proxy.AppConnConsensus) ([]byte, error) {
  277. mempool := types.MockMempool{}
  278. cs := NewConsensusState(h.config, h.state, proxyApp, h.store, mempool)
  279. evsw := types.NewEventSwitch()
  280. evsw.Start()
  281. defer evsw.Stop()
  282. cs.SetEventSwitch(evsw)
  283. newBlockCh := subscribeToEvent(evsw, "consensus-replay", types.EventStringNewBlock(), 1)
  284. // run through the WAL, commit new block, stop
  285. if _, err := cs.Start(); err != nil {
  286. return nil, err
  287. }
  288. defer cs.Stop()
  289. timeout := h.config.GetInt("timeout_handshake")
  290. timer := time.NewTimer(time.Duration(timeout) * time.Millisecond)
  291. log.Notice("Attempting to replay last block", "height", h.store.Height(), "timeout", timeout)
  292. select {
  293. case <-newBlockCh:
  294. case <-timer.C:
  295. return nil, ErrReplayLastBlockTimeout
  296. }
  297. h.nBlocks += 1
  298. return cs.state.AppHash, nil
  299. }
  300. func (h *Handshaker) checkAppHash(appHash []byte) error {
  301. if !bytes.Equal(h.state.AppHash, appHash) {
  302. panic(errors.New(Fmt("Tendermint state.AppHash does not match AppHash after replay. Got %X, expected %X", appHash, h.state.AppHash)).Error())
  303. return nil
  304. }
  305. return nil
  306. }
  307. //--------------------------------------------------------------------------------
  308. func newMockProxyApp(appHash []byte) proxy.AppConnConsensus {
  309. clientCreator := proxy.NewLocalClientCreator(&mockProxyApp{appHash: appHash})
  310. cli, _ := clientCreator.NewABCIClient()
  311. return proxy.NewAppConnConsensus(cli)
  312. }
  313. type mockProxyApp struct {
  314. abci.BaseApplication
  315. appHash []byte
  316. }
  317. func (mock *mockProxyApp) Commit() abci.Result {
  318. return abci.NewResultOK(mock.appHash, "")
  319. }