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.

269 lines
7.0 KiB

8 years ago
8 years ago
  1. package consensus
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "strconv"
  8. "strings"
  9. . "github.com/tendermint/tmlibs/common"
  10. cfg "github.com/tendermint/go-config"
  11. dbm "github.com/tendermint/tmlibs/db"
  12. bc "github.com/tendermint/tendermint/blockchain"
  13. mempl "github.com/tendermint/tendermint/mempool"
  14. "github.com/tendermint/tendermint/proxy"
  15. sm "github.com/tendermint/tendermint/state"
  16. "github.com/tendermint/tendermint/types"
  17. )
  18. //--------------------------------------------------------
  19. // replay messages interactively or all at once
  20. func RunReplayFile(config cfg.Config, walFile string, console bool) {
  21. consensusState := newConsensusStateForReplay(config)
  22. if err := consensusState.ReplayFile(walFile, console); err != nil {
  23. Exit(Fmt("Error during consensus replay: %v", err))
  24. }
  25. }
  26. // Replay msgs in file or start the console
  27. func (cs *ConsensusState) ReplayFile(file string, console bool) error {
  28. if cs.IsRunning() {
  29. return errors.New("cs is already running, cannot replay")
  30. }
  31. if cs.wal != nil {
  32. return errors.New("cs wal is open, cannot replay")
  33. }
  34. cs.startForReplay()
  35. // ensure all new step events are regenerated as expected
  36. newStepCh := subscribeToEvent(cs.evsw, "replay-test", types.EventStringNewRoundStep(), 1)
  37. // just open the file for reading, no need to use wal
  38. fp, err := os.OpenFile(file, os.O_RDONLY, 0666)
  39. if err != nil {
  40. return err
  41. }
  42. pb := newPlayback(file, fp, cs, cs.state.Copy())
  43. defer pb.fp.Close()
  44. var nextN int // apply N msgs in a row
  45. for pb.scanner.Scan() {
  46. if nextN == 0 && console {
  47. nextN = pb.replayConsoleLoop()
  48. }
  49. if err := pb.cs.readReplayMessage(pb.scanner.Bytes(), newStepCh); err != nil {
  50. return err
  51. }
  52. if nextN > 0 {
  53. nextN -= 1
  54. }
  55. pb.count += 1
  56. }
  57. return nil
  58. }
  59. //------------------------------------------------
  60. // playback manager
  61. type playback struct {
  62. cs *ConsensusState
  63. fp *os.File
  64. scanner *bufio.Scanner
  65. count int // how many lines/msgs into the file are we
  66. // replays can be reset to beginning
  67. fileName string // so we can close/reopen the file
  68. genesisState *sm.State // so the replay session knows where to restart from
  69. }
  70. func newPlayback(fileName string, fp *os.File, cs *ConsensusState, genState *sm.State) *playback {
  71. return &playback{
  72. cs: cs,
  73. fp: fp,
  74. fileName: fileName,
  75. genesisState: genState,
  76. scanner: bufio.NewScanner(fp),
  77. }
  78. }
  79. // go back count steps by resetting the state and running (pb.count - count) steps
  80. func (pb *playback) replayReset(count int, newStepCh chan interface{}) error {
  81. pb.cs.Stop()
  82. pb.cs.Wait()
  83. newCS := NewConsensusState(pb.cs.config, pb.genesisState.Copy(), pb.cs.proxyAppConn, pb.cs.blockStore, pb.cs.mempool)
  84. newCS.SetEventSwitch(pb.cs.evsw)
  85. newCS.startForReplay()
  86. pb.fp.Close()
  87. fp, err := os.OpenFile(pb.fileName, os.O_RDONLY, 0666)
  88. if err != nil {
  89. return err
  90. }
  91. pb.fp = fp
  92. pb.scanner = bufio.NewScanner(fp)
  93. count = pb.count - count
  94. log.Notice(Fmt("Reseting from %d to %d", pb.count, count))
  95. pb.count = 0
  96. pb.cs = newCS
  97. for i := 0; pb.scanner.Scan() && i < count; i++ {
  98. if err := pb.cs.readReplayMessage(pb.scanner.Bytes(), newStepCh); err != nil {
  99. return err
  100. }
  101. pb.count += 1
  102. }
  103. return nil
  104. }
  105. func (cs *ConsensusState) startForReplay() {
  106. log.Warn("Replay commands are disabled until someone updates them and writes tests")
  107. /* TODO:!
  108. // since we replay tocks we just ignore ticks
  109. go func() {
  110. for {
  111. select {
  112. case <-cs.tickChan:
  113. case <-cs.Quit:
  114. return
  115. }
  116. }
  117. }()*/
  118. }
  119. // console function for parsing input and running commands
  120. func (pb *playback) replayConsoleLoop() int {
  121. for {
  122. fmt.Printf("> ")
  123. bufReader := bufio.NewReader(os.Stdin)
  124. line, more, err := bufReader.ReadLine()
  125. if more {
  126. Exit("input is too long")
  127. } else if err != nil {
  128. Exit(err.Error())
  129. }
  130. tokens := strings.Split(string(line), " ")
  131. if len(tokens) == 0 {
  132. continue
  133. }
  134. switch tokens[0] {
  135. case "next":
  136. // "next" -> replay next message
  137. // "next N" -> replay next N messages
  138. if len(tokens) == 1 {
  139. return 0
  140. } else {
  141. i, err := strconv.Atoi(tokens[1])
  142. if err != nil {
  143. fmt.Println("next takes an integer argument")
  144. } else {
  145. return i
  146. }
  147. }
  148. case "back":
  149. // "back" -> go back one message
  150. // "back N" -> go back N messages
  151. // NOTE: "back" is not supported in the state machine design,
  152. // so we restart and replay up to
  153. // ensure all new step events are regenerated as expected
  154. newStepCh := subscribeToEvent(pb.cs.evsw, "replay-test", types.EventStringNewRoundStep(), 1)
  155. if len(tokens) == 1 {
  156. pb.replayReset(1, newStepCh)
  157. } else {
  158. i, err := strconv.Atoi(tokens[1])
  159. if err != nil {
  160. fmt.Println("back takes an integer argument")
  161. } else if i > pb.count {
  162. fmt.Printf("argument to back must not be larger than the current count (%d)\n", pb.count)
  163. } else {
  164. pb.replayReset(i, newStepCh)
  165. }
  166. }
  167. case "rs":
  168. // "rs" -> print entire round state
  169. // "rs short" -> print height/round/step
  170. // "rs <field>" -> print another field of the round state
  171. rs := pb.cs.RoundState
  172. if len(tokens) == 1 {
  173. fmt.Println(rs)
  174. } else {
  175. switch tokens[1] {
  176. case "short":
  177. fmt.Printf("%v/%v/%v\n", rs.Height, rs.Round, rs.Step)
  178. case "validators":
  179. fmt.Println(rs.Validators)
  180. case "proposal":
  181. fmt.Println(rs.Proposal)
  182. case "proposal_block":
  183. fmt.Printf("%v %v\n", rs.ProposalBlockParts.StringShort(), rs.ProposalBlock.StringShort())
  184. case "locked_round":
  185. fmt.Println(rs.LockedRound)
  186. case "locked_block":
  187. fmt.Printf("%v %v\n", rs.LockedBlockParts.StringShort(), rs.LockedBlock.StringShort())
  188. case "votes":
  189. fmt.Println(rs.Votes.StringIndented(" "))
  190. default:
  191. fmt.Println("Unknown option", tokens[1])
  192. }
  193. }
  194. case "n":
  195. fmt.Println(pb.count)
  196. }
  197. }
  198. return 0
  199. }
  200. //--------------------------------------------------------------------------------
  201. // convenience for replay mode
  202. func newConsensusStateForReplay(config cfg.Config) *ConsensusState {
  203. // Get BlockStore
  204. blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir"))
  205. blockStore := bc.NewBlockStore(blockStoreDB)
  206. // Get State
  207. stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir"))
  208. state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  209. // Create proxyAppConn connection (consensus, mempool, query)
  210. proxyApp := proxy.NewAppConns(config, proxy.DefaultClientCreator(config), NewHandshaker(config, state, blockStore))
  211. _, err := proxyApp.Start()
  212. if err != nil {
  213. Exit(Fmt("Error starting proxy app conns: %v", err))
  214. }
  215. // add the chainid to the global config
  216. config.Set("chain_id", state.ChainID)
  217. // Make event switch
  218. eventSwitch := types.NewEventSwitch()
  219. if _, err := eventSwitch.Start(); err != nil {
  220. Exit(Fmt("Failed to start event switch: %v", err))
  221. }
  222. mempool := mempl.NewMempool(config, proxyApp.Mempool())
  223. consensusState := NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  224. consensusState.SetEventSwitch(eventSwitch)
  225. return consensusState
  226. }