stats.inc 8.63 KB
Newer Older
1
<?php
Ad Schellevis's avatar
Ad Schellevis committed
2 3

require_once("config.inc");
4
require_once("filter.inc");
5
require_once("pfsense-utils.inc");
6
require_once("interfaces.inc");
Ad Schellevis's avatar
Ad Schellevis committed
7

8 9 10 11 12 13 14 15 16 17 18 19 20
function get_uptime_sec() {
        $boottime = "";
        $matches = "";
        $boottime = get_single_sysctl("kern.boottime");
        preg_match("/sec = (\d+)/", $boottime, $matches);
        $boottime = $matches[1];
        if(intval($boottime) == 0)
                return 0;

        $uptime = time() - $boottime;
        return $uptime;
}

Ad Schellevis's avatar
Ad Schellevis committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
function get_stats() {
	$stats['cpu'] = cpu_usage();
	$stats['mem'] = mem_usage();
	$stats['uptime'] = get_uptime();
	$stats['states'] = get_pfstate();
	$stats['temp'] = get_temp();
	$stats['datetime'] = update_date_time();
	$stats['interfacestatistics'] = get_interfacestats();
	$stats['interfacestatus'] = get_interfacestatus();
	$stats['gateways'] = get_gatewaystats();
	$stats['cpufreq'] = get_cpufreq();
	$stats['load_average'] = get_load_average();
	$stats['mbuf'] = get_mbuf();
	$stats['mbufpercent'] = get_mbuf(true);
	$stats['statepercent'] = get_pfstate(true);
	$stats = join("|", $stats);
	return $stats;
}

function get_gatewaystats() {
	$a_gateways = return_gateways_array();
	$gateways_status = array();
	$gateways_status = return_gateways_status(true);
	$data = "";
	$isfirst = true;
	foreach($a_gateways as $gname => $gw) {
		if(!$isfirst)
			$data .= ",";
		$isfirst = false;
		$data .= $gw['name'] . ",";
		if ($gateways_status[$gname]) {
			$data .= lookup_gateway_ip_by_name($gname) . ",";
			$gws = $gateways_status[$gname];
			switch(strtolower($gws['status'])) {
			case "none":
				$online = "Online";
				$bgcolor = "#90EE90";  // lightgreen
				break;
			case "down":
				$online = "Offline";
				$bgcolor = "#F08080";  // lightcoral
				break;
			case "delay":
				$online = "Latency";
				$bgcolor = "#F0E68C";  // khaki
				break;
			case "loss":
				$online = "Packetloss";
				$bgcolor = "#F0E68C";  // khaki
				break;
			default:
				$online = "Pending";
				break;
			}
		} else {
			$data .= "~,";
			$gws['delay'] = "~";
			$gws['loss'] = "~";
			$online = "Unknown";
			$bgcolor = "#ADD8E6";  // lightblue
		}
		$data .= ($online == "Pending") ? "{$online},{$online}," : "{$gws['delay']},{$gws['loss']},";
		$data .= "<table border=\"0\" cellpadding=\"0\" cellspacing=\"2\" style=\"table-layout: fixed;\" summary=\"status\"><tr><td bgcolor=\"$bgcolor\">&nbsp;$online&nbsp;</td></tr></table>";
	}
	return $data;
}

