This repository has been archived by the owner on Jul 6, 2023. It is now read-only.
/
Scheduler.php
361 lines (313 loc) · 9.01 KB
/
Scheduler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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
227
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
<?php
/**
* @package Joomla.Administrator
* @subpackage com_scheduler
*
* @copyright (C) 2021 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\Component\Scheduler\Administrator\Scheduler;
// Restrict direct access
\defined('_JEXEC') or die;
use Joomla\CMS\Application\CMSApplication;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Log\Log;
use Joomla\Component\Scheduler\Administrator\Extension\SchedulerComponent;
use Joomla\Component\Scheduler\Administrator\Model\TaskModel;
use Joomla\Component\Scheduler\Administrator\Model\TasksModel;
use Joomla\Component\Scheduler\Administrator\Task\Status;
use Joomla\Component\Scheduler\Administrator\Task\Task;
use Symfony\Component\OptionsResolver\Exception\AccessException;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* The Scheduler class provides the core functionality of ComScheduler.
* Currently, this includes fetching scheduled tasks from the database
* and execution of any or the next due task.
* It is planned that this class is extended with C[R]UD methods for
* scheduled tasks.
*
* @since 4.1.0
* @todo A global instance?
*/
class Scheduler
{
private const LOG_TEXT = [
Status::OK => 'COM_SCHEDULER_SCHEDULER_TASK_COMPLETE',
Status::NO_LOCK => 'COM_SCHEDULER_SCHEDULER_TASK_LOCKED',
Status::NO_RUN => 'COM_SCHEDULER_SCHEDULER_TASK_UNLOCKED',
Status::NO_ROUTINE => 'COM_SCHEDULER_SCHEDULER_TASK_ROUTINE_NA',
];
/**
* Filters for the task queue. Can be used with fetchTaskRecords().
*
* @since 4.1.0
* @todo remove?
*/
public const TASK_QUEUE_FILTERS = [
'due' => 1,
'locked' => -1,
];
/**
* List config for the task queue. Can be used with fetchTaskRecords().
*
* @since 4.1.0
* @todo remove?
*/
public const TASK_QUEUE_LIST_CONFIG = [
'multi_ordering' => ['a.priority DESC ', 'a.next_execution ASC'],
];
/**
* Run a scheduled task.
* Runs a single due task from the task queue by default if $id and $title are not passed.
*
* @param array $options Array with options to configure the method's behavior. Supports:
* 1. `id`: (Optional) ID of the task to run.
* 2. `allowDisabled`: Allow running disabled tasks.
* 3. `allowConcurrent`: Allow concurrent execution, i.e., running the task when another
* task may be running.
*
* @return ?Task The task executed or null if not exists
*
* @since 4.1.0
* @throws \RuntimeException
*/
public function runTask(array $options): ?Task
{
$resolver = new OptionsResolver;
try
{
$this->configureTaskRunnerOptions($resolver);
}
catch (\Exception $e)
{
}
try
{
$options = $resolver->resolve($options);
}
catch (\Exception $e)
{
if ($e instanceof UndefinedOptionsException || $e instanceof InvalidOptionsException)
{
throw $e;
}
}
/** @var CMSApplication $app */
$app = Factory::getApplication();
// ? Sure about inferring scheduling bypass?
$task = $this->getTask(
[
'id' => $options['id'],
'allowDisabled' => $options['allowDisabled'],
'bypassScheduling' => $options['id'] === 0,
'allowConcurrent' => $options['allowConcurrent'],
'includeCliExclusive' => ($app->isClient('cli')),
]
);
// ? Should this be logged? (probably, if an ID is passed?)
if (empty($task))
{
return null;
}
$app->getLanguage()->load('com_scheduler', JPATH_ADMINISTRATOR);
$options['text_entry_format'] = '{DATE} {TIME} {PRIORITY} {MESSAGE}';
$options['text_file'] = 'joomla_scheduler.php';
Log::addLogger($options, Log::ALL, $task->logCategory);
$taskId = $task->get('id');
$taskTitle = $task->get('title');
$task->log(Text::sprintf('COM_SCHEDULER_SCHEDULER_TASK_START', $taskId, $taskTitle), 'info');
// Let's try to avoid time-outs
if (\function_exists('set_time_limit'))
{
set_time_limit(0);
}
try
{
$task->run();
}
catch (\Exception $e)
{
// We suppress the exception here, it's still accessible with `$task->getContent()['exception']`.
}
$executionSnapshot = $task->getContent();
$exitCode = $executionSnapshot['status'] ?? Status::NO_EXIT;
$netDuration = $executionSnapshot['netDuration'] ?? 0;
$duration = $executionSnapshot['duration'] ?? 0;
if (\array_key_exists($exitCode, self::LOG_TEXT))
{
$level = $exitCode === Status::OK ? 'info' : 'warning';
$task->log(Text::sprintf(self::LOG_TEXT[$exitCode], $taskId, $duration, $netDuration), $level);
return $task;
}
$task->log(
Text::sprintf('COM_SCHEDULER_SCHEDULER_TASK_UNKNOWN_EXIT', $taskId, $duration, $netDuration, $exitCode),
'warning'
);
return $task;
}
/**
* Set up an {@see OptionsResolver} to resolve options compatible with {@see runTask}.
*
* @param OptionsResolver $resolver The {@see OptionsResolver} instance to set up.
*
* @return void
*
* @since 4.1.0
* @throws AccessException
*/
protected function configureTaskRunnerOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(
[
'id' => 0,
'allowDisabled' => false,
'allowConcurrent' => false,
]
)
->setAllowedTypes('id', 'int')
->setAllowedTypes('allowDisabled', 'bool')
->setAllowedTypes('allowConcurrent', 'bool');
}
/**
* Get the next task which is due to run, limit to a specific task when ID is given
*
* @param array $options Options for the getter, see {@see TaskModel::getTask()}.
* ! should probably also support a non-locking getter.
*
* @return Task $task The task to execute
*
* @since 4.1.0
* @throws \RuntimeException
*/
public function getTask(array $options = []): ?Task
{
$resolver = new OptionsResolver;
try
{
TaskModel::configureTaskGetterOptions($resolver);
}
catch (\Exception $e)
{
}
try
{
$options = $resolver->resolve($options);
}
catch (\Exception $e)
{
if ($e instanceof UndefinedOptionsException || $e instanceof InvalidOptionsException)
{
throw $e;
}
}
try
{
/** @var SchedulerComponent $component */
$component = Factory::getApplication()->bootComponent('com_scheduler');
/** @var TaskModel $model */
$model = $component->getMVCFactory()->createModel('Task', 'Administrator', ['ignore_request' => true]);
}
catch (\Exception $e)
{
}
if (!isset($model))
{
throw new \RuntimeException('JLIB_APPLICATION_ERROR_MODEL_CREATE');
}
$task = $model->getTask($options);
if (empty($task))
{
return null;
}
return new Task($task);
}
/**
* Fetches a single scheduled task in a Task instance.
* If no id or title is specified, a due task is returned.
*
* @param int $id The task ID.
* @param bool $allowDisabled Allow disabled/trashed tasks?
*
* @return ?object A matching task record, if it exists
*
* @since 4.1.0
* @throws \RuntimeException
*/
public function fetchTaskRecord(int $id = 0, bool $allowDisabled = false): ?object
{
$filters = [];
$listConfig = ['limit' => 1];
if ($id > 0)
{
$filters['id'] = $id;
}
else
{
// Filters and list config for scheduled task queue
$filters['due'] = 1;
$filters['locked'] = -1;
$listConfig['multi_ordering'] = [
'a.priority DESC',
'a.next_execution ASC',
];
}
if ($allowDisabled)
{
$filters['state'] = '';
}
return $this->fetchTaskRecords($filters, $listConfig)[0] ?? null;
}
/**
* @param array $filters The filters to set to the model
* @param array $listConfig The list config (ordering, etc.) to set to the model
*
* @return array
*
* @since 4.1.0
* @throws \RunTimeException
*/
public function fetchTaskRecords(array $filters, array $listConfig): array
{
$model = null;
try
{
/** @var SchedulerComponent $component */
$component = Factory::getApplication()->bootComponent('com_scheduler');
/** @var TasksModel $model */
$model = $component->getMVCFactory()
->createModel('Tasks', 'Administrator', ['ignore_request' => true]);
}
catch (\Exception $e)
{
}
if (!$model)
{
throw new \RuntimeException('JLIB_APPLICATION_ERROR_MODEL_CREATE');
}
$model->setState('list.select', '*');
// Default to only enabled tasks
if (!isset($filters['state']))
{
$model->setState('filter.state', 1);
}
// Default to including orphaned tasks
$model->setState('filter.orphaned', 0);
// Default to ordering by ID
$model->setState('list.ordering', 'a.id');
$model->setState('list.direction', 'ASC');
// List options
foreach ($listConfig as $key => $value)
{
$model->setState('list.' . $key, $value);
}
// Filter options
foreach ($filters as $type => $filter)
{
$model->setState('filter.' . $type, $filter);
}
return $model->getItems() ?: [];
}
}