-
Notifications
You must be signed in to change notification settings - Fork 180
/
service.go
711 lines (570 loc) · 16.1 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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
/*
* Copyright (c) 2018. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
// Package service acts as a factory for all Pydio services.
//
// Pydio services are wrapped around micro services with additional information and ability to declare themselves to the
// registry. Services can be of three main different type :
// - Generic Service : providing a Runner function, they can be used to package any kind of server library as a pydio service
// - Micro Service : GRPC-based services implementing specific protobuf-services
// - Web Service : Services adding more logic and exposing Rest APIs defined by the OpenAPI definitions generated from protobufs.
//
// Package provides additional aspects that can be added to any service and declared by "WithXXX" functions.
package service
import (
"bufio"
"context"
"fmt"
"net"
"os"
"os/exec"
"regexp"
"strings"
"time"
"github.com/gyuho/goraph"
"github.com/micro/go-micro"
"github.com/micro/go-micro/client"
microregistry "github.com/micro/go-micro/registry"
"github.com/micro/go-web"
"github.com/spf13/viper"
"go.uber.org/zap"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/boltdb"
"github.com/pydio/cells/common/config"
"github.com/pydio/cells/common/dao"
"github.com/pydio/cells/common/log"
"github.com/pydio/cells/common/registry"
servicecontext "github.com/pydio/cells/common/service/context"
"github.com/pydio/cells/common/sql"
net2 "github.com/pydio/cells/common/utils/net"
)
const (
TYPE_GENERIC = iota
TYPE_GRPC
TYPE_REST
TYPE_API
)
var (
types = []string{"generic", "grpc", "rest", "api"}
)
type Service interface {
registry.Service
Init(...ServiceOption)
Options() ServiceOptions
}
func buildForkStartParams(name string) []string {
params := []string{
"start",
"--fork",
"--registry", viper.GetString("registry"),
"--registry_address", viper.GetString("registry_address"),
"--registry_cluster_address", viper.GetString("registry_cluster_address"),
"--registry_cluster_routes", viper.GetString("registry_cluster_routes"),
"--broker", viper.GetString("broker"),
"--broker_address", viper.GetString("broker_address"),
}
if viper.GetBool("enable_metrics") {
params = append(params, "--enable_metrics")
}
if viper.GetBool("enable_pprof") {
params = append(params, "--enable_pprof")
}
params = append(params, name)
return params
}
// Service for the pydio app
type service struct {
// Computed by external functions during listing operations
nodes []*microregistry.Node
excluded bool
opts ServiceOptions
node goraph.Node
}
// Checker is a function that checks if the service is correctly Running
type Checker interface {
Check() error
}
type CheckerFunc func() error
// Check implements the Chercker interface
func (f CheckerFunc) Check() error {
return f()
}
type Runner interface {
Run() error
}
type RunnerFunc func() error
func (f RunnerFunc) Run() error {
return f()
}
type Stopper interface {
Stop() error
}
type StopperFunc func() error
func (f StopperFunc) Stop() error {
defer func() {
recover()
}()
return f()
}
type StopFunctionKey struct{}
// HandlerProvider returns a handler function from a micro service
type HandlerProvider func(micro.Service) interface{}
// NewService provides everything needed to run a service, no matter the type
func NewService(opts ...ServiceOption) Service {
s := &service{
opts: newOptions(append(mandatoryOptions, opts...)...),
}
//opts: newOptions(append(mandatoryOptions(), opts...)...),
name := s.Options().Name
// Checking that the service is not bound to a certain IP
peerAddress := config.Get("services", name, "PeerAddress").String("")
if peerAddress != "" && !net2.PeerAddressIsLocal(peerAddress) {
log.Debug("Ignoring this service as peerAddress is not local", zap.String("name", name), zap.String("ip", peerAddress))
return nil
}
// Setting context
ctx, cancel := context.WithCancel(context.Background())
ctx = servicecontext.WithServiceName(ctx, name)
if s.IsGRPC() {
ctx = servicecontext.WithServiceColor(ctx, servicecontext.ServiceColorGrpc)
} else if s.IsREST() {
ctx = servicecontext.WithServiceColor(ctx, servicecontext.ServiceColorRest)
// TODO : adding web services automatic dependencies to auth, this should be done in each service instead
if s.Options().Name != common.SERVICE_REST_NAMESPACE_+common.SERVICE_INSTALL {
s.Init(WithWebAuth())
}
} else {
ctx = servicecontext.WithServiceColor(ctx, servicecontext.ServiceColorOther)
}
// Setting config
s.Init(
Context(ctx),
Cancel(cancel),
Version(common.Version().String()),
Watch(func(ctx context.Context, v common.ConfigValues) {
ctx = servicecontext.WithConfig(ctx, v)
s.Init(Context(ctx))
}),
)
// Finally, register on the main app registry
s.Options().Registry.Register(s)
return s
}
var mandatoryOptions = []ServiceOption{
// Adding the config to the context
AfterInit(func(s Service) error {
ctx := s.Options().Context
cfg := make(config.Map)
if err := config.Get("services", s.Name()).Scan(&cfg); err != nil {
log.Logger(ctx).Error("", zap.Error(err))
return err
}
if cfg == nil {
cfg = make(config.Map)
}
// Retrieving and assigning port to the config
if p := config.Get("ports", s.Name()).Int(0); p != 0 {
cfg.Set("port", p)
}
//log.Logger(ctx).Debug("Service configuration retrieved", zap.String("service", s.Name()), zap.Any("cfg", cfg))
ctx = servicecontext.WithConfig(ctx, cfg)
s.Init(Context(ctx))
return nil
}),
// Setting config watchers
AfterInit(func(s Service) error {
watchers := s.Options().Watchers
if len(watchers) == 0 {
return nil
}
w, err := config.Watch("services", s.Name())
if err != nil {
return err
}
go func() {
defer w.Stop()
for {
ch, err := w.Next()
if err != nil {
break
}
var c config.Map
if err := ch.Scan(&c); err != nil {
continue
}
for _, watcher := range watchers {
watcher(s.Options().Context, c)
}
}
}()
return nil
}),
// Adding the dao to the context
BeforeStart(func(s Service) error {
ctx := s.Options().Context
// Only if we have a DAO
if s.Options().DAO == nil {
return nil
}
var d dao.DAO
driver, dsn := config.GetDatabase(s.Name())
var prefix string
switch v := s.Options().Prefix.(type) {
case func(Service) string:
prefix = v(s)
case string:
prefix = v
default:
prefix = ""
}
switch driver {
case "mysql":
if c := sql.NewDAO(driver, dsn, prefix); c != nil {
d = s.Options().DAO(c)
}
case "sqlite3":
if c := sql.NewDAO(driver, dsn, prefix); c != nil {
d = s.Options().DAO(c)
}
case "boltdb":
if c := boltdb.NewDAO(driver, dsn, prefix); c != nil {
d = s.Options().DAO(c)
}
default:
return fmt.Errorf("unsupported driver type: %s", driver)
}
if d == nil {
return fmt.Errorf("Storage is not available")
}
ctx = servicecontext.WithDAO(ctx, d)
s.Init(Context(ctx))
return nil
}),
// Adding a check before starting the service to ensure only one is started if unique
BeforeStart(func(s Service) error {
ctx := s.Options().Context
if s.MustBeUnique() {
runningServices, err := registry.ListRunningServices()
if err != nil {
return err
}
for _, r := range runningServices {
log.Logger(ctx).Debug("BeforeStart - Check unique ", zap.String("name ", s.Name()), zap.String("name2 ", r.Name()))
if s.Name() == r.Name() {
return fmt.Errorf("already started")
}
}
}
return nil
}),
// Adding a check before starting the service to ensure all dependencies are running
BeforeStart(func(s Service) error {
ctx := s.Options().Context
log.Logger(ctx).Debug("BeforeStart - Check dependencies")
for _, d := range s.Options().Dependencies {
err := Retry(func() error {
runningServices, err := registry.ListRunningServices()
if err != nil {
return err
}
for _, r := range runningServices {
if d.Name == r.Name() {
return nil
}
}
return fmt.Errorf("dependency %s not found", d.Name)
}, 2*time.Second, 20*time.Minute) // This is long for distributed setup
if err != nil {
return err
}
}
log.Logger(ctx).Debug("BeforeStart - Valid dependencies")
return nil
}),
}
func (s *service) Init(opts ...ServiceOption) {
// process options
for _, o := range opts {
o(&s.opts)
}
}
func (s *service) Options() ServiceOptions {
return s.opts
}
func (s *service) BeforeInit() error {
for _, f := range s.Options().BeforeInit {
if err := f(s); err != nil {
return err
}
}
return nil
}
func (s *service) AfterInit() error {
for _, f := range s.Options().AfterInit {
if err := f(s); err != nil {
return err
}
}
return nil
}
// Start a service and its dependencies
func (s *service) Start() {
ctx := s.Options().Context
cancel := s.Options().Cancel
for _, f := range s.Options().BeforeStart {
if err := f(s); err != nil {
log.Logger(ctx).Error("Could not prepare start ", zap.Error(err))
cancel()
return
}
}
if s.Options().Micro != nil {
go func() {
if err := s.Options().MicroInit(s); err != nil {
log.Logger(ctx).Error("Could not micro init ", zap.Error(err))
cancel()
return
}
if err := s.Options().Micro.Run(); err != nil {
log.Logger(ctx).Error("Could not run ", zap.Error(err))
if stopper, ok := s.Options().Micro.(Stopper); ok {
stopper.Stop()
}
cancel()
}
}()
}
if s.Options().Web != nil {
go func() {
if err := s.Options().WebInit(s); err != nil {
log.Logger(ctx).Error("Could not web init ", zap.Error(err))
cancel()
return
}
if err := s.Options().Web.Run(); err != nil {
log.Logger(ctx).Error("Could not run ", zap.Error(err))
if stopper, ok := s.Options().Micro.(Stopper); ok {
stopper.Stop()
}
cancel()
}
}()
}
for _, f := range s.Options().AfterStart {
if err := f(s); err != nil {
log.Logger(ctx).Error("Could not finalize start ", zap.Error(err))
cancel()
}
}
}
// ForkStart uses a fork process to start the service
func (s *service) ForkStart() {
name := s.Options().Name
ctx := s.Options().Context
cancel := s.Options().Cancel
// Do not do anything
cmd := exec.CommandContext(ctx, os.Args[0], buildForkStartParams(name)...)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Logger(ctx).Error("Could not initiate fork ", zap.Error(err))
cancel()
}
stderr, err := cmd.StderrPipe()
if err != nil {
log.Logger(ctx).Error("Could not initiate fork", zap.Error(err))
cancel()
}
scannerOut := bufio.NewScanner(stdout)
go func() {
for scannerOut.Scan() {
log.StdOut.WriteString(strings.TrimRight(scannerOut.Text(), "\n") + "\n")
}
}()
scannerErr := bufio.NewScanner(stderr)
go func() {
for scannerErr.Scan() {
log.StdOut.WriteString(strings.TrimRight(scannerErr.Text(), "\n") + "\n")
}
}()
log.Logger(ctx).Debug("Starting SubProcess: " + name)
if err := cmd.Start(); err != nil {
log.Logger(ctx).Error("Could not start process", zap.Error(err))
cancel()
}
log.Logger(ctx).Debug("Started SubProcess: " + name)
if err := cmd.Wait(); err != nil {
cancel()
}
}
// Start a service and its dependencies
func (s *service) Stop() {
ctx := s.Options().Context
cancel := s.Options().Cancel
for _, f := range s.Options().BeforeStop {
if err := f(s); err != nil {
log.Logger(ctx).Error("Could not prepare stop ", zap.Error(err))
}
}
// Cancelling context should stop the service altogether
cancel()
for _, f := range s.Options().AfterStop {
if err := f(s); err != nil {
log.Logger(ctx).Error("Could not finalize stop ", zap.Error(err))
}
}
}
// IsRunning provides a quick way to check that a service is running.
func (s *service) IsRunning() bool {
ctx := s.getContext()
if err := s.Check(ctx); err != nil {
return false
}
return true
}
// Check the status of the service (globally - not specific to an endpoint)
func (s *service) Check(ctx context.Context) error {
running, err := registry.ListRunningServices()
if err != nil {
return err
}
for _, r := range running {
if s.Name() == r.Name() {
return nil
}
}
return fmt.Errorf("Not found")
}
func (s *service) AddDependency(name string) {
if name == s.Name() {
return
}
s.Init(Dependency(name, []string{""}))
}
func (s *service) GetDependencies() []registry.Service {
var r []registry.Service
for _, d := range s.Options().Dependencies {
for _, rr := range s.Options().Registry.GetServicesByName(d.Name) {
r = append(r, rr)
}
}
return r
}
func (s *service) Name() string {
return s.Options().Name
}
func (s *service) Tags() []string {
return s.Options().Tags
}
func (s *service) Version() string {
return s.Options().Version
}
func (s *service) Description() string {
return s.Options().Description
}
func (s *service) Regexp() *regexp.Regexp {
return s.Options().Regexp
}
func (s *service) Address() string {
address := "127.0.0.1:0"
port := s.Options().Port
if m := s.Options().Micro; m != nil {
address = m.Server().Options().Address
}
if w := s.Options().Web; w != nil {
address = w.Options().Address
}
a, _, err := net.SplitHostPort(address)
if err != nil {
return address
}
if port != "" {
address = net.JoinHostPort(a, port)
}
return address
}
func (s *service) SetExcluded(ex bool) {
s.excluded = ex
}
func (s *service) IsExcluded() bool {
return s.excluded
}
func (s *service) SetRunningNodes(nodes []*microregistry.Node) {
s.nodes = nodes
}
func (s *service) RunningNodes() []*microregistry.Node {
var nodes []*microregistry.Node
for _, p := range registry.GetPeers() {
for _, ms := range p.GetServices(s.Name()) {
nodes = append(nodes, ms.Nodes...)
}
}
return nodes
}
func (s *service) DAO() interface{} {
return s.Options().DAO
}
func (s *service) IsGeneric() bool {
return (s.Options().Micro != nil && !strings.HasPrefix(s.Name(), common.SERVICE_GRPC_NAMESPACE_))
}
func (s *service) IsGRPC() bool {
return s.Options().Micro != nil && strings.HasPrefix(s.Name(), common.SERVICE_GRPC_NAMESPACE_)
}
func (s *service) IsREST() bool {
return s.Options().Web != nil
}
// RequiresFork reads config fork=true to decide whether this service starts in a forked process or not.
func (s *service) AutoStart() bool {
ctx := s.Options().Context
return s.Options().AutoStart || servicecontext.GetConfig(ctx).Bool("autostart")
}
// RequiresFork reads config fork=true to decide whether this service starts in a forked process or not.
func (s *service) RequiresFork() bool {
ctx := s.Options().Context
return s.Options().Fork || servicecontext.GetConfig(ctx).Bool("fork")
}
// RequiresFork reads config fork=true to decide whether this service starts in a forked process or not.
func (s *service) MustBeUnique() bool {
ctx := s.Options().Context
return s.Options().Unique || servicecontext.GetConfig(ctx).Bool("unique")
}
func (s *service) Client() (string, client.Client) {
return s.Options().Micro.Server().Options().Name, s.Options().Micro.Client()
}
func (s *service) MatchesRegexp(o string) bool {
if reg := s.Options().Regexp; reg != nil && reg.MatchString(o) {
if matches := reg.FindStringSubmatch(o); len(matches) == 2 {
s.Init(
Name(matches[0]),
Source(matches[1]),
)
return true
}
}
return false
}
func (s *service) getContext() context.Context {
// if m, ok := (s.micro).(micro.Service); ok {
// return m.Options().Context
// } else if w, ok := (s.micro).(web.Service); ok {
// return w.Options().Context
// }
return nil
}
// RestHandlerBuilder builds a RestHandler
type RestHandlerBuilder func(service web.Service, defaultClient client.Client) interface{}