simulation.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package simulation
  17. import (
  18. "context"
  19. "errors"
  20. "net/http"
  21. "sync"
  22. "time"
  23. "github.com/ethereum/go-ethereum/log"
  24. "github.com/ethereum/go-ethereum/node"
  25. "github.com/ethereum/go-ethereum/p2p/discover"
  26. "github.com/ethereum/go-ethereum/p2p/simulations"
  27. "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
  28. )
  29. // Common errors that are returned by functions in this package.
  30. var (
  31. ErrNodeNotFound = errors.New("node not found")
  32. ErrNoPivotNode = errors.New("no pivot node set")
  33. )
  34. // Simulation provides methods on network, nodes and services
  35. // to manage them.
  36. type Simulation struct {
  37. // Net is exposed as a way to access lower level functionalities
  38. // of p2p/simulations.Network.
  39. Net *simulations.Network
  40. serviceNames []string
  41. cleanupFuncs []func()
  42. buckets map[discover.NodeID]*sync.Map
  43. pivotNodeID *discover.NodeID
  44. shutdownWG sync.WaitGroup
  45. done chan struct{}
  46. mu sync.RWMutex
  47. httpSrv *http.Server //attach a HTTP server via SimulationOptions
  48. handler *simulations.Server //HTTP handler for the server
  49. runC chan struct{} //channel where frontend signals it is ready
  50. }
  51. // ServiceFunc is used in New to declare new service constructor.
  52. // The first argument provides ServiceContext from the adapters package
  53. // giving for example the access to NodeID. Second argument is the sync.Map
  54. // where all "global" state related to the service should be kept.
  55. // All cleanups needed for constructed service and any other constructed
  56. // objects should ne provided in a single returned cleanup function.
  57. // Returned cleanup function will be called by Close function
  58. // after network shutdown.
  59. type ServiceFunc func(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Service, cleanup func(), err error)
  60. // New creates a new Simulation instance with new
  61. // simulations.Network initialized with provided services.
  62. func New(services map[string]ServiceFunc) (s *Simulation) {
  63. s = &Simulation{
  64. buckets: make(map[discover.NodeID]*sync.Map),
  65. done: make(chan struct{}),
  66. }
  67. adapterServices := make(map[string]adapters.ServiceFunc, len(services))
  68. for name, serviceFunc := range services {
  69. s.serviceNames = append(s.serviceNames, name)
  70. adapterServices[name] = func(ctx *adapters.ServiceContext) (node.Service, error) {
  71. b := new(sync.Map)
  72. service, cleanup, err := serviceFunc(ctx, b)
  73. if err != nil {
  74. return nil, err
  75. }
  76. s.mu.Lock()
  77. defer s.mu.Unlock()
  78. if cleanup != nil {
  79. s.cleanupFuncs = append(s.cleanupFuncs, cleanup)
  80. }
  81. s.buckets[ctx.Config.ID] = b
  82. return service, nil
  83. }
  84. }
  85. s.Net = simulations.NewNetwork(
  86. adapters.NewSimAdapter(adapterServices),
  87. &simulations.NetworkConfig{ID: "0"},
  88. )
  89. return s
  90. }
  91. // RunFunc is the function that will be called
  92. // on Simulation.Run method call.
  93. type RunFunc func(context.Context, *Simulation) error
  94. // Result is the returned value of Simulation.Run method.
  95. type Result struct {
  96. Duration time.Duration
  97. Error error
  98. }
  99. // Run calls the RunFunc function while taking care of
  100. // cancelation provided through the Context.
  101. func (s *Simulation) Run(ctx context.Context, f RunFunc) (r Result) {
  102. //if the option is set to run a HTTP server with the simulation,
  103. //init the server and start it
  104. start := time.Now()
  105. if s.httpSrv != nil {
  106. log.Info("Waiting for frontend to be ready...(send POST /runsim to HTTP server)")
  107. //wait for the frontend to connect
  108. select {
  109. case <-s.runC:
  110. case <-ctx.Done():
  111. return Result{
  112. Duration: time.Since(start),
  113. Error: ctx.Err(),
  114. }
  115. }
  116. log.Info("Received signal from frontend - starting simulation run.")
  117. }
  118. errc := make(chan error)
  119. quit := make(chan struct{})
  120. defer close(quit)
  121. go func() {
  122. select {
  123. case errc <- f(ctx, s):
  124. case <-quit:
  125. }
  126. }()
  127. var err error
  128. select {
  129. case <-ctx.Done():
  130. err = ctx.Err()
  131. case err = <-errc:
  132. }
  133. return Result{
  134. Duration: time.Since(start),
  135. Error: err,
  136. }
  137. }
  138. // Maximal number of parallel calls to cleanup functions on
  139. // Simulation.Close.
  140. var maxParallelCleanups = 10
  141. // Close calls all cleanup functions that are returned by
  142. // ServiceFunc, waits for all of them to finish and other
  143. // functions that explicitly block shutdownWG
  144. // (like Simulation.PeerEvents) and shuts down the network
  145. // at the end. It is used to clean all resources from the
  146. // simulation.
  147. func (s *Simulation) Close() {
  148. close(s.done)
  149. // Close all connections before calling the Network Shutdown.
  150. // It is possible that p2p.Server.Stop will block if there are
  151. // existing connections.
  152. for _, c := range s.Net.Conns {
  153. if c.Up {
  154. s.Net.Disconnect(c.One, c.Other)
  155. }
  156. }
  157. s.shutdownWG.Wait()
  158. s.Net.Shutdown()
  159. sem := make(chan struct{}, maxParallelCleanups)
  160. s.mu.RLock()
  161. cleanupFuncs := make([]func(), len(s.cleanupFuncs))
  162. for i, f := range s.cleanupFuncs {
  163. if f != nil {
  164. cleanupFuncs[i] = f
  165. }
  166. }
  167. s.mu.RUnlock()
  168. var cleanupWG sync.WaitGroup
  169. for _, cleanup := range cleanupFuncs {
  170. cleanupWG.Add(1)
  171. sem <- struct{}{}
  172. go func(cleanup func()) {
  173. defer cleanupWG.Done()
  174. defer func() { <-sem }()
  175. cleanup()
  176. }(cleanup)
  177. }
  178. cleanupWG.Wait()
  179. if s.httpSrv != nil {
  180. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  181. defer cancel()
  182. err := s.httpSrv.Shutdown(ctx)
  183. if err != nil {
  184. log.Error("Error shutting down HTTP server!", "err", err)
  185. }
  186. close(s.runC)
  187. }
  188. }
  189. // Done returns a channel that is closed when the simulation
  190. // is closed by Close method. It is useful for signaling termination
  191. // of all possible goroutines that are created within the test.
  192. func (s *Simulation) Done() <-chan struct{} {
  193. return s.done
  194. }