forked from beatlabs/patron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
343 lines (292 loc) · 7.92 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
package patron
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"strconv"
"sync"
"syscall"
"github.com/beatlabs/patron/component/http"
patronErrors "github.com/beatlabs/patron/errors"
"github.com/beatlabs/patron/log"
"github.com/beatlabs/patron/log/zerolog"
"github.com/beatlabs/patron/trace"
jaeger "github.com/uber/jaeger-client-go"
)
var logSetupOnce sync.Once
// SetupLogging sets up the default metrics logging.
func SetupLogging(name, version string) error {
lvl, ok := os.LookupEnv("PATRON_LOG_LEVEL")
if !ok {
lvl = string(log.InfoLevel)
}
hostname, err := os.Hostname()
if err != nil {
return fmt.Errorf("failed to get hostname: %w", err)
}
f := map[string]interface{}{
"srv": name,
"ver": version,
"host": hostname,
}
logSetupOnce.Do(func() {
err = log.Setup(zerolog.Create(log.Level(lvl)), f)
})
return err
}
// Component interface for implementing service components.
type Component interface {
Run(ctx context.Context) error
}
// service is responsible for managing and setting up everything.
// The service will start by default a HTTP component in order to host management endpoint.
type service struct {
cps []Component
routesBuilder *http.RoutesBuilder
middlewares []http.MiddlewareFunc
acf http.AliveCheckFunc
rcf http.ReadyCheckFunc
termSig chan os.Signal
sighupHandler func()
}
func (s *service) setupOSSignal() {
signal.Notify(s.termSig, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
}
func (s *service) run(ctx context.Context) error {
defer func() {
err := trace.Close()
if err != nil {
log.Errorf("failed to close trace %v", err)
}
}()
cctx, cnl := context.WithCancel(ctx)
chErr := make(chan error, len(s.cps))
wg := sync.WaitGroup{}
wg.Add(len(s.cps))
for _, cp := range s.cps {
go func(c Component) {
defer wg.Done()
chErr <- c.Run(cctx)
}(cp)
}
ee := make([]error, 0, len(s.cps))
ee = append(ee, s.waitTermination(chErr))
cnl()
wg.Wait()
close(chErr)
for err := range chErr {
ee = append(ee, err)
}
return patronErrors.Aggregate(ee...)
}
func (s *service) setupDefaultTracing(name, version string) error {
var err error
host, ok := os.LookupEnv("PATRON_JAEGER_AGENT_HOST")
if !ok {
host = "0.0.0.0"
}
port, ok := os.LookupEnv("PATRON_JAEGER_AGENT_PORT")
if !ok {
port = "6831"
}
agent := host + ":" + port
tp, ok := os.LookupEnv("PATRON_JAEGER_SAMPLER_TYPE")
if !ok {
tp = jaeger.SamplerTypeProbabilistic
}
prmVal := 0.0
prm := "0.0"
if prm, ok := os.LookupEnv("PATRON_JAEGER_SAMPLER_PARAM"); ok {
prmVal, err = strconv.ParseFloat(prm, 64)
if err != nil {
return fmt.Errorf("env var for jaeger sampler param is not valid: %w", err)
}
}
log.Infof("setting up default tracing %s, %s with param %s", agent, tp, prm)
return trace.Setup(name, version, agent, tp, prmVal)
}
func (s *service) createHTTPComponent() (Component, error) {
var err error
portVal := int64(50000)
port, ok := os.LookupEnv("PATRON_HTTP_DEFAULT_PORT")
if ok {
portVal, err = strconv.ParseInt(port, 10, 64)
if err != nil {
return nil, fmt.Errorf("env var for HTTP default port is not valid: %w", err)
}
}
port = strconv.FormatInt(portVal, 10)
log.Infof("creating default HTTP component at port %s", port)
b := http.NewBuilder().WithPort(int(portVal))
if s.acf != nil {
b.WithAliveCheckFunc(s.acf)
}
if s.rcf != nil {
b.WithReadyCheckFunc(s.rcf)
}
if s.routesBuilder != nil {
b.WithRoutesBuilder(s.routesBuilder)
}
if s.middlewares != nil && len(s.middlewares) > 0 {
b.WithMiddlewares(s.middlewares...)
}
cp, err := b.Create()
if err != nil {
return nil, fmt.Errorf("failed to create default HTTP component: %w", err)
}
return cp, nil
}
func (s *service) waitTermination(chErr <-chan error) error {
for {
select {
case sig := <-s.termSig:
log.Infof("signal %s received", sig.String())
switch sig {
case syscall.SIGHUP:
s.sighupHandler()
default:
return nil
}
case err := <-chErr:
log.Info("component error received")
return err
}
}
}
// Builder gathers all required properties to
// construct a Patron service.
type Builder struct {
errors []error
name string
version string
cps []Component
routesBuilder *http.RoutesBuilder
middlewares []http.MiddlewareFunc
acf http.AliveCheckFunc
rcf http.ReadyCheckFunc
termSig chan os.Signal
sighupHandler func()
}
// New initiates the Service builder chain.
// The builder contains default values for Alive/Ready checks,
// the SIGHUP handler and its version.
func New(name, version string) *Builder {
var errs []error
if name == "" {
errs = append(errs, errors.New("name is required"))
}
if version == "" {
version = "dev"
}
return &Builder{
errors: errs,
name: name,
version: version,
acf: http.DefaultAliveCheck,
rcf: http.DefaultReadyCheck,
termSig: make(chan os.Signal, 1),
sighupHandler: func() { log.Info("SIGHUP received: nothing setup") },
}
}
// WithRoutesBuilder adds routes builder to the default HTTP component.
func (b *Builder) WithRoutesBuilder(rb *http.RoutesBuilder) *Builder {
if rb == nil {
b.errors = append(b.errors, errors.New("routes builder is nil"))
} else {
log.Info("setting routes builder")
b.routesBuilder = rb
}
return b
}
// WithMiddlewares adds generic middlewares to the default HTTP component.
func (b *Builder) WithMiddlewares(mm ...http.MiddlewareFunc) *Builder {
if len(mm) == 0 {
b.errors = append(b.errors, errors.New("provided middlewares slice was empty"))
} else {
log.Info("setting middlewares")
b.middlewares = append(b.middlewares, mm...)
}
return b
}
// WithAliveCheck overrides the default liveness check of the default HTTP component.
func (b *Builder) WithAliveCheck(acf http.AliveCheckFunc) *Builder {
if acf == nil {
b.errors = append(b.errors, errors.New("alive check func provided was nil"))
} else {
log.Info("setting alive check func")
b.acf = acf
}
return b
}
// WithReadyCheck overrides the default readiness check of the default HTTP component.
func (b *Builder) WithReadyCheck(rcf http.ReadyCheckFunc) *Builder {
if rcf == nil {
b.errors = append(b.errors, errors.New("ready check func provided was nil"))
} else {
log.Info("setting ready check func")
b.rcf = rcf
}
return b
}
// WithComponents adds custom components to the Patron service.
func (b *Builder) WithComponents(cc ...Component) *Builder {
if len(cc) == 0 {
b.errors = append(b.errors, errors.New("provided components slice was empty"))
} else {
log.Info("setting components")
b.cps = append(b.cps, cc...)
}
return b
}
// WithSIGHUP adds a custom handler for when the service receives a SIGHUP.
func (b *Builder) WithSIGHUP(handler func()) *Builder {
if handler == nil {
b.errors = append(b.errors, errors.New("provided SIGHUP handler was nil"))
} else {
log.Info("setting SIGHUP handler func")
b.sighupHandler = handler
}
return b
}
// Build constructs the Patron service by applying the gathered properties.
func (b *Builder) build() (*service, error) {
if len(b.errors) > 0 {
return nil, patronErrors.Aggregate(b.errors...)
}
s := service{
cps: b.cps,
routesBuilder: b.routesBuilder,
middlewares: b.middlewares,
acf: b.acf,
rcf: b.rcf,
termSig: b.termSig,
sighupHandler: b.sighupHandler,
}
err := SetupLogging(b.name, b.version)
if err != nil {
return nil, err
}
err = s.setupDefaultTracing(b.name, b.version)
if err != nil {
return nil, err
}
httpCp, err := s.createHTTPComponent()
if err != nil {
return nil, err
}
s.cps = append(s.cps, httpCp)
s.setupOSSignal()
return &s, nil
}
// Run starts up all service components and monitors for errors.
// If a component returns a error the service is responsible for shutting down
// all components and terminate itself.
func (b *Builder) Run(ctx context.Context) error {
s, err := b.build()
if err != nil {
return err
}
return s.run(ctx)
}