-
Notifications
You must be signed in to change notification settings - Fork 16
/
service.go
95 lines (81 loc) · 1.68 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package service
import (
"context"
"fmt"
"github.com/Qitmeer/qng/rpc/api"
"reflect"
"sync/atomic"
)
type Service struct {
ctx context.Context
cancel context.CancelFunc
started int32
shutdown int32
services *ServiceRegistry
kind reflect.Type
}
func (s *Service) Start() error {
if atomic.AddInt32(&s.started, 1) != 1 {
return fmt.Errorf("Service is already in the process of started")
}
if s.kind != nil {
log.Debug(fmt.Sprintf("(%v) service start", s.kind))
}
s.InitContext()
if s.services != nil {
err := s.services.StartAll()
if err != nil {
atomic.AddInt32(&s.started, -1)
return err
}
}
return nil
}
func (s *Service) Stop() error {
if !s.IsStarted() {
return nil
}
if atomic.AddInt32(&s.shutdown, 1) != 1 {
return fmt.Errorf("Service is already in the process of shutting down")
}
if s.kind != nil {
log.Debug(fmt.Sprintf("(%v) service stop", s.kind))
}
s.cancel()
if s.services != nil {
return s.services.StopAll()
}
return nil
}
func (s *Service) IsStarted() bool {
return atomic.LoadInt32(&s.started) != 0
}
func (s *Service) IsShutdown() bool {
return atomic.LoadInt32(&s.shutdown) != 0
}
func (s *Service) APIs() []api.API {
if s.services != nil {
return s.services.APIs()
}
return nil
}
func (s *Service) Status() error {
return nil
}
func (s *Service) Context() context.Context {
return s.ctx
}
func (s *Service) InitContext() {
if s.ctx == nil {
s.ctx, s.cancel = context.WithCancel(context.Background())
}
}
func (s *Service) Services() *ServiceRegistry {
return s.services
}
func (s *Service) InitServices() {
s.services = NewServiceRegistry()
}
func (s *Service) SetKind(kind reflect.Type) {
s.kind = kind
}