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.2 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. consensusState := NewConsensusState(config.Consensus, state.Copy(), proxyApp.Consensus(), blockStore, mempool)
  64. consensusState.SetLogger(logger)
  65. consensusState.SetEventBus(eventBus)
  66. if privValidator != nil {
  67. consensusState.SetPrivValidator(privValidator)
  68. }
  69. // END OF COPY PASTE
  70. /////////////////////////////////////////////////////////////////////////////
  71. // set consensus wal to buffered WAL, which will write all incoming msgs to buffer
  72. var b bytes.Buffer
  73. wr := bufio.NewWriter(&b)
  74. numBlocksWritten := make(chan struct{})
  75. wal := newByteBufferWAL(logger, NewWALEncoder(wr), int64(numBlocks), numBlocksWritten)
  76. // see wal.go#103
  77. wal.Save(EndHeightMessage{0})
  78. consensusState.wal = wal
  79. if err := consensusState.Start(); err != nil {
  80. return nil, errors.Wrap(err, "failed to start consensus state")
  81. }
  82. defer consensusState.Stop()
  83. select {
  84. case <-numBlocksWritten:
  85. wr.Flush()
  86. return b.Bytes(), nil
  87. case <-time.After(1 * time.Minute):
  88. wr.Flush()
  89. return b.Bytes(), fmt.Errorf("waited too long for tendermint to produce %d blocks (grep logs for `wal_generator`)", numBlocks)
  90. }
  91. }
  92. // f**ing long, but unique for each test
  93. func makePathname() string {
  94. // get path
  95. p, err := os.Getwd()
  96. if err != nil {
  97. panic(err)
  98. }
  99. // fmt.Println(p)
  100. sep := string(filepath.Separator)
  101. return strings.Replace(p, sep, "_", -1)
  102. }
  103. func randPort() int {
  104. // returns between base and base + spread
  105. base, spread := 20000, 20000
  106. return base + rand.Intn(spread)
  107. }
  108. func makeAddrs() (string, string, string) {
  109. start := randPort()
  110. return fmt.Sprintf("tcp://0.0.0.0:%d", start),
  111. fmt.Sprintf("tcp://0.0.0.0:%d", start+1),
  112. fmt.Sprintf("tcp://0.0.0.0:%d", start+2)
  113. }
  114. // getConfig returns a config for test cases
  115. func getConfig() *cfg.Config {
  116. pathname := makePathname()
  117. c := cfg.ResetTestRoot(pathname)
  118. // and we use random ports to run in parallel
  119. tm, rpc, grpc := makeAddrs()
  120. c.P2P.ListenAddress = tm
  121. c.RPC.ListenAddress = rpc
  122. c.RPC.GRPCListenAddress = grpc
  123. return c
  124. }
  125. // byteBufferWAL is a WAL which writes all msgs to a byte buffer. Writing stops
  126. // when the heightToStop is reached. Client will be notified via
  127. // signalWhenStopsTo channel.
  128. type byteBufferWAL struct {
  129. enc *WALEncoder
  130. stopped bool
  131. heightToStop int64
  132. signalWhenStopsTo chan<- struct{}
  133. logger log.Logger
  134. }
  135. // needed for determinism
  136. var fixedTime, _ = time.Parse(time.RFC3339, "2017-01-02T15:04:05Z")
  137. func newByteBufferWAL(logger log.Logger, enc *WALEncoder, nBlocks int64, signalStop chan<- struct{}) *byteBufferWAL {
  138. return &byteBufferWAL{
  139. enc: enc,
  140. heightToStop: nBlocks,
  141. signalWhenStopsTo: signalStop,
  142. logger: logger,
  143. }
  144. }
  145. // Save writes message to the internal buffer except when heightToStop is
  146. // reached, in which case it will signal the caller via signalWhenStopsTo and
  147. // skip writing.
  148. func (w *byteBufferWAL) Save(m WALMessage) {
  149. if w.stopped {
  150. w.logger.Debug("WAL already stopped. Not writing message", "msg", m)
  151. return
  152. }
  153. if endMsg, ok := m.(EndHeightMessage); ok {
  154. w.logger.Debug("WAL write end height message", "height", endMsg.Height, "stopHeight", w.heightToStop)
  155. if endMsg.Height == w.heightToStop {
  156. w.logger.Debug("Stopping WAL at height", "height", endMsg.Height)
  157. w.signalWhenStopsTo <- struct{}{}
  158. w.stopped = true
  159. return
  160. }
  161. }
  162. w.logger.Debug("WAL Write Message", "msg", m)
  163. err := w.enc.Encode(&TimedWALMessage{fixedTime, m})
  164. if err != nil {
  165. panic(fmt.Sprintf("failed to encode the msg %v", m))
  166. }
  167. }
  168. func (w *byteBufferWAL) Group() *auto.Group {
  169. panic("not implemented")
  170. }
  171. func (w *byteBufferWAL) SearchForEndHeight(height int64, options *WALSearchOptions) (gr *auto.GroupReader, found bool, err error) {
  172. return nil, false, nil
  173. }
  174. func (w *byteBufferWAL) Start() error { return nil }
  175. func (w *byteBufferWAL) Stop() error { return nil }
  176. func (w *byteBufferWAL) Wait() {}