#! /bin/sh
# Multigraph CPU plugin
# It shows a global cpu graph, and you can drill down per-core

PLUGINBASE=$(basename $0)

emit_config()
{
cat <<EOF
graph_title CPU usage $1
graph_order system user nice idle iowait irq softirq
graph_vlabel %
graph_scale no
graph_info This graph shows how CPU time is spent.
graph_category system
graph_period second
system.label system
system.draw AREA
system.min 0
system.type DERIVE
system.info CPU time spent by the kernel in system activities
user.label user
user.draw STACK
user.min 0
user.type DERIVE
user.info CPU time spent by normal programs and daemons
nice.label nice
nice.draw STACK
nice.min 0
nice.type DERIVE
nice.info CPU time spent by nice(1)d programs
idle.label idle
idle.draw STACK
idle.min 0
idle.type DERIVE
idle.info Idle CPU time
iowait.label iowait
iowait.draw STACK
iowait.min 0
iowait.type DERIVE
iowait.info CPU time spent waiting for I/O operations to finish when there is nothing else to do.
irq.label irq
irq.draw STACK
irq.min 0
irq.type DERIVE
irq.info CPU time spent handling interrupts
softirq.label softirq
softirq.draw STACK
softirq.min 0
softirq.type DERIVE
softirq.info CPU time spent handling "batched" interrupts
steal.label steal
steal.draw STACK
steal.min 0
steal.type DERIVE
steal.info The time that a virtual CPU had runnable tasks, but the virtual CPU itself was not running
guest.label guest
guest.draw STACK
guest.min 0
guest.type DERIVE
guest.info The time spent running a virtual CPU for guest operating systems under the control of the Linux kernel.
guest_nice.label guest
guest_nice.draw STACK
guest_nice.min 0
guest_nice.type DERIVE
guest_nice.info The time spent running a virtual CPU for niced guest operating systems under the control of the Linux kernel.
EOF
}

CPUS=$(grep '^cpu[0-9]' /proc/stat | cut -d ' ' -f 1)

if [ "$1" = "config" ]
then
	echo multigraph $PLUGINBASE
	emit_config
	# Emit one subgraph per core
	for cpu in $CPUS
	do
		echo multigraph $PLUGINBASE.$cpu
		emit_config $cpu
	done

	exit 0
fi

emit_values()
{
	while read key user nice system idle iowait irq softirq steal guest guest_nice
	do
		[ "$guest_nice" = "" ] && guest_nice=0
		[ "$key" != "$1" ] && continue
		cat <<EOF
system.value $system
user.value $user
nice.value $nice
idle.value $idle
iowait.value $iowait
irq.value $irq
softirq.value $softirq
steal.value $steal
guest.value $guest
guest_nice.value $guest_nice
EOF
	done < /proc/stat
}

# Values
echo multigraph $PLUGINBASE
emit_values cpu

# Emit one subgraph per core
for cpu in $CPUS
do
	echo multigraph $PLUGINBASE.$cpu
	emit_values $cpu
done

exit 0
