Last active
April 21, 2024 06:16
-
-
Save utdrmac/125da3652b864e5cbdfb to your computer and use it in GitHub Desktop.
Perl Script to Monitor MySQL Replication and Send Email on Failure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use DBI; | |
use Email::MIME; | |
use Log::Log4perl qw(get_logger :levels); | |
use Data::Dumper; | |
use strict; | |
# For backgrounding | |
my $pid = fork(); | |
#my $pid = 0; | |
if (!defined $pid) | |
{ | |
die "Cannot fork:$!\n"; | |
} | |
elsif ($pid == 0) | |
{ | |
do_monitor(); | |
} | |
else | |
{ | |
print "Forked. Running in background.\n"; | |
} | |
sub do_monitor() | |
{ | |
# logging | |
my $logger = get_logger('mysql'); | |
$logger->level($INFO); | |
my $layout = Log::Log4perl::Layout::PatternLayout->new("%d %p> %m%n"); | |
my $fileAppender = Log::Log4perl::Appender->new( | |
"Log::Dispatch::File", | |
filename => "/tmp/monitor_mysql.log", | |
mode => "append"); | |
$fileAppender->layout($layout); | |
#my $screenAppender = Log::Log4perl::Appender->new("Log::Dispatch::Screen", newline => 1); | |
#$screenAppender->layout($layout); | |
$logger->add_appender($fileAppender); | |
#$logger->add_appender($screenAppender); | |
# MySQL | |
my $dsn = "DBI:mysql:database=mysql:$ARGV[0];mysql_read_default_group=client"; | |
my $dbh = DBI->connect($dsn); | |
if (!$dbh) | |
{ | |
die $DBI::errstr; | |
} | |
my $sentNotification = 0; | |
while(1) | |
{ | |
my $sth = $dbh->prepare("SHOW SLAVE STATUS") or die $DBI::errstr; | |
$sth->execute or die $DBI::errstr; | |
my $r = $sth->fetchrow_hashref(); | |
$sth->finish; | |
if ($$r{'Slave_SQL_Running'} eq "No" || $$r{'Slave_IO_Running'} eq "No") | |
{ | |
$logger->error("Slave replication broken: "); | |
$logger->info(Dumper($r)); | |
sendEmail($sentNotification); | |
$sentNotification = 1; | |
} | |
else | |
{ | |
# OK or possibly Recovered | |
$logger->info("Slave replication OK"); | |
$sentNotification = 0; | |
} | |
sleep 60; | |
} | |
} | |
sub sendEmail | |
{ | |
my $sentNotif = shift; | |
if ($sentNotif == 0) | |
{ | |
my $message = Email::MIME->create( | |
header_str => [ | |
From => '[email protected]', | |
To => '[email protected]', | |
Subject => 'MySQL-Master-DB Replication Failure' | |
], | |
attributes => { encoding => 'quoted-printable', charset => 'ISO-8859-1' }, | |
body_str => "Slave is not running."); | |
use Email::Sender::Simple qw(sendmail); | |
sendmail($message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment