Fix race condition, add graph toggles

This commit is contained in:
Cryptkeeper 2015-12-18 18:10:58 -06:00
parent c87a377621
commit 649d8abd33
5 changed files with 147 additions and 107 deletions

40
app.js

@ -122,22 +122,8 @@ function startMainLoop() {
}, config.rates.upateMojangStatus); }, config.rates.upateMojangStatus);
} }
if (config.logToDatabase) { function startServices() {
// Setup our database. server.start(function() {
db.setup();
var timestamp = util.getCurrentTimeMs();
db.queryPings(24 * 60 * 60 * 1000, function(data) {
graphData = util.convertPingsToGraph(data);
logger.log('info', 'Queried and parsed ping history in %sms', util.getCurrentTimeMs() - timestamp);
});
} else {
logger.warn('Database logging is not enabled. You can enable it by setting "logToDatabase" to true in config.json. This requires sqlite3 to be installed.');
}
server.start(function() {
// Track how many people are currently connected. // Track how many people are currently connected.
server.io.on('connect', function(client) { server.io.on('connect', function(client) {
// If we haven't sent out at least one round of pings, disconnect them for now. // If we haven't sent out at least one round of pings, disconnect them for now.
@ -179,4 +165,24 @@ server.start(function() {
}); });
startMainLoop(); startMainLoop();
}); });
}
if (config.logToDatabase) {
// Setup our database.
db.setup();
var timestamp = util.getCurrentTimeMs();
db.queryPings(24 * 60 * 60 * 1000, function(data) {
graphData = util.convertPingsToGraph(data);
logger.log('info', 'Queried and parsed ping history in %sms', util.getCurrentTimeMs() - timestamp);
startServices();
});
} else {
logger.warn('Database logging is not enabled. You can enable it by setting "logToDatabase" to true in config.json. This requires sqlite3 to be installed.');
startServices();
}

@ -179,9 +179,11 @@ h3 {
} }
/* The big graph */ /* The big graph */
#big-graph, #big-graph-controls {
width: 1000px;
margin: 15px auto 0 auto;
}
#big-graph { #big-graph {
height: 500px; height: 500px;
width: 800px;
margin: 15px auto 0 auto;
padding-left: 500px;
} }

@ -35,6 +35,7 @@
</div> </div>
<div id="big-graph"></div> <div id="big-graph"></div>
<div id="big-graph-controls"></div>
<div id="server-container" class="container"></div> <div id="server-container" class="container"></div>

