on-demand release 3.5beta+
[moodle.git] / lib / cronlib.php
CommitLineData
28bd3d9a 1<?php
28bd3d9a
PS
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.
13//
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/>.
16
17/**
18 * Cron functions.
19 *
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
24 */
25
50ed196e
PS
26/**
27 * Execute cron tasks
28 */
28bd3d9a
PS
29function cron_run() {
30 global $DB, $CFG, $OUTPUT;
31
9957af68
PS
32 if (CLI_MAINTENANCE) {
33 echo "CLI maintenance mode active, cron execution suspended.\n";
34 exit(1);
35 }
36
4c56c7bf
PS
37 if (moodle_needs_upgrading()) {
38 echo "Moodle upgrade pending, cron execution suspended.\n";
39 exit(1);
40 }
41
28bd3d9a 42 require_once($CFG->libdir.'/adminlib.php');
28bd3d9a
PS
43
44 if (!empty($CFG->showcronsql)) {
45 $DB->set_debug(true);
46 }
47 if (!empty($CFG->showcrondebugging)) {
96f81ea3 48 set_debugging(DEBUG_DEVELOPER, true);
28bd3d9a
PS
49 }
50
3ef7279f 51 core_php_time_limit::raise();
28bd3d9a
PS
52 $starttime = microtime();
53
50ed196e 54 // Increase memory limit
346c5887 55 raise_memory_limit(MEMORY_EXTRA);
28bd3d9a 56
50ed196e 57 // Emulate normal session - we use admin accoutn by default
28bd3d9a
PS
58 cron_setup_user();
59
50ed196e 60 // Start output log
28bd3d9a 61 $timenow = time();
658b9372 62 mtrace("Server Time: ".date('r', $timenow)."\n\n");
28bd3d9a 63
309ae892
DW
64 // Run all scheduled tasks.
65 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
66 $task = \core\task\manager::get_next_scheduled_task($timenow)) {
38fa1ca5 67 cron_run_inner_scheduled_task($task);
309ae892 68 unset($task);
50ed196e
PS
69 }
70
309ae892
DW
71 // Run all adhoc tasks.
72 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
73 $task = \core\task\manager::get_next_adhoc_task($timenow)) {
7e4c4b6f 74 cron_run_inner_adhoc_task($task);
309ae892 75 unset($task);
50ed196e
PS
76 }
77
28bd3d9a
PS
78 mtrace("Cron script completed correctly");
79
658b9372
TH
80 gc_collect_cycles();
81 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
28bd3d9a
PS
82 $difftime = microtime_diff($starttime, microtime());
83 mtrace("Execution took ".$difftime." seconds");
cbb9e9b8 84}
b5541735 85
38fa1ca5 86/**
87 * Shared code that handles running of a single scheduled task within the cron.
88 *
89 * Not intended for calling directly outside of this library!
90 *
91 * @param \core\task\task_base $task
92 */
93function cron_run_inner_scheduled_task(\core\task\task_base $task) {
94 global $CFG, $DB;
95
96 $fullname = $task->get_name() . ' (' . get_class($task) . ')';
97 mtrace('Execute scheduled task: ' . $fullname);
98 cron_trace_time_and_memory();
99 $predbqueries = null;
100 $predbqueries = $DB->perf_get_queries();
101 $pretime = microtime(1);
102 try {
103 get_mailer('buffer');
104 $task->execute();
105 if ($DB->is_transaction_started()) {
106 throw new coding_exception("Task left transaction open");
107 }
108 if (isset($predbqueries)) {
109 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
110 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
111 }
112 mtrace('Scheduled task complete: ' . $fullname);
113 \core\task\manager::scheduled_task_complete($task);
114 } catch (Exception $e) {
115 if ($DB && $DB->is_transaction_started()) {
116 error_log('Database transaction aborted automatically in ' . get_class($task));
117 $DB->force_transaction_rollback();
118 }
119 if (isset($predbqueries)) {
120 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
121 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
122 }
123 mtrace('Scheduled task failed: ' . $fullname . ',' . $e->getMessage());
124 if ($CFG->debugdeveloper) {
125 if (!empty($e->debuginfo)) {
126 mtrace("Debug info:");
127 mtrace($e->debuginfo);
128 }
129 mtrace("Backtrace:");
130 mtrace(format_backtrace($e->getTrace(), true));
131 }
132 \core\task\manager::scheduled_task_failed($task);
133 }
134 get_mailer('close');
135}
136
7e4c4b6f
AN
137/**
138 * Shared code that handles running of a single adhoc task within the cron.
139 *
140 * @param \core\task\adhoc_task $task
141 */
142function cron_run_inner_adhoc_task(\core\task\adhoc_task $task) {
143 global $DB, $CFG;
144 mtrace("Execute adhoc task: " . get_class($task));
145 cron_trace_time_and_memory();
146 $predbqueries = null;
147 $predbqueries = $DB->perf_get_queries();
148 $pretime = microtime(1);
149
150 if ($userid = $task->get_userid()) {
151 // This task has a userid specified.
152 if ($user = \core_user::get_user($userid)) {
153 // User found. Check that they are suitable.
154 try {
155 \core_user::require_active_user($user, true, true);
156 } catch (moodle_exception $e) {
157 mtrace("User {$userid} cannot be used to run an adhoc task: " . get_class($task) . ". Cancelling task.");
158 $user = null;
159 }
160 } else {
161 // Unable to find the user for this task.
162 // A user missing in the database will never reappear.
163 mtrace("User {$userid} could not be found for adhoc task: " . get_class($task) . ". Cancelling task.");
164 }
165
166 if (empty($user)) {
167 // A user missing in the database will never reappear so the task needs to be failed to ensure that locks are removed,
168 // and then removed to prevent future runs.
169 // A task running as a user should only be run as that user.
170 \core\task\manager::adhoc_task_failed($task);
171 $DB->delete_records('task_adhoc', ['id' => $task->get_id()]);
172
173 return;
174 }
175
176 cron_setup_user($user);
177 }
178
179 try {
180 get_mailer('buffer');
181 $task->execute();
182 if ($DB->is_transaction_started()) {
183 throw new coding_exception("Task left transaction open");
184 }
185 if (isset($predbqueries)) {
186 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
187 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
188 }
189 mtrace("Adhoc task complete: " . get_class($task));
190 \core\task\manager::adhoc_task_complete($task);
191 } catch (Exception $e) {
192 if ($DB && $DB->is_transaction_started()) {
193 error_log('Database transaction aborted automatically in ' . get_class($task));
194 $DB->force_transaction_rollback();
195 }
196 if (isset($predbqueries)) {
197 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
198 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
199 }
200 mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
201 if ($CFG->debugdeveloper) {
202 if (!empty($e->debuginfo)) {
203 mtrace("Debug info:");
204 mtrace($e->debuginfo);
205 }
206 mtrace("Backtrace:");
207 mtrace(format_backtrace($e->getTrace(), true));
208 }
209 \core\task\manager::adhoc_task_failed($task);
210 } finally {
211 // Reset back to the standard admin user.
212 cron_setup_user();
213 }
214 get_mailer('close');
215}
216
38fa1ca5 217/**
218 * Runs a single cron task. This function assumes it is displaying output in pseudo-CLI mode.
219 *
220 * The function will fail if the task is disabled.
221 *
222 * Warning: Because this function closes the browser session, it may not be safe to continue
223 * with other processing (other than displaying the rest of the page) after using this function!
224 *
225 * @param \core\task\scheduled_task $task Task to run
226 * @return bool True if cron run successful
227 */
228function cron_run_single_task(\core\task\scheduled_task $task) {
229 global $CFG, $DB, $USER;
230
231 if (CLI_MAINTENANCE) {
232 echo "CLI maintenance mode active, cron execution suspended.\n";
233 return false;
234 }
235
236 if (moodle_needs_upgrading()) {
237 echo "Moodle upgrade pending, cron execution suspended.\n";
238 return false;
239 }
240
241 // Check task and component is not disabled.
242 $taskname = get_class($task);
243 if ($task->get_disabled()) {
244 echo "Task is disabled ($taskname).\n";
245 return false;
246 }
247 $component = $task->get_component();
248 if ($plugininfo = core_plugin_manager::instance()->get_plugin_info($component)) {
6d7c06a9 249 if ($plugininfo->is_enabled() === false && !$task->get_run_if_component_disabled()) {
38fa1ca5 250 echo "Component is not enabled ($component).\n";
251 return false;
252 }
253 }
254
255 // Enable debugging features as per config settings.
256 if (!empty($CFG->showcronsql)) {
257 $DB->set_debug(true);
258 }
259 if (!empty($CFG->showcrondebugging)) {
260 set_debugging(DEBUG_DEVELOPER, true);
261 }
262
263 // Increase time and memory limits.
264 core_php_time_limit::raise();
265 raise_memory_limit(MEMORY_EXTRA);
266
267 // Switch to admin account for cron tasks, but close the session so we don't send this stuff
268 // to the browser.
269 session_write_close();
270 $realuser = clone($USER);
271 cron_setup_user(null, null, true);
272
273 // Get lock for cron task.
274 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
275 if (!$cronlock = $cronlockfactory->get_lock('core_cron', 1)) {
276 echo "Unable to get cron lock.\n";
277 return false;
278 }
279 if (!$lock = $cronlockfactory->get_lock($taskname, 1)) {
280 $cronlock->release();
281 echo "Unable to get task lock for $taskname.\n";
282 return false;
283 }
284 $task->set_lock($lock);
285 if (!$task->is_blocking()) {
286 $cronlock->release();
287 } else {
288 $task->set_cron_lock($cronlock);
289 }
290
291 // Run actual tasks.
292 cron_run_inner_scheduled_task($task);
293
294 // Go back to real user account.
295 cron_setup_user($realuser, null, true);
296
297 return true;
298}
299
309ae892
DW
300/**
301 * Output some standard information during cron runs. Specifically current time
302 * and memory usage. This method also does gc_collect_cycles() (before displaying
303 * memory usage) to try to help PHP manage memory better.
304 */
305function cron_trace_time_and_memory() {
306 gc_collect_cycles();
307 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
308}
309
e4a626b9 310/**
311 * Executes cron functions for a specific type of plugin.
50ed196e 312 *
e4a626b9 313 * @param string $plugintype Plugin type (e.g. 'report')
314 * @param string $description If specified, will display 'Starting (whatever)'
315 * and 'Finished (whatever)' lines, otherwise does not display
316 */
b5541735
PS
317function cron_execute_plugin_type($plugintype, $description = null) {
318 global $DB;
319
e4a626b9 320 // Get list from plugin => function for all plugins
321 $plugins = get_plugin_list_with_function($plugintype, 'cron');
322
323 // Modify list for backward compatibility (different files/names)
324 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
b5541735 325
e4a626b9 326 // Return if no plugins with cron function to process
b5541735
PS
327 if (!$plugins) {
328 return;
329 }
330
331 if ($description) {
332 mtrace('Starting '.$description);
333 }
334
335 foreach ($plugins as $component=>$cronfunction) {
b0d1d941 336 $dir = core_component::get_component_directory($component);
e4a626b9 337
338 // Get cron period if specified in version.php, otherwise assume every cron
b5541735
PS
339 $cronperiod = 0;
340 if (file_exists("$dir/version.php")) {
341 $plugin = new stdClass();
342 include("$dir/version.php");
343 if (isset($plugin->cron)) {
344 $cronperiod = $plugin->cron;
345 }
346 }
347
e4a626b9 348 // Using last cron and cron period, don't run if it already ran recently
b5541735 349 $lastcron = get_config($component, 'lastcron');
e4a626b9 350 if ($cronperiod && $lastcron) {
b5541735
PS
351 if ($lastcron + $cronperiod > time()) {
352 // do not execute cron yet
353 continue;
354 }
355 }
356
e4a626b9 357 mtrace('Processing cron function for ' . $component . '...');
658b9372 358 cron_trace_time_and_memory();
b5541735 359 $pre_dbqueries = $DB->perf_get_queries();
e4a626b9 360 $pre_time = microtime(true);
b5541735
PS
361
362 $cronfunction();
363
e4a626b9 364 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
365 round(microtime(true) - $pre_time, 2) . " seconds)");
b5541735
PS
366
367 set_config('lastcron', time(), $component);
3ef7279f 368 core_php_time_limit::raise();
b5541735
PS
369 }
370
371 if ($description) {
e4a626b9 372 mtrace('Finished ' . $description);
b5541735
PS
373 }
374}
375
e4a626b9 376/**
377 * Used to add in old-style cron functions within plugins that have not been converted to the
378 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
379 * cron.php and some used a different name.)
50ed196e 380 *
e4a626b9 381 * @param string $plugintype Plugin type e.g. 'report'
382 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
383 * 'report_frog_cron') for plugin cron functions that were already found using the new API
384 * @return array Revised version of $plugins that adds in any extra plugin functions found by
385 * looking in the older location
386 */
387function cron_bc_hack_plugin_functions($plugintype, $plugins) {
388 global $CFG; // mandatory in case it is referenced by include()d PHP script
389
390 if ($plugintype === 'report') {
391 // Admin reports only - not course report because course report was
392 // never implemented before, so doesn't need BC
bd3b3bba 393 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
e4a626b9 394 $component = $plugintype . '_' . $pluginname;
b5541735 395 if (isset($plugins[$component])) {
e4a626b9 396 // We already have detected the function using the new API
b5541735
PS
397 continue;
398 }
399 if (!file_exists("$dir/cron.php")) {
e4a626b9 400 // No old style cron file present
b5541735
PS
401 continue;
402 }
403 include_once("$dir/cron.php");
e4a626b9 404 $cronfunction = $component . '_cron';
b5541735
PS
405 if (function_exists($cronfunction)) {
406 $plugins[$component] = $cronfunction;
407 } else {
e4a626b9 408 debugging("Invalid legacy cron.php detected in $component, " .
409 "please use lib.php instead");
b5541735
PS
410 }
411 }
b5541735 412 } else if (strpos($plugintype, 'grade') === 0) {
e4a626b9 413 // Detect old style cron function names
414 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
415 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
bd3b3bba 416 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
b5541735
PS
417 $component = $plugintype.'_'.$pluginname;
418 if (isset($plugins[$component])) {
e4a626b9 419 // We already have detected the function using the new API
b5541735
PS
420 continue;
421 }
422 if (!file_exists("$dir/lib.php")) {
423 continue;
424 }
425 include_once("$dir/lib.php");
e4a626b9 426 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
427 $pluginname . '_cron';
b5541735
PS
428 if (function_exists($cronfunction)) {
429 $plugins[$component] = $cronfunction;
430 }
431 }
432 }
433
434 return $plugins;
50ed196e 435}