-
Notifications
You must be signed in to change notification settings - Fork 180
/
service.go
789 lines (626 loc) · 17.9 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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
/*
* 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"
"math/rand"
"net"
"os"
"os/exec"
"regexp"
"runtime/debug"
"strings"
"time"
"github.com/gyuho/goraph"
micro "github.com/micro/go-micro"
"github.com/micro/go-micro/client"
microregistry "github.com/micro/go-micro/registry"
web "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"
errorUtils "github.com/pydio/cells/common/utils/error"
unet "github.com/pydio/cells/common/utils/net"
"github.com/pydio/cells/x/configx"
)
var (
DefaultRegisterTTL = 10 * time.Minute
)
const (
configSrvKeyFork = "fork"
configSrvKeyAutoStart = "autostart"
configSrvKeyForkDebug = "debugFork"
configSrvKeyUnique = "unique"
)
// Service definition
type Service interface {
registry.Service
Init(...ServiceOption)
Options() ServiceOptions
Done() chan (struct{})
}
func buildForkStartParams(serviceName string) []string {
//r := viper.GetString("registry")
//if r == "memory" {
r := fmt.Sprintf("grpc://:%d", viper.GetInt("port_registry"))
//}
//b := viper.GetString("broker")
//if b == "memory" {
b := fmt.Sprintf("grpc://:%d", viper.GetInt("port_broker"))
//}
params := []string{
"start",
"--fork",
// "--config", "remote",
"--registry", r,
"--broker", b,
}
if viper.GetBool("enable_metrics") {
params = append(params, "--enable_metrics")
}
if viper.GetBool("enable_pprof") {
params = append(params, "--enable_pprof")
}
if config.Get("services", serviceName, configSrvKeyForkDebug).Bool() /*|| strings.HasPrefix(serviceName, "pydio.grpc.data.")*/ {
params = append(params, "--log", "debug")
}
// Use regexp to specify that we want to start that specific service
params = append(params, "^"+serviceName+"$")
bindFlags := config.DefaultBindOverrideToFlags()
if len(bindFlags) > 0 {
params = append(params, bindFlags...)
}
return params
}
// Service for the pydio app
type service struct {
// Computed by external functions during listing operations
nodes []*microregistry.Node
excluded bool
origCtx context.Context
opts ServiceOptions
node goraph.Node
done chan (struct{})
}
// Runnable service definition
type Runnable interface {
Run() error
}
// RunnableFunc provides ability to use a function as a run service
type RunnableFunc func() error
// Run function as a service
func (f RunnableFunc) Run() error {
return f()
}
// Addressable service definition
type Addressable interface {
Addresses() []net.Addr
}
// NonAddressable service definition
type NonAddressable interface {
NoAddress() string
}
// Starter service definition
type Starter interface {
Start() error
}
// Stopper service definiion
type Stopper interface {
Stop() error
}
// StopperFunc allows to use a function as a stopper service
type StopperFunc func() error
// Stop service with recover
func (f StopperFunc) Stop() error {
defer func() {
recover()
}()
return f()
}
// StopFunctionKey definition
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...)...),
done: make(chan struct{}),
}
name := s.Options().Name
// Checking that the service is not bound to a certain IP
peerAddress := config.Get("services", name, "PeerAddress").String()
if peerAddress != "" && !unet.PeerAddressIsLocal(peerAddress) {
log.Debug("Ignoring this service as peerAddress is not local", zap.String("name", name), zap.String("ip", peerAddress))
return nil
}
ctx := s.Options().Context
if ctx == nil {
ctx = context.Background()
}
// Setting context
ctx = servicecontext.WithServiceName(ctx, name)
// TODO : adding web services automatic dependencies to auth, this should be done in each service instead
if s.IsREST() && s.Options().Name != common.ServiceRestNamespace_+common.ServiceInstall {
s.Init(WithWebAuth())
}
s.origCtx = ctx
// Setting config
s.Init(
Context(ctx),
Version(common.Version().String()),
)
// 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
ctx = servicecontext.WithConfig(ctx, config.Get("services", s.Name()))
s.Init(Context(ctx))
return nil
}),
AfterInit(func(s Service) error {
if s.Options().AutoRestart {
s.Init(Watch(func(_ Service, c configx.Values) {
s.Stop()
<-time.After(1 * time.Second)
s.Start(s.Options().Context)
}))
}
return nil
}),
// Setting config watchers
AfterInit(func(s Service) error {
for k, w := range s.Options().Watchers {
if k == "" {
k = "services/" + s.Name()
}
registerWatchers(s, k, w)
}
return nil
}),
AfterInit(func(s Service) error {
s.(*service).origCtx = s.Options().Context
return nil
}),
// Checking port if set is available
BeforeStart(func(s Service) error {
ctx := s.Options().Context
log.Logger(ctx).Debug("BeforeStart - Check port availability")
port := s.Options().Port
if port == "" {
return nil
}
for {
err := unet.CheckPortAvailability(port)
if err == nil {
break
}
<-time.After(1 * time.Second)
}
log.Logger(ctx).Debug("BeforeStart - Checked port availability")
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 {
if d.Name == s.Name() {
continue
}
log.Logger(ctx).Debug("BeforeStart - Check dependency", zap.String("service", d.Name))
err := Retry(ctx, func() error {
running, err := registry.GetRunningService(d.Name)
if err != nil {
return err
}
if len(running) > 0 {
return nil
}
log.Logger(ctx).Debug("BeforeStart - Check dependency retry", zap.String("service", d.Name))
return fmt.Errorf("dependency %s not found", d.Name)
}, 50*time.Millisecond, 20*time.Minute) // This is long for distributed setup
if err != nil {
return err
}
}
log.Logger(ctx).Debug("BeforeStart - Valid dependencies")
return nil
}),
// Adding a check before starting the service to ensure only one is started if unique
BeforeStart(func(s Service) error {
if !s.MustBeUnique() {
return nil
}
ctx := s.Options().Context
log.Logger(ctx).Debug("BeforeStart - Unique check")
ticker := time.NewTicker(100 * time.Millisecond)
loop:
for {
select {
case <-ticker.C:
if !s.IsRunning() {
ticker.Stop()
break loop
}
ticker.Reset(5 * time.Second)
}
}
log.Logger(ctx).Debug("BeforeStart - Unique checked")
return nil
}),
// Adding the dao to the context
BeforeStart(func(s Service) error {
ctx := s.Options().Context
log.Logger(ctx).Debug("BeforeStart - Database connection")
// 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 %s is not available", driver)
}
ctx = servicecontext.WithDAO(ctx, d)
s.Init(Context(ctx))
log.Logger(ctx).Debug("BeforeStart - Connected to a database")
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 context.Context) {
// Resetting the original context for the service in case of a restart
ctx, cancel := context.WithCancel(s.origCtx)
s.Init(
Context(ctx),
Cancel(cancel),
)
for _, f := range s.Options().BeforeStart {
if err := f(s); err != nil {
log.Logger(ctx).Error("Could not prepare start ", zap.Error(err))
return
}
}
if s.Options().MicroInit != nil {
debug.SetPanicOnFault(true)
if err := s.Options().MicroInit(s); err != nil {
log.Logger(ctx).Error("Could not micro init ", zap.Error(err))
return
}
go func() {
looprun:
for {
select {
case <-ctx.Done():
// Checking context
return
default:
err := s.Options().Micro.Run()
if err == nil {
break looprun
}
if errorUtils.IsServiceStartNeedsRetry(err) {
log.Logger(ctx).Info("Service failed to start - restarting in 10s", zap.Error(err))
<-time.After(10 * time.Second)
continue looprun
}
log.Logger(s.Options().Context).Error("Could not run ", zap.Error(err))
break looprun
}
}
}()
}
for _, f := range s.Options().AfterStart {
if err := f(s); err != nil {
log.Logger(ctx).Error("Could not finalize start ", zap.Error(err))
}
}
}
// ForkStart uses a fork process to start the service
func (s *service) ForkStart(ctx context.Context, retries ...int) {
name := s.Options().Name
// We don't use the CommandContext because that would send the wrong signal to the child process
cmd := exec.Command(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))
}
log.Logger(ctx).Debug("Started SubProcess: " + name)
if err := cmd.Wait(); err == nil {
return
}
r := 0
if len(retries) > 0 {
r = retries[0]
}
if r >= 4 {
log.Logger(ctx).Error("SubProcess finished: but reached max retries")
return
}
<-time.After(2 * time.Second)
select {
case <-ctx.Done():
return
default:
log.Logger(ctx).Error("SubProcess finished with error: trying to restart now " + name)
s.ForkStart(ctx, r+1)
}
}
// 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 stops the service properly
if cancel != nil {
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 {
log.Logger(ctx).Debug("Check failed with error ", zap.String("name", s.Name()), zap.Error(err))
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.GetRunningService(s.Name())
if err != nil {
return err
}
if len(running) > 0 {
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) ID() string {
return s.Options().ID
}
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 := unet.DefaultAdvertiseAddress
port := s.Options().Port
if port != "" {
address = net.JoinHostPort(address, 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
ss, err := microregistry.DefaultRegistry.GetService(s.Name())
if err != nil {
return nodes
}
for _, s := range ss {
nodes = append(nodes, s.Nodes...)
}
return nodes
}
func (s *service) DAO() interface{} {
return s.Options().DAO
}
func (s *service) IsGeneric() bool {
return !strings.HasPrefix(s.Name(), common.ServiceGrpcNamespace_) &&
!strings.HasPrefix(s.Name(), common.ServiceWebNamespace_) &&
!strings.HasPrefix(s.Name(), common.ServiceRestNamespace_)
}
func (s *service) IsGRPC() bool {
return strings.HasPrefix(s.Name(), common.ServiceGrpcNamespace_)
}
func (s *service) IsREST() bool {
return strings.HasPrefix(s.Name(), common.ServiceWebNamespace_) ||
strings.HasPrefix(s.Name(), common.ServiceRestNamespace_)
}
// 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 || config.Get("services", s.Options().Name, configSrvKeyAutoStart).Bool()
}
// 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 || config.Get("services", s.Options().Name, configSrvKeyFork).Bool() || config.Get("services", s.Options().Name, configSrvKeyForkDebug).Bool()
}
// RequiresFork reads config fork=true to decide whether this service starts in a forked process or not.
func (s *service) MustBeUnique() bool {
return s.Options().Unique || config.Get("services", s.Options().Name, configSrvKeyUnique).Bool()
}
// 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) Done() chan struct{} {
return s.done
}
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{}
// randomTimeout returns a value that is between the minVal and 2x minVal.
func randomTimeout(minVal time.Duration) time.Duration {
//return minVal
if minVal == 0 {
return minVal
}
extra := time.Duration(rand.Int63()) % minVal
return minVal + extra
}