Merge branch 'MDL-65349-profile-match-greedy' of https://github.com/brendanheywood...
[moodle.git] / lib / cronlib.php
blob8de7602fe3098e792a9f1ba9eecfe1c9bf983022
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.
132 function cron_run_adhoc_tasks(int $timenow) {
133 // Allow a restriction on the number of adhoc task runners at once.
134 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
135 $maxruns = get_config('core', 'task_adhoc_concurrency_limit');
136 $maxruntime = get_config('core', 'task_adhoc_max_runtime');
138 $adhoclock = null;
139 for ($run = 0; $run < $maxruns; $run++) {
140 if ($adhoclock = $cronlockfactory->get_lock("adhoc_task_runner_{$run}", 1)) {
141 break;
145 if (!$adhoclock) {
146 mtrace("Skipping processing of adhoc tasks. Concurrency limit reached.");
147 return;
150 $starttime = time();
152 // Run all adhoc tasks.
153 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
154 $task = \core\task\manager::get_next_adhoc_task($timenow)) {
155 cron_run_inner_adhoc_task($task);
156 unset($task);
158 if ((time() - $starttime) > $maxruntime) {
159 mtrace("Stopping processing of adhoc tasks as time limit has been reached.");
160 break;
164 // Release the adhoc task runner lock.
165 $adhoclock->release();
169 * Shared code that handles running of a single scheduled task within the cron.
171 * Not intended for calling directly outside of this library!
173 * @param \core\task\task_base $task
175 function cron_run_inner_scheduled_task(\core\task\task_base $task) {
176 global $CFG, $DB;
178 \core\task\logmanager::start_logging($task);
180 $fullname = $task->get_name() . ' (' . get_class($task) . ')';
181 mtrace('Execute scheduled task: ' . $fullname);
182 cron_trace_time_and_memory();
183 $predbqueries = null;
184 $predbqueries = $DB->perf_get_queries();
185 $pretime = microtime(1);
186 try {
187 get_mailer('buffer');
188 cron_prepare_core_renderer();
189 $task->execute();
190 if ($DB->is_transaction_started()) {
191 throw new coding_exception("Task left transaction open");
193 if (isset($predbqueries)) {
194 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
195 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
197 mtrace('Scheduled task complete: ' . $fullname);
198 \core\task\manager::scheduled_task_complete($task);
199 } catch (Exception $e) {
200 if ($DB && $DB->is_transaction_started()) {
201 error_log('Database transaction aborted automatically in ' . get_class($task));
202 $DB->force_transaction_rollback();
204 if (isset($predbqueries)) {
205 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
206 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
208 mtrace('Scheduled task failed: ' . $fullname . ',' . $e->getMessage());
209 if ($CFG->debugdeveloper) {
210 if (!empty($e->debuginfo)) {
211 mtrace("Debug info:");
212 mtrace($e->debuginfo);
214 mtrace("Backtrace:");
215 mtrace(format_backtrace($e->getTrace(), true));
217 \core\task\manager::scheduled_task_failed($task);
218 } finally {
219 cron_prepare_core_renderer(true);
221 get_mailer('close');
225 * Shared code that handles running of a single adhoc task within the cron.
227 * @param \core\task\adhoc_task $task
229 function cron_run_inner_adhoc_task(\core\task\adhoc_task $task) {
230 global $DB, $CFG;
232 \core\task\logmanager::start_logging($task);
234 mtrace("Execute adhoc task: " . get_class($task));
235 cron_trace_time_and_memory();
236 $predbqueries = null;
237 $predbqueries = $DB->perf_get_queries();
238 $pretime = microtime(1);
240 if ($userid = $task->get_userid()) {
241 // This task has a userid specified.
242 if ($user = \core_user::get_user($userid)) {
243 // User found. Check that they are suitable.
244 try {
245 \core_user::require_active_user($user, true, true);
246 } catch (moodle_exception $e) {
247 mtrace("User {$userid} cannot be used to run an adhoc task: " . get_class($task) . ". Cancelling task.");
248 $user = null;
250 } else {
251 // Unable to find the user for this task.
252 // A user missing in the database will never reappear.
253 mtrace("User {$userid} could not be found for adhoc task: " . get_class($task) . ". Cancelling task.");
256 if (empty($user)) {
257 // A user missing in the database will never reappear so the task needs to be failed to ensure that locks are removed,
258 // and then removed to prevent future runs.
259 // A task running as a user should only be run as that user.
260 \core\task\manager::adhoc_task_failed($task);
261 $DB->delete_records('task_adhoc', ['id' => $task->get_id()]);
263 return;
266 cron_setup_user($user);
269 try {
270 get_mailer('buffer');
271 cron_prepare_core_renderer();
272 $task->execute();
273 if ($DB->is_transaction_started()) {
274 throw new coding_exception("Task left transaction open");
276 if (isset($predbqueries)) {
277 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
278 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
280 mtrace("Adhoc task complete: " . get_class($task));
281 \core\task\manager::adhoc_task_complete($task);
282 } catch (Exception $e) {
283 if ($DB && $DB->is_transaction_started()) {
284 error_log('Database transaction aborted automatically in ' . get_class($task));
285 $DB->force_transaction_rollback();
287 if (isset($predbqueries)) {
288 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
289 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
291 mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
292 if ($CFG->debugdeveloper) {
293 if (!empty($e->debuginfo)) {
294 mtrace("Debug info:");
295 mtrace($e->debuginfo);
297 mtrace("Backtrace:");
298 mtrace(format_backtrace($e->getTrace(), true));
300 \core\task\manager::adhoc_task_failed($task);
301 } finally {
302 // Reset back to the standard admin user.
303 cron_setup_user();
304 cron_prepare_core_renderer(true);
306 get_mailer('close');
310 * Runs a single cron task. This function assumes it is displaying output in pseudo-CLI mode.
312 * The function will fail if the task is disabled.
314 * Warning: Because this function closes the browser session, it may not be safe to continue
315 * with other processing (other than displaying the rest of the page) after using this function!
317 * @param \core\task\scheduled_task $task Task to run
318 * @return bool True if cron run successful
320 function cron_run_single_task(\core\task\scheduled_task $task) {
321 global $CFG, $DB, $USER;
323 if (CLI_MAINTENANCE) {
324 echo "CLI maintenance mode active, cron execution suspended.\n";
325 return false;
328 if (moodle_needs_upgrading()) {
329 echo "Moodle upgrade pending, cron execution suspended.\n";
330 return false;
333 // Check task and component is not disabled.
334 $taskname = get_class($task);
335 if ($task->get_disabled()) {
336 echo "Task is disabled ($taskname).\n";
337 return false;
339 $component = $task->get_component();
340 if ($plugininfo = core_plugin_manager::instance()->get_plugin_info($component)) {
341 if ($plugininfo->is_enabled() === false && !$task->get_run_if_component_disabled()) {
342 echo "Component is not enabled ($component).\n";
343 return false;
347 // Enable debugging features as per config settings.
348 if (!empty($CFG->showcronsql)) {
349 $DB->set_debug(true);
351 if (!empty($CFG->showcrondebugging)) {
352 set_debugging(DEBUG_DEVELOPER, true);
355 // Increase time and memory limits.
356 core_php_time_limit::raise();
357 raise_memory_limit(MEMORY_EXTRA);
359 // Switch to admin account for cron tasks, but close the session so we don't send this stuff
360 // to the browser.
361 session_write_close();
362 $realuser = clone($USER);
363 cron_setup_user(null, null, true);
365 // Get lock for cron task.
366 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
367 if (!$cronlock = $cronlockfactory->get_lock('core_cron', 1)) {
368 echo "Unable to get cron lock.\n";
369 return false;
371 if (!$lock = $cronlockfactory->get_lock($taskname, 1)) {
372 $cronlock->release();
373 echo "Unable to get task lock for $taskname.\n";
374 return false;
376 $task->set_lock($lock);
377 if (!$task->is_blocking()) {
378 $cronlock->release();
379 } else {
380 $task->set_cron_lock($cronlock);
383 // Run actual tasks.
384 cron_run_inner_scheduled_task($task);
386 // Go back to real user account.
387 cron_setup_user($realuser, null, true);
389 return true;
393 * Output some standard information during cron runs. Specifically current time
394 * and memory usage. This method also does gc_collect_cycles() (before displaying
395 * memory usage) to try to help PHP manage memory better.
397 function cron_trace_time_and_memory() {
398 gc_collect_cycles();
399 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
403 * Executes cron functions for a specific type of plugin.
405 * @param string $plugintype Plugin type (e.g. 'report')
406 * @param string $description If specified, will display 'Starting (whatever)'
407 * and 'Finished (whatever)' lines, otherwise does not display
409 function cron_execute_plugin_type($plugintype, $description = null) {
410 global $DB;
412 // Get list from plugin => function for all plugins
413 $plugins = get_plugin_list_with_function($plugintype, 'cron');
415 // Modify list for backward compatibility (different files/names)
416 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
418 // Return if no plugins with cron function to process
419 if (!$plugins) {
420 return;
423 if ($description) {
424 mtrace('Starting '.$description);
427 foreach ($plugins as $component=>$cronfunction) {
428 $dir = core_component::get_component_directory($component);
430 // Get cron period if specified in version.php, otherwise assume every cron
431 $cronperiod = 0;
432 if (file_exists("$dir/version.php")) {
433 $plugin = new stdClass();
434 include("$dir/version.php");
435 if (isset($plugin->cron)) {
436 $cronperiod = $plugin->cron;
440 // Using last cron and cron period, don't run if it already ran recently
441 $lastcron = get_config($component, 'lastcron');
442 if ($cronperiod && $lastcron) {
443 if ($lastcron + $cronperiod > time()) {
444 // do not execute cron yet
445 continue;
449 mtrace('Processing cron function for ' . $component . '...');
450 cron_trace_time_and_memory();
451 $pre_dbqueries = $DB->perf_get_queries();
452 $pre_time = microtime(true);
454 $cronfunction();
456 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
457 round(microtime(true) - $pre_time, 2) . " seconds)");
459 set_config('lastcron', time(), $component);
460 core_php_time_limit::raise();
463 if ($description) {
464 mtrace('Finished ' . $description);
469 * Used to add in old-style cron functions within plugins that have not been converted to the
470 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
471 * cron.php and some used a different name.)
473 * @param string $plugintype Plugin type e.g. 'report'
474 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
475 * 'report_frog_cron') for plugin cron functions that were already found using the new API
476 * @return array Revised version of $plugins that adds in any extra plugin functions found by
477 * looking in the older location
479 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
480 global $CFG; // mandatory in case it is referenced by include()d PHP script
482 if ($plugintype === 'report') {
483 // Admin reports only - not course report because course report was
484 // never implemented before, so doesn't need BC
485 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
486 $component = $plugintype . '_' . $pluginname;
487 if (isset($plugins[$component])) {
488 // We already have detected the function using the new API
489 continue;
491 if (!file_exists("$dir/cron.php")) {
492 // No old style cron file present
493 continue;
495 include_once("$dir/cron.php");
496 $cronfunction = $component . '_cron';
497 if (function_exists($cronfunction)) {
498 $plugins[$component] = $cronfunction;
499 } else {
500 debugging("Invalid legacy cron.php detected in $component, " .
501 "please use lib.php instead");
504 } else if (strpos($plugintype, 'grade') === 0) {
505 // Detect old style cron function names
506 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
507 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
508 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
509 $component = $plugintype.'_'.$pluginname;
510 if (isset($plugins[$component])) {
511 // We already have detected the function using the new API
512 continue;
514 if (!file_exists("$dir/lib.php")) {
515 continue;
517 include_once("$dir/lib.php");
518 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
519 $pluginname . '_cron';
520 if (function_exists($cronfunction)) {
521 $plugins[$component] = $cronfunction;
526 return $plugins;
530 * Prepare the output renderer for the cron run.
532 * This involves creating a new $PAGE, and $OUTPUT fresh for each task and prevents any one task from influencing
533 * any other.
535 * @param bool $restore Whether to restore the original PAGE and OUTPUT
537 function cron_prepare_core_renderer($restore = false) {
538 global $OUTPUT, $PAGE;
540 // Store the original PAGE and OUTPUT values so that they can be reset at a later point to the original.
541 // This should not normally be required, but may be used in places such as the scheduled task tool's "Run now"
542 // functionality.
543 static $page = null;
544 static $output = null;
546 if (null === $page) {
547 $page = $PAGE;
550 if (null === $output) {
551 $output = $OUTPUT;
554 if (!empty($restore)) {
555 $PAGE = $page;
556 $page = null;
558 $OUTPUT = $output;
559 $output = null;
560 } else {
561 // Setup a new General renderer.
562 // Cron tasks may produce output to be used in web, so we must use the appropriate renderer target.
563 // This allows correct use of templates, etc.
564 $PAGE = new \moodle_page();
565 $OUTPUT = new \core_renderer($PAGE, RENDERER_TARGET_GENERAL);