Commit 4da39cab authored by Ad Schellevis's avatar Ad Schellevis

(dashboard, widgets) refactor traffic_graphs.widget.php

parent 7c3dadb0
<?php
/*
Copyright (C) 2016 Deciso B.V.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
function traffic_api()
{
global $config;
$result = array();
$result['interfaces'] = legacy_interface_stats();
$temp = gettimeofday();
$result['time'] = (double)$temp["sec"] + (double)$temp["usec"] / 1000000.0;
// collect user friendly interface names
foreach ($config['interfaces'] as $interfaceKey => $interfaceData) {
if (array_key_exists($interfaceData['if'], $result['interfaces'])) {
$result['interfaces'][$interfaceData['if']]['name'] = !empty($interfaceData['descr']) ? $interfaceData['descr'] : $interfaceKey;
}
}
if (!empty($result['interfaces']['enc0'])) {
$result['interfaces']['enc0']['name'] = "IPsec";
}
return $result;
}
function trafficshowDiv(incDiv,swapButtons){
//appear element
selectedDiv = incDiv + "graphdiv";
jQuery('#' + selectedDiv).show();
d = document;
if (swapButtons){
selectIntLink = selectedDiv + "-min";
textlink = d.getElementById(selectIntLink);
textlink.style.display = "inline";
selectIntLink = selectedDiv + "-open";
textlink = d.getElementById(selectIntLink);
textlink.style.display = "none";
}
document.iform["shown[" + incDiv + "]"].value = "show";
}
function trafficminimizeDiv(incDiv,swapButtons){
//fade element
selectedDiv = incDiv + "graphdiv";
jQuery('#' + selectedDiv).hide();
d = document;
if (swapButtons){
selectIntLink = selectedDiv + "-open";
textlink = d.getElementById(selectIntLink);
textlink.style.display = "inline";
selectIntLink = selectedDiv + "-min";
textlink = d.getElementById(selectIntLink);
textlink.style.display = "none";
}
document.iform["shown[" + incDiv + "]"].value = "hide";
}
...@@ -29,172 +29,152 @@ ...@@ -29,172 +29,152 @@
POSSIBILITY OF SUCH DAMAGE. POSSIBILITY OF SUCH DAMAGE.
*/ */
require_once("guiconfig.inc"); ?>
require_once("pfsense-utils.inc");
require_once("interfaces.inc");
if (!is_array($config["widgets"]["trafficgraphs"])) {
$config["widgets"]["trafficgraphs"] = array();
}
$a_config = &$config["widgets"]["trafficgraphs"];
if (!is_array($a_config["shown"])) {
$a_config["shown"] = array();
}
if (!is_array($a_config["shown"]["item"])) {
$a_config["shown"]["item"] = array();
}
$ifdescrs = get_configured_interface_with_descr();
if (isset($config['ipsec']['enable'])) {
$ifdescrs['enc0'] = "IPsec";
}
if ($_POST) {
if (isset($_POST["refreshinterval"])) {
$a_config["refreshinterval"] = $_POST["refreshinterval"];
}
if (isset($_POST["scale_type"])) {
$a_config["scale_type"] = $_POST["scale_type"];
}
$a_config["shown"]["item"] = array();
foreach ($ifdescrs as $ifname => $ifdescr) {
$state = $_POST["shown"][$ifname];
if ($state === "show") {
$a_config["shown"]["item"][] = $ifname;
}
}
write_config("Updated traffic graph settings via dashboard.");
header("Location: /");
exit(0);
}
$shown = array();
foreach ($a_config["shown"]["item"] as $if) {
$shown[$if] = true;
}
if (count($config["widgets"]["trafficgraphs"])) {
$keys = array_keys($ifdescrs);
$shown[$keys[0]] = true;
}
if (isset($a_config["refreshinterval"])) { <script type="text/javascript">
$refreshinterval = $a_config["refreshinterval"]; var traffic_graph_widget_data = [];
} else { var traffic_graph_widget_chart_in = null;
$refreshinterval = 10; var traffic_graph_widget_chart_data_in = null;
} var traffic_graph_widget_chart_out = null;
var traffic_graph_widget_chart_data_out = null;
function traffic_widget_update(sender, data)
{
// push new measurement, keep a maximum of 100 measures in
traffic_graph_widget_data.push(data);
if (traffic_graph_widget_data.length > 100) {
traffic_graph_widget_data.shift();
} else if (traffic_graph_widget_data.length == 1) {
traffic_graph_widget_data.push(data);
}
chart_data_in = [];
chart_data_out = [];
chart_data_keys = {};
for (var i=traffic_graph_widget_data.length-1 ; i > 0 ; --i) {
var elapsed_time = traffic_graph_widget_data[i]['time'] - traffic_graph_widget_data[i-1]['time'];
for (var key in traffic_graph_widget_data[i]['interfaces']) {
var intf_item = traffic_graph_widget_data[i]['interfaces'][key];
var prev_intf_item = traffic_graph_widget_data[i-1]['interfaces'][key];
if (chart_data_keys[key] == undefined && intf_item['name'] != undefined) {
// only show configured interfaces
chart_data_keys[key] = chart_data_in.length;
chart_data_in[chart_data_in.length] = {'key': intf_item['name'], 'values': []};
chart_data_out[chart_data_out.length] = {'key': intf_item['name'], 'values': []};
}
if (chart_data_keys[key] != undefined) {
if (elapsed_time > 0) {
bps_in = ((parseInt(intf_item['bytes received']) - parseInt(prev_intf_item['bytes received']))/elapsed_time)*8;
bps_out = ((parseInt(intf_item['bytes transmitted']) - parseInt(prev_intf_item['bytes transmitted']))/elapsed_time)*8;
} else {
bps_in = 0;
bps_out = 0;
}
chart_data_in[chart_data_keys[key]]['values'].push([traffic_graph_widget_data[i]['time']*1000, bps_in])
chart_data_out[chart_data_keys[key]]['values'].push([traffic_graph_widget_data[i]['time']*1000, bps_out])
}
}
}
// get selections
var deselected_series_in = [];
var deselected_series_out = [];
d3.select("#traffic_graph_widget_chart_in").selectAll(".nv-series").each(function(d, i) {
if (d.disabled) {
deselected_series_in.push(d.key);
}
});
d3.select("#traffic_graph_widget_chart_out").selectAll(".nv-series").each(function(d, i) {
if (d.disabled) {
deselected_series_out.push(d.key);
}
});
// load data
traffic_graph_widget_chart_data_in.datum(chart_data_in).transition().duration(500).call(traffic_graph_widget_chart_in);
traffic_graph_widget_chart_data_out.datum(chart_data_out).transition().duration(500).call(traffic_graph_widget_chart_out);
// set selection
d3.selectAll("#traffic_graph_widget_chart_in").selectAll(".nv-series").each(function(d, i) {
if (deselected_series_in.indexOf(d.key) > -1) {
d3.select(this).on("click").apply(this, [d, i]);
}
});
d3.selectAll("#traffic_graph_widget_chart_out").selectAll(".nv-series").each(function(d, i) {
if (deselected_series_out.indexOf(d.key) > -1) {
d3.select(this).on("click").apply(this, [d, i]);
}
});
}
/**
* page setup
*/
$( document ).ready(function() {
// draw traffic in graph
nv.addGraph(function() {
traffic_graph_widget_chart_in = nv.models.lineChart()
.x(function(d) { return d[0] })
.y(function(d) { return d[1] })
.useInteractiveGuideline(false)
.interactive(true)
.showLegend(true)
.showXAxis(false)
.clipEdge(true)
.margin({top:5,right:5,bottom:5,left:50})
;
traffic_graph_widget_chart_in.yAxis.tickFormat(d3.format(',.2s'));
traffic_graph_widget_chart_in.xAxis.tickFormat(function(d) {
return d3.time.format('%b %e %H:%M:%S')(new Date(d));
});
traffic_graph_widget_chart_data_in = d3.select("#traffic_graph_widget_chart_in svg").datum([{'key':'', 'values':[[0, 0]]}]);
traffic_graph_widget_chart_data_in.transition().duration(500).call(traffic_graph_widget_chart_in);
});
// draw traffic out graph
nv.addGraph(function() {
traffic_graph_widget_chart_out = nv.models.lineChart()
.x(function(d) { return d[0] })
.y(function(d) { return d[1] })
.useInteractiveGuideline(false)
.interactive(true)
.showLegend(true)
.showXAxis(false)
.clipEdge(true)
.margin({top:5,right:5,bottom:5,left:50})
;
traffic_graph_widget_chart_out.yAxis.tickFormat(d3.format(',.2s'));
traffic_graph_widget_chart_out.xAxis.tickFormat(function(d) {
return d3.time.format('%b %e %H:%M:%S')(new Date(d));
});
traffic_graph_widget_chart_data_out = d3.select("#traffic_graph_widget_chart_out svg").datum([{'key':'', 'values':[[0, 0]]}]);
traffic_graph_widget_chart_data_out.transition().duration(500).call(traffic_graph_widget_chart_out);
});
});
</script>
if (isset($a_config["scale_type"])) {
$scale_type = $a_config["scale_type"];
} else {
$scale_type = "up";
}
?> <!-- traffic graph table -->
<div id="traffic_graphs-settings" class="widgetconfigdiv" style="display:none;"> <table class="table table-condensed" data-plugin="traffic" data-callback="traffic_widget_update">
<form action="/widgets/widgets/traffic_graphs.widget.php" method="post" name="iform" id="iform"> <tbody>
<?php <tr>
foreach ($ifdescrs as $ifname => $ifdescr):?> <td><?=gettext("In (bps)");?></td>
<input type="hidden" name="shown[<?= $ifname ?>]" value="<?= $shown[$ifname] ? "show" : "hide" ?>" /> </tr>
<?php <tr>
endforeach; ?> <td>
<table class="table table-striped"> <div id="traffic_graph_widget_chart_in">
<tbody> <svg style="height:150px;"></svg>
<tr> </div>
<td> </td>
<?= gettext('Default AutoScale:') ?> </tr>
</td> <tr>
</tr> <td><?=gettext("Out (bps)");?></td>
<?php </tr>
$scale_type_up='checked="checked"'; <tr>
$scale_type_follow="";
if (isset($config["widgets"]["trafficgraphs"]["scale_type"])) {
$selected_radio = $config["widgets"]["trafficgraphs"]["scale_type"];
if ($selected_radio == "up") {
$scale_type_up = 'checked="checked"';
$scale_type_follow="";
} elseif ($selected_radio == "follow") {
$scale_type_up="";
$scale_type_follow = 'checked="checked"';
}
}
?>
<tr>
<td>
<input name="scale_type" type="radio" id="scale_type_up" value="up" <?= $scale_type_up; ?> /> <?= gettext('Scale up')?>
</td>
</tr>
<tr>
<td>
<input name="scale_type" type="radio" id="scale_type_follow" value="follow" <?= $scale_type_follow; ?> /> <?= gettext('Scale follow')?><br /><br />
<?= gettext('Refresh Interval:') ?>
<select name="refreshinterval" class="formfld" id="refreshinterval" >
<?php
for ($i = 1; $i <= 10; $i += 1) {
?>
<option value="<?= $i ?>" <?php if ($refreshinterval == $i) {
echo 'selected="selected"';
}?>><?= $i ?></option>
<?php
} ?>
</select>&nbsp; <?= gettext('Seconds') ?><br />&nbsp; &nbsp; &nbsp; <b><?= gettext('Note:') ?></b> <?= gettext('changing this setting will increase CPU utilization') ?><br /><br />
</td>
</tr>
<tr>
<td> <td>
<input id="submit_settings" name="submit_settings" type="submit" class="formbtn btn btn-primary" value="<?= gettext('Save Settings') ?>" /> <div id="traffic_graph_widget_chart_out">
<svg style="height:150px;"></svg>
</div>
</td> </td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
</form>
</div>
<script type="text/javascript">
//<![CDATA[
d = document;
selectIntLink = "traffic_graphs-configure";
textlink = d.getElementById(selectIntLink);
textlink.style.display = "inline";
//]]>
</script>
<?php
foreach ($ifdescrs as $ifname => $ifdescr):
$ifinfo = get_interface_info($ifname);
if ($shown[$ifname]) {
$mingraphbutton = "inline";
$showgraphbutton = "none";
$graphdisplay = "inline";
$interfacevalue = "show";
} else {
$mingraphbutton = "none";
$showgraphbutton = "inline";
$graphdisplay = "none";
$interfacevalue = "hide";
}
if ($ifinfo['status'] != "down"):
?>
<div id="<?=$ifname;?>trafficdiv" style="padding: 5px">
<div id="<?=$ifname;?>topic" class="widgetsubheader">
<div style="float:left;width:49%">
<span onclick="location.href='/status_graph.php?if=<?=$ifname;?>'" style="cursor:pointer"><?= sprintf(gettext('Current %s Traffic'),$ifdescr) ?></span>
</div>
<div align="right" style="float:right;width:49%">
<div id="<?=$ifname;?>graphdiv-min" onclick='return trafficminimizeDiv("<?= $ifname ?>", true);' style="display:<?=$mingraphbutton;?>; cursor:pointer" ><span class="glyphicon glyphicon-minus" alt="Minimize <?=$ifname;?> traffic graph" /></span></div>
<div id="<?=$ifname;?>graphdiv-open" onclick='return trafficshowDiv("<?= $ifname ?>", true);' style="display:<?=$showgraphbutton;?>; cursor:pointer" ><span class="glyphicon glyphicon-plus" alt="Show <?=$ifname;?> traffic graph" /></span></div>
</div>
<div style="clear:both;"></div>
</div>
<div id="<?=$ifname;?>graphdiv" style="display:<?= $graphdisplay;?>">
<object data="graph.php?ifnum=<?=$ifname;?>&amp;ifname=<?=rawurlencode($ifdescr);?>&amp;timeint=<?=$refreshinterval;?>&amp;initdelay=<?=($graphcounter+1) * 2;?>" height="100%" width="100%">
<param name="id" value="graph" />
<param name="type" value="image/svg+xml" />
<param name="pluginspage" value="http://www.adobe.com/svg/viewer/install/auto" />
</object>
</div>
</div>
<?php
endif;
endforeach;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment