-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
275 lines (242 loc) · 8.48 KB
/
app.js
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
var version = "0.3.9-beta";
var debug = require('debug')('pagermon:server');
var io = require('@pm2/io').init({
http : true, // HTTP routes logging (default: true)
ignore_routes : [/socket\.io/, /notFound/], // Ignore http routes with this pattern (Default: [])
errors : true, // Exceptions logging (default: true)
custom_probes : true, // Auto expose JS Loop Latency and HTTP req/s as custom metrics
network : true, // Network monitoring at the application level
ports : true, // Shows which ports your app is listening on (default: false)
transactions : true
});
var http = require('http');
var compression = require('compression');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('./log');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs');
var session = require('express-session');
var request = require('request');
var SQLiteStore = require('connect-sqlite3')(session);
var passport = require('passport');
var flash = require('connect-flash');
require('./config/passport')(passport);
process.on('SIGINT', function() {
console.log( "\nGracefully shutting down from SIGINT (Ctrl-C)" );
process.exit(1);
});
// create config file if it does not exist, and set defaults
var conf_defaults = require('./config/default.json');
var conf_file = './config/config.json';
if( ! fs.existsSync(conf_file) ) {
fs.writeFileSync( conf_file, JSON.stringify(conf_defaults,null, 2) );
}
// load the config file
var nconf = require('nconf');
nconf.file({file: conf_file});
nconf.load();
//Load current theme
var theme = nconf.get('global:theme')
// set the theme if none found, for backwards compatibility
if (!theme) {
nconf.set('global:theme', "default");
nconf.save();
var theme = nconf.get('global:theme')
}
//Enable Azure Monitoring if enabled
var azureEnable = nconf.get('monitoring:azureEnable')
var azureKey = nconf.get('monitoring:azureKey')
if (azureEnable) {
logger.main.debug('Starting Azure Application Insights')
const appInsights = require('applicationinsights');
appInsights.setup(azureKey)
.setAutoDependencyCorrelation(true)
.setAutoCollectRequests(true)
.setAutoCollectPerformance(true)
.setAutoCollectExceptions(true)
.setAutoCollectDependencies(true)
.setAutoCollectConsole(true)
.setUseDiskRetryCaching(true)
.start();
}
var dbinit = require('./db');
dbinit.init();
var db = require('./knex/knex.js');
// routes
var index = require('./routes/index');
var admin = require('./routes/admin');
var api = require('./routes/api');
var port = normalizePort(process.env.PORT || '3000');
var app = express();
app.set('port', port);
// view engine setup
app.set('views', path.join(__dirname,'themes',theme, 'views'));
app.set('view engine', 'ejs');
app.set('trust proxy', 'loopback, linklocal, uniquelocal');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
//Set connection timeout to prevent long running queries failing on large databases - mostly capacode refresh on MySQL
server.on('connection', function(connection) {
connection.setTimeout(600 * 1000);
});
//Lets set setMaxListeners to a decent number - not to high to allow the memory leak warking to still trigger
io.sockets.setMaxListeners(20);
io.sockets.on('connection', function (socket) {
socket.removeAllListeners();
debug('client connect to normal socket');
// socket.on('echo', function (data) {
// io.sockets.emit('message', data);
// console.log('message', data);
// });
});
//Admin Socket
var adminio = io.of('/adminio');
adminio.on('connection', function (socket) {
socket.removeAllListeners();
debug('client connect to admin socket');
// adminio.on('echo', function (data) {
// adminio.emit('message', data);
// console.log('message', data);
// });
});
app.use(favicon(path.join(__dirname,'themes',theme, 'public', 'favicon.ico')));
// set socket.io to be shared across all modules
app.use(function(req,res,next){
req.io = io;
next();
});
// session secret is controlled by config
var secret = nconf.get('global:sessionSecret');
// compress all responses
app.use(compression());
app.use(require("morgan")("combined", { "stream": logger.http.stream }));
app.use(bodyParser.json({
limit: '1mb',
})); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({
extended: true,
limit: '1mb',
})); // to support URL-encoded bodies
app.use(cookieParser());
var sessSet = {
cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 }, // 1 week
store: new SQLiteStore,
saveUninitialized: true,
resave: 'true',
secret: secret
}
if (process.env.HOSTNAME && process.env.USE_COOKIE_HOST)
sessSet.cookie.domain = '.'+process.env.HOSTNAME;
app.use(session(sessSet));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());
app.use(express.static(path.join(__dirname,'themes',theme, 'public')));
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));
app.use(function(req, res, next) {
res.locals.version = version;
res.locals.loglevel = nconf.get('global:loglevel') || 'info';
next();
});
app.use('/', index);
app.use('/admin', admin);
app.use('/post', api);
app.use('/api', api);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
var title = nconf.get('global:monitorName') || 'PagerMon';
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
//these 3 have to be here to stop the error handler shitting up the logs with undefined references when it receives a 500 error ... nfi why
res.locals.login = req.isAuthenticated();
res.locals.gaEnable = nconf.get('monitoring:gaEnable');
res.locals.monitorName = nconf.get("global:monitorName");
// render the error page
res.status(err.status || 500);
res.render(path.join(__dirname,'themes',theme, 'views', 'global', 'error'), { title: title });
});
// Add cronjob to automatically refresh aliases
var dbtype = nconf.get('database:type')
if (dbtype == 'mysql') {
var aliasRefreshJob = require('cron').CronJob;
new aliasRefreshJob('0 5,35 * * * *', function() {
var refreshRequired = nconf.get('database:aliasRefreshRequired')
logger.main.debug('CRON: Running Cronjob AliasRefresh')
if (refreshRequired == 1) {
console.time('updateMap');
logger.main.info('CRON: Alias Refresh required, running.')
db('messages').update('alias_id', function() {
this.select('id')
.from('capcodes')
.where(db.ref('messages.address'), 'like', db.ref('capcodes.address') )
.orderByRaw("REPLACE(address, '_', '%') DESC LIMIT 1")
})
.then((result) => {
console.timeEnd('updateMap');
nconf.set('database:aliasRefreshRequired', 0);
nconf.save();
logger.main.info('CRON: Alias Refresh Successful')
})
.catch((err) => {
logger.main.error('CRON: Error refreshing aliases' + err);
console.timeEnd('updateMap');
})
} else {
logger.main.debug('CRON: Alias Refresh not Required, Skipping.')
}
}, null, true);
}
module.exports = app;
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
logger.main.info('Listening on ' + bind);
}