forked from schmittjoh/JMSJobQueueBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCleanUpCommand.php
More file actions
213 lines (180 loc) · 7.63 KB
/
CleanUpCommand.php
File metadata and controls
213 lines (180 loc) · 7.63 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
<?php
namespace JMS\JobQueueBundle\Command;
use Doctrine\DBAL\Exception;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Exception\ORMException;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\OptimisticLockException;
use JMS\JobQueueBundle\Entity\Job;
use JMS\JobQueueBundle\Entity\Repository\JobManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class CleanUpCommand extends Command
{
public const COMMAND_NAME = 'jms-job-queue:clean-up';
private EntityManagerInterface $entityManager;
private JobManager $jobManager;
public function __construct(EntityManagerInterface $entityManager, JobManager $jobManager)
{
parent::__construct(self::COMMAND_NAME);
$this->entityManager = $entityManager;
$this->jobManager = $jobManager;
}
public static function getDefaultName(): string
{
return self::COMMAND_NAME;
}
protected function configure(): void
{
$this
->setDescription('Cleans up jobs which exceed the maximum retention time.')
->addOption('max-retention', null, InputOption::VALUE_REQUIRED, 'The maximum retention time (value must be parsable by DateTime).', '7 days')
->addOption('max-retention-succeeded', null, InputOption::VALUE_REQUIRED, 'The maximum retention time for succeeded jobs (value must be parsable by DateTime).', '1 hour')
->addOption('per-call', null, InputOption::VALUE_REQUIRED, 'The maximum number of jobs to clean-up per call.', 1000)
;
}
/**
* @throws OptimisticLockException
* @throws \Throwable
* @throws ORMException
* @throws Exception
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->cleanUpExpiredJobs($input);
$this->collectStaleJobs();
return 0;
}
/**
* @throws OptimisticLockException
* @throws ORMException
* @throws NonUniqueResultException
* @throws Exception
*/
private function collectStaleJobs(): void
{
foreach ($this->findStaleJobs() as $job) {
if ($job->isRetried()) {
continue;
}
$this->jobManager->closeJob($job, Job::STATE_INCOMPLETE);
}
}
/**
* @return Job[]
* @throws NonUniqueResultException
*/
private function findStaleJobs(): iterable
{
$excludedIds = array(-1);
do {
$this->entityManager->clear();
/** @var Job $job */
$job = $this->entityManager->createQuery("SELECT j FROM JMSJobQueueBundle:Job j
WHERE j.state = :running AND j.workerName IS NOT NULL AND j.checkedAt < :maxAge
AND j.id NOT IN (:excludedIds)")
->setParameter('running', Job::STATE_RUNNING)
->setParameter('maxAge', new \DateTime('-5 minutes'), 'datetime')
->setParameter('excludedIds', $excludedIds)
->setMaxResults(1)
->getOneOrNullResult();
if ($job !== null) {
$excludedIds[] = $job->getId();
yield $job;
}
} while ($job !== null);
}
/**
* @throws Exception
*/
private function cleanUpExpiredJobs(InputInterface $input): void
{
$con = $this->entityManager->getConnection();
$incomingDepsSql = $con->getDatabasePlatform()->modifyLimitQuery("SELECT 1 FROM jms_job_dependencies WHERE dest_job_id = :id", 1);
$count = 0;
foreach ($this->findExpiredJobs($input) as $job) {
/** @var Job $job */
$count++;
$result = $con->executeQuery($incomingDepsSql, array('id' => $job->getId()));
if ($result->fetchOne() !== false) {
$this->entityManager->wrapInTransaction(function() use ($job) {
$this->resolveDependencies($job);
$this->entityManager->remove($job);
});
continue;
}
$this->entityManager->remove($job);
if ($count >= $input->getOption('per-call')) {
break;
}
}
$this->entityManager->flush();
}
/**
* @param Job $job
* @throws Exception
* @throws ORMException
* @throws OptimisticLockException
*/
private function resolveDependencies(Job $job)
{
// If this job has failed, or has otherwise not succeeded, we need to set the
// incoming dependencies to failed if that has not been done already.
if ( ! $job->isFinished()) {
foreach ($this->jobManager->findIncomingDependencies($job) as $incomingDep) {
if ($incomingDep->isInFinalState()) {
continue;
}
$finalState = Job::STATE_CANCELED;
if ($job->isRunning()) {
$finalState = Job::STATE_FAILED;
}
$this->jobManager->closeJob($incomingDep, $finalState);
}
}
$this->entityManager->getConnection()->executeStatement("DELETE FROM jms_job_dependencies WHERE dest_job_id = :id", array('id' => $job->getId()));
}
private function findExpiredJobs(InputInterface $input): \Generator
{
$succeededJobs = function(array $excludedIds) use ($input) {
return $this->entityManager->createQuery("SELECT j FROM JMSJobQueueBundle:Job j WHERE j.closedAt < :maxRetentionTime AND j.originalJob IS NULL AND j.state = :succeeded AND j.id NOT IN (:excludedIds)")
->setParameter('maxRetentionTime', new \DateTime('-'.$input->getOption('max-retention-succeeded')))
->setParameter('excludedIds', $excludedIds)
->setParameter('succeeded', Job::STATE_FINISHED)
->setMaxResults(100)
->getResult();
};
yield from $this->whileResults( $succeededJobs );
$finishedJobs = function(array $excludedIds) use ($input) {
return $this->entityManager->createQuery("SELECT j FROM JMSJobQueueBundle:Job j WHERE j.closedAt < :maxRetentionTime AND j.originalJob IS NULL AND j.id NOT IN (:excludedIds)")
->setParameter('maxRetentionTime', new \DateTime('-'.$input->getOption('max-retention')))
->setParameter('excludedIds', $excludedIds)
->setMaxResults(100)
->getResult();
};
yield from $this->whileResults( $finishedJobs );
$canceledJobs = function(array $excludedIds) use ($input) {
return $this->entityManager->createQuery("SELECT j FROM JMSJobQueueBundle:Job j WHERE j.state = :canceled AND j.createdAt < :maxRetentionTime AND j.originalJob IS NULL AND j.id NOT IN (:excludedIds)")
->setParameter('maxRetentionTime', new \DateTime('-'.$input->getOption('max-retention')))
->setParameter('canceled', Job::STATE_CANCELED)
->setParameter('excludedIds', $excludedIds)
->setMaxResults(100)
->getResult();
};
yield from $this->whileResults( $canceledJobs );
}
private function whileResults(callable $resultProducer): \Generator
{
$excludedIds = array(-1);
do {
/** @var Job[] $jobs */
$jobs = $resultProducer($excludedIds);
foreach ($jobs as $job) {
$excludedIds[] = $job->getId();
yield $job;
}
} while ( ! empty($jobs));
}
}