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.

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