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.

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