#!/bin/bash
#
# Monitors memory usage in openVZ or Virtuozzo
# based on http://www.huschi.net/archiv/speicher-anzeigen-mit-vzfree.html
# Author: Michael Richter, http://osor.de/ 
# Cleaned up and translated to english by: Marian Sigler <m@qjym.de>, 2010-08-13
#
#%# capabilities=autoconf

BEANCOUNTERS=/proc/user_beancounters

if [ "$1" == "autoconf" ]; then
    if [ -e $BEANCOUNTERS ]; then
        echo yes
        exit 0
    else
        echo no
        exit 1
    fi
fi

if [ ! -r $BEANCOUNTERS ]; then
    echo "$BEANCOUNTERS not readable" >&2
    exit 1
fi

if [ "$1" == "config" ]; then
    limit=$(awk '/privvmpages/ {print $5*4096}' $BEANCOUNTERS)
    cut -c9- <<EOF
        graph_args --base 1024 -l 0 --vertical-label bytes --upper-limit $limit
        graph_title VPS memory usage
        graph_category system
        graph_info Shows memory usage and VPS memory limits.
        graph_order maxheld held oomguar barrier limit

        held.label held
        held.draw AREA
        held.info currently held memory
        maxheld.label maxheld
        maxheld.draw AREA
        maxheld.info maximum held memory
        oomguar.label guaranteed
        oomguar.draw LINE2
        oomguar.info memory guaranteed for OOM
        barrier.label barrier
        barrier.draw LINE2
        barrier.info memory usage barrier
        limit.label limit
        limit.draw LINE2
        limit.info memory usage limit
EOF
    exit 0
fi

if [ -n "$1" ]; then
    echo "Invalid argument: $1" >&2
    exit 1
fi




awk '/privvmpages/ {print "held.value", $2*4096 "\nmaxheld.value", $3*4096 "\nbarrier.value", $4*4096 "\nlimit.value", $5*4096}' $BEANCOUNTERS
awk '/oomguarpages/ { print "oomguar.value", $4*4096 }' $BEANCOUNTERS
