Completed
Push — master ( b7b31c...0ef8ec )
by Matthew
04:34
created

BaseJobManager::getRunArchiveClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Dtc\QueueBundle\Doctrine;
4
5
use Doctrine\Common\Persistence\ObjectManager;
6
use Doctrine\Common\Persistence\ObjectRepository;
7
use Doctrine\ODM\MongoDB\DocumentRepository;
8
use Doctrine\ORM\EntityRepository;
9
use Dtc\QueueBundle\Model\BaseJob;
10
use Dtc\QueueBundle\Model\Job;
11
use Dtc\QueueBundle\Model\PriorityJobManager;
12
use Dtc\QueueBundle\Model\RetryableJob;
13
use Dtc\QueueBundle\Model\Run;
14
use Dtc\QueueBundle\Util\Util;
15
16
abstract class BaseJobManager extends PriorityJobManager
17
{
18
    /** Number of jobs to prune / reset / gather at a time */
19
    const FETCH_COUNT = 100;
20
21
    /** Number of seconds before a job is considered stalled if the runner is no longer active */
22
    const STALLED_SECONDS = 1800;
23
    protected $objectManager;
24
    protected $objectName;
25
    protected $archiveObjectName;
26
    protected $runClass;
27
    protected $runArchiveClass;
28
29
    /**
30
     * @param string $objectName
31
     * @param string $archiveObjectName
32
     * @param string $runClass
33
     * @param string $runArchiveClass
34
     */
35 11
    public function __construct(ObjectManager $objectManager,
36
        $objectName,
37
        $archiveObjectName,
38
        $runClass,
39
        $runArchiveClass)
40
    {
41 11
        $this->objectManager = $objectManager;
42 11
        $this->objectName = $objectName;
43 11
        $this->archiveObjectName = $archiveObjectName;
44 11
        $this->runClass = $runClass;
45 11
        $this->runArchiveClass = $runArchiveClass;
46 11
    }
47
48
    /**
49
     * @return ObjectManager
50
     */
51 38
    public function getObjectManager()
52
    {
53 38
        return $this->objectManager;
54
    }
55
56
    /**
57
     * @return string
58
     */
59 36
    public function getObjectName()
60
    {
61 36
        return $this->objectName;
62
    }
63
64
    /**
65
     * @return string
66
     */
67 24
    public function getArchiveObjectName()
68
    {
69 24
        return $this->archiveObjectName;
70
    }
71
72
    /**
73
     * @return string
74
     */
75 4
    public function getRunClass()
76
    {
77 4
        return $this->runClass;
78
    }
79
80
    /**
81
     * @return string
82
     */
83 5
    public function getRunArchiveClass()
84
    {
85 5
        return $this->runArchiveClass;
86
    }
87
88
    /**
89
     * @return ObjectRepository
90
     */
91 28
    public function getRepository()
92
    {
93 28
        return $this->getObjectManager()->getRepository($this->getObjectName());
94
    }
95
96
    /**
97
     * @param string $objectName
98
     */
99
    abstract protected function countJobsByStatus($objectName, $status, $workerName = null, $method = null);
100
101 2
    public function resetErroneousJobs($workerName = null, $method = null)
102
    {
103 2
        $count = $this->countJobsByStatus($this->getArchiveObjectName(), Job::STATUS_ERROR, $workerName, $method);
104
105 2
        $criterion = ['status' => Job::STATUS_ERROR];
106 2
        $this->addWorkerNameMethod($criterion, $workerName, $method);
107
108 2
        $countProcessed = 0;
109 2
        for ($i = 0; $i < $count; $i += static::FETCH_COUNT) {
110 2
            $countProcessed += $this->resetJobsByCriterion(
111 2
                $criterion, static::FETCH_COUNT, $i);
112
        }
113
114 2
        return $countProcessed;
115
    }
116
117
    /**
118
     * Sets the status to Job::STATUS_EXPIRED for those jobs that are expired.
119
     *
120
     * @param null $workerName
121
     * @param null $method
122
     *
123
     * @return mixed
124
     */
125
    abstract protected function updateExpired($workerName = null, $method = null);
126
127 9
    protected function addWorkerNameMethod(array &$criterion, $workerName = null, $method = null)
128
    {
129 9
        if (null !== $workerName) {
130 4
            $criterion['workerName'] = $workerName;
131
        }
132 9
        if (null !== $method) {
133 4
            $criterion['method'] = $method;
134
        }
135 9
    }
136
137 3
    public function pruneExpiredJobs($workerName = null, $method = null)
138
    {
139 3
        $count = $this->updateExpired($workerName, $method);
140 3
        $criterion = ['status' => Job::STATUS_EXPIRED];
141 3
        $this->addWorkerNameMethod($criterion, $workerName, $method);
142 3
        $objectManager = $this->getObjectManager();
143 3
        $repository = $this->getRepository();
144 3
        $finalCount = 0;
145 3
        for ($i = 0; $i < $count; $i += static::FETCH_COUNT) {
146 3
            $expiredJobs = $repository->findBy($criterion, null, static::FETCH_COUNT, $i);
147 3
            if (!empty($expiredJobs)) {
148 3
                foreach ($expiredJobs as $expiredJob) {
149
                    /* @var Job $expiredJob */
150 3
                    $expiredJob->setStatus(Job::STATUS_EXPIRED);
151 3
                    $objectManager->remove($expiredJob);
152 3
                    ++$finalCount;
153
                }
154
            }
155 3
            $this->flush();
156
        }
157
158 3
        return $finalCount;
159
    }
160
161 7
    protected function flush()
162
    {
163 7
        $this->getObjectManager()->flush();
164 7
    }
165
166 4
    protected function getStalledJobs($workerName = null, $method = null)
167
    {
168 4
        $count = $this->countJobsByStatus($this->getObjectName(), Job::STATUS_RUNNING, $workerName, $method);
169
170 4
        $criterion = ['status' => BaseJob::STATUS_RUNNING];
171 4
        $this->addWorkerNameMethod($criterion, $workerName, $method);
172
173 4
        $runningJobs = $this->findRunningJobs($criterion, $count);
174
175 4
        return $this->extractStalledJobs($runningJobs);
176
    }
177
178 4
    protected function findRunningJobs($criterion, $count)
179
    {
180 4
        $repository = $this->getRepository();
181 4
        $runningJobsById = [];
182
183 4
        for ($i = 0; $i < $count; $i += static::FETCH_COUNT) {
184 4
            $runningJobs = $repository->findBy($criterion, null, static::FETCH_COUNT, $i);
185 4
            if (!empty($runningJobs)) {
186 4
                foreach ($runningJobs as $job) {
187
                    /** @var RetryableJob $job */
188 4
                    if (null !== $runId = $job->getRunId()) {
189 4
                        $runningJobsById[$runId][] = $job;
190
                    }
191
                }
192
            }
193
        }
194
195 4
        return $runningJobsById;
196
    }
197
198
    /**
199
     * @param $runId
200
     * @param array $jobs
201
     * @param array $stalledJobs
202
     */
203 4
    protected function extractStalledLiveRuns($runId, array $jobs, array &$stalledJobs)
204
    {
205 4
        $objectManager = $this->getObjectManager();
206 4
        $runRepository = $objectManager->getRepository($this->runClass);
207 4
        if ($run = $runRepository->find($runId)) {
208 2
            foreach ($jobs as $job) {
209 2
                if ($run->getCurrentJobId() == $job->getId()) {
210 2
                    continue;
211
                }
212 2
                $stalledJobs[] = $job;
213
            }
214
        }
215 4
    }
216
217
    /**
218
     * @param array $runningJobsById
219
     *
220
     * @return array
221
     */
222 4
    protected function extractStalledJobs(array $runningJobsById)
223
    {
224 4
        $objectManager = $this->getObjectManager();
225
        /** @var EntityRepository|DocumentRepository $runArchiveRepository */
226 4
        $runArchiveRepository = $objectManager->getRepository($this->runArchiveClass);
227
228 4
        $stalledJobs = [];
229 4
        foreach (array_keys($runningJobsById) as $runId) {
230 4
            $this->extractStalledLiveRuns($runId, $runningJobsById[$runId], $stalledJobs);
231
            /** @var Run $run */
232 4
            if ($run = $runArchiveRepository->find($runId)) {
233 4
                if ($endTime = $run->getEndedAt()) {
234
                    // Did it end over an hour ago
235 4
                    if ((time() - $endTime->getTimestamp()) > static::STALLED_SECONDS) {
236 4
                        $stalledJobs = array_merge($stalledJobs, $runningJobsById[$runId]);
237
                    }
238
                }
239
            }
240
        }
241
242 4
        return $stalledJobs;
243
    }
244
245 6
    protected function updateMaxStatus(RetryableJob $job, $status, $max = null, $count = 0)
246
    {
247 6
        if (null !== $max && $count >= $max) {
248 4
            $job->setStatus($status);
249
250 4
            return true;
251
        }
252
253 6
        return false;
254
    }
255
256 2
    protected function runStalledLoop($i, $count, array $stalledJobs, &$countProcessed)
257
    {
258 2
        $objectManager = $this->getObjectManager();
259 2
        for ($j = $i, $max = $i + static::FETCH_COUNT; $j < $max && $j < $count; ++$j) {
260
            /* RetryableJob $job */
261 2
            $job = $stalledJobs[$j];
262 2
            $job->setStalledCount($job->getStalledCount() + 1);
263 2
            if ($this->updateMaxStatus($job, RetryableJob::STATUS_MAX_STALLED, $job->getMaxStalled(), $job->getStalledCount()) ||
264 2
                $this->updateMaxStatus($job, RetryableJob::STATUS_MAX_RETRIES, $job->getMaxRetries(), $job->getRetries())) {
265 2
                $objectManager->remove($job);
266 2
                continue;
267
            }
268
269 2
            $job->setRetries($job->getRetries() + 1);
270 2
            $job->setStatus(BaseJob::STATUS_NEW);
271 2
            $job->setLocked(null);
272 2
            $job->setLockedAt(null);
273 2
            $objectManager->persist($job);
274 2
            ++$countProcessed;
275
        }
276 2
    }
277
278 2
    public function resetStalledJobs($workerName = null, $method = null)
279
    {
280 2
        $stalledJobs = $this->getStalledJobs($workerName, $method);
281
282 2
        $countProcessed = 0;
283 2
        for ($i = 0, $count = count($stalledJobs); $i < $count; $i += static::FETCH_COUNT) {
284 2
            $this->runStalledLoop($i, $count, $stalledJobs, $countProcessed);
285 2
            $this->flush();
286
        }
287
288 2
        return $countProcessed;
289
    }
290
291
    /**
292
     * @param string $workerName
293
     * @param string $method
294
     */
295 2
    public function pruneStalledJobs($workerName = null, $method = null)
296
    {
297 2
        $stalledJobs = $this->getStalledJobs($workerName, $method);
298 2
        $objectManager = $this->getObjectManager();
299
300 2
        $countProcessed = 0;
301 2
        for ($i = 0, $count = count($stalledJobs); $i < $count; $i += static::FETCH_COUNT) {
302 2
            for ($j = $i, $max = $i + static::FETCH_COUNT; $j < $max && $j < $count; ++$j) {
303
                /** @var RetryableJob $job */
304 2
                $job = $stalledJobs[$j];
305 2
                $job->setStalledCount($job->getStalledCount() + 1);
306 2
                $job->setStatus(BaseJob::STATUS_ERROR);
307 2
                $job->setMessage('stalled');
308 2
                $this->updateMaxStatus($job, RetryableJob::STATUS_MAX_STALLED, $job->getMaxStalled(), $job->getStalledCount());
309 2
                $objectManager->remove($job);
310 2
                ++$countProcessed;
311
            }
312 2
            $this->flush();
313
        }
314
315 2
        return $countProcessed;
316
    }
317
318 10
    public function deleteJob(\Dtc\QueueBundle\Model\Job $job)
319
    {
320 10
        $objectManager = $this->getObjectManager();
321 10
        $objectManager->remove($job);
322 10
        $objectManager->flush();
323 10
    }
324
325 2
    public function saveHistory(\Dtc\QueueBundle\Model\Job $job)
326
    {
327 2
        $this->deleteJob($job); // Should cause job to be archived
328 2
    }
329
330 33
    protected function prioritySave(\Dtc\QueueBundle\Model\Job $job)
331
    {
332
        // Generate crc hash for the job
333 33
        $hashValues = array($job->getClassName(), $job->getMethod(), $job->getWorkerName(), $job->getArgs());
334 33
        $crcHash = hash('sha256', serialize($hashValues));
335 33
        $job->setCrcHash($crcHash);
336 33
        $objectManager = $this->getObjectManager();
337
338 33
        if (true === $job->getBatch()) {
339 2
            $oldJob = $this->updateNearestBatch($job);
340 2
            if ($oldJob) {
341 2
                return $oldJob;
342
            }
343
        }
344
345
        // Just save a new job
346 33
        $this->resetSaveOk(__FUNCTION__);
347 33
        $objectManager->persist($job);
348 33
        $objectManager->flush();
349
350 33
        return $job;
351
    }
352
353
    abstract protected function updateNearestBatch(Job $job);
354
355
    /**
356
     * @param string $objectName
357
     */
358
    abstract protected function stopIdGenerator($objectName);
359
360
    abstract protected function restoreIdGenerator($objectName);
361
362
    /**
363
     * @param array $criterion
364
     * @param int   $limit
365
     * @param int   $offset
366
     */
367 2
    private function resetJobsByCriterion(
368
        array $criterion,
369
        $limit,
370
        $offset)
371
    {
372 2
        $objectManager = $this->getObjectManager();
373 2
        $this->resetSaveOk(__FUNCTION__);
374 2
        $objectName = $this->getObjectName();
375 2
        $archiveObjectName = $this->getArchiveObjectName();
376 2
        $jobRepository = $objectManager->getRepository($objectName);
377 2
        $jobArchiveRepository = $objectManager->getRepository($archiveObjectName);
378 2
        $className = $jobRepository->getClassName();
379 2
        $metadata = $objectManager->getClassMetadata($className);
380 2
        $this->stopIdGenerator($objectName);
381 2
        $identifierData = $metadata->getIdentifier();
382 2
        $idColumn = isset($identifierData[0]) ? $identifierData[0] : 'id';
383 2
        $results = $jobArchiveRepository->findBy($criterion, [$idColumn => 'ASC'], $limit, $offset);
384 2
        $countProcessed = 0;
385
386 2
        foreach ($results as $jobArchive) {
387 2
            $this->resetJob($jobArchive, $className, $countProcessed);
388
        }
389 2
        $objectManager->flush();
390
391 2
        $this->restoreIdGenerator($objectName);
392
393 2
        return $countProcessed;
394
    }
395
396 17
    protected function resetSaveOk($function)
397
    {
398 17
    }
399
400
    /**
401
     * @param null $workerName
402
     * @param null $methodName
403
     * @param bool $prioritize
404
     */
405
    abstract public function getJobQueryBuilder($workerName = null, $methodName = null, $prioritize = true);
406
407
    /**
408
     * @param RetryableJob $jobArchive
409
     * @param $className
410
     * @param $countProcessed
411
     */
412 2
    protected function resetJob(RetryableJob $jobArchive, $className, &$countProcessed)
413
    {
414 2
        $objectManager = $this->getObjectManager();
415 2
        if ($this->updateMaxStatus($jobArchive, RetryableJob::STATUS_MAX_RETRIES, $jobArchive->getMaxRetries(), $jobArchive->getRetries())) {
416 2
            $objectManager->persist($jobArchive);
417
418 2
            return;
419
        }
420
421
        /** @var RetryableJob $job */
422 2
        $job = new $className();
423
424 2
        Util::copy($jobArchive, $job);
425 2
        $job->setStatus(BaseJob::STATUS_NEW);
426 2
        $job->setLocked(null);
427 2
        $job->setLockedAt(null);
428 2
        $job->setMessage(null);
429 2
        $job->setFinishedAt(null);
430 2
        $job->setStartedAt(null);
431 2
        $job->setElapsed(null);
432 2
        $job->setRetries($job->getRetries() + 1);
433
434 2
        $objectManager->persist($job);
435 2
        $objectManager->remove($jobArchive);
436 2
        ++$countProcessed;
437 2
    }
438
}
439