#!/usr/local/bin/php
<?php
	# check_nginx_vhost - Plugin for monitoring Nginx vhost requests with Nagios and Influx LP output formats
	# version 1.0   15.07.2016
	# by Mikanoshi - iam@mikanoshi.name, http://code.highspec.ru/Mikanoshi/check_nginx_vhost
	#
	# Requires ngx_http_vhost_traffic_status_module (compiled statically or as a dynamic module)
	# https://github.com/vozlt/nginx-module-vts
	#
	# 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:z:tim:");

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

	$myzones = isset($options["z"]) ? explode(",", $options["z"]) : false;
	if ($myzones) $myzones[] = "*";
	$istotal = isset($options["t"]) ? true : false;
	$isinflux = isset($options["i"]) ? true : false;
	$measurement = isset($options["m"]) ? $options["m"] : "nginxvhost";
	$timestamp = time() * 1000000000;

	$json = file_get_contents($url);
	$data = json_decode($json);
	$out = Array();
	$status = 0;
	if ($json == '' or !$data) {
		$status = 3;
	} else {
		foreach ($data->serverZones as $zone=>$stats) {
			if (!$myzones || in_array($zone, $myzones)) {
				if ($zone == "*" && !$istotal) continue;
				if ($zone == "*") $zone = "total";
				$out[$zone] = $stats->requestCounter;
			}
		}
	}

	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) {
		if (!$isinflux) echo " | ";
		foreach ($out as $zone=>$stat)
		echo $isinflux ? $measurement.",zone=".$zone." reqs=".$stat." ".$timestamp."\n" : $zone."_reqs=".$stat."; ";
		if (!$isinflux) echo "\n";
	}
	exit($status);

	function usage() {
		echo "Usage: check_nginx_vhost -u <url to json formatted vhost stats> [-z <domain.com,example.org,...>] [-t] [-i] [-m measurement]
Optional parameters
	-z	Comma-separated list of zones (vhosts), display all if not specified
	-t	Include total request count
	-i	Influx Line Protocol output format instead of nagios
	-m	Measurement name (\"nginxvhost\" by default)
Example: check_nginx_vhost -u \"http://example.com/status/format/json\" -z one.com,two.com -i -m myvhosts\n";
		exit(1);
	}
?>