1
0

cron.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. $job->start($jobList);
  148. $memoryAfter = memory_get_usage();
  149. $memoryPeakAfter = memory_get_peak_usage();
  150. if ($memoryAfter - $memoryBefore > 10_000_000) {
  151. $logger->warning('Used memory grew by more than 10 MB when executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryAfter). ' (before: ' . Util::humanFileSize($memoryBefore) . ')', ['app' => 'cron']);
  152. }
  153. if ($memoryPeakAfter > 300_000_000) {
  154. $logger->warning('Cron job used more than 300 MB of ram after executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryPeakAfter) . ' (before: ' . Util::humanFileSize($memoryPeakBefore) . ')', ['app' => 'cron']);
  155. }
  156. // clean up after unclean jobs
  157. Server::get(\OC\Files\SetupManager::class)->tearDown();
  158. $tempManager->clean();
  159. $jobList->setLastJob($job);
  160. $executedJobs[$job->getId()] = true;
  161. unset($job);
  162. if (time() > $endTime) {
  163. break;
  164. }
  165. }
  166. } else {
  167. // We call cron.php from some website
  168. if ($appMode === 'cron') {
  169. // Cron is cron :-P
  170. OC_JSON::error(['data' => ['message' => 'Backgroundjobs are using system cron!']]);
  171. } else {
  172. // Work and success :-)
  173. $jobList = Server::get(IJobList::class);
  174. $job = $jobList->getNext();
  175. if ($job != null) {
  176. $logger->debug('WebCron call has selected job with ID ' . strval($job->getId()), ['app' => 'cron']);
  177. $job->start($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. }