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