@ -42,7 +42,7 @@ var bigChartOptions = {
}, },
yaxis: { yaxis: {
show: true, show: true,
tickSize: 1000, tickSize: 2000,
tickLength: 10, tickLength: 10,
tickFormatter: function(value) { tickFormatter: function(value) {
return formatNumber(value); return formatNumber(value);
@ -64,7 +64,6 @@ var bigChartOptions = {
var lastMojangServiceUpdate; var lastMojangServiceUpdate;
var graphs = {}; var graphs = {};
var lastLatencyEntries = {};
var lastPlayerEntries = {}; var lastPlayerEntries = {};
// Generate (and set) the HTML that displays Mojang status. // Generate (and set) the HTML that displays Mojang status.
@ -140,20 +139,7 @@ function updateServerStatus(lastEntry) {
newStatus += playerDifference + ')</span>'; newStatus += playerDifference + ')</span>';
} }
/*if (lastLatencyEntries[info.name]) {
newStatus += '<br />';
var latencyDifference = lastLatencyEntries[info.name] - result.latency;
if (latencyDifference >= 0) {
newStatus += '+';
}
newStatus += latencyDifference + 'ms';
}*/
lastPlayerEntries[info.name] = result.players.online; lastPlayerEntries[info.name] = result.players.online;
lastLatencyEntries[info.name] = result.latency;
div.html(newStatus); div.html(newStatus);
} else { } else {
@ -196,42 +182,6 @@ function sortServers() {
} }
} }
function safeName(name) {
return name.replace(/ /g, '');
}
function handlePlotHover(event, pos, item) {
if (item) {
var text = getTimestamp(item.datapoint[0] / 1000) + '\
<br />\
' + formatNumber(item.datapoint[1]) + ' Players';
if (item.series && item.series.label) {
text = item.series.label + '<br />' + text;
}
renderTooltip(item.pageX + 5, item.pageY + 5, text);
} else {
hideTooltip();
}
}
function convertGraphData(rawData) {
var data = [];
var keys = Object.keys(rawData);
for (var i = 0; i < keys.length; i++) {
data.push({
data: rawData[keys[i]],
yaxis: 1,
label: keys[i]
});
}
return data;
}
$(document).ready(function() { $(document).ready(function() {
var socket = io.connect({ var socket = io.connect({
reconnect: true, reconnect: true,
@ -243,7 +193,8 @@ $(document).ready(function() {
var sortServersTask; var sortServersTask;
var historyPlot; var historyPlot;
var historyData; var displayedGraphData;
var hiddenGraphData = [];
socket.on('connect', function() { socket.on('connect', function() {
$('#tagline-text').text('Loading...'); $('#tagline-text').text('Loading...');
@ -262,7 +213,6 @@ $(document).ready(function() {
$('#tagline-text').text('Disconnected! Refresh?'); $('#tagline-text').text('Disconnected! Refresh?');
lastPlayerEntries = {}; lastPlayerEntries = {};
lastLatencyEntries = {};
graphs = {}; graphs = {};
$('#server-container').html(''); $('#server-container').html('');
@ -271,21 +221,34 @@ $(document).ready(function() {
}); });
socket.on('historyGraph', function(rawData) { socket.on('historyGraph', function(rawData) {
historyData = rawData; displayedGraphData = rawData;
historyPlot = $.plot('#big-graph', convertGraphData(rawData), bigChartOptions); historyPlot = $.plot('#big-graph', convertGraphData(rawData), bigChartOptions);
$('#big-graph').bind('plothover', handlePlotHover); $('#big-graph').bind('plothover', handlePlotHover);
var keys = Object.keys(rawData);
for (var i = 0; i < keys.length; i++) {
$('#big-graph-controls').append('<input type="checkbox" class="graph-control" id="graph-controls" data-target-network="' + keys[i] + '" checked=checked> ' + keys[i] + '</input> ');
}
}); });
socket.on('updateHistoryGraph', function(rawData) { socket.on('updateHistoryGraph', function(rawData) {
if (historyData[rawData.ip].length > 24 * 60) { var targetGraphData = displayedGraphData[rawData.ip];
historyData[rawData.ip].shift();
// If it's not in our display group, push it to the hidden group instead so it can be restored and still be up to date.
if (!targetGraphData) {
targetGraphData = hiddenGraphData[rawData.ip];
} }
historyData[rawData.ip].push([rawData.timestamp, rawData.players]); if (targetGraphData.length > 24 * 60) {
targetGraphData.shift();
}
historyPlot.setData(convertGraphData(historyData)); targetGraphData.push([rawData.timestamp, rawData.players]);
historyPlot.setData(convertGraphData(displayedGraphData));
historyPlot.setupGrid(); historyPlot.setupGrid();
historyPlot.draw(); historyPlot.draw();
@ -311,10 +274,8 @@ $(document).ready(function() {
if (lastEntry.error) { if (lastEntry.error) {
lastPlayerEntries[info.name] = 0; lastPlayerEntries[info.name] = 0;
lastLatencyEntries[info.name] = 0;
} else if (lastEntry.result) { } else if (lastEntry.result) {
lastPlayerEntries[info.name] = lastEntry.result.players.online; lastPlayerEntries[info.name] = lastEntry.result.players.online;
lastLatencyEntries[info.name] = lastEntry.result.latency;
} }
$('<div/>', { $('<div/>', {
@ -414,4 +375,25 @@ $(document).ready(function() {
scrollTop: target.offset().top scrollTop: target.offset().top
}, 100); }, 100);
}); });
$(document).on('click', '.graph-control', function(e) {
var serverIp = $(this).attr('data-target-network');
var checked = $(this).attr('checked');
// Restore it, or delete it - either works.
if (!this.checked) {
hiddenGraphData[serverIp] = displayedGraphData[serverIp];
delete displayedGraphData[serverIp];
} else {
displayedGraphData[serverIp] = hiddenGraphData[serverIp];
delete hiddenGraphData[serverIp];
}
historyPlot.setData(convertGraphData(displayedGraphData));
historyPlot.setupGrid();
historyPlot.draw();
});
}); });

@ -10,6 +10,10 @@ function getTimestamp(ms, timeOnly) {
return date.toLocaleTimeString(); return date.toLocaleTimeString();
} }
function safeName(name) {
return name.replace(/ /g, '');
}
function renderTooltip(x, y, html) { function renderTooltip(x, y, html) {
tooltip.html(html).css({ tooltip.html(html).css({
top: y, top: y,
@ -25,6 +29,51 @@ function formatNumber(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
} }
function handlePlotHover(event, pos, item) {
if (item) {
var text = getTimestamp(item.datapoint[0] / 1000) + '\
<br />\
' + formatNumber(item.datapoint[1]) + ' Players';
if (item.series && item.series.label) {
text = item.series.label + '<br />' + text;
}
renderTooltip(item.pageX + 5, item.pageY + 5, text);
} else {
hideTooltip();
}
}
function convertGraphData(rawData) {
var data = [];
var keys = Object.keys(rawData);
for (var i = 0; i < keys.length; i++) {
data.push({
data: rawData[keys[i]],
yaxis: 1,
label: keys[i],
color: stringToColor(keys[i])
});
}
return data;
}
function stringToColor(base) {
var hash;
for (var i = 0, hash = 0; i < base.length; i++) {
hash = base.charCodeAt(i) + ((hash << 5) - hash);
}
color = Math.floor(Math.abs((Math.sin(hash) * 10000) % 1 * 16777216)).toString(16);
return '#' + Array(6 - color.length + 1).join('0') + color;
}
function msToTime(timer) { function msToTime(timer) {
var milliseconds = timer % 1000; var milliseconds = timer % 1000;
timer = (timer - milliseconds) / 1000; timer = (timer - milliseconds) / 1000;