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.

423 lines
14 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
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. )
  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. cs.Logger.Info("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. cs.Logger.Info("Replay: Proposal", "height", p.Height, "round", p.Round, "header",
  69. p.BlockPartsHeader, "pol", p.POLRound, "peer", peerKey)
  70. case *BlockPartMessage:
  71. cs.Logger.Info("Replay: BlockPart", "height", msg.Height, "round", msg.Round, "peer", peerKey)
  72. case *VoteMessage:
  73. v := msg.Vote
  74. cs.Logger.Info("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. cs.Logger.Info("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 ENDHEIGHT for this height doesn't exist
  93. // NOTE: This is just a sanity check. As far as we know things work fine without it,
  94. // and Handshake could reuse ConsensusState if it weren't for this check (since we can crash after writing ENDHEIGHT).
  95. gr, found, err := cs.wal.group.Search("#ENDHEIGHT: ", makeHeightSearchFunc(csHeight))
  96. if err != nil {
  97. return err
  98. }
  99. if gr != nil {
  100. gr.Close()
  101. }
  102. if found {
  103. return errors.New(cmn.Fmt("WAL should not contain #ENDHEIGHT %d.", csHeight))
  104. }
  105. // Search for last height marker
  106. gr, found, err = cs.wal.group.Search("#ENDHEIGHT: ", makeHeightSearchFunc(csHeight-1))
  107. if err == io.EOF {
  108. cs.Logger.Error("Replay: wal.group.Search returned EOF", "#ENDHEIGHT", csHeight-1)
  109. // if we upgraded from 0.9 to 0.9.1, we may have #HEIGHT instead
  110. // TODO (0.10.0): remove this
  111. gr, found, err = cs.wal.group.Search("#HEIGHT: ", makeHeightSearchFunc(csHeight))
  112. if err == io.EOF {
  113. cs.Logger.Error("Replay: wal.group.Search returned EOF", "#HEIGHT", csHeight)
  114. return nil
  115. } else if err != nil {
  116. return err
  117. }
  118. } else if err != nil {
  119. return err
  120. } else {
  121. defer gr.Close()
  122. }
  123. if !found {
  124. // if we upgraded from 0.9 to 0.9.1, we may have #HEIGHT instead
  125. // TODO (0.10.0): remove this
  126. gr, _, err = cs.wal.group.Search("#HEIGHT: ", makeHeightSearchFunc(csHeight))
  127. if err == io.EOF {
  128. cs.Logger.Error("Replay: wal.group.Search returned EOF", "#HEIGHT", csHeight)
  129. return nil
  130. } else if err != nil {
  131. return err
  132. } else {
  133. defer gr.Close()
  134. }
  135. // TODO (0.10.0): uncomment
  136. // return errors.New(cmn.Fmt("Cannot replay height %d. WAL does not contain #ENDHEIGHT for %d.", csHeight, csHeight-1))
  137. }
  138. cs.Logger.Info("Catchup by replaying consensus messages", "height", csHeight)
  139. for {
  140. line, err := gr.ReadLine()
  141. if err != nil {
  142. if err == io.EOF {
  143. break
  144. } else {
  145. return err
  146. }
  147. }
  148. // NOTE: since the priv key is set when the msgs are received
  149. // it will attempt to eg double sign but we can just ignore it
  150. // since the votes will be replayed and we'll get to the next step
  151. if err := cs.readReplayMessage([]byte(line), nil); err != nil {
  152. return err
  153. }
  154. }
  155. cs.Logger.Info("Replay: Done")
  156. return nil
  157. }
  158. //--------------------------------------------------------------------------------
  159. // Parses marker lines of the form:
  160. // #ENDHEIGHT: 12345
  161. func makeHeightSearchFunc(height int) auto.SearchFunc {
  162. return func(line string) (int, error) {
  163. line = strings.TrimRight(line, "\n")
  164. parts := strings.Split(line, " ")
  165. if len(parts) != 2 {
  166. return -1, errors.New("Line did not have 2 parts")
  167. }
  168. i, err := strconv.Atoi(parts[1])
  169. if err != nil {
  170. return -1, errors.New("Failed to parse INFO: " + err.Error())
  171. }
  172. if height < i {
  173. return 1, nil
  174. } else if height == i {
  175. return 0, nil
  176. } else {
  177. return -1, nil
  178. }
  179. }
  180. }
  181. //----------------------------------------------
  182. // Recover from failure during block processing
  183. // by handshaking with the app to figure out where
  184. // we were last and using the WAL to recover there
  185. type Handshaker struct {
  186. state *sm.State
  187. store types.BlockStore
  188. logger log.Logger
  189. nBlocks int // number of blocks applied to the state
  190. }
  191. func NewHandshaker(state *sm.State, store types.BlockStore) *Handshaker {
  192. return &Handshaker{state, store, log.NewNopLogger(), 0}
  193. }
  194. func (h *Handshaker) SetLogger(l log.Logger) {
  195. h.logger = l
  196. }
  197. func (h *Handshaker) NBlocks() int {
  198. return h.nBlocks
  199. }
  200. // TODO: retry the handshake/replay if it fails ?
  201. func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error {
  202. // handshake is done via info request on the query conn
  203. res, err := proxyApp.Query().InfoSync()
  204. if err != nil {
  205. return errors.New(cmn.Fmt("Error calling Info: %v", err))
  206. }
  207. blockHeight := int(res.LastBlockHeight) // XXX: beware overflow
  208. appHash := res.LastBlockAppHash
  209. h.logger.Info("ABCI Handshake", "appHeight", blockHeight, "appHash", fmt.Sprintf("%X", appHash))
  210. // TODO: check version
  211. // replay blocks up to the latest in the blockstore
  212. _, err = h.ReplayBlocks(appHash, blockHeight, proxyApp)
  213. if err != nil {
  214. return errors.New(cmn.Fmt("Error on replay: %v", err))
  215. }
  216. h.logger.Info("Completed ABCI Handshake - Tendermint and App are synced", "appHeight", blockHeight, "appHash", fmt.Sprintf("%X", appHash))
  217. // TODO: (on restart) replay mempool
  218. return nil
  219. }
  220. // Replay all blocks since appBlockHeight and ensure the result matches the current state.
  221. // Returns the final AppHash or an error
  222. func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, proxyApp proxy.AppConns) ([]byte, error) {
  223. storeBlockHeight := h.store.Height()
  224. stateBlockHeight := h.state.LastBlockHeight
  225. h.logger.Info("ABCI Replay Blocks", "appHeight", appBlockHeight, "storeHeight", storeBlockHeight, "stateHeight", stateBlockHeight)
  226. // If appBlockHeight == 0 it means that we are at genesis and hence should send InitChain
  227. if appBlockHeight == 0 {
  228. validators := types.TM2PB.Validators(h.state.Validators)
  229. proxyApp.Consensus().InitChainSync(validators)
  230. }
  231. // First handle edge cases and constraints on the storeBlockHeight
  232. if storeBlockHeight == 0 {
  233. return appHash, h.checkAppHash(appHash)
  234. } else if storeBlockHeight < appBlockHeight {
  235. // the app should never be ahead of the store (but this is under app's control)
  236. return appHash, sm.ErrAppBlockHeightTooHigh{storeBlockHeight, appBlockHeight}
  237. } else if storeBlockHeight < stateBlockHeight {
  238. // the state should never be ahead of the store (this is under tendermint's control)
  239. cmn.PanicSanity(cmn.Fmt("StateBlockHeight (%d) > StoreBlockHeight (%d)", stateBlockHeight, storeBlockHeight))
  240. } else if storeBlockHeight > stateBlockHeight+1 {
  241. // store should be at most one ahead of the state (this is under tendermint's control)
  242. cmn.PanicSanity(cmn.Fmt("StoreBlockHeight (%d) > StateBlockHeight + 1 (%d)", storeBlockHeight, stateBlockHeight+1))
  243. }
  244. // Now either store is equal to state, or one ahead.
  245. // For each, consider all cases of where the app could be, given app <= store
  246. if storeBlockHeight == stateBlockHeight {
  247. // Tendermint ran Commit and saved the state.
  248. // Either the app is asking for replay, or we're all synced up.
  249. if appBlockHeight < storeBlockHeight {
  250. // the app is behind, so replay blocks, but no need to go through WAL (state is already synced to store)
  251. return h.replayBlocks(proxyApp, appBlockHeight, storeBlockHeight, false)
  252. } else if appBlockHeight == storeBlockHeight {
  253. // We're good!
  254. return appHash, h.checkAppHash(appHash)
  255. }
  256. } else if storeBlockHeight == stateBlockHeight+1 {
  257. // We saved the block in the store but haven't updated the state,
  258. // so we'll need to replay a block using the WAL.
  259. if appBlockHeight < stateBlockHeight {
  260. // the app is further behind than it should be, so replay blocks
  261. // but leave the last block to go through the WAL
  262. return h.replayBlocks(proxyApp, appBlockHeight, storeBlockHeight, true)
  263. } else if appBlockHeight == stateBlockHeight {
  264. // We haven't run Commit (both the state and app are one block behind),
  265. // so replayBlock with the real app.
  266. // NOTE: We could instead use the cs.WAL on cs.Start,
  267. // but we'd have to allow the WAL to replay a block that wrote it's ENDHEIGHT
  268. h.logger.Info("Replay last block using real app")
  269. return h.replayBlock(storeBlockHeight, proxyApp.Consensus())
  270. } else if appBlockHeight == storeBlockHeight {
  271. // We ran Commit, but didn't save the state, so replayBlock with mock app
  272. abciResponses := h.state.LoadABCIResponses()
  273. mockApp := newMockProxyApp(appHash, abciResponses)
  274. h.logger.Info("Replay last block using mock app")
  275. return h.replayBlock(storeBlockHeight, mockApp)
  276. }
  277. }
  278. cmn.PanicSanity("Should never happen")
  279. return nil, nil
  280. }
  281. func (h *Handshaker) replayBlocks(proxyApp proxy.AppConns, appBlockHeight, storeBlockHeight int, mutateState bool) ([]byte, error) {
  282. // App is further behind than it should be, so we need to replay blocks.
  283. // We replay all blocks from appBlockHeight+1.
  284. // Note that we don't have an old version of the state,
  285. // so we by-pass state validation/mutation using sm.ExecCommitBlock.
  286. // If mutateState == true, the final block is replayed with h.replayBlock()
  287. var appHash []byte
  288. var err error
  289. finalBlock := storeBlockHeight
  290. if mutateState {
  291. finalBlock -= 1
  292. }
  293. for i := appBlockHeight + 1; i <= finalBlock; i++ {
  294. h.logger.Info("Applying block", "height", i)
  295. block := h.store.LoadBlock(i)
  296. appHash, err = sm.ExecCommitBlock(proxyApp.Consensus(), block, h.logger)
  297. if err != nil {
  298. return nil, err
  299. }
  300. h.nBlocks += 1
  301. }
  302. if mutateState {
  303. // sync the final block
  304. return h.replayBlock(storeBlockHeight, proxyApp.Consensus())
  305. }
  306. return appHash, h.checkAppHash(appHash)
  307. }
  308. // ApplyBlock on the proxyApp with the last block.
  309. func (h *Handshaker) replayBlock(height int, proxyApp proxy.AppConnConsensus) ([]byte, error) {
  310. mempool := types.MockMempool{}
  311. var eventCache types.Fireable // nil
  312. block := h.store.LoadBlock(height)
  313. meta := h.store.LoadBlockMeta(height)
  314. if err := h.state.ApplyBlock(eventCache, proxyApp, block, meta.BlockID.PartsHeader, mempool); err != nil {
  315. return nil, err
  316. }
  317. h.nBlocks += 1
  318. return h.state.AppHash, nil
  319. }
  320. func (h *Handshaker) checkAppHash(appHash []byte) error {
  321. if !bytes.Equal(h.state.AppHash, appHash) {
  322. panic(errors.New(cmn.Fmt("Tendermint state.AppHash does not match AppHash after replay. Got %X, expected %X", appHash, h.state.AppHash)).Error())
  323. return nil
  324. }
  325. return nil
  326. }
  327. //--------------------------------------------------------------------------------
  328. // mockProxyApp uses ABCIResponses to give the right results
  329. // Useful because we don't want to call Commit() twice for the same block on the real app.
  330. func newMockProxyApp(appHash []byte, abciResponses *sm.ABCIResponses) proxy.AppConnConsensus {
  331. clientCreator := proxy.NewLocalClientCreator(&mockProxyApp{
  332. appHash: appHash,
  333. abciResponses: abciResponses,
  334. })
  335. cli, _ := clientCreator.NewABCIClient()
  336. cli.Start()
  337. return proxy.NewAppConnConsensus(cli)
  338. }
  339. type mockProxyApp struct {
  340. abci.BaseApplication
  341. appHash []byte
  342. txCount int
  343. abciResponses *sm.ABCIResponses
  344. }
  345. func (mock *mockProxyApp) DeliverTx(tx []byte) abci.Result {
  346. r := mock.abciResponses.DeliverTx[mock.txCount]
  347. mock.txCount += 1
  348. return abci.Result{
  349. r.Code,
  350. r.Data,
  351. r.Log,
  352. }
  353. }
  354. func (mock *mockProxyApp) EndBlock(height uint64) abci.ResponseEndBlock {
  355. mock.txCount = 0
  356. return mock.abciResponses.EndBlock
  357. }
  358. func (mock *mockProxyApp) Commit() abci.Result {
  359. return abci.NewResultOK(mock.appHash, "")
  360. }