Project

General

Profile

Download (15.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
	graph.php
4
*/
5
/* ====================================================================
6
 *  Copyright (c)  2004-2015  Electric Sheep Fencing, LLC. All rights reserved.
7
 *  Copyright (c)  2004-2006 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
8
 *							 and Jonathan Watt <jwatt@jwatt.org>
9
 *
10
 *  Some or all of this file is based on the m0n0wall project which is
11
 *  Copyright (c)  2004 Manuel Kasper (BSD 2 clause)
12
 *
13
 *  Redistribution and use in source and binary forms, with or without modification,
14
 *  are permitted provided that the following conditions are met:
15
 *
16
 *  1. Redistributions of source code must retain the above copyright notice,
17
 *      this list of conditions and the following disclaimer.
18
 *
19
 *  2. Redistributions in binary form must reproduce the above copyright
20
 *      notice, this list of conditions and the following disclaimer in
21
 *      the documentation and/or other materials provided with the
22
 *      distribution.
23
 *
24
 *  3. All advertising materials mentioning features or use of this software
25
 *      must display the following acknowledgment:
26
 *      "This product includes software developed by the pfSense Project
27
 *       for use in the pfSense software distribution. (http://www.pfsense.org/).
28
 *
29
 *  4. The names "pfSense" and "pfSense Project" must not be used to
30
 *       endorse or promote products derived from this software without
31
 *       prior written permission. For written permission, please contact
32
 *       coreteam@pfsense.org.
33
 *
34
 *  5. Products derived from this software may not be called "pfSense"
35
 *      nor may "pfSense" appear in their names without prior written
36
 *      permission of the Electric Sheep Fencing, LLC.
37
 *
38
 *  6. Redistributions of any form whatsoever must retain the following
39
 *      acknowledgment:
40
 *
41
 *  "This product includes software developed by the pfSense Project
42
 *  for use in the pfSense software distribution (http://www.pfsense.org/).
43
 *
44
 *  THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
45
 *  EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
47
 *  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
48
 *  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
49
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
50
 *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
51
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52
 *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
53
 *  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
54
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
55
 *  OF THE POSSIBILITY OF SUCH DAMAGE.
56
 *
57
 *  ====================================================================
58
 *
59
 */
60
/*
61
	pfSense_MODULE:	graph
62
*/
63

    
64
##|+PRIV
65
##|*IDENT=page-diagnostics-interfacetraffic
66
##|*NAME=Diagnostics: Interface Traffic
67
##|*DESCR=Allow access to the 'Diagnostics: Interface Traffic' page.
68
##|*MATCH=graph.php*
69
##|-PRIV
70

    
71
require("globals.inc");
72
require("guiconfig.inc");
73

    
74
header("Last-Modified: " . gmdate("D, j M Y H:i:s") . " GMT");
75
header("Expires: " . gmdate("D, j M Y H:i:s", time()) . " GMT");
76
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP/1.1
77
header("Pragma: no-cache"); // HTTP/1.0
78
header("Content-type: image/svg+xml");
79

    
80
/********** HTTP GET Based Conf ***********/
81
$ifnum = @$_GET["ifnum"];  // BSD / SNMP interface name / number
82
$ifnum = get_real_interface($ifnum);
83
$ifname = @$_GET["ifname"]?$_GET["ifname"]:"Interface $ifnum";  //Interface name that will be showed on top right of graph
84

    
85
/********* Other conf *******/
86
if (isset($config["widgets"]["trafficgraphs"]["scale_type"])) {
87
	$scale_type = $config["widgets"]["trafficgraphs"]["scale_type"];
88
} else {
89
	$scale_type = "up";
90
}
91

    
92
$nb_plot=120;                   //NB plot in graph
93
if ($_GET["timeint"]) {
94
	$time_interval = $_GET["timeint"];		//Refresh time Interval
95
} else {
96
	$time_interval = 3;
97
}
98

    
99
if ($_GET["initdelay"]) {
100
	$init_delay = $_GET["initdelay"];		//Initial Delay
101
} else {
102
	$init_delay = 3;
103
}
104

    
105
//SVG attributes
106
$attribs['axis']='fill="black" stroke="black"';
107
$attribs['in']='fill="#FF0000" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="7"';
108
$attribs['out']='fill="#000000" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="7"';
109
$attribs['graph_in']='fill="none" stroke="#FF0000" stroke-opacity="0.8"';
110
$attribs['graph_out']='fill="none" stroke="#000000" stroke-opacity="0.8"';
111
$attribs['legend']='fill="black" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4"';
112
$attribs['graphname']='fill="#FF0000" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="8"';
113
$attribs['grid_txt']='fill="gray" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="6"';
114
$attribs['grid']='stroke="gray" stroke-opacity="0.5"';
115
$attribs['switch_unit']='fill="#FF0000" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4" text-decoration="underline"';
116
$attribs['switch_scale']='fill="#FF0000" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4" text-decoration="underline"';
117
$attribs['error']='fill="blue" font-family="Arial" font-size="4"';
118
$attribs['collect_initial']='fill="gray" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4"';
119

    
120
//Error text if we cannot fetch data : depends on which method is used
121
$error_text = "Cannot get data about interface " . htmlspecialchars($ifnum);
122

    
123
$height=100;            //SVG internal height : do not modify
124
$width=200;             //SVG internal width : do not modify
125

    
126
$fetch_link = "ifstats.php?if=" . htmlspecialchars($ifnum);
127

    
128
/********* Graph DATA **************/
129
print('<?xml version="1.0" encoding="UTF-8"?>' . "\n");?>
130
<svg width="100%" height="100%" viewBox="0 0 <?=$width?> <?=$height?>" preserveAspectRatio="none" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" onload="init(evt)">
131
	<g id="graph">
132
		<rect id="bg" x1="0" y1="0" width="100%" height="100%" fill="white"/>
133
		<line id="axis_x" x1="0" y1="0" x2="0" y2="100%" <?=$attribs['axis']?>/>
134
		<line id="axis_y" x1="0" y1="100%" x2="100%" y2="100%" <?=$attribs['axis']?>/>
135
		<path id="graph_out" d="M0 <?=$height?> L 0 <?=$height?>" <?=$attribs['graph_out']?>/>
136
		<path id="graph_in" d="M0 <?=$height?> L 0 <?=$height?>" <?=$attribs['graph_in']?>/>
137
		<path id="grid" d="M0 <?=$height/4*1?> L <?=$width?> <?=$height/4*1?> M0 <?=$height/4*2?> L <?=$width?> <?=$height/4*2?> M0 <?=$height/4*3?> L <?=$width?> <?=$height/4*3?>" <?=$attribs['grid']?>/>
138
		<text id="grid_txt1" x="<?=$width?>" y="<?=$height/4*1?>" <?=$attribs['grid_txt']?> text-anchor="end"> </text>
139
		<text id="grid_txt2" x="<?=$width?>" y="<?=$height/4*2?>" <?=$attribs['grid_txt']?> text-anchor="end"> </text>
140
		<text id="grid_txt3" x="<?=$width?>" y="<?=$height/4*3?>" <?=$attribs['grid_txt']?> text-anchor="end"> </text>
141
		<text id="graph_in_lbl" x="5" y="8" <?=$attribs['in']?>><?=gettext("In"); ?></text>
142
		<text id="graph_out_lbl" x="5" y="16" <?=$attribs['out']?>><?=gettext("Out"); ?></text>
143
		<text id="graph_in_txt" x="20" y="8" <?=$attribs['in']?>> </text>
144
		<text id="graph_out_txt" x="20" y="16" <?=$attribs['out']?>> </text>
145
		<text id="ifname" x="<?=$width?>" y="8" <?=$attribs['graphname']?> text-anchor="end"><?=htmlspecialchars($ifname)?></text>
146
		<text id="switch_unit" x="<?=$width*0.55?>" y="5" <?=$attribs['switch_unit']?>><?=gettext("Switch to bytes/s"); ?></text>
147
		<text id="switch_scale" x="<?=$width*0.55?>" y="11" <?=$attribs['switch_scale']?>><?=gettext("AutoScale"); ?> (<?=$scale_type?>)</text>
148
		<text id="date" x="<?=$width*0.33?>" y="5" <?=$attribs['legend']?>> </text>
149
		<text id="time" x="<?=$width*0.33?>" y="11" <?=$attribs['legend']?>> </text>
150
		<text id="graphlast" x="<?=$width*0.55?>" y="17" <?=$attribs['legend']?>><?=gettext("Graph shows last"); ?> <?=$time_interval*$nb_plot?> <?=gettext("seconds"); ?></text>
151
		<polygon id="axis_arrow_x" <?=$attribs['axis']?> points="<?=($width) . "," . ($height)?> <?=($width-2) . "," . ($height-2)?> <?=($width-2) . "," . $height?>"/>
152
		<text id="error" x="<?=$width*0.5?>" y="<?=$height*0.5?>" visibility="hidden" <?=$attribs['error']?> text-anchor="middle"><?=$error_text?></text>
153
		<text id="collect_initial" x="<?=$width*0.5?>" y="<?=$height*0.5?>" visibility="hidden" <?=$attribs['collect_initial']?> text-anchor="middle"><?=gettext("Collecting initial data, please wait"); ?>...</text>
154
	</g>
155
	<script type="text/ecmascript">
156
	<![CDATA[
157

    
158
/**
159
 * getURL is a proprietary Adobe function, but it's simplicity has made it very
160
 * popular. If getURL is undefined we spin our own by wrapping XMLHttpRequest.
161
 */
162
if (typeof getURL == 'undefined') {
163
	getURL = function(url, callback) {
164
		if (!url) {
165
			throw '<?=gettext("No URL for getURL"); ?>';
166
		}
167

    
168
		try {
169
			if (typeof callback.operationComplete == 'function') {
170
				callback = callback.operationComplete;
171
			}
172
		} catch (e) {}
173
		if (typeof callback != 'function') {
174
			throw '<?=gettext("No callback function for getURL"); ?>';
175
		}
176

    
177
		var http_request = null;
178
		if (typeof XMLHttpRequest != 'undefined') {
179
			http_request = new XMLHttpRequest();
180
		} else if (typeof ActiveXObject != 'undefined') {
181
			try {
182
				http_request = new ActiveXObject('Msxml2.XMLHTTP');
183
			} catch (e) {
184
				try {
185
				http_request = new ActiveXObject('Microsoft.XMLHTTP');
186
				} catch (e) {}
187
			}
188
		}
189
		if (!http_request) {
190
			throw '<?=gettext("Both getURL and XMLHttpRequest are undefined"); ?>';
191
		}
192

    
193
		http_request.onreadystatechange = function() {
194
			if (http_request.readyState == 4) {
195
				callback( { success : true,
196
					content : http_request.responseText,
197
					contentType : http_request.getResponseHeader("Content-Type") } );
198
			}
199
		}
200
		http_request.open('GET', url, true);
201
		http_request.send(null);
202
	}
203
}
204

    
205
var SVGDoc = null;
206
var last_ifin = 0;
207
var last_ifout = 0;
208
var last_ugmt = 0;
209
var max = 0;
210
var plot_in = new Array();
211
var plot_out = new Array();
212

    
213
var max_num_points = <?=$nb_plot?>;  // maximum number of plot data points
214
var step = <?=$width?> / max_num_points ;
215
var unit = 'bits';
216
var scale_type = '<?=$scale_type?>';
217

    
218
function init(evt) {
219
	SVGDoc = evt.target.ownerDocument;
220
	SVGDoc.getElementById("switch_unit").addEventListener("mousedown", switch_unit, false);
221
	SVGDoc.getElementById("switch_scale").addEventListener("mousedown", switch_scale, false);
222

    
223
	fetch_data();
224
}
225

    
226
function switch_unit(event) {
227
	SVGDoc.getElementById('switch_unit').firstChild.data = '<?=gettext("Switch to"); ?> ' + unit + '/s';
228
	unit = (unit == 'bits') ? 'bytes' : 'bits';
229
}
230

    
231
function switch_scale(event) {
232
	scale_type = (scale_type == 'up') ? '<?=gettext("follow"); ?>' : '<?=gettext("up"); ?>';
233
	SVGDoc.getElementById('switch_scale').firstChild.data = 'AutoScale (' + scale_type + ')';
234
}
235

    
236
function fetch_data() {
237
	getURL('<?=$fetch_link?>', plot_data);
238
}
239

    
240
function plot_data(obj) {
241
	// Show datetimelegend
242
	var now = new Date();
243
	var time = LZ(now.getHours()) + ":" + LZ(now.getMinutes()) + ":" + LZ(now.getSeconds());
244
	SVGDoc.getElementById('time').firstChild.data = time;
245
	var date = (now.getMonth()+1) + "/" + now.getDate() + "/" + now.getFullYear();
246
	SVGDoc.getElementById('date').firstChild.data = date;
247

    
248
	if (!obj.success) {
249
		return handle_error();  // getURL failed to get data
250
	}
251

    
252
	var t = obj.content.split("|");
253
	var ugmt = parseFloat(t[0]);  // ugmt is an unixtimestamp style
254
	var ifin = parseInt(t[1], 10);    // number of bytes received by the interface
255
	var ifout = parseInt(t[2], 10);   // number of bytes sent by the interface
256
	var scale;
257

    
258
	if (!isNumber(ifin) || !isNumber(ifout)) {
259
		return handle_error();
260
	}
261

    
262
	var diff_ugmt  = ugmt - last_ugmt;
263
	var diff_ifin  = ifin - last_ifin;
264
	var diff_ifout = ifout - last_ifout;
265

    
266
	if (diff_ugmt == 0) {
267
		diff_ugmt = 1;  /* avoid division by zero */
268
	}
269

    
270
	last_ugmt = ugmt;
271
	last_ifin = ifin;
272
	last_ifout = ifout;
273
	var graphTimerId = 0;
274
	switch (plot_in.length) {
275
		case 0:
276
			SVGDoc.getElementById("collect_initial").setAttributeNS(null, 'visibility', 'visible');
277
			plot_in[0] = diff_ifin / diff_ugmt;
278
			plot_out[0] = diff_ifout / diff_ugmt;
279
			setTimeout('fetch_data()', <?=1000*($time_interval + $init_delay)?>);
280
			return;
281
		case 1:
282
			SVGDoc.getElementById("collect_initial").setAttributeNS(null, 'visibility', 'hidden');
283
			break;
284
		case max_num_points:
285
			// shift plot to left if the maximum number of plot points has been reached
286
			var i = 0;
287
			while (i < max_num_points) {
288
				plot_in[i] = plot_in[i+1];
289
				plot_out[i] = plot_out[++i];
290
			}
291
			plot_in.length--;
292
			plot_out.length--;
293
	}
294

    
295
	plot_in[plot_in.length] = diff_ifin / diff_ugmt;
296
	plot_out[plot_out.length]= diff_ifout / diff_ugmt;
297
	var index_plot = plot_in.length - 1;
298

    
299
	SVGDoc.getElementById('graph_in_txt').firstChild.data = formatSpeed(plot_in[index_plot], unit);
300
	SVGDoc.getElementById('graph_out_txt').firstChild.data = formatSpeed(plot_out[index_plot], unit);
301

    
302
	/* determine peak for sensible scaling */
303
	if (scale_type == 'up') {
304
		if (plot_in[index_plot] > max) {
305
			max = plot_in[index_plot];
306
		}
307
		if (plot_out[index_plot] > max) {
308
			max = plot_out[index_plot];
309
		}
310
	} else if (scale_type == 'follow') {
311
		i = 0;
312
		max = 0;
313
		while (i < plot_in.length) {
314
			if (plot_in[i] > max) {
315
				max = plot_in[i];
316
			}
317
			if (plot_out[i] > max) {
318
				max = plot_out[i];
319
			}
320
			i++;
321
		}
322
	}
323

    
324
	var rmax;  // max, rounded up
325

    
326
	if (unit == 'bits') {
327
		/* round up max, such that
328
		   100 kbps -> 200 kbps -> 400 kbps -> 800 kbps -> 1 Mbps -> 2 Mbps -> ... */
329
		rmax = 12500;
330
		i = 0;
331
		while (max > rmax) {
332
			i++;
333
			if (i && (i % 4 == 0)) {
334
				rmax *= 1.25;
335
			} else {
336
				rmax *= 2;
337
			}
338
		}
339
	} else {
340
		/* round up max, such that
341
		   10 KB/s -> 20 KB/s -> 40 KB/s -> 80 KB/s -> 100 KB/s -> 200 KB/s -> 400 KB/s -> 800 KB/s -> 1 MB/s ... */
342
		rmax = 10240;
343
		i = 0;
344
		while (max > rmax) {
345
			i++;
346
			if (i && (i % 4 == 0)) {
347
				rmax *= 1.25;
348
			} else {
349
				rmax *= 2;
350
			}
351

    
352
			if (i == 8) {
353
				rmax *= 1.024;
354
			}
355
		}
356
	}
357

    
358
	scale = <?=$height?> / rmax;
359

    
360
	/* change labels accordingly */
361
	SVGDoc.getElementById('grid_txt1').firstChild.data = formatSpeed(3*rmax/4, unit);
362
	SVGDoc.getElementById('grid_txt2').firstChild.data = formatSpeed(2*rmax/4, unit);
363
	SVGDoc.getElementById('grid_txt3').firstChild.data = formatSpeed(rmax/4, unit);
364

    
365
	var path_in = "M 0 " + (<?=$height?> - (plot_in[0] * scale));
366
	var path_out = "M 0 " + (<?=$height?> - (plot_out[0] * scale));
367
	for (i = 1; i < plot_in.length; i++) {
368
		var x = step * i;
369
		var y_in = <?=$height?> - (plot_in[i] * scale);
370
		var y_out = <?=$height?> - (plot_out[i] * scale);
371
		path_in += " L" + x + " " + y_in;
372
		path_out += " L" + x + " " + y_out;
373
	}
374

    
375
	SVGDoc.getElementById('error').setAttributeNS(null, 'visibility', 'hidden');
376
	SVGDoc.getElementById('graph_in').setAttributeNS(null, 'd', path_in);
377
	SVGDoc.getElementById('graph_out').setAttributeNS(null, 'd', path_out);
378

    
379
	setTimeout('fetch_data()', <?=1000*$time_interval?>);
380
}
381

    
382
function handle_error() {
383
	SVGDoc.getElementById("error").setAttributeNS(null, 'visibility', 'visible');
384
	setTimeout('fetch_data()', <?=1000*$time_interval?>);
385
}
386

    
387
function isNumber(a) {
388
	return typeof a == 'number' && isFinite(a);
389
}
390

    
391
function formatSpeed(speed, unit) {
392
	if (unit == 'bits') {
393
		return formatSpeedBits(speed);
394
	}
395
	if (unit == 'bytes') {
396
		return formatSpeedBytes(speed);
397
	}
398
}
399

    
400
function formatSpeedBits(speed) {
401
	// format speed in bits/sec, input: bytes/sec
402
	if (speed < 125000) {
403
		return Math.round(speed / 125) + " <?=gettext("Kbps"); ?>";
404
	}
405
	if (speed < 125000000) {
406
		return Math.round(speed / 1250)/100 + " <?=gettext("Mbps"); ?>";
407
	}
408
	// else
409
	return Math.round(speed / 1250000)/100 + " <?=gettext("Gbps"); ?>";  /* wow! */
410
}
411

    
412
function formatSpeedBytes(speed) {
413
	// format speed in bytes/sec, input:  bytes/sec
414
	if (speed < 1048576) {
415
		return Math.round(speed / 10.24)/100 + " <?=gettext("KB/s"); ?>";
416
	}
417
	if (speed < 1073741824) {
418
		return Math.round(speed / 10485.76)/100 + " <?=gettext("MB/s"); ?>";
419
	}
420
	// else
421
	return Math.round(speed / 10737418.24)/100 + " <?=gettext("GB/s"); ?>";  /* wow! */
422
}
423

    
424
function LZ(x) {
425
	return (x < 0 || x > 9 ? "" : "0") + x;
426
}
427

    
428
    ]]>
429
	</script>
430
</svg>
(72-72/228)