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.

413 lines
13 KiB

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