#!/usr/bin/php -q
<?php
//#####################################################
//# check_replication_slave -  Nagios Plugin to check #
//# state of mysql slave replication server.          #
//# updated 19 Feb 2009                               #
//#                                                   #
//# By Yunus Bookwala <yunusbookwala@gmail.com>       #
//#####################################################
error_reporting(0);

if ( $argc != 4 ) {
print "Usage: $argv[0] DB_HOST DB_USER DB_PASS\n";
exit;
}

$db_host = "$argv[1]";
$db_user = "$argv[2]";
$db_pass = "$argv[3]";

$warn_sec_behind_master = "60";
$critical_sec_behind_master = "120";

$errors = array (
		"UNKNOWN" => -1,
		"OK" => 0,
		"WARNING" => 1,
		"CRITICAL" => 2
	  );

$state = "UNKNOWN";

$link = mysql_connect($db_host, $db_user, $db_pass);
if (!$link) {
    $errmesg = mysql_error();
    $state = "CRITICAL";
    print "$state: $errmesg\n";
    exit ($errors[$state]);
    
};

$sql = "show slave status";
$result = mysql_query ( "$sql" );
if (!$result) {
   $state = "UNKNOWN";
   $errmesg = mysql_error();
   print "$state: $errmesg\n";
   exit ($errors[$state]);
}

$status = mysql_fetch_object( $result );

$status_slave_io_running = $status->Slave_IO_Running;
$status_slave_sql_running = $status->Slave_SQL_Running;
$status_seconds_behind_master = $status->Seconds_Behind_Master;

$answer = "SLAVE IO Running: $status_slave_io_running, SLAVE SQL Running: $status_slave_sql_running, $status_seconds_behind_master secs behind Master";

if ( "2" == checkcritical ( $status_slave_io_running, $status_slave_sql_running, $status_seconds_behind_master, $critical_sec_behind_master ) ) {
   $state = 'CRITICAL';
} elseif ( "1" == checkwarning ( $status_seconds_behind_master, $warn_sec_behind_master ) ) {
   $state = 'WARNING';
} elseif ( "0" == checkok ( $status_slave_io_running, $status_slave_sql_running, $status_seconds_behind_master, $warn_sec_behind_master ) ) {
   $state = 'OK';
}

function checkcritical ( $status_slave_io_running, $status_slave_sql_running, $status_seconds_behind_master, $critical_sec_behind_master )
{
   
   if ( "Yes" != $status_slave_io_running or "Yes" != $status_slave_sql_running  or $critical_sec_behind_master < $status_seconds_behind_master)  {

   return 2;
   }
   return -1;
}

function checkwarning ( $status_seconds_behind_master, $warn_sec_behind_master )
{
   if ( $warn_sec_behind_master < $status_seconds_behind_master ) {
   return 1;
   }
   return -1;
}

function checkok ( $status_slave_io_running, $status_slave_sql_running, $status_seconds_behind_master, $warn_sec_behind_master )
{
   if ( "Yes" == $status_slave_io_running  and "Yes" == $status_slave_sql_running  and $warn_sec_behind_master > $status_seconds_behind_master)  {
   return 0;
   }
   return -1;
}

print "$state: $answer\n";
exit ($errors[$state]);
?>
