forked from ortuman/jackal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
312 lines (277 loc) · 7.27 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
/*
* Copyright (c) 2018 Miguel Ángel Ortuño.
* See the LICENSE file for more information.
*/
package app
import (
"context"
"flag"
"fmt"
"io"
"net"
"net/http"
_ "net/http/pprof" // http profile handlers
"os"
"os/signal"
"path/filepath"
"strconv"
"syscall"
"time"
"github.com/ortuman/jackal/c2s"
"github.com/ortuman/jackal/cluster"
"github.com/ortuman/jackal/component"
"github.com/ortuman/jackal/log"
"github.com/ortuman/jackal/module"
"github.com/ortuman/jackal/router"
"github.com/ortuman/jackal/s2s"
"github.com/ortuman/jackal/storage"
"github.com/ortuman/jackal/version"
"github.com/pkg/errors"
)
const (
defaultShutDownWaitTime = time.Duration(5) * time.Second
)
var logoStr = []string{
` __ __ __ `,
` |__|____ ____ | | _______ | | `,
` | \__ \ _/ ___\| |/ /\__ \ | | `,
` | |/ __ \\ \___| < / __ \| |__`,
` /\__| (____ /\___ >__|_ \(____ /____/`,
` \______| \/ \/ \/ \/ `,
}
const usageStr = `
Usage: jackal [options]
Server Options:
-c, --Config <file> Configuration file path
Common Options:
-h, --help Show this message
-v, --version Show version
`
// Application encapsulates a jackal server application.
type Application struct {
output io.Writer
args []string
logger log.Logger
storage storage.Storage
cluster *cluster.Cluster
router *router.Router
mods *module.Modules
comps *component.Components
s2s *s2s.S2S
c2s *c2s.C2S
debugSrv *http.Server
waitStopCh chan os.Signal
shutDownWaitSecs time.Duration
}
// New returns a runnable application given an output and a command line arguments array.
func New(output io.Writer, args []string) *Application {
return &Application{
output: output,
args: args,
waitStopCh: make(chan os.Signal, 1),
shutDownWaitSecs: defaultShutDownWaitTime}
}
// Run runs jackal application until either a stop signal is received or an error occurs.
func (a *Application) Run() error {
if len(a.args) == 0 {
return errors.New("empty command-line arguments")
}
var configFile string
var showVersion, showUsage bool
fs := flag.NewFlagSet("jackal", flag.ExitOnError)
fs.SetOutput(a.output)
fs.BoolVar(&showUsage, "help", false, "Show this message")
fs.BoolVar(&showUsage, "h", false, "Show this message")
fs.BoolVar(&showVersion, "version", false, "Print version information.")
fs.BoolVar(&showVersion, "v", false, "Print version information.")
fs.StringVar(&configFile, "config", "/etc/jackal/jackal.yml", "Configuration file path.")
fs.StringVar(&configFile, "c", "/etc/jackal/jackal.yml", "Configuration file path.")
fs.Usage = func() {
for i := range logoStr {
fmt.Fprintf(a.output, "%s\n", logoStr[i])
}
fmt.Fprintf(a.output, "%s\n", usageStr)
}
fs.Parse(a.args[1:])
// print usage
if showUsage {
fs.Usage()
return nil
}
// print version
if showVersion {
fmt.Fprintf(a.output, "jackal version: %v\n", version.ApplicationVersion)
return nil
}
// load configuration
var cfg Config
err := cfg.FromFile(configFile)
if err != nil {
return err
}
// create PID file
if err := a.createPIDFile(cfg.PIDFile); err != nil {
return err
}
// initialize logger
err = a.initLogger(&cfg.Logger, a.output)
if err != nil {
return err
}
// show jackal's fancy logo
a.printLogo()
// initialize storage
err = a.initStorage(&cfg.Storage)
if err != nil {
return err
}
// initialize router
a.router, err = router.New(&cfg.Router)
if err != nil {
return err
}
// initialize cluster
if cfg.Cluster != nil && storage.IsClusterCompatible() {
a.cluster, err = cluster.New(cfg.Cluster, a.router.ClusterDelegate())
if err != nil {
return err
}
if a.cluster != nil {
a.router.SetCluster(a.cluster)
if err := a.cluster.Join(); err != nil {
log.Warnf("%v", err)
}
}
} else {
log.Warnf("cluster mode disabled: storage type '%s' is not compatible", cfg.Storage.Type)
}
// initialize modules & components...
a.mods = module.New(&cfg.Modules, a.router)
a.comps = component.New(&cfg.Components, a.mods.DiscoInfo)
// start serving s2s...
a.s2s = s2s.New(cfg.S2S, a.mods, a.router)
if a.s2s != nil {
a.router.SetOutS2SProvider(a.s2s)
a.s2s.Start()
}
// start serving c2s...
a.c2s, err = c2s.New(cfg.C2S, a.mods, a.comps, a.router)
if err != nil {
return err
}
a.c2s.Start()
// initialize debug server...
if cfg.Debug.Port > 0 {
if err := a.initDebugServer(cfg.Debug.Port); err != nil {
return err
}
}
// ...wait for stop signal to shutdown
sig := a.waitForStopSignal()
log.Infof("received %s signal... shutting down...", sig.String())
return a.gracefullyShutdown()
}
func (a *Application) showVersion() {
fmt.Fprintf(a.output, "jackal version: %v\n", version.ApplicationVersion)
}
func (a *Application) createPIDFile(pidFile string) error {
if len(pidFile) == 0 {
return nil
}
if err := os.MkdirAll(filepath.Dir(pidFile), os.ModePerm); err != nil {
return err
}
file, err := os.Create(pidFile)
if err != nil {
return err
}
defer file.Close()
currentPid := os.Getpid()
if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
return err
}
return nil
}
func (a *Application) initLogger(config *loggerConfig, output io.Writer) error {
var logFiles []io.WriteCloser
if len(config.LogPath) > 0 {
// create logFile intermediate directories.
if err := os.MkdirAll(filepath.Dir(config.LogPath), os.ModePerm); err != nil {
return err
}
f, err := os.OpenFile(config.LogPath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
logFiles = append(logFiles, f)
}
l, err := log.New(config.Level, output, logFiles...)
if err != nil {
return err
}
a.logger = l
log.Set(a.logger)
return nil
}
func (a *Application) initStorage(config *storage.Config) error {
s, err := storage.New(config)
if err != nil {
return err
}
a.storage = s
storage.Set(a.storage)
return nil
}
func (a *Application) printLogo() {
for i := range logoStr {
log.Infof("%s", logoStr[i])
}
log.Infof("")
log.Infof("jackal %v\n", version.ApplicationVersion)
}
func (a *Application) initDebugServer(port int) error {
a.debugSrv = &http.Server{}
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return err
}
go a.debugSrv.Serve(ln)
log.Infof("debug server listening at %d...", port)
return nil
}
func (a *Application) waitForStopSignal() os.Signal {
signal.Notify(a.waitStopCh, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
return <-a.waitStopCh
}
func (a *Application) gracefullyShutdown() error {
// wait until application has been shut down
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(a.shutDownWaitSecs))
defer cancel()
select {
case <-a.shutdown(ctx):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (a *Application) shutdown(ctx context.Context) <-chan bool {
c := make(chan bool, 1)
go func() {
if a.debugSrv != nil {
a.debugSrv.Shutdown(ctx)
}
a.c2s.Shutdown(ctx)
if a.s2s != nil {
a.s2s.Shutdown(ctx)
}
if a.cluster != nil {
a.cluster.Shutdown()
}
a.comps.Shutdown(ctx)
a.mods.Shutdown(ctx)
storage.Unset()
log.Unset()
c <- true
}()
return c
}