1
0

BackgroundCleanupUpdaterBackupsJob.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\BackgroundJobs;
  8. use OCP\AppFramework\Utility\ITimeFactory;
  9. use OCP\BackgroundJob\QueuedJob;
  10. use OCP\IConfig;
  11. use Psr\Log\LoggerInterface;
  12. class BackgroundCleanupUpdaterBackupsJob extends QueuedJob {
  13. public function __construct(
  14. protected IConfig $config,
  15. protected LoggerInterface $log,
  16. ITimeFactory $time,
  17. ) {
  18. parent::__construct($time);
  19. }
  20. /**
  21. * This job cleans up all backups except the latest 3 from the updaters backup directory
  22. *
  23. * @param array $argument
  24. */
  25. public function run($argument): void {
  26. $updateDir = $this->config->getSystemValue('updatedirectory', null) ?? $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
  27. $instanceId = $this->config->getSystemValue('instanceid', null);
  28. if (!is_string($instanceId) || empty($instanceId)) {
  29. return;
  30. }
  31. $updaterFolderPath = $updateDir . '/updater-' . $instanceId;
  32. $backupFolderPath = $updaterFolderPath . '/backups';
  33. if (file_exists($backupFolderPath)) {
  34. $this->log->info("$backupFolderPath exists - start to clean it up");
  35. $dirList = [];
  36. $dirs = new \DirectoryIterator($backupFolderPath);
  37. foreach ($dirs as $dir) {
  38. // skip files and dot dirs
  39. if ($dir->isFile() || $dir->isDot()) {
  40. continue;
  41. }
  42. $mtime = $dir->getMTime();
  43. $realPath = $dir->getRealPath();
  44. if ($realPath === false) {
  45. continue;
  46. }
  47. $dirList[$mtime] = $realPath;
  48. }
  49. ksort($dirList);
  50. // drop the newest 3 directories
  51. $dirList = array_slice($dirList, 0, -3);
  52. $this->log->info('List of all directories that will be deleted: ' . json_encode($dirList));
  53. foreach ($dirList as $dir) {
  54. $this->log->info("Removing $dir ...");
  55. \OC_Helper::rmdirr($dir);
  56. }
  57. $this->log->info('Cleanup finished');
  58. } else {
  59. $this->log->info("Could not find updater directory $backupFolderPath - cleanup step not needed");
  60. }
  61. }
  62. }