Created
November 26, 2013 12:43
-
-
Save Ulv/7657723 to your computer and use it in GitHub Desktop.
архивация файлов в tar.gz средствами php с блокировкой архива в процессе (простейший mutex)
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
/** | |
* архивирует файлы модуля в tar.gz и возвращает имя архива | |
* Реализована блокировка архива на время архивации (чтобы избежать race) | |
* | |
* @return string | |
*/ | |
public function export() | |
{ | |
if (is_readable($this->archive_name . '.gz')) { | |
return $this->archive_name . '.gz'; | |
} | |
$export_files = | |
$this->getControllersFullPath() + | |
$this->getModelsFullPath() + | |
$this->getTemplatesFullPath(); | |
$lockfile = $this->archive_name . '.lock'; | |
// если нет lock - считаем что tar остался старый и удаляем его | |
if (is_readable($this->archive_name) && ! file_exists($lockfile)) { | |
unlink($this->archive_name); | |
} | |
$i = 0; | |
do { | |
// ставим блокировку | |
$fp = @fopen($lockfile, 'w'); | |
if (! $fp) { | |
usleep(25); | |
continue; | |
} | |
if (flock($fp, LOCK_EX)) { | |
try { | |
$a = new PharData($this->archive_name); | |
foreach ($export_files as $key => $val) { | |
$a->addFile($val, $key); | |
} | |
// db dump & rules file | |
$a->addFromString('data', $this->dbDump); | |
$a->addFromString('rules', $this->_createRulesString()); | |
$a->compress(Phar::GZ); | |
unlink($this->archive_name); | |
// снимаем блокировку | |
flock($fp, LOCK_UN) && @fclose($fp); | |
@unlink($lockfile); | |
return $this->archive_name . '.gz'; | |
} catch (Exception $e) { | |
// @todo здесь возможно будет лог | |
unset($e); | |
@flock($fp, LOCK_UN) && @fclose($fp); | |
} | |
} | |
} while ($i ++ < 8); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment