#!/usr/local/bin/php
<?php
	# check_influx - Plugin for monitoring the PHP OPCache with Nagios and Influx LP output formats
	# version 1.0   19.06.2016
	# by Mikanoshi - iam@mikanoshi.name, http://code.highspec.ru/Mikanoshi/check_phpopcache
	#
	# This plugin is a free software and comes with ABSOLUTELY NO WARRANTY.
	# It may be used, redistributed and/or modified under the terms of the
	# GNU General Public Licence Version 3 (see https://www.gnu.org/licenses/gpl.txt).

	$options = getopt("U:w:c:im:");

	if (isset($options["U"]))
		$url = $options["U"];
	else
		usage();

	if (isset($options["w"]))
	        $used_pct_warn = $options["w"];
	else
	        $used_pct_warn = "";

	if (isset($options["c"]))
	        $used_pct_crit = $options["c"];
	else
	        $used_pct_crit = "";

	$isinflux = isset($options["i"]) ? true : false;
	$measurement = isset($options["m"]) ? $options["m"] : "opcache";
	$timestamp = time() * 1000000000;

	$status = 3;

	$f = explode("\r\n", file_get_contents($url));
	$used = $f[0];
	$free = $f[1];
	$hits_pct = $f[2];
	$miss_pct = $f[3];

	$used_pct = round($used/($used + $free) * 100, 1);
	if ($used_pct_crit !== "" && $used_pct >= $used_pct_crit)
		$status = 2;
	else if ($used_pct_warn !== "" && $used_pct >= $used_pct_warn)
		$status = 1;
	else
		$status = 0;

	if ($isinflux)
		$out = $measurement." used_pct=".$used_pct.",hit_pct=".$hits_pct.",miss_pct=".$miss_pct." ".$timestamp;
	else
		$out = $used_pct."% cache used | used_pct=".$used_pct."%;".$used_pct_warn.";".$used_pct_crit." hit_pct=".$hits_pct."%; miss_pct=".$miss_pct."%;";

	if ($isinflux) $status = 0;
	else if ($status == 0) echo "OK - ";
	else if ($status == 1) echo "WARNING - ";
	else echo "CRITICAL - ";
	echo $out."\n";

	exit($status);

	function usage() {
		echo "Usage: check_phpopcache -U <full URL to opcache.php> [-w 80] [-c 90] [-i] [-m measurement]
Optional parameters
	-w	Warning level for Nagios format
	-c	Critical level for Nagios format
	-i	Influx Line Protocol output format instead of nagios
	-m	Measurement name (\"opcache\" by default)
Example: check_phpopcache -U http://domain.com/opcache.php -w 75 -c 85\n";
		exit(3);
	}
?>