forked from micro/micro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
235 lines (192 loc) · 5.3 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package service
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"runtime"
"syscall"
"github.com/urfave/cli/v2"
"github.com/crazybber/micro/v3/cmd"
"github.com/crazybber/micro/v3/service/client"
mudebug "github.com/crazybber/micro/v3/service/debug"
debug "github.com/crazybber/micro/v3/service/debug/handler"
"github.com/crazybber/micro/v3/service/logger"
"github.com/crazybber/micro/v3/service/model"
"github.com/crazybber/micro/v3/service/server"
)
var (
// errMissingName is returned by service.Run when a service is run
// prior to it's name being set.
errMissingName = errors.New("missing service name")
)
// Service is a Micro Service which honours the go-micro/service interface
type Service struct {
opts Options
}
// Run the default service and waits for it to exist
func Run() {
// setup a new service, calling New() will trigger the cmd package
// to parse the command line and
srv := New()
if err := srv.Run(); err == errMissingName {
fmt.Println("Micro services must be run using \"micro run\"")
os.Exit(1)
} else if err != nil {
logger.Fatalf("Error running %v service: %v", srv.Name(), err)
}
}
// New returns a new Micro Service
func New(opts ...Option) *Service {
// before extracts service options from the CLI flags. These
// aren't set by the cmd package to prevent a circular dependancy.
// prepend them to the array so options passed by the user to this
// function are applied after (taking precedence)
before := func(ctx *cli.Context) error {
if n := ctx.String("service_name"); len(n) > 0 {
opts = append(opts, Name(n))
}
if v := ctx.String("service_version"); len(v) > 0 {
opts = append(opts, Version(v))
}
// service address injected by the runtime takes priority as the service port must match the
// port the server is running on
if a := ctx.String("service_address"); len(a) > 0 {
opts = append(opts, Address(a))
}
return nil
}
// setup micro, this triggers the Before
// function which parses CLI flags.
cmd.New(cmd.SetupOnly(), cmd.Before(before)).Run()
// return a new service
return &Service{opts: newOptions(opts...)}
}
// Name of the service
func (s *Service) Name() string {
return s.opts.Name
}
// Version of the service
func (s *Service) Version() string {
return s.opts.Version
}
// Handle registers a handler
func (s *Service) Handle(v interface{}) error {
return s.Server().Handle(s.Server().NewHandler(v))
}
// Subscribe registers a subscriber
func (s *Service) Subscribe(topic string, v interface{}) error {
return s.Server().Subscribe(s.Server().NewSubscriber(topic, v))
}
func (s *Service) Init(opts ...Option) {
for _, o := range opts {
o(&s.opts)
}
}
func (s *Service) Options() Options {
return s.opts
}
func (s *Service) Client() client.Client {
return client.DefaultClient
}
func (s *Service) Model() model.Model {
return model.DefaultModel
}
func (s *Service) Server() server.Server {
return server.DefaultServer
}
func (s *Service) String() string {
return "micro"
}
func (s *Service) Start() error {
for _, fn := range s.opts.BeforeStart {
if err := fn(); err != nil {
return err
}
}
if err := s.Server().Start(); err != nil {
return err
}
for _, fn := range s.opts.AfterStart {
if err := fn(); err != nil {
return err
}
}
return nil
}
func (s *Service) Stop() error {
var gerr error
for _, fn := range s.opts.BeforeStop {
if err := fn(); err != nil {
gerr = err
}
}
if err := server.DefaultServer.Stop(); err != nil {
return err
}
for _, fn := range s.opts.AfterStop {
if err := fn(); err != nil {
gerr = err
}
}
return gerr
}
// Run the service
func (s *Service) Run() error {
// ensure service's have a name, this is injected by the runtime manager
if len(s.Name()) == 0 {
return errMissingName
}
// register the debug handler
s.Server().Handle(
s.Server().NewHandler(
debug.NewHandler(),
server.InternalHandler(true),
),
)
// start the profiler
if mudebug.DefaultProfiler != nil {
// to view mutex contention
runtime.SetMutexProfileFraction(5)
// to view blocking profile
runtime.SetBlockProfileRate(1)
if err := mudebug.DefaultProfiler.Start(); err != nil {
return err
}
defer mudebug.DefaultProfiler.Stop()
}
if logger.V(logger.InfoLevel, logger.DefaultLogger) {
logger.Infof("Starting [service] %s", s.Name())
}
if err := s.Start(); err != nil {
return err
}
ch := make(chan os.Signal, 1)
if s.opts.Signal {
signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL)
}
// wait on kill signal
<-ch
return s.Stop()
}
// Handle is syntactic sugar for registering a handler
func Handle(h interface{}, opts ...server.HandlerOption) error {
return server.DefaultServer.Handle(server.DefaultServer.NewHandler(h, opts...))
}
// Subscribe is syntactic sugar for registering a subscriber
func Subscribe(topic string, h interface{}, opts ...server.SubscriberOption) error {
return server.DefaultServer.Subscribe(server.DefaultServer.NewSubscriber(topic, h, opts...))
}
// Event is an object messages are published to
type Event struct {
topic string
}
// Publish a message to an event
func (e *Event) Publish(ctx context.Context, msg interface{}) error {
return client.Publish(ctx, client.NewMessage(e.topic, msg))
}
// NewEvent creates a new event publisher
func NewEvent(topic string) *Event {
return &Event{topic}
}