Files
backupscript/src/Rclone/Rclone.php
Jens True 188a6ad9fa
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
Cleaning up.
2023-08-15 11:43:12 +00:00

133 lines
3.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Rclone;
use Psr\Log\LoggerInterface;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Exception;
/**
* Wrapper for the rclone command line utility
*
* Installation of rclone is required.
* Configuration of the mounts must be done before use.
* Tested using rclone v1.62.2
*/
class Rclone
{
protected string $version = "";
/**
* Create a new instance.
*
* Default it looks for "rclone" on the path.
* But the path can be configured to be absolute.
*
* @param string $rclonePath Relative or absolute path
*/
public function __construct(protected LoggerInterface $logger, protected string $rclonePath = "rclone")
{
$this->rclonePath = $rclonePath;
$process = $this->exec('--version');
if (!$process->isSuccessful()) {
throw new Exception("Check installation of rclone");
}
$this->version = explode("\n", $process->getOutput())[0];
if (!\str_contains($this->version, 'rclone')) {
throw new Exception("rclone not recognized");
}
}
/**
* Get the rclone version.
*
* @return string Version string
*/
public function getVersion(): string
{
return $this->version;
}
/**
* Calculate the size of a mount/path.
*
* @param string $path mount/path.
*
* @return int Size in bytes
*/
public function getSize(string $path): int
{
$process = $this->exec('size', ['--json', $path]);
if (!$process->isSuccessful()) {
throw new Exception($process->getErrorOutput());
}
/** @var array{bytes: int} */
$output = json_decode($process->getOutput(), true);
return $output['bytes'];
}
/**
* Copy from source to destination.
*
* @param $src Source mount and path
* @param $dest Destination mount and path
* @param string[] $additionalOptions Additional options
*/
public function copy(string $src, string $dest, array $additionalOptions = array()): void
{
$options = array();
$options[] = $src;
$options[] = $dest;
foreach ($additionalOptions as $key => $value) {
$options[] = '--' . (string)$key;
$options[] = $value;
}
$process = $this->exec('copy', $options);
if (!$process->isSuccessful()) {
throw new Exception($process->getErrorOutput());
}
}
/**
* Execute a command on the rclone binary.
*
* @param string $command Top level Rclone command
* @param array<String> $options Array of additional options
*
* @return Process Instance.
*/
protected function exec(string $command, array $options = array()): Process
{
$process = new Process(
array_merge(
[$this->rclonePath],
[$command],
$options
)
);
$this->logger->info("Execute command", [$process->getCommandLine()]);
$process->setTimeout(4 * 3600);
$process->run();
// executes after the command finishes
if (!$process->isSuccessful()) {
$this->logger->error("Failed execution");
}
$this->logger->info("Return code", [$process->getExitCode()]);
return $process;
}
}