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.

377 lines
9.7 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 == io.EOF {
  94. log.Warn("Replay: wal.group.Search returned EOF", "height", csHeight)
  95. return nil
  96. } else if err != nil {
  97. return err
  98. }
  99. if !found {
  100. return errors.New(Fmt("WAL does not contain height %d.", csHeight))
  101. }
  102. defer gr.Close()
  103. log.Notice("Catchup by replaying consensus messages", "height", csHeight)
  104. for {
  105. line, err := gr.ReadLine()
  106. if err != nil {
  107. if err == io.EOF {
  108. break
  109. } else {
  110. return err
  111. }
  112. }
  113. // NOTE: since the priv key is set when the msgs are received
  114. // it will attempt to eg double sign but we can just ignore it
  115. // since the votes will be replayed and we'll get to the next step
  116. if err := cs.readReplayMessage([]byte(line), nil); err != nil {
  117. return err
  118. }
  119. }
  120. log.Notice("Replay: Done")
  121. return nil
  122. }
  123. //--------------------------------------------------------
  124. // replay messages interactively or all at once
  125. // Interactive playback
  126. func (cs ConsensusState) ReplayConsole(file string) error {
  127. return cs.replay(file, true)
  128. }
  129. // Full playback, with tests
  130. func (cs ConsensusState) ReplayMessages(file string) error {
  131. return cs.replay(file, false)
  132. }
  133. // replay all msgs or start the console
  134. func (cs *ConsensusState) replay(file string, console bool) error {
  135. if cs.IsRunning() {
  136. return errors.New("cs is already running, cannot replay")
  137. }
  138. if cs.wal != nil {
  139. return errors.New("cs wal is open, cannot replay")
  140. }
  141. cs.startForReplay()
  142. // ensure all new step events are regenerated as expected
  143. newStepCh := subscribeToEvent(cs.evsw, "replay-test", types.EventStringNewRoundStep(), 1)
  144. // just open the file for reading, no need to use wal
  145. fp, err := os.OpenFile(file, os.O_RDONLY, 0666)
  146. if err != nil {
  147. return err
  148. }
  149. pb := newPlayback(file, fp, cs, cs.state.Copy())
  150. defer pb.fp.Close()
  151. var nextN int // apply N msgs in a row
  152. for pb.scanner.Scan() {
  153. if nextN == 0 && console {
  154. nextN = pb.replayConsoleLoop()
  155. }
  156. if err := pb.cs.readReplayMessage(pb.scanner.Bytes(), newStepCh); err != nil {
  157. return err
  158. }
  159. if nextN > 0 {
  160. nextN -= 1
  161. }
  162. pb.count += 1
  163. }
  164. return nil
  165. }
  166. //------------------------------------------------
  167. // playback manager
  168. type playback struct {
  169. cs *ConsensusState
  170. fp *os.File
  171. scanner *bufio.Scanner
  172. count int // how many lines/msgs into the file are we
  173. // replays can be reset to beginning
  174. fileName string // so we can close/reopen the file
  175. genesisState *sm.State // so the replay session knows where to restart from
  176. }
  177. func newPlayback(fileName string, fp *os.File, cs *ConsensusState, genState *sm.State) *playback {
  178. return &playback{
  179. cs: cs,
  180. fp: fp,
  181. fileName: fileName,
  182. genesisState: genState,
  183. scanner: bufio.NewScanner(fp),
  184. }
  185. }
  186. // go back count steps by resetting the state and running (pb.count - count) steps
  187. func (pb *playback) replayReset(count int, newStepCh chan interface{}) error {
  188. pb.cs.Stop()
  189. pb.cs.Wait()
  190. newCS := NewConsensusState(pb.cs.config, pb.genesisState.Copy(), pb.cs.proxyAppConn, pb.cs.blockStore, pb.cs.mempool)
  191. newCS.SetEventSwitch(pb.cs.evsw)
  192. newCS.startForReplay()
  193. pb.fp.Close()
  194. fp, err := os.OpenFile(pb.fileName, os.O_RDONLY, 0666)
  195. if err != nil {
  196. return err
  197. }
  198. pb.fp = fp
  199. pb.scanner = bufio.NewScanner(fp)
  200. count = pb.count - count
  201. log.Notice(Fmt("Reseting from %d to %d", pb.count, count))
  202. pb.count = 0
  203. pb.cs = newCS
  204. for i := 0; pb.scanner.Scan() && i < count; i++ {
  205. if err := pb.cs.readReplayMessage(pb.scanner.Bytes(), newStepCh); err != nil {
  206. return err
  207. }
  208. pb.count += 1
  209. }
  210. return nil
  211. }
  212. func (cs *ConsensusState) startForReplay() {
  213. // don't want to start full cs
  214. cs.BaseService.OnStart()
  215. log.Warn("Replay commands are disabled until someone updates them and writes tests")
  216. /* TODO:!
  217. // since we replay tocks we just ignore ticks
  218. go func() {
  219. for {
  220. select {
  221. case <-cs.tickChan:
  222. case <-cs.Quit:
  223. return
  224. }
  225. }
  226. }()*/
  227. }
  228. // console function for parsing input and running commands
  229. func (pb *playback) replayConsoleLoop() int {
  230. for {
  231. fmt.Printf("> ")
  232. bufReader := bufio.NewReader(os.Stdin)
  233. line, more, err := bufReader.ReadLine()
  234. if more {
  235. Exit("input is too long")
  236. } else if err != nil {
  237. Exit(err.Error())
  238. }
  239. tokens := strings.Split(string(line), " ")
  240. if len(tokens) == 0 {
  241. continue
  242. }
  243. switch tokens[0] {
  244. case "next":
  245. // "next" -> replay next message
  246. // "next N" -> replay next N messages
  247. if len(tokens) == 1 {
  248. return 0
  249. } else {
  250. i, err := strconv.Atoi(tokens[1])
  251. if err != nil {
  252. fmt.Println("next takes an integer argument")
  253. } else {
  254. return i
  255. }
  256. }
  257. case "back":
  258. // "back" -> go back one message
  259. // "back N" -> go back N messages
  260. // NOTE: "back" is not supported in the state machine design,
  261. // so we restart and replay up to
  262. // ensure all new step events are regenerated as expected
  263. newStepCh := subscribeToEvent(pb.cs.evsw, "replay-test", types.EventStringNewRoundStep(), 1)
  264. if len(tokens) == 1 {
  265. pb.replayReset(1, newStepCh)
  266. } else {
  267. i, err := strconv.Atoi(tokens[1])
  268. if err != nil {
  269. fmt.Println("back takes an integer argument")
  270. } else if i > pb.count {
  271. fmt.Printf("argument to back must not be larger than the current count (%d)\n", pb.count)
  272. } else {
  273. pb.replayReset(i, newStepCh)
  274. }
  275. }
  276. case "rs":
  277. // "rs" -> print entire round state
  278. // "rs short" -> print height/round/step
  279. // "rs <field>" -> print another field of the round state
  280. rs := pb.cs.RoundState
  281. if len(tokens) == 1 {
  282. fmt.Println(rs)
  283. } else {
  284. switch tokens[1] {
  285. case "short":
  286. fmt.Printf("%v/%v/%v\n", rs.Height, rs.Round, rs.Step)
  287. case "validators":
  288. fmt.Println(rs.Validators)
  289. case "proposal":
  290. fmt.Println(rs.Proposal)
  291. case "proposal_block":
  292. fmt.Printf("%v %v\n", rs.ProposalBlockParts.StringShort(), rs.ProposalBlock.StringShort())
  293. case "locked_round":
  294. fmt.Println(rs.LockedRound)
  295. case "locked_block":
  296. fmt.Printf("%v %v\n", rs.LockedBlockParts.StringShort(), rs.LockedBlock.StringShort())
  297. case "votes":
  298. fmt.Println(rs.Votes.StringIndented(" "))
  299. default:
  300. fmt.Println("Unknown option", tokens[1])
  301. }
  302. }
  303. case "n":
  304. fmt.Println(pb.count)
  305. }
  306. }
  307. return 0
  308. }
  309. //--------------------------------------------------------------------------------
  310. // Parses marker lines of the form:
  311. // #HEIGHT: 12345
  312. func makeHeightSearchFunc(height int) auto.SearchFunc {
  313. return func(line string) (int, error) {
  314. line = strings.TrimRight(line, "\n")
  315. parts := strings.Split(line, " ")
  316. if len(parts) != 2 {
  317. return -1, errors.New("Line did not have 2 parts")
  318. }
  319. i, err := strconv.Atoi(parts[1])
  320. if err != nil {
  321. return -1, errors.New("Failed to parse INFO: " + err.Error())
  322. }
  323. if height < i {
  324. return 1, nil
  325. } else if height == i {
  326. return 0, nil
  327. } else {
  328. return -1, nil
  329. }
  330. }
  331. }