simulation.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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/enode"
  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. )
  33. // Simulation provides methods on network, nodes and services
  34. // to manage them.
  35. type Simulation struct {
  36. // Net is exposed as a way to access lower level functionalities
  37. // of p2p/simulations.Network.
  38. Net *simulations.Network
  39. serviceNames []string
  40. cleanupFuncs []func()
  41. buckets map[enode.ID]*sync.Map
  42. pivotNodeID *enode.ID
  43. shutdownWG sync.WaitGroup
  44. done chan struct{}
  45. mu sync.RWMutex
  46. httpSrv *http.Server //attach a HTTP server via SimulationOptions
  47. handler *simulations.Server //HTTP handler for the server
  48. runC chan struct{} //channel where frontend signals it is ready
  49. }
  50. // ServiceFunc is used in New to declare new service constructor.
  51. // The first argument provides ServiceContext from the adapters package
  52. // giving for example the access to NodeID. Second argument is the sync.Map
  53. // where all "global" state related to the service should be kept.
  54. // All cleanups needed for constructed service and any other constructed
  55. // objects should ne provided in a single returned cleanup function.
  56. // Returned cleanup function will be called by Close function
  57. // after network shutdown.
  58. type ServiceFunc func(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Service, cleanup func(), err error)
  59. // New creates a new Simulation instance with new
  60. // simulations.Network initialized with provided services.
  61. // Services map must have unique keys as service names and
  62. // every ServiceFunc must return a node.Service of the unique type.
  63. // This restriction is required by node.Node.Start() function
  64. // which is used to start node.Service returned by ServiceFunc.
  65. func New(services map[string]ServiceFunc) (s *Simulation) {
  66. s = &Simulation{
  67. buckets: make(map[enode.ID]*sync.Map),
  68. done: make(chan struct{}),
  69. }
  70. adapterServices := make(map[string]adapters.ServiceFunc, len(services))
  71. for name, serviceFunc := range services {
  72. // Scope this variables correctly
  73. // as they will be in the adapterServices[name] function accessed later.
  74. name, serviceFunc := name, serviceFunc
  75. s.serviceNames = append(s.serviceNames, name)
  76. adapterServices[name] = func(ctx *adapters.ServiceContext) (node.Service, error) {
  77. b := new(sync.Map)
  78. service, cleanup, err := serviceFunc(ctx, b)
  79. if err != nil {
  80. return nil, err
  81. }
  82. s.mu.Lock()
  83. defer s.mu.Unlock()
  84. if cleanup != nil {
  85. s.cleanupFuncs = append(s.cleanupFuncs, cleanup)
  86. }
  87. s.buckets[ctx.Config.ID] = b
  88. return service, nil
  89. }
  90. }
  91. s.Net = simulations.NewNetwork(
  92. adapters.NewTCPAdapter(adapterServices),
  93. &simulations.NetworkConfig{ID: "0"},
  94. )
  95. return s
  96. }
  97. // RunFunc is the function that will be called
  98. // on Simulation.Run method call.
  99. type RunFunc func(context.Context, *Simulation) error
  100. // Result is the returned value of Simulation.Run method.
  101. type Result struct {
  102. Duration time.Duration
  103. Error error
  104. }
  105. // Run calls the RunFunc function while taking care of
  106. // cancellation provided through the Context.
  107. func (s *Simulation) Run(ctx context.Context, f RunFunc) (r Result) {
  108. //if the option is set to run a HTTP server with the simulation,
  109. //init the server and start it
  110. start := time.Now()
  111. if s.httpSrv != nil {
  112. log.Info("Waiting for frontend to be ready...(send POST /runsim to HTTP server)")
  113. //wait for the frontend to connect
  114. select {
  115. case <-s.runC:
  116. case <-ctx.Done():
  117. return Result{
  118. Duration: time.Since(start),
  119. Error: ctx.Err(),
  120. }
  121. }
  122. log.Info("Received signal from frontend - starting simulation run.")
  123. }
  124. errc := make(chan error)
  125. quit := make(chan struct{})
  126. defer close(quit)
  127. go func() {
  128. select {
  129. case errc <- f(ctx, s):
  130. case <-quit:
  131. }
  132. }()
  133. var err error
  134. select {
  135. case <-ctx.Done():
  136. err = ctx.Err()
  137. case err = <-errc:
  138. }
  139. return Result{
  140. Duration: time.Since(start),
  141. Error: err,
  142. }
  143. }
  144. // Maximal number of parallel calls to cleanup functions on
  145. // Simulation.Close.
  146. var maxParallelCleanups = 10
  147. // Close calls all cleanup functions that are returned by
  148. // ServiceFunc, waits for all of them to finish and other
  149. // functions that explicitly block shutdownWG
  150. // (like Simulation.PeerEvents) and shuts down the network
  151. // at the end. It is used to clean all resources from the
  152. // simulation.
  153. func (s *Simulation) Close() {
  154. close(s.done)
  155. sem := make(chan struct{}, maxParallelCleanups)
  156. s.mu.RLock()
  157. cleanupFuncs := make([]func(), len(s.cleanupFuncs))
  158. for i, f := range s.cleanupFuncs {
  159. if f != nil {
  160. cleanupFuncs[i] = f
  161. }
  162. }
  163. s.mu.RUnlock()
  164. var cleanupWG sync.WaitGroup
  165. for _, cleanup := range cleanupFuncs {
  166. cleanupWG.Add(1)
  167. sem <- struct{}{}
  168. go func(cleanup func()) {
  169. defer cleanupWG.Done()
  170. defer func() { <-sem }()
  171. cleanup()
  172. }(cleanup)
  173. }
  174. cleanupWG.Wait()
  175. if s.httpSrv != nil {
  176. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  177. defer cancel()
  178. err := s.httpSrv.Shutdown(ctx)
  179. if err != nil {
  180. log.Error("Error shutting down HTTP server!", "err", err)
  181. }
  182. close(s.runC)
  183. }
  184. s.shutdownWG.Wait()
  185. s.Net.Shutdown()
  186. }
  187. // Done returns a channel that is closed when the simulation
  188. // is closed by Close method. It is useful for signaling termination
  189. // of all possible goroutines that are created within the test.
  190. func (s *Simulation) Done() <-chan struct{} {
  191. return s.done
  192. }