Project

General

Profile

Download (9 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
	$a_gateways = return_gateways_array();
36
	$gateways_status = array();
37
	$gateways_status = return_gateways_status(true);
38
	$data = "";
39
	$isfirst = true;
40
	foreach($a_gateways as $gname => $gw) {
41
		if(!$isfirst)
42
			$data .= ",";
43
		$isfirst = false;
44
		$data .= $gw['name'] . ",";
45
		if ($gateways_status[$gname]) {
46
			$data .= "<b>" . lookup_gateway_ip_by_name($gname) . "</b>,";
47
			$gws = $gateways_status[$gname];
48
			switch(strtolower($gws['status'])) {
49
			case "none":
50
				$online = "Online";
51
				$bgcolor = "#90EE90";  // lightgreen
52
				break;
53
			case "down":
54
				$online = "Offline";
55
				$bgcolor = "#F08080";  // lightcoral
56
				break;
57
			case "delay":
58
				$online = "Latency";
59
				$bgcolor = "#F0E68C";  // khaki
60
				break;
61
			case "loss":
62
				$online = "Packetloss";
63
				$bgcolor = "#F0E68C";  // khaki
64
				break;
65
			default:
66
				$online = "Pending";
67
				break;
68
			}
69
		} else {
70
			$data .= "~,";
71
			$gws['delay'] = "~";
72
			$gws['loss'] = "~";
73
			$online = "Unknown";
74
			$bgcolor = "#ADD8E6";  // lightblue
75
		}
76
		$data .= ($online == "Pending") ? "{$online},{$online}," : "{$gws['delay']},{$gws['loss']},";
77
		$data .= "{$online}^{$bgcolor}";
78
	}
79
	return $data;
80
}
81

    
82
function get_uptime() {
83
	$uptime = get_uptime_sec();
84

    
85
	if(intval($uptime) == 0)
86
		return;
87

    
88
	$updays = (int)($uptime / 86400);
89
	$uptime %= 86400;
90
	$uphours = (int)($uptime / 3600);
91
	$uptime %= 3600;
92
	$upmins = (int)($uptime / 60);
93
	$uptime %= 60;
94
	$upsecs = (int)($uptime);
95

    
96
	$uptimestr = "";
97
	if ($updays > 1)
98
		$uptimestr .= "$updays Days ";
99
	else if ($updays > 0)
100
		$uptimestr .= "1 Day ";
101

    
102
	if ($uphours > 1)
103
		$hours = "s";
104

    
105
	if ($upmins > 1)
106
		$minutes = "s";
107

    
108
	if ($upmins > 1)
109
		$seconds = "s";
110

    
111
	$uptimestr .= sprintf("%02d Hour$hours %02d Minute$minutes %02d Second$seconds", $uphours, $upmins, $upsecs);
112
	return $uptimestr;
113
}
114

    
115
/* Calculates non-idle CPU time and returns as a percentage */
116
function cpu_usage() {
117
	$duration = 1;
118
	$diff = array('user', 'nice', 'sys', 'intr', 'idle');
119
	$cpuTicks = array_combine($diff, explode(" ", get_single_sysctl('kern.cp_time')));
120
	sleep($duration);
121
	$cpuTicks2 = array_combine($diff, explode(" ", get_single_sysctl('kern.cp_time')));
122

    
123
	$totalStart = array_sum($cpuTicks);
124
	$totalEnd = array_sum($cpuTicks2);
125

    
126
	// Something wrapped ?!?!
127
	if ($totalEnd <= $totalStart)
128
		return 0;
129

    
130
	// Calculate total cycles used
131
	$totalUsed = ($totalEnd - $totalStart) - ($cpuTicks2['idle'] - $cpuTicks['idle']);
132

    
133
	// Calculate the percentage used
134
	$cpuUsage = floor(100 * ($totalUsed / ($totalEnd - $totalStart)));
135

    
136
	return $cpuUsage;
137
}
138

    
139
function get_pfstate($percent=false) {
140
	global $config;
141
	$matches = "";
142
	if (isset($config['system']['maximumstates']) and $config['system']['maximumstates'] > 0)
143
		$maxstates="{$config['system']['maximumstates']}";
144
	else
145
		$maxstates=pfsense_default_state_size();
146
	$curentries = `/sbin/pfctl -si |grep current`;
147
	if (preg_match("/([0-9]+)/", $curentries, $matches)) {
148
		$curentries = $matches[1];
149
	}
150
	if (!is_numeric($curentries))
151
		$curentries = 0;
152
	if ($percent)
153
		if (intval($maxstates) > 0)
154
			return round(($curentries / $maxstates) * 100, 0);
155
		else
156
			return "NA";
157
	else
158
		return $curentries . "/" . $maxstates;
159
}
160

    
161
function has_temp() {
162
	/* no known temp monitors available at present */
163

    
164
	/* should only reach here if there is no hardware monitor */
165
	return false;
166
}
167

    
168
function get_hwtype() {
169
	return;
170
}
171

    
172
function get_mbuf($percent=false) {
173
	$mbufs_output=trim(`/usr/bin/netstat -mb | /usr/bin/grep "mbuf clusters in use" | /usr/bin/awk '{ print $1 }'`);
174
	list( $mbufs_current, $mbufs_cache, $mbufs_total, $mbufs_max ) = explode( "/", $mbufs_output);
175
	if ($percent)
176
		if ($mbufs_max > 0)
177
			return round(($mbufs_total / $mbufs_max) * 100, 0);
178
		else
179
			return "NA";
180
	else
181
		return "{$mbufs_total}/{$mbufs_max}";
182
}
183

    
184
function get_temp() {
185
	$temp_out = get_single_sysctl("dev.cpu.0.temperature");
186
	if ($temp_out == "")
187
		$temp_out = get_single_sysctl("hw.acpi.thermal.tz0.temperature");
188

    
189
	// Remove 'C' from the end
190
	return rtrim($temp_out, 'C');
191
}
192

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

    
199
	/* Get rid of the header */
