#!/bin/bash
#
# Created by Jan Rękorajski <baggins@pld-linux.org> based on vserver_cpu_ plugin.
#
# Graph Vserver cumulative cpu usage stats
#
# Configuration variables
#   vservers - specify the vservers to include in the graph (default: all)
#
# NOTE: If no configuration variable is set, the default will be used
#
# see vserver_resources for example uses of configuration files

VSERVERS="$vservers"

INFO=(`sed 's/.*:\t//' /proc/virtual/info 2>/dev/null || echo '<none>'`)
KCIN="$[ 16#${INFO[2]} ]";

# If this is 1, then VCI_SPACES is present in the kernel (new in 2.6.19)
if [ $[ (KCIN >> 10) & 1 ] -eq 1 ]
then 
    NAMELOC="nsproxy"
else 
    NAMELOC="cvirt"
fi

if [ -z "$VSERVERS" ] ; then
    XIDS=`find /proc/virtual/* -type d -exec basename {} \;`
else
    # it's really more performant to specify vservers by ids or by linking but not in the configuration-file by name
    XIDS=""
    for i in $VSERVERS ; do
	if [ -d /proc/virtual/$i ] ; then
	    XIDS="${XIDS}${i} "
	else
	    for j in `find /proc/virtual/* -type d -exec basename {} \;` ; do
		if [ "$i" = "`cat /proc/virtual/$j/$NAMELOC |grep NodeName |cut -f2`" ] ; then
		    XIDS="${XIDS}${j} "
		fi
	    done
	fi
    done
fi

if [ "$1" = "config" ]; then
	echo 'graph_category vserver'
	echo 'graph_args --base 1000'
	echo 'graph_title Vserver cpu usage'
	echo 'graph_vlabel jiffies used per ${graph_period}'
	echo 'graph_info Shows jiffies used on each vserver.'

	for i in $XIDS ; do 
		LABEL=`grep NodeName /proc/virtual/$i/$NAMELOC | cut -f2`
		NAME=`echo $LABEL | tr '-' '_'`
		echo "${NAME}_hold.label on hold for cpu on $LABEL"
		echo "${NAME}_hold.info on hold for cpu on $LABEL."
		echo "${NAME}_hold.type COUNTER"
		echo "${NAME}_scpu.label system cpu usage for $LABEL"
		echo "${NAME}_scpu.info system cpu usage for $LABEL."
		echo "${NAME}_scpu.type COUNTER"
		echo "${NAME}_ucpu.label user cpu usage for $LABEL"
		echo "${NAME}_ucpu.info user cpu usage for $LABEL."
		echo "${NAME}_ucpu.type COUNTER"
	done
	exit 0
fi

for i in $XIDS ; do
	NAME=`grep NodeName /proc/virtual/$i/$NAMELOC | cut -f2 | tr '-' '_'`
	awk -v name=$NAME -v u=0 -v s=0 -v h=0 '
		/^cpu [0-9]+:/ { u+=$3; s+=$4; h+=$5}
		END {
			print name "_hold.value " h
			print name "_scpu.value " s
			print name "_ucpu.value " u
		}' /proc/virtual/$i/sched
done
