cron.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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] [--verbose] [<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
  29. -v, --verbose Output more information' . PHP_EOL;
  30. exit(0);
  31. }
  32. if (Util::needUpgrade()) {
  33. Server::get(LoggerInterface::class)->debug('Update required, skipping cron', ['app' => 'cron']);
  34. exit;
  35. }
  36. $config = Server::get(IConfig::class);
  37. if ($config->getSystemValueBool('maintenance', false)) {
  38. Server::get(LoggerInterface::class)->debug('We are in maintenance mode, skipping cron', ['app' => 'cron']);
  39. exit;
  40. }
  41. // Don't do anything if Nextcloud has not been installed
  42. if (!$config->getSystemValueBool('installed', false)) {
  43. exit(0);
  44. }
  45. // load all apps to get all api routes properly setup
  46. Server::get(IAppManager::class)->loadApps();
  47. Server::get(ISession::class)->close();
  48. $verbose = isset($argv[1]) && ($argv[1] === '-v' || $argv[1] === '--verbose');
  49. // initialize a dummy memory session
  50. $session = new \OC\Session\Memory();
  51. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  52. $session = $cryptoWrapper->wrapSession($session);
  53. \OC::$server->setSession($session);
  54. $logger = Server::get(LoggerInterface::class);
  55. $appConfig = Server::get(IAppConfig::class);
  56. $tempManager = Server::get(ITempManager::class);
  57. $tempManager->cleanOld();
  58. // Exit if background jobs are disabled!
  59. $appMode = $appConfig->getValueString('core', 'backgroundjobs_mode', 'ajax');
  60. if ($appMode === 'none') {
  61. if (OC::$CLI) {
  62. echo 'Background Jobs are disabled!' . PHP_EOL;
  63. } else {
  64. OC_JSON::error(['data' => ['message' => 'Background jobs disabled!']]);
  65. }
  66. exit(1);
  67. }
  68. if (OC::$CLI) {
  69. // set to run indefinitely if needed
  70. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  71. @set_time_limit(0);
  72. }
  73. // the cron job must be executed with the right user
  74. if (!function_exists('posix_getuid')) {
  75. echo 'The posix extensions are required - see https://www.php.net/manual/en/book.posix.php' . PHP_EOL;
  76. exit(1);
  77. }
  78. $user = posix_getuid();
  79. $configUser = fileowner(OC::$configDir . 'config.php');
  80. if ($user !== $configUser) {
  81. echo 'Console has to be executed with the user that owns the file config/config.php' . PHP_EOL;
  82. echo 'Current user id: ' . $user . PHP_EOL;
  83. echo 'Owner id of config.php: ' . $configUser . PHP_EOL;
  84. exit(1);
  85. }
  86. // We call Nextcloud from the CLI (aka cron)
  87. if ($appMode !== 'cron') {
  88. $appConfig->setValueString('core', 'backgroundjobs_mode', 'cron');
  89. }
  90. // Low-load hours
  91. $onlyTimeSensitive = false;
  92. $startHour = $config->getSystemValueInt('maintenance_window_start', 100);
  93. if ($startHour <= 23) {
  94. $date = new \DateTime('now', new \DateTimeZone('UTC'));
  95. $currentHour = (int)$date->format('G');
  96. $endHour = $startHour + 4;
  97. if ($startHour <= 20) {
  98. // Start time: 01:00
  99. // End time: 05:00
  100. // Only run sensitive tasks when it's before the start or after the end
  101. $onlyTimeSensitive = $currentHour < $startHour || $currentHour > $endHour;
  102. } else {
  103. // Start time: 23:00
  104. // End time: 03:00
  105. $endHour -= 24; // Correct the end time from 27:00 to 03:00
  106. // Only run sensitive tasks when it's after the end and before the start
  107. $onlyTimeSensitive = $currentHour > $endHour && $currentHour < $startHour;
  108. }
  109. }
  110. // Work
  111. $jobList = Server::get(IJobList::class);
  112. // We only ask for jobs for 14 minutes, because after 5 minutes the next
  113. // system cron task should spawn and we want to have at most three
  114. // cron jobs running in parallel.
  115. $endTime = time() + 14 * 60;
  116. $executedJobs = [];
  117. // a specific job class list can optionally be given as argument
  118. $jobClasses = array_slice($argv, $verbose ? 2 : 1);
  119. $jobClasses = empty($jobClasses) ? null : $jobClasses;
  120. while ($job = $jobList->getNext($onlyTimeSensitive, $jobClasses)) {
  121. if (isset($executedJobs[$job->getId()])) {
  122. $jobList->unlockJob($job);
  123. break;
  124. }
  125. $jobDetails = get_class($job) . ' (id: ' . $job->getId() . ', arguments: ' . json_encode($job->getArgument()) . ')';
  126. $logger->debug('CLI cron call has selected job ' . $jobDetails, ['app' => 'cron']);
  127. $timeBefore = time();
  128. $memoryBefore = memory_get_usage();
  129. $memoryPeakBefore = memory_get_peak_usage();
  130. if ($verbose) {
  131. echo 'Starting job ' . $jobDetails . PHP_EOL;
  132. }
  133. /** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
  134. $job->execute($jobList);
  135. $timeAfter = time();
  136. $memoryAfter = memory_get_usage();
  137. $memoryPeakAfter = memory_get_peak_usage();
  138. $cronInterval = 5 * 60;
  139. $timeSpent = $timeAfter - $timeBefore;
  140. if ($timeSpent > $cronInterval) {
  141. $logLevel = match (true) {
  142. $timeSpent > $cronInterval * 128 => \OCP\ILogger::FATAL,
  143. $timeSpent > $cronInterval * 64 => \OCP\ILogger::ERROR,
  144. $timeSpent > $cronInterval * 16 => \OCP\ILogger::WARN,
  145. $timeSpent > $cronInterval * 8 => \OCP\ILogger::INFO,
  146. default => \OCP\ILogger::DEBUG,
  147. };
  148. $logger->log(
  149. $logLevel,
  150. 'Background job ' . $jobDetails . ' ran for ' . $timeSpent . ' seconds',
  151. ['app' => 'cron']
  152. );
  153. }
  154. if ($memoryAfter - $memoryBefore > 50_000_000) {
  155. $message = 'Used memory grew by more than 50 MB when executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryAfter) . ' (before: ' . Util::humanFileSize($memoryBefore) . ')';
  156. $logger->warning($message, ['app' => 'cron']);
  157. if ($verbose) {
  158. echo $message . PHP_EOL;
  159. }
  160. }
  161. if ($memoryPeakAfter > 300_000_000 && $memoryPeakBefore <= 300_000_000) {
  162. $message = 'Cron job used more than 300 MB of ram after executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryPeakAfter) . ' (before: ' . Util::humanFileSize($memoryPeakBefore) . ')';
  163. $logger->warning($message, ['app' => 'cron']);
  164. if ($verbose) {
  165. echo $message . PHP_EOL;
  166. }
  167. }
  168. // clean up after unclean jobs
  169. Server::get(\OC\Files\SetupManager::class)->tearDown();
  170. $tempManager->clean();
  171. if ($verbose) {
  172. echo 'Job ' . $jobDetails . ' done in ' . ($timeAfter - $timeBefore) . ' seconds' . PHP_EOL;
  173. }
  174. $jobList->setLastJob($job);
  175. $executedJobs[$job->getId()] = true;
  176. unset($job);
  177. if ($timeAfter > $endTime) {
  178. break;
  179. }
  180. }
  181. } else {
  182. // We call cron.php from some website
  183. if ($appMode === 'cron') {
  184. // Cron is cron :-P
  185. OC_JSON::error(['data' => ['message' => 'Backgroundjobs are using system cron!']]);
  186. } else {
  187. // Work and success :-)
  188. $jobList = Server::get(IJobList::class);
  189. $job = $jobList->getNext();
  190. if ($job != null) {
  191. $logger->debug('WebCron call has selected job with ID ' . strval($job->getId()), ['app' => 'cron']);
  192. /** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
  193. $job->execute($jobList);
  194. $jobList->setLastJob($job);
  195. }
  196. OC_JSON::success();
  197. }
  198. }
  199. // Log the successful cron execution
  200. $appConfig->setValueInt('core', 'lastcron', time());
  201. exit();
  202. } catch (Exception $ex) {
  203. Server::get(LoggerInterface::class)->error(
  204. $ex->getMessage(),
  205. ['app' => 'cron', 'exception' => $ex]
  206. );
  207. echo $ex . PHP_EOL;
  208. exit(1);
  209. } catch (Error $ex) {
  210. Server::get(LoggerInterface::class)->error(
  211. $ex->getMessage(),
  212. ['app' => 'cron', 'exception' => $ex]
  213. );
  214. echo $ex . PHP_EOL;
  215. exit(1);
  216. }