200
	array_shift($mout);
201
	foreach ($mout as $fs) {
202
		$f = array();
203
		list($f['device'], $f['type'], $f['total_size'], $f['percent_used'], $f['mountpoint']) = explode(' ', $fs);
204

    
205
		/* We dont' want the trailing % sign. */
206
		$f['percent_used'] = trim($f['percent_used'], '%');
207

    
208
		$filesystems[] = $f;
209
	}
210
	return $filesystems;
211
}
212

    
213
function disk_usage($slice = '/') {
214
	$dfout = "";
215
	exec("/bin/df -h {$slice} | /usr/bin/tail -n 1 | /usr/bin/awk '{ print $5 }' | /usr/bin/cut -d '%' -f 1", $dfout);
216
	$diskusage = trim($dfout[0]);
217

    
218
	return $diskusage;
219
}
220

    
221
function swap_usage() {
222
	exec("/usr/sbin/swapinfo", $swap_info);
223
	$swap_used = "";
224
	foreach ($swap_info as $line)
225
		if (preg_match('/(\d+)%$/', $line, $matches)) {
226
			$swap_used = $matches[1];
227
			break;
228
		}
229

    
230
	return $swap_used;
231
}
232

    
233
function mem_usage() {
234
	$totalMem = get_single_sysctl("vm.stats.vm.v_page_count");
235
	if ($totalMem > 0) {
236
		$inactiveMem = get_single_sysctl("vm.stats.vm.v_inactive_count");
237
		$cachedMem = get_single_sysctl("vm.stats.vm.v_cache_count");
238
		$freeMem = get_single_sysctl("vm.stats.vm.v_free_count");
239
		$usedMem = $totalMem - ($inactiveMem + $cachedMem + $freeMem);
240
		$memUsage = round(($usedMem * 100) / $totalMem, 0);
241
	} else
242
		$memUsage = "NA";
243

    
244
	return $memUsage;
245
}
246

    
247
function update_date_time() {
248
	$datetime = date("D M j G:i:s T Y");
249
	return $datetime;
250
}
251

    
252
function get_cpufreq() {
253
	$cpufreqs = "";
254
	$out = "";
255
	$cpufreqs = explode(" ", get_single_sysctl('dev.cpu.0.freq_levels'));
256
	$maxfreq = explode("/", $cpufreqs[0]);
257
	$maxfreq = $maxfreq[0];
258
	$curfreq = "";
259
	$curfreq = get_single_sysctl('dev.cpu.0.freq');
260
	if (($curfreq > 0) && ($curfreq != $maxfreq))
261
		$out = "Current: {$curfreq} MHz, Max: {$maxfreq} MHz";
262
	return $out;
263
}
264

    
265
function get_cpu_count($show_detail = false) {
266
	$cpucount = get_single_sysctl('kern.smp.cpus');
267

    
268
	if ($show_detail) {
269
		$cpudetail = "";
270
		exec("/usr/bin/grep 'SMP.*package.*core' /var/log/dmesg.boot | /usr/bin/cut -f2- -d' '", $cpudetail);
271
		$cpucount = $cpudetail[0];
272
	}
273
	return $cpucount;
274
}
275

    
276
function get_load_average() {
277
	$load_average = "";
278
	exec("/usr/bin/uptime | /usr/bin/sed 's/^.*: //'", $load_average);
279
	return $load_average[0];
280
}
281

    
282
function get_interfacestats() {
283
	global $config;
284
	//build interface list for widget use
285
	$ifdescrs = get_configured_interface_list();
286

    
287
	$array_in_packets = array();
288
	$array_out_packets = array();
289
	$array_in_bytes = array();
290
	$array_out_bytes = array();
291
	$array_in_errors = array();
292
	$array_out_errors = array();
293
	$array_collisions = array();
294
	$array_interrupt = array();
295
	$new_data = "";
296

    
297
	//build data arrays
298
	foreach ($ifdescrs as $ifdescr => $ifname){
299
		$ifinfo = get_interface_info($ifdescr);
300
			$new_data .= "{$ifinfo['inpkts']},";
301
			$new_data .= "{$ifinfo['outpkts']},";
302
			$new_data .= format_bytes($ifinfo['inbytes']) . ",";
303
			$new_data .= format_bytes($ifinfo['outbytes']) . ",";
304
			if (isset($ifinfo['inerrs'])){
305
				$new_data .= "{$ifinfo['inerrs']},";
306
				$new_data .= "{$ifinfo['outerrs']},";
307
			}
308
			else{
309
				$new_data .= "0,";
310
				$new_data .= "0,";
311
			}
312
			if (isset($ifinfo['collisions']))
313
				$new_data .= htmlspecialchars($ifinfo['collisions']) . ",";
314
			else
315
				$new_data .= "0,";
316
	}//end for
317

    
318
	return $new_data;
319
}
320

    
321
function get_interfacestatus() {
322
	$data = "";
323
	global $config;
324

    
325
	//build interface list for widget use
326
	$ifdescrs = get_configured_interface_with_descr();
327

    
328
	foreach ($ifdescrs as $ifdescr => $ifname){
329
		$ifinfo = get_interface_info($ifdescr);
330
		$data .= $ifname . ",";
331
		if($ifinfo['status'] == "up" || $ifinfo['status'] == "associated") {
332
			$data .= "up";
333
		}else if ($ifinfo['status'] == "no carrier") {
334
			$data .= "down";
335
		}else if ($ifinfo['status'] == "down") {
336
			$data .= "block";
337
		}
338
		$data .= ",";
339
		if ($ifinfo['ipaddr'])
340
			$data .= "<strong>" . htmlspecialchars($ifinfo['ipaddr']) . "</strong>";
341
		$data .= ",";
342
		if ($ifinfo['ipaddrv6'])
343
			$data .= "<strong>" . htmlspecialchars($ifinfo['ipaddrv6']) . "</strong>";
344
		$data .= ",";
345
		if ($ifinfo['status'] != "down")
346
			$data .= htmlspecialchars($ifinfo['media']);
347

    
348
		$data .= "~";
349

    
350
	}
351
	return $data;
352
}
353

    
354
?>
    (1-1/1)