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.

404 lines
13 KiB

7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 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
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
  1. package consensus
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "hash/crc32"
  7. "io"
  8. "reflect"
  9. //"strconv"
  10. //"strings"
  11. "time"
  12. abci "github.com/tendermint/abci/types"
  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. var crc32c = crc32.MakeTable(crc32.Castagnoli)
  22. // Functionality to replay blocks and messages on recovery from a crash.
  23. // There are two general failure scenarios: failure during consensus, and failure while applying the block.
  24. // The former is handled by the WAL, the latter by the proxyApp Handshake on restart,
  25. // which ultimately hands off the work to the WAL.
  26. //-----------------------------------------
  27. // recover from failure during consensus
  28. // by replaying messages from the WAL
  29. // Unmarshal and apply a single message to the consensus state
  30. // as if it were received in receiveRoutine
  31. // Lines that start with "#" are ignored.
  32. // NOTE: receiveRoutine should not be running
  33. func (cs *ConsensusState) readReplayMessage(msg *TimedWALMessage, newStepCh chan interface{}) error {
  34. // skip meta messages
  35. if _, ok := msg.Msg.(EndHeightMessage); ok {
  36. return nil
  37. }
  38. // for logging
  39. switch m := msg.Msg.(type) {
  40. case types.EventDataRoundState:
  41. cs.Logger.Info("Replay: New Step", "height", m.Height, "round", m.Round, "step", m.Step)
  42. // these are playback checks
  43. ticker := time.After(time.Second * 2)
  44. if newStepCh != nil {
  45. select {
  46. case mi := <-newStepCh:
  47. m2 := mi.(types.EventDataRoundState)
  48. if m.Height != m2.Height || m.Round != m2.Round || m.Step != m2.Step {
  49. return fmt.Errorf("RoundState mismatch. Got %v; Expected %v", m2, m)
  50. }
  51. case <-ticker:
  52. return fmt.Errorf("Failed to read off newStepCh")
  53. }
  54. }
  55. case msgInfo:
  56. peerKey := m.PeerKey
  57. if peerKey == "" {
  58. peerKey = "local"
  59. }
  60. switch msg := m.Msg.(type) {
  61. case *ProposalMessage:
  62. p := msg.Proposal
  63. cs.Logger.Info("Replay: Proposal", "height", p.Height, "round", p.Round, "header",
  64. p.BlockPartsHeader, "pol", p.POLRound, "peer", peerKey)
  65. case *BlockPartMessage:
  66. cs.Logger.Info("Replay: BlockPart", "height", msg.Height, "round", msg.Round, "peer", peerKey)
  67. case *VoteMessage:
  68. v := msg.Vote
  69. cs.Logger.Info("Replay: Vote", "height", v.Height, "round", v.Round, "type", v.Type,
  70. "blockID", v.BlockID, "peer", peerKey)
  71. }
  72. cs.handleMsg(m)
  73. case timeoutInfo:
  74. cs.Logger.Info("Replay: Timeout", "height", m.Height, "round", m.Round, "step", m.Step, "dur", m.Duration)
  75. cs.handleTimeout(m, cs.RoundState)
  76. default:
  77. return fmt.Errorf("Replay: Unknown TimedWALMessage type: %v", reflect.TypeOf(msg.Msg))
  78. }
  79. return nil
  80. }
  81. // replay only those messages since the last block.
  82. // timeoutRoutine should run concurrently to read off tickChan
  83. func (cs *ConsensusState) catchupReplay(csHeight int64) error {
  84. // set replayMode
  85. cs.replayMode = true
  86. defer func() { cs.replayMode = false }()
  87. // Ensure that ENDHEIGHT for this height doesn't exist
  88. // NOTE: This is just a sanity check. As far as we know things work fine without it,
  89. // and Handshake could reuse ConsensusState if it weren't for this check (since we can crash after writing ENDHEIGHT).
  90. gr, found, err := cs.wal.SearchForEndHeight(csHeight)
  91. if err != nil {
  92. return err
  93. }
  94. if gr != nil {
  95. if err := gr.Close(); err != nil {
  96. return err
  97. }
  98. }
  99. if found {
  100. return fmt.Errorf("WAL should not contain #ENDHEIGHT %d.", csHeight)
  101. }
  102. // Search for last height marker
  103. gr, found, err = cs.wal.SearchForEndHeight(csHeight - 1)
  104. if err == io.EOF {
  105. cs.Logger.Error("Replay: wal.group.Search returned EOF", "#ENDHEIGHT", csHeight-1)
  106. } else if err != nil {
  107. return err
  108. }
  109. if !found {
  110. return errors.New(cmn.Fmt("Cannot replay height %d. WAL does not contain #ENDHEIGHT for %d.", csHeight, csHeight-1))
  111. }
  112. defer gr.Close() // nolint: errcheck
  113. cs.Logger.Info("Catchup by replaying consensus messages", "height", csHeight)
  114. var msg *TimedWALMessage
  115. dec := WALDecoder{gr}
  116. for {
  117. msg, err = dec.Decode()
  118. if err == io.EOF {
  119. break
  120. } else if err != nil {
  121. return err
  122. }
  123. // NOTE: since the priv key is set when the msgs are received
  124. // it will attempt to eg double sign but we can just ignore it
  125. // since the votes will be replayed and we'll get to the next step
  126. if err := cs.readReplayMessage(msg, nil); err != nil {
  127. return err
  128. }
  129. }
  130. cs.Logger.Info("Replay: Done")
  131. return nil
  132. }
  133. //--------------------------------------------------------------------------------
  134. // Parses marker lines of the form:
  135. // #ENDHEIGHT: 12345
  136. /*
  137. func makeHeightSearchFunc(height int64) auto.SearchFunc {
  138. return func(line string) (int, error) {
  139. line = strings.TrimRight(line, "\n")
  140. parts := strings.Split(line, " ")
  141. if len(parts) != 2 {
  142. return -1, errors.New("Line did not have 2 parts")
  143. }
  144. i, err := strconv.Atoi(parts[1])
  145. if err != nil {
  146. return -1, errors.New("Failed to parse INFO: " + err.Error())
  147. }
  148. if height < i {
  149. return 1, nil
  150. } else if height == i {
  151. return 0, nil
  152. } else {
  153. return -1, nil
  154. }
  155. }
  156. }*/
  157. //----------------------------------------------
  158. // Recover from failure during block processing
  159. // by handshaking with the app to figure out where
  160. // we were last and using the WAL to recover there
  161. type Handshaker struct {
  162. state *sm.State
  163. store types.BlockStore
  164. logger log.Logger
  165. nBlocks int // number of blocks applied to the state
  166. }
  167. func NewHandshaker(state *sm.State, store types.BlockStore) *Handshaker {
  168. return &Handshaker{state, store, log.NewNopLogger(), 0}
  169. }
  170. func (h *Handshaker) SetLogger(l log.Logger) {
  171. h.logger = l
  172. }
  173. func (h *Handshaker) NBlocks() int {
  174. return h.nBlocks
  175. }
  176. // TODO: retry the handshake/replay if it fails ?
  177. func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error {
  178. // handshake is done via info request on the query conn
  179. res, err := proxyApp.Query().InfoSync(abci.RequestInfo{version.Version})
  180. if err != nil {
  181. return errors.New(cmn.Fmt("Error calling Info: %v", err))
  182. }
  183. blockHeight := int64(res.LastBlockHeight)
  184. if blockHeight < 0 {
  185. return fmt.Errorf("Got a negative last block height (%d) from the app", blockHeight)
  186. }
  187. appHash := res.LastBlockAppHash
  188. h.logger.Info("ABCI Handshake", "appHeight", blockHeight, "appHash", fmt.Sprintf("%X", appHash))
  189. // TODO: check version
  190. // replay blocks up to the latest in the blockstore
  191. _, err = h.ReplayBlocks(appHash, blockHeight, proxyApp)
  192. if err != nil {
  193. return errors.New(cmn.Fmt("Error on replay: %v", err))
  194. }
  195. h.logger.Info("Completed ABCI Handshake - Tendermint and App are synced", "appHeight", blockHeight, "appHash", fmt.Sprintf("%X", appHash))
  196. // TODO: (on restart) replay mempool
  197. return nil
  198. }
  199. // Replay all blocks since appBlockHeight and ensure the result matches the current state.
  200. // Returns the final AppHash or an error
  201. func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int64, proxyApp proxy.AppConns) ([]byte, error) {
  202. storeBlockHeight := h.store.Height()
  203. stateBlockHeight := h.state.LastBlockHeight
  204. h.logger.Info("ABCI Replay Blocks", "appHeight", appBlockHeight, "storeHeight", storeBlockHeight, "stateHeight", stateBlockHeight)
  205. // If appBlockHeight == 0 it means that we are at genesis and hence should send InitChain
  206. if appBlockHeight == 0 {
  207. validators := types.TM2PB.Validators(h.state.Validators)
  208. if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{validators}); err != nil {
  209. return nil, err
  210. }
  211. }
  212. // First handle edge cases and constraints on the storeBlockHeight
  213. if storeBlockHeight == 0 {
  214. return appHash, h.checkAppHash(appHash)
  215. } else if storeBlockHeight < appBlockHeight {
  216. // the app should never be ahead of the store (but this is under app's control)
  217. return appHash, sm.ErrAppBlockHeightTooHigh{storeBlockHeight, appBlockHeight}
  218. } else if storeBlockHeight < stateBlockHeight {
  219. // the state should never be ahead of the store (this is under tendermint's control)
  220. cmn.PanicSanity(cmn.Fmt("StateBlockHeight (%d) > StoreBlockHeight (%d)", stateBlockHeight, storeBlockHeight))
  221. } else if storeBlockHeight > stateBlockHeight+1 {
  222. // store should be at most one ahead of the state (this is under tendermint's control)
  223. cmn.PanicSanity(cmn.Fmt("StoreBlockHeight (%d) > StateBlockHeight + 1 (%d)", storeBlockHeight, stateBlockHeight+1))
  224. }
  225. // Now either store is equal to state, or one ahead.
  226. // For each, consider all cases of where the app could be, given app <= store
  227. if storeBlockHeight == stateBlockHeight {
  228. // Tendermint ran Commit and saved the state.
  229. // Either the app is asking for replay, or we're all synced up.
  230. if appBlockHeight < storeBlockHeight {
  231. // the app is behind, so replay blocks, but no need to go through WAL (state is already synced to store)
  232. return h.replayBlocks(proxyApp, appBlockHeight, storeBlockHeight, false)
  233. } else if appBlockHeight == storeBlockHeight {
  234. // We're good!
  235. return appHash, h.checkAppHash(appHash)
  236. }
  237. } else if storeBlockHeight == stateBlockHeight+1 {
  238. // We saved the block in the store but haven't updated the state,
  239. // so we'll need to replay a block using the WAL.
  240. if appBlockHeight < stateBlockHeight {
  241. // the app is further behind than it should be, so replay blocks
  242. // but leave the last block to go through the WAL
  243. return h.replayBlocks(proxyApp, appBlockHeight, storeBlockHeight, true)
  244. } else if appBlockHeight == stateBlockHeight {
  245. // We haven't run Commit (both the state and app are one block behind),
  246. // so replayBlock with the real app.
  247. // NOTE: We could instead use the cs.WAL on cs.Start,
  248. // but we'd have to allow the WAL to replay a block that wrote it's ENDHEIGHT
  249. h.logger.Info("Replay last block using real app")
  250. return h.replayBlock(storeBlockHeight, proxyApp.Consensus())
  251. } else if appBlockHeight == storeBlockHeight {
  252. // We ran Commit, but didn't save the state, so replayBlock with mock app
  253. abciResponses := h.state.LoadABCIResponses()
  254. mockApp := newMockProxyApp(appHash, abciResponses)
  255. h.logger.Info("Replay last block using mock app")
  256. return h.replayBlock(storeBlockHeight, mockApp)
  257. }
  258. }
  259. cmn.PanicSanity("Should never happen")
  260. return nil, nil
  261. }
  262. func (h *Handshaker) replayBlocks(proxyApp proxy.AppConns, appBlockHeight, storeBlockHeight int64, mutateState bool) ([]byte, error) {
  263. // App is further behind than it should be, so we need to replay blocks.
  264. // We replay all blocks from appBlockHeight+1.
  265. //
  266. // Note that we don't have an old version of the state,
  267. // so we by-pass state validation/mutation using sm.ExecCommitBlock.
  268. // This also means we won't be saving validator sets if they change during this period.
  269. //
  270. // If mutateState == true, the final block is replayed with h.replayBlock()
  271. var appHash []byte
  272. var err error
  273. finalBlock := storeBlockHeight
  274. if mutateState {
  275. finalBlock -= 1
  276. }
  277. for i := appBlockHeight + 1; i <= finalBlock; i++ {
  278. h.logger.Info("Applying block", "height", i)
  279. block := h.store.LoadBlock(i)
  280. appHash, err = sm.ExecCommitBlock(proxyApp.Consensus(), block, h.logger)
  281. if err != nil {
  282. return nil, err
  283. }
  284. h.nBlocks += 1
  285. }
  286. if mutateState {
  287. // sync the final block
  288. return h.replayBlock(storeBlockHeight, proxyApp.Consensus())
  289. }
  290. return appHash, h.checkAppHash(appHash)
  291. }
  292. // ApplyBlock on the proxyApp with the last block.
  293. func (h *Handshaker) replayBlock(height int64, proxyApp proxy.AppConnConsensus) ([]byte, error) {
  294. mempool := types.MockMempool{}
  295. block := h.store.LoadBlock(height)
  296. meta := h.store.LoadBlockMeta(height)
  297. if err := h.state.ApplyBlock(types.NopEventBus{}, proxyApp, block, meta.BlockID.PartsHeader, mempool); err != nil {
  298. return nil, err
  299. }
  300. h.nBlocks += 1
  301. return h.state.AppHash, nil
  302. }
  303. func (h *Handshaker) checkAppHash(appHash []byte) error {
  304. if !bytes.Equal(h.state.AppHash, appHash) {
  305. panic(errors.New(cmn.Fmt("Tendermint state.AppHash does not match AppHash after replay. Got %X, expected %X", appHash, h.state.AppHash)).Error())
  306. }
  307. return nil
  308. }
  309. //--------------------------------------------------------------------------------
  310. // mockProxyApp uses ABCIResponses to give the right results
  311. // Useful because we don't want to call Commit() twice for the same block on the real app.
  312. func newMockProxyApp(appHash []byte, abciResponses *sm.ABCIResponses) proxy.AppConnConsensus {
  313. clientCreator := proxy.NewLocalClientCreator(&mockProxyApp{
  314. appHash: appHash,
  315. abciResponses: abciResponses,
  316. })
  317. cli, _ := clientCreator.NewABCIClient()
  318. err := cli.Start()
  319. if err != nil {
  320. panic(err)
  321. }
  322. return proxy.NewAppConnConsensus(cli)
  323. }
  324. type mockProxyApp struct {
  325. abci.BaseApplication
  326. appHash []byte
  327. txCount int
  328. abciResponses *sm.ABCIResponses
  329. }
  330. func (mock *mockProxyApp) DeliverTx(tx []byte) abci.ResponseDeliverTx {
  331. r := mock.abciResponses.DeliverTx[mock.txCount]
  332. mock.txCount += 1
  333. return *r
  334. }
  335. func (mock *mockProxyApp) EndBlock(req abci.RequestEndBlock) abci.ResponseEndBlock {
  336. mock.txCount = 0
  337. return *mock.abciResponses.EndBlock
  338. }
  339. func (mock *mockProxyApp) Commit() abci.ResponseCommit {
  340. return abci.ResponseCommit{Code: abci.CodeType_OK, Data: mock.appHash}
  341. }