1
0

RemoveOldTasksBackgroundJob.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\TaskProcessing;
  7. use OC\TaskProcessing\Db\TaskMapper;
  8. use OCP\AppFramework\Utility\ITimeFactory;
  9. use OCP\BackgroundJob\TimedJob;
  10. use OCP\Files\AppData\IAppDataFactory;
  11. use OCP\Files\NotFoundException;
  12. use OCP\Files\NotPermittedException;
  13. use OCP\Files\SimpleFS\ISimpleFolder;
  14. use Psr\Log\LoggerInterface;
  15. class RemoveOldTasksBackgroundJob extends TimedJob {
  16. public const MAX_TASK_AGE_SECONDS = 60 * 50 * 24 * 7 * 4; // 4 weeks
  17. private \OCP\Files\IAppData $appData;
  18. public function __construct(
  19. ITimeFactory $timeFactory,
  20. private TaskMapper $taskMapper,
  21. private LoggerInterface $logger,
  22. IAppDataFactory $appDataFactory,
  23. ) {
  24. parent::__construct($timeFactory);
  25. $this->setInterval(60 * 60 * 24);
  26. // can be deferred to maintenance window
  27. $this->setTimeSensitivity(TimedJob::TIME_INSENSITIVE);
  28. $this->appData = $appDataFactory->get('core');
  29. }
  30. /**
  31. * @inheritDoc
  32. */
  33. protected function run($argument): void {
  34. try {
  35. $this->taskMapper->deleteOlderThan(self::MAX_TASK_AGE_SECONDS);
  36. } catch (\OCP\DB\Exception $e) {
  37. $this->logger->warning('Failed to delete stale task processing tasks', ['exception' => $e]);
  38. }
  39. try {
  40. $this->clearFilesOlderThan($this->appData->getFolder('text2image'), self::MAX_TASK_AGE_SECONDS);
  41. } catch (NotFoundException $e) {
  42. // noop
  43. }
  44. try {
  45. $this->clearFilesOlderThan($this->appData->getFolder('audio2text'), self::MAX_TASK_AGE_SECONDS);
  46. } catch (NotFoundException $e) {
  47. // noop
  48. }
  49. try {
  50. $this->clearFilesOlderThan($this->appData->getFolder('TaskProcessing'), self::MAX_TASK_AGE_SECONDS);
  51. } catch (NotFoundException $e) {
  52. // noop
  53. }
  54. }
  55. /**
  56. * @param ISimpleFolder $folder
  57. * @param int $ageInSeconds
  58. * @return void
  59. */
  60. private function clearFilesOlderThan(ISimpleFolder $folder, int $ageInSeconds): void {
  61. foreach($folder->getDirectoryListing() as $file) {
  62. if ($file->getMTime() < time() - $ageInSeconds) {
  63. try {
  64. $file->delete();
  65. } catch (NotPermittedException $e) {
  66. $this->logger->warning('Failed to delete a stale task processing file', ['exception' => $e]);
  67. }
  68. }
  69. }
  70. }
  71. }