cron.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Artem Sidorenko <artem@posteo.de>
  7. * @author Christopher Schäpers <kondou@ts.unde.re>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Côme Chilliet <come.chilliet@nextcloud.com>
  10. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  11. * @author hoellen <dev@hoellen.eu>
  12. * @author J0WI <J0WI@users.noreply.github.com>
  13. * @author Jakob Sack <mail@jakobsack.de>
  14. * @author Joas Schilling <coding@schilljs.com>
  15. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  16. * @author Ko- <k.stoffelen@cs.ru.nl>
  17. * @author Michael Kuhn <michael@ikkoku.de>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Oliver Kohl D.Sc. <oliver@kohl.bz>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Roeland Jago Douma <roeland@famdouma.nl>
  22. * @author Steffen Lindner <mail@steffen-lindner.de>
  23. * @author Thomas Müller <thomas.mueller@tmit.eu>
  24. * @author Vincent Petry <vincent@nextcloud.com>
  25. * @author Stephen Michel <git@smichel.me>
  26. *
  27. * @license AGPL-3.0
  28. *
  29. * This code is free software: you can redistribute it and/or modify
  30. * it under the terms of the GNU Affero General Public License, version 3,
  31. * as published by the Free Software Foundation.
  32. *
  33. * This program is distributed in the hope that it will be useful,
  34. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  35. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  36. * GNU Affero General Public License for more details.
  37. *
  38. * You should have received a copy of the GNU Affero General Public License, version 3,
  39. * along with this program. If not, see <http://www.gnu.org/licenses/>
  40. *
  41. */
  42. require_once __DIR__ . '/lib/versioncheck.php';
  43. use OCP\App\IAppManager;
  44. use OCP\BackgroundJob\IJobList;
  45. use OCP\IAppConfig;
  46. use OCP\IConfig;
  47. use OCP\ISession;
  48. use OCP\ITempManager;
  49. use OCP\Server;
  50. use OCP\Util;
  51. use Psr\Log\LoggerInterface;
  52. try {
  53. require_once __DIR__ . '/lib/base.php';
  54. if (Util::needUpgrade()) {
  55. Server::get(LoggerInterface::class)->debug('Update required, skipping cron', ['app' => 'cron']);
  56. exit;
  57. }
  58. $config = Server::get(IConfig::class);
  59. if ($config->getSystemValueBool('maintenance', false)) {
  60. Server::get(LoggerInterface::class)->debug('We are in maintenance mode, skipping cron', ['app' => 'cron']);
  61. exit;
  62. }
  63. // Don't do anything if Nextcloud has not been installed
  64. if (!$config->getSystemValueBool('installed', false)) {
  65. exit(0);
  66. }
  67. // load all apps to get all api routes properly setup
  68. Server::get(IAppManager::class)->loadApps();
  69. Server::get(ISession::class)->close();
  70. // initialize a dummy memory session
  71. $session = new \OC\Session\Memory('');
  72. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  73. $session = $cryptoWrapper->wrapSession($session);
  74. \OC::$server->setSession($session);
  75. $logger = Server::get(LoggerInterface::class);
  76. $appConfig = Server::get(IAppConfig::class);
  77. $tempManager = Server::get(ITempManager::class);
  78. $tempManager->cleanOld();
  79. // Exit if background jobs are disabled!
  80. $appMode = $appConfig->getValueString('core', 'backgroundjobs_mode', 'ajax');
  81. if ($appMode === 'none') {
  82. if (OC::$CLI) {
  83. echo 'Background Jobs are disabled!' . PHP_EOL;
  84. } else {
  85. OC_JSON::error(['data' => ['message' => 'Background jobs disabled!']]);
  86. }
  87. exit(1);
  88. }
  89. if (OC::$CLI) {
  90. // set to run indefinitely if needed
  91. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  92. @set_time_limit(0);
  93. }
  94. // the cron job must be executed with the right user
  95. if (!function_exists('posix_getuid')) {
  96. echo "The posix extensions are required - see https://www.php.net/manual/en/book.posix.php" . PHP_EOL;
  97. exit(1);
  98. }
  99. $user = posix_getuid();
  100. $configUser = fileowner(OC::$configDir . 'config.php');
  101. if ($user !== $configUser) {
  102. echo "Console has to be executed with the user that owns the file config/config.php" . PHP_EOL;
  103. echo "Current user id: " . $user . PHP_EOL;
  104. echo "Owner id of config.php: " . $configUser . PHP_EOL;
  105. exit(1);
  106. }
  107. // We call Nextcloud from the CLI (aka cron)
  108. if ($appMode !== 'cron') {
  109. $appConfig->setValueString('core', 'backgroundjobs_mode', 'cron');
  110. }
  111. // Low-load hours
  112. $onlyTimeSensitive = false;
  113. $startHour = $config->getSystemValueInt('maintenance_window_start', 100);
  114. if ($startHour <= 23) {
  115. $date = new \DateTime('now', new \DateTimeZone('UTC'));
  116. $currentHour = (int) $date->format('G');
  117. $endHour = $startHour + 4;
  118. if ($startHour <= 20) {
  119. // Start time: 01:00
  120. // End time: 05:00
  121. // Only run sensitive tasks when it's before the start or after the end
  122. $onlyTimeSensitive = $currentHour < $startHour || $currentHour > $endHour;
  123. } else {
  124. // Start time: 23:00
  125. // End time: 03:00
  126. $endHour -= 24; // Correct the end time from 27:00 to 03:00
  127. // Only run sensitive tasks when it's after the end and before the start
  128. $onlyTimeSensitive = $currentHour > $endHour && $currentHour < $startHour;
  129. }
  130. }
  131. // Work
  132. $jobList = Server::get(IJobList::class);
  133. // We only ask for jobs for 14 minutes, because after 5 minutes the next
  134. // system cron task should spawn and we want to have at most three
  135. // cron jobs running in parallel.
  136. $endTime = time() + 14 * 60;
  137. $executedJobs = [];
  138. while ($job = $jobList->getNext($onlyTimeSensitive)) {
  139. if (isset($executedJobs[$job->getId()])) {
  140. $jobList->unlockJob($job);
  141. break;
  142. }
  143. $jobDetails = get_class($job) . ' (id: ' . $job->getId() . ', arguments: ' . json_encode($job->getArgument()) . ')';
  144. $logger->debug('CLI cron call has selected job ' . $jobDetails, ['app' => 'cron']);
  145. $timeBefore = time();
  146. $memoryBefore = memory_get_usage();
  147. $memoryPeakBefore = memory_get_peak_usage();
  148. /** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
  149. $job->execute($jobList);
  150. $timeAfter = time();
  151. $memoryAfter = memory_get_usage();
  152. $memoryPeakAfter = memory_get_peak_usage();
  153. $cronInterval = 5 * 60;
  154. $timeSpent = $timeAfter - $timeBefore;
  155. if ($timeSpent > $cronInterval) {
  156. $logLevel = match (true) {
  157. $timeSpent > $cronInterval * 128 => \OCP\ILogger::FATAL,
  158. $timeSpent > $cronInterval * 64 => \OCP\ILogger::ERROR,
  159. $timeSpent > $cronInterval * 16 => \OCP\ILogger::WARN,
  160. $timeSpent > $cronInterval * 8 => \OCP\ILogger::INFO,
  161. default => \OCP\ILogger::DEBUG,
  162. };
  163. $logger->log(
  164. $logLevel,
  165. 'Background job ' . $jobDetails . ' ran for ' . $timeSpent . ' seconds',
  166. ['app' => 'cron']
  167. );
  168. }
  169. if ($memoryAfter - $memoryBefore > 10_000_000) {
  170. $logger->warning('Used memory grew by more than 10 MB when executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryAfter). ' (before: ' . Util::humanFileSize($memoryBefore) . ')', ['app' => 'cron']);
  171. }
  172. if ($memoryPeakAfter > 300_000_000) {
  173. $logger->warning('Cron job used more than 300 MB of ram after executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryPeakAfter) . ' (before: ' . Util::humanFileSize($memoryPeakBefore) . ')', ['app' => 'cron']);
  174. }
  175. // clean up after unclean jobs
  176. Server::get(\OC\Files\SetupManager::class)->tearDown();
  177. $tempManager->clean();
  178. $jobList->setLastJob($job);
  179. $executedJobs[$job->getId()] = true;
  180. unset($job);
  181. if ($timeAfter > $endTime) {
  182. break;
  183. }
  184. }
  185. } else {
  186. // We call cron.php from some website
  187. if ($appMode === 'cron') {
  188. // Cron is cron :-P
  189. OC_JSON::error(['data' => ['message' => 'Backgroundjobs are using system cron!']]);
  190. } else {
  191. // Work and success :-)
  192. $jobList = Server::get(IJobList::class);
  193. $job = $jobList->getNext();
  194. if ($job != null) {
  195. $logger->debug('WebCron call has selected job with ID ' . strval($job->getId()), ['app' => 'cron']);
  196. /** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
  197. $job->execute($jobList);
  198. $jobList->setLastJob($job);
  199. }
  200. OC_JSON::success();
  201. }
  202. }
  203. // Log the successful cron execution
  204. $appConfig->setValueInt('core', 'lastcron', time());
  205. exit();
  206. } catch (Exception $ex) {
  207. Server::get(LoggerInterface::class)->error(
  208. $ex->getMessage(),
  209. ['app' => 'cron', 'exception' => $ex]
  210. );
  211. echo $ex . PHP_EOL;
  212. exit(1);
  213. } catch (Error $ex) {
  214. Server::get(LoggerInterface::class)->error(
  215. $ex->getMessage(),
  216. ['app' => 'cron', 'exception' => $ex]
  217. );
  218. echo $ex . PHP_EOL;
  219. exit(1);
  220. }