-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathQueuedJobsController.php
More file actions
494 lines (404 loc) · 13.1 KB
/
Copy pathQueuedJobsController.php
File metadata and controls
494 lines (404 loc) · 13.1 KB
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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
<?php
declare(strict_types=1);
namespace Queue\Controller\Admin;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\Http\Exception\NotFoundException;
use Cake\I18n\DateTime;
use Cake\View\JsonView;
use InvalidArgumentException;
use Queue\Queue\TaskFinder;
use RuntimeException;
/**
* @property \Queue\Model\Table\QueuedJobsTable $QueuedJobs
* @property \Search\Controller\Component\SearchComponent $Search
* @method \Cake\Datasource\ResultSetInterface<\Queue\Model\Entity\QueuedJob> paginate($object = null, array $settings = [])
*/
class QueuedJobsController extends QueueAppController {
/**
* @var string|null
*/
protected ?string $defaultTable = 'Queue.QueuedJobs';
/**
* @var array<string, mixed>
*/
protected array $paginate = [
'order' => [
'created' => 'DESC',
],
];
/**
* @return void
*/
public function initialize(): void {
parent::initialize();
// Set connection for multi-connection support
if ($this->activeConnection !== 'default') {
$this->QueuedJobs->setConnection($this->getActiveConnectionObject());
}
$this->enableSearch();
}
/**
* @return void
*/
protected function enableSearch(): void {
if (Configure::read('Queue.isSearchEnabled') === false || !Plugin::isLoaded('Search')) {
return;
}
if ($this->components()->has('Search')) {
return;
}
$this->loadComponent('Search.Search', [
'actions' => ['index'],
]);
}
/**
* Index method
*
* @return \Cake\Http\Response|null|void
*/
public function index() {
if (Configure::read('Queue.isSearchEnabled') !== false && Plugin::isLoaded('Search')) {
$query = $this->QueuedJobs->find('search', search: $this->request->getQuery());
} else {
$query = $this->QueuedJobs->find();
}
$queuedJobs = $this->paginate($query);
$this->set(compact('queuedJobs'));
if (Configure::read('Queue.isSearchEnabled') !== false && Plugin::isLoaded('Search')) {
$jobTypes = $this->QueuedJobs->find()->where()->find(
'list',
keyField: 'job_task',
valueField: 'job_task',
)->distinct('job_task')->toArray();
$this->set(compact('jobTypes'));
}
}
/**
* Stats method
*
* Uses query parameter `job_type` to filter by specific job type.
* Query parameter is used instead of route parameter to support job types
* containing slashes (e.g., Vendor/Plugin.Task).
*
* @throws \Cake\Http\Exception\NotFoundException
*
* @return void
*/
public function stats(): void {
if (!Configure::read('Queue.isStatisticEnabled')) {
throw new NotFoundException('Not enabled');
}
// Use query parameter to avoid routing issues with job types containing slashes (e.g., Vendor/Plugin.Task)
$jobType = $this->request->getQuery('job_type');
$stats = $this->QueuedJobs->getFullStats($jobType);
$jobTypes = $this->QueuedJobs->find()->where()->find(
'list',
keyField: 'job_task',
valueField: 'job_task',
)->distinct('job_task')->toArray();
$this->set(compact('stats', 'jobTypes', 'jobType'));
}
/**
* Heatmap method
*
* Shows a heatmap visualization of job activity by day of week and hour.
*
* @throws \Cake\Http\Exception\NotFoundException
*
* @return void
*/
public function heatmap(): void {
if (!Configure::read('Queue.isStatisticEnabled')) {
throw new NotFoundException('Not enabled');
}
$jobType = $this->request->getQuery('job_type');
$metric = $this->request->getQuery('metric', 'created');
$days = (int)$this->request->getQuery('days', 30);
// Validate metric
if (!in_array($metric, ['created', 'completed'], true)) {
$metric = 'created';
}
// Validate days range
if ($days < 7) {
$days = 7;
} elseif ($days > 365) {
$days = 365;
}
$heatmapData = $this->QueuedJobs->getHeatmapData($metric, $days, $jobType);
$jobTypes = $this->QueuedJobs->find()->where()->find(
'list',
keyField: 'job_task',
valueField: 'job_task',
)->distinct('job_task')->toArray();
$this->set(compact('heatmapData', 'jobTypes', 'jobType', 'metric', 'days'));
}
/**
* View method
*
* @param int|null $id Queued Job id.
*
* @return \Cake\Http\Response|null|void
*/
public function view(?int $id = null) {
$queuedJob = $this->QueuedJobs->get(
(int)$id,
contain: ['WorkerProcesses'],
);
if ($this->request->getParam('_ext') && $this->request->getParam('_ext') === 'json' && $this->request->getQuery('download')) {
$this->response = $this->response->withDownload('queued-job-' . $id . '.json');
}
$this->set(compact('queuedJob'));
$this->viewBuilder()->setOption('serialize', ['queuedJob']);
}
/**
* @return array<string>
*/
public function viewClasses(): array {
return [JsonView::class];
}
/**
* @throws \RuntimeException
*
* @return \Cake\Http\Response|null|void
*/
public function import() {
if ($this->request->is(['post'])) {
/** @var \Laminas\Diactoros\UploadedFile|null $file */
$file = $this->request->getData('file');
if ($file && $file->getError() == UPLOAD_ERR_OK && $file->getSize() > 0) {
$clientMediaType = $file->getClientMediaType();
if ($clientMediaType !== 'application/json') {
throw new RuntimeException('Only JSON files are allowed');
}
$content = file_get_contents($file->getStream()->getMetadata('uri'));
if ($content === false) {
throw new RuntimeException('Cannot parse file');
}
$json = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Invalid JSON: ' . json_last_error_msg());
}
if (!$json || empty($json['queuedJob'])) {
throw new RuntimeException('Invalid JSON content: missing queuedJob data');
}
if (!is_array($json['queuedJob'])) {
throw new RuntimeException('Invalid JSON structure: queuedJob must be an array');
}
$data = $json['queuedJob'];
unset($data['id']);
$data['created'] = new DateTime($data['created']);
if ($this->request->getData('reset')) {
$data['fetched'] = null;
$data['completed'] = null;
$data['progress'] = null;
$data['attempts'] = 0;
$data['failure_message'] = null;
$data['workerkey'] = null;
$data['status'] = null;
}
if ($data['notbefore']) {
$data['notbefore'] = new DateTime($data['notbefore']);
}
if ($data['fetched']) {
$data['fetched'] = new DateTime($data['fetched']);
}
if ($data['completed']) {
$data['completed'] = new DateTime($data['completed']);
}
$queuedJob = $this->QueuedJobs->newEntity($data);
if ($queuedJob->getErrors()) {
$this->Flash->error('Validation failed: ' . print_r($queuedJob->getErrors(), true));
return $this->redirect($this->referer(['action' => 'index']));
}
$this->QueuedJobs->saveOrFail($queuedJob);
$this->Flash->success('Imported');
return $this->redirect(['action' => 'view', $queuedJob->id]);
}
$this->Flash->error(__d('queue', 'Please, try again.'));
}
}
/**
* Edit method
*
* @param int|null $id Queued Job id.
*
* @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
*/
public function edit(?int $id = null) {
$queuedJob = $this->QueuedJobs->get($id);
if ($queuedJob->completed) {
$this->Flash->error(__d('queue', 'The queued job is already completed.'));
return $this->redirect(['action' => 'view', $id]);
}
if ($this->request->is(['patch', 'post', 'put'])) {
$queuedJob = $this->QueuedJobs->patchEntity($queuedJob, $this->request->getData());
if ($this->QueuedJobs->save($queuedJob)) {
$this->Flash->success(__d('queue', 'The queued job has been saved.'));
return $this->redirect(['action' => 'view', $id]);
}
$this->Flash->error(__d('queue', 'The queued job could not be saved. Please try again.'));
}
$this->set(compact('queuedJob'));
}
/**
* @param int|null $id Queued Job id.
*
* @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
*/
public function data(?int $id = null) {
$this->QueuedJobs->addBehavior('Queue.Jsonable', ['input' => 'json', 'fields' => ['data'], 'map' => ['data_string']]);
$queuedJob = $this->QueuedJobs->get($id);
if ($queuedJob->completed) {
$this->Flash->error(__d('queue', 'The queued job is already completed.'));
return $this->redirect(['action' => 'view', $id]);
}
if ($this->request->is(['patch', 'post', 'put'])) {
try {
$queuedJob = $this->QueuedJobs->patchEntity($queuedJob, $this->request->getData());
if ($this->QueuedJobs->save($queuedJob)) {
$this->Flash->success(__d('queue', 'The queued job has been saved.'));
return $this->redirect(['action' => 'view', $id]);
}
$this->Flash->error(__d('queue', 'The queued job could not be saved. Please try again.'));
} catch (InvalidArgumentException $e) {
$this->Flash->error($e->getMessage());
// Preserve the user's invalid input so they can fix it
$queuedJob->data_string = $this->request->getData('data_string');
}
}
$this->set(compact('queuedJob'));
}
/**
* Delete method
*
* @param int|null $id Queued Job id.
*
* @return \Cake\Http\Response|null|void Redirects to index.
*/
public function delete(?int $id = null) {
$this->request->allowMethod(['post', 'delete']);
$queuedJob = $this->QueuedJobs->get($id);
if ($this->QueuedJobs->delete($queuedJob)) {
$this->Flash->success(__d('queue', 'The queued job has been deleted.'));
} else {
$this->Flash->error(__d('queue', 'The queued job could not be deleted. Please try again.'));
}
return $this->redirect(['action' => 'index']);
}
/**
* @param int|null $id Queued Job id.
*
* @return \Cake\Http\Response|null|void Redirects to index.
*/
public function clone(?int $id = null) {
$this->request->allowMethod(['post', 'put']);
$queuedJob = $this->QueuedJobs->get($id);
if ($this->QueuedJobs->clone($queuedJob)) {
$this->Flash->success(__d('queue', 'The queued job has been cloned and will now run.'));
} else {
$this->Flash->error(__d('queue', 'The queued job could not be cloned. Please try again.'));
}
return $this->redirect(['controller' => 'Queue', 'action' => 'index']);
}
/**
* @throws \Cake\Http\Exception\NotFoundException
*
* @return \Cake\Http\Response|null|void
*/
public function execute() {
if (!Configure::read('debug')) {
throw new NotFoundException('Only for local development. Security implications if open on deployment.');
}
if ($this->request->is(['patch', 'post', 'put'])) {
/** @var array<string, mixed> $data */
$data = (array)$this->request->getData();
if (empty($data['command'])) {
$this->Flash->error('Command is required');
return null;
}
$amount = $data['amount'];
unset($data['amount']);
$data['escape'] = (bool)$data['escape'];
$data['log'] = (bool)$data['log'];
$data['redirect'] = !$data['log'];
$data['accepted'] = $data['exit_code'] === '' ? [] : (array)(int)$data['exit_code'];
unset($data['exit_code']);
for ($i = 0; $i < $amount; $i++) {
$this->QueuedJobs->createJob('Execute', $data);
}
$this->Flash->success(__d('queue', 'The requested job has been queued ' . $amount . 'x.'));
return $this->redirect(['action' => 'execute']);
}
}
/**
* @return \Cake\Http\Response|null|void
*/
public function test() {
$taskFinder = new TaskFinder();
$allTasks = $taskFinder->all();
$tasks = [];
foreach (array_keys($allTasks) as $task) {
if (!str_starts_with($task, 'Queue.')) {
continue;
}
if (!str_ends_with($task, 'Example')) {
continue;
}
$tasks[$task] = $task;
}
$queuedJob = $this->QueuedJobs->newEmptyEntity();
if ($this->request->is(['post', 'patch', 'put'])) {
$queuedJob = $this->QueuedJobs->patchEntity($queuedJob, $this->request->getData());
$jobType = $queuedJob->job_task;
$notBefore = $queuedJob->notbefore;
if ($jobType && isset($tasks[$jobType]) && $notBefore) {
$config = [
'notBefore' => $notBefore,
];
$this->QueuedJobs->createJob($jobType, null, $config);
$this->Flash->success(__d('queue', 'The requested job has been queued.'));
return $this->redirect(['action' => 'test']);
}
$this->Flash->error(__d('queue', 'The job could not be queued. Please try again.'));
}
$this->set(compact('tasks', 'queuedJob'));
}
/**
* @return \Cake\Http\Response|null|void
*/
public function migrate() {
$taskFinder = new TaskFinder();
$allTasks = $taskFinder->all();
$existingTasks = $this->QueuedJobs->find()
->select(['job_task'])
->distinct('job_task')
->disableHydration()
->find('list', keyField: 'job_task', valueField: 'job_task')
->toArray();
$tasks = [];
foreach (array_keys($allTasks) as $task) {
if (!str_starts_with($task, 'Queue.')) {
continue;
}
[$plugin, $name] = explode('.', $task, 2);
if (!isset($existingTasks[$name])) {
continue;
}
$tasks[$name] = $task;
}
if ($this->request->is('post')) {
$tasksToMigrate = $this->request->getData('tasks');
$count = 0;
foreach ($tasksToMigrate as $taskToMigrate => $status) {
if (!$status) {
continue;
}
$count += $this->QueuedJobs->updateAll(['job_task' => 'Queue.' . $taskToMigrate], ['job_task' => $taskToMigrate]);
}
$this->Flash->success('Done: ' . $count);
return $this->redirect(['action' => 'migrate']);
}
$this->set(compact('tasks'));
}
}