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.

360 lines
9.3 KiB

  1. package consensus
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "reflect"
  9. "strconv"
  10. "strings"
  11. "time"
  12. . "github.com/tendermint/go-common"
  13. "github.com/tendermint/go-wire"
  14. sm "github.com/tendermint/tendermint/state"
  15. "github.com/tendermint/tendermint/types"
  16. )
  17. // unmarshal and apply a single message to the consensus state
  18. // as if it were received in receiveRoutine
  19. // NOTE: receiveRoutine should not be running
  20. func (cs *ConsensusState) readReplayMessage(msgBytes []byte, newStepCh chan interface{}) error {
  21. var err error
  22. var msg ConsensusLogMessage
  23. wire.ReadJSON(&msg, msgBytes, &err)
  24. if err != nil {
  25. fmt.Println("MsgBytes:", msgBytes, string(msgBytes))
  26. return fmt.Errorf("Error reading json data: %v", err)
  27. }
  28. // for logging
  29. switch m := msg.Msg.(type) {
  30. case types.EventDataRoundState:
  31. log.Notice("Replay: New Step", "height", m.Height, "round", m.Round, "step", m.Step)
  32. // these are playback checks
  33. ticker := time.After(time.Second * 2)
  34. if newStepCh != nil {
  35. select {
  36. case mi := <-newStepCh:
  37. m2 := mi.(types.EventDataRoundState)
  38. if m.Height != m2.Height || m.Round != m2.Round || m.Step != m2.Step {
  39. return fmt.Errorf("RoundState mismatch. Got %v; Expected %v", m2, m)
  40. }
  41. case <-ticker:
  42. return fmt.Errorf("Failed to read off newStepCh")
  43. }
  44. }
  45. case msgInfo:
  46. peerKey := m.PeerKey
  47. if peerKey == "" {
  48. peerKey = "local"
  49. }
  50. switch msg := m.Msg.(type) {
  51. case *ProposalMessage:
  52. p := msg.Proposal
  53. log.Notice("Replay: Proposal", "height", p.Height, "round", p.Round, "header",
  54. p.BlockPartsHeader, "pol", p.POLRound, "peer", peerKey)
  55. case *BlockPartMessage:
  56. log.Notice("Replay: BlockPart", "height", msg.Height, "round", msg.Round, "peer", peerKey)
  57. case *VoteMessage:
  58. v := msg.Vote
  59. log.Notice("Replay: Vote", "height", v.Height, "round", v.Round, "type", v.Type,
  60. "hash", v.BlockHash, "header", v.BlockPartsHeader, "peer", peerKey)
  61. }
  62. cs.handleMsg(m, cs.RoundState)
  63. case timeoutInfo:
  64. log.Notice("Replay: Timeout", "height", m.Height, "round", m.Round, "step", m.Step, "dur", m.Duration)
  65. cs.handleTimeout(m, cs.RoundState)
  66. default:
  67. return fmt.Errorf("Replay: Unknown ConsensusLogMessage type: %v", reflect.TypeOf(msg.Msg))
  68. }
  69. return nil
  70. }
  71. // replay only those messages since the last block.
  72. // timeoutRoutine should run concurrently to read off tickChan
  73. func (cs *ConsensusState) catchupReplay(height int) error {
  74. if !cs.wal.Exists() {
  75. return nil
  76. }
  77. // set replayMode
  78. cs.replayMode = true
  79. defer func() { cs.replayMode = false }()
  80. // starting from end of file,
  81. // read messages until a new height is found
  82. nLines, err := cs.wal.SeekFromEnd(func(lineBytes []byte) bool {
  83. var err error
  84. var msg ConsensusLogMessage
  85. wire.ReadJSON(&msg, lineBytes, &err)
  86. if err != nil {
  87. panic(Fmt("Failed to read cs_msg_log json: %v", err))
  88. }
  89. m, ok := msg.Msg.(types.EventDataRoundState)
  90. if ok && m.Step == RoundStepNewHeight.String() {
  91. // TODO: ensure the height matches
  92. return true
  93. }
  94. return false
  95. })
  96. if err != nil {
  97. return err
  98. }
  99. var beginning bool // if we had to go back to the beginning
  100. if c, _ := cs.wal.fp.Seek(0, 1); c == 0 {
  101. beginning = true
  102. }
  103. log.Notice("Catchup by replaying consensus messages", "n", nLines)
  104. // now we can replay the latest nLines on consensus state
  105. // note we can't use scan because we've already been reading from the file
  106. reader := bufio.NewReader(cs.wal.fp)
  107. for i := 0; i < nLines; i++ {
  108. msgBytes, err := reader.ReadBytes('\n')
  109. if err == io.EOF {
  110. break
  111. } else if err != nil {
  112. return err
  113. } else if len(msgBytes) == 0 {
  114. continue
  115. } else if len(msgBytes) == 1 && msgBytes[0] == '\n' {
  116. continue
  117. }
  118. // the first msg is the NewHeight event (if we're not at the beginning), so we can ignore it
  119. if !beginning && i == 1 {
  120. continue
  121. }
  122. // NOTE: since the priv key is set when the msgs are received
  123. // it will attempt to eg double sign but we can just ignore it
  124. // since the votes will be replayed and we'll get to the next step
  125. if err := cs.readReplayMessage(msgBytes, nil); err != nil {
  126. return err
  127. }
  128. }
  129. log.Notice("Done catchup replay")
  130. return nil
  131. }
  132. //--------------------------------------------------------
  133. // replay messages interactively or all at once
  134. // Interactive playback
  135. func (cs ConsensusState) ReplayConsole(file string) error {
  136. return cs.replay(file, true)
  137. }
  138. // Full playback, with tests
  139. func (cs ConsensusState) ReplayMessages(file string) error {
  140. return cs.replay(file, false)
  141. }
  142. // replay all msgs or start the console
  143. func (cs *ConsensusState) replay(file string, console bool) error {
  144. if cs.IsRunning() {
  145. return errors.New("cs is already running, cannot replay")
  146. }
  147. if cs.wal != nil {
  148. return errors.New("cs wal is open, cannot replay")
  149. }
  150. cs.startForReplay()
  151. // ensure all new step events are regenerated as expected
  152. newStepCh := subscribeToEvent(cs.evsw, "replay-test", types.EventStringNewRoundStep(), 1)
  153. // just open the file for reading, no need to use wal
  154. fp, err := os.OpenFile(file, os.O_RDONLY, 0666)
  155. if err != nil {
  156. return err
  157. }
  158. pb := newPlayback(file, fp, cs, cs.state.Copy())
  159. defer pb.fp.Close()
  160. var nextN int // apply N msgs in a row
  161. for pb.scanner.Scan() {
  162. if nextN == 0 && console {
  163. nextN = pb.replayConsoleLoop()
  164. }
  165. if err := pb.cs.readReplayMessage(pb.scanner.Bytes(), newStepCh); err != nil {
  166. return err
  167. }
  168. if nextN > 0 {
  169. nextN -= 1
  170. }
  171. pb.count += 1
  172. }
  173. return nil
  174. }
  175. //------------------------------------------------
  176. // playback manager
  177. type playback struct {
  178. cs *ConsensusState
  179. fp *os.File
  180. scanner *bufio.Scanner
  181. count int // how many lines/msgs into the file are we
  182. // replays can be reset to beginning
  183. fileName string // so we can close/reopen the file
  184. genesisState *sm.State // so the replay session knows where to restart from
  185. }
  186. func newPlayback(fileName string, fp *os.File, cs *ConsensusState, genState *sm.State) *playback {
  187. return &playback{
  188. cs: cs,
  189. fp: fp,
  190. fileName: fileName,
  191. genesisState: genState,
  192. scanner: bufio.NewScanner(fp),
  193. }
  194. }
  195. // go back count steps by resetting the state and running (pb.count - count) steps
  196. func (pb *playback) replayReset(count int, newStepCh chan interface{}) error {
  197. pb.cs.Stop()
  198. newCS := NewConsensusState(pb.cs.config, pb.genesisState.Copy(), pb.cs.proxyAppConn, pb.cs.blockStore, pb.cs.mempool)
  199. newCS.SetEventSwitch(pb.cs.evsw)
  200. newCS.startForReplay()
  201. pb.fp.Close()
  202. fp, err := os.OpenFile(pb.fileName, os.O_RDONLY, 0666)
  203. if err != nil {
  204. return err
  205. }
  206. pb.fp = fp
  207. pb.scanner = bufio.NewScanner(fp)
  208. count = pb.count - count
  209. log.Notice(Fmt("Reseting from %d to %d", pb.count, count))
  210. pb.count = 0
  211. pb.cs = newCS
  212. for i := 0; pb.scanner.Scan() && i < count; i++ {
  213. if err := pb.cs.readReplayMessage(pb.scanner.Bytes(), newStepCh); err != nil {
  214. return err
  215. }
  216. pb.count += 1
  217. }
  218. return nil
  219. }
  220. func (cs *ConsensusState) startForReplay() {
  221. // don't want to start full cs
  222. cs.BaseService.OnStart()
  223. // since we replay tocks we just ignore ticks
  224. go func() {
  225. for {
  226. select {
  227. case <-cs.tickChan:
  228. case <-cs.Quit:
  229. return
  230. }
  231. }
  232. }()
  233. }
  234. // console function for parsing input and running commands
  235. func (pb *playback) replayConsoleLoop() int {
  236. for {
  237. fmt.Printf("> ")
  238. bufReader := bufio.NewReader(os.Stdin)
  239. line, more, err := bufReader.ReadLine()
  240. if more {
  241. Exit("input is too long")
  242. } else if err != nil {
  243. Exit(err.Error())
  244. }
  245. tokens := strings.Split(string(line), " ")
  246. if len(tokens) == 0 {
  247. continue
  248. }
  249. switch tokens[0] {
  250. case "next":
  251. // "next" -> replay next message
  252. // "next N" -> replay next N messages
  253. if len(tokens) == 1 {
  254. return 0
  255. } else {
  256. i, err := strconv.Atoi(tokens[1])
  257. if err != nil {
  258. fmt.Println("next takes an integer argument")
  259. } else {
  260. return i
  261. }
  262. }
  263. case "back":
  264. // "back" -> go back one message
  265. // "back N" -> go back N messages
  266. // NOTE: "back" is not supported in the state machine design,
  267. // so we restart and replay up to
  268. // ensure all new step events are regenerated as expected
  269. newStepCh := subscribeToEvent(pb.cs.evsw, "replay-test", types.EventStringNewRoundStep(), 1)
  270. if len(tokens) == 1 {
  271. pb.replayReset(1, newStepCh)
  272. } else {
  273. i, err := strconv.Atoi(tokens[1])
  274. if err != nil {
  275. fmt.Println("back takes an integer argument")
  276. } else if i > pb.count {
  277. fmt.Printf("argument to back must not be larger than the current count (%d)\n", pb.count)
  278. } else {
  279. pb.replayReset(i, newStepCh)
  280. }
  281. }
  282. case "rs":
  283. // "rs" -> print entire round state
  284. // "rs short" -> print height/round/step
  285. // "rs <field>" -> print another field of the round state
  286. rs := pb.cs.RoundState
  287. if len(tokens) == 1 {
  288. fmt.Println(rs)
  289. } else {
  290. switch tokens[1] {
  291. case "short":
  292. fmt.Printf("%v/%v/%v\n", rs.Height, rs.Round, rs.Step)
  293. case "validators":
  294. fmt.Println(rs.Validators)
  295. case "proposal":
  296. fmt.Println(rs.Proposal)
  297. case "proposal_block":
  298. fmt.Printf("%v %v\n", rs.ProposalBlockParts.StringShort(), rs.ProposalBlock.StringShort())
  299. case "locked_round":
  300. fmt.Println(rs.LockedRound)
  301. case "locked_block":
  302. fmt.Printf("%v %v\n", rs.LockedBlockParts.StringShort(), rs.LockedBlock.StringShort())
  303. case "votes":
  304. fmt.Println(rs.Votes.StringIndented(" "))
  305. default:
  306. fmt.Println("Unknown option", tokens[1])
  307. }
  308. }
  309. case "n":
  310. fmt.Println(pb.count)
  311. }
  312. }
  313. return 0
  314. }