读取 mysql binlog 开始和结束时间(二)

2014-11-24 15:41:41 · 作者: · 浏览: 1
e'] != self::FORMAT_DESCRIPTION_EVENT) {
return null;
}
$data_str= fread($file, self::FORMAT_DESCRIPTION_EVENT_DATA_SIZE);
$data = unpack($this->formatDescriptionEventDataPackStr, $data_str);

return array('head'=>$head, 'data'=>$data);
}

/**
* @param resource $file
*
* Rotate event is the last event of a binglog.
* After event header, there is a 64bit int indicate the first event
* position of next binlog file and next binlog file name without \0 at end.
* The position is always be 4 (hex: 0400000000000000).
*
*/
protected function readRotateEvent($file)
{
/**
* Rotate event size is 19(head size) + 8(pos) + len(filename).
* 100 bytes can contain a filename which length less than 73 bytes and
* it is short than the length of format description event so filesize -
* bufsize will never be negative.
*/
$bufsize = 100;
$size_pos = 8;
fseek($file, -$bufsize, SEEK_END);
$buf = fread($file, $bufsize);
$min_begin = strlen(self::BINLOG_HEAD) + self::EVENT_HEAD_SIZE + $size_pos;
$ok = false;
for ($i = $bufsize - 1; $i > $min_begin; $i--) {
if ($buf[$i] == "\0") {
$ok = true;
break;
}
}
if (!$ok) {
return null;
}
$next_filename = substr($buf, $i + 1);

$head_str = substr($buf, $i + 1 - $size_pos - self::EVENT_HEAD_SIZE, self::EVENT_HEAD_SIZE);
$head = unpack($this->eventHeadPackStr, $head_str);
if ($head['type_code'] != self::ROTATE_EVENT) {
return null;
}
return array('head'=>$head, 'nextFile'=>$next_filename);
}

/**
* @param string $path path to binlog file
*/
function read($path) {
$file = fopen($path, 'r');
if (!$file) {
return null;
}
if (!$this->isBinlog($file)) {
fclose($file);
return null;
}

$fde = $this->readFormatDescriptionEvent($file);
$re = $this->readRotateEvent($file);
fclose($file);
return array(
'beginAt' => $fde['head']['timestamp'],
'endAt' => $re['head']['timestamp'],
'nextFile' => $re['nextFile'],
'serverVersion' => $fde['data']['server_version'],
);
}
}