#!/bin/sh
#
#
# A simple CheckMK local-plugin that checks some statistics of a JAVA JVM.
# Adapted from the Nagios-plugin, originally written by Eric Blanchard: https://github.com/Ericbla/check_jstat
#
# CMK adaption by: Michel Hoogervorst, august 18, 2014
# License: LGPL v2.1
#
# For this plugin to work, make sure you have the file /etc/check_mk/jstat.conf in this form:
# <label> <pidfile>
#
# So, if you were to monitor Tomcat, you could use:
# Tomcat /var/run/tomcat6.pid
#
# You can monitor multiple processes just by adding lines like that in the config file.
#

# Define jstat-command
jstat="/usr/bin/jstat";

# Warning/Critical levels
ws=85
cs=95


if [ ! -f /etc/check_mk/jstat.conf ]; then
  echo "Missing configuration file: /etc/check_mk/jstat.conf"
  exit 3
fi

cat /etc/check_mk/jstat.conf | while read label pidfile; do

  pid=$(cat $pidfile)


  if [ ! -d /proc/$pid ] ; then
    echo "2 jstat-$label - process pid[$pid] not found"
  fi

  gc=$($jstat -gc $pid | tail -1 | sed -e 's/[ ][ ]*/ /g')
  if [ -z "$gc" ]; then
    echo "2 jstat-$label - Can't get GC statistics"
  fi
  set -- $gc
  eu=$(expr "${6}" : '\([0-9]\+\)')
  ou=$(expr "${8}" : '\([0-9]\+\)')
  pu=$(expr "${10}" : '\([0-9]\+\)')

  gccapacity=$($jstat -gccapacity $pid | tail -1 | sed -e 's/[ ][ ]*/ /g')
  if [ -z "$gccapacity" ]; then
    echo "2 jstat-$label - Can't get GC capacity"
  fi

  set -- $gccapacity
  ygcmx=$(expr "${2}" : '\([0-9]\+\)')
  ogcmx=$(expr "${8}" : '\([0-9]\+\)')
  pgcmx=$(expr "${12}" : '\([0-9]\+\)')

  heap=$(($eu + $ou))
  heapmx=$(($ygcmx + $ogcmx))
  heapratio=$((($heap * 100) / $heapmx))
  permratio=$((($pu * 100) / $pgcmx))

  perfdata="heap=$[$heap/1024]|perm=$[$pu/1024]"

  if [ $cs -gt 0 -a $permratio -ge $cs ]; then
    echo "2 jstat-$label $perfdata jstat process $label ($pid) critical PermGen (${permratio}% of MaxPermSize)"
  fi
  if [ $cs -gt 0 -a $heapratio -ge $cs ]; then
    echo "2 jstat-$label $perfdata jstat process $label ($pid) critical Heap (${heapratio}% of MaxHeapSize)"
  fi

  if [ $ws -gt 0 -a $permratio -ge $ws ]; then
    echo "1 jstat-$label $perfdata jstat process $label ($pid) warning PermGen (${permratio}% of MaxPermSize)"
  fi
  if [ $ws -gt 0 -a $heapratio -ge $ws ]; then
    echo "1 jstat-$label $perfdata jstat process $label ($pid) warning Heap (${heapratio}% of MaxHeapSize)"
  fi
  echo "0 jstat-$label $perfdata jstat process $label ($pid) alive"

done
