cron.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. require_once __DIR__ . '/lib/versioncheck.php';
  9. use OCP\App\IAppManager;
  10. use OCP\BackgroundJob\IJobList;
  11. use OCP\IAppConfig;
  12. use OCP\IConfig;
  13. use OCP\ISession;
  14. use OCP\ITempManager;
  15. use OCP\Server;
  16. use OCP\Util;
  17. use Psr\Log\LoggerInterface;
  18. try {
  19. require_once __DIR__ . '/lib/base.php';
  20. if ($argv[1] === '-h' || $argv[1] === '--help') {
  21. echo 'Description:
  22. Run the background job routine
  23. Usage:
  24. php -f cron.php -- [-h] [<job-classes>...]
  25. Arguments:
  26. job-classes Optional job class list to only run those jobs
  27. Options:
  28. -h, --help Display this help message' . PHP_EOL;
  29. exit(0);
  30. }
  31. if (Util::needUpgrade()) {
  32. Server::get(LoggerInterface::class)->debug('Update required, skipping cron', ['app' => 'cron']);
  33. exit;
  34. }
  35. $config = Server::get(IConfig::class);
  36. if ($config->getSystemValueBool('maintenance', false)) {
  37. Server::get(LoggerInterface::class)->debug('We are in maintenance mode, skipping cron', ['app' => 'cron']);
  38. exit;
  39. }
  40. // Don't do anything if Nextcloud has not been installed
  41. if (!$config->getSystemValueBool('installed', false)) {
  42. exit(0);
  43. }
  44. // load all apps to get all api routes properly setup
  45. Server::get(IAppManager::class)->loadApps();
  46. Server::get(ISession::class)->close();
  47. // initialize a dummy memory session
  48. $session = new \OC\Session\Memory('');
  49. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  50. $session = $cryptoWrapper->wrapSession($session);
  51. \OC::$server->setSession($session);
  52. $logger = Server::get(LoggerInterface::class);
  53. $appConfig = Server::get(IAppConfig::class);
  54. $tempManager = Server::get(ITempManager::class);
  55. $tempManager->cleanOld();
  56. // Exit if background jobs are disabled!
  57. $appMode = $appConfig->getValueString('core', 'backgroundjobs_mode', 'ajax');
  58. if ($appMode === 'none') {
  59. if (OC::$CLI) {
  60. echo 'Background Jobs are disabled!' . PHP_EOL;
  61. } else {
  62. OC_JSON::error(['data' => ['message' => 'Background jobs disabled!']]);
  63. }
  64. exit(1);
  65. }
  66. if (OC::$CLI) {
  67. // set to run indefinitely if needed
  68. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  69. @set_time_limit(0);
  70. }
  71. // the cron job must be executed with the right user
  72. if (!function_exists('posix_getuid')) {
  73. echo "The posix extensions are required - see https://www.php.net/manual/en/book.posix.php" . PHP_EOL;
  74. exit(1);
  75. }
  76. $user = posix_getuid();
  77. $configUser = fileowner(OC::$configDir . 'config.php');
  78. if ($user !== $configUser) {
  79. echo "Console has to be executed with the user that owns the file config/config.php" . PHP_EOL;
  80. echo "Current user id: " . $user . PHP_EOL;
  81. echo "Owner id of config.php: " . $configUser . PHP_EOL;
  82. exit(1);
  83. }
  84. // We call Nextcloud from the CLI (aka cron)
  85. if ($appMode !== 'cron') {
  86. $appConfig->setValueString('core', 'backgroundjobs_mode', 'cron');
  87. }
  88. // Low-load hours
  89. $onlyTimeSensitive = false;
  90. $startHour = $config->getSystemValueInt('maintenance_window_start', 100);
  91. if ($startHour <= 23) {
  92. $date = new \DateTime('now', new \DateTimeZone('UTC'));
  93. $currentHour = (int) $date->format('G');
  94. $endHour = $startHour + 4;
  95. if ($startHour <= 20) {
  96. // Start time: 01:00
  97. // End time: 05:00
  98. // Only run sensitive tasks when it's before the start or after the end
  99. $onlyTimeSensitive = $currentHour < $startHour || $currentHour > $endHour;
  100. } else {
  101. // Start time: 23:00
  102. // End time: 03:00
  103. $endHour -= 24; // Correct the end time from 27:00 to 03:00
  104. // Only run sensitive tasks when it's after the end and before the start
  105. $onlyTimeSensitive = $currentHour > $endHour && $currentHour < $startHour;
  106. }
  107. }
  108. // Work
  109. $jobList = Server::get(IJobList::class);
  110. // We only ask for jobs for 14 minutes, because after 5 minutes the next
  111. // system cron task should spawn and we want to have at most three
  112. // cron jobs running in parallel.
  113. $endTime = time() + 14 * 60;
  114. $executedJobs = [];
  115. // a specific job class list can optionally be given as argument
  116. $jobClasses = array_slice($argv, 1);
  117. $jobClasses = empty($jobClasses) ? null : $jobClasses;
  118. while ($job = $jobList->getNext($onlyTimeSensitive, $jobClasses)) {
  119. if (isset($executedJobs[$job->getId()])) {
  120. $jobList->unlockJob($job);
  121. break;
  122. }
  123. $jobDetails = get_class($job) . ' (id: ' . $job->getId() . ', arguments: ' . json_encode($job->getArgument()) . ')';
  124. $logger->debug('CLI cron call has selected job ' . $jobDetails, ['app' => 'cron']);
  125. $memoryBefore = memory_get_usage();
  126. $memoryPeakBefore = memory_get_peak_usage();
  127. /** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
  128. $job->execute($jobList);
  129. $memoryAfter = memory_get_usage();
  130. $memoryPeakAfter = memory_get_peak_usage();
  131. if ($memoryAfter - $memoryBefore > 10_000_000) {
  132. $logger->warning('Used memory grew by more than 10 MB when executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryAfter). ' (before: ' . Util::humanFileSize($memoryBefore) . ')', ['app' => 'cron']);
  133. }
  134. if ($memoryPeakAfter > 300_000_000) {
  135. $logger->warning('Cron job used more than 300 MB of ram after executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryPeakAfter) . ' (before: ' . Util::humanFileSize($memoryPeakBefore) . ')', ['app' => 'cron']);
  136. }
  137. // clean up after unclean jobs
  138. Server::get(\OC\Files\SetupManager::class)->tearDown();
  139. $tempManager->clean();
  140. $jobList->setLastJob($job);
  141. $executedJobs[$job->getId()] = true;
  142. unset($job);
  143. if (time() > $endTime) {
  144. break;
  145. }
  146. }
  147. } else {
  148. // We call cron.php from some website
  149. if ($appMode === 'cron') {
  150. // Cron is cron :-P
  151. OC_JSON::error(['data' => ['message' => 'Backgroundjobs are using system cron!']]);
  152. } else {
  153. // Work and success :-)
  154. $jobList = Server::get(IJobList::class);
  155. $job = $jobList->getNext();
  156. if ($job != null) {
  157. $logger->debug('WebCron call has selected job with ID ' . strval($job->getId()), ['app' => 'cron']);
  158. /** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
  159. $job->execute($jobList);
  160. $jobList->setLastJob($job);
  161. }
  162. OC_JSON::success();
  163. }
  164. }
  165. // Log the successful cron execution
  166. $appConfig->setValueInt('core', 'lastcron', time());
  167. exit();
  168. } catch (Exception $ex) {
  169. Server::get(LoggerInterface::class)->error(
  170. $ex->getMessage(),
  171. ['app' => 'cron', 'exception' => $ex]
  172. );
  173. echo $ex . PHP_EOL;
  174. exit(1);
  175. } catch (Error $ex) {
  176. Server::get(LoggerInterface::class)->error(
  177. $ex->getMessage(),
  178. ['app' => 'cron', 'exception' => $ex]
  179. );
  180. echo $ex . PHP_EOL;
  181. exit(1);
  182. }