Project

General

Profile

Download (10.3 KB) Statistics
| Branch: | Tag: | Revision:
1
<?
2
/*
3
	functions.inc.php
4
	pfSense_MODULE:	ajax
5
	Copyright (C) 2013-2015 Electric Sheep Fencing, LP
6
*/
7

    
8
if (Connection_Aborted()) {
9
	exit;
10
}
11

    
12
require_once("config.inc");
13
require_once("pfsense-utils.inc");
14

    
15
function get_stats() {
16
	$stats['cpu'] = cpu_usage();
17
	$stats['mem'] = mem_usage();
18
	$stats['uptime'] = get_uptime();
19
	$stats['states'] = get_pfstate();
20
	$stats['temp'] = get_temp();
21
	$stats['datetime'] = update_date_time();
22
	$stats['interfacestatistics'] = get_interfacestats();
23
	$stats['interfacestatus'] = get_interfacestatus();
24
	$stats['gateways'] = get_gatewaystats();
25
	$stats['cpufreq'] = get_cpufreq();
26
	$stats['load_average'] = get_load_average();
27
	$stats['mbuf'] = get_mbuf();
28
	$stats['mbufpercent'] = get_mbuf(true);
29
	$stats['statepercent'] = get_pfstate(true);
30
	$stats = join("|", $stats);
31
	return $stats;
32
}
33

    
34
function get_gatewaystats() {
35
	global $config;
36
	if (isset($config["widgets"]["gateways_widget"]["display_type"])) {
37
		$display_type = $config["widgets"]["gateways_widget"]["display_type"];
38
	} else {
39
		$display_type = "gw_ip";
40
	}
41

    
42
	$a_gateways = return_gateways_array();
43
	$gateways_status = array();
44
	$gateways_status = return_gateways_status(true);
45
	$data = "";
46
	$isfirst = true;
47
	foreach ($a_gateways as $gname => $gw) {
48
		if (!$isfirst) {
49
			$data .= ",";
50
		}
51
		$isfirst = false;
52
		$data .= $gw['name'] . ",";
53

    
54
		$monitor_address = "";
55
		$monitor_address_disp = "";
56
		if ($display_type == "monitor_ip" || $display_type == "both_ip") {
57
			$monitor_address = $gw['monitor'];
58
			if ($monitor_address != "" && $display_type == "both_ip") {
59
				$monitor_address_disp = " (" . $monitor_address . ")";
60
			} else {
61
				$monitor_address_disp = $monitor_address;
62
			}
63
		}
64

    
65
		if ($gateways_status[$gname]) {
66
			if ($display_type == "gw_ip" || $display_type == "both_ip" || ($display_type == "monitor_ip" && $monitor_address == "")) {
67
				$if_gw = lookup_gateway_ip_by_name($gname);
68
			} else {
69
				$if_gw = "";
70
			}
71
			if ($monitor_address == $if_gw) {
72
				$monitor_address_disp = "";
73
			}
74

    
75
			$data .= "<b>" . $if_gw . $monitor_address_disp . "</b>,";
76
			$gws = $gateways_status[$gname];
77
			switch (strtolower($gws['status'])) {
78
				case "none":
79
					$online = "Online";
80
					$bgcolor = "#90EE90";  // lightgreen
81
					break;
82
				case "down":
83
					$online = "Offline";
84
					$bgcolor = "#F08080";  // lightcoral
85
					break;
86
				case "delay":
87
					$online = "Latency";
88
					$bgcolor = "#F0E68C";  // khaki
89
					break;
90
				case "loss":
91
					$online = "Packetloss";
92
					$bgcolor = "#F0E68C";  // khaki
93
					break;
94
				default:
95
					$online = "Pending";
96
					break;
97
			}
98
		} else {
99
			if ($display_type == "gw_ip" || $display_type == "both_ip" || ($display_type == "monitor_ip" && $monitor_address == "")) {
100
				$if_gw = "~";
101
			} else {
102
				$if_gw = "";
103
			}
104
			$data .= $if_gw . $monitor_address_disp . ",";
105
			$gws['delay'] = "~";
106
			$gws['loss'] = "~";
107
			$online = "Unknown";
108
			$bgcolor = "#ADD8E6";  // lightblue
109
		}
110
		$data .= ($online == "Pending") ? "{$online},{$online}," : "{$gws['delay']},{$gws['loss']},";
111
		$data .= "{$online}^{$bgcolor}";
112
	}
113
	return $data;
114
}
115

    
116
function get_uptime() {
117
	$uptime = get_uptime_sec();
118

    
119
	if (intval($uptime) == 0) {
120
		return;
121
	}
122

    
123
	$updays = (int)($uptime / 86400);
124
	$uptime %= 86400;
125
	$uphours = (int)($uptime / 3600);
126
	$uptime %= 3600;
127
	$upmins = (int)($uptime / 60);
128
	$uptime %= 60;
129
	$upsecs = (int)($uptime);
130

    
131
	$uptimestr = "";
132
	if ($updays > 1) {
133
		$uptimestr .= "$updays Days ";
134
	} else if ($updays > 0) {
135
		$uptimestr .= "1 Day ";
136
	}
137

    
138
	if ($uphours > 1) {
139
		$hours = "s";
140
	}
141

    
142
	if ($upmins > 1) {
143
		$minutes = "s";
144
	}
145

    
146
	if ($upmins > 1) {
147
		$seconds = "s";
148
	}
149

    
150
	$uptimestr .= sprintf("%02d Hour$hours %02d Minute$minutes %02d Second$seconds", $uphours, $upmins, $upsecs);
151
	return $uptimestr;
152
}
153

    
154
/* Calculates non-idle CPU time and returns as a percentage */
155
function cpu_usage() {
156
	$duration = 1;
157
	$diff = array('user', 'nice', 'sys', 'intr', 'idle');
158
	$cpuTicks = array_combine($diff, explode(" ", get_single_sysctl('kern.cp_time')));
159
	sleep($duration);
160
	$cpuTicks2 = array_combine($diff, explode(" ", get_single_sysctl('kern.cp_time')));
161

    
162
	$totalStart = array_sum($cpuTicks);
163
	$totalEnd = array_sum($cpuTicks2);
164

    
165
	// Something wrapped ?!?!
166
	if ($totalEnd <= $totalStart) {
167
		return 0;
168
	}
169

    
170
	// Calculate total cycles used
171
	$totalUsed = ($totalEnd - $totalStart) - ($cpuTicks2['idle'] - $cpuTicks['idle']);
172

    
173
	// Calculate the percentage used
174
	$cpuUsage = floor(100 * ($totalUsed / ($totalEnd - $totalStart)));
175

    
176
	return $cpuUsage;
177
}
178

    
179
function get_pfstate($percent=false) {
180
	global $config;
181
	$matches = "";
182
	if (isset($config['system']['maximumstates']) and $config['system']['maximumstates'] > 0) {
183
		$maxstates="{$config['system']['maximumstates']}";
184
	} else {
185
		$maxstates=pfsense_default_state_size();
186
	}
187
	$curentries = `/sbin/pfctl -si |grep current`;
188
	if (preg_match("/([0-9]+)/", $curentries, $matches)) {
189
		$curentries = $matches[1];
190
	}
191
	if (!is_numeric($curentries)) {
192
		$curentries = 0;
193
	}
194
	if ($percent) {
195
		if (intval($maxstates) > 0) {
196
			return round(($curentries / $maxstates) * 100, 0);
197
		} else {
198
			return "NA";
199
		}
200
	} else {
201
		return $curentries . "/" . $maxstates;
202
	}
203
}
204

    
205
function has_temp() {
206
	/* no known temp monitors available at present */
207

    
208
	/* should only reach here if there is no hardware monitor */
209
	return false;
210
}
211

    
212
function get_hwtype() {
213
	return;
214
}
215

    
216
function get_mbuf($percent=false) {
217
	$mbufs_output=trim(`/usr/bin/netstat -mb | /usr/bin/grep "mbuf clusters in use" | /usr/bin/awk '{ print $1 }'`);
218
	list($mbufs_current, $mbufs_cache, $mbufs_total, $mbufs_max) = explode("/", $mbufs_output);
219
	if ($percent) {
220
		if ($mbufs_max > 0) {
221
			return round(($mbufs_total / $mbufs_max) * 100, 0);
222
		} else {
223
			return "NA";
224
		}
225
	} else {
226
		return "{$mbufs_total}/{$mbufs_max}";
227
	}
228
}
229

    
230
function get_temp() {
231
	$temp_out = get_single_sysctl("dev.cpu.0.temperature");
232
	if ($temp_out == "") {
233
		$temp_out = get_single_sysctl("hw.acpi.thermal.tz0.temperature");
234
	}
235

    
236
	// Remove 'C' from the end and spaces
237
	$temp_out = trim(rtrim($temp_out, 'C'));
238

    
239
	if ($temp_out[0] == '-') {
240
		return '';
241
	}
242

    
243
	return $temp_out;
244
}
245

    
246
/* Get mounted filesystems and usage. Do not display entries for virtual filesystems (e.g. devfs, nullfs, unionfs) */
247
function get_mounted_filesystems() {
248
	$mout = "";
249
	$filesystems = array();
250
	exec("/bin/df -Tht ufs,zfs,cd9660 | /usr/bin/awk '{print $1, $2, $3, $6, $7;}'", $mout);
251

    
252
	/* Get rid of the header */
253
	array_shift($mout);
254
	foreach ($mout as $fs) {
255
		$f = array();
256
		list($f['device'], $f['type'], $f['total_size'], $f['percent_used'], $f['mountpoint']) = explode(' ', $fs);
257

    
258
		/* We dont' want the trailing % sign. */
259
		$f['percent_used'] = trim($f['percent_used'], '%');
260

    
261
		$filesystems[] = $f;
262
	}
263
	return $filesystems;
264
}
265

    
266
function disk_usage($slice = '/') {
267
	$dfout = "";
268
	exec("/bin/df -h {$slice} | /usr/bin/tail -n 1 | /usr/bin/awk '{ print $5 }' | /usr/bin/cut -d '%' -f 1", $dfout);
269
	$diskusage = trim($dfout[0]);
270

    
271
	return $diskusage;
272
}
273

    
274
function swap_usage() {
275
	exec("/usr/sbin/swapinfo", $swap_info);
276
	$swap_used = "";
277
	foreach ($swap_info as $line) {
278
		if (preg_match('/(\d+)%$/', $line, $matches)) {
279
			$swap_used = $matches[1];
280
			break;
281
		}
282
	}
283

    
284
	return $swap_used;
285
}
286

    
287
function mem_usage() {
288
	$totalMem = get_single_sysctl("vm.stats.vm.v_page_count");
289
	if ($totalMem > 0) {
290
		$inactiveMem = get_single_sysctl("vm.stats.vm.v_inactive_count");
291
		$cachedMem = get_single_sysctl("vm.stats.vm.v_cache_count");
292
		$freeMem = get_single_sysctl("vm.stats.vm.v_free_count");
293
		$usedMem = $totalMem - ($inactiveMem + $cachedMem + $freeMem);
294
		$memUsage = round(($usedMem * 100) / $totalMem, 0);
295
	} else {
296
		$memUsage = "NA";
297
	}
298

    
299
	return $memUsage;
300
}
301

    
302
function update_date_time() {
303
	$datetime = date("D M j G:i:s T Y");
304
	return $datetime;
305
}
306

    
307
function get_cpufreq() {
308
	$cpufreqs = "";
309
	$out = "";
310
	$cpufreqs = explode(" ", get_single_sysctl('dev.cpu.0.freq_levels'));
311
	$maxfreq = explode("/", $cpufreqs[0]);
312
	$maxfreq = $maxfreq[0];
313
	$curfreq = "";
314
	$curfreq = get_single_sysctl('dev.cpu.0.freq');
315
	if (($curfreq > 0) && ($curfreq != $maxfreq)) {
316
		$out = "Current: {$curfreq} MHz, Max: {$maxfreq} MHz";
317
	}
318
	return $out;
319
}
320

    
321
function get_cpu_count($show_detail = false) {
322
	$cpucount = get_single_sysctl('kern.smp.cpus');
323

    
324
	if ($show_detail) {
325
		$cpudetail = "";
326
		exec("/usr/bin/grep 'SMP.*package.*core' /var/log/dmesg.boot | /usr/bin/cut -f2- -d' '", $cpudetail);
327
		$cpucount = $cpudetail[0];
328
	}
329
	return $cpucount;
330
}
331

    
332
function get_load_average() {
333
	$load_average = "";
334
	exec("/usr/bin/uptime | /usr/bin/sed 's/^.*: //'", $load_average);
335
	return $load_average[0];
336
}
337

    
338
function get_interfacestats() {
339
	global $config;
340
	//build interface list for widget use
341
	$ifdescrs = get_configured_interface_list();
342

    
343
	$array_in_packets = array();
344
	$array_out_packets = array();
345
	$array_in_bytes = array();
346
	$array_out_bytes = array();
347
	$array_in_errors = array();
348
	$array_out_errors = array();
349
	$array_collisions = array();
350
	$array_interrupt = array();
351
	$new_data = "";
352

    
353
	//build data arrays
354
	foreach ($ifdescrs as $ifdescr => $ifname) {
355
		$ifinfo = get_interface_info($ifdescr);
356
		$new_data .= "{$ifinfo['inpkts']},";
357
		$new_data .= "{$ifinfo['outpkts']},";
358
		$new_data .= format_bytes($ifinfo['inbytes']) . ",";
359
		$new_data .= format_bytes($ifinfo['outbytes']) . ",";
360
		if (isset($ifinfo['inerrs'])) {
361
			$new_data .= "{$ifinfo['inerrs']},";
362
			$new_data .= "{$ifinfo['outerrs']},";
363
		} else {
364
			$new_data .= "0,";
365
			$new_data .= "0,";
366
		}
367
		if (isset($ifinfo['collisions'])) {
368
			$new_data .= htmlspecialchars($ifinfo['collisions']) . ",";
369
		} else {
370
			$new_data .= "0,";
371
		}
372
	}//end for
373

    
374
	return $new_data;
375
}
376

    
377
function get_interfacestatus() {
378
	$data = "";
379
	global $config;
380

    
381
	//build interface list for widget use
382
	$ifdescrs = get_configured_interface_with_descr();
383

    
384
	foreach ($ifdescrs as $ifdescr => $ifname) {
385
		$ifinfo = get_interface_info($ifdescr);
386
		$data .= $ifname . "^";
387
		if ($ifinfo['status'] == "up" || $ifinfo['status'] == "associated") {
388
			$data .= "up";
389
		} else if ($ifinfo['status'] == "no carrier") {
390
			$data .= "down";
391
		} else if ($ifinfo['status'] == "down") {
392
			$data .= "block";
393
		}
394
		$data .= "^";
395
		if ($ifinfo['ipaddr']) {
396
			$data .= "<strong>" . htmlspecialchars($ifinfo['ipaddr']) . "</strong>";
397
		}
398
		$data .= "^";
399
		if ($ifinfo['ipaddrv6']) {
400
			$data .= "<strong>" . htmlspecialchars($ifinfo['ipaddrv6']) . "</strong>";
401
		}
402
		$data .= "^";
403
		if ($ifinfo['status'] != "down") {
404
			$data .= htmlspecialchars($ifinfo['media']);
405
		}
406

    
407
		$data .= "~";
408

    
409
	}
410
	return $data;
411
}
412

    
413
?>
    (1-1/1)