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.

203 lines
5.7 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
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/atomic"
  6. "github.com/tendermint/tendermint/libs/log"
  7. )
  8. var (
  9. // ErrAlreadyStarted is returned when somebody tries to start an already
  10. // running service.
  11. ErrAlreadyStarted = errors.New("already started")
  12. // ErrAlreadyStopped is returned when somebody tries to stop an already
  13. // stopped service (without resetting it).
  14. ErrAlreadyStopped = errors.New("already stopped")
  15. // ErrNotStarted is returned when somebody tries to stop a not running
  16. // service.
  17. ErrNotStarted = errors.New("not started")
  18. )
  19. // Service defines a service that can be started, stopped, and reset.
  20. type Service interface {
  21. // Start is called to start the service, which should run until
  22. // the context terminates. If the service is already running, Start
  23. // must report an error.
  24. Start(context.Context) error
  25. // Return true if the service is running
  26. IsRunning() bool
  27. // String representation of the service
  28. String() string
  29. // Wait blocks until the service is stopped.
  30. Wait()
  31. }
  32. // Implementation describes the implementation that the
  33. // BaseService implementation wraps.
  34. type Implementation interface {
  35. Service
  36. // Called by the Services Start Method
  37. OnStart(context.Context) error
  38. // Called when the service's context is canceled.
  39. OnStop()
  40. }
  41. /*
  42. Classical-inheritance-style service declarations. Services can be started, then
  43. stopped, then optionally restarted.
  44. Users can override the OnStart/OnStop methods. In the absence of errors, these
  45. methods are guaranteed to be called at most once. If OnStart returns an error,
  46. service won't be marked as started, so the user can call Start again.
  47. A call to Reset will panic, unless OnReset is overwritten, allowing
  48. OnStart/OnStop to be called again.
  49. The caller must ensure that Start and Stop are not called concurrently.
  50. It is ok to call Stop without calling Start first.
  51. Typical usage:
  52. type FooService struct {
  53. BaseService
  54. // private fields
  55. }
  56. func NewFooService() *FooService {
  57. fs := &FooService{
  58. // init
  59. }
  60. fs.BaseService = *NewBaseService(log, "FooService", fs)
  61. return fs
  62. }
  63. func (fs *FooService) OnStart(ctx context.Context) error {
  64. fs.BaseService.OnStart() // Always call the overridden method.
  65. // initialize private fields
  66. // start subroutines, etc.
  67. }
  68. func (fs *FooService) OnStop() error {
  69. fs.BaseService.OnStop() // Always call the overridden method.
  70. // close/destroy private fields
  71. // stop subroutines, etc.
  72. }
  73. */
  74. type BaseService struct {
  75. Logger log.Logger
  76. name string
  77. started uint32 // atomic
  78. stopped uint32 // atomic
  79. quit chan struct{}
  80. // The "subclass" of BaseService
  81. impl Implementation
  82. }
  83. // NewBaseService creates a new BaseService.
  84. func NewBaseService(logger log.Logger, name string, impl Implementation) *BaseService {
  85. if logger == nil {
  86. logger = log.NewNopLogger()
  87. }
  88. return &BaseService{
  89. Logger: logger,
  90. name: name,
  91. quit: make(chan struct{}),
  92. impl: impl,
  93. }
  94. }
  95. // Start starts the Service and calls its OnStart method. An error will be
  96. // returned if the service is already running or stopped. To restart a
  97. // stopped service, call Reset.
  98. func (bs *BaseService) Start(ctx context.Context) error {
  99. if atomic.CompareAndSwapUint32(&bs.started, 0, 1) {
  100. if atomic.LoadUint32(&bs.stopped) == 1 {
  101. bs.Logger.Error("not starting service; already stopped", "service", bs.name, "impl", bs.impl.String())
  102. atomic.StoreUint32(&bs.started, 0)
  103. return ErrAlreadyStopped
  104. }
  105. bs.Logger.Info("starting service", "service", bs.name, "impl", bs.impl.String())
  106. if err := bs.impl.OnStart(ctx); err != nil {
  107. // revert flag
  108. atomic.StoreUint32(&bs.started, 0)
  109. return err
  110. }
  111. go func(ctx context.Context) {
  112. <-ctx.Done()
  113. if err := bs.Stop(); err != nil {
  114. bs.Logger.Error("stopped service",
  115. "err", err.Error(),
  116. "service", bs.name,
  117. "impl", bs.impl.String())
  118. }
  119. bs.Logger.Info("stopped service",
  120. "service", bs.name,
  121. "impl", bs.impl.String())
  122. }(ctx)
  123. return nil
  124. }
  125. bs.Logger.Debug("not starting service; already started", "service", bs.name, "impl", bs.impl.String())
  126. return ErrAlreadyStarted
  127. }
  128. // OnStart implements Service by doing nothing.
  129. // NOTE: Do not put anything in here,
  130. // that way users don't need to call BaseService.OnStart()
  131. func (bs *BaseService) OnStart(ctx context.Context) error { return nil }
  132. // Stop implements Service by calling OnStop (if defined) and closing quit
  133. // channel. An error will be returned if the service is already stopped.
  134. func (bs *BaseService) Stop() error {
  135. if atomic.CompareAndSwapUint32(&bs.stopped, 0, 1) {
  136. if atomic.LoadUint32(&bs.started) == 0 {
  137. bs.Logger.Error("not stopping service; not started yet", "service", bs.name, "impl", bs.impl.String())
  138. atomic.StoreUint32(&bs.stopped, 0)
  139. return ErrNotStarted
  140. }
  141. bs.Logger.Info("stopping service", "service", bs.name, "impl", bs.impl.String())
  142. bs.impl.OnStop()
  143. close(bs.quit)
  144. return nil
  145. }
  146. bs.Logger.Debug("not stopping service; already stopped", "service", bs.name, "impl", bs.impl.String())
  147. return ErrAlreadyStopped
  148. }
  149. // OnStop implements Service by doing nothing.
  150. // NOTE: Do not put anything in here,
  151. // that way users don't need to call BaseService.OnStop()
  152. func (bs *BaseService) OnStop() {}
  153. // IsRunning implements Service by returning true or false depending on the
  154. // service's state.
  155. func (bs *BaseService) IsRunning() bool {
  156. return atomic.LoadUint32(&bs.started) == 1 && atomic.LoadUint32(&bs.stopped) == 0
  157. }
  158. // Wait blocks until the service is stopped.
  159. func (bs *BaseService) Wait() { <-bs.quit }
  160. // String implements Service by returning a string representation of the service.
  161. func (bs *BaseService) String() string { return bs.name }
  162. // Quit Implements Service by returning a quit channel.
  163. func (bs *BaseService) Quit() <-chan struct{} { return bs.quit }