simulation.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. "github.com/ethereum/go-ethereum/swarm/network"
  29. )
  30. // Common errors that are returned by functions in this package.
  31. var (
  32. ErrNodeNotFound = errors.New("node not found")
  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[enode.ID]*sync.Map
  43. shutdownWG sync.WaitGroup
  44. done chan struct{}
  45. mu sync.RWMutex
  46. neighbourhoodSize int
  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
  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. neighbourhoodSize: network.NewKadParams().NeighbourhoodSize,
  70. }
  71. adapterServices := make(map[string]adapters.ServiceFunc, len(services))
  72. for name, serviceFunc := range services {
  73. // Scope this variables correctly
  74. // as they will be in the adapterServices[name] function accessed later.
  75. name, serviceFunc := name, serviceFunc
  76. s.serviceNames = append(s.serviceNames, name)
  77. adapterServices[name] = func(ctx *adapters.ServiceContext) (node.Service, error) {
  78. s.mu.Lock()
  79. defer s.mu.Unlock()
  80. b, ok := s.buckets[ctx.Config.ID]
  81. if !ok {
  82. b = new(sync.Map)
  83. }
  84. service, cleanup, err := serviceFunc(ctx, b)
  85. if err != nil {
  86. return nil, err
  87. }
  88. if cleanup != nil {
  89. s.cleanupFuncs = append(s.cleanupFuncs, cleanup)
  90. }
  91. s.buckets[ctx.Config.ID] = b
  92. return service, nil
  93. }
  94. }
  95. s.Net = simulations.NewNetwork(
  96. adapters.NewTCPAdapter(adapterServices),
  97. &simulations.NetworkConfig{ID: "0"},
  98. )
  99. return s
  100. }
  101. // RunFunc is the function that will be called
  102. // on Simulation.Run method call.
  103. type RunFunc func(context.Context, *Simulation) error
  104. // Result is the returned value of Simulation.Run method.
  105. type Result struct {
  106. Duration time.Duration
  107. Error error
  108. }
  109. // Run calls the RunFunc function while taking care of
  110. // cancellation provided through the Context.
  111. func (s *Simulation) Run(ctx context.Context, f RunFunc) (r Result) {
  112. //if the option is set to run a HTTP server with the simulation,
  113. //init the server and start it
  114. start := time.Now()
  115. if s.httpSrv != nil {
  116. log.Info("Waiting for frontend to be ready...(send POST /runsim to HTTP server)")
  117. //wait for the frontend to connect
  118. select {
  119. case <-s.runC:
  120. case <-ctx.Done():
  121. return Result{
  122. Duration: time.Since(start),
  123. Error: ctx.Err(),
  124. }
  125. }
  126. log.Info("Received signal from frontend - starting simulation run.")
  127. }
  128. errc := make(chan error)
  129. quit := make(chan struct{})
  130. defer close(quit)
  131. go func() {
  132. select {
  133. case errc <- f(ctx, s):
  134. case <-quit:
  135. }
  136. }()
  137. var err error
  138. select {
  139. case <-ctx.Done():
  140. err = ctx.Err()
  141. case err = <-errc:
  142. }
  143. return Result{
  144. Duration: time.Since(start),
  145. Error: err,
  146. }
  147. }
  148. // Maximal number of parallel calls to cleanup functions on
  149. // Simulation.Close.
  150. var maxParallelCleanups = 10
  151. // Close calls all cleanup functions that are returned by
  152. // ServiceFunc, waits for all of them to finish and other
  153. // functions that explicitly block shutdownWG
  154. // (like Simulation.PeerEvents) and shuts down the network
  155. // at the end. It is used to clean all resources from the
  156. // simulation.
  157. func (s *Simulation) Close() {
  158. close(s.done)
  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. s.shutdownWG.Wait()
  189. s.Net.Shutdown()
  190. }
  191. // Done returns a channel that is closed when the simulation
  192. // is closed by Close method. It is useful for signaling termination
  193. // of all possible goroutines that are created within the test.
  194. func (s *Simulation) Done() <-chan struct{} {
  195. return s.done
  196. }