#!/bin/sh
#
# Script for monitoring nginx Virtual host output traffic
#
# Requierements: logtail awk
# one unique access log file with $bytes_sent value for more accuracy
# check http://wiki.nginx.org/NginxHttpLogModule
#
# Configuration Options (all options have defaults)
# [nginx_vhost_traffic]
#
# Virtual host list
# env.vhosts "example.com example.net example.org"
#
# Log path
# env.logdir = /var/log/nginx
# env.flogfile = access.log
#
# Position of the $bytes_sent in the access.log file
# env.bparam 11
#
# Aggregate subdomains
# ex: example.com will match www.example.com, webmail.example.com and *example.com
# BUG: will also match also www.bad-example.com
# env.aggregate true #change to false to disable aggregation
#
# To report bugs, improvements or get updates
# see http://github.com/joanpc/nginix_vhost_traffic
#
# inspired in postfix_filtered_awk
# Copyright (c) 2010, Joan Perez i Cauhe

LOGDIR=${logdir:-/var/log/nginx}
ACCESS_LOG=$LOGDIR/${logfile:-access.log}
LOGTAIL=${logtail:-`which logtail`}
STATEFILE=$MUNIN_PLUGSTATE/nginx_vhost_traffic.state
VHOSTS=${vhosts:-`hostname`}
AGGREGATE=${aggregate:true}

BPARAM=${bparam:-11}

case $1 in
   config)
   	DRAW=AREA
	echo 'graph_title Nginx Virtual host traffic'
	echo 'graph_vlabel bits out / ${graph_period}'
	echo 'graph_args --base 1000 -l 0'
	echo 'graph_category webserver'

	i=0
	for vhost in $VHOSTS
	do
		i=$(($i + 1))
		echo vhost$i.label $vhost
		echo vhost$i.type ABSOLUTE
		echo vhost$i.cdef vhost$i,8,*
		echo vhost$i.draw $DRAW
		DRAW=STACK
	done

	echo rest.label Rest
	echo rest.type ABSOLUTE
	echo rest.cdef rest,8,*
	echo rest.draw STACK
    exit 0;;
esac

export BPARAM
export VHOSTS
export AGGREGATE

# Awk Script
$LOGTAIL ${ACCESS_LOG} -o $STATEFILE | awk '

BEGIN {
split(ENVIRON["VHOSTS"], hosts)
for (host in hosts) { track[hosts[host]] = host}
}
{
		cn[$2]+=$ENVIRON["BPARAM"]
}
END {
		for (host in cn) {
		if (match(ENVIRON["AGGREGATE"], "true")) {
			found = 0
			for (vhost in track) {
				if (index(host, vhost)) {
				res[vhost] += cn[host]
				found = 1
				break
				}
			}
			if (! found) rest+=cn[host]
		} else {
			if (host in track) {
				res[host] += cn[host]
			} else rest+=cn[host]
		}
		}
		print "aggregate: " ENVIRON["AGGREGATE"]
		for (vhost in track) print "vhost" track[vhost] ".value " res[vhost]+0
		print "rest.value " rest + 0
}'
