cron.php 15.1 KB
Newer Older
Martyn Smith's avatar
Martyn Smith committed
1 2 3 4 5
<?php
/**
 *
 * @package    mahara
 * @subpackage core
6
 * @author     Catalyst IT Ltd
7 8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
Martyn Smith's avatar
Martyn Smith committed
9 10 11
 *
 */

12 13 14
define('INTERNAL', 1);
define('PUBLIC', 1);
define('CRON', 1);
15
define('TITLE', '');
Martyn Smith's avatar
Martyn Smith committed
16 17

require(dirname(dirname(__FILE__)).'/init.php');
18
require_once(get_config('docroot') . 'artefact/lib.php');
19
require_once(get_config('docroot') . 'import/lib.php');
20
require_once(get_config('docroot') . 'export/lib.php');
21
require_once(get_config('docroot') . 'lib/activity.php');
22
require_once(get_config('docroot') . 'lib/file.php');
Martyn Smith's avatar
Martyn Smith committed
23 24 25

// This is here for debugging purposes, it allows us to fake the time to test
// cron behaviour
26 27 28
$realstart = time();
$fake = isset($argv[1]);
$start = $fake ? strtotime($argv[1]) : $realstart;
Martyn Smith's avatar
Martyn Smith committed
29

30
log_info('---------- cron running ' . date('r', $start) . ' ----------');
Martyn Smith's avatar
Martyn Smith committed
31

32
if (!is_writable(get_config('dataroot'))) {
33
    log_warn("Unable to write to dataroot directory.");
34 35
}

Martyn Smith's avatar
Martyn Smith committed
36 37 38
// for each plugin type
foreach (plugin_types() as $plugintype) {

39 40
    $table = $plugintype . '_cron';

Martyn Smith's avatar
Martyn Smith committed
41
    // get list of cron jobs to run for this plugin type
42
    $now = $fake ? (time() - ($realstart - $start)) : time();
43
    $jobs = get_records_select_array(
44
        $table,
45
        'nextrun < ? OR nextrun IS NULL',
46
        array(db_format_timestamp($now)),
Martyn Smith's avatar
Martyn Smith committed
47 48 49 50 51 52 53
        '',
        'plugin,callfunction,minute,hour,day,month,dayofweek,' . db_format_tsfield('nextrun')
    );

    if ($jobs) {
        // for each cron entry
        foreach ($jobs as $job) {
54 55 56 57 58 59 60 61 62 63 64 65 66
            if (!cron_lock($job, $start, $plugintype)) {
                continue;
            }

            // If some other cron instance ran the job while we were messing around,
            // skip it.
            $nextrun = get_field_sql('
                SELECT ' . db_format_tsfield('nextrun') . '
                FROM {' . $table . '}
                WHERE plugin = ? AND callfunction = ?',
                array($job->plugin, $job->callfunction)
            );
            if ($nextrun != $job->nextrun) {
67
                log_info("Too late to run $plugintype $job->plugin $job->callfunction; skipping.");
68 69 70 71
                cron_free($job, $start, $plugintype);
                continue;
            }

72
            $classname = generate_class_name($plugintype, $job->plugin);
Martyn Smith's avatar
Martyn Smith committed
73

74
            log_info("Running $classname::" . $job->callfunction);
Martyn Smith's avatar
Martyn Smith committed
75

76
            safe_require($plugintype, $job->plugin, 'lib.php', 'require_once');
77 78 79 80 81 82 83 84 85 86

            try {
                call_static_method($classname, $job->callfunction);
            }
            catch (Exception $e) {
                log_message($e->getMessage(), LOG_LEVEL_WARN, true, true, $e->getFile(), $e->getLine(), $e->getTrace());
                $output = $e instanceof MaharaException ? $e->render_exception() : $e->getMessage();
                echo "$output\n";
                // Don't call handle_exception; try to update next run time and free the lock
            }
Martyn Smith's avatar
Martyn Smith committed
87

88
            $nextrun = cron_next_run_time($start, (array)$job);
Martyn Smith's avatar
Martyn Smith committed
89 90 91 92 93

            // update next run time
            set_field(
                $plugintype . '_cron',
                'nextrun',
Aaron Wells's avatar
Aaron Wells committed
94
                db_format_timestamp($nextrun),
Martyn Smith's avatar
Martyn Smith committed
95
                'plugin',
Nigel McNie's avatar
Nigel McNie committed
96
                $job->plugin,
Martyn Smith's avatar
Martyn Smith committed
97
                'callfunction',
Nigel McNie's avatar
Nigel McNie committed
98
                $job->callfunction
Martyn Smith's avatar
Martyn Smith committed
99 100
            );

101 102
            cron_free($job, $start, $plugintype);
            $now = $fake ? (time() - ($realstart - $start)) : time();
Martyn Smith's avatar
Martyn Smith committed
103 104 105 106
        }
    }
}

