#!/usr/bin/perl
# -*- perl -*-
#
# Show postgres lock statistics
#
# Parameters:
# 	
# 	config
# 	autoconf
#
# Configuration variables:
#
#	PGHOST		- Database server to use. Defaults to using ident
#			  authentication with the local server.
#	PGPORT		- Port to connect to. Defaults to '5432'.
#	PGDATABASE	- Database to connect to. Defaults to 'template1'.
#	PGUSER		- User to connect as, if necessary.
#	PGPASSWORD	- Corresponding password to use, if necessary.
#
#	(See libpq documentation for more.)
#	Note that PGDATABASE will default to 'template1' in this plugin, and
#	without PGHOST it will try ident authentication with the local server,
#	as the user that the plugin is running as.
#
# Configuration example:
#
#	# Use local server, ident authentication with the 'postgres' user.
#	[postgres_*]
#	user postgres
#
#	# Use local server, TCP authentication with a username and password.
#	[postgres_*]
#	env.PGHOST localhost
#	env.PGUSER someuser
#	env.PGPASSWORD somepassword
#
# Magic markers
#%# family=auto
#%# capabilities=suggest

use strict;
use warnings;
use DBI;

# Default to template1 database.
$ENV{'PGDATABASE'} ||= 'template1';

if ($ARGV[0] && $ARGV[0] eq "config") {
    print <<EOF;
graph_title Postgres locks
graph_args --base 1000
graph_vlabel Locks
graph_category PostgreSQL
graph_info Shows PostgreSQL locks
locks.label Locks
locks.info Locks (more info here, please... :)
locks.type GAUGE
locks.warning 5
locks.critical 10
exlocks.label Exclusive locks
exlocks.info Exclusive locks (here too, please... :)
exlocks.type GAUGE
exlocks.warning 5
exlocks.critical 10
EOF
} else {
    my $dbh = DBI->connect ('dbi:Pg:', '', '', {RaiseError =>1})
        || die "Unable to access database.\nError returned was: ". $DBI::errstr;

    my $sql="SELECT mode,COUNT(mode) FROM pg_locks GROUP BY mode ORDER BY mode;";
    my $sth = $dbh->prepare ($sql);
    $sth->execute ();
    my $locks = 0;
    my $exlocks = 0;
    while (my ($mode, $count) = $sth->fetchrow ()) {
	if ($mode =~ /exclusive/i) {
	    $exlocks = $exlocks + $count;
	}
	$locks = $locks+$count;
    }
    print "locks.value $locks\n";
    print "exlocks.value $exlocks\n";
}
