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.

215 lines
6.7 KiB

  1. package consensus
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "time"
  11. "github.com/pkg/errors"
  12. "github.com/tendermint/tendermint/abci/example/kvstore"
  13. bc "github.com/tendermint/tendermint/blockchain"
  14. cfg "github.com/tendermint/tendermint/config"
  15. auto "github.com/tendermint/tendermint/libs/autofile"
  16. cmn "github.com/tendermint/tendermint/libs/common"
  17. "github.com/tendermint/tendermint/libs/db"
  18. "github.com/tendermint/tendermint/libs/log"
  19. "github.com/tendermint/tendermint/privval"
  20. "github.com/tendermint/tendermint/proxy"
  21. sm "github.com/tendermint/tendermint/state"
  22. "github.com/tendermint/tendermint/types"
  23. )
  24. // WALGenerateNBlocks generates a consensus WAL. It does this by spining up a
  25. // stripped down version of node (proxy app, event bus, consensus state) with a
  26. // persistent kvstore application and special consensus wal instance
  27. // (byteBufferWAL) and waits until numBlocks are created. If the node fails to produce given numBlocks, it returns an error.
  28. func WALGenerateNBlocks(wr io.Writer, numBlocks int) (err error) {
  29. config := getConfig()
  30. app := kvstore.NewPersistentKVStoreApplication(filepath.Join(config.DBDir(), "wal_generator"))
  31. logger := log.TestingLogger().With("wal_generator", "wal_generator")
  32. logger.Info("generating WAL (last height msg excluded)", "numBlocks", numBlocks)
  33. /////////////////////////////////////////////////////////////////////////////
  34. // COPY PASTE FROM node.go WITH A FEW MODIFICATIONS
  35. // NOTE: we can't import node package because of circular dependency
  36. privValidatorFile := config.PrivValidatorFile()
  37. privValidator := privval.LoadOrGenFilePV(privValidatorFile)
  38. genDoc, err := types.GenesisDocFromFile(config.GenesisFile())
  39. if err != nil {
  40. return errors.Wrap(err, "failed to read genesis file")
  41. }
  42. stateDB := db.NewMemDB()
  43. blockStoreDB := db.NewMemDB()
  44. state, err := sm.MakeGenesisState(genDoc)
  45. if err != nil {
  46. return errors.Wrap(err, "failed to make genesis state")
  47. }
  48. blockStore := bc.NewBlockStore(blockStoreDB)
  49. proxyApp := proxy.NewAppConns(proxy.NewLocalClientCreator(app))
  50. proxyApp.SetLogger(logger.With("module", "proxy"))
  51. if err := proxyApp.Start(); err != nil {
  52. return errors.Wrap(err, "failed to start proxy app connections")
  53. }
  54. defer proxyApp.Stop()
  55. eventBus := types.NewEventBus()
  56. eventBus.SetLogger(logger.With("module", "events"))
  57. if err := eventBus.Start(); err != nil {
  58. return errors.Wrap(err, "failed to start event bus")
  59. }
  60. defer eventBus.Stop()
  61. mempool := sm.MockMempool{}
  62. evpool := sm.MockEvidencePool{}
  63. blockExec := sm.NewBlockExecutor(stateDB, log.TestingLogger(), proxyApp.Consensus(), mempool, evpool)
  64. consensusState := NewConsensusState(config.Consensus, state.Copy(), blockExec, blockStore, mempool, evpool)
  65. consensusState.SetLogger(logger)
  66. consensusState.SetEventBus(eventBus)
  67. if privValidator != nil {
  68. consensusState.SetPrivValidator(privValidator)
  69. }
  70. // END OF COPY PASTE
  71. /////////////////////////////////////////////////////////////////////////////
  72. // set consensus wal to buffered WAL, which will write all incoming msgs to buffer
  73. numBlocksWritten := make(chan struct{})
  74. wal := newByteBufferWAL(logger, NewWALEncoder(wr), int64(numBlocks), numBlocksWritten)
  75. // see wal.go#103
  76. wal.Write(EndHeightMessage{0})
  77. consensusState.wal = wal
  78. if err := consensusState.Start(); err != nil {
  79. return errors.Wrap(err, "failed to start consensus state")
  80. }
  81. select {
  82. case <-numBlocksWritten:
  83. consensusState.Stop()
  84. return nil
  85. case <-time.After(1 * time.Minute):
  86. consensusState.Stop()
  87. return fmt.Errorf("waited too long for tendermint to produce %d blocks (grep logs for `wal_generator`)", numBlocks)
  88. }
  89. }
  90. //WALWithNBlocks returns a WAL content with numBlocks.
  91. func WALWithNBlocks(numBlocks int) (data []byte, err error) {
  92. var b bytes.Buffer
  93. wr := bufio.NewWriter(&b)
  94. if err := WALGenerateNBlocks(wr, numBlocks); err != nil {
  95. return []byte{}, err
  96. }
  97. wr.Flush()
  98. return b.Bytes(), nil
  99. }
  100. // f**ing long, but unique for each test
  101. func makePathname() string {
  102. // get path
  103. p, err := os.Getwd()
  104. if err != nil {
  105. panic(err)
  106. }
  107. // fmt.Println(p)
  108. sep := string(filepath.Separator)
  109. return strings.Replace(p, sep, "_", -1)
  110. }
  111. func randPort() int {
  112. // returns between base and base + spread
  113. base, spread := 20000, 20000
  114. return base + cmn.RandIntn(spread)
  115. }
  116. func makeAddrs() (string, string, string) {
  117. start := randPort()
  118. return fmt.Sprintf("tcp://0.0.0.0:%d", start),
  119. fmt.Sprintf("tcp://0.0.0.0:%d", start+1),
  120. fmt.Sprintf("tcp://0.0.0.0:%d", start+2)
  121. }
  122. // getConfig returns a config for test cases
  123. func getConfig() *cfg.Config {
  124. pathname := makePathname()
  125. c := cfg.ResetTestRoot(fmt.Sprintf("%s_%d", pathname, cmn.RandInt()))
  126. // and we use random ports to run in parallel
  127. tm, rpc, grpc := makeAddrs()
  128. c.P2P.ListenAddress = tm
  129. c.RPC.ListenAddress = rpc
  130. c.RPC.GRPCListenAddress = grpc
  131. return c
  132. }
  133. // byteBufferWAL is a WAL which writes all msgs to a byte buffer. Writing stops
  134. // when the heightToStop is reached. Client will be notified via
  135. // signalWhenStopsTo channel.
  136. type byteBufferWAL struct {
  137. enc *WALEncoder
  138. stopped bool
  139. heightToStop int64
  140. signalWhenStopsTo chan<- struct{}
  141. logger log.Logger
  142. }
  143. // needed for determinism
  144. var fixedTime, _ = time.Parse(time.RFC3339, "2017-01-02T15:04:05Z")
  145. func newByteBufferWAL(logger log.Logger, enc *WALEncoder, nBlocks int64, signalStop chan<- struct{}) *byteBufferWAL {
  146. return &byteBufferWAL{
  147. enc: enc,
  148. heightToStop: nBlocks,
  149. signalWhenStopsTo: signalStop,
  150. logger: logger,
  151. }
  152. }
  153. // Save writes message to the internal buffer except when heightToStop is
  154. // reached, in which case it will signal the caller via signalWhenStopsTo and
  155. // skip writing.
  156. func (w *byteBufferWAL) Write(m WALMessage) {
  157. if w.stopped {
  158. w.logger.Debug("WAL already stopped. Not writing message", "msg", m)
  159. return
  160. }
  161. if endMsg, ok := m.(EndHeightMessage); ok {
  162. w.logger.Debug("WAL write end height message", "height", endMsg.Height, "stopHeight", w.heightToStop)
  163. if endMsg.Height == w.heightToStop {
  164. w.logger.Debug("Stopping WAL at height", "height", endMsg.Height)
  165. w.signalWhenStopsTo <- struct{}{}
  166. w.stopped = true
  167. return
  168. }
  169. }
  170. w.logger.Debug("WAL Write Message", "msg", m)
  171. err := w.enc.Encode(&TimedWALMessage{fixedTime, m})
  172. if err != nil {
  173. panic(fmt.Sprintf("failed to encode the msg %v", m))
  174. }
  175. }
  176. func (w *byteBufferWAL) WriteSync(m WALMessage) {
  177. w.Write(m)
  178. }
  179. func (w *byteBufferWAL) Group() *auto.Group {
  180. panic("not implemented")
  181. }
  182. func (w *byteBufferWAL) SearchForEndHeight(height int64, options *WALSearchOptions) (gr *auto.GroupReader, found bool, err error) {
  183. return nil, false, nil
  184. }
  185. func (w *byteBufferWAL) Start() error { return nil }
  186. func (w *byteBufferWAL) Stop() error { return nil }
  187. func (w *byteBufferWAL) Wait() {}