This repository has been archived by the owner on May 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathapp.js
898 lines (712 loc) · 35.7 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
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
/*
© Anthrino > Express APP
*/
'use strict';
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var tail_module = require('always-tail2');
const execSync = require('child_process').execSync;
var app = express();
var api_agent = require('./lib/api_service.js');
/* Read Config */
var json_file = require('jsonfile');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
/* URL Routes */
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));
app.use('/nw_detail_info', require('./routes/nw_detail_info'));
app.use('/dhcp_device_statistics_page', require('./routes/dhcp_device_statistics_page'));
app.use('/get_mac_device_stats', require('./routes/get_mac_device_stats'));
app.use('/get_dhcp_requests', require('./routes/get_dhcp_requests'));
app.use('/dhcp_leases', require('./routes/dhcp_leases'));
app.use('/dhcp_lease_search', require('./routes/dhcp_lease_search'));
app.use('/dhcp_log', require('./routes/dhcp_log'));
app.use('/dhcp_config', require('./routes/dhcp_config'));
app.use('/dhcp_config_snapshots', require('./routes/dhcp_config_snapshots'));
app.use('/dhcp_config_snapshot_view', require('./routes/dhcp_config_snapshot_view'));
app.use('/dhcp_config_update', require('./routes/dhcp_config_update'));
app.use('/dhcp_boot_ops', require('./routes/dhcp_boot_ops'));
app.use('/anterius_settings', require('./routes/anterius_settings'));
app.use('/anterius_alerts', require('./routes/anterius_alert_settings'));
app.use('/anterius_alert_settings_save', require('./routes/anterius_alert_settings_save'));
app.use('/anterius_settings_save', require('./routes/anterius_settings_save'));
/* Glass API Routes - disabled */
// app.use('/api/get_subnet_details/', require('./api/get_subnet_details'));
// app.use('/api/get_vendor_count/', require('./api/get_vendor_count'));
// app.use('/api/get_mac_oui_count_by_vendor/', require('./api/get_mac_oui_count_by_vendor'));
// app.use('/api/get_server_info/', require('./api/get_server_info'));
// app.use('/api/get_mac_oui_list/', require('./api/get_mac_oui_list'));
app.set('view engine', 'html');
// 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) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.send(err.message);
});
module.exports = app;
/* Anterius Data Model - Global Variables */
var host_name = '';
global.kea_stats = {};
global.kea_config = {};
global.anterius_config = json_file.readFileSync('config/anterius_config.json');
/* Global Identifier structure for current server */
global.kea_server = {
'server_config': {}, 'svr_tag': '', 'sn_tag': '', 'addr_tag': '',
'cpu_utilization': 0,
'total_leases': 0,
'leases_per_sec_date': null,
'leases_per_sec_total': 0,
'leases_per_sec': 0,
'leases_per_minute_date': null,
'leases_per_minute_total': 0,
'leases_per_minute': 0,
'server_active': 1,
'data_fetch': 0,
'local_server': 0,
'run_status': '',
'subnet_list': [],
};
global.oui_data = {};
var listening_to_log_file = 0;
var options = { 'interval': 1000 };
/* Dir for config file snapshots */
global.bkp_dir = "config_backups/" + global.anterius_config.current_server;
if (global.anterius_config.ip_ranges_to_allow != "") {
var ip_filter = require('express-ipfilter').IpFilter;
var ips = global.anterius_config.ip_ranges_to_allow;
app.use(ip_filter(ips, { mode: 'allow' }));
}
// TODO: Add Mechanism to retrieve following attibutes from remote machine - future release
if (global.anterius_config.server_addr == 'localhost' || global.anterius_config.server_addr == '127.0.0.1') {
global.kea_server.local_server = 1;
host_name = execSync("cat /etc/hostname").toString().replace("\n", "");
global.kea_server.run_status = execSync("keactrl status").toString();
/* Poll: CPU Utilization */
var cpu_utilization_poll = setInterval(function () {
global.kea_server.cpu_utilization = parseFloat(execSync("top -bn 1 | awk 'NR>7{s+=$9} END {print s/4}'").toString())
}, (15 * 1000));
}
/* Kea CA REST API call - config-get and statistics-get */
var stats_req_data = JSON.stringify({ "command": "statistic-get-all", "service": [global.anterius_config.current_server] });
var config_get_req_data = JSON.stringify({ "command": "config-get", "service": [global.anterius_config.current_server] });
/* Fetch and set server stats*/
api_agent.fire_kea_api(stats_req_data, global.anterius_config.server_addr, global.anterius_config.server_port).then(function (api_data) {
// console.log(api_data);
if (api_data.result == 0)
global.kea_stats = api_data.arguments;
else
console.log("CA Error: " + api_data.text);
}).catch(function () {
global.kea_server.server_active = 0;
});
/* Fetch and set server config*/
api_agent.fire_kea_api(config_get_req_data, global.anterius_config.server_addr, global.anterius_config.server_port).then(function (api_data) {
// console.log(api_data);
if (api_data.result == 0)
global.kea_config = api_data.arguments;
else
console.log("CA Error: " + api_data.text);
}).catch(function () {
global.kea_server.server_active = 0;
});;
/* Ingest OUI Database */
var fs = require('fs');
var oui_database_file = "bin/oui_table.txt";
/* Global global.oui_data bucket */
if (fs.existsSync(oui_database_file)) {
fs.readFile(oui_database_file, 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
else {
/* Iterate through file */
var lines = data.split("\n");
for (var l = 0; l < lines.length; l++) {
/* Trim whitespaces at each ends of the line */
lines[l] = lines[l].trim();
var oui_line_data = lines[l].split(":::");
if (typeof oui_line_data[1] !== "undefined")
global.oui_data[oui_line_data[0].trim()] = oui_line_data[1].trim();
}
// console.log(global.oui_data);
console.log("Anterius Server> OUI Database Loaded");
}
});
}
var hostMonitorInterval = null;
var leaseStatsMonitorInterval = null;
var host_monitor = function () {
return new Promise(function (resolve, reject) {
if (global.anterius_config.server_addr == 'localhost' || global.anterius_config.server_addr == '127.0.0.1') {
global.kea_server.local_server = 1;
host_name = execSync("cat /etc/hostname").toString().replace("\n", "");
global.kea_server.run_status = execSync("keactrl status").toString();
global.kea_server.cpu_utilization = parseFloat(execSync("top -bn 1 | awk 'NR>7{s+=$9} END {print s/4}'").toString())
}
resolve();
});
}
/* * Recurrent Loop for lease stats * */
var lease_stats_monitor = function () {
stats_req_data = JSON.stringify({ "command": "statistic-get-all", "service": [global.anterius_config.current_server] });
config_get_req_data = JSON.stringify({ "command": "config-get", "service": [global.anterius_config.current_server] });
return new Promise(function (resolve, reject) {
var response_data = api_agent.fire_kea_api(config_get_req_data, global.anterius_config.server_addr, global.anterius_config.server_port).then(function (data) {
if (data.result == 0 && data.arguments != undefined) {
global.kea_config = data.arguments;
global.kea_server.subnet_list = [];
global.kea_server.server_config = global.kea_config;
/* Set identifiers based on current server */
if (global.anterius_config.current_server == 'dhcp4') {
global.kea_server.svr_tag = 'Dhcp4';
global.kea_server.sn_tag = 'subnet4';
global.kea_server.addr_tag = 'addresses';
}
else {
global.kea_server.svr_tag = 'Dhcp6';
global.kea_server.sn_tag = 'subnet6';
global.kea_server.addr_tag = 'pds';
}
// console.log(server,global.kea_server.server_config[global.kea_server.svr_tag], global.kea_server.sn_tag, global.kea_server.addr_tag);
/* Retrieve and store subnets defined within shared nw */
global.kea_server.server_config[global.kea_server.svr_tag]['shared-networks'].forEach(shnw => {
shnw[global.kea_server.sn_tag].forEach(x => {
x['shared_nw_name'] = shnw.name;
global.kea_server.subnet_list.push(x);
});
});
/* Retrieve and store subnets defined*/
global.kea_server.server_config[global.kea_server.svr_tag][global.kea_server.sn_tag].forEach(x => {
global.kea_server.subnet_list.push(x);
});
/* Subnet sorting by ID */
global.kea_server.subnet_list.sort(function (a, b) {
return parseInt(a.id) - parseInt(b.id);
});
} else {
console.log("CA Error: " + data.text);
global.kea_server.server_active = 0;
}
}).catch(function (e) {
console.log('Error 2: ', e);
global.kea_server.server_active = 0;
});
/* Fetch and set server stats*/
var response_data = api_agent.fire_kea_api(stats_req_data, global.anterius_config.server_addr, global.anterius_config.server_port).then(function (sdata) {
if (sdata.result == 0) {
global.kea_server.total_leases = 0;
var subnet_count = global.kea_server.subnet_list.length;
var shared_nw_count = global.kea_server.server_config[global.kea_server.svr_tag]['shared-networks'].length;
global.kea_stats = sdata.arguments;
for (var i = 1; i <= subnet_count; i++) {
global.kea_server.total_leases += global.kea_stats['subnet[' + i + '].assigned-' + global.kea_server.addr_tag][0][0];
}
var now = new Date();
if (global.kea_server.leases_per_sec_date !== null) {
var leaseDifference = global.kea_server.total_leases - global.kea_server.leases_per_sec_total;
global.kea_server.leases_per_sec_total = global.kea_server.total_leases;
if (leaseDifference > 0) {
var timeDifference = (now.getTime() - global.kea_server.leases_per_sec_date.getTime()) / 1000;
global.kea_server.leases_per_sec = Math.round(leaseDifference / timeDifference);
if (global.kea_server.leases_per_sec > global.kea_server.total_leases) {
global.kea_server.leases_per_sec = global.kea_server.total_leases;
}
} else {
global.kea_server.leases_per_sec = 0;
}
}
global.kea_server.leases_per_sec_date = new Date();
if (global.kea_server.leases_per_minute_date !== null) {
var timeDifference = (now.getTime() - global.kea_server.leases_per_minute_date.getTime()) / 1000;
if (timeDifference >= 60) {
var leaseDifference = global.kea_server.total_leases - global.kea_server.leases_per_minute_total;
global.kea_server.leases_per_minute = Math.round(leaseDifference * 60 / timeDifference);
if (global.kea_server.leases_per_minute < 0) {
global.kea_server.leases_per_minute = 0;
} else if (global.kea_server.leases_per_minute > global.kea_server.total_leases) {
global.kea_server.leases_per_minute = global.kea_server.total_leases;
}
global.kea_server.leases_per_minute_total = global.kea_server.total_leases;
global.kea_server.leases_per_minute_date = new Date();
}
} else {
global.kea_server.leases_per_minute_date = new Date();
}
} else {
console.log("CA Error: " + sdata.text);
global.kea_server.server_active = 0;
}
}).catch(function (e) {
console.log('Error 1: ', e);
global.kea_server.server_active = 0;
});
resolve();
});
};
/* Call and export stats function */
lease_stats_monitor();
// dummy
function reload() {
return new Promise(function (resolve, reject) {
resolve();
});
return;
}
exports.reload = reload;
/**
* Clean Expired Leases
*/
// lease_clean_timer = setInterval(function () {
// lease_parser.clean();
// }, (60 * 1000));
// function get_socket_clients_connected_count() {
// wss.clients.forEach(function each(client) {
// if (client.readyState === WebSocket.OPEN) {
// socket_clients++;
// }
// });
// return socket_clients;
// }
/* Watch Anterius settings file changes and reload */
fs.watch('config/anterius_config.json', function (event, filename) {
lease_stats_monitor();
if (filename) {
setTimeout(function () {
json_file.readFile('config/anterius_config.json', function (err, data) {
if (err) throw err;
global.anterius_config = data;
});
global.kea_server.server_active = 1;
console.log("Anterius Server> Config Loaded");
}, 2000);
} else {
console.log('filename not provided');
}
});
/* Websocket Server */
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
options.interval = 300;
var tail_dhcp_log = new tail_module(
global.anterius_config.log_file,
"\n",
options
);
global.dhcp_requests = {};
/* Watch DHCP Log File */
tail_dhcp_log.on("line", function (data) {
if (listening_to_log_file) {
wss.broadcast_event(data, 'dhcp_log_subscription');
}
/* Collect Excessive DHCP Request Data */
if (/DHCPREQUEST/i.test(data)) {
var request_from = "";
var request_for = "";
var request_via = "";
var request_data = data.split(" ");
var length = request_data.length;
for (var i = 0; i < length; i++) {
if (request_data[i] == "from") {
request_from = request_data[i + 1];
}
if (request_data[i] == "for") {
request_for = request_data[i + 1];
}
if (request_data[i] == "via") {
request_via = request_data[i + 1];
}
}
if (typeof dhcp_requests[request_from] === "undefined")
dhcp_requests[request_from] = {};
if (typeof dhcp_requests[request_from].request_for === "undefined")
dhcp_requests[request_from].request_for = request_for;
if (typeof dhcp_requests[request_from].request_via === "undefined")
dhcp_requests[request_from].request_via = request_via;
if (typeof dhcp_requests[request_from].request_count === "undefined")
dhcp_requests[request_from].request_count = 0;
if (typeof request_from !== "undefined") {
if (request_from.length == 17 && /:/.test(request_from)) {
var mac_oui = request_from.split(":").join("").toUpperCase().slice(0, 6);
if (typeof dhcp_requests[request_from].request_vendor === "undefined")
dhcp_requests[request_from].request_vendor = global.oui_data[mac_oui];
}
}
dhcp_requests[request_from].request_count++;
}
});
// const purge_request_data = setInterval(function () {
// for (var key in dhcp_requests) {
// if (dhcp_requests[key].request_count <= 10)
// delete dhcp_requests[key];
// }
// }, 600 * 1000);
// /* 10 Minutes */
// const purge_request_data_hour = setInterval(function () {
// dhcp_requests = {};
// }, 3600 * 1000);
/* 60 Minutes */
function closeClientConnection(ws) {
if (ws.keepAliveInterval != undefined) {
clearInterval(ws.keepAliveInterval);
}
try {
ws.terminate();
} catch (e) {console.log(e)}
var count = 0;
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
count++;
}
});
if (count === 0) {
if (leaseStatsMonitorInterval !== null) {
clearInterval(leaseStatsMonitorInterval);
leaseStatsMonitorInterval = null;
}
if (hostMonitorInterval !== null) {
clearInterval(hostMonitorInterval);
hostMonitorInterval = null;
}
}
console.log("[WS] close connection (" + ws.id + ")");
}
wss.on('connection', function connection(ws, req) {
if (leaseStatsMonitorInterval === null) {
lease_stats_monitor();
leaseStatsMonitorInterval = setInterval(lease_stats_monitor, global.anterius_config.stat_refresh_interval * 1000);
}
if (hostMonitorInterval === null) {
host_monitor();
hostMonitorInterval = setInterval(host_monitor, global.anterius_config.stat_refresh_interval * 1000);
}
ws.id = req.headers['sec-websocket-key'];
console.log("[WS] open connection (" + ws.id + ")");
ws.keepAliveInterval = setInterval(function(ws) {
if (ws.readyState === WebSocket.OPEN) {
ws.ping('noop');
ws.keepAliveTimeout = setTimeout(function(ws) {
closeClientConnection(ws);
}, 2 * 1000, ws);
console.log("[WS] ping from (" + ws.id + ")");
} else {
closeClientConnection(ws);
}
}, 10 * 1000, ws);
ws.on('close', function() {
closeClientConnection(this);
});
ws.on('pong',function() {
console.log("[WS] received pong from (" + this.id + ")");
clearTimeout(ws.keepAliveTimeout);
});
if (!listening_to_log_file) {
/* Watch log file for new information */
var tail_module = require('always-tail2');
listening_to_log_file = 1;
}
ws.event_subscription = [];
ws.on('message', function incoming(data) {
if (data != "" && isJson(data)) {
var json = JSON.parse(data);
if (typeof json["event_subscription"] !== "undefined") {
console.log("[WS] Incoming Subscription '%s'", json['event_subscription']);
ws.event_subscription[json["event_subscription"]] = 1;
}
if (typeof json["event_unsubscribe"] !== "undefined") {
console.log("[WS] event_unsubscribe '%s'", json['event_unsubscribe']);
delete ws.event_subscription[json["event_unsubscribe"]];
}
if (typeof json["all_events"] !== "undefined") {
console.log("[WS] event_unsubscribe '%s'", json['event_unsubscribe']);
ws.event_subscription = [];
}
}
});
});
function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function ws_event_subscribers(event) {
if (typeof wss === "undefined")
return false;
var is_listening = false;
wss.clients.forEach(function each(ws) {
/* Count event listeners */
for (var event_listening in ws.event_subscription) {
if (event_listening == event) {
is_listening = true;
return true;
}
}
});
if (is_listening) {
return true;
}
return false;
}
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
};
wss.broadcast_event = function broadcast(data, event) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
if (client.event_subscription[event])
client.send(JSON.stringify({ "event": event, "data": data }));
}
});
};
/**
* Slack Hooks
*/
// var Slack = require('slack-node');
// webhookUri = global.anterius_config.slack_webhook_url;
// slack = new Slack();
// slack.setWebhook(webhookUri);
// function slack_message(message) {
// console.log("[Slack] %s", message);
// slack.webhook({
// channel: global.anterius_config.slack_alert_channel,
// username: "Glass",
// icon_emoji: "https://imgur.com/wD3CcBi",
// text: "(" + host_name + ") " + message
// }, function (err, response) {
// console.log(response);
// });
// }
/**
* Alert Checks - disabled
*/
// alert_status = [];
// alert_status['global.kea_server.leases_per_minute'] = 0;
// setTimeout(function () {
// console.log("Anterius Server> Alert loop started");
// // Server LPM Alert timer - 5s loop
// alert_check_timer = setInterval(function () {
// // console.log("[Timer] Alert Timer check");
// if (global.anterius_config.leases_per_minute_threshold > 0) {
// // console.log("[Timer] lpm: %s lpm_th: %s", global.kea_server.leases_per_minute, global.anterius_config.leases_per_minute_threshold);
// if (global.kea_server.leases_per_minute <= global.anterius_config.leases_per_minute_threshold && alert_status['global.kea_server.leases_per_minute'] == 0) {
// alert_status['global.kea_server.leases_per_minute'] = 1;
// // TODO: enable slack warning hook if required
// // slack_message(":warning: CRITICAL: DHCP leases per minute have dropped below threshold " +
// // "(" + parseInt(global.anterius_config.leases_per_minute_threshold).toLocaleString('en') + ") " +
// // "Current (" + parseInt(global.kea_server.leases_per_minute).toLocaleString('en') + ")");
// email_alert("CRITICAL: Leases Per Minute Threshold", "DHCP leases per minute dropped below critical threshold <br><br>" +
// "Threshold: (" + parseInt(global.anterius_config.leases_per_minute_threshold).toLocaleString('en') + ") <br>" +
// "Current: (" + parseInt(global.kea_server.leases_per_minute).toLocaleString('en') + ") <br><br>" +
// "This is usually indicative of a process or hardware problem and needs to be addressed immediately");
// }
// else if (global.kea_server.leases_per_minute >= global.anterius_config.leases_per_minute_threshold && alert_status['global.kea_server.leases_per_minute'] == 1) {
// alert_status['global.kea_server.leases_per_minute'] = 0;
// // TODO: enable slack warning hook if required
// // slack_message(":white_check_mark: CLEAR: DHCP leases per minute have returned to above threshold " +
// // "(" + parseInt(global.anterius_config.leases_per_minute_threshold).toLocaleString('en') + ") " +
// // "Current (" + parseInt(global.kea_server.leases_per_minute).toLocaleString('en') + ")");
// email_alert("CLEAR: Leases Per Minute Threshold", "DHCP leases per minute have returned to normal <br><br>" +
// "Threshold: (" + parseInt(global.anterius_config.leases_per_minute_threshold).toLocaleString('en') + ") <br>" +
// "Current: (" + parseInt(global.kea_server.leases_per_minute).toLocaleString('en') + ")"
// );
// }
// }
// }, (5 * 1000));
// alert_status_networks_warning = [];
// alert_status_networks_critical = [];
// /*
// ** TODO: Replace shared nw location attribute as per global.kea_stats results
// */
// // Shared nw utilzn Alert timer - 5s loop
// alert_subnet_check_timer = setInterval(function () {
// // console.log("[Timer] Alert Timer check - subnets");
// if (global.anterius_config.shared_network_warning_threshold > 0 || global.anterius_config.shared_network_critical_threshold > 0) {
// // TODO: remove local dhcpd-pools parser tools if deemed not required
// // const execSync = require('child_process').execSync;
// // output = execSync('./bin/dhcpd-pools -c ' + global.anterius_config.config_file + ' -l ' + global.anterius_config.leases_file + ' -f j -A -s e');
// // var dhcp_data = JSON.parse(output);
// // Calculate Shared network utilization
// shared_nw_count = global.kea_config['Dhcp4']['shared-networks'].length;
// shared_nw_util = [];
// for (var i = 0; i < shared_nw_count; i++) {
// // TODO: verify shared nw stats are received as below usage
// utilization = round(parseFloat(global.kea_stats['shared-network[' + i + '].assigned-addresses'][0][0] / global.kea_stats['shared-network[' + i + '].total-addresses'][0][0]) * 100, 2);
// if (isNaN(utilization))
// utilization = 0;
// /* Initialize these array buckets */
// if (typeof alert_status_networks_warning[global.kea_stats['shared-networks'][i].location] === "undefined")
// alert_status_networks_warning[global.kea_stats['shared-networks'][i].location] = 0;
// if (typeof alert_status_networks_critical[global.kea_stats['shared-networks'][i].location] === "undefined")
// alert_status_networks_critical[global.kea_stats['shared-networks'][i].location] = 0;
// /*
// console.log("Location: %s", global.kea_stats['shared-networks'][i].location);
// console.log("Used: %s", dhcp_data['shared-networks'][i].used.toLocaleString('en'));
// console.log("Defined: %s", dhcp_data['shared-networks'][i].defined.toLocaleString('en'));
// console.log("Free: %s", dhcp_data['shared-networks'][i].free.toLocaleString('en'));
// console.log("Utilization: %s", utilization);
// console.log(" \n");
// */
// /* Check Warnings */
// if (global.anterius_config.shared_network_warning_threshold > 0) {
// if (
// utilization >= global.anterius_config.shared_network_warning_threshold &&
// utilization <= global.anterius_config.shared_network_critical_threshold &&
// alert_status_networks_warning[global.kea_stats['shared-networks'][i].location] == 0
// ) {
// alert_status_networks_warning[global.kea_stats['shared-networks'][i].location] = 1;
// // TODO: enable slack warning hook if required
// // slack_message(":warning: WARNING: DHCP shared network utilization (" + global.kea_stats['shared-networks'][i].location + ") " +
// // "Current: (" + utilization + "%) " +
// // "Threshold: (" + global.anterius_config.shared_network_warning_threshold + "%)"
// // );
// email_alert("WARNING: DHCP shared network utilization",
// "WARNING: DHCP shared network utilization (" + global.kea_stats['shared-networks'][i].location + ") <br><br>" +
// "Threshold: (" + global.anterius_config.shared_network_warning_threshold + "%) <br>" +
// "Current: (" + utilization + "%)"
// );
// }
// else if (
// utilization <= global.anterius_config.shared_network_warning_threshold &&
// alert_status_networks_warning[global.kea_stats['shared-networks'][i].location] == 1
// ) {
// alert_status_networks_warning[global.kea_stats['shared-networks'][i].location] = 0;
// // TODO: enable slack warning hook if required
// // slack_message(":white_check_mark: CLEAR: Warning DHCP shared network utilization (" + global.kea_stats['shared-networks'][i].location + ") " +
// // "Current: (" + utilization + "%) " +
// // "Threshold: (" + global.anterius_config.shared_network_warning_threshold + "%)"
// // );
// email_alert("CLEAR: DHCP shared network utilization warning",
// "CLEAR: DHCP shared network utilization (" + global.kea_stats['shared-networks'][i].location + ") <br><br>" +
// "Threshold: (" + global.anterius_config.shared_network_warning_threshold + "%) <br>" +
// "Current: (" + utilization + "%)"
// );
// }
// }
// /* Check Critical */
// if (global.anterius_config.shared_network_critical_threshold > 0) {
// if (
// utilization >= global.anterius_config.shared_network_critical_threshold &&
// alert_status_networks_critical[global.kea_stats['shared-networks'][i].location] == 0
// ) {
// alert_status_networks_critical[global.kea_stats['shared-networks'][i].location] = 1;
// // TODO: enable slack warning hook if required
// // slack_message(":fire: CRITICAL: DHCP shared network utilization (" + global.kea_stats['shared-networks'][i].location + ") " +
// // "Current: (" + utilization + "%) " +
// // "Threshold: (" + global.anterius_config.shared_network_critical_threshold + "%)"
// // );
// email_alert("CRITICAL: DHCP shared network utilization",
// "CRITICAL: DHCP shared network utilization (" + global.kea_stats['shared-networks'][i].location + ") <br><br>" +
// "Threshold: (" + global.anterius_config.shared_network_critical_threshold + "%) <br>" +
// "Current: (" + utilization + "%)"
// );
// }
// else if (
// utilization <= global.anterius_config.shared_network_critical_threshold &&
// alert_status_networks_critical[global.kea_stats['shared-networks'][i].location] == 1
// ) {
// alert_status_networks_critical[global.kea_stats['shared-networks'][i].location] = 0;
// // TODO: enable slack warning hook if required
// // slack_message(":white_check_mark: CLEAR: Critical DHCP shared network utilization (" + global.kea_stats['shared-networks'][i].location + ") " +
// // "Current: (" + utilization + "%) " +
// // "Threshold: (" + global.anterius_config.shared_network_critical_threshold + "%)"
// // );
// email_alert("CLEAR: DHCP shared network utilization",
// "CLEAR: DHCP shared network utilization (" + global.kea_stats['shared-networks'][i].location + ") <br><br>" +
// "Threshold: (" + global.anterius_config.shared_network_critical_threshold + "%) <br>" +
// "Current: (" + utilization + "%)"
// );
// }
// }
// }
// }
// }, (5 * 1000));
// // Shared ne
// }, 60 * 1000);
// // function round(num, places) {
// // var multiplier = Math.pow(10, places);
// // return Math.round(num * multiplier) / multiplier;
// // }
// /* Load Mailer */
// const nodemailer = require('nodemailer');
// let transporter = nodemailer.createTransport({
// sendmail: true,
// newline: 'unix',
// path: '/usr/sbin/sendmail'
// });
// function email_alert(alert_title, alert_message) {
// console.log("Anterius Server> Loading E-Mail template...");
// fs = require('fs');
// var email_body = fs.readFileSync('./public/templates/email_template.html', "utf8");
// console.log("Anterius Server> Loading E-Mail template... DONE...");
// /* E-Mail Template Load */
// console.log("Anterius Server> Sending E-Mail Alert...\n");
// if (typeof global.anterius_config.email_alert_to === "undefined" && typeof global.anterius_config.sms_alert_to === "undefined")
// return false;
// if (global.anterius_config.email_alert_to == "" && global.anterius_config.sms_alert_to != "") {
// console.log("Anterius Server> No email_to specified - returning...");
// return false;
// }
// /* Populate E-Mail Template */
// email_body = email_body.replace("[body_content_placeholder]", alert_message);
// email_body = email_body.replace("[alert_title]", alert_title);
// email_body = email_body.replace("[local_time]", new Date().toString());
// /* Clean extra commas etc. */
// global.anterius_config.email_alert_to = global.anterius_config.email_alert_to.replace(/^[,\s]+|[,\s]+$/g, '').replace(/,[,\s]*,/g, ',');
// /* Publish HTML E-Mail Alert (regular mail) */
// if (global.anterius_config.email_alert_to.trim() != "") {
// var mailOptions = {
// from: "Kea-Anterius Monitor Alerts [email protected]",
// to: global.anterius_config.email_alert_to,
// subject: "Kea-Anterius " + "(" + host_name + ") " + alert_title,
// html: email_body,
// };
// transporter.sendMail(mailOptions, function (error, info) {
// if (error) {
// console.log(error);
// }
// else {
// console.log('Message sent: ' + info.response);
// }
// });
// }
// /* Publish SMS Alert */
// if (global.anterius_config.sms_alert_to.trim() != "") {
// var mailOptions = {
// from: "Kea-Anterius Monitor Alerts [email protected]",
// to: global.anterius_config.sms_alert_to,
// subject: "Kea-Anterius " + "(" + host_name + ") " + alert_title,
// html: (alert_message.substring(0, 130) + "..."),
// };
// transporter.sendMail(mailOptions, function (error, info) {
// if (error) {
// console.log(error);
// }
// else {
// console.log('Message sent: ' + info.response);
// }
// });
// }
// }
console.log("Anterius Server> Bootup complete");