check_nagios_db_pg.pl 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/perl -w
  2. use strict;
  3. $|++;
  4. use vars qw/$opt_e $opt_c/;
  5. $ENV{"PATH"} = "/usr/bin:/usr/sbin:/bin";
  6. use Getopt::Std;
  7. use DBI;
  8. my $driver = "Pg";
  9. my $CFG_DEF = "/etc/nagios/cgi.cfg";
  10. # this works only in mysql
  11. # my $QUERY = "select *, UNIX_TIMESTAMP(last_update) as ut from programstatus;";
  12. # the following is the same for postgres
  13. my $QUERY = "select *, round(date_part('epoch',last_update)) as ut from programstatus;";
  14. my $EXPIRE_DEF = 5; ## expressed in minutes
  15. my $PROCCNT = 0;
  16. use constant OK => 1;
  17. use constant WARN => 2;
  18. my $STAT = WARN;
  19. sub usage {
  20. print STDERR "\n";
  21. print STDERR "$0 -F -e <expire time in minutes> -C <process string>\n";
  22. print STDERR "\n";
  23. exit -1;
  24. }
  25. getopt("e:c:");
  26. my $EXPIRE = $opt_e || $EXPIRE_DEF;
  27. my $CFG = $opt_c || $CFG_DEF;
  28. ( -f $CFG ) or die "Can't open config file '$CFG': $!\n";
  29. my ($dbhost, $dbport, $dbuser, $dbpass, $dbname);
  30. open(F, "< $CFG");
  31. while ( <F> ) {
  32. if (/^xsddb_host=(.+)/) { $dbhost = $1; next; };
  33. if (/^xsddb_port=(.+)/) { $dbport = $1; next; };
  34. if (/^xsddb_database=(.+)/) { $dbname = $1; next; };
  35. if (/^xsddb_username=(.+)/) { $dbuser = $1; next; };
  36. if (/^xsddb_password=(.+)/) { $dbpass = $1; next; };
  37. }
  38. close(F);
  39. #print "($dbhost, $dbport, $dbuser, $dbpass, $dbname)\n";
  40. my $dsn = "DBI:$driver:dbname=$dbname;host=$dbhost;port=$dbport";
  41. my $dbh = DBI->connect($dsn, $dbuser, $dbpass, {'RaiseError' => 1});
  42. my $sth = $dbh->prepare($QUERY);
  43. if (!$sth) { die "Error:" . $dbh->errstr . "\n"; }
  44. $sth->execute;
  45. if (!$sth->execute) { die "Error:" . $sth->errstr . "\n"; }
  46. my %status = ();
  47. my $names = $sth->{'NAME'};
  48. my $numFields = $sth->{'NUM_OF_FIELDS'};
  49. my $ref = $sth->fetchrow_arrayref;
  50. for (my $i = 0; $i < $numFields; $i++) {
  51. $status{"$$names[$i]"} = $$ref[$i];
  52. }
  53. #foreach (keys(%status)) {
  54. # print "$_: $status{$_}\n";
  55. #}
  56. my $lastupdated = time() - $status{"ut"};
  57. if ( $lastupdated < ($EXPIRE*60) ) { ## convert $EXPIRE to seconds
  58. $STAT = OK;
  59. }
  60. open(PS, "ps -eaf | grep $status{nagios_pid} | grep -v grep | ");
  61. $PROCCNT = 0;
  62. while(<PS>) {
  63. $PROCCNT++;
  64. }
  65. close(PS);
  66. if ( $STAT == OK ) {
  67. print "Nagios OK: located $PROCCNT processes, program status updated $lastupdated seconds ago\n";
  68. }