Article Listing 1 may2007.tar

Listing 1 SHOW SLAVE STATUS command results

#!/usr/bin/perl -w

# check_mysql_repl.pl
#   Nagios plugin for checking the status of MySQL replication.
#   Brian Smith (bpsmith@u.washington.edu) 2005-2007

use DBI;
use strict;

&main;

# Main function
# arguments: hostname
# returns: printed result, error code for nagios
sub main {
  my ($host) = @ARGV;

  if (!$host) {
    print "REPL UNKNOWN: syntax: check_mysql_repl.pl host";
    exit -1;
  }

  my $username = 'username';
  my $password = 'password';
  my $warn_threshold = 60;
  my $crit_threshold = 300;

  my $dsn = "DBI:mysql:database=;host=$host;port=3306";
  my $dbh = DBI->connect($dsn, $username, $password);

  my $sth = $dbh->prepare("SHOW SLAVE STATUS");
  $sth->execute;
  my $results = $sth->fetchrow_hashref();

  if (!$results) {
    print "REPL WARNING No results returned";
    exit 1;
  }

  if ($results->{"Slave_SQL_Running"} ne 'Yes') {
    print "REPL CRITICAL Slave SQL thread is not running. \
      Last error: ". $results->{"Last_Error"};
    exit 2;
  }

  if ($results->{"Seconds_Behind_Master"} < $warn_threshold) {
    print "REPL OK " . $results->{"Seconds_Behind_Master"} . " \
      seconds behind master\n";
    exit 0;
  } elsif ($results->{"Seconds_Behind_Master"} < $crit_threshold) {
    print "REPL WARNING " . $results->{"Seconds_Behind_Master"} . \
      " seconds behind master\n";
    exit 1;
  } else {
    print "REPL CRITICAL " . $results->{"Seconds_Behind_Master"} . \
      " seconds behind master\n";
    exit 2;
  }

  printf "REPL UNKNOWN This should never happen";
  exit -1;
}