Fix indents app.js

This commit is contained in:
Akkadius 2017-10-05 13:05:06 -05:00
parent 765df5f74f
commit 0a2e180a13
1 changed files with 281 additions and 283 deletions

564
app.js
View File

@ -17,14 +17,14 @@ var glass_config = json_file.readFileSync('config/glass_config.json');
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev')); app.use(logger('dev'));
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser()); app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public')));
if(glass_config.ip_ranges_to_allow != "") { if (glass_config.ip_ranges_to_allow != "") {
var ip_filter = require('express-ipfilter').IpFilter; var ip_filter = require('express-ipfilter').IpFilter;
var ips = glass_config.ip_ranges_to_allow; var ips = glass_config.ip_ranges_to_allow;
app.use(ip_filter(ips, {mode: 'allow'})); app.use(ip_filter(ips, {mode: 'allow'}));
} }
/* Normal Web Routes */ /* Normal Web Routes */
@ -58,21 +58,21 @@ app.use('/api/get_mac_oui_list/', require('./api/get_mac_oui_list'));
app.set('view engine', 'html'); app.set('view engine', 'html');
// catch 404 and forward to error handler // catch 404 and forward to error handler
app.use(function(req, res, next) { app.use(function (req, res, next) {
var err = new Error('Not Found'); var err = new Error('Not Found');
err.status = 404; err.status = 404;
next(err); next(err);
}); });
// error handler // error handler
app.use(function(err, req, res, next) { app.use(function (err, req, res, next) {
// set locals, only providing error in development // set locals, only providing error in development
res.locals.message = err.message; res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {}; res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page // render the error page
res.status(err.status || 500); res.status(err.status || 500);
res.send(err.message); res.send(err.message);
}); });
module.exports = app; module.exports = app;
@ -112,14 +112,14 @@ if (fs.existsSync(oui_database_file)) {
return console.log(err); return console.log(err);
} }
else { else {
/* Iterate through file */ /* Iterate through file */
lines = data.split("\n"); lines = data.split("\n");
for (l = 0; l < lines.length; l++) { for (l = 0; l < lines.length; l++) {
/* Trim whitespaces at each ends of the line */ /* Trim whitespaces at each ends of the line */
lines[l] = lines[l].trim(); lines[l] = lines[l].trim();
var oui_line_data = lines[l].split(":::"); var oui_line_data = lines[l].split(":::");
if(typeof oui_line_data[1] !== "undefined") if (typeof oui_line_data[1] !== "undefined")
oui_data[oui_line_data[0].trim()] = oui_line_data[1].trim(); oui_data[oui_line_data[0].trim()] = oui_line_data[1].trim();
} }
console.log("[Glass Server] OUI Database Loaded"); console.log("[Glass Server] OUI Database Loaded");
@ -135,14 +135,14 @@ dhcp_lease_data = {};
lease_read_buffer = ""; lease_read_buffer = "";
fs = require('fs'); fs = require('fs');
fs.readFile(glass_config.leases_file, 'utf8', function (err,data) { fs.readFile(glass_config.leases_file, 'utf8', function (err, data) {
if (err) { if (err) {
return console.log(err); return console.log(err);
} }
else { else {
lease_parser.parse(data); lease_parser.parse(data);
console.log("[Glass Server] Leases file loaded"); console.log("[Glass Server] Leases file loaded");
} }
}); });
/** /**
@ -150,33 +150,33 @@ fs.readFile(glass_config.leases_file, 'utf8', function (err,data) {
*/ */
var tail_module = require('always-tail2'); var tail_module = require('always-tail2');
tail = new tail_module( tail = new tail_module(
glass_config.leases_file, glass_config.leases_file,
"\n", "\n",
options options
); );
tail.on("line", function(data) { tail.on("line", function (data) {
unix_time = Math.floor(new Date() / 1000); unix_time = Math.floor(new Date() / 1000);
/* Buffering lines until we get full lease data */ /* Buffering lines until we get full lease data */
lease_read_buffer = lease_read_buffer + data + "\n"; lease_read_buffer = lease_read_buffer + data + "\n";
/* End of lease - cut off and parse the buffer */ /* End of lease - cut off and parse the buffer */
if (/}/i.test(data)){ if (/}/i.test(data)) {
lease_parser.parse(lease_read_buffer); lease_parser.parse(lease_read_buffer);
lease_read_buffer = ""; lease_read_buffer = "";
} }
/* Count leases per second */ /* Count leases per second */
if(/lease/.test(data)) { if (/lease/.test(data)) {
leases_per_second++; leases_per_second++;
} }
if(current_time != unix_time) { if (current_time != unix_time) {
current_time = unix_time; current_time = unix_time;
current_leases_per_second = leases_per_second; current_leases_per_second = leases_per_second;
leases_last_update_time = unix_time; leases_last_update_time = unix_time;
leases_per_second = 0; leases_per_second = 0;
} }
}); });
/** /**
@ -189,14 +189,14 @@ var glass_config = json_file.readFileSync('config/glass_config.json');
var options = {}; var options = {};
options.interval = 1000; options.interval = 1000;
var dashboard_timer = setInterval(function(){ var dashboard_timer = setInterval(function () {
// console.log("Checking timers..."); // console.log("Checking timers...");
unix_time = Math.floor(new Date() / 1000); unix_time = Math.floor(new Date() / 1000);
if((unix_time - 5) > leases_last_update_time){ if ((unix_time - 5) > leases_last_update_time) {
current_leases_per_second = 0; current_leases_per_second = 0;
} }
// console.log(JSON.stringify(dhcp_lease_data, null, 2)); // console.log(JSON.stringify(dhcp_lease_data, null, 2));
}, 5000); }, 5000);
@ -206,30 +206,30 @@ var dashboard_timer = setInterval(function(){
var leases_per_minute_data = []; var leases_per_minute_data = [];
var leases_per_minute_counter = 0; var leases_per_minute_counter = 0;
leases_per_minute_counter_timer = setInterval(function(){ leases_per_minute_counter_timer = setInterval(function () {
// console.log("leases per minute counter %i", leases_per_minute_counter); // console.log("leases per minute counter %i", leases_per_minute_counter);
leases_per_minute_data[leases_per_minute_counter] = current_leases_per_second; leases_per_minute_data[leases_per_minute_counter] = current_leases_per_second;
leases_per_minute_counter++; leases_per_minute_counter++;
/* Count how many actual data sets we walked that have values */ /* Count how many actual data sets we walked that have values */
leases_per_minute = 0; leases_per_minute = 0;
for (i = 0; i < 59; i++){ for (i = 0; i < 59; i++) {
if(leases_per_minute_data[i] > 0) { if (leases_per_minute_data[i] > 0) {
leases_per_minute += leases_per_minute_data[i]; leases_per_minute += leases_per_minute_data[i];
// console.log("iteration " + i + " val: " + leases_per_minute_data[i] + " lpm: " + leases_per_minute); // console.log("iteration " + i + " val: " + leases_per_minute_data[i] + " lpm: " + leases_per_minute);
} }
else { else {
// console.log("no data " + i); // console.log("no data " + i);
} }
} }
if (leases_per_minute_counter == 60) if (leases_per_minute_counter == 60)
leases_per_minute_counter = 0; leases_per_minute_counter = 0;
/* Websockets statistics subscription broadcast */ /* Websockets statistics subscription broadcast */
if(ws_event_subscribers('dhcp_statistics')) { if (ws_event_subscribers('dhcp_statistics')) {
return_data = { return_data = {
"cpu_utilization": cpu_utilization, "cpu_utilization": cpu_utilization,
"leases_per_second": current_leases_per_second, "leases_per_second": current_leases_per_second,
@ -243,38 +243,38 @@ leases_per_minute_counter_timer = setInterval(function(){
/** /**
* Poll: CPU Utilization * Poll: CPU Utilization
*/ */
cpu_utilization_poll = setInterval(function(){ cpu_utilization_poll = setInterval(function () {
cpu_utilization = parseFloat(execSync("top -bn 1 | awk 'NR>7{s+=$9} END {print s/4}'").toString()) cpu_utilization = parseFloat(execSync("top -bn 1 | awk 'NR>7{s+=$9} END {print s/4}'").toString())
}, (15 * 1000)); }, (15 * 1000));
/** /**
* Clean Expired Leases * Clean Expired Leases
*/ */
lease_clean_timer = setInterval(function(){ lease_clean_timer = setInterval(function () {
lease_parser.clean(); lease_parser.clean();
}, (60 * 1000)); }, (60 * 1000));
function get_socket_clients_connected_count() { function get_socket_clients_connected_count() {
wss.clients.forEach(function each(client) { wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) { if (client.readyState === WebSocket.OPEN) {
socket_clients++; socket_clients++;
} }
}); });
return socket_clients; return socket_clients;
} }
/** /**
* Watch config changes so we reload it for core functions... * Watch config changes so we reload it for core functions...
*/ */
fs.watch('config/glass_config.json', function (event, filename) { fs.watch('config/glass_config.json', function (event, filename) {
if (filename) { if (filename) {
setTimeout(function(){ setTimeout(function () {
glass_config = json_file.readFileSync('config/glass_config.json'); glass_config = json_file.readFileSync('config/glass_config.json');
console.log("[Glass Server] Config Loaded"); console.log("[Glass Server] Config Loaded");
}, 1000); }, 1000);
} else { } else {
console.log('filename not provided'); console.log('filename not provided');
} }
}); });
/** /**
@ -282,23 +282,23 @@ fs.watch('config/glass_config.json', function (event, filename) {
*/ */
const WebSocket = require('ws'); const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 }); const wss = new WebSocket.Server({port: 8080});
options.interval = 300; options.interval = 300;
var tail_dhcp_log = new tail_module( var tail_dhcp_log = new tail_module(
glass_config.log_file, glass_config.log_file,
"\n", "\n",
options options
); );
dhcp_requests = {}; dhcp_requests = {};
tail_dhcp_log.on("line", function(data) { tail_dhcp_log.on("line", function (data) {
if (listening_to_log_file) { if (listening_to_log_file) {
wss.broadcast_event(data, 'dhcp_log_subscription'); wss.broadcast_event(data, 'dhcp_log_subscription');
} }
/* Collect Excessive DHCP Request Data */ /* Collect Excessive DHCP Request Data */
if (/DHCPREQUEST/i.test(data)) { if (/DHCPREQUEST/i.test(data)) {
var request_from = ""; var request_from = "";
@ -344,23 +344,25 @@ tail_dhcp_log.on("line", function(data) {
} }
}); });
const purge_request_data = setInterval(function() { const purge_request_data = setInterval(function () {
for (var key in dhcp_requests) { for (var key in dhcp_requests) {
if(dhcp_requests[key].request_count <= 10) if (dhcp_requests[key].request_count <= 10)
delete dhcp_requests[key]; delete dhcp_requests[key];
} }
}, 600 * 1000); /* 10 Minutes */ }, 600 * 1000);
/* 10 Minutes */
const purge_request_data_hour = setInterval(function() { const purge_request_data_hour = setInterval(function () {
dhcp_requests = {}; dhcp_requests = {};
}, 3600 * 1000); /* 60 Minutes */ }, 3600 * 1000);
/* 60 Minutes */
wss.on('connection', function connection(ws) { wss.on('connection', function connection(ws) {
socket_clients++; socket_clients++;
console.log("[WS] CLIENT_CONNECT: Socket clients (" + socket_clients + ")"); console.log("[WS] CLIENT_CONNECT: Socket clients (" + socket_clients + ")");
if (!listening_to_log_file) { if (!listening_to_log_file) {
/* Watch log file for new information */ /* Watch log file for new information */
var tail_module = require('always-tail2'); var tail_module = require('always-tail2');
listening_to_log_file = 1; listening_to_log_file = 1;
@ -369,32 +371,32 @@ wss.on('connection', function connection(ws) {
}); });
wss.on('close', function close() { wss.on('close', function close() {
socket_clients--; socket_clients--;
console.log("[WS] CLIENT_DISCONNECT: Socket clients (" + socket_clients + ")"); console.log("[WS] CLIENT_DISCONNECT: Socket clients (" + socket_clients + ")");
}); });
function heartbeat() { function heartbeat() {
this.isAlive = true; this.isAlive = true;
} }
function isJson(str) { function isJson(str) {
try { try {
JSON.parse(str); JSON.parse(str);
} catch (e) { } catch (e) {
return false; return false;
} }
return true; return true;
} }
function ws_event_subscribers(event){ function ws_event_subscribers(event) {
if(typeof wss === "undefined") if (typeof wss === "undefined")
return false; return false;
var is_listening = false; var is_listening = false;
wss.clients.forEach(function each(ws) { wss.clients.forEach(function each(ws) {
/* Count event listeners */ /* Count event listeners */
for (var event_listening in ws.event_subscription) { for (var event_listening in ws.event_subscription) {
if (event_listening == event) { if (event_listening == event) {
is_listening = true; is_listening = true;
@ -408,69 +410,69 @@ function ws_event_subscribers(event){
return true; return true;
} }
return false; return false;
} }
wss.on('connection', function connection(ws) { wss.on('connection', function connection(ws) {
ws.isAlive = true; ws.isAlive = true;
ws.on('pong', heartbeat); ws.on('pong', heartbeat);
ws.event_subscription = []; ws.event_subscription = [];
ws.on('message', function incoming(data) { ws.on('message', function incoming(data) {
if(data != "" && isJson(data)) { if (data != "" && isJson(data)) {
var json = JSON.parse(data); var json = JSON.parse(data);
if(typeof json["event_subscription"] !== "undefined"){ if (typeof json["event_subscription"] !== "undefined") {
console.log("[WS] Incoming Subscription '%s'", json['event_subscription']); console.log("[WS] Incoming Subscription '%s'", json['event_subscription']);
ws.event_subscription[json["event_subscription"]] = 1; ws.event_subscription[json["event_subscription"]] = 1;
} }
if(typeof json["event_unsubscribe"] !== "undefined"){ if (typeof json["event_unsubscribe"] !== "undefined") {
console.log("[WS] event_unsubscribe '%s'", json['event_unsubscribe']); console.log("[WS] event_unsubscribe '%s'", json['event_unsubscribe']);
delete ws.event_subscription[json["event_unsubscribe"]]; delete ws.event_subscription[json["event_unsubscribe"]];
} }
if(typeof json["all_events"] !== "undefined"){ if (typeof json["all_events"] !== "undefined") {
console.log("[WS] event_unsubscribe '%s'", json['event_unsubscribe']); console.log("[WS] event_unsubscribe '%s'", json['event_unsubscribe']);
ws.event_subscription = []; ws.event_subscription = [];
} }
} }
}); });
stale_connections_audit(); stale_connections_audit();
}); });
wss.broadcast = function broadcast(data) { wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) { wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) { if (client.readyState === WebSocket.OPEN) {
client.send(data); client.send(data);
} }
}); });
}; };
wss.broadcast_event = function broadcast(data, event) { wss.broadcast_event = function broadcast(data, event) {
wss.clients.forEach(function each(client) { wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) { if (client.readyState === WebSocket.OPEN) {
if(client.event_subscription[event]) if (client.event_subscription[event])
client.send(JSON.stringify({"event": event, "data": data})); client.send(JSON.stringify({"event": event, "data": data}));
} }
}); });
}; };
function stale_connections_audit() { function stale_connections_audit() {
socket_clients = 0; socket_clients = 0;
wss.clients.forEach(function each(ws) { wss.clients.forEach(function each(ws) {
if (ws.isAlive === false) return ws.terminate(); if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false; ws.isAlive = false;
ws.ping('', false, true); ws.ping('', false, true);
socket_clients++; socket_clients++;
}); });
console.log("[WS] STATUS: Socket clients (" + socket_clients + ")"); console.log("[WS] STATUS: Socket clients (" + socket_clients + ")");
} }
/* Keepalive - kill stale connections (30s poll) */ /* Keepalive - kill stale connections (30s poll) */
const interval = setInterval(function ping() { const interval = setInterval(function ping() {
stale_connections_audit(); stale_connections_audit();
}, 30000); }, 30000);
var socket_clients = 0; var socket_clients = 0;
@ -488,16 +490,16 @@ slack = new Slack();
slack.setWebhook(webhookUri); slack.setWebhook(webhookUri);
function slack_message(message) { function slack_message(message) {
console.log("[Slack] %s", message); console.log("[Slack] %s", message);
slack.webhook({ slack.webhook({
channel: glass_config.slack_alert_channel, channel: glass_config.slack_alert_channel,
username: "Glass", username: "Glass",
icon_emoji: "https://imgur.com/wD3CcBi", icon_emoji: "https://imgur.com/wD3CcBi",
text: message text: message
}, function (err, response) { }, function (err, response) {
console.log(response); console.log(response);
}); });
} }
/** /**
@ -506,92 +508,91 @@ function slack_message(message) {
alert_status = []; alert_status = [];
alert_status['leases_per_minute'] = 0; alert_status['leases_per_minute'] = 0;
setTimeout(function(){ setTimeout(function () {
console.log("[Glass Server] Alert loop started"); console.log("[Glass Server] Alert loop started");
alert_check_timer = setInterval(function(){ alert_check_timer = setInterval(function () {
// console.log("[Timer] Alert Timer check"); // console.log("[Timer] Alert Timer check");
if(glass_config.leases_per_minute_threshold > 0) { if (glass_config.leases_per_minute_threshold > 0) {
// console.log("[Timer] lpm: %s lpm_th: %s", leases_per_minute, glass_config.leases_per_minute_threshold); // console.log("[Timer] lpm: %s lpm_th: %s", leases_per_minute, glass_config.leases_per_minute_threshold);
if (leases_per_minute <= glass_config.leases_per_minute_threshold && alert_status['leases_per_minute'] == 0) { if (leases_per_minute <= glass_config.leases_per_minute_threshold && alert_status['leases_per_minute'] == 0) {
alert_status['leases_per_minute'] = 1; alert_status['leases_per_minute'] = 1;
slack_message(":warning: CRITICAL: DHCP leases per minute have dropped below threshold " + slack_message(":warning: CRITICAL: DHCP leases per minute have dropped below threshold " +
"(" + parseInt(glass_config.leases_per_minute_threshold).toLocaleString('en') + ") " + "(" + parseInt(glass_config.leases_per_minute_threshold).toLocaleString('en') + ") " +
"Current (" + parseInt(leases_per_minute).toLocaleString('en') + ")"); "Current (" + parseInt(leases_per_minute).toLocaleString('en') + ")");
email_alert("CRITICAL: Leases Per Minute Threshold", "DHCP leases per minute dropped below critical threshold <br><br>" + email_alert("CRITICAL: Leases Per Minute Threshold", "DHCP leases per minute dropped below critical threshold <br><br>" +
"Threshold: (" + parseInt(glass_config.leases_per_minute_threshold).toLocaleString('en') + ") <br>" + "Threshold: (" + parseInt(glass_config.leases_per_minute_threshold).toLocaleString('en') + ") <br>" +
"Current: (" + parseInt(leases_per_minute).toLocaleString('en') + ") <br><br>" + "Current: (" + parseInt(leases_per_minute).toLocaleString('en') + ") <br><br>" +
"This is usually indicative of a process or hardware problem and needs to be addressed immediately"); "This is usually indicative of a process or hardware problem and needs to be addressed immediately");
} }
else if (leases_per_minute >= glass_config.leases_per_minute_threshold && alert_status['leases_per_minute'] == 1) { else if (leases_per_minute >= glass_config.leases_per_minute_threshold && alert_status['leases_per_minute'] == 1) {
alert_status['leases_per_minute'] = 0; alert_status['leases_per_minute'] = 0;
slack_message(":white_check_mark: CLEAR: DHCP leases per minute have returned to above threshold " + slack_message(":white_check_mark: CLEAR: DHCP leases per minute have returned to above threshold " +
"(" + parseInt(glass_config.leases_per_minute_threshold).toLocaleString('en') + ") " + "(" + parseInt(glass_config.leases_per_minute_threshold).toLocaleString('en') + ") " +
"Current (" + parseInt(leases_per_minute).toLocaleString('en') + ")"); "Current (" + parseInt(leases_per_minute).toLocaleString('en') + ")");
email_alert("CLEAR: Leases Per Minute Threshold", "DHCP leases per minute have returned to normal <br><br>" + email_alert("CLEAR: Leases Per Minute Threshold", "DHCP leases per minute have returned to normal <br><br>" +
"Threshold: (" + parseInt(glass_config.leases_per_minute_threshold).toLocaleString('en') + ") <br>" + "Threshold: (" + parseInt(glass_config.leases_per_minute_threshold).toLocaleString('en') + ") <br>" +
"Current: (" + parseInt(leases_per_minute).toLocaleString('en') + ")" "Current: (" + parseInt(leases_per_minute).toLocaleString('en') + ")"
); );
} }
} }
}, (5 * 1000)); }, (5 * 1000));
alert_status_networks_warning = []; alert_status_networks_warning = [];
alert_status_networks_critical = []; alert_status_networks_critical = [];
alert_subnet_check_timer = setInterval(function(){ alert_subnet_check_timer = setInterval(function () {
// console.log("[Timer] Alert Timer check - subnets"); // console.log("[Timer] Alert Timer check - subnets");
if(glass_config.shared_network_warning_threshold > 0 || glass_config.shared_network_critical_threshold > 0) { if (glass_config.shared_network_warning_threshold > 0 || glass_config.shared_network_critical_threshold > 0) {
const execSync = require('child_process').execSync; const execSync = require('child_process').execSync;
output = execSync('./bin/dhcpd-pools -c ' + glass_config.config_file + ' -l ' + glass_config.leases_file + ' -f j -A -s e'); output = execSync('./bin/dhcpd-pools -c ' + glass_config.config_file + ' -l ' + glass_config.leases_file + ' -f j -A -s e');
var dhcp_data = JSON.parse(output); var dhcp_data = JSON.parse(output);
/* /*
* Iterate through Shared Networks * Iterate through Shared Networks
*/ */
for ( var i = 0; i < dhcp_data['shared-networks'].length; i++) { for (var i = 0; i < dhcp_data['shared-networks'].length; i++) {
utilization = round(parseFloat(dhcp_data['shared-networks'][i].used / dhcp_data['shared-networks'][i].defined) * 100, 2); utilization = round(parseFloat(dhcp_data['shared-networks'][i].used / dhcp_data['shared-networks'][i].defined) * 100, 2);
if(isNaN(utilization)) if (isNaN(utilization))
utilization = 0; utilization = 0;
/* Initialize these array buckets */ /* Initialize these array buckets */
if(typeof alert_status_networks_warning[dhcp_data['shared-networks'][i].location] === "undefined") if (typeof alert_status_networks_warning[dhcp_data['shared-networks'][i].location] === "undefined")
alert_status_networks_warning[dhcp_data['shared-networks'][i].location] = 0; alert_status_networks_warning[dhcp_data['shared-networks'][i].location] = 0;
if(typeof alert_status_networks_critical[dhcp_data['shared-networks'][i].location] === "undefined") if (typeof alert_status_networks_critical[dhcp_data['shared-networks'][i].location] === "undefined")
alert_status_networks_critical[dhcp_data['shared-networks'][i].location] = 0; alert_status_networks_critical[dhcp_data['shared-networks'][i].location] = 0;
/* /*
console.log("Location: %s", dhcp_data['shared-networks'][i].location); console.log("Location: %s", dhcp_data['shared-networks'][i].location);
console.log("Used: %s", dhcp_data['shared-networks'][i].used.toLocaleString('en')); 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("Defined: %s", dhcp_data['shared-networks'][i].defined.toLocaleString('en'));
console.log("Free: %s", dhcp_data['shared-networks'][i].free.toLocaleString('en')); console.log("Free: %s", dhcp_data['shared-networks'][i].free.toLocaleString('en'));
console.log("Utilization: %s", utilization); console.log("Utilization: %s", utilization);
console.log(" \n"); console.log(" \n");
*/ */
/* Check Warnings */ /* Check Warnings */
if(glass_config.shared_network_warning_threshold > 0) { if (glass_config.shared_network_warning_threshold > 0) {
if ( if (
utilization >= glass_config.shared_network_warning_threshold && utilization >= glass_config.shared_network_warning_threshold &&
utilization <= glass_config.shared_network_critical_threshold && utilization <= glass_config.shared_network_critical_threshold &&
alert_status_networks_warning[dhcp_data['shared-networks'][i].location] == 0 alert_status_networks_warning[dhcp_data['shared-networks'][i].location] == 0
) ) {
{ alert_status_networks_warning[dhcp_data['shared-networks'][i].location] = 1;
alert_status_networks_warning[dhcp_data['shared-networks'][i].location] = 1;
slack_message(":warning: WARNING: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") " + slack_message(":warning: WARNING: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") " +
"Current: (" + utilization + "%) " + "Current: (" + utilization + "%) " +
"Threshold: (" + glass_config.shared_network_warning_threshold + "%)" "Threshold: (" + glass_config.shared_network_warning_threshold + "%)"
); );
email_alert("WARNING: DHCP shared network utilization", email_alert("WARNING: DHCP shared network utilization",
"WARNING: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") <br><br>" + "WARNING: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") <br><br>" +
@ -599,18 +600,17 @@ setTimeout(function(){
"Current: (" + utilization + "%)" "Current: (" + utilization + "%)"
); );
} }
else if ( else if (
utilization <= glass_config.shared_network_warning_threshold && utilization <= glass_config.shared_network_warning_threshold &&
alert_status_networks_warning[dhcp_data['shared-networks'][i].location] == 1 alert_status_networks_warning[dhcp_data['shared-networks'][i].location] == 1
) ) {
{ alert_status_networks_warning[dhcp_data['shared-networks'][i].location] = 0;
alert_status_networks_warning[dhcp_data['shared-networks'][i].location] = 0;
slack_message(":white_check_mark: CLEAR: Warning DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") " + slack_message(":white_check_mark: CLEAR: Warning DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") " +
"Current: (" + utilization + "%) " + "Current: (" + utilization + "%) " +
"Threshold: (" + glass_config.shared_network_warning_threshold + "%)" "Threshold: (" + glass_config.shared_network_warning_threshold + "%)"
); );
email_alert("CLEAR: DHCP shared network utilization warning", email_alert("CLEAR: DHCP shared network utilization warning",
"CLEAR: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") <br><br>" + "CLEAR: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") <br><br>" +
@ -618,21 +618,20 @@ setTimeout(function(){
"Current: (" + utilization + "%)" "Current: (" + utilization + "%)"
); );
} }
} }
/* Check Critical */ /* Check Critical */
if(glass_config.shared_network_critical_threshold > 0) { if (glass_config.shared_network_critical_threshold > 0) {
if ( if (
utilization >= glass_config.shared_network_critical_threshold && utilization >= glass_config.shared_network_critical_threshold &&
alert_status_networks_critical[dhcp_data['shared-networks'][i].location] == 0 alert_status_networks_critical[dhcp_data['shared-networks'][i].location] == 0
) ) {
{ alert_status_networks_critical[dhcp_data['shared-networks'][i].location] = 1;
alert_status_networks_critical[dhcp_data['shared-networks'][i].location] = 1; slack_message(":fire: CRITICAL: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") " +
slack_message(":fire: CRITICAL: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") " + "Current: (" + utilization + "%) " +
"Current: (" + utilization + "%) " + "Threshold: (" + glass_config.shared_network_critical_threshold + "%)"
"Threshold: (" + glass_config.shared_network_critical_threshold + "%)" );
);
email_alert("CRITICAL: DHCP shared network utilization", email_alert("CRITICAL: DHCP shared network utilization",
"CRITICAL: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") <br><br>" + "CRITICAL: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") <br><br>" +
@ -640,33 +639,32 @@ setTimeout(function(){
"Current: (" + utilization + "%)" "Current: (" + utilization + "%)"
); );
} }
else if ( else if (
utilization <= glass_config.shared_network_critical_threshold && utilization <= glass_config.shared_network_critical_threshold &&
alert_status_networks_critical[dhcp_data['shared-networks'][i].location] == 1 alert_status_networks_critical[dhcp_data['shared-networks'][i].location] == 1
) ) {
{ alert_status_networks_critical[dhcp_data['shared-networks'][i].location] = 0;
alert_status_networks_critical[dhcp_data['shared-networks'][i].location] = 0; slack_message(":white_check_mark: CLEAR: Critical DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") " +
slack_message(":white_check_mark: CLEAR: Critical DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") " + "Current: (" + utilization + "%) " +
"Current: (" + utilization + "%) " + "Threshold: (" + glass_config.shared_network_critical_threshold + "%)"
"Threshold: (" + glass_config.shared_network_critical_threshold + "%)" );
);
email_alert("CLEAR: DHCP shared network utilization", email_alert("CLEAR: DHCP shared network utilization",
"CLEAR: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") <br><br>" + "CLEAR: DHCP shared network utilization (" + dhcp_data['shared-networks'][i].location + ") <br><br>" +
"Threshold: (" + glass_config.shared_network_critical_threshold + "%) <br>" + "Threshold: (" + glass_config.shared_network_critical_threshold + "%) <br>" +
"Current: (" + utilization + "%)" "Current: (" + utilization + "%)"
); );
} }
} }
} }
} }
}, (5 * 1000)); }, (5 * 1000));
}, 60 * 1000); }, 60 * 1000);
function round(num, places) { function round(num, places) {
var multiplier = Math.pow(10, places); var multiplier = Math.pow(10, places);
return Math.round(num * multiplier) / multiplier; return Math.round(num * multiplier) / multiplier;
} }
/* Load Mailer */ /* Load Mailer */
@ -689,24 +687,24 @@ function email_alert(alert_title, alert_message) {
/* E-Mail Template Load */ /* E-Mail Template Load */
console.log("[Glass Server] Sending E-Mail Alert...\n"); console.log("[Glass Server] Sending E-Mail Alert...\n");
if(typeof glass_config.email_alert_to === "undefined" && typeof glass_config.sms_alert_to === "undefined") if (typeof glass_config.email_alert_to === "undefined" && typeof glass_config.sms_alert_to === "undefined")
return false; return false;
if (glass_config.email_alert_to == "" && glass_config.sms_alert_to != ""){ if (glass_config.email_alert_to == "" && glass_config.sms_alert_to != "") {
console.log("[Glass Server] No email_to specified - returning..."); console.log("[Glass Server] No email_to specified - returning...");
return false; return false;
} }
/* Write on top of E-Mail Template */ /* Write on top of E-Mail Template */
email_body = email_body.replace("[body_content_placeholder]", alert_message); email_body = email_body.replace("[body_content_placeholder]", alert_message);
email_body = email_body.replace("[alert_title]", alert_title); email_body = email_body.replace("[alert_title]", alert_title);
email_body = email_body.replace("[local_time]", new Date().toString() ); email_body = email_body.replace("[local_time]", new Date().toString());
/* Clean extra commas etc. */ /* Clean extra commas etc. */
glass_config.email_alert_to = glass_config.email_alert_to.replace(/^[,\s]+|[,\s]+$/g, '').replace(/,[,\s]*,/g, ','); glass_config.email_alert_to = glass_config.email_alert_to.replace(/^[,\s]+|[,\s]+$/g, '').replace(/,[,\s]*,/g, ',');
/* Send regular HTML E-Mails */ /* Send regular HTML E-Mails */
if(glass_config.email_alert_to.trim() != "") { if (glass_config.email_alert_to.trim() != "") {
var mailOptions = { var mailOptions = {
from: "Glass Alerting Monitor glass@noreply.com", from: "Glass Alerting Monitor glass@noreply.com",
to: glass_config.email_alert_to, to: glass_config.email_alert_to,
@ -724,7 +722,7 @@ function email_alert(alert_title, alert_message) {
} }
/* Send SMS */ /* Send SMS */
if(glass_config.sms_alert_to.trim() != "") { if (glass_config.sms_alert_to.trim() != "") {
var mailOptions = { var mailOptions = {
from: "Glass Alerting Monitor glass@noreply.com", from: "Glass Alerting Monitor glass@noreply.com",
to: glass_config.sms_alert_to, to: glass_config.sms_alert_to,