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.

402 lines
13 KiB

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