-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsrvApp.go
More file actions
435 lines (341 loc) · 8.39 KB
/
srvApp.go
File metadata and controls
435 lines (341 loc) · 8.39 KB
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
// ---------------------------------------------------------------------------
//
// srvApp.go
//
// Copyright (c) 2015, Jared Chavez.
// All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// -----------
// Package srvApp manages common server tasks related to managing
// application state, logging, and configuration.
package srvApp
import (
"bytes"
"flag"
"fmt"
"os"
"os/signal"
"runtime"
"runtime/pprof"
"sync"
"github.com/xaevman/app"
"github.com/xaevman/counters"
"github.com/xaevman/crash"
"github.com/xaevman/ini"
"github.com/xaevman/log"
"github.com/xaevman/shutdown"
_ "github.com/xaevman/trace"
)
// RunMode enum
const (
CMDLINE = iota
RUN_SVC
INST_SVC
UNINST_SVC
)
// coutner names
const APP_UPTIME_COUNTER = "app.uptime_sec"
// RunCfg represents the desired run configuration for the application before
// ini or command line flag based options are taken into consideration. This can
// currently be used to force enable/disable the http listeners depending on run
// mode.
type RunCfg struct {
InitSrvCmd bool
InitSrvSvc bool
}
// AppConfig returns a reference to the application's configuration file.
func AppConfig() *ini.IniCfg {
cfgLock.RLock()
defer cfgLock.RUnlock()
return appConfig
}
var appConfig *ini.IniCfg
// AppCounters returns a reference to the container for this application's
// performance counters.
func AppCounters() *counters.List {
cfgLock.RLock()
defer cfgLock.RUnlock()
return appCounters
}
var appCounters = counters.NewList()
// AppProcess returns a reference to the current process.
func AppProcess() *os.Process {
cfgLock.RLock()
defer cfgLock.RUnlock()
return appProcess
}
var appProcess *os.Process
// CrashDir returns the relative path to the application's crash
// directory.
func CrashDir() string {
cfgLock.RLock()
defer cfgLock.RUnlock()
return crashDir
}
var crashDir = fmt.Sprintf("%s/%s", app.GetExeDir(), "crash")
// ConfigDir returns the relative path to the application's config
// directory.
func ConfigDir() string {
cfgLock.RLock()
defer cfgLock.RUnlock()
return configDir
}
var configDir = fmt.Sprintf("%s/%s", app.GetExeDir(), "config")
// EmailCrashHandler returns the email crash handler for the app.
func EmailCrashHandler() *crash.EmailHandler {
cfgLock.RLock()
defer cfgLock.RUnlock()
return emailCrashHandler
}
var emailCrashHandler *crash.EmailHandler
// FileCrashHandler returns the file crash handler for the app.
func FileCrashHandler() *crash.FileHandler {
cfgLock.RLock()
defer cfgLock.RUnlock()
return fileCrashHandler
}
var fileCrashHandler *crash.FileHandler
// Http returns a refernce to the http sever object for the application.
func Http() *HttpSrv {
cfgLock.RLock()
defer cfgLock.RUnlock()
return httpSrv
}
var httpSrv = NewHttpSrv()
// Log returns a refernce to the SrvLog instance for the application.
func Log() *SrvLog {
cfgLock.RLock()
defer cfgLock.RUnlock()
return srvLog
}
var srvLog *SrvLog
// internal log buffer object
func LogBuffer() *log.LogBuffer {
cfgLock.RLock()
defer cfgLock.RUnlock()
return logBuffer
}
var logBuffer *log.LogBuffer
// LogDir returns the relative path to the application's log directory.
func LogDir() string {
cfgLock.RLock()
defer cfgLock.RUnlock()
return logDir
}
var logDir = fmt.Sprintf("%s/%s", app.GetExeDir(), "log")
// Internal vars.
var (
cleanPid = true
crashChan = make(chan bool, 0)
exitCode = 0
modeInstallSvc = false
modeRunSvc = false
modeUninstallSvc = false
cfgLock sync.RWMutex
runLock sync.Mutex
runMode byte
appShutdown = shutdown.New()
shuttingDown = false
runCfg *RunCfg
)
// Init calls InitCfg to initialize the server appplication with a default configuration.
func Init() {
InitCfg(&RunCfg{
InitSrvCmd: true,
InitSrvSvc: true,
})
}
// InitCfg Initializations sets up signal
// handling, arg parsing, run mode, initializes a default config file,
// file and email crash handlers, both private and public facing http server
// listeners, and some default debugging Uri handlers.
func InitCfg(cfg *RunCfg) {
runLock.Lock()
defer runLock.Unlock()
cfgLock.Lock()
defer cfgLock.Unlock()
runCfg = cfg
os.Chdir(app.GetExeDir())
parseFlags()
initLogs()
afterFlags()
if shuttingDown {
return
}
uptime := counters.NewTimer(APP_UPTIME_COUNTER)
uptime.Set(0)
appCounters.Add(uptime)
appConfig = ini.New(fmt.Sprintf("%s/%s.ini", configDir, app.GetName()))
fileCrashHandler = new(crash.FileHandler)
fileCrashHandler.SetCrashDir(crashDir)
crash.AddHandler(fileCrashHandler)
emailCrashHandler = crash.NewEmailHandler()
crash.AddHandler(emailCrashHandler)
catchSigInt()
catchCrash()
netInit()
ini.Subscribe(appConfig, onCfgChange)
}
// QueryRunmode returns the configured runmode for the application
func QueryRunmode() byte {
cfgLock.RLock()
defer cfgLock.RUnlock()
return runMode
}
// QueryShutdown returns a boolean values indicating whether or not
// the application is shutting down
func QueryShutdown() bool {
cfgLock.RLock()
defer cfgLock.RUnlock()
return shuttingDown
}
// Run executes the application in whatever run mode is configured.
func Run() int {
runLock.Lock()
defer runLock.Unlock()
return run()
}
// SignalShutdown ensures a config lock before calling
// the unsafe _signalShutdown
func SignalShutdown(returnCode int) {
cfgLock.Lock()
defer cfgLock.Unlock()
_signalShutdown(returnCode)
}
func _signalShutdown(returnCode int) {
if shuttingDown {
return
}
shuttingDown = true
exitCode = returnCode
appShutdown.Start()
}
// blockUntilShutdown does exactly what it sounds like, it blocks until
// the shutdown signal is received, then calls Shutdown.
func blockUntilShutdown() int {
<-appShutdown.Signal
_shutdown()
appShutdown.Complete()
if appShutdown.WaitForTimeout() {
var buffer bytes.Buffer
pprof.Lookup("goroutine").WriteTo(&buffer, 1)
panic(fmt.Sprintf("Timeout shutting down srvApp\n\n%s", buffer.String()))
}
return exitCode
}
// catchCrash catches the user-initiated crash signal and happily panics
// the application.
func catchCrash() {
go func() {
defer crash.HandleAll()
select {
case <-crashChan:
cfgLock.RLock()
isShuttingDown := shuttingDown
cfgLock.RUnlock()
if isShuttingDown {
return
}
panic("User initiated crash")
}
}()
}
// catchSigInt catches the SIGINT signal and, in turn, signals the applciation
// to start a graceful shutdown.
func catchSigInt() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
defer crash.HandleAll()
select {
case <-c:
go func() {
defer crash.HandleAll()
SignalShutdown(0)
}()
}
}()
}
// parseFlags registers and parses default command line flags, then
// sets the default run mode for the application.
func parseFlags() {
// windows-specific options
if runtime.GOOS == "windows" {
flag.BoolVar(
&modeRunSvc,
"runSvc",
false,
"Run the application as a windows service.",
)
flag.BoolVar(
&modeInstallSvc,
"install",
false,
"Install the application as a windows service.",
)
flag.BoolVar(
&modeUninstallSvc,
"uninstall",
false,
"Uninstall the application's service instance.",
)
}
flag.Parse()
setRunMode()
}
// setRunMode stores the run mode for the application.
func setRunMode() {
if modeRunSvc {
runMode = RUN_SVC
} else if modeInstallSvc {
runMode = INST_SVC
} else if modeUninstallSvc {
runMode = UNINST_SVC
} else {
runMode = CMDLINE
}
}
// shutdown handles shutting down the server process, closing open logs,
// and terminating subprocesses.
func _shutdown() {
notifyShutdown()
netShutdown()
ini.Shutdown()
close(crashChan)
if cleanPid {
err := app.DeletePidFile()
if err != nil {
Log().Error("%v\n", err)
}
}
closeLogs()
}
// startSingleton intializes the server process, attempting to make sure
// that it is the only such process running.
func startSingleton() bool {
cfgLock.Lock()
defer cfgLock.Unlock()
appProcess = app.GetRunStatus()
if appProcess != nil {
srvLog.Error(
"Application already running under PID %d\n",
appProcess.Pid,
)
cleanPid = false
return false
}
_, err := app.CreatePidFile()
if err != nil {
srvLog.Error("Error creating PID file (%s)", err)
return false
}
appProcess = app.GetRunStatus()
if appProcess == nil {
srvLog.Error("Error finding our process")
return false
}
return true
}