Created
April 30, 2014 05:34
-
-
Save cbednarski/040521675d9eba597c8a to your computer and use it in GitHub Desktop.
MySQL Replication Healthcheck
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
<?php | |
$username = ''; | |
$password = ''; | |
$servers = array( | |
'127.0.0.1', | |
); | |
class ReplicationCheck | |
{ | |
private $host; | |
private $pdo; | |
/** | |
* @return PDO|false | |
*/ | |
public function connect($host = '127.0.0.1', $user = 'root', $password = '', $database = null) | |
{ | |
$this->host = $host; | |
$connection = 'host='.$host; | |
if ($database) { | |
$connection = 'dbname='.$database.$connection; | |
} | |
try { | |
$this->pdo = new PDO('mysql:'.$connection, $user, $password); | |
} catch (Exception $e) { | |
// database connection failed; | |
return false; | |
} | |
} | |
public function getSlaveStatus() | |
{ | |
if (!$this->pdo) { | |
return false; | |
} | |
$query = $this->pdo->prepare('SHOW SLAVE STATUS'); | |
$query->execute(); | |
$results = $query->fetch(PDO::FETCH_ASSOC); | |
return $results; | |
} | |
public function showSlaveStatus($color_display = true) | |
{ | |
$results = $this->getSlaveStatus(); | |
if (!$results || intval($results['Seconds_Behind_Master']) > 0) { | |
$status = 'FAIL'; | |
$color = '[1;31m'; | |
$pass = false; | |
} else { | |
$status = 'OK'; | |
$color = '[1;32m'; | |
$pass = true; | |
} | |
$color_code = null; | |
if ($color_display) { | |
$color_code = chr(27).$color; | |
} | |
if ($results) { | |
$message = sprintf('master=%s seconds_behind=%s', | |
$results['Master_Host'], | |
$results['Seconds_Behind_Master'] | |
); | |
} else { | |
$message = 'unable to connect'; | |
} | |
echo sprintf($color_code.'%sReplication status for %s: %s -- status %s'.PHP_EOL, | |
$color_code, | |
$this->host, | |
$message, | |
$status | |
); | |
return $pass; | |
} | |
} | |
foreach ($servers as $server) { | |
$pdo = new ReplicationCheck(); | |
$pdo->connect($server, $username, $password); | |
$pdo->showSlaveStatus(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment