#!/bin/sh
#
# Plugin to monitor CPU usage, for a selected systemd unit
#
# Usage: Place in /usr/local/etc/munin/plugins/ (or link it there  using ln -s)
#        Add this to your /ur/local/etc/munin/plugin-conf.d/plugins.conf:
#       [cpu-usage-by-unit]
#       env.units apache2 nginx mysqld
#
#    apache2, nginx and mysqld being a list of the units to monitor

#
# Parameters understood:
#
#       config   (required)
#       autoconf (optional - used by munin-config)
#

#%# family=auto
#%# capabilities=autoconf

if [ "$1" = "autoconf" ] ; then 
	if [ -n "$units" ] ; then
		echo "yes"
	else
		echo "\$units not defined."
	fi
	exit
fi

if [ "$1" = "config" ] ; then
	cpucores=`nproc --all`
	allcputime=$((cpucores * 60))
	echo "graph_args --base 1000 -r --lower-limit 0";
	echo "graph_title CPU time used by unit";
	echo "graph_category system";
	echo "graph_info This graph shows CPU time used by monitored systemd units.";
	echo 'graph_vlabel CPUsec/min'
	echo 'graph_scale no'
	echo 'graph_period minute'

	echo "graph_order $units"

	FIRSTUNIT=1;
	for unit in $units; do
		echo "${unit}.label $unit"
		echo "${unit}.info CPU used by unit $unit"
		echo "${unit}.type DERIVE"
		echo "${unit}.max ${allcputime}"
		echo "${unit}.min 0"
		if [ $FIRSTUNIT -eq 1 ] ; then
			echo "${unit}.draw AREA"
			export FIRSTUNIT=0;
		else
			echo "${unit}.draw STACK"
		fi
	done ;
	exit
fi


for unit in $units ; do {

	echo -n "${unit}.value "
	nval=`systemctl show ${unit} | grep '^CPUUsageNSec' | grep -oe '[0-9]*'`
	echo $((nval / 1000000000))

}

done;
