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.

199 lines
4.3 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "sync"
  6. "github.com/tendermint/tendermint/libs/log"
  7. )
  8. var (
  9. // errAlreadyStopped is returned when somebody tries to stop an already
  10. // stopped service (without resetting it).
  11. errAlreadyStopped = errors.New("already stopped")
  12. )
  13. // Service defines a service that can be started, stopped, and reset.
  14. type Service interface {
  15. // Start is called to start the service, which should run until
  16. // the context terminates. If the service is already running, Start
  17. // must report an error.
  18. Start(context.Context) error
  19. // Return true if the service is running
  20. IsRunning() bool
  21. // Wait blocks until the service is stopped.
  22. Wait()
  23. }
  24. // Implementation describes the implementation that the
  25. // BaseService implementation wraps.
  26. type Implementation interface {
  27. // Called by the Services Start Method
  28. OnStart(context.Context) error
  29. // Called when the service's context is canceled.
  30. OnStop()
  31. }
  32. /*
  33. Classical-inheritance-style service declarations. Services can be started, then
  34. stopped, but cannot be restarted.
  35. Users must implement OnStart/OnStop methods. In the absence of errors, these
  36. methods are guaranteed to be called at most once. If OnStart returns an error,
  37. service won't be marked as started, so the user can call Start again.
  38. The BaseService implementation ensures that the OnStop method is
  39. called after the context passed to Start is canceled.
  40. Typical usage:
  41. type FooService struct {
  42. BaseService
  43. // private fields
  44. }
  45. func NewFooService() *FooService {
  46. fs := &FooService{
  47. // init
  48. }
  49. fs.BaseService = *NewBaseService(log, "FooService", fs)
  50. return fs
  51. }
  52. func (fs *FooService) OnStart(ctx context.Context) error {
  53. // initialize private fields
  54. // start subroutines, etc.
  55. }
  56. func (fs *FooService) OnStop() {
  57. // close/destroy private fields
  58. // stop subroutines, etc.
  59. }
  60. */
  61. type BaseService struct {
  62. logger log.Logger
  63. name string
  64. mtx sync.Mutex
  65. quit <-chan (struct{})
  66. cancel context.CancelFunc
  67. // The "subclass" of BaseService
  68. impl Implementation
  69. }
  70. // NewBaseService creates a new BaseService.
  71. func NewBaseService(logger log.Logger, name string, impl Implementation) *BaseService {
  72. return &BaseService{
  73. logger: logger,
  74. name: name,
  75. impl: impl,
  76. }
  77. }
  78. // Start starts the Service and calls its OnStart method. An error
  79. // will be returned if the service is stopped, but not if it is
  80. // already running.
  81. func (bs *BaseService) Start(ctx context.Context) error {
  82. bs.mtx.Lock()
  83. defer bs.mtx.Unlock()
  84. if bs.quit != nil {
  85. return nil
  86. }
  87. select {
  88. case <-bs.quit:
  89. return errAlreadyStopped
  90. default:
  91. bs.logger.Info("starting service", "service", bs.name, "impl", bs.name)
  92. if err := bs.impl.OnStart(ctx); err != nil {
  93. return err
  94. }
  95. // we need a separate context to ensure that we start
  96. // a thread that will get cleaned up and that the
  97. // Stop/Wait functions work as expected.
  98. srvCtx, cancel := context.WithCancel(context.Background())
  99. bs.cancel = cancel
  100. bs.quit = srvCtx.Done()
  101. go func(ctx context.Context) {
  102. select {
  103. case <-srvCtx.Done():
  104. // this means stop was called manually
  105. return
  106. case <-ctx.Done():
  107. bs.Stop()
  108. }
  109. bs.logger.Info("stopped service",
  110. "service", bs.name)
  111. }(ctx)
  112. return nil
  113. }
  114. }
  115. // Stop manually terminates the service by calling OnStop method from
  116. // the implementation and releases all resources related to the
  117. // service.
  118. func (bs *BaseService) Stop() {
  119. bs.mtx.Lock()
  120. defer bs.mtx.Unlock()
  121. if bs.quit == nil {
  122. return
  123. }
  124. select {
  125. case <-bs.quit:
  126. return
  127. default:
  128. bs.logger.Info("stopping service", "service", bs.name)
  129. bs.impl.OnStop()
  130. bs.cancel()
  131. return
  132. }
  133. }
  134. // IsRunning implements Service by returning true or false depending on the
  135. // service's state.
  136. func (bs *BaseService) IsRunning() bool {
  137. bs.mtx.Lock()
  138. defer bs.mtx.Unlock()
  139. if bs.quit == nil {
  140. return false
  141. }
  142. select {
  143. case <-bs.quit:
  144. return false
  145. default:
  146. return true
  147. }
  148. }
  149. func (bs *BaseService) getWait() <-chan struct{} {
  150. bs.mtx.Lock()
  151. defer bs.mtx.Unlock()
  152. if bs.quit == nil {
  153. out := make(chan struct{})
  154. close(out)
  155. return out
  156. }
  157. return bs.quit
  158. }
  159. // Wait blocks until the service is stopped.
  160. func (bs *BaseService) Wait() { <-bs.getWait() }
  161. // String implements Service by returning a string representation of the service.
  162. func (bs *BaseService) String() string { return bs.name }