-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.go
491 lines (464 loc) · 13.8 KB
/
application.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
/*
* Copyright 2023 Wang Min Xiang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package fns
import (
"fmt"
"github.com/aacfactory/configures"
"github.com/aacfactory/errors"
"github.com/aacfactory/fns/barriers"
"github.com/aacfactory/fns/clusters"
"github.com/aacfactory/fns/commons/procs"
"github.com/aacfactory/fns/commons/switchs"
"github.com/aacfactory/fns/commons/uid"
"github.com/aacfactory/fns/commons/versions"
"github.com/aacfactory/fns/configs"
"github.com/aacfactory/fns/context"
"github.com/aacfactory/fns/hooks"
"github.com/aacfactory/fns/logs"
"github.com/aacfactory/fns/proxies"
"github.com/aacfactory/fns/runtime"
"github.com/aacfactory/fns/services"
"github.com/aacfactory/fns/shareds"
"github.com/aacfactory/fns/transports"
"github.com/aacfactory/workers"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
)
type Application interface {
Deploy(service ...services.Service) Application
Run(ctx context.Context) Application
Sync()
}
// +-------------------------------------------------------------------------------------------------------------------+
func New(options ...Option) (app Application) {
opt := defaultOptions
if options != nil {
for _, option := range options {
optErr := option(opt)
if optErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed").WithCause(optErr)))
return
}
}
}
// app
appId := strings.TrimSpace(opt.id)
if appId == "" {
appId = uid.UID()
}
appName := opt.name
appVersion := opt.version
// status
status := &switchs.Switch{}
// config
configRetriever, configRetrieverErr := configures.NewRetriever(opt.configRetrieverOption)
if configRetrieverErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed for invalid config retriever").WithCause(configRetrieverErr)))
return
}
configure, configureErr := configRetriever.Get()
if configureErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, get config via retriever failed").WithCause(configureErr)))
return
}
config := configs.Config{}
configErr := configure.As(&config)
if configErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, decode config failed").WithCause(configErr)))
return
}
// log
logger, loggerErr := logs.New(config.Log, opt.logWriters)
if loggerErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, new log failed").WithCause(loggerErr)))
return
}
// proc
amp := procs.New(config.Runtime.Procs.Min)
// worker
workerOptions := make([]workers.Option, 0, 1)
if workersMax := config.Runtime.Workers.Max; workersMax > 0 {
workerOptions = append(workerOptions, workers.MaxWorkers(workersMax))
}
if workersMaxIdleSeconds := config.Runtime.Workers.MaxIdleSeconds; workersMaxIdleSeconds > 0 {
workerOptions = append(workerOptions, workers.MaxIdleWorkerDuration(time.Duration(workersMaxIdleSeconds)*time.Second))
}
worker := workers.New(workerOptions...)
handlers := make([]transports.MuxHandler, 0, 1)
var manager services.EndpointsManager
local := services.New(appId, appVersion, logger.With("fns", "endpoints"), config.Services, worker)
handlers = append(handlers, services.Handler(local))
handlers = append(handlers, runtime.HealthHandler())
// barrier
var barrier barriers.Barrier
// shared
var shared shareds.Shared
// cluster
if clusterConfig := config.Cluster; clusterConfig.Name != "" {
port, portErr := config.Transport.GetPort()
if portErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed").WithCause(portErr)))
return
}
var clusterHandlers []transports.MuxHandler
var clusterErr error
manager, shared, barrier, clusterHandlers, clusterErr = clusters.New(clusters.Options{
Id: appId,
Version: appVersion,
Port: port,
Log: logger.With("fns", "cluster"),
Worker: worker,
Local: local,
Dialer: opt.transport,
Config: clusterConfig,
})
if clusterErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed").WithCause(clusterErr)))
return
}
handlers = append(handlers, clusterHandlers...)
} else {
var sharedErr error
shared, sharedErr = shareds.Local(logger.With("shared", "local"), config.Runtime.Shared)
if sharedErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed").WithCause(sharedErr)))
return
}
barrier = barriers.New()
manager = local
}
// runtime
rt := runtime.New(
appId, appName, appVersion,
status, logger, worker,
manager,
barrier, shared,
)
// builtins
builtins := make([]services.Service, 0, 1)
// transport >>>
// middlewares
middlewares := make([]transports.Middleware, 0, 1)
middlewares = append(middlewares, runtime.Middleware(rt))
var corsMiddleware transports.Middleware
for _, middleware := range opt.middlewares {
builtin, isBuiltin := middleware.(services.Middleware)
if isBuiltin {
builtins = append(builtins, builtin.Services()...)
}
if middleware.Name() == "cors" {
corsMiddleware = middleware
continue
}
middlewares = append(middlewares, middleware)
}
if corsMiddleware != nil {
middlewares = append([]transports.Middleware{corsMiddleware}, middlewares...)
}
middleware, middlewareErr := transports.WaveMiddlewares(logger, config.Transport, middlewares)
if middlewareErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, new transport middleware failed").WithCause(middlewareErr)))
return
}
// handler
mux := transports.NewMux()
handlers = append(handlers, opt.handlers...)
for _, handler := range handlers {
handlerConfig, handlerConfigErr := config.Transport.HandlerConfig(handler.Name())
if handlerConfigErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, new transport handler failed").WithCause(handlerConfigErr).WithMeta("handler", handler.Name())))
return
}
handlerErr := handler.Construct(transports.MuxHandlerOptions{
Log: logger.With("handler", handler.Name()),
Config: handlerConfig,
})
if handlerErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, new transport handler failed").WithCause(handlerErr).WithMeta("handler", handler.Name())))
return
}
mux.Add(handler)
builtin, isBuiltin := handler.(services.MuxHandler)
if isBuiltin {
builtins = append(builtins, builtin.Services()...)
}
}
transport := opt.transport
transportErr := transport.Construct(transports.Options{
Log: logger.With("transport", transport.Name()),
Config: config.Transport,
Handler: middleware.Handler(mux),
})
if transportErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, new transport failed").WithCause(transportErr)))
return
}
// transport <<<
// proxy >>>
var proxy proxies.Proxy
if proxyOptions := opt.proxyOptions; len(proxyOptions) > 0 {
cluster, ok := manager.(clusters.ClusterEndpointsManager)
if !ok {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, new proxy failed").WithCause(fmt.Errorf("application was not in cluster mode"))))
return
}
var proxyErr error
proxy, proxyErr = proxies.New(proxyOptions...)
if proxyErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, new proxy failed").WithCause(proxyErr)))
return
}
constructErr := proxy.Construct(proxies.ProxyOptions{
Log: logger.With("fns", "proxy"),
Config: config.Proxy,
Runtime: rt,
Manager: cluster,
Dialer: transport,
})
if constructErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, new proxy failed").WithCause(constructErr)))
return
}
}
// proxy <<<
// hooks
for _, hook := range opt.hooks {
hookConfig, hookConfigErr := config.Hooks.Get(hook.Name())
if hookConfigErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, new hook failed").WithCause(hookConfigErr)))
return
}
hookErr := hook.Construct(hooks.Options{
Log: logger.With("hook", hook.Name()),
Config: hookConfig,
})
if hookErr != nil {
panic(fmt.Errorf("%+v", errors.Warning("fns: new application failed, new hook failed").WithCause(hookErr)))
return
}
}
// signal
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh,
syscall.SIGINT,
syscall.SIGKILL,
syscall.SIGQUIT,
syscall.SIGABRT,
syscall.SIGTERM,
)
app = &application{
id: appId,
name: appName,
version: appVersion,
rt: rt,
status: status,
shared: shared,
log: logger,
config: config,
amp: amp,
worker: worker,
manager: manager,
middlewares: middleware,
transport: transport,
proxy: proxy,
hooks: opt.hooks,
shutdownTimeout: opt.shutdownTimeout,
synced: false,
signalCh: signalCh,
}
// deploy
app.Deploy(builtins...)
return
}
// +-------------------------------------------------------------------------------------------------------------------+
type application struct {
id string
name string
version versions.Version
rt *runtime.Runtime
status *switchs.Switch
shared shareds.Shared
log logs.Logger
config configs.Config
amp *procs.AutoMaxProcs
worker workers.Workers
manager services.EndpointsManager
middlewares transports.Middlewares
transport transports.Transport
proxy proxies.Proxy
hooks []hooks.Hook
shutdownTimeout time.Duration
synced bool
signalCh chan os.Signal
}
func (app *application) Deploy(s ...services.Service) Application {
for _, service := range s {
err := app.manager.Add(service)
if err != nil {
panic(fmt.Sprintf("%+v", errors.Warning("fns: deploy failed").WithCause(err)))
return app
}
}
return app
}
func (app *application) Run(ctx context.Context) Application {
app.amp.Enable()
// with runtime
runtime.With(ctx, app.rt)
// on
app.status.On()
// transport
trErrs := make(chan error, 1)
go func(ctx context.Context, transport transports.Transport, errs chan error) {
lnErr := transport.ListenAndServe()
if lnErr != nil {
errs <- lnErr
close(errs)
}
}(ctx, app.transport, trErrs)
select {
case trErr := <-trErrs:
app.amp.Reset()
panic(fmt.Sprintf("%+v", errors.Warning("fns: application run failed").WithCause(trErr)))
return app
case <-time.After(3 * time.Second):
break
}
if app.log.DebugEnabled() {
app.log.Debug().With("port", strconv.Itoa(app.transport.Port())).Message("fns: transport is serving...")
}
// endpoints
lnErr := app.manager.Listen(ctx)
if lnErr != nil {
app.shutdown()
panic(fmt.Sprintf("%+v", errors.Warning("fns: application run failed").WithCause(lnErr)))
return app
}
// confirm
app.status.Confirm()
// proxy
if app.proxy != nil {
prErrs := make(chan error, 1)
go func(ctx context.Context, proxy proxies.Proxy, errs chan error) {
proxyErr := proxy.Run(ctx)
if proxyErr != nil {
errs <- proxyErr
close(errs)
}
}(ctx, app.proxy, prErrs)
select {
case prErr := <-prErrs:
app.shutdown()
panic(fmt.Sprintf("%+v", errors.Warning("fns: application run failed").WithCause(prErr)))
return app
case <-time.After(3 * time.Second):
break
}
if app.log.DebugEnabled() {
app.log.Debug().With("port", strconv.Itoa(app.proxy.Port())).Message("fns: proxy is serving...")
}
}
// hooks
for _, hook := range app.hooks {
name := hook.Name()
if name == "" {
if app.log.DebugEnabled() {
app.log.Debug().Message("fns: one hook has no name")
}
continue
}
hookConfig, hookConfigErr := app.config.Hooks.Get(name)
if hookConfigErr != nil {
if app.log.DebugEnabled() {
app.log.Debug().With("hook", name).Cause(hookConfigErr).Message("fns: get hook config failed")
}
continue
}
hookErr := hook.Construct(hooks.Options{
Log: app.log.With("hook", name),
Config: hookConfig,
})
if hookErr != nil {
if app.log.DebugEnabled() {
app.log.Debug().With("hook", name).Cause(hookErr).Message("fns: construct hook failed")
}
continue
}
go hook.Execute(ctx)
if app.log.DebugEnabled() {
app.log.Debug().With("hook", hook.Name()).Message("fns: hook is dispatched")
}
}
// log
if app.log.DebugEnabled() {
app.log.Debug().Message("fns: application is running...")
}
return app
}
func (app *application) Sync() {
if app.synced {
return
}
app.synced = true
<-app.signalCh
app.shutdown()
return
}
func (app *application) shutdown() {
if off, _ := app.status.IsOff(); off {
return
}
// status
app.status.Off()
defer app.amp.Reset()
timeout := app.shutdownTimeout
if timeout < 1 {
timeout = 10 * time.Minute
}
ctx, cancel := context.WithTimeout(context.TODO(), timeout)
runtime.With(ctx, app.rt)
go func(ctx context.Context, cancel context.CancelFunc, app *application) {
// hooks
for _, hook := range app.hooks {
hook.Shutdown(ctx)
}
// endpoints
app.manager.Shutdown(ctx)
// transport
app.middlewares.Close()
app.transport.Shutdown(ctx)
// proxy
if app.proxy != nil {
app.proxy.Shutdown(ctx)
}
// shared
app.shared.Close()
// log
_ = app.log.Shutdown(ctx)
cancel()
}(context.Wrap(ctx), cancel, app)
<-ctx.Done()
app.status.Confirm()
// log
if app.log.DebugEnabled() {
app.log.Debug().Message("fns: application is stopped!!!")
}
}