function get_uptime() {
	$uptime = get_uptime_sec();

	if(intval($uptime) == 0)
		return;

	$updays = (int)($uptime / 86400);
	$uptime %= 86400;
	$uphours = (int)($uptime / 3600);
	$uptime %= 3600;
	$upmins = (int)($uptime / 60);
	$uptime %= 60;
	$upsecs = (int)($uptime);

	$uptimestr = "";
	if ($updays > 1)
		$uptimestr .= "$updays Days ";
	else if ($updays > 0)
		$uptimestr .= "1 Day ";

Ad Schellevis's avatar
Ad Schellevis committed
108
	if ($uphours > 1) {
Ad Schellevis's avatar
Ad Schellevis committed
109
		$hours = "s";
Ad Schellevis's avatar
Ad Schellevis committed
110 111 112
	} else {
		$hours = "";
	}
Ad Schellevis's avatar
Ad Schellevis committed
113

Ad Schellevis's avatar
Ad Schellevis committed
114
	if ($upmins > 1) {
Ad Schellevis's avatar
Ad Schellevis committed
115
		$minutes = "s";
Ad Schellevis's avatar
Ad Schellevis committed
116 117 118
	} else {
		$minutes = "" ;
	}
Ad Schellevis's avatar
Ad Schellevis committed
119

Ad Schellevis's avatar
Ad Schellevis committed
120
	if ($upmins > 1) {
Ad Schellevis's avatar
Ad Schellevis committed
121
		$seconds = "s";
Ad Schellevis's avatar
Ad Schellevis committed
122 123 124
	} else {
		$seconds = "";
	}
Ad Schellevis's avatar
Ad Schellevis committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

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

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

	$totalStart = array_sum($cpuTicks);
	$totalEnd = array_sum($cpuTicks2);

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

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

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

	return $cpuUsage;
}

function get_pfstate($percent=false) {
	global $config;
	$matches = "";
	if (isset($config['system']['maximumstates']) and $config['system']['maximumstates'] > 0)
		$maxstates="{$config['system']['maximumstates']}";
	else
160
		$maxstates=default_state_size();
Ad Schellevis's avatar
Ad Schellevis committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
	$curentries = `/sbin/pfctl -si |grep current`;
	if (preg_match("/([0-9]+)/", $curentries, $matches)) {
		$curentries = $matches[1];
	}
	if (!is_numeric($curentries))
		$curentries = 0;
	if ($percent)
		if (intval($maxstates) > 0)
			return round(($curentries / $maxstates) * 100, 0);
		else
			return "NA";
	else
		return $curentries . "/" . $maxstates;
}

function get_mbuf($percent=false) {
	$mbufs_output=trim(`/usr/bin/netstat -mb | /usr/bin/grep "mbuf clusters in use" | /usr/bin/awk '{ print $1 }'`);
	list( $mbufs_current, $mbufs_cache, $mbufs_total, $mbufs_max ) = explode( "/", $mbufs_output);
	if ($percent)
		if ($mbufs_max > 0)
			return round(($mbufs_total / $mbufs_max) * 100, 0);
		else
			return "NA";
	else
		return "{$mbufs_total}/{$mbufs_max}";
}

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

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

/* Get mounted filesystems and usage. Do not display entries for virtual filesystems (e.g. devfs, nullfs, unionfs) */
function get_mounted_filesystems() {
	$mout = "";
	$filesystems = array();
201
	exec("/bin/df -Tht ufs,tmpfs,zfs,cd9660 | /usr/bin/awk '{print $1, $2, $3, $4, $6, $7;}'", $mout);
Ad Schellevis's avatar
Ad Schellevis committed
202 203 204 205 206

	/* Get rid of the header */
	array_shift($mout);
	foreach ($mout as $fs) {
		$f = array();
207
		list($f['device'], $f['type'], $f['total_size'], $f['used_size'], $f['percent_used'], $f['mountpoint']) = explode(' ', $fs);
Ad Schellevis's avatar
Ad Schellevis committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

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

		$filesystems[] = $f;
	}
	return $filesystems;
}


function swap_usage() {
	exec("/usr/sbin/swapinfo", $swap_info);
	$swap_used = "";
	foreach ($swap_info as $line)
		if (preg_match('/(\d+)%$/', $line, $matches)) {
			$swap_used = $matches[1];
			break;
		}

	return $swap_used;
}

function mem_usage() {
	$totalMem = get_single_sysctl("vm.stats.vm.v_page_count");
	if ($totalMem > 0) {
		$inactiveMem = get_single_sysctl("vm.stats.vm.v_inactive_count");
		$cachedMem = get_single_sysctl("vm.stats.vm.v_cache_count");
		$freeMem = get_single_sysctl("vm.stats.vm.v_free_count");
		$usedMem = $totalMem - ($inactiveMem + $cachedMem + $freeMem);
		$memUsage = round(($usedMem * 100) / $totalMem, 0);
	} else
		$memUsage = "NA";

	return $memUsage;
}

