#!/usr/local/bin/php
<?php
	# check_influx - Plugin for monitoring uWSGI Emperor vassal states with Nagios and Influx LP output formats
	# version 1.0   19.06.2016
	# by Mikanoshi - iam@mikanoshi.name, http://code.highspec.ru/Mikanoshi/check_uwsgi
	#
	# 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("s:im:");

	if (isset($options["s"]))
		$socketpath = $options["s"];
	else
		usage();

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

	$socket = fsockopen("unix://".$socketpath);
	while ($resp = fread($socket, 512)) {
		if (trim($resp) == '') break;
		$json .= $resp;
	}
	fclose($socket);

	$data = json_decode($json);
	$out = Array();
	$status = 0;
	if (count($data->vassals) == 0) {
		$status = 3;
	} else foreach ($data->vassals as $vassal) {
		$out[] = Array(str_replace(Array('.uwsgi.ini','.ini'), Array('',''), $vassal->id), $vassal->accepting, $vassal->loyal, $vassal->ready, $vassal->cursed);
		if (intval($vassal->accepting) !== 1) $status = 2;
	}

	if ($isinflux) $status = 0;
	else if ($status == 0) echo "OK - ";
	else if ($status == 1) echo "WARNING - ";
	else if ($status == 2) echo "CRITICAL - ";
	else if ($status == 3) echo "UNKNOWN\n";

	if ($status < 3) {
		foreach ($out as $point) {
			$tmp .= $isinflux ? $measurement.",vassal=".$point[0]." accepting=".$point[1].",loyal=".$point[2].",ready=".$point[3].",cursed=".$point[4]." ".$timestamp."\n"
				 : $point[0]." is ".(intval($point[1]) == 1 ? "accepting" : "NOT accepting" ).", ";
			$tmp2 .= $point[0]."_accepting=".$point[1]."; ";
		}
		echo $isinflux ? $tmp : rtrim($tmp, ', ')." | ".$tmp2."\n";
	}
	exit($status);

	function usage() {
		echo "Usage: check_uwsgi -s <path to emperor-stats socket> [-i] [-m measurement]
Optional parameters
	-i	Influx Line Protocol output format instead of nagios
	-m	Measurement name (\"uwsgi\" by default)
Example: check_uwsgi -s /tmp/uwsgistats.sock -i -m uwsgistats\n";
		exit(1);
	}
?>