Merge branch 'MDL-58281-file-missing-500' of https://github.com/brendanheywood/moodle
[moodle.git] / lib / cronlib.php
blob4ad08cbbaa60163934f555f4e3ac1cb98fe520d1
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Cron functions.
20 * @package core
21 * @subpackage admin
22 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 /**
27 * Execute cron tasks
29 function cron_run() {
30 global $DB, $CFG, $OUTPUT;
32 if (CLI_MAINTENANCE) {
33 echo "CLI maintenance mode active, cron execution suspended.\n";
34 exit(1);
37 if (moodle_needs_upgrading()) {
38 echo "Moodle upgrade pending, cron execution suspended.\n";
39 exit(1);
42 require_once($CFG->libdir.'/adminlib.php');
44 if (!empty($CFG->showcronsql)) {
45 $DB->set_debug(true);
47 if (!empty($CFG->showcrondebugging)) {
48 set_debugging(DEBUG_DEVELOPER, true);
51 core_php_time_limit::raise();
52 $starttime = microtime();
54 // Increase memory limit
55 raise_memory_limit(MEMORY_EXTRA);
57 // Emulate normal session - we use admin accoutn by default
58 cron_setup_user();
60 // Start output log
61 $timenow = time();
62 mtrace("Server Time: ".date('r', $timenow)."\n\n");
64 // Record start time and interval between the last cron runs.
65 $laststart = get_config('tool_task', 'lastcronstart');
66 set_config('lastcronstart', $timenow, 'tool_task');
67 if ($laststart) {
68 // Record the interval between last two runs (always store at least 1 second).
69 set_config('lastcroninterval', max(1, $timenow - $laststart), 'tool_task');
72 // Run all scheduled tasks.
73 cron_run_scheduled_tasks($timenow);
75 // Run adhoc tasks.
76 cron_run_adhoc_tasks($timenow);
78 mtrace("Cron script completed correctly");
80 gc_collect_cycles();
81 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
82 $difftime = microtime_diff($starttime, microtime());
83 mtrace("Execution took ".$difftime." seconds");
86 /**
87 * Execute all queued scheduled tasks, applying necessary concurrency limits and time limits.
89 * @param int $timenow The time this process started.
91 function cron_run_scheduled_tasks(int $timenow) {
92 // Allow a restriction on the number of scheduled task runners at once.
93 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
94 $maxruns = get_config('core', 'task_scheduled_concurrency_limit');
95 $maxruntime = get_config('core', 'task_scheduled_max_runtime');
97 $scheduledlock = null;
98 for ($run = 0; $run < $maxruns; $run++) {
99 if ($scheduledlock = $cronlockfactory->get_lock("scheduled_task_runner_{$run}", 1)) {
100 break;
104 if (!$scheduledlock) {
105 mtrace("Skipping processing of scheduled tasks. Concurrency limit reached.");
106 return;
109 $starttime = time();
111 // Run all scheduled tasks.
112 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
113 $task = \core\task\manager::get_next_scheduled_task($timenow)) {
114 cron_run_inner_scheduled_task($task);
115 unset($task);
117 if ((time() - $starttime) > $maxruntime) {
118 mtrace("Stopping processing of scheduled tasks as time limit has been reached.");
119 break;
123 // Release the scheduled task runner lock.
124 $scheduledlock->release();
128 * Execute all queued adhoc tasks, applying necessary concurrency limits and time limits.
130 * @param int $timenow The time this process started.
131 * @param int $keepalive Keep this function alive for N seconds and poll for new adhoc tasks.
132 * @param bool $checklimits Should we check limits?
134 function cron_run_adhoc_tasks(int $timenow, $keepalive = 0, $checklimits = true) {
135 // Allow a restriction on the number of adhoc task runners at once.
136 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
137 $maxruns = get_config('core', 'task_adhoc_concurrency_limit');
138 $maxruntime = get_config('core', 'task_adhoc_max_runtime');
140 if ($checklimits) {
141 $adhoclock = null;
142 for ($run = 0; $run < $maxruns; $run++) {
143 if ($adhoclock = $cronlockfactory->get_lock("adhoc_task_runner_{$run}", 1)) {
144 break;
148 if (!$adhoclock) {
149 mtrace("Skipping processing of adhoc tasks. Concurrency limit reached.");
150 return;
154 $humantimenow = date('r', $timenow);
155 $finishtime = $timenow + $keepalive;
156 $waiting = false;
157 $taskcount = 0;
159 // Run all adhoc tasks.
160 while (!\core\task\manager::static_caches_cleared_since($timenow)) {
162 if ($checklimits && (time() - $timenow) >= $maxruntime) {
163 if ($waiting) {
164 $waiting = false;
165 mtrace('');
167 mtrace("Stopping processing of adhoc tasks as time limit has been reached.");
168 break;
171 $task = \core\task\manager::get_next_adhoc_task(time(), $checklimits);
173 if ($task) {
174 if ($waiting) {
175 mtrace('');
177 $waiting = false;
178 cron_run_inner_adhoc_task($task);
179 $taskcount++;
180 unset($task);
181 } else {
182 if (time() >= $finishtime) {
183 break;
185 if (!$waiting) {
186 mtrace('Waiting for more adhoc tasks to be queued ', '');
187 } else {
188 mtrace('.', '');
190 $waiting = true;
191 sleep(1);
195 if ($waiting) {
196 mtrace('');
199 mtrace("Ran {$taskcount} adhoc tasks found at {$humantimenow}");
201 if ($adhoclock) {
202 // Release the adhoc task runner lock.
203 $adhoclock->release();
208 * Shared code that handles running of a single scheduled task within the cron.
210 * Not intended for calling directly outside of this library!
212 * @param \core\task\task_base $task
214 function cron_run_inner_scheduled_task(\core\task\task_base $task) {
215 global $CFG, $DB;
217 \core\task\logmanager::start_logging($task);
219 $fullname = $task->get_name() . ' (' . get_class($task) . ')';
220 mtrace('Execute scheduled task: ' . $fullname);
221 cron_trace_time_and_memory();
222 $predbqueries = null;
223 $predbqueries = $DB->perf_get_queries();
224 $pretime = microtime(1);
225 try {
226 get_mailer('buffer');
227 cron_prepare_core_renderer();
228 $task->execute();
229 if ($DB->is_transaction_started()) {
230 throw new coding_exception("Task left transaction open");
232 if (isset($predbqueries)) {
233 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
234 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
236 mtrace('Scheduled task complete: ' . $fullname);
237 \core\task\manager::scheduled_task_complete($task);
238 } catch (Exception $e) {
239 if ($DB && $DB->is_transaction_started()) {
240 error_log('Database transaction aborted automatically in ' . get_class($task));
241 $DB->force_transaction_rollback();
243 if (isset($predbqueries)) {
244 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
245 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
247 mtrace('Scheduled task failed: ' . $fullname . ',' . $e->getMessage());
248 if ($CFG->debugdeveloper) {
249 if (!empty($e->debuginfo)) {
250 mtrace("Debug info:");
251 mtrace($e->debuginfo);
253 mtrace("Backtrace:");
254 mtrace(format_backtrace($e->getTrace(), true));
256 \core\task\manager::scheduled_task_failed($task);
257 } finally {
258 cron_prepare_core_renderer(true);
260 get_mailer('close');
264 * Shared code that handles running of a single adhoc task within the cron.
266 * @param \core\task\adhoc_task $task
268 function cron_run_inner_adhoc_task(\core\task\adhoc_task $task) {
269 global $DB, $CFG;
271 \core\task\logmanager::start_logging($task);
273 mtrace("Execute adhoc task: " . get_class($task));
274 cron_trace_time_and_memory();
275 $predbqueries = null;
276 $predbqueries = $DB->perf_get_queries();
277 $pretime = microtime(1);
279 if ($userid = $task->get_userid()) {
280 // This task has a userid specified.
281 if ($user = \core_user::get_user($userid)) {
282 // User found. Check that they are suitable.
283 try {
284 \core_user::require_active_user($user, true, true);
285 } catch (moodle_exception $e) {
286 mtrace("User {$userid} cannot be used to run an adhoc task: " . get_class($task) . ". Cancelling task.");
287 $user = null;
289 } else {
290 // Unable to find the user for this task.
291 // A user missing in the database will never reappear.
292 mtrace("User {$userid} could not be found for adhoc task: " . get_class($task) . ". Cancelling task.");
295 if (empty($user)) {
296 // A user missing in the database will never reappear so the task needs to be failed to ensure that locks are removed,
297 // and then removed to prevent future runs.
298 // A task running as a user should only be run as that user.
299 \core\task\manager::adhoc_task_failed($task);
300 $DB->delete_records('task_adhoc', ['id' => $task->get_id()]);
302 return;
305 cron_setup_user($user);
308 try {
309 get_mailer('buffer');
310 cron_prepare_core_renderer();
311 $task->execute();
312 if ($DB->is_transaction_started()) {
313 throw new coding_exception("Task left transaction open");
315 if (isset($predbqueries)) {
316 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
317 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
319 mtrace("Adhoc task complete: " . get_class($task));
320 \core\task\manager::adhoc_task_complete($task);
321 } catch (Exception $e) {
322 if ($DB && $DB->is_transaction_started()) {
323 error_log('Database transaction aborted automatically in ' . get_class($task));
324 $DB->force_transaction_rollback();
326 if (isset($predbqueries)) {
327 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
328 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
330 mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
331 if ($CFG->debugdeveloper) {
332 if (!empty($e->debuginfo)) {
333 mtrace("Debug info:");
334 mtrace($e->debuginfo);
336 mtrace("Backtrace:");
337 mtrace(format_backtrace($e->getTrace(), true));
339 \core\task\manager::adhoc_task_failed($task);
340 } finally {
341 // Reset back to the standard admin user.
342 cron_setup_user();
343 cron_prepare_core_renderer(true);
345 get_mailer('close');
349 * Runs a single cron task. This function assumes it is displaying output in pseudo-CLI mode.
351 * The function will fail if the task is disabled.
353 * Warning: Because this function closes the browser session, it may not be safe to continue
354 * with other processing (other than displaying the rest of the page) after using this function!
356 * @param \core\task\scheduled_task $task Task to run
357 * @return bool True if cron run successful
359 function cron_run_single_task(\core\task\scheduled_task $task) {
360 global $CFG, $DB, $USER;
362 if (CLI_MAINTENANCE) {
363 echo "CLI maintenance mode active, cron execution suspended.\n";
364 return false;
367 if (moodle_needs_upgrading()) {
368 echo "Moodle upgrade pending, cron execution suspended.\n";
369 return false;
372 // Check task and component is not disabled.
373 $taskname = get_class($task);
374 if ($task->get_disabled()) {
375 echo "Task is disabled ($taskname).\n";
376 return false;
378 $component = $task->get_component();
379 if ($plugininfo = core_plugin_manager::instance()->get_plugin_info($component)) {
380 if ($plugininfo->is_enabled() === false && !$task->get_run_if_component_disabled()) {
381 echo "Component is not enabled ($component).\n";
382 return false;
386 // Enable debugging features as per config settings.
387 if (!empty($CFG->showcronsql)) {
388 $DB->set_debug(true);
390 if (!empty($CFG->showcrondebugging)) {
391 set_debugging(DEBUG_DEVELOPER, true);
394 // Increase time and memory limits.
395 core_php_time_limit::raise();
396 raise_memory_limit(MEMORY_EXTRA);
398 // Switch to admin account for cron tasks, but close the session so we don't send this stuff
399 // to the browser.
400 session_write_close();
401 $realuser = clone($USER);
402 cron_setup_user(null, null, true);
404 // Get lock for cron task.
405 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
406 if (!$cronlock = $cronlockfactory->get_lock('core_cron', 1)) {
407 echo "Unable to get cron lock.\n";
408 return false;
410 if (!$lock = $cronlockfactory->get_lock($taskname, 1)) {
411 $cronlock->release();
412 echo "Unable to get task lock for $taskname.\n";
413 return false;
415 $task->set_lock($lock);
416 if (!$task->is_blocking()) {
417 $cronlock->release();
418 } else {
419 $task->set_cron_lock($cronlock);
422 // Run actual tasks.
423 cron_run_inner_scheduled_task($task);
425 // Go back to real user account.
426 cron_setup_user($realuser, null, true);
428 return true;
432 * Output some standard information during cron runs. Specifically current time
433 * and memory usage. This method also does gc_collect_cycles() (before displaying
434 * memory usage) to try to help PHP manage memory better.
436 function cron_trace_time_and_memory() {
437 gc_collect_cycles();
438 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
442 * Executes cron functions for a specific type of plugin.
444 * @param string $plugintype Plugin type (e.g. 'report')
445 * @param string $description If specified, will display 'Starting (whatever)'
446 * and 'Finished (whatever)' lines, otherwise does not display
448 function cron_execute_plugin_type($plugintype, $description = null) {
449 global $DB;
451 // Get list from plugin => function for all plugins
452 $plugins = get_plugin_list_with_function($plugintype, 'cron');
454 // Modify list for backward compatibility (different files/names)
455 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
457 // Return if no plugins with cron function to process
458 if (!$plugins) {
459 return;
462 if ($description) {
463 mtrace('Starting '.$description);
466 foreach ($plugins as $component=>$cronfunction) {
467 $dir = core_component::get_component_directory($component);
469 // Get cron period if specified in version.php, otherwise assume every cron
470 $cronperiod = 0;
471 if (file_exists("$dir/version.php")) {
472 $plugin = new stdClass();
473 include("$dir/version.php");
474 if (isset($plugin->cron)) {
475 $cronperiod = $plugin->cron;
479 // Using last cron and cron period, don't run if it already ran recently
480 $lastcron = get_config($component, 'lastcron');
481 if ($cronperiod && $lastcron) {
482 if ($lastcron + $cronperiod > time()) {
483 // do not execute cron yet
484 continue;
488 mtrace('Processing cron function for ' . $component . '...');
489 cron_trace_time_and_memory();
490 $pre_dbqueries = $DB->perf_get_queries();
491 $pre_time = microtime(true);
493 $cronfunction();
495 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
496 round(microtime(true) - $pre_time, 2) . " seconds)");
498 set_config('lastcron', time(), $component);
499 core_php_time_limit::raise();
502 if ($description) {
503 mtrace('Finished ' . $description);
508 * Used to add in old-style cron functions within plugins that have not been converted to the
509 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
510 * cron.php and some used a different name.)
512 * @param string $plugintype Plugin type e.g. 'report'
513 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
514 * 'report_frog_cron') for plugin cron functions that were already found using the new API
515 * @return array Revised version of $plugins that adds in any extra plugin functions found by
516 * looking in the older location
518 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
519 global $CFG; // mandatory in case it is referenced by include()d PHP script
521 if ($plugintype === 'report') {
522 // Admin reports only - not course report because course report was
523 // never implemented before, so doesn't need BC
524 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
525 $component = $plugintype . '_' . $pluginname;
526 if (isset($plugins[$component])) {
527 // We already have detected the function using the new API
528 continue;
530 if (!file_exists("$dir/cron.php")) {
531 // No old style cron file present
532 continue;
534 include_once("$dir/cron.php");
535 $cronfunction = $component . '_cron';
536 if (function_exists($cronfunction)) {
537 $plugins[$component] = $cronfunction;
538 } else {
539 debugging("Invalid legacy cron.php detected in $component, " .
540 "please use lib.php instead");
543 } else if (strpos($plugintype, 'grade') === 0) {
544 // Detect old style cron function names
545 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
546 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
547 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
548 $component = $plugintype.'_'.$pluginname;
549 if (isset($plugins[$component])) {
550 // We already have detected the function using the new API
551 continue;
553 if (!file_exists("$dir/lib.php")) {
554 continue;
556 include_once("$dir/lib.php");
557 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
558 $pluginname . '_cron';
559 if (function_exists($cronfunction)) {
560 $plugins[$component] = $cronfunction;
565 return $plugins;
569 * Prepare the output renderer for the cron run.
571 * This involves creating a new $PAGE, and $OUTPUT fresh for each task and prevents any one task from influencing
572 * any other.
574 * @param bool $restore Whether to restore the original PAGE and OUTPUT
576 function cron_prepare_core_renderer($restore = false) {
577 global $OUTPUT, $PAGE;
579 // Store the original PAGE and OUTPUT values so that they can be reset at a later point to the original.
580 // This should not normally be required, but may be used in places such as the scheduled task tool's "Run now"
581 // functionality.
582 static $page = null;
583 static $output = null;
585 if (null === $page) {
586 $page = $PAGE;
589 if (null === $output) {
590 $output = $OUTPUT;
593 if (!empty($restore)) {
594 $PAGE = $page;
595 $page = null;
597 $OUTPUT = $output;
598 $output = null;
599 } else {
600 // Setup a new General renderer.
601 // Cron tasks may produce output to be used in web, so we must use the appropriate renderer target.
602 // This allows correct use of templates, etc.
603 $PAGE = new \moodle_page();
604 $OUTPUT = new \core_renderer($PAGE, RENDERER_TARGET_GENERAL);