MDL-51330 Cron: In log, scheduled tasks don't show component
[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)) {
b9dba4e3 67 $fullname = $task->get_name() . ' (' . get_class($task) . ')';
68 mtrace('Execute scheduled task: ' . $fullname);
658b9372 69 cron_trace_time_and_memory();
309ae892
DW
70 $predbqueries = null;
71 $predbqueries = $DB->perf_get_queries();
72 $pretime = microtime(1);
73 try {
371bfca1 74 get_mailer('buffer');
309ae892 75 $task->execute();
5ea1e111
MA
76 if ($DB->is_transaction_started()) {
77 throw new coding_exception("Task left transaction open");
78 }
309ae892
DW
79 if (isset($predbqueries)) {
80 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
81 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
50ed196e 82 }
b9dba4e3 83 mtrace('Scheduled task complete: ' . $fullname);
309ae892
DW
84 \core\task\manager::scheduled_task_complete($task);
85 } catch (Exception $e) {
86 if ($DB && $DB->is_transaction_started()) {
87 error_log('Database transaction aborted automatically in ' . get_class($task));
88 $DB->force_transaction_rollback();
50ed196e 89 }
309ae892
DW
90 if (isset($predbqueries)) {
91 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
92 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
50ed196e 93 }
b9dba4e3 94 mtrace('Scheduled task failed: ' . $fullname . ',' . $e->getMessage());
a6e9c230
DP
95 if ($CFG->debugdeveloper) {
96 if (!empty($e->debuginfo)) {
97 mtrace("Debug info:");
98 mtrace($e->debuginfo);
99 }
100 mtrace("Backtrace:");
101 mtrace(format_backtrace($e->getTrace(), true));
102 }
309ae892 103 \core\task\manager::scheduled_task_failed($task);
50ed196e 104 }
371bfca1 105 get_mailer('close');
309ae892 106 unset($task);
50ed196e
PS
107 }
108
309ae892
DW
109 // Run all adhoc tasks.
110 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
111 $task = \core\task\manager::get_next_adhoc_task($timenow)) {
112 mtrace("Execute adhoc task: " . get_class($task));
658b9372 113 cron_trace_time_and_memory();
309ae892
DW
114 $predbqueries = null;
115 $predbqueries = $DB->perf_get_queries();
116 $pretime = microtime(1);
117 try {
371bfca1 118 get_mailer('buffer');
309ae892 119 $task->execute();
5ea1e111
MA
120 if ($DB->is_transaction_started()) {
121 throw new coding_exception("Task left transaction open");
122 }
309ae892
DW
123 if (isset($predbqueries)) {
124 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
125 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
28bd3d9a 126 }
309ae892
DW
127 mtrace("Adhoc task complete: " . get_class($task));
128 \core\task\manager::adhoc_task_complete($task);
129 } catch (Exception $e) {
130 if ($DB && $DB->is_transaction_started()) {
131 error_log('Database transaction aborted automatically in ' . get_class($task));
132 $DB->force_transaction_rollback();
28bd3d9a 133 }
309ae892
DW
134 if (isset($predbqueries)) {
135 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
136 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
50ed196e 137 }
309ae892 138 mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
a6e9c230
DP
139 if ($CFG->debugdeveloper) {
140 if (!empty($e->debuginfo)) {
141 mtrace("Debug info:");
142 mtrace($e->debuginfo);
143 }
144 mtrace("Backtrace:");
145 mtrace(format_backtrace($e->getTrace(), true));
146 }
309ae892 147 \core\task\manager::adhoc_task_failed($task);
50ed196e 148 }
371bfca1 149 get_mailer('close');
309ae892 150 unset($task);
50ed196e
PS
151 }
152
28bd3d9a
PS
153 mtrace("Cron script completed correctly");
154
658b9372
TH
155 gc_collect_cycles();
156 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
28bd3d9a
PS
157 $difftime = microtime_diff($starttime, microtime());
158 mtrace("Execution took ".$difftime." seconds");
cbb9e9b8 159}
b5541735 160
309ae892
DW
161/**
162 * Output some standard information during cron runs. Specifically current time
163 * and memory usage. This method also does gc_collect_cycles() (before displaying
164 * memory usage) to try to help PHP manage memory better.
165 */
166function cron_trace_time_and_memory() {
167 gc_collect_cycles();
168 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
169}
170
e4a626b9 171/**
172 * Executes cron functions for a specific type of plugin.
50ed196e 173 *
e4a626b9 174 * @param string $plugintype Plugin type (e.g. 'report')
175 * @param string $description If specified, will display 'Starting (whatever)'
176 * and 'Finished (whatever)' lines, otherwise does not display
177 */
b5541735
PS
178function cron_execute_plugin_type($plugintype, $description = null) {
179 global $DB;
180
e4a626b9 181 // Get list from plugin => function for all plugins
182 $plugins = get_plugin_list_with_function($plugintype, 'cron');
183
184 // Modify list for backward compatibility (different files/names)
185 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
b5541735 186
e4a626b9 187 // Return if no plugins with cron function to process
b5541735
PS
188 if (!$plugins) {
189 return;
190 }
191
192 if ($description) {
193 mtrace('Starting '.$description);
194 }
195
196 foreach ($plugins as $component=>$cronfunction) {
b0d1d941 197 $dir = core_component::get_component_directory($component);
e4a626b9 198
199 // Get cron period if specified in version.php, otherwise assume every cron
b5541735
PS
200 $cronperiod = 0;
201 if (file_exists("$dir/version.php")) {
202 $plugin = new stdClass();
203 include("$dir/version.php");
204 if (isset($plugin->cron)) {
205 $cronperiod = $plugin->cron;
206 }
207 }
208
e4a626b9 209 // Using last cron and cron period, don't run if it already ran recently
b5541735 210 $lastcron = get_config($component, 'lastcron');
e4a626b9 211 if ($cronperiod && $lastcron) {
b5541735
PS
212 if ($lastcron + $cronperiod > time()) {
213 // do not execute cron yet
214 continue;
215 }
216 }
217
e4a626b9 218 mtrace('Processing cron function for ' . $component . '...');
658b9372 219 cron_trace_time_and_memory();
b5541735 220 $pre_dbqueries = $DB->perf_get_queries();
e4a626b9 221 $pre_time = microtime(true);
b5541735
PS
222
223 $cronfunction();
224
e4a626b9 225 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
226 round(microtime(true) - $pre_time, 2) . " seconds)");
b5541735
PS
227
228 set_config('lastcron', time(), $component);
3ef7279f 229 core_php_time_limit::raise();
b5541735
PS
230 }
231
232 if ($description) {
e4a626b9 233 mtrace('Finished ' . $description);
b5541735
PS
234 }
235}
236
e4a626b9 237/**
238 * Used to add in old-style cron functions within plugins that have not been converted to the
239 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
240 * cron.php and some used a different name.)
50ed196e 241 *
e4a626b9 242 * @param string $plugintype Plugin type e.g. 'report'
243 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
244 * 'report_frog_cron') for plugin cron functions that were already found using the new API
245 * @return array Revised version of $plugins that adds in any extra plugin functions found by
246 * looking in the older location
247 */
248function cron_bc_hack_plugin_functions($plugintype, $plugins) {
249 global $CFG; // mandatory in case it is referenced by include()d PHP script
250
251 if ($plugintype === 'report') {
252 // Admin reports only - not course report because course report was
253 // never implemented before, so doesn't need BC
bd3b3bba 254 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
e4a626b9 255 $component = $plugintype . '_' . $pluginname;
b5541735 256 if (isset($plugins[$component])) {
e4a626b9 257 // We already have detected the function using the new API
b5541735
PS
258 continue;
259 }
260 if (!file_exists("$dir/cron.php")) {
e4a626b9 261 // No old style cron file present
b5541735
PS
262 continue;
263 }
264 include_once("$dir/cron.php");
e4a626b9 265 $cronfunction = $component . '_cron';
b5541735
PS
266 if (function_exists($cronfunction)) {
267 $plugins[$component] = $cronfunction;
268 } else {
e4a626b9 269 debugging("Invalid legacy cron.php detected in $component, " .
270 "please use lib.php instead");
b5541735
PS
271 }
272 }
b5541735 273 } else if (strpos($plugintype, 'grade') === 0) {
e4a626b9 274 // Detect old style cron function names
275 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
276 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
bd3b3bba 277 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
b5541735
PS
278 $component = $plugintype.'_'.$pluginname;
279 if (isset($plugins[$component])) {
e4a626b9 280 // We already have detected the function using the new API
b5541735
PS
281 continue;
282 }
283 if (!file_exists("$dir/lib.php")) {
284 continue;
285 }
286 include_once("$dir/lib.php");
e4a626b9 287 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
288 $pluginname . '_cron';
b5541735
PS
289 if (function_exists($cronfunction)) {
290 $plugins[$component] = $cronfunction;
291 }
292 }
293 }
294
295 return $plugins;
50ed196e 296}