Penny Leach's avatar
Penny Leach committed
107
// and now the core ones (much simpler)
108 109 110
$now = $fake ? (time() - ($realstart - $start)) : time();
$jobs = get_records_select_array(
    'cron',
111
    'nextrun < ? OR nextrun IS NULL',
112 113 114 115 116
    array(db_format_timestamp($now)),
    '',
    'id,callfunction,minute,hour,day,month,dayofweek,' . db_format_tsfield('nextrun')
);
if ($jobs) {
Penny Leach's avatar
Penny Leach committed
117
    foreach ($jobs as $job) {
118 119 120 121 122 123 124 125 126 127 128 129 130
        if (!cron_lock($job, $start)) {
            continue;
        }

        // If some other cron instance ran the job while we were messing around,
        // skip it.
        $nextrun = get_field_sql('
            SELECT ' . db_format_tsfield('nextrun') . '
            FROM {cron}
            WHERE id = ?',
            array($job->id)
        );
        if ($nextrun != $job->nextrun) {
131
            log_info("Too late to run core $job->callfunction; skipping.");
132 133 134 135
            cron_free($job, $start);
            continue;
        }

136
        log_info("Running core cron " . $job->callfunction);
Penny Leach's avatar
Penny Leach committed
137

138
        $function = $job->callfunction;
139 140 141 142 143 144 145 146 147 148

        try {
            $function();
        }
        catch (Exception $e) {
            log_message($e->getMessage(), LOG_LEVEL_WARN, true, true, $e->getFile(), $e->getLine(), $e->getTrace());
            $output = $e instanceof MaharaException ? $e->render_exception() : $e->getMessage();
            echo "$output\n";
            // Don't call handle_exception; try to update next run time and free the lock
        }
Aaron Wells's avatar
Aaron Wells committed
149

150
        $nextrun = cron_next_run_time($start, (array)$job);
Aaron Wells's avatar
Aaron Wells committed
151

Penny Leach's avatar
Penny Leach committed
152
        // update next run time
153
        set_field('cron', 'nextrun', db_format_timestamp($nextrun), 'id', $job->id);
Penny Leach's avatar
Penny Leach committed
154

155 156
        cron_free($job, $start);
        $now = $fake ? (time() - ($realstart - $start)) : time();
Penny Leach's avatar
Penny Leach committed
157 158 159
    }
}

160 161 162 163
$finish = time();

//Time relative to fake cron time
if (isset($argv[1])) {
164
    $diff = $realstart - $start;
165 166
    $finish = $finish - $diff;
}
167
log_info('---------- cron finished ' . date('r', $finish) . ' ----------');
Penny Leach's avatar
Penny Leach committed
168

Martyn Smith's avatar
Martyn Smith committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
function cron_next_run_time($lastrun, $job) {
    $run_date = getdate($lastrun);

    // we don't care about seconds for cron
    $run_date['seconds'] = 0;

    // assert valid month
    if (!cron_valid_month($job, $run_date)) {
        cron_next_month($job, $run_date);

        cron_first_day($job, $run_date);
        cron_first_hour($job, $run_date);
        cron_first_minute($job, $run_date);

        return datearray_to_timestamp($run_date);
    }

    // assert valid day
    if (!cron_valid_day($job, $run_date)) {
        cron_next_day($job, $run_date);

        cron_first_hour($job, $run_date);
        cron_first_minute($job, $run_date);

        return datearray_to_timestamp($run_date);
    }

    // assert valid hour
    if (!cron_valid_hour($job, $run_date)) {
        cron_next_hour($job, $run_date);

        cron_first_minute($job, $run_date);

        return datearray_to_timestamp($run_date);
    }

    cron_next_minute($job, $run_date);

    return datearray_to_timestamp($run_date);

}

function datearray_to_timestamp($date_array) {
    return mktime(
        $date_array['hours'],
        $date_array['minutes'],
        $date_array['seconds'],
        $date_array['mon'],
        $date_array['mday'],
        $date_array['year']
    );
}

/**
  * Determine next value for a single cron field
  *
  * This function is designed to parse a cron field specification and then
  * given a current value of the field, determine the next value of that field.
Aaron Wells's avatar
Aaron Wells committed
227
  *
Martyn Smith's avatar
Martyn Smith committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
  * @param $fieldspec Cron field specification (e.g. "3,7,20-30,40-50/2")
  * @param $currentvalue Current value of this field
  * @param $ceiling Maximum value this field can take (e.g. for minutes this would be set to 60)
  * @param &$propagate Determines (a) if this value can remain at current value
  * or not, (b) returns true if this field wrapped to zero to find the next
  * value.
  * @param &$steps Returns the number of steps that were taken to get from currentvalue to the next value.
  * @param $allowzero Is this field allowed to be 0?
  * @param $ceil_zero_same If the fieldspec has a number equivalent of ceiling in it, is that the same as 0?
  *
  * @return The next value for this field
  */
function cron_next_field_value($fieldspec, $currentvalue, $ceiling, &$propagate, &$steps, $allowzero = true, $ceil_zero_same = false) {
    $timeslices = array_pad(Array(), $ceiling, false);

    foreach ( explode(',',$fieldspec) as $spec ) {
		if (preg_match("~^(\\*|([0-9]{1,2})(-([0-9]{1,2}))?)(/([0-9]{1,2}))?$~",$spec,$matches)) {
            if ($matches[1] == '*') {
                $from = 0;
                $to   = $ceiling - 1;
            }
            else {
                $from = $matches[2];
                if (isset($matches[4])) {
                    $to   = $matches[4];
                }
                else {
                    $to   = $from;
                }
            }
            if (isset($matches[6])) {
                $step = $matches[6];
            }
            else {
                $step = 1;
            }

            for ($i = $from; $i <= $to; $i += $step) {
                if ($ceil_zero_same && $i == $ceiling) {
                    $timeslices[0] = true;
                }
                else {
                    $timeslices[$i] = true;
                }
            }

        }
    }

    // the previous field wrapped, this one HAS to change
    if ($propagate) {
        $currentvalue++;
        $steps = 1;
    }
    else {
        $steps = 0;
    }

    for ($currentvalue; $currentvalue < $ceiling; $currentvalue++, $steps++) {
        if ($timeslices[$currentvalue]) {
            break;
        }
    }

    // if we found a value
    if ($currentvalue != $ceiling) {
        $propagate = 0;
        return $currentvalue;
    }

    for ($currentvalue= ($allowzero ? 0 : 1); $currentvalue < $ceiling; $currentvalue++, $steps++) {
        if ($timeslices[$currentvalue]) {
            break;
        }
    }

    $propagate = 1;
    return $currentvalue;
}

function cron_day_of_week($date_array) {
    return date('w', mktime(0, 0, 0, $date_array['mon'], $date_array['mday'], $date_array['year']));
}

// --------------------------------------------------------

function cron_valid_month($job, $run_date) {
    $propagate = 0;
    cron_next_field_value($job['month'], $run_date['mon'], 13, $propagate, $steps, false);

    if ($steps) {
        return false;
    }
    else {
        return true;
    }
}

function cron_valid_day($job, $run_date) {
    $propagate = 0;
    cron_next_field_value($job['day'], $run_date['mday'], 32, $propagate, $dayofmonth_steps, false);

    $propagate = 0;
    cron_next_field_value($job['dayofweek'], cron_day_of_week($run_date), 7, $propagate, $dayofweek_steps, true);

    if ($job['dayofweek'] == '*') {
        return ($dayofmonth_steps ? false : true);
    }
    else if ($job['day'] == '*') {
        return ($dayofweek_steps ? false : true);
    }
    else {
        if ($dayofmonth_steps && $dayofweek_steps) {
            return false;
        }
        else {
            return true;
        }
    }
}

function cron_valid_hour($job, $run_date) {
    $propagate = 0;
    cron_next_field_value($job['hour'], $run_date['hours'], 24, $propagate, $steps);

    if ($steps) {
        return false;
    }
    else {
        return true;
    }
}

function cron_valid_minute($job, $run_date) {
    $propagate = 0;
    cron_next_field_value($job['minute'], $run_date['minutes'], 60, $propagate, $steps);

    if ($steps) {
        return false;
    }
    else {
        return true;
    }
}

function cron_next_month($job, &$run_date) {
    $propagate = 1;
    $run_date['mon'] = cron_next_field_value($job['month'], $run_date['mon'], 13, $propagate, $steps, false);

    if ($propagate) {
        $run_date['year']++;
    }
}

function cron_next_day($job, &$run_date) {
    // work out which has less steps
    $propagate = 1;
    cron_next_field_value($job['day'], $run_date['mday'], 32, $propagate, $month_steps, false);
    $propagate = 1;
    cron_next_field_value($job['dayofweek'], cron_day_of_week($run_date), 7, $propagate, $week_steps, true, true);

    if ($job['dayofweek'] == '*') {
        $run_date['mday'] += $month_steps;
    }
    else if ($job['day'] == '*') {
        $run_date['mday'] += $week_steps;
    }
    else if ($month_steps < $week_steps) {
        $run_date['mday'] += $month_steps;
    }
    else {
        $run_date['mday'] += $week_steps;
    }

    // if the day is outside the range of this month, try again from 0
    if ($run_date['mday'] > date('t', mktime(0, 0, 0, $run_date['mon'], 1, $run_date['year']))) {
        cron_next_month($job, $run_date);

        cron_first_day($job, $run_date);
    }
}

function cron_next_hour($job, &$run_date) {
    $propagate = 1;
    $run_date['hours'] = cron_next_field_value($job['hour'], $run_date['hours'], 24, $propagate, $steps);

    if ($propagate) {
        cron_next_day($job, $run_date);
    }
}

function cron_next_minute($job, &$run_date) {
    $propagate = 1;
    $run_date['minutes'] = cron_next_field_value($job['minute'], $run_date['minutes'], 60, $propagate, $steps);

    if ($propagate) {
        cron_next_hour($job, $run_date);
    }
}

function cron_first_day($job, &$run_date) {
    $propagate = 0;
    cron_next_field_value($job['day'], 1, 32, $propagate, $month_steps, false);

    $propagate = 0;
    $run_date['mday'] = 1;
    cron_next_field_value($job['dayofweek'], cron_day_of_week($run_date), 7, $propagate, $week_steps, true, true);

    if ($job['dayofweek'] == '*') {
        $run_date['mday'] += $month_steps;
    }
    else if ($job['day'] == '*') {
        $run_date['mday'] += $week_steps;
    }
    else if ($month_steps < $week_steps) {
        $run_date['mday'] += $month_steps;
    }
    else {
Penny Leach's avatar
Penny Leach committed
446
        log_debug('using week_steps: ' . $week_steps);
Martyn Smith's avatar
Martyn Smith committed
447 448 449
        $run_date['mday'] += $week_steps;
    }

Penny Leach's avatar
Penny Leach committed
450
    log_debug('    setting mday to ' . $run_date['mday']);
Martyn Smith's avatar
Martyn Smith committed
451 452 453 454 455 456 457 458 459 460 461 462
}

function cron_first_hour($job, &$run_date) {
    $propagate = 0;
    $run_date['hours'] = cron_next_field_value($job['hour'], 0, 24, $propagate, $steps);
}

function cron_first_minute($job, &$run_date) {
    $propagate = 0;
    $run_date['minutes'] = cron_next_field_value($job['minute'], 0, 60, $propagate, $steps);
}

463 464 465 466 467
function cron_job_id($job, $plugintype) {
    return $plugintype . (!empty($job->plugin) ? "_$job->plugin" : '') . '_' . $job->callfunction;
}

function cron_lock($job, $start, $plugintype='core') {
468 469
    global $DB_IGNORE_SQL_EXCEPTIONS;

470 471 472
    $jobname = cron_job_id($job, $plugintype);
    $lockname = '_cron_lock_' . $jobname;

473 474 475 476
    // The rationale for catching the SQLException on this insert is to
    // ensure that if two crons run simultaneously, they may both fail the
    // get_field and thus both try the insert. We try the get_field first
    // to try and limit the number of exceptions that we catch and throw.
477
    if (!$started = get_field('config', 'value', 'field', $lockname)) {
478 479
        try {
            $DB_IGNORE_SQL_EXCEPTIONS = true;
480
            insert_record('config', (object) array('field' => $lockname, 'value' => $start));
481
            $DB_IGNORE_SQL_EXCEPTIONS = false;
482 483
            return true;
        }
484 485 486 487 488
        catch (SQLException $e) {
            $DB_IGNORE_SQL_EXCEPTIONS = false;
            $started = get_field('config', 'value', 'field', $lockname);
        }
    }
489

490 491 492
    $strstart = $started ? date('r', $started) : '';
    $msg = "long-running cron job $jobname ($strstart).";

493
    // If it's been going for more than 24 hours, remove the lock
494
    if ($started && $started < $start - 60*60*24) {
495
        log_info('Removing lock record for ' . $msg);
496 497
        cron_free($job, $started, $plugintype);
        return false;
498 499
    }

500
    log_info('Skipping ' . $msg);
501
    return false;
502 503 504 505 506
}

function cron_free($job, $start, $plugintype='core') {
    delete_records('config', 'field', '_cron_lock_' . cron_job_id($job, $plugintype), 'value', $start);
}