MDL-67814 core_h5p: added renderer and editor classes
[moodle.git] / lib / cronlib.php
blobf15fae8dc85d97558e1ab48bdcd59aacc7327efb
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.
90 * @throws \moodle_exception
92 function cron_run_scheduled_tasks(int $timenow) {
93 // Allow a restriction on the number of scheduled task runners at once.
94 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
95 $maxruns = get_config('core', 'task_scheduled_concurrency_limit');
96 $maxruntime = get_config('core', 'task_scheduled_max_runtime');
98 $scheduledlock = null;
99 for ($run = 0; $run < $maxruns; $run++) {
100 // If we can't get a lock instantly it means runner N is already running
101 // so fail as fast as possible and try N+1 so we don't limit the speed at
102 // which we bring new runners into the pool.
103 if ($scheduledlock = $cronlockfactory->get_lock("scheduled_task_runner_{$run}", 0)) {
104 break;
108 if (!$scheduledlock) {
109 mtrace("Skipping processing of scheduled tasks. Concurrency limit reached.");
110 return;
113 $starttime = time();
115 // Run all scheduled tasks.
116 try {
117 while (!\core\local\cli\shutdown::should_gracefully_exit() &&
118 !\core\task\manager::static_caches_cleared_since($timenow) &&
119 $task = \core\task\manager::get_next_scheduled_task($timenow)) {
120 cron_run_inner_scheduled_task($task);
121 unset($task);
123 if ((time() - $starttime) > $maxruntime) {
124 mtrace("Stopping processing of scheduled tasks as time limit has been reached.");
125 break;
128 } finally {
129 // Release the scheduled task runner lock.
130 $scheduledlock->release();
135 * Execute all queued adhoc tasks, applying necessary concurrency limits and time limits.
137 * @param int $timenow The time this process started.
138 * @param int $keepalive Keep this function alive for N seconds and poll for new adhoc tasks.
139 * @param bool $checklimits Should we check limits?
140 * @throws \moodle_exception
142 function cron_run_adhoc_tasks(int $timenow, $keepalive = 0, $checklimits = true) {
143 // Allow a restriction on the number of adhoc task runners at once.
144 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
145 $maxruns = get_config('core', 'task_adhoc_concurrency_limit');
146 $maxruntime = get_config('core', 'task_adhoc_max_runtime');
148 if ($checklimits) {
149 $adhoclock = null;
150 for ($run = 0; $run < $maxruns; $run++) {
151 // If we can't get a lock instantly it means runner N is already running
152 // so fail as fast as possible and try N+1 so we don't limit the speed at
153 // which we bring new runners into the pool.
154 if ($adhoclock = $cronlockfactory->get_lock("adhoc_task_runner_{$run}", 0)) {
155 break;
159 if (!$adhoclock) {
160 mtrace("Skipping processing of adhoc tasks. Concurrency limit reached.");
161 return;
165 $humantimenow = date('r', $timenow);
166 $finishtime = $timenow + $keepalive;
167 $waiting = false;
168 $taskcount = 0;
170 // Run all adhoc tasks.
171 while (!\core\local\cli\shutdown::should_gracefully_exit() &&
172 !\core\task\manager::static_caches_cleared_since($timenow)) {
174 if ($checklimits && (time() - $timenow) >= $maxruntime) {
175 if ($waiting) {
176 $waiting = false;
177 mtrace('');
179 mtrace("Stopping processing of adhoc tasks as time limit has been reached.");
180 break;
183 try {
184 $task = \core\task\manager::get_next_adhoc_task(time(), $checklimits);
185 } catch (Exception $e) {
186 if ($adhoclock) {
187 // Release the adhoc task runner lock.
188 $adhoclock->release();
190 throw $e;
193 if ($task) {
194 if ($waiting) {
195 mtrace('');
197 $waiting = false;
198 cron_run_inner_adhoc_task($task);
199 $taskcount++;
200 unset($task);
201 } else {
202 if (time() >= $finishtime) {
203 break;
205 if (!$waiting) {
206 mtrace('Waiting for more adhoc tasks to be queued ', '');
207 } else {
208 mtrace('.', '');
210 $waiting = true;
211 sleep(1);
215 if ($waiting) {
216 mtrace('');
219 mtrace("Ran {$taskcount} adhoc tasks found at {$humantimenow}");
221 if ($adhoclock) {
222 // Release the adhoc task runner lock.
223 $adhoclock->release();
228 * Shared code that handles running of a single scheduled task within the cron.
230 * Not intended for calling directly outside of this library!
232 * @param \core\task\task_base $task
234 function cron_run_inner_scheduled_task(\core\task\task_base $task) {
235 global $CFG, $DB;
237 \core\task\logmanager::start_logging($task);
239 $fullname = $task->get_name() . ' (' . get_class($task) . ')';
240 mtrace('Execute scheduled task: ' . $fullname);
241 cron_trace_time_and_memory();
242 $predbqueries = null;
243 $predbqueries = $DB->perf_get_queries();
244 $pretime = microtime(1);
245 try {
246 get_mailer('buffer');
247 cron_prepare_core_renderer();
248 $task->execute();
249 if ($DB->is_transaction_started()) {
250 throw new coding_exception("Task left transaction open");
252 if (isset($predbqueries)) {
253 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
254 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
256 mtrace('Scheduled task complete: ' . $fullname);
257 \core\task\manager::scheduled_task_complete($task);
258 } catch (Exception $e) {
259 if ($DB && $DB->is_transaction_started()) {
260 error_log('Database transaction aborted automatically in ' . get_class($task));
261 $DB->force_transaction_rollback();
263 if (isset($predbqueries)) {
264 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
265 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
267 mtrace('Scheduled task failed: ' . $fullname . ',' . $e->getMessage());
268 if ($CFG->debugdeveloper) {
269 if (!empty($e->debuginfo)) {
270 mtrace("Debug info:");
271 mtrace($e->debuginfo);
273 mtrace("Backtrace:");
274 mtrace(format_backtrace($e->getTrace(), true));
276 \core\task\manager::scheduled_task_failed($task);
277 } finally {
278 cron_prepare_core_renderer(true);
280 get_mailer('close');
284 * Shared code that handles running of a single adhoc task within the cron.
286 * @param \core\task\adhoc_task $task
288 function cron_run_inner_adhoc_task(\core\task\adhoc_task $task) {
289 global $DB, $CFG;
291 \core\task\logmanager::start_logging($task);
293 mtrace("Execute adhoc task: " . get_class($task));
294 cron_trace_time_and_memory();
295 $predbqueries = null;
296 $predbqueries = $DB->perf_get_queries();
297 $pretime = microtime(1);
299 if ($userid = $task->get_userid()) {
300 // This task has a userid specified.
301 if ($user = \core_user::get_user($userid)) {
302 // User found. Check that they are suitable.
303 try {
304 \core_user::require_active_user($user, true, true);
305 } catch (moodle_exception $e) {
306 mtrace("User {$userid} cannot be used to run an adhoc task: " . get_class($task) . ". Cancelling task.");
307 $user = null;
309 } else {
310 // Unable to find the user for this task.
311 // A user missing in the database will never reappear.
312 mtrace("User {$userid} could not be found for adhoc task: " . get_class($task) . ". Cancelling task.");
315 if (empty($user)) {
316 // A user missing in the database will never reappear so the task needs to be failed to ensure that locks are removed,
317 // and then removed to prevent future runs.
318 // A task running as a user should only be run as that user.
319 \core\task\manager::adhoc_task_failed($task);
320 $DB->delete_records('task_adhoc', ['id' => $task->get_id()]);
322 return;
325 cron_setup_user($user);
328 try {
329 get_mailer('buffer');
330 cron_prepare_core_renderer();
331 $task->execute();
332 if ($DB->is_transaction_started()) {
333 throw new coding_exception("Task left transaction open");
335 if (isset($predbqueries)) {
336 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
337 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
339 mtrace("Adhoc task complete: " . get_class($task));
340 \core\task\manager::adhoc_task_complete($task);
341 } catch (Exception $e) {
342 if ($DB && $DB->is_transaction_started()) {
343 error_log('Database transaction aborted automatically in ' . get_class($task));
344 $DB->force_transaction_rollback();
346 if (isset($predbqueries)) {
347 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
348 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
350 mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
351 if ($CFG->debugdeveloper) {
352 if (!empty($e->debuginfo)) {
353 mtrace("Debug info:");
354 mtrace($e->debuginfo);
356 mtrace("Backtrace:");
357 mtrace(format_backtrace($e->getTrace(), true));
359 \core\task\manager::adhoc_task_failed($task);
360 } finally {
361 // Reset back to the standard admin user.
362 cron_setup_user();
363 cron_prepare_core_renderer(true);
365 get_mailer('close');
369 * Runs a single cron task. This function assumes it is displaying output in pseudo-CLI mode.
371 * The function will fail if the task is disabled.
373 * Warning: Because this function closes the browser session, it may not be safe to continue
374 * with other processing (other than displaying the rest of the page) after using this function!
376 * @param \core\task\scheduled_task $task Task to run
377 * @return bool True if cron run successful
379 function cron_run_single_task(\core\task\scheduled_task $task) {
380 global $CFG, $DB, $USER;
382 if (CLI_MAINTENANCE) {
383 echo "CLI maintenance mode active, cron execution suspended.\n";
384 return false;
387 if (moodle_needs_upgrading()) {
388 echo "Moodle upgrade pending, cron execution suspended.\n";
389 return false;
392 // Check task and component is not disabled.
393 $taskname = get_class($task);
394 if ($task->get_disabled()) {
395 echo "Task is disabled ($taskname).\n";
396 return false;
398 $component = $task->get_component();
399 if ($plugininfo = core_plugin_manager::instance()->get_plugin_info($component)) {
400 if ($plugininfo->is_enabled() === false && !$task->get_run_if_component_disabled()) {
401 echo "Component is not enabled ($component).\n";
402 return false;
406 // Enable debugging features as per config settings.
407 if (!empty($CFG->showcronsql)) {
408 $DB->set_debug(true);
410 if (!empty($CFG->showcrondebugging)) {
411 set_debugging(DEBUG_DEVELOPER, true);
414 // Increase time and memory limits.
415 core_php_time_limit::raise();
416 raise_memory_limit(MEMORY_EXTRA);
418 // Switch to admin account for cron tasks, but close the session so we don't send this stuff
419 // to the browser.
420 session_write_close();
421 $realuser = clone($USER);
422 cron_setup_user(null, null, true);
424 // Get lock for cron task.
425 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
426 if (!$cronlock = $cronlockfactory->get_lock('core_cron', 1)) {
427 echo "Unable to get cron lock.\n";
428 return false;
430 if (!$lock = $cronlockfactory->get_lock($taskname, 1)) {
431 $cronlock->release();
432 echo "Unable to get task lock for $taskname.\n";
433 return false;
435 $task->set_lock($lock);
436 if (!$task->is_blocking()) {
437 $cronlock->release();
438 } else {
439 $task->set_cron_lock($cronlock);
442 // Run actual tasks.
443 cron_run_inner_scheduled_task($task);
445 // Go back to real user account.
446 cron_setup_user($realuser, null, true);
448 return true;
452 * Output some standard information during cron runs. Specifically current time
453 * and memory usage. This method also does gc_collect_cycles() (before displaying
454 * memory usage) to try to help PHP manage memory better.
456 function cron_trace_time_and_memory() {
457 gc_collect_cycles();
458 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
462 * Executes cron functions for a specific type of plugin.
464 * @param string $plugintype Plugin type (e.g. 'report')
465 * @param string $description If specified, will display 'Starting (whatever)'
466 * and 'Finished (whatever)' lines, otherwise does not display
468 function cron_execute_plugin_type($plugintype, $description = null) {
469 global $DB;
471 // Get list from plugin => function for all plugins
472 $plugins = get_plugin_list_with_function($plugintype, 'cron');
474 // Modify list for backward compatibility (different files/names)
475 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
477 // Return if no plugins with cron function to process
478 if (!$plugins) {
479 return;
482 if ($description) {
483 mtrace('Starting '.$description);
486 foreach ($plugins as $component=>$cronfunction) {
487 $dir = core_component::get_component_directory($component);
489 // Get cron period if specified in version.php, otherwise assume every cron
490 $cronperiod = 0;
491 if (file_exists("$dir/version.php")) {
492 $plugin = new stdClass();
493 include("$dir/version.php");
494 if (isset($plugin->cron)) {
495 $cronperiod = $plugin->cron;
499 // Using last cron and cron period, don't run if it already ran recently
500 $lastcron = get_config($component, 'lastcron');
501 if ($cronperiod && $lastcron) {
502 if ($lastcron + $cronperiod > time()) {
503 // do not execute cron yet
504 continue;
508 mtrace('Processing cron function for ' . $component . '...');
509 cron_trace_time_and_memory();
510 $pre_dbqueries = $DB->perf_get_queries();
511 $pre_time = microtime(true);
513 $cronfunction();
515 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
516 round(microtime(true) - $pre_time, 2) . " seconds)");
518 set_config('lastcron', time(), $component);
519 core_php_time_limit::raise();
522 if ($description) {
523 mtrace('Finished ' . $description);
528 * Used to add in old-style cron functions within plugins that have not been converted to the
529 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
530 * cron.php and some used a different name.)
532 * @param string $plugintype Plugin type e.g. 'report'
533 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
534 * 'report_frog_cron') for plugin cron functions that were already found using the new API
535 * @return array Revised version of $plugins that adds in any extra plugin functions found by
536 * looking in the older location
538 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
539 global $CFG; // mandatory in case it is referenced by include()d PHP script
541 if ($plugintype === 'report') {
542 // Admin reports only - not course report because course report was
543 // never implemented before, so doesn't need BC
544 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
545 $component = $plugintype . '_' . $pluginname;
546 if (isset($plugins[$component])) {
547 // We already have detected the function using the new API
548 continue;
550 if (!file_exists("$dir/cron.php")) {
551 // No old style cron file present
552 continue;
554 include_once("$dir/cron.php");
555 $cronfunction = $component . '_cron';
556 if (function_exists($cronfunction)) {
557 $plugins[$component] = $cronfunction;
558 } else {
559 debugging("Invalid legacy cron.php detected in $component, " .
560 "please use lib.php instead");
563 } else if (strpos($plugintype, 'grade') === 0) {
564 // Detect old style cron function names
565 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
566 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
567 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
568 $component = $plugintype.'_'.$pluginname;
569 if (isset($plugins[$component])) {
570 // We already have detected the function using the new API
571 continue;
573 if (!file_exists("$dir/lib.php")) {
574 continue;
576 include_once("$dir/lib.php");
577 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
578 $pluginname . '_cron';
579 if (function_exists($cronfunction)) {
580 $plugins[$component] = $cronfunction;
585 return $plugins;
589 * Prepare the output renderer for the cron run.
591 * This involves creating a new $PAGE, and $OUTPUT fresh for each task and prevents any one task from influencing
592 * any other.
594 * @param bool $restore Whether to restore the original PAGE and OUTPUT
596 function cron_prepare_core_renderer($restore = false) {
597 global $OUTPUT, $PAGE;
599 // Store the original PAGE and OUTPUT values so that they can be reset at a later point to the original.
600 // This should not normally be required, but may be used in places such as the scheduled task tool's "Run now"
601 // functionality.
602 static $page = null;
603 static $output = null;
605 if (null === $page) {
606 $page = $PAGE;
609 if (null === $output) {
610 $output = $OUTPUT;
613 if (!empty($restore)) {
614 $PAGE = $page;
615 $page = null;
617 $OUTPUT = $output;
618 $output = null;
619 } else {
620 // Setup a new General renderer.
621 // Cron tasks may produce output to be used in web, so we must use the appropriate renderer target.
622 // This allows correct use of templates, etc.
623 $PAGE = new \moodle_page();
624 $OUTPUT = new \core_renderer($PAGE, RENDERER_TARGET_GENERAL);