Skip to content

Instantly share code, notes, and snippets.

@infynyxx
Forked from kchodorow/gist:318781
Created March 1, 2010 20:46
Show Gist options
  • Save infynyxx/318789 to your computer and use it in GitHub Desktop.
Save infynyxx/318789 to your computer and use it in GitHub Desktop.
Get MongoDB replication info
<?php
function getReplicationInfo($m) {
$db = $m->local;
$result = array();
$ol = $db->system->namespaces->findOne(array("name" => 'local.oplog.$main'));
if ($ol && array_key_exists('options', $ol)) {
$result['logSizeMB'] = $ol['options']['size'] / 1000 / 1000;
} else {
$result['errmsg'] = 'local.oplog.$main, or its options, not found in system.namespaces collection (not --master?)';
return $result;
}
$c = $db->selectCollection('oplog.$main');
$firstc = $c->find()->sort(array('$natural' => 1))->limit(1);
$lastc = $c->find()->sort(array('$natural' => -1))->limit(1);
if (!$firstc->hasNext() || !$lastc->hasNext()) {
$result['errmsg'] = "objects not found in local.oplog.$main -- is this a new and empty db instance?";
$result['oplogMainRowCount'] = $c->count();
return $result;
}
$first = $firstc->getNext();
$last = $lastc->getNext();
$tfirst = $first['ts'];
$tlast = $last['ts'];
if ($tfirst && $tlast) {
$tfirst = $tfirst->sec;
$tlast = $tlast->sec;
$result['timeDiff'] = $tlast - $tfirst;
$result['timeDiffHours'] = round($result['timeDiff'] / 36) / 100;
$result['tFirst'] = new MongoDate($tfirst);
$result['tLast'] = new MongoDate($tlast);
$result['now'] = new MongoDate();
} else {
$result['errmsg'] = "ts element not found in oplog objects";
}
return $result;
}
function printReplicationInfo($m) {
$result = getReplicationInfo($m);
if (array_key_exists('errmsg', $result)) {
print_r($result);
return;
}
echo "configured oplog size: " . $result['logSizeMB'] . "MB\n";
echo "log length start to end: " . $result['timeDiff'] . "secs (" . $result['timeDiffHours'] . "hrs)\n";
echo "oplog first event time: " . $result['tFirst']."\n";
echo "oplog last event time: " . $result['tLast']."\n";
echo "now: " . $result['now']."\n";
}
function getSlaveReplicationInfo($x) {
echo "source: " . $x['host']."\n";
$st = new MongoDate($x['syncedTo']->sec);
$now = new MongoDate;
echo "syncedTo: " . $st."\n";
$ago = ($now->sec - $st->sec) / 1000 + ($now->usec - $st->usec) * 1000;
$hrs = round($ago / 36) / 100;
echo " = " . round($ago) . "secs ago (" . $hrs . "hrs)\n";
}
function printSlaveReplicationInfo($m) {
$db = $m->local;
if ($db->sources->count() == 0) {
echo "local.sources is empty; is this db a --slave?\n";
return;
}
$cursor = $db->sources->find();
while ($cursor->hasNext()) {
$source = $cursor->getNext();
// foreach($cursor as $source) {
getSlaveReplicationInfo($source);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment