1
0

cron.php 8.2 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 ($argv[1] === '-h' || $argv[1] === '--help') {
  55. echo 'Description:
  56. Run the background job routine
  57. Usage:
  58. php -f cron.php -- [-h] [<job-classes>...]
  59. Arguments:
  60. job-classes Optional job class list to only run those jobs
  61. Options:
  62. -h, --help Display this help message' . PHP_EOL;
  63. exit(0);
  64. }
  65. if (Util::needUpgrade()) {
  66. Server::get(LoggerInterface::class)->debug('Update required, skipping cron', ['app' => 'cron']);
  67. exit;
  68. }
  69. $config = Server::get(IConfig::class);
  70. if ($config->getSystemValueBool('maintenance', false)) {
  71. Server::get(LoggerInterface::class)->debug('We are in maintenance mode, skipping cron', ['app' => 'cron']);
  72. exit;
  73. }
  74. // Don't do anything if Nextcloud has not been installed
  75. if (!$config->getSystemValueBool('installed', false)) {
  76. exit(0);
  77. }
  78. // load all apps to get all api routes properly setup
  79. Server::get(IAppManager::class)->loadApps();
  80. Server::get(ISession::class)->close();
  81. // initialize a dummy memory session
  82. $session = new \OC\Session\Memory('');
  83. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  84. $session = $cryptoWrapper->wrapSession($session);
  85. \OC::$server->setSession($session);
  86. $logger = Server::get(LoggerInterface::class);
  87. $appConfig = Server::get(IAppConfig::class);
  88. $tempManager = Server::get(ITempManager::class);
  89. $tempManager->cleanOld();
  90. // Exit if background jobs are disabled!
  91. $appMode = $appConfig->getValueString('core', 'backgroundjobs_mode', 'ajax');
  92. if ($appMode === 'none') {
  93. if (OC::$CLI) {
  94. echo 'Background Jobs are disabled!' . PHP_EOL;
  95. } else {
  96. OC_JSON::error(['data' => ['message' => 'Background jobs disabled!']]);
  97. }
  98. exit(1);
  99. }
  100. if (OC::$CLI) {
  101. // set to run indefinitely if needed
  102. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  103. @set_time_limit(0);
  104. }
  105. // the cron job must be executed with the right user
  106. if (!function_exists('posix_getuid')) {
  107. echo "The posix extensions are required - see https://www.php.net/manual/en/book.posix.php" . PHP_EOL;
  108. exit(1);
  109. }
  110. $user = posix_getuid();
  111. $configUser = fileowner(OC::$configDir . 'config.php');
  112. if ($user !== $configUser) {
  113. echo "Console has to be executed with the user that owns the file config/config.php" . PHP_EOL;
  114. echo "Current user id: " . $user . PHP_EOL;
  115. echo "Owner id of config.php: " . $configUser . PHP_EOL;
  116. exit(1);
  117. }
  118. // We call Nextcloud from the CLI (aka cron)
  119. if ($appMode !== 'cron') {
  120. $appConfig->setValueString('core', 'backgroundjobs_mode', 'cron');
  121. }
  122. // Low-load hours
  123. $onlyTimeSensitive = false;
  124. $startHour = $config->getSystemValueInt('maintenance_window_start', 100);
  125. if ($startHour <= 23) {
  126. $date = new \DateTime('now', new \DateTimeZone('UTC'));
  127. $currentHour = (int) $date->format('G');
  128. $endHour = $startHour + 4;
  129. if ($startHour <= 20) {
  130. // Start time: 01:00
  131. // End time: 05:00
  132. // Only run sensitive tasks when it's before the start or after the end
  133. $onlyTimeSensitive = $currentHour < $startHour || $currentHour > $endHour;
  134. } else {
  135. // Start time: 23:00
  136. // End time: 03:00
  137. $endHour -= 24; // Correct the end time from 27:00 to 03:00
  138. // Only run sensitive tasks when it's after the end and before the start
  139. $onlyTimeSensitive = $currentHour > $endHour && $currentHour < $startHour;
  140. }
  141. }
  142. // Work
  143. $jobList = Server::get(IJobList::class);
  144. // We only ask for jobs for 14 minutes, because after 5 minutes the next
  145. // system cron task should spawn and we want to have at most three
  146. // cron jobs running in parallel.
  147. $endTime = time() + 14 * 60;
  148. $executedJobs = [];
  149. // a specific job class list can optionally be given as argument
  150. $jobClasses = array_slice($argv, 1);
  151. $jobClasses = empty($jobClasses) ? null : $jobClasses;
  152. while ($job = $jobList->getNext($onlyTimeSensitive, $jobClasses)) {
  153. if (isset($executedJobs[$job->getId()])) {
  154. $jobList->unlockJob($job);
  155. break;
  156. }
  157. $jobDetails = get_class($job) . ' (id: ' . $job->getId() . ', arguments: ' . json_encode($job->getArgument()) . ')';
  158. $logger->debug('CLI cron call has selected job ' . $jobDetails, ['app' => 'cron']);
  159. $memoryBefore = memory_get_usage();
  160. $memoryPeakBefore = memory_get_peak_usage();
  161. /** @psalm-suppress DeprecatedMethod Calling execute until it is removed, then will switch to start */
  162. $job->execute($jobList);
  163. $memoryAfter = memory_get_usage();
  164. $memoryPeakAfter = memory_get_peak_usage();
  165. if ($memoryAfter - $memoryBefore > 10_000_000) {
  166. $logger->warning('Used memory grew by more than 10 MB when executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryAfter). ' (before: ' . Util::humanFileSize($memoryBefore) . ')', ['app' => 'cron']);
  167. }
  168. if ($memoryPeakAfter > 300_000_000) {
  169. $logger->warning('Cron job used more than 300 MB of ram after executing job ' . $jobDetails . ': ' . Util::humanFileSize($memoryPeakAfter) . ' (before: ' . Util::humanFileSize($memoryPeakBefore) . ')', ['app' => 'cron']);
  170. }
  171. // clean up after unclean jobs
  172. Server::get(\OC\Files\SetupManager::class)->tearDown();
  173. $tempManager->clean();
  174. $jobList->setLastJob($job);
  175. $executedJobs[$job->getId()] = true;
  176. unset($job);
  177. if (time() > $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. }