#!/usr/local/bin/perl 
#    Checks if a PostgreSQL-server is online
#    Copyright (c) 2000 Mark van Eijk <mark@luon.net>

#    Notes:
#    Make sure that the remote host accepts PostgreSQL-connections to 
#    the 'template1' database from the host this plugin runs on.

#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# use strict here to ensure 'decent' coding
use strict;
use Getopt::Std;
# added for database interfacing
use DBI;
use DBD::Pg;

# if extra options are needed add them in the next few lines
# use the $opt_? syntax
use vars qw($opt_p $opt_t $opt_h);

getopts("p:t:h:");
# standard port for PostgreSQL is 5432
my $port = $opt_p || 5432;
my $TIMEOUT = $opt_t || 5;
my $host = $opt_h || "localhost";

exit &serviceGET($host, $port, $TIMEOUT);

sub serviceGET
{
  my ($server, $port, $serviceTIMEOUT) = @_;
  # return failure status code by default
  my $serviceOK = 1;

  eval
  {
    # set timeout alarm
    local $SIG{ALRM} = sub { die "Timeout Alarm" };
    alarm $serviceTIMEOUT;

    # load PostgreSQL database driver
    my $psqlDriverHandle = DBI->install_driver("Pg");
    # connect to 'template1' database on PostgreSQL server
    my $psqlDatabaseHandle = DBI->connect("dbi:Pg:dbname=template1;host=$server;port=$port", "", "");
    # check validity of database handle
    my $psqlPingResult = $psqlDatabaseHandle->ping;
    # disconnect from PostgreSQL server
    $psqlDatabaseHandle->disconnect;

    # cancel alarm
    alarm 0;

    if ($psqlPingResult)
    {
      # change status code to OK
      $serviceOK = 0;
    }
  };

  #check for timeout
  if ($@ and ($@ =~ /Timeout Alarm/))
  {
    # change status code to TIMEOUT
    $serviceOK = 2;
  }

  # exit with service status code
  return $serviceOK;
}



syntax highlighted by Code2HTML, v. 0.9.1