-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.go
380 lines (342 loc) · 8.63 KB
/
app.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
package app
import (
"context"
"os"
"os/signal"
"runtime/debug"
"sync"
"syscall"
"time"
"github.com/abulo/ratel/v3/core/component"
"github.com/abulo/ratel/v3/core/cycle"
"github.com/abulo/ratel/v3/core/ecode"
"github.com/abulo/ratel/v3/core/env"
"github.com/abulo/ratel/v3/core/executor"
"github.com/abulo/ratel/v3/core/goroutine"
"github.com/abulo/ratel/v3/core/hooks"
"github.com/abulo/ratel/v3/core/logger"
"github.com/abulo/ratel/v3/registry"
"github.com/abulo/ratel/v3/server"
"github.com/abulo/ratel/v3/worker"
"github.com/abulo/ratel/v3/worker/job"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
)
// Application ...
type Application struct {
cycle *cycle.Cycle
smu *sync.RWMutex
initOnce sync.Once
stopOnce sync.Once
servers []server.Server
workers []worker.Worker
jobs map[string]job.Runner
disableMap map[Disable]bool
HideBanner bool
stopped chan struct{}
components []component.Component
sig chan os.Signal
}
type Option func(a *Application)
type Disable int
const (
DisableParserFlag Disable = 1
DisableLoadConfig Disable = 2
DisableDefaultGovernor Disable = 3
)
func (a *Application) WithOptions(options ...Option) {
for _, option := range options {
option(a)
}
}
func WithDisable(d Disable) Option {
return func(a *Application) {
a.disableMap[d] = true
}
}
// New create a new Application instance
func New(fns ...func() error) (*Application, error) {
app := &Application{}
if err := app.Startup(fns...); err != nil {
return nil, err
}
return app, nil
}
// DefaultApp ...
func DefaultApp() *Application {
app := &Application{}
app.initialize()
return app
}
// run hooks
func (app *Application) runHooks(stage hooks.Stage) {
hooks.Do(stage)
}
// RegisterHooks register a stage Hook
func (app *Application) RegisterHooks(stage hooks.Stage, fns ...func()) {
hooks.Register(stage, fns...)
}
// initialize application
func (app *Application) initialize() {
app.initOnce.Do(func() {
//assign
app.cycle = cycle.NewCycle()
app.smu = &sync.RWMutex{}
app.servers = make([]server.Server, 0)
app.workers = make([]worker.Worker, 0)
app.jobs = make(map[string]job.Runner)
app.disableMap = make(map[Disable]bool)
app.stopped = make(chan struct{})
app.components = make([]component.Component, 0)
_ = app.printBanner()
// app.initLogger()
})
}
// Startup ...
func (app *Application) Startup(fns ...func() error) error {
app.initialize()
return goroutine.SerialUntilError(fns...)()
}
// Serve start server
func (app *Application) Serve(s ...server.Server) error {
app.smu.Lock()
defer app.smu.Unlock()
app.servers = append(app.servers, s...)
return nil
}
// Schedule ..
func (app *Application) Schedule(w worker.Worker) error {
app.workers = append(app.workers, w)
return nil
}
// Job ..
func (app *Application) Job(runner job.Runner) error {
namedJob, ok := runner.(interface{ GetJobName() string })
// job runner must implement GetJobName
if !ok {
return nil
}
jobName := namedJob.GetJobName()
app.jobs[jobName] = runner
return nil
}
// Executor ...
func (app *Application) Executor(e executor.Executor) {
executor.Register(e.GetAddress(), e)
}
// SetRegistry set customize registry
func (app *Application) SetRegistry(reg registry.Registry) {
registry.DefaultRegisterer = reg
}
// clean after app quit
func (app *Application) clean() {
}
// Run run application
func (app *Application) Run(servers ...server.Server) error {
app.smu.Lock()
app.servers = append(app.servers, servers...)
app.smu.Unlock()
hooks.Do(hooks.Stage_BeforeRun)
app.waitSignals() //start signal listen task in goroutine
defer app.clean()
// todo jobs not graceful
_ = app.startJobs()
// start servers and govern server
app.cycle.Run(app.startServers)
// start workers
app.cycle.Run(app.startWorkers)
//blocking and wait quit
if err := <-app.cycle.Wait(); err != nil {
logger.Logger.WithFields(logrus.Fields{
"app": ecode.ModApp,
"err": err,
}).Error("ratel shutdown with error")
return err
}
logger.Logger.Info("shutdown ratel, bye!", ecode.ModApp)
return nil
}
// Stop application immediately after necessary cleanup
func (app *Application) Stop() (err error) {
app.stopOnce.Do(func() {
app.stopped <- struct{}{}
app.runHooks(hooks.Stage_BeforeStop)
//stop servers
for _, s := range app.servers {
func(s server.Server) {
app.smu.RLock()
if err := registry.DefaultRegisterer.UnregisterService(context.Background(), s.Info()); err != nil {
logger.Logger.WithFields(logrus.Fields{
"ModApp": ecode.ModApp,
"Name": s.Info().Name,
"Label": s.Info().Label(),
"err": err,
}).Info("exit server stop")
}
app.cycle.Run(s.Stop)
app.smu.RUnlock()
}(s)
}
//stop workers
for _, w := range app.workers {
func(w worker.Worker) {
app.cycle.Run(w.WorkerStop)
}(w)
}
<-app.cycle.Done()
// run hook
app.runHooks(hooks.Stage_AfterStop)
app.cycle.Close()
})
return
}
// GracefulStop application after necessary cleanup
func (app *Application) GracefulStop(ctx context.Context) (err error) {
app.stopOnce.Do(func() {
app.stopped <- struct{}{}
app.runHooks(hooks.Stage_BeforeStop)
//stop servers
for _, s := range app.servers {
func(s server.Server) {
app.cycle.Run(func() error {
app.smu.RLock()
defer app.smu.RUnlock()
if err := registry.DefaultRegisterer.UnregisterService(ctx, s.Info()); err != nil {
logger.Logger.WithFields(logrus.Fields{
"ModApp": ecode.ModApp,
"Name": s.Info().Name,
"Label": s.Info().Label(),
"err": err,
}).Info("exit server graceful stop")
}
return s.GracefulStop(ctx)
})
}(s)
}
//stop workers
for _, w := range app.workers {
func(w worker.Worker) {
app.cycle.Run(w.WorkerStop)
}(w)
}
// stop executor
app.cycle.Run(executor.GracefulStop)
<-app.cycle.Done()
// run hooks
app.runHooks(hooks.Stage_AfterStop)
app.cycle.Close()
})
return err
}
func (app *Application) startServers() error {
var eg errgroup.Group
var ctx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
go func() {
<-app.stopped
cancel()
}()
// start multi servers
app.smu.Lock()
for _, s := range app.servers {
s := s
eg.Go(func() (err error) {
time.AfterFunc(time.Second, func() {
_ = registry.DefaultRegisterer.RegisterService(ctx, s.Info())
logger.Logger.WithFields(logrus.Fields{
"app": ecode.ModApp,
"action": "init",
"name": s.Info().Name,
"label": s.Info().Label(),
}).Info("start server")
})
err = s.Serve()
return
})
}
app.smu.Unlock()
return eg.Wait()
}
func (app *Application) startWorkers() error {
var eg errgroup.Group
// start multi workers
for _, w := range app.workers {
w := w
eg.Go(func() error {
return w.WorkerStart()
})
}
return eg.Wait()
}
// startJobs starts jobs
func (app *Application) startJobs() error {
if len(app.jobs) == 0 {
return nil
}
var jobs = make([]func(), 0)
//warp jobs
for name, runner := range app.jobs {
jobs = append(jobs, func() {
// runner.Run panic 错误在更上层抛出
logger.Logger.WithFields(logrus.Fields{
"jobName": name,
}).Info("job run begin")
defer func() {
logger.Logger.WithFields(logrus.Fields{
"jobName": name,
}).Info("job run end")
}()
runner.Run()
})
}
goroutine.Parallel(jobs...)()
return nil
}
// start executor
func (app *Application) startExecutors() error {
return executor.Run()
}
func (app *Application) isDisable(d Disable) bool {
b, ok := app.disableMap[d]
if !ok {
return false
}
return b
}
func (app *Application) waitSignals() {
logger.Logger.WithFields(logrus.Fields{
"pid": syscall.Getpid(),
}).Info("init listen signal")
signals := []os.Signal{syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGTSTP, syscall.SIGUSR1, syscall.SIGQUIT, os.Interrupt}
app.sig = make(chan os.Signal)
signal.Notify(app.sig, signals...)
go app.exitHandler()
}
func (app *Application) exitHandler() {
debug.FreeOSMemory()
sig := <-app.sig
logger.Logger.WithFields(logrus.Fields{
"pid": syscall.Getpid(),
"SIG": sig,
}).Info("Received SIG")
switch sig {
case syscall.SIGHUP:
if err := app.Run(); err != nil {
logger.Logger.WithFields(logrus.Fields{
"pid": syscall.Getpid(),
"SIG": sig,
}).Info("Received SIG")
}
_ = app.GracefulStop(context.Background())
case syscall.SIGINT, syscall.SIGTERM, syscall.SIGTSTP, syscall.SIGUSR1, syscall.SIGQUIT, os.Interrupt:
logger.Logger.Info("close server")
os.Exit(128 + int(sig.(syscall.Signal)))
}
}
// printBanner init
func (app *Application) printBanner() error {
if app.HideBanner {
return nil
}
env.PrintVersion()
return nil
}