-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
668 lines (496 loc) · 13.2 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
package service
import (
"bytes"
"fmt"
htmltemplate "html/template"
"os"
"os/signal"
"path"
"syscall"
texttemplate "text/template"
"github.com/galdor/go-ejson"
"github.com/galdor/go-log"
"github.com/galdor/go-program"
"github.com/galdor/go-service/pkg/influx"
"github.com/galdor/go-service/pkg/pg"
"github.com/galdor/go-service/pkg/shttp"
"github.com/galdor/go-service/pkg/utils"
)
type ServiceImplementation interface {
DefaultCfg() interface{}
ValidateCfg() error
ServiceCfg() *ServiceCfg
Init(*Service) error
Start(*Service) error
Stop(*Service)
Terminate(*Service)
}
type ServiceImplementationWithInitProgram interface {
ServiceImplementation
InitProgram(*program.Program)
}
type ServiceCfg struct {
name string
Logger *log.LoggerCfg `json:"logger"`
DataDirectory string `json:"data_directory"`
Influx *influx.ClientCfg `json:"influx"`
PgClients map[string]*pg.ClientCfg `json:"pg_clients"`
HTTPClients map[string]*shttp.ClientCfg `json:"http_clients"`
HTTPServers map[string]*shttp.ServerCfg `json:"http_servers"`
ServiceAPI *ServiceAPICfg `json:"service_api"`
Workers map[string]*WorkerCfg `json:"workers"`
TemplateFuncMap map[string]interface{} `json:"-"`
}
type Service struct {
Cfg *ServiceCfg
Log *log.Logger
Name string
Implementation ServiceImplementation
Program *program.Program
Hostname string
Influx *influx.Client
PgClients map[string]*pg.Client
HTTPClients map[string]*shttp.Client
HTTPServers map[string]*shttp.Server
ServiceAPI *ServiceAPI
Workers map[string]*Worker
TextTemplate *texttemplate.Template
HTMLTemplate *htmltemplate.Template
stopChan chan struct{} // used to interrupt wait()
errorChan chan error // used to signal a fatal error
terminationChan chan struct{} // used to wait for termination in Stop()
}
func (cfg *ServiceCfg) ValidateJSON(v *ejson.Validator) {
v.CheckOptionalObject("logger", cfg.Logger)
v.CheckStringNotEmpty("data_directory", cfg.DataDirectory)
v.CheckOptionalObject("influx", cfg.Influx)
v.Push("pg_clients")
for name, clientCfg := range cfg.PgClients {
v.CheckObject(name, clientCfg)
}
v.Pop()
v.Push("http_clients")
for name, clientCfg := range cfg.HTTPClients {
v.CheckObject(name, clientCfg)
}
v.Pop()
v.Push("http_servers")
for name, serverCfg := range cfg.HTTPServers {
v.CheckObject(name, serverCfg)
}
v.Pop()
v.CheckOptionalObject("service_api", cfg.ServiceAPI)
}
func newService(cfg *ServiceCfg, implementation ServiceImplementation) *Service {
s := Service{
Cfg: cfg,
Name: cfg.name,
Implementation: implementation,
HTTPClients: make(map[string]*shttp.Client),
HTTPServers: make(map[string]*shttp.Server),
PgClients: make(map[string]*pg.Client),
Workers: make(map[string]*Worker),
stopChan: make(chan struct{}, 1),
errorChan: make(chan error),
terminationChan: make(chan struct{}),
}
return &s
}
func (s *Service) init() error {
s.Log = log.DefaultLogger(s.Name)
initFuncs := []func() error{
s.initHostname,
s.initLogger,
s.initTemplates,
s.initInflux,
s.initPgClients,
s.initHTTPServers,
s.initHTTPClients,
s.initServiceAPI,
s.initWorkers,
}
for _, initFunc := range initFuncs {
if err := initFunc(); err != nil {
return err
}
}
if err := s.Implementation.Init(s); err != nil {
return err
}
return nil
}
func (s *Service) initHostname() error {
hostname, err := os.Hostname()
if err != nil {
return fmt.Errorf("cannot obtain hostname: %w", err)
}
s.Hostname = hostname
return nil
}
func (s *Service) initLogger() error {
if s.Cfg.Logger == nil {
return nil
}
logger, err := log.NewLogger(s.Name, *s.Cfg.Logger)
if err != nil {
return fmt.Errorf("invalid logger configuration: %w", err)
}
s.Log = logger
return nil
}
func (s *Service) initTemplates() error {
dirPath := path.Join(s.Cfg.DataDirectory, "templates")
textTemplate, htmlTemplate, err := LoadTemplates(dirPath,
s.Cfg.TemplateFuncMap)
if err != nil {
return fmt.Errorf("cannot load templates: %w", err)
}
s.TextTemplate = textTemplate
s.HTMLTemplate = htmlTemplate
return nil
}
func (s *Service) initInflux() error {
if s.Cfg.Influx == nil {
return nil
}
httpClientCfg := shttp.ClientCfg{
LogRequests: s.Cfg.Influx.LogRequests,
}
httpClient, err := shttp.NewClient(httpClientCfg)
if err != nil {
return fmt.Errorf("cannot create influx http client: %w", err)
}
cfg := *s.Cfg.Influx
cfg.Log = s.Log.Child("influx", log.Data{})
cfg.HTTPClient = httpClient.Client
cfg.Hostname = s.Hostname
client, err := influx.NewClient(cfg)
if err != nil {
return fmt.Errorf("cannot create influx client: %w", err)
}
s.Influx = client
return nil
}
func (s *Service) initHTTPServers() error {
for name, serverCfg := range s.Cfg.HTTPServers {
serverCfg.Log = s.Log.Child("http_server", log.Data{"server": name})
serverCfg.ErrorChan = s.ErrorChan()
serverCfg.InfluxClient = s.Influx
serverCfg.Name = name
serverCfg.DataDirectory = s.Cfg.DataDirectory
server, err := shttp.NewServer(*serverCfg)
if err != nil {
return fmt.Errorf("cannot create http server %q: %w", name, err)
}
s.HTTPServers[name] = server
}
return nil
}
func (s *Service) initHTTPClients() error {
for name, clientCfg := range s.Cfg.HTTPClients {
clientCfg.Log = s.Log.Child("http_client", log.Data{"client": name})
client, err := shttp.NewClient(*clientCfg)
if err != nil {
return fmt.Errorf("cannot create http client %q: %w", name, err)
}
s.HTTPClients[name] = client
}
return nil
}
func (s *Service) initServiceAPI() error {
if s.Cfg.ServiceAPI == nil {
return nil
}
apiCfg := *s.Cfg.ServiceAPI
apiCfg.Log = s.Log.Child("service_api", log.Data{})
apiCfg.Service = s
s.ServiceAPI = NewServiceAPI(apiCfg)
return nil
}
func (s *Service) initWorkers() error {
for name, workerCfg := range s.Cfg.Workers {
if workerCfg.Disabled {
continue
}
workerCfg.Log = s.Log.Child("worker", log.Data{"worker": name})
worker, err := NewWorker(*workerCfg)
if err != nil {
return fmt.Errorf("cannot create worker %q: %w", name, err)
}
s.Workers[name] = worker
}
return nil
}
func (s *Service) initPgClients() error {
defaultSchemaDirectory := path.Join(s.Cfg.DataDirectory, "pg", "schemas")
for name, clientCfg := range s.Cfg.PgClients {
clientCfg.Log = s.Log.Child("pg", log.Data{"client": name})
clientCfg.InfluxClient = s.Influx
clientCfg.Name = name
if clientCfg.SchemaDirectory == "" {
clientCfg.SchemaDirectory = defaultSchemaDirectory
}
client, err := pg.NewClient(*clientCfg)
if err != nil {
return fmt.Errorf("cannot create pg client %q: %w", name, err)
}
s.PgClients[name] = client
}
return nil
}
func (s *Service) start() error {
s.Log.Debug(1, "starting")
// The implementation may use the Influx client so we start it first.
if s.Influx != nil {
s.Influx.Start()
}
if err := s.Implementation.Start(s); err != nil {
return err
}
// HTTP server handlers may use systems started by the implementation. So
// do workers. So they all start after the implemention.
if err := s.startHTTPServers(); err != nil {
return err
}
if s.ServiceAPI != nil {
if err := s.ServiceAPI.Start(); err != nil {
return err
}
}
if err := s.startWorkers(); err != nil {
return err
}
s.Log.Debug(1, "started")
return nil
}
func (s *Service) startHTTPServers() error {
for name, s := range s.HTTPServers {
if err := s.Start(); err != nil {
return fmt.Errorf("cannot start http server %q: %w", name, err)
}
}
return nil
}
func (s *Service) startWorkers() error {
for name, w := range s.Workers {
if err := w.Start(); err != nil {
return fmt.Errorf("cannot start worker %q: %w", name, err)
}
}
return nil
}
func (s *Service) wait() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
select {
case signo := <-sigChan:
// Cosmetic fix to avoid having "^C" displayed before the next log
// line in shells which print interrupting characters.
fmt.Fprintln(os.Stderr)
s.Log.Info("received signal %d (%v)", signo, signo)
case <-s.stopChan:
case err := <-s.errorChan:
s.Log.Error("service error: %v", err)
os.Exit(1)
}
}
func (s *Service) stop() error {
s.Log.Debug(1, "stopping")
s.Implementation.Stop(s)
s.stopWorkers()
if s.ServiceAPI != nil {
s.ServiceAPI.Stop()
}
s.stopHTTPClients()
s.stopHTTPServers()
s.stopPgClients()
if s.Influx != nil {
s.Influx.Stop()
}
s.Log.Debug(1, "stopped")
return nil
}
func (s *Service) stopWorkers() {
for _, w := range s.Workers {
w.Stop()
}
}
func (s *Service) stopHTTPServers() {
for _, server := range s.HTTPServers {
server.Stop()
}
}
func (s *Service) stopPgClients() {
for _, client := range s.PgClients {
client.Close()
}
}
func (s *Service) stopHTTPClients() {
for _, client := range s.HTTPClients {
client.CloseConnections()
}
}
func (s *Service) terminate() error {
s.Implementation.Terminate(s)
if s.Influx != nil {
s.Influx.Terminate()
}
close(s.stopChan)
close(s.errorChan)
close(s.terminationChan)
return nil
}
func Run(name, description string, implementation ServiceImplementation) {
// Program
p := program.NewProgram(name, description)
p.AddOption("c", "cfg-file", "path", "",
"the path of the configuration file")
p.AddFlag("", "validate-cfg",
"validate the configuration and exit")
if i2, ok := implementation.(ServiceImplementationWithInitProgram); ok {
i2.InitProgram(p)
}
p.ParseCommandLine()
// Configuration
cfg := implementation.DefaultCfg()
if p.IsOptionSet("cfg-file") {
cfgPath := p.OptionValue("cfg-file")
p.Info("loading configuration from %q", cfgPath)
templateData := map[string]interface{}{
"Program": p,
}
if err := LoadCfg(cfgPath, templateData, cfg); err != nil {
p.Fatal("cannot load configuration: %v", err)
}
if err := implementation.ValidateCfg(); err != nil {
p.Fatal("invalid configuration: %v", err)
}
}
serviceCfg := implementation.ServiceCfg()
serviceCfg.name = name
if p.IsOptionSet("validate-cfg") {
p.Info("configuration validated successfully")
return
}
// The --debug command line option overrides what is in the configuration
// file.
if p.IsOptionSet("debug") {
serviceCfg.Logger.DebugLevel = p.DebugLevel
}
// Service
//
// We setup recovery early to catch potential initialization panic.
s := newService(serviceCfg, implementation)
s.Program = p
defer func() {
if v := recover(); v != nil {
msg := utils.RecoverValueString(v)
trace := utils.StackTrace(0, 20, true)
if s.Log == nil {
p.Error("panic: %s\n%s", msg, trace)
} else {
s.Log.Error("panic: %s\n%s", msg, trace)
os.Exit(1)
}
}
}()
if err := s.init(); err != nil {
// We want to use the service logger as much as possible. It is
// initialized first in (*Service).init so most of the time we should
// be able to use it.
if s.Log == nil {
p.Fatal("cannot initialize service: %v", err)
} else {
s.Log.Error("cannot initialize service: %v", err)
os.Exit(1)
}
}
if err := s.start(); err != nil {
s.Log.Error("cannot start service: %v", err)
os.Exit(1)
}
s.wait()
s.stop()
s.terminate()
}
func RunTest(name string, implementation ServiceImplementation, cfgPath string, readyChan chan<- struct{}) {
// Configuration
cfg := implementation.DefaultCfg()
if cfgPath != "" {
if err := LoadCfg(cfgPath, nil, cfg); err != nil {
utils.Abort("cannot load configuration: %v", err)
}
if err := implementation.ValidateCfg(); err != nil {
utils.Abort("invalid configuration: %v", err)
}
}
serviceCfg := implementation.ServiceCfg()
serviceCfg.name = name
// Service
s := newService(serviceCfg, implementation)
if err := s.init(); err != nil {
utils.Abort("cannot initialize service: %v", err)
}
if err := s.start(); err != nil {
utils.Abort("cannot start service: %v", err)
}
close(readyChan)
s.wait()
s.stop()
s.terminate()
}
func (s *Service) Stop() {
s.stopChan <- struct{}{}
select {
case <-s.terminationChan:
}
}
func (s *Service) ErrorChan() chan<- error {
return s.errorChan
}
func (s *Service) HTTPClient(name string) *shttp.Client {
client, found := s.HTTPClients[name]
if !found {
utils.Panicf("unknown http client %q", name)
}
return client
}
func (s *Service) HTTPServer(name string) *shttp.Server {
server, found := s.HTTPServers[name]
if !found {
utils.Panicf("unknown http server %q", name)
}
return server
}
func (s *Service) PgClient(name string) *pg.Client {
client, found := s.PgClients[name]
if !found {
utils.Panicf("unknown pg client %q", name)
}
return client
}
func (s *Service) Worker(name string) *Worker {
worker, found := s.Workers[name]
if !found {
utils.Panicf("unknown worker %q", name)
}
return worker
}
func (s *Service) AddTemplateFunctions(functions map[string]interface{}) {
s.TextTemplate.Funcs(functions)
s.HTMLTemplate.Funcs(functions)
}
func (s *Service) RenderTextTemplate(name string, data interface{}) ([]byte, error) {
var buf bytes.Buffer
if err := s.TextTemplate.ExecuteTemplate(&buf, name, data); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (s *Service) RenderHTMLTemplate(name string, data interface{}) ([]byte, error) {
var buf bytes.Buffer
if err := s.HTMLTemplate.ExecuteTemplate(&buf, name, data); err != nil {
return nil, err
}
return buf.Bytes(), nil
}