#!/bin/bash
#
# Plugin to monitor PostgreSQL Backends
#
# Author:
#    Guilherme Augusto da Rocha Silva <gars.dba@gmail.com>
#
# Created:
#    5th of november 2007
#
# Usage:
#    Place in /etc/munin/plugins/ (or link it there using ln -s)
#
# Parameters:
#    config   (required)
#
# General info:
#    Require permission for database access and read (no writes are processed).
#    Recommended user is PostgreSQL database owner (default: postgres).
#
# Log info:
# 2007/11/30 - Review on comments
# 2012/12/19 - Updated to connect locally instead of localhost by default
#              (PostgreSQL has different permissions for these).
#

dbserver='' #'-h hostname'
dbuser='postgres'

if [ "$1" = "config" ]; then
   maximum=$(psql ${dbserver} -U ${dbuser} -tc "SHOW max_connections;" | bc)
   reserved=$(psql ${dbserver} -U ${dbuser} -tc "SHOW superuser_reserved_connections;" | bc)
   warning=$(((maximum-reserved)*70/100))
   critical=$(((maximum-reserved)*90/100))
   echo 'graph_args --base 1000 --lower-limit 0 --upper-limit '${maximum}
   echo 'graph_category db'
   echo 'graph_info Shows open backends on the PostgreSQL Server.'
   echo 'graph_scale no'
   echo 'graph_title PostgreSQL Active Backends'
   echo 'graph_vlabel Number of active backends'
   echo 'backends.label backends'
   echo 'backends.type GAUGE'
   echo 'backends.min 0'
   echo 'backends.max '${maximum}
   echo 'backends.warning '${warning}
   echo 'backends.critical '${critical}
   echo 'backends.info Number of open sessions.'
   exit 0
fi

echo 'backends.value '$(psql ${dbserver} -U ${dbuser} -tc "SELECT SUM(numbackends) FROM pg_stat_database;" | bc)
