This repository has been archived by the owner on Apr 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparliament.js
2068 lines (1756 loc) · 61.5 KB
/
parliament.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
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
'use strict';
const MIN_PARLIAMENT_VERSION = 3;
/* dependencies ------------------------------------------------------------- */
const express = require('express');
const http = require('http');
const https = require('https');
const fs = require('fs');
const favicon = require('serve-favicon');
const rp = require('request-promise');
const bp = require('body-parser');
const logger = require('morgan');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const glob = require('glob');
const os = require('os');
const helmet = require('helmet');
const uuid = require('uuidv4').default;
const upgrade = require('./upgrade');
/* app setup --------------------------------------------------------------- */
const app = express();
const router = express.Router();
const saltrounds = 13;
const issueTypes = {
esRed: { on: true, name: 'ES Red', text: 'ES is red', severity: 'red', description: 'ES status is red' },
esDown: { on: true, name: 'ES Down', text: ' ES is down', severity: 'red', description: 'ES is unreachable' },
esDropped: { on: true, name: 'ES Dropped', text: 'ES is dropping bulk inserts', severity: 'yellow', description: 'the capture node is overloading ES' },
outOfDate: { on: true, name: 'Out of Date', text: 'has not checked in since', severity: 'red', description: 'the capture node has not checked in' },
noPackets: { on: true, name: 'Low Packets', text: 'is not receiving many packets', severity: 'red', description: 'the capture node is not receiving many packets' }
};
const settingsDefault = {
general : {
noPackets: 0,
noPacketsLength: 10,
outOfDate: 30,
esQueryTimeout: 5,
removeIssuesAfter: 60,
removeAcknowledgedAfter: 15
},
notifiers: {}
};
const parliamentReadError = `\nYou must fix this before you can run Parliament.
Try using parliament.example.json as a starting point`;
// keep a map of invalid tokens for when a user logs out before jwt expires
let invalidTokens = {};
(function () { // parse arguments
let appArgs = process.argv.slice(2);
let file, port;
let debug = 0;
function setPasswordHash (err, hash) {
if (err) {
console.log(`Error hashing password: ${err}`);
return;
}
app.set('password', hash);
}
function help () {
console.log('parliament.js [<config options>]\n');
console.log('Config Options:');
console.log(' -c, --config Parliament config file to use');
console.log(' --pass Password for updating the parliament');
console.log(' --port Port for the web app to listen on');
console.log(' --cert Public certificate to use for https');
console.log(' --key Private certificate to use for https');
console.log(' --debug Increase debug level, multiple are supported');
process.exit(0);
}
for (let i = 0, len = appArgs.length; i < len; i++) {
switch (appArgs[i]) {
case '-c':
case '--config':
file = appArgs[i + 1];
i++;
break;
case '--pass':
bcrypt.hash(appArgs[i + 1], saltrounds, setPasswordHash);
i++;
break;
case '--port':
port = appArgs[i + 1];
i++;
break;
case '--cert':
app.set('certFile', appArgs[i + 1]);
i++;
break;
case '--key':
app.set('keyFile', appArgs[i + 1]);
i++;
break;
case '--dashboardOnly':
app.set('dashboardOnly', true);
break;
case '--regressionTests':
app.set('regressionTests', 1);
break;
case '--debug':
debug++;
break;
case '-h':
case '--help':
help();
break;
default:
console.log(`Unknown option ${appArgs[i]}`);
help();
break;
}
}
if (!appArgs.length) {
console.log('WARNING: No config options were set, starting Parliament in view only mode with defaults.\n');
}
app.set('debug', debug);
// set optional config options that reqiure defaults
app.set('port', port || 8008);
app.set('file', file || './parliament.json');
}());
if (app.get('regressionTests')) {
app.post('/shutdown', function (req, res) {
process.exit(0);
});
}
// parliament object!
let parliament;
try { // check if the file exists
fs.accessSync(app.get('file'), fs.constants.F_OK);
} catch (e) { // if the file doesn't exist, create it
try { // write the new file
parliament = { version: MIN_PARLIAMENT_VERSION };
fs.writeFileSync(app.get('file'), JSON.stringify(parliament, null, 2), 'utf8');
} catch (e) { // notify of error saving new parliament and exit
console.log(`Error creating new Parliament:\n\n`, e.stack);
console.log(parliamentReadError);
process.exit(1);
}
}
try { // get the parliament file or error out if it's unreadable
parliament = require(`${app.get('file')}`);
// set the password if passed in when starting the server
// IMPORTANT! this will overwrite any password in the parliament json file
if (app.get('password')) {
parliament.password = app.get('password');
} else if (parliament.password) {
// if the password is not supplied when starting the server,
// use any existing password in the parliament json file
app.set('password', parliament.password);
}
} catch (e) {
console.log(`Error reading ${app.get('file') || 'your parliament file'}:\n\n`, e.stack);
console.log(parliamentReadError);
process.exit(1);
}
// construct the issues file name
let issuesFilename = 'issues.json';
if (app.get('file').indexOf('.json') > -1) {
let name = app.get('file').replace(/\.json/g, '');
issuesFilename = `${name}.issues.json`;
}
app.set('issuesfile', issuesFilename);
// get the issues file or create it if it doesn't exist
let issues;
try {
issues = require(issuesFilename);
} catch (err) {
issues = [];
}
// define ids for groups and clusters
let groupId = 0;
let clusterId = 0;
// save noPackets issues so that the time of issue can be compared to the
// noPacketsLength user setting (only issue alerts when the time the issue
// was encounterd exceeds the noPacketsLength user setting)
let noPacketsMap = {};
// super secret
app.use(helmet.hidePoweredBy());
app.use(helmet.xssFilter());
app.use(helmet.hsts({
maxAge: 31536000,
includeSubDomains: true
}));
// calculate nonce
app.use((req, res, next) => {
res.locals.nonce = Buffer.from(uuid()).toString('base64');
next();
});
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
/* can remove unsafe-inline for css when this is fixed
https://github.com/vuejs/vue-style-loader/issues/33 */
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'", "'unsafe-eval'", (req, res) => `'nonce-${res.locals.nonce}'`],
objectSrc: ["'none'"],
imgSrc: ["'self'", 'data:'],
frameSrc: ["'none'"]
}
}));
// expose vue bundles (prod)
app.use('/parliament/static', express.static(`${__dirname}/vueapp/dist/static`));
// expose vue bundle (dev)
app.use(['/app.js', '/vueapp/app.js'], express.static(`${__dirname}/vueapp/dist/app.js`));
app.use('/parliament/font-awesome', express.static(`${__dirname}/../node_modules/font-awesome`, { maxAge: 600 * 1000 }));
// log requests
app.use(logger(':date \x1b[1m:method\x1b[0m \x1b[33m:url\x1b[0m :status :res[content-length] bytes :response-time ms', { stream: process.stdout }));
app.use(favicon(`${__dirname}/favicon.ico`));
// define router to mount api related functions
app.use('/parliament/api', router);
router.use(bp.json());
router.use(bp.urlencoded({ extended: true }));
let internals = {
notifierTypes: {}
};
// Load notifier plugins for Parliament alerting
function loadNotifiers () {
let api = {
register: function (str, info) {
internals.notifierTypes[str] = info;
}
};
// look for all notifier providers and initialize them
let files = glob.sync(`${__dirname}/../notifiers/provider.*.js`);
files.forEach((file) => {
let plugin = require(file);
plugin.init(api);
});
}
loadNotifiers();
/* Middleware -------------------------------------------------------------- */
// App should always have parliament data
router.use((req, res, next) => {
if (!parliament) {
const error = new Error('Unable to fetch parliament data.');
error.httpStatusCode = 500;
return next(error);
}
next();
});
// Handle errors
app.use((err, req, res, next) => {
console.log(err.stack);
res.status(err.httpStatusCode || 500).json({
success : false,
text : err.message || 'Error'
});
});
// Verify token
function verifyToken (req, res, next) {
function tokenError (req, res, errorText) {
errorText = errorText || 'Token Error!';
res.status(403).json({
tokenError: true,
success : false,
text : `Permission Denied: ${errorText}`
});
}
let hasAuth = !!app.get('password');
if (!hasAuth) {
return tokenError(req, res, 'No password set.');
}
// check for token in header, url parameters, or post parameters
let token = req.body.token || req.query.token || req.headers['x-access-token'];
if (!token) {
return tokenError(req, res, 'No token provided.');
}
// check for invalid token
if (invalidTokens[token]) {
return tokenError(req, res, 'You\'ve been logged out. Please login again.');
}
// verifies token and expiration
jwt.verify(token, app.get('password'), (err, decoded) => {
if (err) {
return tokenError(req, res, 'Failed to authenticate token. Try logging in again.');
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
}
/* Helper functions -------------------------------------------------------- */
// list of alerts that will be sent at every 10 seconds
let alerts = [];
// sends alerts in the alerts list
async function sendAlerts () {
let promise = new Promise((resolve, reject) => {
for (let i = 0, len = alerts.length; i < len; i++) {
(function (i) {
// timeout so that alerts are alerted in order
setTimeout(() => {
let alert = alerts[i];
let links = [];
if (parliament.settings.general.includeUrl) {
links.push({
text: 'Parliament Dashboard',
url: `${parliament.settings.general.hostname}?searchTerm=${alert.cluster}`
});
}
alert.notifier.sendAlert(alert.config, alert.message, links);
if (app.get('debug')) {
console.log('Sending alert:', alert.message, JSON.stringify(alert.config, null, 2));
}
if (i === len - 1) { resolve(); }
}, 250 * i);
})(i);
}
});
promise.then(() => {
alerts = []; // clear the queue
});
}
// sorts the list of alerts by cluster title then sends them
// assumes that the alert message starts with the cluster title
function processAlerts () {
if (alerts && alerts.length) {
alerts.sort((a, b) => {
return a.message.localeCompare(b.message);
});
sendAlerts();
}
}
function formatIssueMessage (cluster, issue) {
let message = '';
if (issue.node) { message += `${issue.node} `; }
message += `${issue.text}`;
if (issue.value !== undefined) {
let value = ': ';
if (issue.type === 'esDropped') {
value += issue.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
} else if (issue.type === 'outOfDate') {
value += new Date(issue.value);
} else {
value += issue.value;
}
message += `${value}`;
}
return message;
}
function buildAlert (cluster, issue) {
// if there are no notifiers set, skip everything, there's nowhere to alert
if (!parliament.settings.notifiers) { return; }
issue.alerted = Date.now();
const message = `${cluster.title} - ${issue.message}`;
for (let n in parliament.settings.notifiers) {
let setNotifier = parliament.settings.notifiers[n];
// keep looking for notifiers if the notifier is off
if (!setNotifier.on) { continue; }
// quit before sending the alert if the alert is off
if (!setNotifier.alerts[issue.type]) { continue; }
let config = {};
const notifierDef = internals.notifierTypes[setNotifier.type];
for (let f in notifierDef.fields) {
let fieldDef = notifierDef.fields[f];
let field = setNotifier.fields[fieldDef.name];
if (!field || (fieldDef.required && !field.value)) {
// field doesn't exist, or field is required and doesn't have a value
console.log(`Missing the ${field.name} field for ${n} alerting. Add it on the settings page.`);
continue;
}
config[fieldDef.name] = field.value;
}
alerts.push({
config: config,
message: message,
notifier: notifierDef,
cluster: cluster.title
});
}
}
// Finds an issue in a cluster
function findIssue (clusterId, issueType, node) {
for (let issue of issues) {
if (issue.clusterId === clusterId &&
issue.type === issueType &&
issue.node === node) {
return issue;
}
}
}
// Updates an existing issue or pushes a new issue onto the issue array
function setIssue (cluster, newIssue) {
// build issue
let issueType = issueTypes[newIssue.type];
newIssue.text = issueType.text;
newIssue.title = issueType.name;
newIssue.severity = issueType.severity;
newIssue.clusterId = cluster.id;
newIssue.cluster = cluster.title;
newIssue.message = formatIssueMessage(cluster, newIssue);
newIssue.provisional = true;
let existingIssue = false;
// don't duplicate existing issues, update them
for (let issue of issues) {
if (issue.clusterId === newIssue.clusterId &&
issue.type === newIssue.type &&
issue.node === newIssue.node) {
existingIssue = true;
// this is at least the second time we've seen this issue
// so it must be a persistent issue
issue.provisional = false;
if (Date.now() > issue.ignoreUntil && issue.ignoreUntil !== -1) {
// the ignore has expired, so alert!
issue.ignoreUntil = undefined;
issue.alerted = undefined;
}
issue.lastNoticed = Date.now();
// if the issue has not been acknowledged, ignored, or alerted, or
// if the cluster is not a no alert cluster or multiviewer cluster,
// build and issue an alert
if (!issue.acknowledged && !issue.ignoreUntil &&
!issue.alerted && cluster.type !== 'noAlerts' &&
cluster.type !== 'multiviewer') {
buildAlert(cluster, issue);
}
}
}
if (!existingIssue) {
// this is the first time we've seen this issue
// don't alert yet, but create the issue
newIssue.firstNoticed = Date.now();
newIssue.lastNoticed = Date.now();
issues.push(newIssue);
}
if (app.get('debug') > 1) {
console.log('Setting issue:', JSON.stringify(newIssue, null, 2));
}
const issuesError = validateIssues();
if (!issuesError) {
fs.writeFile(app.get('issuesfile'), JSON.stringify(issues, null, 2), 'utf8',
(err) => {
if (err) {
console.log('Unable to write issue:', err.message || err);
}
}
);
}
}
// Retrieves the health of each cluster and updates the cluster with that info
function getHealth (cluster) {
return new Promise((resolve, reject) => {
let timeout = getGeneralSetting('esQueryTimeout') * 1000;
let options = {
url: `${cluster.localUrl || cluster.url}/eshealth.json`,
method: 'GET',
rejectUnauthorized: false,
timeout: timeout
};
rp(options)
.then((response) => {
cluster.healthError = undefined;
let health;
try {
health = JSON.parse(response);
} catch (e) {
cluster.healthError = 'ES health parse failure';
console.log('Bad response for es health', cluster.localUrl || cluster.url);
return resolve();
}
if (health) {
cluster.status = health.status;
cluster.totalNodes = health.number_of_nodes;
cluster.dataNodes = health.number_of_data_nodes;
if (cluster.status === 'red') { // alert on red es status
setIssue(cluster, { type: 'esRed' });
}
}
return resolve();
})
.catch((error) => {
let message = error.message || error;
setIssue(cluster, { type: 'esDown', value: message });
cluster.healthError = message;
if (app.get('debug')) {
console.log('HEALTH ERROR:', options.url, message);
}
return resolve();
});
});
}
// Retrieves, then calculates stats for each cluster and updates the cluster with that info
function getStats (cluster) {
return new Promise((resolve, reject) => {
let timeout = getGeneralSetting('esQueryTimeout') * 1000;
let options = {
url: `${cluster.localUrl || cluster.url}/parliament.json`,
method: 'GET',
rejectUnauthorized: false,
timeout: timeout
};
// Get now before the query since we don't know how long query/response will take
let now = Date.now() / 1000;
rp(options)
.then((response) => {
cluster.statsError = undefined;
if (response.bsqErr) {
cluster.statsError = response.bsqErr;
console.log('Get stats error', response.bsqErr);
return resolve();
}
let stats;
try {
stats = JSON.parse(response);
} catch (e) {
cluster.statsError = 'ES stats parse failure';
console.log('Bad response for stats', cluster.localUrl || cluster.url);
return resolve();
}
if (!stats || !stats.data) { return resolve(); }
cluster.deltaBPS = 0;
cluster.deltaTDPS = 0;
cluster.molochNodes = 0;
cluster.monitoring = 0;
let outOfDate = getGeneralSetting('outOfDate');
for (let stat of stats.data) {
// sum delta bytes per second
if (stat.deltaBytesPerSec) {
cluster.deltaBPS += stat.deltaBytesPerSec;
}
// sum delta total dropped per second
if (stat.deltaTotalDroppedPerSec) {
cluster.deltaTDPS += stat.deltaTotalDroppedPerSec;
}
if (stat.monitoring) {
cluster.monitoring += stat.monitoring;
}
if ((now - stat.currentTime) <= outOfDate && stat.deltaPacketsPerSec > 0) {
cluster.molochNodes++;
}
// Look for issues
if ((now - stat.currentTime) > outOfDate) {
setIssue(cluster, {
type : 'outOfDate',
node : stat.nodeName,
value : stat.currentTime * 1000
});
}
// look for no packets issue
if (stat.deltaPacketsPerSec <= getGeneralSetting('noPackets')) {
let now = Date.now();
let id = cluster.title + stat.nodeName;
// only set the noPackets issue if there is a record of this cluster/node
// having noPackets and that issue has persisted for the set length of time
if (noPacketsMap[id] &&
now - noPacketsMap[id] >= (getGeneralSetting('noPacketsLength') * 1000)) {
setIssue(cluster, {
type: 'noPackets',
node: stat.nodeName,
value: stat.deltaPacketsPerSec
});
} else if (!noPacketsMap[id]) {
// if this issue has not been encountered yet, make a record of it
noPacketsMap[id] = Date.now();
}
}
if (stat.deltaESDroppedPerSec > 0) {
setIssue(cluster, {
type : 'esDropped',
node : stat.nodeName,
value : stat.deltaESDroppedPerSec
});
}
}
return resolve();
})
.catch((error) => {
let message = error.message || error;
setIssue(cluster, { type: 'esDown', value: message });
cluster.statsError = message;
if (app.get('debug')) {
console.log('STATS ERROR:', options.url, message);
}
return resolve();
});
});
}
function buildNotifierTypes () {
for (let n in internals.notifierTypes) {
let notifier = internals.notifierTypes[n];
// add alert issue types to notifiers
notifier.alerts = issueTypes;
// make fields a map
let fieldsMap = {};
for (let field of notifier.fields) {
fieldsMap[field.name] = field;
}
notifier.fields = fieldsMap;
}
if (app.get('debug')) {
console.log('Built notifier alerts:', JSON.stringify(internals.notifierTypes, null, 2));
}
}
// Initializes the parliament with ids for each group and cluster
// and sets up the parliament settings
function initializeParliament () {
return new Promise((resolve, reject) => {
if (!parliament.version || parliament.version < MIN_PARLIAMENT_VERSION) {
// notify of upgrade
console.log(
`WARNING - Current parliament version (${parliament.version || 1}) is less then required version (${MIN_PARLIAMENT_VERSION})
Upgrading ${app.get('file')} file...\n`
);
// do the upgrade
parliament = upgrade.upgrade(parliament, internals.notifierTypes);
try { // write the upgraded file
const parliamentError = validateParliament();
if (!parliamentError) {
fs.writeFileSync(app.get('file'), JSON.stringify(parliament, null, 2), 'utf8');
}
} catch (e) { // notify of error saving upgraded parliament and exit
console.log(`Error upgrading Parliament:\n\n`, e.stack);
console.log(parliamentReadError);
process.exit(1);
}
// notify of upgrade success
console.log(`SUCCESS - Parliament upgraded to version ${MIN_PARLIAMENT_VERSION}`);
}
if (!parliament.groups) { parliament.groups = []; }
// set id for each group/cluster
for (let group of parliament.groups) {
group.id = groupId++;
if (group.clusters) {
for (let cluster of group.clusters) {
cluster.id = clusterId++;
}
}
}
if (!parliament.settings) {
parliament.settings = settingsDefault;
}
if (!parliament.settings.notifiers) {
parliament.settings.notifiers = settingsDefault.notifiers;
}
if (!parliament.settings.general) {
parliament.settings.general = settingsDefault.general;
}
if (!parliament.settings.general.outOfDate) {
parliament.settings.general.outOfDate = settingsDefault.general.outOfDate;
}
if (!parliament.settings.general.noPackets) {
parliament.settings.general.noPackets = settingsDefault.general.noPackets;
}
if (!parliament.settings.general.noPacketsLength) {
parliament.settings.general.noPacketsLength = settingsDefault.general.noPacketsLength;
}
if (!parliament.settings.general.esQueryTimeout) {
parliament.settings.general.esQueryTimeout = settingsDefault.general.esQueryTimeout;
}
if (!parliament.settings.general.removeIssuesAfter) {
parliament.settings.general.removeIssuesAfter = settingsDefault.general.removeIssuesAfter;
}
if (!parliament.settings.general.removeAcknowledgedAfter) {
parliament.settings.general.removeAcknowledgedAfter = settingsDefault.general.removeAcknowledgedAfter;
}
if (!parliament.settings.general.hostname) {
parliament.settings.general.hostname = os.hostname();
}
if (app.get('debug')) {
console.log('Parliament initialized!');
console.log('Parliament groups:', JSON.stringify(parliament.groups, null, 2));
console.log('Parliament general settings:', JSON.stringify(parliament.settings.general, null, 2));
}
buildNotifierTypes();
const parliamentError = validateParliament();
if (!parliamentError) {
fs.writeFile(app.get('file'), JSON.stringify(parliament, null, 2), 'utf8',
(err) => {
if (err) {
console.log('Parliament initialization error:', err.message || err);
return reject(new Error('Parliament initialization error'));
}
return resolve();
}
);
}
});
}
// Chains all promises for requests for health and stats to update each cluster
// in the parliament
function updateParliament () {
return new Promise((resolve, reject) => {
let promises = [];
for (let group of parliament.groups) {
if (group.clusters) {
for (let cluster of group.clusters) {
// only get health for online clusters
if (cluster.type !== 'disabled') {
promises.push(getHealth(cluster));
}
// don't get stats for multiviewers or offline clusters
if (cluster.type !== 'multiviewer' && cluster.type !== 'disabled') {
promises.push(getStats(cluster));
}
}
}
}
let issuesRemoved = cleanUpIssues();
Promise.all(promises)
.then(() => {
if (issuesRemoved) { // save the issues that were removed
const issuesError = validateIssues();
if (!issuesError) {
fs.writeFile(app.get('issuesfile'), JSON.stringify(issues, null, 2), 'utf8',
(err) => {
if (err) {
console.log('Unable to write issue:', err.message || err);
}
}
);
}
}
// save the data created after updating the parliament
const parliamentError = validateParliament();
if (!parliamentError) {
fs.writeFile(app.get('file'), JSON.stringify(parliament, null, 2), 'utf8',
(err) => {
if (err) {
console.log('Parliament update error:', err.message || err);
return reject(new Error('Parliament update error'));
}
return resolve();
});
}
if (app.get('debug')) {
console.log('Parliament updated!');
if (issuesRemoved) {
console.log('Issues updated!');
}
}
return resolve();
})
.catch((error) => {
console.log('Parliament update error:', error.messge || error);
return resolve();
});
});
}
function cleanUpIssues () {
let issuesRemoved = false;
let len = issues.length;
while (len--) {
const issue = issues[len];
const timeSinceLastNoticed = Date.now() - issue.lastNoticed || issue.firstNoticed;
const removeIssuesAfter = getGeneralSetting('removeIssuesAfter') * 1000 * 60;
const removeAcknowledgedAfter = getGeneralSetting('removeAcknowledgedAfter') * 1000 * 60;
if (!issue.ignoreUntil) { // don't clean up any ignored issues, wait for the ignore to expire
// remove issues that are provisional that haven't been seen since the last cycle
if (issue.provisional && timeSinceLastNoticed >= 10000) {
issuesRemoved = true;
issues.splice(len, 1);
}
// remove all issues that have not been seen again for the removeIssuesAfter time, and
// remove all acknowledged issues that have not been seen again for the removeAcknowledgedAfter time
if ((!issue.acknowledged && timeSinceLastNoticed > removeIssuesAfter) ||
(issue.acknowledged && timeSinceLastNoticed > removeAcknowledgedAfter)) {
issuesRemoved = true;
issues.splice(len, 1);
}
// if the issue was acknowledged but still persists, unacknowledge and alert again
if (issue.acknowledged && (Date.now() - issue.acknowledged) > removeAcknowledgedAfter) {
issue.alerted = undefined;
issue.acknowledged = undefined;
}
}
}
return issuesRemoved;
}
function removeIssue (issueType, clusterId, nodeId) {
let foundIssue = false;
let len = issues.length;
while (len--) {
const issue = issues[len];
if (issue.clusterId === parseInt(clusterId) &&
issue.type === issueType &&
issue.node === nodeId) {
foundIssue = true;
issues.splice(len, 1);
if (issue.type === 'noPackets') {
// also remove it from the no packets record
delete noPacketsMap[issue.cluster + nodeId];
}
}
}
return foundIssue;
}
function getGeneralSetting (type) {
let val = settingsDefault.general[type];
if (parliament.settings && parliament.settings.general && parliament.settings.general[type]) {
val = parliament.settings.general[type];
}
return val;
}
// Validates that the parliament object exists
// Use this before writing the parliament file
function validateParliament (next) {
const length = Buffer.from(JSON.stringify(parliament, null, 2)).length;
if (length < 320) {
// if it's an empty file, don't save it, return an error
const errorMsg = 'Error writing parliament data: empty or invalid parliament';
console.log(errorMsg);
if (next) {
const error = new Error(errorMsg);
error.httpStatusCode = 500;
return error;
}
return errorMsg;
}
return false;
}
// Writes the parliament to the parliament json file, updates the parliament
// with health and stats, then sends success or error
function writeParliament (req, res, next, successObj, errorText, sendParliament) {
const parliamentError = validateParliament(next);
if (parliamentError) {
return next(parliamentError);
}
fs.writeFile(app.get('file'), JSON.stringify(parliament, null, 2), 'utf8',
(err) => {
if (app.get('debug')) {
console.log('Wrote parliament file', err || '');
}
if (err) {
const errorMsg = `Unable to write parliament data: ${err.message || err}`;
console.log(errorMsg);
const error = new Error(errorMsg);
error.httpStatusCode = 500;
return next(error);
}
updateParliament()
.then(() => {
// send the updated parliament with the response
if (sendParliament && successObj.parliament) {
successObj.parliament = parliament;
}
return res.json(successObj);
})
.catch((err) => {
const error = new Error(errorText || 'Error updating parliament.');
error.httpStatusCode = 500;
return next(error);
});
}
);
}
// Validates that issues exist
// Use this before writing the issues file
function validateIssues (next) {
const length = Buffer.from(JSON.stringify(issues, null, 2)).length;
if (length < 2) {
// if it's an empty file, don't save it, return an error