cron.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 (isset($argv[1]) && ($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. $timeBefore = time();
  126. $memoryBefore = memory_get_usage();
  127. $memoryPeakBefore = memory_get_peak_usage();
  128. /** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
  129. $job->execute($jobList);
  130. $timeAfter = time();
  131. $memoryAfter = memory_get_usage();
  132. $memoryPeakAfter = memory_get_peak_usage();
  133. $cronInterval = 5 * 60;
  134. $timeSpent = $timeAfter - $timeBefore;
  135. if ($timeSpent > $cronInterval) {
  136. $logLevel = match (true) {
  137. $timeSpent > $cronInterval * 128 => \OCP\ILogger::FATAL,
  138. $timeSpent > $cronInterval * 64 => \OCP\ILogger::ERROR,
  139. $timeSpent > $cronInterval * 16 => \OCP\ILogger::WARN,
  140. $timeSpent > $cronInterval * 8 => \OCP\ILogger::INFO,
  141. default => \OCP\ILogger::DEBUG,
  142. };
  143. $logger->log(
  144. $logLevel,
  145. 'Background job ' . $jobDetails . ' ran for ' . $timeSpent . ' seconds',
  146. ['app' => 'cron']
  147. );
  148. }
  149. if ($memoryAfter - $memoryBefore > 50_000_000) {
  150. $logger->warning('Used memory grew by more than 50 MB when executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryAfter). ' (before: ' . Util::humanFileSize($memoryBefore) . ')', ['app' => 'cron']);
  151. }
  152. if ($memoryPeakAfter > 300_000_000 && $memoryPeakBefore <= 300_000_000) {
  153. $logger->warning('Cron job used more than 300 MB of ram after executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryPeakAfter) . ' (before: ' . Util::humanFileSize($memoryPeakBefore) . ')', ['app' => 'cron']);
  154. }
  155. // clean up after unclean jobs
  156. Server::get(\OC\Files\SetupManager::class)->tearDown();
  157. $tempManager->clean();
  158. $jobList->setLastJob($job);
  159. $executedJobs[$job->getId()] = true;
  160. unset($job);
  161. if ($timeAfter > $endTime) {
  162. break;
  163. }
  164. }
  165. } else {
  166. // We call cron.php from some website
  167. if ($appMode === 'cron') {
  168. // Cron is cron :-P
  169. OC_JSON::error(['data' => ['message' => 'Backgroundjobs are using system cron!']]);
  170. } else {
  171. // Work and success :-)
  172. $jobList = Server::get(IJobList::class);
  173. $job = $jobList->getNext();
  174. if ($job != null) {
  175. $logger->debug('WebCron call has selected job with ID ' . strval($job->getId()), ['app' => 'cron']);
  176. /** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
  177. $job->execute($jobList);
  178. $jobList->setLastJob($job);
  179. }
  180. OC_JSON::success();
  181. }
  182. }
  183. // Log the successful cron execution
  184. $appConfig->setValueInt('core', 'lastcron', time());
  185. exit();
  186. } catch (Exception $ex) {
  187. Server::get(LoggerInterface::class)->error(
  188. $ex->getMessage(),
  189. ['app' => 'cron', 'exception' => $ex]
  190. );
  191. echo $ex . PHP_EOL;
  192. exit(1);
  193. } catch (Error $ex) {
  194. Server::get(LoggerInterface::class)->error(
  195. $ex->getMessage(),
  196. ['app' => 'cron', 'exception' => $ex]
  197. );
  198. echo $ex . PHP_EOL;
  199. exit(1);
  200. }