Merge branch 'MDL-74756-MOODLE_401_STABLE' of https://github.com/sh-csg/moodle into...
[moodle.git] / lib / cronlib.php
blob2e98a6540509200790cd188bd2d351bd0a743e62
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 (\Throwable $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 cron_set_process_title("Waiting for next adhoc task");
200 $taskcount++;
201 unset($task);
202 } else {
203 $timeleft = $finishtime - time();
204 if ($timeleft <= 0) {
205 break;
207 if (!$waiting) {
208 mtrace('Waiting for more adhoc tasks to be queued ', '');
209 } else {
210 mtrace('.', '');
212 $waiting = true;
213 cron_set_process_title("Waiting {$timeleft}s for next adhoc task");
214 sleep(1);
218 if ($waiting) {
219 mtrace('');
222 mtrace("Ran {$taskcount} adhoc tasks found at {$humantimenow}");
224 if ($adhoclock) {
225 // Release the adhoc task runner lock.
226 $adhoclock->release();
231 * Shared code that handles running of a single scheduled task within the cron.
233 * Not intended for calling directly outside of this library!
235 * @param \core\task\task_base $task
237 function cron_run_inner_scheduled_task(\core\task\task_base $task) {
238 global $CFG, $DB;
239 $debuglevel = $CFG->debug;
241 \core\task\manager::scheduled_task_starting($task);
242 \core\task\logmanager::start_logging($task);
244 $fullname = $task->get_name() . ' (' . get_class($task) . ')';
245 mtrace('Execute scheduled task: ' . $fullname);
246 cron_set_process_title('Scheduled task: ' . get_class($task));
247 cron_trace_time_and_memory();
248 $predbqueries = null;
249 $predbqueries = $DB->perf_get_queries();
250 $pretime = microtime(1);
251 try {
252 get_mailer('buffer');
253 cron_prepare_core_renderer();
254 // Temporarily increase debug level if task has failed and debugging isn't already at maximum.
255 if ($debuglevel !== DEBUG_DEVELOPER && $faildelay = $task->get_fail_delay()) {
256 mtrace('Debugging increased temporarily due to faildelay of ' . $faildelay);
257 set_debugging(DEBUG_DEVELOPER);
259 $task->execute();
260 if ($DB->is_transaction_started()) {
261 throw new coding_exception("Task left transaction open");
263 if (isset($predbqueries)) {
264 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
265 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
267 mtrace('Scheduled task complete: ' . $fullname);
268 \core\task\manager::scheduled_task_complete($task);
269 } catch (\Throwable $e) {
270 if ($DB && $DB->is_transaction_started()) {
271 error_log('Database transaction aborted automatically in ' . get_class($task));
272 $DB->force_transaction_rollback();
274 if (isset($predbqueries)) {
275 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
276 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
278 mtrace('Scheduled task failed: ' . $fullname . ',' . $e->getMessage());
279 if ($CFG->debugdeveloper) {
280 if (!empty($e->debuginfo)) {
281 mtrace("Debug info:");
282 mtrace($e->debuginfo);
284 mtrace("Backtrace:");
285 mtrace(format_backtrace($e->getTrace(), true));
287 \core\task\manager::scheduled_task_failed($task);
288 } finally {
289 // Reset debugging if it changed.
290 if ($CFG->debug !== $debuglevel) {
291 set_debugging($debuglevel);
293 // Reset back to the standard admin user.
294 cron_setup_user();
295 cron_set_process_title('Waiting for next scheduled task');
296 cron_prepare_core_renderer(true);
298 get_mailer('close');
302 * Shared code that handles running of a single adhoc task within the cron.
304 * @param \core\task\adhoc_task $task
306 function cron_run_inner_adhoc_task(\core\task\adhoc_task $task) {
307 global $CFG, $DB;
308 $debuglevel = $CFG->debug;
310 \core\task\manager::adhoc_task_starting($task);
311 \core\task\logmanager::start_logging($task);
313 mtrace("Execute adhoc task: " . get_class($task));
314 mtrace("Adhoc task id: " . $task->get_id());
315 mtrace("Adhoc task custom data: " . $task->get_custom_data_as_string());
316 cron_set_process_title('Adhoc task: ' . $task->get_id() . ' ' . get_class($task));
317 cron_trace_time_and_memory();
318 $predbqueries = null;
319 $predbqueries = $DB->perf_get_queries();
320 $pretime = microtime(1);
322 if ($userid = $task->get_userid()) {
323 // This task has a userid specified.
324 if ($user = \core_user::get_user($userid)) {
325 // User found. Check that they are suitable.
326 try {
327 \core_user::require_active_user($user, true, true);
328 } catch (moodle_exception $e) {
329 mtrace("User {$userid} cannot be used to run an adhoc task: " . get_class($task) . ". Cancelling task.");
330 $user = null;
332 } else {
333 // Unable to find the user for this task.
334 // A user missing in the database will never reappear.
335 mtrace("User {$userid} could not be found for adhoc task: " . get_class($task) . ". Cancelling task.");
338 if (empty($user)) {
339 // A user missing in the database will never reappear so the task needs to be failed to ensure that locks are removed,
340 // and then removed to prevent future runs.
341 // A task running as a user should only be run as that user.
342 \core\task\manager::adhoc_task_failed($task);
343 $DB->delete_records('task_adhoc', ['id' => $task->get_id()]);
345 return;
348 cron_setup_user($user);
351 try {
352 get_mailer('buffer');
353 cron_prepare_core_renderer();
354 // Temporarily increase debug level if task has failed and debugging isn't already at maximum.
355 if ($debuglevel !== DEBUG_DEVELOPER && $faildelay = $task->get_fail_delay()) {
356 mtrace('Debugging increased temporarily due to faildelay of ' . $faildelay);
357 set_debugging(DEBUG_DEVELOPER);
359 $task->execute();
360 if ($DB->is_transaction_started()) {
361 throw new coding_exception("Task left transaction open");
363 if (isset($predbqueries)) {
364 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
365 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
367 mtrace("Adhoc task complete: " . get_class($task));
368 \core\task\manager::adhoc_task_complete($task);
369 } catch (\Throwable $e) {
370 if ($DB && $DB->is_transaction_started()) {
371 error_log('Database transaction aborted automatically in ' . get_class($task));
372 $DB->force_transaction_rollback();
374 if (isset($predbqueries)) {
375 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
376 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
378 mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
379 if ($CFG->debugdeveloper) {
380 if (!empty($e->debuginfo)) {
381 mtrace("Debug info:");
382 mtrace($e->debuginfo);
384 mtrace("Backtrace:");
385 mtrace(format_backtrace($e->getTrace(), true));
387 \core\task\manager::adhoc_task_failed($task);
388 } finally {
389 // Reset debug level if it changed.
390 if ($CFG->debug !== $debuglevel) {
391 set_debugging($debuglevel);
393 // Reset back to the standard admin user.
394 cron_setup_user();
395 cron_prepare_core_renderer(true);
397 get_mailer('close');
401 * Sets the process title
403 * This makes it very easy for a sysadmin to immediately see what task
404 * a cron process is running at any given moment.
406 * @param string $title process status title
408 function cron_set_process_title(string $title) {
409 global $CFG;
410 if (CLI_SCRIPT) {
411 require_once($CFG->libdir . '/clilib.php');
412 $datetime = userdate(time(), '%b %d, %H:%M:%S');
413 cli_set_process_title_suffix("$datetime $title");
418 * Output some standard information during cron runs. Specifically current time
419 * and memory usage. This method also does gc_collect_cycles() (before displaying
420 * memory usage) to try to help PHP manage memory better.
422 function cron_trace_time_and_memory() {
423 gc_collect_cycles();
424 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
428 * Prepare the output renderer for the cron run.
430 * This involves creating a new $PAGE, and $OUTPUT fresh for each task and prevents any one task from influencing
431 * any other.
433 * @param bool $restore Whether to restore the original PAGE and OUTPUT
435 function cron_prepare_core_renderer($restore = false) {
436 global $OUTPUT, $PAGE;
438 // Store the original PAGE and OUTPUT values so that they can be reset at a later point to the original.
439 // This should not normally be required, but may be used in places such as the scheduled task tool's "Run now"
440 // functionality.
441 static $page = null;
442 static $output = null;
444 if (null === $page) {
445 $page = $PAGE;
448 if (null === $output) {
449 $output = $OUTPUT;
452 if (!empty($restore)) {
453 $PAGE = $page;
454 $page = null;
456 $OUTPUT = $output;
457 $output = null;
458 } else {
459 // Setup a new General renderer.
460 // Cron tasks may produce output to be used in web, so we must use the appropriate renderer target.
461 // This allows correct use of templates, etc.
462 $PAGE = new \moodle_page();
463 $OUTPUT = new \core_renderer($PAGE, RENDERER_TARGET_GENERAL);