check_nagios_db.pl 2.1 KB

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