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.

271 lines
7.1 KiB

  1. package consensus
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "strconv"
  8. "strings"
  9. . "github.com/tendermint/go-common"
  10. cfg "github.com/tendermint/go-config"
  11. dbm "github.com/tendermint/go-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. // don't want to start full cs
  107. cs.BaseService.OnStart()
  108. log.Warn("Replay commands are disabled until someone updates them and writes tests")
  109. /* TODO:!
  110. // since we replay tocks we just ignore ticks
  111. go func() {
  112. for {
  113. select {
  114. case <-cs.tickChan:
  115. case <-cs.Quit:
  116. return
  117. }
  118. }
  119. }()*/
  120. }
  121. // console function for parsing input and running commands
  122. func (pb *playback) replayConsoleLoop() int {
  123. for {
  124. fmt.Printf("> ")
  125. bufReader := bufio.NewReader(os.Stdin)
  126. line, more, err := bufReader.ReadLine()
  127. if more {
  128. Exit("input is too long")
  129. } else if err != nil {
  130. Exit(err.Error())
  131. }
  132. tokens := strings.Split(string(line), " ")
  133. if len(tokens) == 0 {
  134. continue
  135. }
  136. switch tokens[0] {
  137. case "next":
  138. // "next" -> replay next message
  139. // "next N" -> replay next N messages
  140. if len(tokens) == 1 {
  141. return 0
  142. } else {
  143. i, err := strconv.Atoi(tokens[1])
  144. if err != nil {
  145. fmt.Println("next takes an integer argument")
  146. } else {
  147. return i
  148. }
  149. }
  150. case "back":
  151. // "back" -> go back one message
  152. // "back N" -> go back N messages
  153. // NOTE: "back" is not supported in the state machine design,
  154. // so we restart and replay up to
  155. // ensure all new step events are regenerated as expected
  156. newStepCh := subscribeToEvent(pb.cs.evsw, "replay-test", types.EventStringNewRoundStep(), 1)
  157. if len(tokens) == 1 {
  158. pb.replayReset(1, newStepCh)
  159. } else {
  160. i, err := strconv.Atoi(tokens[1])
  161. if err != nil {
  162. fmt.Println("back takes an integer argument")
  163. } else if i > pb.count {
  164. fmt.Printf("argument to back must not be larger than the current count (%d)\n", pb.count)
  165. } else {
  166. pb.replayReset(i, newStepCh)
  167. }
  168. }
  169. case "rs":
  170. // "rs" -> print entire round state
  171. // "rs short" -> print height/round/step
  172. // "rs <field>" -> print another field of the round state
  173. rs := pb.cs.RoundState
  174. if len(tokens) == 1 {
  175. fmt.Println(rs)
  176. } else {
  177. switch tokens[1] {
  178. case "short":
  179. fmt.Printf("%v/%v/%v\n", rs.Height, rs.Round, rs.Step)
  180. case "validators":
  181. fmt.Println(rs.Validators)
  182. case "proposal":
  183. fmt.Println(rs.Proposal)
  184. case "proposal_block":
  185. fmt.Printf("%v %v\n", rs.ProposalBlockParts.StringShort(), rs.ProposalBlock.StringShort())
  186. case "locked_round":
  187. fmt.Println(rs.LockedRound)
  188. case "locked_block":
  189. fmt.Printf("%v %v\n", rs.LockedBlockParts.StringShort(), rs.LockedBlock.StringShort())
  190. case "votes":
  191. fmt.Println(rs.Votes.StringIndented(" "))
  192. default:
  193. fmt.Println("Unknown option", tokens[1])
  194. }
  195. }
  196. case "n":
  197. fmt.Println(pb.count)
  198. }
  199. }
  200. return 0
  201. }
  202. //--------------------------------------------------------------------------------
  203. // convenience for replay mode
  204. func newConsensusStateForReplay(config cfg.Config) *ConsensusState {
  205. // Get BlockStore
  206. blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir"))
  207. blockStore := bc.NewBlockStore(blockStoreDB)
  208. // Get State
  209. stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir"))
  210. state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  211. // Create proxyAppConn connection (consensus, mempool, query)
  212. proxyApp := proxy.NewAppConns(config, proxy.DefaultClientCreator(config), sm.NewHandshaker(config, state, blockStore, ReplayLastBlock))
  213. _, err := proxyApp.Start()
  214. if err != nil {
  215. Exit(Fmt("Error starting proxy app conns: %v", err))
  216. }
  217. // add the chainid to the global config
  218. config.Set("chain_id", state.ChainID)
  219. // Make event switch
  220. eventSwitch := types.NewEventSwitch()
  221. if _, err := eventSwitch.Start(); err != nil {
  222. Exit(Fmt("Failed to start event switch: %v", err))
  223. }
  224. mempool := mempl.NewMempool(config, proxyApp.Mempool())
  225. consensusState := NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  226. consensusState.SetEventSwitch(eventSwitch)
  227. return consensusState
  228. }