Docker-S3DB/syncer/MysqlSyncer.php

78 lines
2.5 KiB
PHP
Raw Normal View History

2022-08-20 03:20:49 +00:00
<?php
namespace S3DB\Sync;
2022-08-23 12:19:05 +00:00
use Rych\ByteSize\ByteSize;
use Spatie\Emoji\Emoji;
2022-08-28 09:38:02 +00:00
class MysqlSyncer extends AbstractSyncer
2022-08-20 03:20:49 +00:00
{
public function push(): void
{
2022-08-23 12:19:05 +00:00
// Dump file from Postgres
$dumpFile = 'dump.sql';
2022-08-28 09:38:02 +00:00
$command = sprintf('mysqldump -u $MARIADB_USER -p$MARIADB_PASSWORD --extended-insert --quick --add-locks --add-drop-database --add-drop-table --add-drop-trigger $MARIADB_DATABASE > /dumps/%s', $dumpFile);
2022-08-23 12:19:05 +00:00
passthru($command);
// Verify the dump worked
if (!$this->localFilesystem->fileExists($dumpFile)) {
$this->logger->critical('Database dump failed');
exit;
}
$this->logger->debug(sprintf(
'Dump file was made, and is %s uncompressed',
ByteSize::formatMetric(
$this->localFilesystem->fileSize($dumpFile)
)
));
// Checksum dump and don't upload if the checksum is the same as last time.
$hash = sha1_file("/dumps/{$dumpFile}");
if ($this->localFilesystem->has('previous_hash') && $hash == $this->localFilesystem->read('previous_hash')) {
$this->logger->debug(sprintf(
'%s Dump of %s matches previous dump (%s), not uploading the same file again.',
Emoji::abacus(),
$dumpFile,
substr($hash, 0, 7)
));
exit;
}
$this->localFilesystem->write('previous_hash', $hash);
2022-08-23 12:19:05 +00:00
// XZ compress dump
$compressedDumpFile = $this->compress($dumpFile);
// Upload
$storageFile = sprintf('s3db-%s.sql.xz', date('Ymd-His'));
$this->upload($storageFile, $compressedDumpFile);
// Cleanup
$this->cleanup([$compressedDumpFile]);
2022-08-20 03:20:49 +00:00
}
public function pull(): void
{
2022-08-23 12:19:05 +00:00
// Download latest dumpfile
$localDownloadedFile = $this->download();
// Decompress
$localDecompressedFile = $this->decompress($localDownloadedFile);
2022-08-28 09:38:02 +00:00
// Push into MySQL
2022-08-23 12:19:05 +00:00
$startImport = microtime(true);
2022-08-28 09:38:02 +00:00
$command = sprintf('mysql -u $MARIADB_USER -p$MARIADB_PASSWORD $MARIADB_DATABASE < /dumps/%s', $localDecompressedFile);
2022-08-23 12:19:05 +00:00
exec($command);
$this->logger->info(sprintf(
2022-08-28 09:38:02 +00:00
'%s Imported %s to MySQL in %s seconds',
2022-08-23 12:19:05 +00:00
Emoji::accordion(),
$localDecompressedFile,
number_format(microtime(true) - $startImport, 3)
));
// Cleanup
$this->cleanup([$localDecompressedFile]);
2022-08-20 03:20:49 +00:00
}
}