Proyectos de Subversion Moodle

Rev

Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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.
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
 * Scheduled and adhoc task management.
19
 *
20
 * @package    core
21
 * @category   task
22
 * @copyright  2013 Damyon Wiese
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
namespace core\task;
26
 
27
use core\lock\lock;
28
use core\lock\lock_factory;
29
use core_shutdown_manager;
30
 
31
define('CORE_TASK_TASKS_FILENAME', 'db/tasks.php');
32
/**
33
 * Collection of task related methods.
34
 *
35
 * Some locking rules for this class:
36
 * All changes to scheduled tasks must be protected with both - the global cron lock and the lock
37
 * for the specific scheduled task (in that order). Locks must be released in the reverse order.
38
 * @copyright  2013 Damyon Wiese
39
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40
 */
41
class manager {
42
 
43
    /**
44
     * @var int Used to tell the adhoc task queue to fairly distribute tasks.
45
     */
46
    const ADHOC_TASK_QUEUE_MODE_DISTRIBUTING = 0;
47
 
48
    /**
49
     * @var int Used to tell the adhoc task queue to try and fill unused capacity.
50
     */
51
    const ADHOC_TASK_QUEUE_MODE_FILLING = 1;
52
 
53
    /**
54
     * @var int Used to set the retention period for adhoc tasks that have failed and to be cleaned up.
55
     * The number is in week unit. The default value is 4 weeks.
56
     */
57
    const ADHOC_TASK_FAILED_RETENTION = 4 * WEEKSECS;
58
 
59
    /**
60
     * @var ?task_base $runningtask Used to tell what is the current running task in this process.
61
     */
62
    public static ?task_base $runningtask = null;
63
 
64
    /**
65
     * @var bool Used to tell if the manager's shutdown callback has been registered.
66
     */
67
    public static bool $registeredshutdownhandler = false;
68
 
69
    /**
70
     * @var array A cached queue of adhoc tasks
71
     */
72
    protected static array $miniqueue = [];
73
 
74
    /**
75
     * @var int The last recorded number of unique adhoc tasks.
76
     */
77
    protected static int $numtasks = 0;
78
 
79
    /**
80
     * @var null|int Used to determine if the adhoc task queue is distributing or filling capacity.
81
     */
82
    protected static ?int $mode = null;
83
 
84
    /**
85
     * Reset the state of the task manager.
86
     */
87
    public static function reset_state(): void {
88
        self::$miniqueue = [];
89
        self::$numtasks = 0;
90
        self::$mode = null;
91
    }
92
 
93
    /**
94
     * Given a component name, will load the list of tasks in the db/tasks.php file for that component.
95
     *
96
     * @param string $componentname - The name of the component to fetch the tasks for.
97
     * @param bool $expandr - if true (default) an 'R' value in a time is expanded to an appropriate int.
98
     *      If false, they are left as 'R'
99
     * @return \core\task\scheduled_task[] - List of scheduled tasks for this component.
100
     */
101
    public static function load_default_scheduled_tasks_for_component($componentname, $expandr = true) {
102
        $dir = \core_component::get_component_directory($componentname);
103
 
104
        if (!$dir) {
105
            return array();
106
        }
107
 
108
        $file = $dir . '/' . CORE_TASK_TASKS_FILENAME;
109
        if (!file_exists($file)) {
110
            return array();
111
        }
112
 
113
        $tasks = null;
114
        include($file);
115
 
116
        if (!isset($tasks)) {
117
            return array();
118
        }
119
 
120
        $scheduledtasks = array();
121
 
122
        foreach ($tasks as $task) {
123
            $record = (object) $task;
124
            $scheduledtask = self::scheduled_task_from_record($record, $expandr, false);
125
            // Safety check in case the task in the DB does not match a real class (maybe something was uninstalled).
126
            if ($scheduledtask) {
127
                $scheduledtask->set_component($componentname);
128
                $scheduledtasks[] = $scheduledtask;
129
            }
130
        }
131
 
132
        return $scheduledtasks;
133
    }
134
 
135
    /**
136
     * Update the database to contain a list of scheduled task for a component.
137
     * The list of scheduled tasks is taken from @load_scheduled_tasks_for_component.
138
     * Will throw exceptions for any errors.
139
     *
140
     * @param string $componentname - The frankenstyle component name.
141
     */
142
    public static function reset_scheduled_tasks_for_component($componentname) {
143
        global $DB;
144
        $tasks = self::load_default_scheduled_tasks_for_component($componentname);
145
        $validtasks = array();
146
 
147
        foreach ($tasks as $taskid => $task) {
148
            $classname = self::get_canonical_class_name($task);
149
 
150
            $validtasks[] = $classname;
151
 
152
            if ($currenttask = self::get_scheduled_task($classname)) {
153
                if ($currenttask->is_customised()) {
154
                    // If there is an existing task with a custom schedule, do not override it.
155
                    continue;
156
                }
157
 
158
                // Update the record from the default task data.
159
                self::configure_scheduled_task($task);
160
            } else {
161
                // Ensure that the first run follows the schedule.
162
                $task->set_next_run_time($task->get_next_scheduled_time());
163
 
164
                // Insert the new task in the database.
165
                $record = self::record_from_scheduled_task($task);
166
                $DB->insert_record('task_scheduled', $record);
167
            }
168
        }
169
 
170
        // Delete any task that is not defined in the component any more.
171
        $sql = "component = :component";
172
        $params = array('component' => $componentname);
173
        if (!empty($validtasks)) {
174
            list($insql, $inparams) = $DB->get_in_or_equal($validtasks, SQL_PARAMS_NAMED, 'param', false);
175
            $sql .= ' AND classname ' . $insql;
176
            $params = array_merge($params, $inparams);
177
        }
178
        $DB->delete_records_select('task_scheduled', $sql, $params);
179
    }
180
 
181
    /**
182
     * Checks if the task with the same classname, component and customdata is already scheduled
183
     *
184
     * @param adhoc_task $task
185
     * @return bool
186
     */
187
    protected static function task_is_scheduled($task) {
188
        return false !== self::get_queued_adhoc_task_record($task);
189
    }
190
 
191
    /**
192
     * Checks if the task with the same classname, component and customdata is already scheduled
193
     *
194
     * @param adhoc_task $task
195
     * @return \stdClass|false
196
     */
197
    protected static function get_queued_adhoc_task_record($task) {
198
        global $DB;
199
 
200
        $record = self::record_from_adhoc_task($task);
201
        $params = [$record->classname, $record->component, $record->customdata];
202
        $sql = 'classname = ? AND component = ? AND ' .
203
            $DB->sql_compare_text('customdata', \core_text::strlen($record->customdata) + 1) . ' = ?';
204
 
205
        if ($record->userid) {
206
            $params[] = $record->userid;
207
            $sql .= " AND userid = ? ";
208
        }
209
        return $DB->get_record_select('task_adhoc', $sql, $params);
210
    }
211
 
212
    /**
213
     * Schedule a new task, or reschedule an existing adhoc task which has matching data.
214
     *
215
     * Only a task matching the same user, classname, component, and customdata will be rescheduled.
216
     * If these values do not match exactly then a new task is scheduled.
217
     *
218
     * @param \core\task\adhoc_task $task - The new adhoc task information to store.
219
     * @since Moodle 3.7
220
     */
221
    public static function reschedule_or_queue_adhoc_task(adhoc_task $task): void {
222
        global $DB;
223
 
224
        if ($existingrecord = self::get_queued_adhoc_task_record($task)) {
225
            // Only update the next run time if it is explicitly set on the task.
226
            $nextruntime = $task->get_next_run_time();
227
            if ($nextruntime && ($existingrecord->nextruntime != $nextruntime)) {
228
                $DB->set_field('task_adhoc', 'nextruntime', $nextruntime, ['id' => $existingrecord->id]);
229
            }
230
        } else {
231
            // There is nothing queued yet. Just queue as normal.
232
            self::queue_adhoc_task($task);
233
        }
234
    }
235
 
236
    /**
237
     * Queue an adhoc task to run in the background.
238
     *
239
     * @param \core\task\adhoc_task $task - The new adhoc task information to store.
240
     * @param bool $checkforexisting - If set to true and the task with the same user, classname, component and customdata
241
     *     is already scheduled then it will not schedule a new task. Can be used only for ASAP tasks.
242
     * @return boolean - True if the config was saved.
243
     */
244
    public static function queue_adhoc_task(adhoc_task $task, $checkforexisting = false) {
245
        global $DB;
246
 
247
        if ($userid = $task->get_userid()) {
248
            // User found. Check that they are suitable.
249
            \core_user::require_active_user(\core_user::get_user($userid, '*', MUST_EXIST), true, true);
250
        }
251
 
252
        $record = self::record_from_adhoc_task($task);
253
        // Schedule it immediately if nextruntime not explicitly set.
254
        if (!$task->get_next_run_time()) {
255
            $record->nextruntime = time() - 1;
256
        }
257
 
258
        // Check if the task is allowed to be retried or not.
259
        $record->attemptsavailable = $task->retry_until_success() ? $record->attemptsavailable : 1;
260
        // Set the time the task was created.
261
        $record->timecreated = time();
262
 
263
        // Check if the same task is already scheduled.
264
        if ($checkforexisting && self::task_is_scheduled($task)) {
265
            return false;
266
        }
267
 
268
        // Queue the task.
269
        $result = $DB->insert_record('task_adhoc', $record);
270
 
271
        return $result;
272
    }
273
 
274
    /**
275
     * Change the default configuration for a scheduled task.
276
     * The list of scheduled tasks is taken from {@link load_scheduled_tasks_for_component}.
277
     *
278
     * @param \core\task\scheduled_task $task - The new scheduled task information to store.
279
     * @return boolean - True if the config was saved.
280
     */
281
    public static function configure_scheduled_task(scheduled_task $task) {
282
        global $DB;
283
 
284
        $classname = self::get_canonical_class_name($task);
285
 
286
        $original = $DB->get_record('task_scheduled', array('classname'=>$classname), 'id', MUST_EXIST);
287
 
288
        $record = self::record_from_scheduled_task($task);
289
        $record->id = $original->id;
290
        $record->nextruntime = $task->get_next_scheduled_time();
291
        unset($record->lastruntime);
292
        $result = $DB->update_record('task_scheduled', $record);
293
 
294
        return $result;
295
    }
296
 
297
    /**
298
     * Utility method to create a DB record from a scheduled task.
299
     *
300
     * @param \core\task\scheduled_task $task
301
     * @return \stdClass
302
     */
303
    public static function record_from_scheduled_task($task) {
304
        $record = new \stdClass();
305
        $record->classname = self::get_canonical_class_name($task);
306
        $record->component = $task->get_component();
307
        $record->customised = $task->is_customised();
308
        $record->lastruntime = $task->get_last_run_time();
309
        $record->nextruntime = $task->get_next_run_time();
310
        $record->faildelay = $task->get_fail_delay();
311
        $record->hour = $task->get_hour();
312
        $record->minute = $task->get_minute();
313
        $record->day = $task->get_day();
314
        $record->dayofweek = $task->get_day_of_week();
315
        $record->month = $task->get_month();
316
        $record->disabled = $task->get_disabled();
317
        $record->timestarted = $task->get_timestarted();
318
        $record->hostname = $task->get_hostname();
319
        $record->pid = $task->get_pid();
320
 
321
        return $record;
322
    }
323
 
324
    /**
325
     * Utility method to create a DB record from an adhoc task.
326
     *
327
     * @param \core\task\adhoc_task $task
328
     * @return \stdClass
329
     */
330
    public static function record_from_adhoc_task($task) {
331
        $record = new \stdClass();
332
        $record->classname = self::get_canonical_class_name($task);
333
        $record->id = $task->get_id();
334
        $record->component = $task->get_component();
335
        $record->nextruntime = $task->get_next_run_time();
336
        $record->faildelay = $task->get_fail_delay();
337
        $record->customdata = $task->get_custom_data_as_string();
338
        $record->userid = $task->get_userid();
339
        $record->timestarted = $task->get_timestarted();
340
        $record->hostname = $task->get_hostname();
341
        $record->pid = $task->get_pid();
342
        $record->attemptsavailable = $task->get_attempts_available();
343
 
344
        return $record;
345
    }
346
 
347
    /**
348
     * Utility method to create an adhoc task from a DB record.
349
     *
350
     * @param \stdClass $record
351
     * @return \core\task\adhoc_task
352
     * @throws \moodle_exception
353
     */
354
    public static function adhoc_task_from_record($record) {
355
        $classname = self::get_canonical_class_name($record->classname);
356
        if (!class_exists($classname)) {
357
            throw new \moodle_exception('invalidtaskclassname', '', '', $record->classname);
358
        }
359
        $task = new $classname;
360
        if (isset($record->nextruntime)) {
361
            $task->set_next_run_time($record->nextruntime);
362
        }
363
        if (isset($record->id)) {
364
            $task->set_id($record->id);
365
        }
366
        if (isset($record->component)) {
367
            $task->set_component($record->component);
368
        }
369
        if (isset($record->faildelay)) {
370
            $task->set_fail_delay($record->faildelay);
371
        }
372
        if (isset($record->customdata)) {
373
            $task->set_custom_data_as_string($record->customdata);
374
        }
375
 
376
        if (isset($record->userid)) {
377
            $task->set_userid($record->userid);
378
        }
379
        if (isset($record->timestarted)) {
380
            $task->set_timestarted($record->timestarted);
381
        }
382
        if (isset($record->hostname)) {
383
            $task->set_hostname($record->hostname);
384
        }
385
        if (isset($record->pid)) {
386
            $task->set_pid($record->pid);
387
        }
388
        if (isset($record->attemptsavailable)) {
389
            $task->set_attempts_available($record->attemptsavailable);
390
        }
391
 
392
        return $task;
393
    }
394
 
395
    /**
396
     * Utility method to create a task from a DB record.
397
     *
398
     * @param \stdClass $record
399
     * @param bool $expandr - if true (default) an 'R' value in a time is expanded to an appropriate int.
400
     *      If false, they are left as 'R'
401
     * @param bool $override - if true loads overridden settings from config.
402
     * @return \core\task\scheduled_task|false
403
     */
404
    public static function scheduled_task_from_record($record, $expandr = true, $override = true) {
405
        $classname = self::get_canonical_class_name($record->classname);
406
        if (!class_exists($classname)) {
407
            debugging("Failed to load task: " . $classname, DEBUG_DEVELOPER);
408
            return false;
409
        }
410
        /** @var \core\task\scheduled_task $task */
411
        $task = new $classname;
412
 
413
        if ($override) {
414
            // Update values with those defined in the config, if any are set.
415
            $record = self::get_record_with_config_overrides($record);
416
        }
417
 
418
        if (isset($record->lastruntime)) {
419
            $task->set_last_run_time($record->lastruntime);
420
        }
421
        if (isset($record->nextruntime)) {
422
            $task->set_next_run_time($record->nextruntime);
423
        }
424
        if (isset($record->customised)) {
425
            $task->set_customised($record->customised);
426
        }
427
        if (isset($record->component)) {
428
            $task->set_component($record->component);
429
        }
430
        if (isset($record->minute)) {
431
            $task->set_minute($record->minute, $expandr);
432
        }
433
        if (isset($record->hour)) {
434
            $task->set_hour($record->hour, $expandr);
435
        }
436
        if (isset($record->day)) {
437
            $task->set_day($record->day);
438
        }
439
        if (isset($record->month)) {
440
            $task->set_month($record->month);
441
        }
442
        if (isset($record->dayofweek)) {
443
            $task->set_day_of_week($record->dayofweek, $expandr);
444
        }
445
        if (isset($record->faildelay)) {
446
            $task->set_fail_delay($record->faildelay);
447
        }
448
        if (isset($record->disabled)) {
449
            $task->set_disabled($record->disabled);
450
        }
451
        if (isset($record->timestarted)) {
452
            $task->set_timestarted($record->timestarted);
453
        }
454
        if (isset($record->hostname)) {
455
            $task->set_hostname($record->hostname);
456
        }
457
        if (isset($record->pid)) {
458
            $task->set_pid($record->pid);
459
        }
460
        $task->set_overridden(self::scheduled_task_has_override($classname));
461
 
462
        return $task;
463
    }
464
 
465
    /**
466
     * Given a component name, will load the list of tasks from the scheduled_tasks table for that component.
467
     * Do not execute tasks loaded from this function - they have not been locked.
468
     * @param string $componentname - The name of the component to load the tasks for.
469
     * @return \core\task\scheduled_task[]
470
     */
471
    public static function load_scheduled_tasks_for_component($componentname) {
472
        global $DB;
473
 
474
        $tasks = array();
475
        // We are just reading - so no locks required.
476
        $records = $DB->get_records('task_scheduled', array('component' => $componentname), 'classname', '*', IGNORE_MISSING);
477
        foreach ($records as $record) {
478
            $task = self::scheduled_task_from_record($record);
479
            // Safety check in case the task in the DB does not match a real class (maybe something was uninstalled).
480
            if ($task) {
481
                $tasks[] = $task;
482
            }
483
        }
484
 
485
        return $tasks;
486
    }
487
 
488
    /**
489
     * This function load the scheduled task details for a given classname.
490
     *
491
     * @param string $classname
492
     * @return \core\task\scheduled_task or false
493
     */
494
    public static function get_scheduled_task($classname) {
495
        global $DB;
496
 
497
        $classname = self::get_canonical_class_name($classname);
498
        // We are just reading - so no locks required.
499
        $record = $DB->get_record('task_scheduled', array('classname'=>$classname), '*', IGNORE_MISSING);
500
        if (!$record) {
501
            return false;
502
        }
503
        return self::scheduled_task_from_record($record);
504
    }
505
 
506
    /**
507
     * This function load the adhoc tasks for a given classname.
508
     *
509
     * @param string $classname
510
     * @param bool $failedonly
511
     * @param bool $skiprunning do not return tasks that are in the running state
512
     * @return array
513
     */
514
    public static function get_adhoc_tasks(string $classname, bool $failedonly = false, bool $skiprunning = false): array {
515
        global $DB;
516
 
517
        $conds[] = 'classname = ?';
518
        $params[] = self::get_canonical_class_name($classname);
519
 
520
        if ($failedonly) {
521
            $conds[] = 'faildelay > 0';
522
        }
523
        if ($skiprunning) {
524
            $conds[] = 'timestarted IS NULL';
525
        }
526
 
527
        // We are just reading - so no locks required.
528
        $sql = 'SELECT * FROM {task_adhoc}';
529
        if ($conds) {
530
            $sql .= ' WHERE '.implode(' AND ', $conds);
531
        }
532
        $rs = $DB->get_records_sql($sql, $params);
533
        return array_map(function($record) {
534
            return self::adhoc_task_from_record($record);
535
        }, $rs);
536
    }
537
 
538
    /**
539
     * This function returns adhoc tasks summary per component classname
540
     *
541
     * @return array
542
     */
543
    public static function get_adhoc_tasks_summary(): array {
544
        global $DB;
545
 
546
        $now = time();
547
        $records = $DB->get_records('task_adhoc');
548
        $summary = [];
549
        foreach ($records as $r) {
550
            if (!isset($summary[$r->component])) {
551
                $summary[$r->component] = [];
552
            }
553
 
554
            if (isset($summary[$r->component][$r->classname])) {
555
                $classsummary = $summary[$r->component][$r->classname];
556
            } else {
557
                $classsummary = [
558
                    'nextruntime' => null,
559
                    'count' => 0,
560
                    'failed' => 0,
561
                    'running' => 0,
562
                    'due' => 0,
563
                    'stop' => false,
564
                ];
565
            }
566
 
567
            $classsummary['count']++;
568
            $nextruntime = (int)$r->nextruntime;
569
            if (!$classsummary['nextruntime'] || $nextruntime < $classsummary['nextruntime']) {
570
                $classsummary['nextruntime'] = $nextruntime;
571
            }
572
 
573
            if ((int)$r->timestarted > 0) {
574
                $classsummary['running']++;
575
            } else {
576
                if ((int)$r->faildelay > 0) {
577
                    $classsummary['failed']++;
578
                }
579
 
580
                if ($nextruntime <= $now) {
581
                    $classsummary['due']++;
582
                }
583
            }
584
 
585
            // Mark the task as stopped if it has no attempts available.
586
            if (isset($r->attemptsavailable) && $r->attemptsavailable == 0) {
587
                $classsummary['stop'] = true;
588
            }
589
 
590
            $summary[$r->component][$r->classname] = $classsummary;
591
        }
592
        return $summary;
593
    }
594
 
595
    /**
596
     * This function load the default scheduled task details for a given classname.
597
     *
598
     * @param string $classname
599
     * @param bool $expandr - if true (default) an 'R' value in a time is expanded to an appropriate int.
600
     *      If false, they are left as 'R'
601
     * @return \core\task\scheduled_task|false
602
     */
603
    public static function get_default_scheduled_task($classname, $expandr = true) {
604
        $task = self::get_scheduled_task($classname);
605
        $componenttasks = array();
606
 
607
        // Safety check in case no task was found for the given classname.
608
        if ($task) {
609
            $componenttasks = self::load_default_scheduled_tasks_for_component(
610
                    $task->get_component(), $expandr);
611
        }
612
 
613
        foreach ($componenttasks as $componenttask) {
614
            if (get_class($componenttask) == get_class($task)) {
615
                return $componenttask;
616
            }
617
        }
618
 
619
        return false;
620
    }
621
 
622
    /**
623
     * This function will return a list of all the scheduled tasks that exist in the database.
624
     *
625
     * @return \core\task\scheduled_task[]
626
     */
627
    public static function get_all_scheduled_tasks() {
628
        global $DB;
629
 
630
        $records = $DB->get_records('task_scheduled', null, 'component, classname', '*', IGNORE_MISSING);
631
        $tasks = array();
632
 
633
        foreach ($records as $record) {
634
            $task = self::scheduled_task_from_record($record);
635
            // Safety check in case the task in the DB does not match a real class (maybe something was uninstalled).
636
            if ($task) {
637
                $tasks[] = $task;
638
            }
639
        }
640
 
641
        return $tasks;
642
    }
643
 
644
    /**
645
     * This function will return a list of all adhoc tasks that have a faildelay
646
     *
647
     * @param int $delay filter how long the task has been delayed
648
     * @return \core\task\adhoc_task[]
649
     */
650
    public static function get_failed_adhoc_tasks(int $delay = 0): array {
651
        global $DB;
652
 
653
        $tasks = [];
654
        $records = $DB->get_records_sql('SELECT * from {task_adhoc} WHERE faildelay > ?', [$delay]);
655
 
656
        foreach ($records as $record) {
657
            try {
658
                $tasks[] = self::adhoc_task_from_record($record);
659
            } catch (\moodle_exception $e) {
660
                debugging("Failed to load task: $record->classname", DEBUG_DEVELOPER, $e->getTrace());
661
            }
662
        }
663
        return $tasks;
664
    }
665
 
666
    /**
667
     * Ensure quality of service for the ad hoc task queue.
668
     *
669
     * This reshuffles the adhoc tasks queue to balance by type to ensure a
670
     * level of quality of service per type, while still maintaining the
671
     * relative order of tasks queued by timestamp.
672
     *
673
     * @param array $records array of task records
674
     * @param array $records array of same task records shuffled
675
     * @deprecated since Moodle 4.1 MDL-67648 - please do not use this method anymore.
676
     * @todo MDL-74843 This method will be deleted in Moodle 4.5
677
     * @see \core\task\manager::get_next_adhoc_task
678
     */
679
    public static function ensure_adhoc_task_qos(array $records): array {
680
        debugging('The method \core\task\manager::ensure_adhoc_task_qos is deprecated.
681
             Please use \core\task\manager::get_next_adhoc_task instead.', DEBUG_DEVELOPER);
682
 
683
        $count = count($records);
684
        if ($count == 0) {
685
            return $records;
686
        }
687
 
688
        $queues = []; // This holds a queue for each type of adhoc task.
689
        $limits = []; // The relative limits of each type of task.
690
        $limittotal = 0;
691
 
692
        // Split the single queue up into queues per type.
693
        foreach ($records as $record) {
694
            $type = $record->classname;
695
            if (!array_key_exists($type, $queues)) {
696
                $queues[$type] = [];
697
            }
698
            if (!array_key_exists($type, $limits)) {
699
                $limits[$type] = 1;
700
                $limittotal += 1;
701
            }
702
            $queues[$type][] = $record;
703
        }
704
 
705
        $qos = []; // Our new queue with ensured quality of service.
706
        $seed = $count % $limittotal; // Which task queue to shuffle from first?
707
 
708
        $move = 1; // How many tasks to shuffle at a time.
709
        do {
710
            $shuffled = 0;
711
 
712
            // Now cycle through task type queues and interleaving the tasks
713
            // back into a single queue.
714
            foreach ($limits as $type => $limit) {
715
 
716
                // Just interleaving the queue is not enough, because after
717
                // any task is processed the whole queue is rebuilt again. So
718
                // we need to deterministically start on different types of
719
                // tasks so that *on average* we rotate through each type of task.
720
                //
721
                // We achieve this by using a $seed to start moving tasks off a
722
                // different queue each time. The seed is based on the task count
723
                // modulo the number of types of tasks on the queue. As we count
724
                // down this naturally cycles through each type of record.
725
                if ($seed < 1) {
726
                    $shuffled = 1;
727
                    $seed += 1;
728
                    continue;
729
                }
730
                $tasks = array_splice($queues[$type], 0, $move);
731
                $qos = array_merge($qos, $tasks);
732
 
733
                // Stop if we didn't move any tasks onto the main queue.
734
                $shuffled += count($tasks);
735
            }
736
            // Generally the only tasks that matter are those that are near the start so
737
            // after we have shuffled the first few 1 by 1, start shuffling larger groups.
738
            if (count($qos) >= (4 * count($limits))) {
739
                $move *= 2;
740
            }
741
        } while ($shuffled > 0);
742
 
743
        return $qos;
744
    }
745
 
746
    /**
747
     * This function will dispatch the next adhoc task in the queue. The task will be handed out
748
     * with an open lock - possibly on the entire cron process. Make sure you call either
749
     * {@link adhoc_task_failed} or {@link adhoc_task_complete} to release the lock and reschedule the task.
750
     *
751
     * @param int $timestart
752
     * @param bool $checklimits Should we check limits?
753
     * @param string|null $classname Return only task of this class
754
     * @return \core\task\adhoc_task|null
755
     * @throws \moodle_exception
756
     */
757
    public static function get_next_adhoc_task(int $timestart, ?bool $checklimits = true, ?string $classname = null): ?adhoc_task {
758
        global $DB;
759
 
760
        $concurrencylimit = get_config('core', 'task_adhoc_concurrency_limit');
761
        $cachedqueuesize = 1200;
762
 
763
        $uniquetasksinqueue = array_map(
764
            ['\core\task\manager', 'adhoc_task_from_record'],
765
            $DB->get_records_sql(
766
                'SELECT classname FROM {task_adhoc} WHERE nextruntime < :timestart GROUP BY classname',
767
                ['timestart' => $timestart]
768
            )
769
        );
770
 
771
        if (!isset(self::$numtasks) || self::$numtasks !== count($uniquetasksinqueue)) {
772
            self::$numtasks = count($uniquetasksinqueue);
773
            self::$miniqueue = [];
774
        }
775
 
776
        $concurrencylimits = [];
777
        if ($checklimits) {
778
            $concurrencylimits = array_map(
779
                function ($task) {
780
                    return $task->get_concurrency_limit();
781
                },
782
                $uniquetasksinqueue
783
            );
784
        }
785
 
786
        /*
787
         * The maximum number of cron runners that an individual task is allowed to use.
788
         * For example if the concurrency limit is 20 and there are 5 unique types of tasks
789
         * in the queue, each task should not be allowed to consume more than 3 (i.e., ⌊20/6⌋).
790
         * The + 1 is needed to prevent the queue from becoming full of only one type of class.
791
         * i.e., if it wasn't there and there were 20 tasks of the same type in the queue, every
792
         * runner would become consumed with the same (potentially long-running task) and no more
793
         * tasks can run. This way, some resources are always available if some new types
794
         * of tasks enter the queue.
795
         *
796
         * We use the short-ternary to force the value to 1 in the case when the number of tasks
797
         * exceeds the runners (e.g., there are 8 tasks and 4 runners, ⌊4/(8+1)⌋ = 0).
798
         */
799
        $slots = floor($concurrencylimit / (count($uniquetasksinqueue) + 1)) ?: 1;
800
        if (empty(self::$miniqueue)) {
801
            self::$mode = self::ADHOC_TASK_QUEUE_MODE_DISTRIBUTING;
802
            self::$miniqueue = self::get_candidate_adhoc_tasks(
803
                $timestart,
804
                $cachedqueuesize,
805
                $slots,
806
                $concurrencylimits
807
            );
808
        }
809
 
810
        // The query to cache tasks is expensive on big data sets, so we use this cheap
811
        // query to get the ordering (which is the interesting part about the main query)
812
        // We can use this information to filter the cache and also order it.
813
        $runningtasks = $DB->get_records_sql(
814
            'SELECT classname, COALESCE(COUNT(*), 0) running, MIN(timestarted) earliest
815
               FROM {task_adhoc}
816
              WHERE timestarted IS NOT NULL
817
                    AND (attemptsavailable > 0 OR attemptsavailable IS NULL)
818
                    AND nextruntime < :timestart
819
           GROUP BY classname
820
           ORDER BY running ASC, earliest DESC',
821
            ['timestart' => $timestart]
822
        );
823
 
824
        /*
825
         * Each runner has a cache, so the same task can be in multiple runners' caches.
826
         * We need to check that each task we have cached hasn't gone over its fair number
827
         * of slots. This filtering is only applied during distributing mode as when we are
828
         * filling capacity we intend for fast tasks to go over their slot limit.
829
         */
830
        if (self::$mode === self::ADHOC_TASK_QUEUE_MODE_DISTRIBUTING) {
831
            self::$miniqueue = array_filter(
832
                self::$miniqueue,
833
                function (\stdClass $task) use ($runningtasks, $slots) {
834
                    return !array_key_exists($task->classname, $runningtasks) || $runningtasks[$task->classname]->running < $slots;
835
                }
836
            );
837
        }
838
 
839
        /*
840
         * If this happens that means each task has consumed its fair share of capacity, but there's still
841
         * runners left over (and we are one of them). Fetch tasks without checking slot limits.
842
         */
843
        if (empty(self::$miniqueue) && array_sum(array_column($runningtasks, 'running')) < $concurrencylimit) {
844
            self::$mode = self::ADHOC_TASK_QUEUE_MODE_FILLING;
845
            self::$miniqueue = self::get_candidate_adhoc_tasks(
846
                $timestart,
847
                $cachedqueuesize,
848
                false,
849
                $concurrencylimits
850
            );
851
        }
852
 
853
        // Used below to order the cache.
854
        $ordering = array_flip(array_keys($runningtasks));
855
 
856
        // Order the queue so it's consistent with the ordering from the DB.
857
        usort(
858
            self::$miniqueue,
859
            function ($a, $b) use ($ordering) {
860
                return ($ordering[$a->classname] ?? -1) - ($ordering[$b->classname] ?? -1);
861
            }
862
        );
863
 
864
        $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
865
 
866
        $skipclasses = array();
867
 
868
        foreach (self::$miniqueue as $taskid => $record) {
869
 
870
            if (!empty($classname) && $record->classname != self::get_canonical_class_name($classname)) {
871
                // Skip the task if The class is specified, and doesn't match.
872
                continue;
873
            }
874
 
875
            if (in_array($record->classname, $skipclasses)) {
876
                // Skip the task if it can't be started due to per-task concurrency limit.
877
                continue;
878
            }
879
 
880
            if ($lock = $cronlockfactory->get_lock('adhoc_' . $record->id, 0)) {
881
 
882
                // Safety check, see if the task has been already processed by another cron run.
883
                $record = $DB->get_record('task_adhoc', array('id' => $record->id));
884
                if (!$record) {
885
                    $lock->release();
886
                    unset(self::$miniqueue[$taskid]);
887
                    continue;
888
                }
889
 
890
                // Safety check in case the task in the DB does not match a real class (maybe something was uninstalled).
891
                try {
892
                    $task = self::adhoc_task_from_record($record);
893
                } catch (\moodle_exception $e) {
894
                    debugging("Failed to load task: $record->classname", DEBUG_DEVELOPER);
895
                    $lock->release();
896
                    unset(self::$miniqueue[$taskid]);
897
                    continue;
898
                }
899
 
900
                $tasklimit = $task->get_concurrency_limit();
901
                if ($checklimits && $tasklimit > 0) {
902
                    if ($concurrencylock = self::get_concurrent_task_lock($task)) {
903
                        $task->set_concurrency_lock($concurrencylock);
904
                    } else {
905
                        // Unable to obtain a concurrency lock.
906
                        mtrace("Skipping $record->classname adhoc task class as the per-task limit of $tasklimit is reached.");
907
                        $skipclasses[] = $record->classname;
908
                        unset(self::$miniqueue[$taskid]);
909
                        $lock->release();
910
                        continue;
911
                    }
912
                }
913
 
914
                self::set_locks($task, $lock, $cronlockfactory);
915
                unset(self::$miniqueue[$taskid]);
916
 
917
                return $task;
918
            } else {
919
                unset(self::$miniqueue[$taskid]);
920
            }
921
        }
922
 
923
        return null;
924
    }
925
 
926
    /**
927
     * Return a list of candidate adhoc tasks to run.
928
     *
929
     * @param int $timestart Only return tasks where nextruntime is less than this value
930
     * @param int $limit Limit the list to this many results
931
     * @param int|null $runmax Only return tasks that have less than this value currently running
932
     * @param array $pertasklimits An array of classname => limit specifying how many instance of a task may be returned
933
     * @return array Array of candidate tasks
934
     */
935
    public static function get_candidate_adhoc_tasks(
936
        int $timestart,
937
        int $limit,
938
        ?int $runmax,
939
        array $pertasklimits = []
940
    ): array {
941
        global $DB;
942
 
943
        $pertaskclauses = array_map(
944
            function (string $class, int $limit, int $index): array {
945
                $limitcheck = $limit > 0 ? " AND COALESCE(run.running, 0) < :running_$index" : "";
946
                $limitparam = $limit > 0 ? ["running_$index" => $limit] : [];
947
 
948
                return [
949
                    "sql" => "(q.classname = :classname_$index" . $limitcheck . ")",
950
                    "params" => ["classname_$index" => $class] + $limitparam
951
                ];
952
            },
953
            array_keys($pertasklimits),
954
            $pertasklimits,
955
            $pertasklimits ? range(1, count($pertasklimits)) : []
956
        );
957
 
958
        $pertasksql = implode(" OR ", array_column($pertaskclauses, 'sql'));
959
        $pertaskparams = $pertaskclauses ? array_merge(...array_column($pertaskclauses, 'params')) : [];
960
 
961
        $params = ['timestart' => $timestart] +
962
                ($runmax ? ['runmax' => $runmax] : []) +
963
                $pertaskparams;
964
 
965
        return $DB->get_records_sql(
966
            "SELECT q.id, q.classname, q.timestarted, COALESCE(run.running, 0) running, run.earliest
967
              FROM {task_adhoc} q
968
         LEFT JOIN (
969
                       SELECT classname, COUNT(*) running, MIN(timestarted) earliest
970
                         FROM {task_adhoc} run
971
                        WHERE timestarted IS NOT NULL
972
                              AND (attemptsavailable > 0 OR attemptsavailable IS NULL)
973
                     GROUP BY classname
974
                   ) run ON run.classname = q.classname
975
             WHERE nextruntime < :timestart
976
                   AND q.timestarted IS NULL
977
                   AND (q.attemptsavailable > 0 OR q.attemptsavailable IS NULL) " .
978
            (!empty($pertasksql) ? "AND (" . $pertasksql . ") " : "") .
979
            ($runmax ? "AND (COALESCE(run.running, 0)) < :runmax " : "") .
980
         "ORDER BY COALESCE(run.running, 0) ASC, run.earliest DESC, q.nextruntime ASC, q.id ASC",
981
            $params,
982
            0,
983
            $limit
984
        );
985
    }
986
 
987
    /**
988
     * This function will get an adhoc task by id. The task will be handed out
989
     * with an open lock - possibly on the entire cron process. Make sure you call either
990
     * {@see ::adhoc_task_failed} or {@see ::adhoc_task_complete} to release the lock and reschedule the task.
991
     *
992
     * @param int $taskid
993
     * @return \core\task\adhoc_task|null
994
     * @throws \moodle_exception
995
     */
996
    public static function get_adhoc_task(int $taskid): ?adhoc_task {
997
        global $DB;
998
 
999
        $record = $DB->get_record('task_adhoc', ['id' => $taskid]);
1000
        if (!$record) {
1001
            throw new \moodle_exception('invalidtaskid');
1002
        }
1003
 
1004
        $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
1005
 
1006
        if ($lock = $cronlockfactory->get_lock('adhoc_' . $record->id, 0)) {
1007
            // Safety check in case the task in the DB does not match a real class (maybe something was uninstalled).
1008
            try {
1009
                $task = self::adhoc_task_from_record($record);
1010
            } catch (\moodle_exception $e) {
1011
                $lock->release();
1012
                throw $e;
1013
            }
1014
 
1015
            self::set_locks($task, $lock, $cronlockfactory);
1016
            return $task;
1017
        }
1018
 
1019
        return null;
1020
    }
1021
 
1022
    /**
1023
     * This function will set locks on the task.
1024
     *
1025
     * @param adhoc_task    $task
1026
     * @param lock          $lock task lock
1027
     * @param lock_factory  $cronlockfactory
1028
     * @throws \moodle_exception
1029
     */
1030
    private static function set_locks(adhoc_task $task, lock $lock, lock_factory $cronlockfactory): void {
1031
        // The global cron lock is under the most contention so request it
1032
        // as late as possible and release it as soon as possible.
1033
        if (!$cronlock = $cronlockfactory->get_lock('core_cron', 10)) {
1034
            $lock->release();
1035
            throw new \moodle_exception('locktimeout');
1036
        }
1037
 
1038
        $task->set_lock($lock);
1039
        $cronlock->release();
1040
    }
1041
 
1042
    /**
1043
     * This function will dispatch the next scheduled task in the queue. The task will be handed out
1044
     * with an open lock - possibly on the entire cron process. Make sure you call either
1045
     * {@link scheduled_task_failed} or {@link scheduled_task_complete} to release the lock and reschedule the task.
1046
     *
1047
     * @param int $timestart - The start of the cron process - do not repeat any tasks that have been run more recently than this.
1048
     * @return \core\task\scheduled_task or null
1049
     * @throws \moodle_exception
1050
     */
1051
    public static function get_next_scheduled_task($timestart) {
1052
        global $DB;
1053
        $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
1054
 
1055
        $where = "(lastruntime IS NULL OR lastruntime < :timestart1)
1056
                  AND (nextruntime IS NULL OR nextruntime < :timestart2)
1057
                  ORDER BY lastruntime, id ASC";
1058
        $params = array('timestart1' => $timestart, 'timestart2' => $timestart);
1059
        $records = $DB->get_records_select('task_scheduled', $where, $params);
1060
 
1061
        $pluginmanager = \core_plugin_manager::instance();
1062
 
1063
        foreach ($records as $record) {
1064
 
1065
            $task = self::scheduled_task_from_record($record);
1066
            // Safety check in case the task in the DB does not match a real class (maybe something was uninstalled).
1067
            // Also check to see if task is disabled or enabled after applying overrides.
1068
            if (!$task || $task->get_disabled()) {
1069
                continue;
1070
            }
1071
 
1072
            if ($lock = $cronlockfactory->get_lock(($record->classname), 0)) {
1073
                $classname = '\\' . $record->classname;
1074
 
1075
                $task->set_lock($lock);
1076
 
1077
                // See if the component is disabled.
1078
                $plugininfo = $pluginmanager->get_plugin_info($task->get_component());
1079
 
1080
                if ($plugininfo) {
1081
                    if (($plugininfo->is_enabled() === false) && !$task->get_run_if_component_disabled()) {
1082
                        $lock->release();
1083
                        continue;
1084
                    }
1085
                }
1086
 
1087
                if (!self::scheduled_task_has_override($record->classname)) {
1088
                    // Make sure the task data is unchanged unless an override is being used.
1089
                    if (!$DB->record_exists('task_scheduled', (array)$record)) {
1090
                        $lock->release();
1091
                        continue;
1092
                    }
1093
                }
1094
 
1095
                // The global cron lock is under the most contention so request it
1096
                // as late as possible and release it as soon as possible.
1097
                if (!$cronlock = $cronlockfactory->get_lock('core_cron', 10)) {
1098
                    $lock->release();
1099
                    throw new \moodle_exception('locktimeout');
1100
                }
1101
 
1102
                $cronlock->release();
1103
                return $task;
1104
            }
1105
        }
1106
 
1107
        return null;
1108
    }
1109
 
1110
    /**
1111
     * This function will fail the currently running task, if there is one.
1112
     */
1113
    public static function fail_running_task(): void {
1114
        $runningtask = self::$runningtask;
1115
 
1116
        if ($runningtask === null) {
1117
            return;
1118
        }
1119
 
1120
        if ($runningtask instanceof scheduled_task) {
1121
            self::scheduled_task_failed($runningtask);
1122
            return;
1123
        }
1124
 
1125
        if ($runningtask instanceof adhoc_task) {
1126
            self::adhoc_task_failed($runningtask);
1127
            return;
1128
        }
1129
    }
1130
 
1131
    /**
1132
     * This function set's the $runningtask variable and ensures that the shutdown handler is registered.
1133
     * @param task_base $task
1134
     */
1135
    private static function task_starting(task_base $task): void {
1136
        self::$runningtask = $task;
1137
 
1138
        // Add \core\task\manager::fail_running_task to shutdown manager, so we can ensure running tasks fail on shutdown.
1139
        if (!self::$registeredshutdownhandler) {
1140
            core_shutdown_manager::register_function('\core\task\manager::fail_running_task');
1141
 
1142
            self::$registeredshutdownhandler = true;
1143
        }
1144
    }
1145
 
1146
    /**
1147
     * This function indicates that an adhoc task was not completed successfully and should be retried.
1148
     *
1149
     * @param \core\task\adhoc_task $task
1150
     */
1151
    public static function adhoc_task_failed(adhoc_task $task) {
1152
        global $DB;
1153
        // Finalise the log output.
1154
        logmanager::finalise_log(true);
1155
 
1156
        $delay = $task->get_fail_delay();
1157
 
1158
        // Reschedule task with exponential fall off for failing tasks.
1159
        if (empty($delay)) {
1160
            $delay = 60;
1161
        } else {
1162
            $delay *= 2;
1163
        }
1164
 
1165
        // Max of 24 hour delay.
1166
        if ($delay >= 86400) {
1167
            $delay = 86400;
1168
 
1169
            // Dispatch hook when max fail delay has reached.
1170
            $hook = new \core\hook\task\after_failed_task_max_delay(
1171
                task: $task,
1172
            );
1173
            \core\di::get(\core\hook\manager::class)->dispatch($hook);
1174
        }
1175
 
1176
        // Reschedule and then release the locks.
1177
        $task->set_timestarted();
1178
        $task->set_hostname();
1179
        $task->set_pid();
1180
        $task->set_next_run_time(time() + $delay);
1181
        $task->set_fail_delay($delay);
1182
        if ($task->get_attempts_available() > 0) {
1183
            $task->set_attempts_available($task->get_attempts_available() - 1);
1184
        }
1185
        $record = self::record_from_adhoc_task($task);
1186
        $DB->update_record('task_adhoc', $record);
1187
 
1188
        $task->release_concurrency_lock();
1189
        $task->get_lock()->release();
1190
 
1191
        self::$runningtask = null;
1192
    }
1193
 
1194
    /**
1195
     * Records that a adhoc task is starting to run.
1196
     *
1197
     * @param adhoc_task $task Task that is starting
1198
     * @param int $time Start time (leave blank for now)
1199
     * @throws \dml_exception
1200
     * @throws \coding_exception
1201
     */
1202
    public static function adhoc_task_starting(adhoc_task $task, int $time = 0) {
1203
        global $DB;
1204
        $pid = (int)getmypid();
1205
        $hostname = (string)gethostname();
1206
 
1207
        if (empty($time)) {
1208
            $time = time();
1209
        }
1210
 
1211
        $task->set_timestarted($time);
1212
        $task->set_hostname($hostname);
1213
        $task->set_pid($pid);
1214
 
1215
        $record = self::record_from_adhoc_task($task);
1216
 
1217
        // If this is the first time the task has been started, then set the first starting time.
1218
        $firststartingtime = $DB->get_field('task_adhoc', 'firststartingtime', ['id' => $record->id]);
1219
        if (is_null($firststartingtime)) {
1220
            $record->firststartingtime = $time;
1221
        }
1222
 
1223
        $DB->update_record('task_adhoc', $record);
1224
 
1225
        self::task_starting($task);
1226
    }
1227
 
1228
    /**
1229
     * This function indicates that an adhoc task was completed successfully.
1230
     *
1231
     * @param \core\task\adhoc_task $task
1232
     */
1233
    public static function adhoc_task_complete(adhoc_task $task) {
1234
        global $DB;
1235
 
1236
        // Finalise the log output.
1237
        logmanager::finalise_log();
1238
        $task->set_timestarted();
1239
        $task->set_hostname();
1240
        $task->set_pid();
1241
 
1242
        // Delete the adhoc task record - it is finished.
1243
        $DB->delete_records('task_adhoc', array('id' => $task->get_id()));
1244
 
1245
        // Release the locks.
1246
        $task->release_concurrency_lock();
1247
        $task->get_lock()->release();
1248
 
1249
        self::$runningtask = null;
1250
    }
1251
 
1252
    /**
1253
     * This function indicates that a scheduled task was not completed successfully and should be retried.
1254
     *
1255
     * @param \core\task\scheduled_task $task
1256
     */
1257
    public static function scheduled_task_failed(scheduled_task $task) {
1258
        global $DB;
1259
        // Finalise the log output.
1260
        logmanager::finalise_log(true);
1261
 
1262
        $delay = $task->get_fail_delay();
1263
 
1264
        // Reschedule task with exponential fall off for failing tasks.
1265
        if (empty($delay)) {
1266
            $delay = 60;
1267
        } else {
1268
            $delay *= 2;
1269
        }
1270
 
1271
        // Max of 24 hour delay.
1272
        if ($delay >= 86400) {
1273
            $delay = 86400;
1274
 
1275
            // Dispatch hook when max fail delay has reached.
1276
            $hook = new \core\hook\task\after_failed_task_max_delay(
1277
                task: $task,
1278
            );
1279
            \core\di::get(\core\hook\manager::class)->dispatch($hook);
1280
        }
1281
 
1282
        $task->set_timestarted();
1283
        $task->set_hostname();
1284
        $task->set_pid();
1285
 
1286
        $classname = self::get_canonical_class_name($task);
1287
 
1288
        $record = $DB->get_record('task_scheduled', array('classname' => $classname));
1289
        $record->nextruntime = time() + $delay;
1290
        $record->faildelay = $delay;
1291
        $record->timestarted = null;
1292
        $record->hostname = null;
1293
        $record->pid = null;
1294
        $DB->update_record('task_scheduled', $record);
1295
 
1296
        $task->get_lock()->release();
1297
 
1298
        self::$runningtask = null;
1299
    }
1300
 
1301
    /**
1302
     * Clears the fail delay for the given task and updates its next run time based on the schedule.
1303
     *
1304
     * @param scheduled_task $task Task to reset
1305
     * @throws \dml_exception If there is a database error
1306
     */
1307
    public static function clear_fail_delay(scheduled_task $task) {
1308
        global $DB;
1309
 
1310
        $record = new \stdClass();
1311
        $record->id = $DB->get_field('task_scheduled', 'id',
1312
                ['classname' => self::get_canonical_class_name($task)]);
1313
        $record->nextruntime = $task->get_next_scheduled_time();
1314
        $record->faildelay = 0;
1315
        $DB->update_record('task_scheduled', $record);
1316
    }
1317
 
1318
    /**
1319
     * Records that a scheduled task is starting to run.
1320
     *
1321
     * @param scheduled_task $task Task that is starting
1322
     * @param int $time Start time (0 = current)
1323
     * @throws \dml_exception If the task doesn't exist
1324
     */
1325
    public static function scheduled_task_starting(scheduled_task $task, int $time = 0) {
1326
        global $DB;
1327
        $pid = (int)getmypid();
1328
        $hostname = (string)gethostname();
1329
 
1330
        if (!$time) {
1331
            $time = time();
1332
        }
1333
 
1334
        $task->set_timestarted($time);
1335
        $task->set_hostname($hostname);
1336
        $task->set_pid($pid);
1337
 
1338
        $classname = self::get_canonical_class_name($task);
1339
        $record = $DB->get_record('task_scheduled', ['classname' => $classname], '*', MUST_EXIST);
1340
        $record->timestarted = $time;
1341
        $record->hostname = $hostname;
1342
        $record->pid = $pid;
1343
        $DB->update_record('task_scheduled', $record);
1344
 
1345
        self::task_starting($task);
1346
    }
1347
 
1348
    /**
1349
     * This function indicates that a scheduled task was completed successfully and should be rescheduled.
1350
     *
1351
     * @param \core\task\scheduled_task $task
1352
     */
1353
    public static function scheduled_task_complete(scheduled_task $task) {
1354
        global $DB;
1355
 
1356
        // Finalise the log output.
1357
        logmanager::finalise_log();
1358
        $task->set_timestarted();
1359
        $task->set_hostname();
1360
        $task->set_pid();
1361
 
1362
        $classname = self::get_canonical_class_name($task);
1363
        $record = $DB->get_record('task_scheduled', array('classname' => $classname));
1364
        if ($record) {
1365
            $record->lastruntime = time();
1366
            $record->faildelay = 0;
1367
            $record->nextruntime = $task->get_next_scheduled_time();
1368
            $record->timestarted = null;
1369
            $record->hostname = null;
1370
            $record->pid = null;
1371
 
1372
            $DB->update_record('task_scheduled', $record);
1373
        }
1374
 
1375
        // Reschedule and then release the locks.
1376
        $task->get_lock()->release();
1377
 
1378
        self::$runningtask = null;
1379
    }
1380
 
1381
    /**
1382
     * Gets a list of currently-running tasks.
1383
     *
1384
     * @param  string $sort Sorting method
1385
     * @return array Array of scheduled and adhoc tasks
1386
     * @throws \dml_exception
1387
     */
1388
    public static function get_running_tasks($sort = ''): array {
1389
        global $DB;
1390
        if (empty($sort)) {
1391
            $sort = 'timestarted ASC, classname ASC';
1392
        }
1393
        $params = ['now1' => time(), 'now2' => time()];
1394
 
1395
        $sql = "SELECT subquery.*
1396
                  FROM (SELECT " . $DB->sql_concat("'s'", 'ts.id') . " as uniqueid,
1397
                               ts.id,
1398
                               'scheduled' as type,
1399
                               ts.classname,
1400
                               (:now1 - ts.timestarted) as time,
1401
                               ts.timestarted,
1402
                               ts.hostname,
1403
                               ts.pid
1404
                          FROM {task_scheduled} ts
1405
                         WHERE ts.timestarted IS NOT NULL
1406
                         UNION ALL
1407
                        SELECT " . $DB->sql_concat("'a'", 'ta.id') . " as uniqueid,
1408
                               ta.id,
1409
                               'adhoc' as type,
1410
                               ta.classname,
1411
                               (:now2 - ta.timestarted) as time,
1412
                               ta.timestarted,
1413
                               ta.hostname,
1414
                               ta.pid
1415
                          FROM {task_adhoc} ta
1416
                         WHERE ta.timestarted IS NOT NULL) subquery
1417
              ORDER BY " . $sort;
1418
 
1419
        return $DB->get_records_sql($sql, $params);
1420
    }
1421
 
1422
    /**
1423
     * Cleanup stale task metadata.
1424
     */
1425
    public static function cleanup_metadata() {
1426
        global $DB;
1427
 
1428
        $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
1429
        $runningtasks = self::get_running_tasks();
1430
 
1431
        foreach ($runningtasks as $runningtask) {
1432
            if ($runningtask->timestarted > time() - HOURSECS) {
1433
                continue;
1434
            }
1435
 
1436
            if ($runningtask->type == 'adhoc') {
1437
                $lock = $cronlockfactory->get_lock('adhoc_' . $runningtask->id, 0);
1438
            }
1439
 
1440
            if ($runningtask->type == 'scheduled') {
1441
                $lock = $cronlockfactory->get_lock($runningtask->classname, 0);
1442
            }
1443
 
1444
            // If we got this lock it means one of three things:
1445
            //
1446
            // 1. The task was stopped abnormally and the metadata was not cleaned up
1447
            // 2. This is the process running the cleanup task
1448
            // 3. We took so long getting to it in this loop that it did finish, and we now have the lock
1449
            //
1450
            // In the case of 1. we need to make the task as failed, in the case of 2. and 3. we do nothing.
1451
            if (!empty($lock)) {
1452
                if ($runningtask->classname == "\\" . \core\task\task_lock_cleanup_task::class) {
1453
                    $lock->release();
1454
                    continue;
1455
                }
1456
 
1457
                // We need to get the record again to verify whether or not we are dealing with case 3.
1458
                $taskrecord = $DB->get_record('task_' . $runningtask->type, ['id' => $runningtask->id]);
1459
 
1460
                if ($runningtask->type == 'scheduled') {
1461
                    // Empty timestarted indicates that this task finished (case 3) and was properly cleaned up.
1462
                    if (empty($taskrecord->timestarted)) {
1463
                        $lock->release();
1464
                        continue;
1465
                    }
1466
 
1467
                    $task = self::scheduled_task_from_record($taskrecord);
1468
                    $task->set_lock($lock);
1469
                    self::scheduled_task_failed($task);
1470
                } else if ($runningtask->type == 'adhoc') {
1471
                    // Ad hoc tasks are removed from the DB if they finish successfully.
1472
                    // If we can't re-get this task, that means it finished and was properly
1473
                    // cleaned up.
1474
                    if (!$taskrecord) {
1475
                        $lock->release();
1476
                        continue;
1477
                    }
1478
 
1479
                    $task = self::adhoc_task_from_record($taskrecord);
1480
                    $task->set_lock($lock);
1481
                    self::adhoc_task_failed($task);
1482
                }
1483
            }
1484
        }
1485
    }
1486
 
1487
    /**
1488
     * This function is used to indicate that any long running cron processes should exit at the
1489
     * next opportunity and restart. This is because something (e.g. DB changes) has changed and
1490
     * the static caches may be stale.
1491
     */
1492
    public static function clear_static_caches() {
1493
        global $DB;
1494
        // Do not use get/set config here because the caches cannot be relied on.
1495
        $record = $DB->get_record('config', array('name'=>'scheduledtaskreset'));
1496
        if ($record) {
1497
            $record->value = time();
1498
            $DB->update_record('config', $record);
1499
        } else {
1500
            $record = new \stdClass();
1501
            $record->name = 'scheduledtaskreset';
1502
            $record->value = time();
1503
            $DB->insert_record('config', $record);
1504
        }
1505
    }
1506
 
1507
    /**
1508
     * Return true if the static caches have been cleared since $starttime.
1509
     * @param int $starttime The time this process started.
1510
     * @return boolean True if static caches need resetting.
1511
     */
1512
    public static function static_caches_cleared_since($starttime) {
1513
        global $DB;
1514
        $record = $DB->get_record('config', array('name'=>'scheduledtaskreset'));
1515
        return $record && (intval($record->value) > $starttime);
1516
    }
1517
 
1518
    /**
1519
     * Gets class name for use in database table. Always begins with a \.
1520
     *
1521
     * @param string|task_base $taskorstring Task object or a string
1522
     */
1523
    public static function get_canonical_class_name($taskorstring) {
1524
        if (is_string($taskorstring)) {
1525
            $classname = $taskorstring;
1526
        } else {
1527
            $classname = get_class($taskorstring);
1528
        }
1529
        if (strpos($classname, '\\') !== 0) {
1530
            $classname = '\\' . $classname;
1531
        }
1532
        return $classname;
1533
    }
1534
 
1535
    /**
1536
     * Gets the concurrent lock required to run an adhoc task.
1537
     *
1538
     * @param   adhoc_task $task The task to obtain the lock for
1539
     * @return  \core\lock\lock The lock if one was obtained successfully
1540
     * @throws  \coding_exception
1541
     */
1542
    protected static function get_concurrent_task_lock(adhoc_task $task): ?\core\lock\lock {
1543
        $adhoclock = null;
1544
        $cronlockfactory = \core\lock\lock_config::get_lock_factory(get_class($task));
1545
 
1546
        for ($run = 0; $run < $task->get_concurrency_limit(); $run++) {
1547
            if ($adhoclock = $cronlockfactory->get_lock("concurrent_run_{$run}", 0)) {
1548
                return $adhoclock;
1549
            }
1550
        }
1551
 
1552
        return null;
1553
    }
1554
 
1555
    /**
1556
     * Find the path of PHP CLI binary.
1557
     *
1558
     * @return string|false The PHP CLI executable PATH
1559
     */
1560
    protected static function find_php_cli_path() {
1561
        global $CFG;
1562
 
1563
        if (!empty($CFG->pathtophp) && is_executable(trim($CFG->pathtophp))) {
1564
            return $CFG->pathtophp;
1565
        }
1566
 
1567
        return false;
1568
    }
1569
 
1570
    /**
1571
     * Returns if Moodle have access to PHP CLI binary or not.
1572
     *
1573
     * @return bool
1574
     */
1575
    public static function is_runnable(): bool {
1576
        return self::find_php_cli_path() !== false;
1577
    }
1578
 
1579
    /**
1580
     * Executes a cron from web invocation using PHP CLI.
1581
     *
1582
     * @param scheduled_task $task Task that be executed via CLI.
1583
     * @return bool
1584
     * @throws \moodle_exception
1585
     */
1586
    public static function run_from_cli(scheduled_task $task): bool {
1587
        global $CFG;
1588
 
1589
        if (!self::is_runnable()) {
1590
            $redirecturl = new \moodle_url('/admin/settings.php', ['section' => 'systempaths']);
1591
            throw new \moodle_exception('cannotfindthepathtothecli', 'tool_task', $redirecturl->out());
1592
        } else {
1593
            // Shell-escaped path to the PHP binary.
1594
            $phpbinary = escapeshellarg(self::find_php_cli_path());
1595
 
1596
            // Shell-escaped path CLI script.
1597
            $pathcomponents = [$CFG->dirroot, $CFG->admin, 'cli', 'scheduled_task.php'];
1598
            $scriptpath     = escapeshellarg(implode(DIRECTORY_SEPARATOR, $pathcomponents));
1599
 
1600
            // Shell-escaped task name.
1601
            $classname = get_class($task);
1602
            $taskarg   = escapeshellarg("--execute={$classname}") . " " . escapeshellarg("--force");
1603
 
1604
            // Build the CLI command.
1605
            $command = "{$phpbinary} {$scriptpath} {$taskarg}";
1606
 
1607
            // Execute it.
1608
            self::passthru_via_mtrace($command);
1609
        }
1610
 
1611
        return true;
1612
    }
1613
 
1614
    /**
1615
     * This behaves similar to passthru but filters every line via
1616
     * the mtrace function so it can be post processed.
1617
     *
1618
     * @param string $command to run
1619
     * @return void
1620
     */
1621
    public static function passthru_via_mtrace(string $command) {
1622
        $descriptorspec = [
1623
 
1624
            1 => ['pipe', 'w'], // STDOUT.
1625
            2 => ['pipe', 'w'], // STDERR.
1626
        ];
1627
        flush();
1628
        $process = proc_open($command, $descriptorspec, $pipes, realpath('./'));
1629
        if (is_resource($process)) {
1630
            while ($s = fgets($pipes[1])) {
1631
                mtrace($s, '');
1632
                flush();
1633
            }
1634
        }
1635
 
1636
        fclose($pipes[0]);
1637
        fclose($pipes[1]);
1638
        fclose($pipes[2]);
1639
        proc_close($process);
1640
    }
1641
 
1642
    /**
1643
     * Executes an ad hoc task from web invocation using PHP CLI.
1644
     *
1645
     * @param int   $taskid Task to execute via CLI.
1646
     * @throws \moodle_exception
1647
     */
1648
    public static function run_adhoc_from_cli(int $taskid) {
1649
        // Shell-escaped task name.
1650
        $taskarg = escapeshellarg("--id={$taskid}");
1651
 
1652
        self::run_adhoc_from_cli_base($taskarg);
1653
    }
1654
 
1655
    /**
1656
     * Executes ad hoc tasks from web invocation using PHP CLI.
1657
     *
1658
     * @param bool|null   $failedonly
1659
     * @param string|null $classname  Task class to execute via CLI.
1660
     * @throws \moodle_exception
1661
     */
1662
    public static function run_all_adhoc_from_cli(?bool $failedonly = false, ?string $classname = null) {
1663
        $taskargs = [];
1664
        if ($failedonly) {
1665
            $taskargs[] = '--failed';
1666
        }
1667
        if ($classname) {
1668
            // Shell-escaped task select.
1669
            $taskargs[] = escapeshellarg("--classname={$classname}");
1670
        }
1671
 
1672
        self::run_adhoc_from_cli_base($taskargs ? implode(' ', $taskargs) : '--execute');
1673
    }
1674
 
1675
    /**
1676
     * Executes an ad hoc task from web invocation using PHP CLI.
1677
     *
1678
     * @param string $taskarg Task to execute via CLI.
1679
     * @throws \moodle_exception
1680
     */
1681
    private static function run_adhoc_from_cli_base(string $taskarg): void {
1682
        global $CFG;
1683
 
1684
        if (!self::is_runnable()) {
1685
            $redirecturl = new \moodle_url('/admin/settings.php', ['section' => 'systempaths']);
1686
            throw new \moodle_exception('cannotfindthepathtothecli', 'tool_task', $redirecturl->out());
1687
        }
1688
 
1689
        // Shell-escaped path to the PHP binary.
1690
        $phpbinary = escapeshellarg(self::find_php_cli_path());
1691
 
1692
        // Shell-escaped path CLI script.
1693
        $pathcomponents = [$CFG->dirroot, $CFG->admin, 'cli', 'adhoc_task.php'];
1694
        $scriptpath = escapeshellarg(implode(DIRECTORY_SEPARATOR, $pathcomponents));
1695
 
1696
        // Build the CLI command.
1697
        $command = "{$phpbinary} {$scriptpath} {$taskarg} --force";
1698
 
1699
        // We cannot run it in phpunit.
1700
        if (PHPUNIT_TEST) {
1701
            echo $command;
1702
            return;
1703
        }
1704
 
1705
        // Execute it.
1706
        self::passthru_via_mtrace($command);
1707
    }
1708
 
1709
    /**
1710
     * For a given scheduled task record, this method will check to see if any overrides have
1711
     * been applied in config and return a copy of the record with any overridden values.
1712
     *
1713
     * The format of the config value is:
1714
     *      $CFG->scheduled_tasks = array(
1715
     *          '$classname' => array(
1716
     *              'schedule' => '* * * * *',
1717
     *              'disabled' => 1,
1718
     *          ),
1719
     *      );
1720
     *
1721
     * Where $classname is the value of the task's classname, i.e. '\core\task\grade_cron_task'.
1722
     *
1723
     * @param \stdClass $record scheduled task record
1724
     * @return \stdClass scheduled task with any configured overrides
1725
     */
1726
    protected static function get_record_with_config_overrides(\stdClass $record): \stdClass {
1727
        global $CFG;
1728
 
1729
        $scheduledtaskkey = self::scheduled_task_get_override_key($record->classname);
1730
        $overriddenrecord = $record;
1731
 
1732
        if ($scheduledtaskkey) {
1733
            $overriddenrecord->customised = true;
1734
            $taskconfig = $CFG->scheduled_tasks[$scheduledtaskkey];
1735
 
1736
            if (isset($taskconfig['disabled'])) {
1737
                $overriddenrecord->disabled = $taskconfig['disabled'];
1738
            }
1739
            if (isset($taskconfig['schedule'])) {
1740
                list (
1741
                    $overriddenrecord->minute,
1742
                    $overriddenrecord->hour,
1743
                    $overriddenrecord->day,
1744
                    $overriddenrecord->month,
1745
                    $overriddenrecord->dayofweek
1746
                ) = explode(' ', $taskconfig['schedule']);
1747
            }
1748
        }
1749
 
1750
        return $overriddenrecord;
1751
    }
1752
 
1753
    /**
1754
     * This checks whether or not there is a value set in config
1755
     * for a scheduled task.
1756
     *
1757
     * @param string $classname Scheduled task's classname
1758
     * @return bool true if there is an entry in config
1759
     */
1760
    public static function scheduled_task_has_override(string $classname): bool {
1761
        return self::scheduled_task_get_override_key($classname) !== null;
1762
    }
1763
 
1764
    /**
1765
     * Get the key within the scheduled tasks config object that
1766
     * for a classname.
1767
     *
1768
     * @param string $classname the scheduled task classname to find
1769
     * @return string the key if found, otherwise null
1770
     */
1771
    public static function scheduled_task_get_override_key(string $classname): ?string {
1772
        global $CFG;
1773
 
1774
        if (isset($CFG->scheduled_tasks)) {
1775
            // Firstly, attempt to get a match against the full classname.
1776
            if (isset($CFG->scheduled_tasks[$classname])) {
1777
                return $classname;
1778
            }
1779
 
1780
            // Check to see if there is a wildcard matching the classname.
1781
            foreach (array_keys($CFG->scheduled_tasks) as $key) {
1782
                if (strpos($key, '*') === false) {
1783
                    continue;
1784
                }
1785
 
1786
                $pattern = '/' . str_replace('\\', '\\\\', str_replace('*', '.*', $key)) . '/';
1787
 
1788
                if (preg_match($pattern, $classname)) {
1789
                    return $key;
1790
                }
1791
            }
1792
        }
1793
 
1794
        return null;
1795
    }
1796
 
1797
    /**
1798
     * Clean up failed adhoc tasks.
1799
     */
1800
    public static function clean_failed_adhoc_tasks(): void {
1801
        global $CFG, $DB;
1802
        $difftime = !empty($CFG->task_adhoc_failed_retention) ?
1803
            $CFG->task_adhoc_failed_retention : static::ADHOC_TASK_FAILED_RETENTION;
1804
        $DB->delete_records_select(
1805
            table: 'task_adhoc',
1806
            select: 'attemptsavailable = 0 AND firststartingtime < :time',
1807
            params: ['time' => time() - $difftime],
1808
        );
1809
    }
1810
}