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.

200 lines
6.3 KiB

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