Skip to content

Instantly share code, notes, and snippets.

@tom--
Created August 17, 2012 18:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tom--/3381140 to your computer and use it in GitHub Desktop.
Save tom--/3381140 to your computer and use it in GitHub Desktop.
Test a MySQL replication slave's status
#!/usr/local/bin/php
<?php
$error = false;
$errno = 0;
try {
$db = new PDO('mysql:dbname=stations;host=localhost', 'root', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/** @var $slave_status StdClass */
$slave_status = $db->query('show slave status')->fetchObject();
} catch (PDOException $e) {
$error = "Error getting slave status";
$errno = 20;
}
if (!$errno) {
if (!$slave_status) {
$error = "Empty slave status response";
$errno = 1; // Probably not a slave
} elseif (!property_exists($slave_status, 'Slave_IO_Running')
|| !property_exists($slave_status, 'Slave_SQL_Running')
|| !property_exists($slave_status, 'Seconds_Behind_Master')
) {
$error = "Expected vars in slave status response missing";
$errno = 21; // Shouldn't happen
} elseif ($slave_status->Slave_IO_Running !== 'Yes') {
$error = "Slave IO thread stopped";
$errno = 2; // Probably not a slave
} elseif ($slave_status->Slave_SQL_Running !== 'Yes') {
$error = "Slave IO running but slave SQL thread stopped";
$errno = 10; // Probably a slave that's in trouble
} elseif (!preg_match('/^\d+$/', $slave_status->Seconds_Behind_Master)) {
$error = "Seconds behind is NaN";
$errno = 11; // Probably a slave that's in trouble
} elseif ($slave_status->Seconds_Behind_Master > 99) {
$error = "Excessive slave lag: $slave_status->Seconds_Behind_Master";
$errno = 12; // Probably a slave that's in trouble
}
}
if ($errno) {
if ($errno >= 20) {
echo "MySQL server is in trouble. ";
} elseif ($errno >= 10) {
echo "Replication slave server is in trouble. ";
} else {
echo "Server is probably not supposed to be a slave. ";
}
fwrite(STDERR, "$error ($errno)\n");
exit($errno);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment