-
Notifications
You must be signed in to change notification settings - Fork 5
/
service.go
393 lines (335 loc) · 8.5 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// Package micro is a pluggable framework for microservices
package micro // import "go.unistack.org/micro/v3"
import (
"fmt"
"sync"
"go.unistack.org/micro/v3/broker"
"go.unistack.org/micro/v3/client"
"go.unistack.org/micro/v3/config"
"go.unistack.org/micro/v3/logger"
"go.unistack.org/micro/v3/meter"
"go.unistack.org/micro/v3/register"
"go.unistack.org/micro/v3/router"
"go.unistack.org/micro/v3/server"
"go.unistack.org/micro/v3/store"
"go.unistack.org/micro/v3/tracer"
)
// Service is an interface that wraps the lower level components.
// Its works as container with building blocks for service.
type Service interface {
// The service name
Name() string
// Init initialises options
Init(...Option) error
// Options returns the current options
Options() Options
// Logger is for output log from service components
Logger(...string) logger.Logger
// Config if for config handling via load/save methods and also with ability to watch changes
Config(...string) config.Config
// Client is for sync calling services via RPC
Client(...string) client.Client
// Broker is for sending and receiving async events
Broker(...string) broker.Broker
// Server is for handling requests and broker unmarshaled events
Server(...string) server.Server
// Store is for key/val store
Store(...string) store.Store
// Register used by client to lookup other services and server registers on it
Register(...string) register.Register
// Tracer
Tracer(...string) tracer.Tracer
// Router
Router(...string) router.Router
// Meter may be used internally by other component to export metrics
Meter(...string) meter.Meter
// Runtime
// Runtime(string) (runtime.Runtime, bool)
// Profile
// Profile(string) (profile.Profile, bool)
// Run the service and wait for stop
Run() error
// Start the service and not wait
Start() error
// Stop the service
Stop() error
// The service implementation
String() string
}
// RegisterHandler is syntactic sugar for registering a handler
func RegisterHandler(s server.Server, h interface{}, opts ...server.HandlerOption) error {
return s.Handle(s.NewHandler(h, opts...))
}
// RegisterSubscriber is syntactic sugar for registering a subscriber
func RegisterSubscriber(topic string, s server.Server, h interface{}, opts ...server.SubscriberOption) error {
return s.Subscribe(s.NewSubscriber(topic, h, opts...))
}
type service struct {
sync.RWMutex
opts Options
}
// NewService creates and returns a new Service based on the packages within.
func NewService(opts ...Option) Service {
return &service{opts: NewOptions(opts...)}
}
func (s *service) Name() string {
return s.opts.Name
}
// Init initialises options. Additionally it calls cmd.Init
// which parses command line flags. cmd.Init is only called
// on first Init.
//nolint:gocyclo
func (s *service) Init(opts ...Option) error {
var err error
// process options
for _, o := range opts {
if err = o(&s.opts); err != nil {
return err
}
}
for _, cfg := range s.opts.Configs {
if cfg.Options().Struct == nil {
// skip config as the struct not passed
continue
}
if err = cfg.Init(config.Context(cfg.Options().Context)); err != nil {
return err
}
}
for _, log := range s.opts.Loggers {
if err = log.Init(logger.WithContext(log.Options().Context)); err != nil {
return err
}
}
for _, reg := range s.opts.Registers {
if err = reg.Init(register.Context(reg.Options().Context)); err != nil {
return err
}
}
for _, brk := range s.opts.Brokers {
if err = brk.Init(broker.Context(brk.Options().Context)); err != nil {
return err
}
}
for _, str := range s.opts.Stores {
if err = str.Init(store.Context(str.Options().Context)); err != nil {
return err
}
}
for _, srv := range s.opts.Servers {
if err = srv.Init(server.Context(srv.Options().Context)); err != nil {
return err
}
}
for _, cli := range s.opts.Clients {
if err = cli.Init(client.Context(cli.Options().Context)); err != nil {
return err
}
}
return nil
}
func (s *service) Options() Options {
return s.opts
}
func (s *service) Broker(names ...string) broker.Broker {
idx := 0
if len(names) == 1 {
idx = getNameIndex(names[0], s.opts.Brokers)
}
return s.opts.Brokers[idx]
}
func (s *service) Tracer(names ...string) tracer.Tracer {
idx := 0
if len(names) == 1 {
idx = getNameIndex(names[0], s.opts.Tracers)
}
return s.opts.Tracers[idx]
}
func (s *service) Config(names ...string) config.Config {
idx := 0
if len(names) == 1 {
idx = getNameIndex(names[0], s.opts.Configs)
}
return s.opts.Configs[idx]
}
func (s *service) Client(names ...string) client.Client {
idx := 0
if len(names) == 1 {
idx = getNameIndex(names[0], s.opts.Clients)
}
return s.opts.Clients[idx]
}
func (s *service) Server(names ...string) server.Server {
idx := 0
if len(names) == 1 {
idx = getNameIndex(names[0], s.opts.Servers)
}
return s.opts.Servers[idx]
}
func (s *service) Store(names ...string) store.Store {
idx := 0
if len(names) == 1 {
idx = getNameIndex(names[0], s.opts.Stores)
}
return s.opts.Stores[idx]
}
func (s *service) Register(names ...string) register.Register {
idx := 0
if len(names) == 1 {
idx = getNameIndex(names[0], s.opts.Registers)
}
return s.opts.Registers[idx]
}
func (s *service) Logger(names ...string) logger.Logger {
idx := 0
if len(names) == 1 {
idx = getNameIndex(names[0], s.opts.Loggers)
}
return s.opts.Loggers[idx]
}
func (s *service) Router(names ...string) router.Router {
idx := 0
if len(names) == 1 {
idx = getNameIndex(names[0], s.opts.Routers)
}
return s.opts.Routers[idx]
}
func (s *service) Meter(names ...string) meter.Meter {
idx := 0
if len(names) == 1 {
idx = getNameIndex(names[0], s.opts.Meters)
}
return s.opts.Meters[idx]
}
func (s *service) String() string {
return s.opts.Name
}
//nolint:gocyclo
func (s *service) Start() error {
var err error
s.RLock()
config := s.opts
s.RUnlock()
for _, cfg := range s.opts.Configs {
if cfg.Options().Struct == nil {
// skip config as the struct not passed
continue
}
if err = cfg.Load(s.opts.Context); err != nil {
return err
}
}
for _, fn := range s.opts.BeforeStart {
if err = fn(s.opts.Context); err != nil {
return err
}
}
if config.Loggers[0].V(logger.InfoLevel) {
config.Loggers[0].Infof(s.opts.Context, "starting [service] %s version %s", s.Options().Name, s.Options().Version)
}
if len(s.opts.Servers) == 0 {
return fmt.Errorf("cant start nil server")
}
for _, reg := range s.opts.Registers {
if err = reg.Connect(s.opts.Context); err != nil {
return err
}
}
for _, brk := range s.opts.Brokers {
if err = brk.Connect(s.opts.Context); err != nil {
return err
}
}
for _, str := range s.opts.Stores {
if err = str.Connect(s.opts.Context); err != nil {
return err
}
}
for _, srv := range s.opts.Servers {
if err = srv.Start(); err != nil {
return err
}
}
for _, fn := range s.opts.AfterStart {
if err = fn(s.opts.Context); err != nil {
return err
}
}
return nil
}
func (s *service) Stop() error {
s.RLock()
config := s.opts
s.RUnlock()
if config.Loggers[0].V(logger.InfoLevel) {
config.Loggers[0].Infof(s.opts.Context, "stoppping [service] %s", s.Name())
}
var err error
for _, fn := range s.opts.BeforeStop {
if err = fn(s.opts.Context); err != nil {
return err
}
}
for _, srv := range s.opts.Servers {
if err = srv.Stop(); err != nil {
return err
}
}
for _, fn := range s.opts.AfterStop {
if err = fn(s.opts.Context); err != nil {
return err
}
}
for _, reg := range s.opts.Registers {
if err = reg.Disconnect(s.opts.Context); err != nil {
return err
}
}
for _, brk := range s.opts.Brokers {
if err = brk.Disconnect(s.opts.Context); err != nil {
return err
}
}
for _, str := range s.opts.Stores {
if err = str.Disconnect(s.opts.Context); err != nil {
return err
}
}
return nil
}
func (s *service) Run() error {
// start the profiler
/*
if s.opts.Profile != nil {
// to view mutex contention
rtime.SetMutexProfileFraction(5)
// to view blocking profile
rtime.SetBlockProfileRate(1)
if err := s.opts.Profile.Start(); err != nil {
return err
}
defer s.opts.Profile.Stop()
}
*/
if err := s.Start(); err != nil {
return err
}
// wait on context cancel
<-s.opts.Context.Done()
return s.Stop()
}
type nameIface interface {
Name() string
}
func getNameIndex(n string, ifaces interface{}) int {
values, ok := ifaces.([]interface{})
if !ok {
return 0
}
for idx, iface := range values {
if ifc, ok := iface.(nameIface); ok && ifc.Name() == n {
return idx
}
}
return 0
}