244

Ad Schellevis's avatar
Ad Schellevis committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
function update_date_time() {
	$datetime = date("D M j G:i:s T Y");
	return $datetime;
}

function get_cpufreq() {
	$cpufreqs = "";
	$out = "";
	$cpufreqs = explode(" ", get_single_sysctl('dev.cpu.0.freq_levels'));
	$maxfreq = explode("/", $cpufreqs[0]);
	$maxfreq = $maxfreq[0];
	$curfreq = "";
	$curfreq = get_single_sysctl('dev.cpu.0.freq');
	if (($curfreq > 0) && ($curfreq != $maxfreq))
		$out = "Current: {$curfreq} MHz, Max: {$maxfreq} MHz";
	return $out;
}

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

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

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

280 281
function get_interfacestats()
{
Ad Schellevis's avatar
Ad Schellevis committed
282 283
	$ifdescrs = get_configured_interface_list();
	$array_collisions = array();
284
	$new_data = '';
Ad Schellevis's avatar
Ad Schellevis committed
285

286
	foreach ($ifdescrs as $ifdescr => $ifname) {
Ad Schellevis's avatar
Ad Schellevis committed
287
		$ifinfo = get_interface_info($ifdescr);
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
		$new_data .= "{$ifinfo['inpkts']},";
		$new_data .= "{$ifinfo['outpkts']},";
		$new_data .= format_bytes($ifinfo['inbytes']) . ",";
		$new_data .= format_bytes($ifinfo['outbytes']) . ",";
		if (isset($ifinfo['inerrs'])){
			$new_data .= "{$ifinfo['inerrs']},";
			$new_data .= "{$ifinfo['outerrs']},";
		} else {
			$new_data .= "0,";
			$new_data .= "0,";
		}
		if (isset($ifinfo['collisions'])) {
			$new_data .= htmlspecialchars($ifinfo['collisions']) . ",";
		} else {
			$new_data .= "0,";
		}
	}
Ad Schellevis's avatar
Ad Schellevis committed
305 306 307 308

	return $new_data;
}

309 310
function get_interfacestatus()
{
Ad Schellevis's avatar
Ad Schellevis committed
311
	$ifdescrs = get_configured_interface_with_descr();
312
	$data = '';
Ad Schellevis's avatar
Ad Schellevis committed
313

314
	foreach ($ifdescrs as $ifdescr => $ifname) {
Ad Schellevis's avatar
Ad Schellevis committed
315 316
		$ifinfo = get_interface_info($ifdescr);
		$data .= $ifname . ",";
317
		if ($ifinfo['status'] == "up" || $ifinfo['status'] == "associated") {
Ad Schellevis's avatar
Ad Schellevis committed
318
			$data .= "up";
319
		} elseif ($ifinfo['status'] == "no carrier") {
Ad Schellevis's avatar
Ad Schellevis committed
320
			$data .= "down";
321
		} elseif ($ifinfo['status'] == "down") {
Ad Schellevis's avatar
Ad Schellevis committed
322 323 324
			$data .= "block";
		}
		$data .= ",";
325
		if ($ifinfo['ipaddr']) {
Ad Schellevis's avatar
Ad Schellevis committed
326
			$data .= htmlspecialchars($ifinfo['ipaddr']);
327
		}
Ad Schellevis's avatar
Ad Schellevis committed
328
		$data .= ",";
329
		if ($ifinfo['status'] != "down") {
Ad Schellevis's avatar
Ad Schellevis committed
330
			$data .= htmlspecialchars($ifinfo['media']);
331
		}
Ad Schellevis's avatar
Ad Schellevis committed
332 333 334 335
		$data .= "~";
	}
	return $data;
}