1
0

cron.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. $memoryBefore = memory_get_usage();
  146. $memoryPeakBefore = memory_get_peak_usage();
  147. /** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
  148. $job->execute($jobList);
  149. $memoryAfter = memory_get_usage();
  150. $memoryPeakAfter = memory_get_peak_usage();
  151. if ($memoryAfter - $memoryBefore > 10_000_000) {
  152. $logger->warning('Used memory grew by more than 10 MB when executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryAfter). ' (before: ' . Util::humanFileSize($memoryBefore) . ')', ['app' => 'cron']);
  153. }
  154. if ($memoryPeakAfter > 300_000_000) {
  155. $logger->warning('Cron job used more than 300 MB of ram after executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryPeakAfter) . ' (before: ' . Util::humanFileSize($memoryPeakBefore) . ')', ['app' => 'cron']);
  156. }
  157. // clean up after unclean jobs
  158. Server::get(\OC\Files\SetupManager::class)->tearDown();
  159. $tempManager->clean();
  160. $jobList->setLastJob($job);
  161. $executedJobs[$job->getId()] = true;
  162. unset($job);
  163. if (time() > $endTime) {
  164. break;
  165. }
  166. }
  167. } else {
  168. // We call cron.php from some website
  169. if ($appMode === 'cron') {
  170. // Cron is cron :-P
  171. OC_JSON::error(['data' => ['message' => 'Backgroundjobs are using system cron!']]);
  172. } else {
  173. // Work and success :-)
  174. $jobList = Server::get(IJobList::class);
  175. $job = $jobList->getNext();
  176. if ($job != null) {
  177. $logger->debug('WebCron call has selected job with ID ' . strval($job->getId()), ['app' => 'cron']);
  178. /** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
  179. $job->execute($jobList);
  180. $jobList->setLastJob($job);
  181. }
  182. OC_JSON::success();
  183. }
  184. }
  185. // Log the successful cron execution
  186. $appConfig->setValueInt('core', 'lastcron', time());
  187. exit();
  188. } catch (Exception $ex) {
  189. Server::get(LoggerInterface::class)->error(
  190. $ex->getMessage(),
  191. ['app' => 'cron', 'exception' => $ex]
  192. );
  193. echo $ex . PHP_EOL;
  194. exit(1);
  195. } catch (Error $ex) {
  196. Server::get(LoggerInterface::class)->error(
  197. $ex->getMessage(),
  198. ['app' => 'cron', 'exception' => $ex]
  199. );
  200. echo $ex . PHP_EOL;
  201. exit(1);
  202. }