cron.php 7.0 KB

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