Completed
Push — master ( 4109b7...859c70 )
by Matthew
08:07 queued 02:26
created

BaseJobManager::runStalledLoop()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6.0045

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 19
cts 20
cp 0.95
rs 8.439
c 0
b 0
f 0
cc 6
eloc 18
nc 4
nop 4
crap 6.0045
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 9
    public function __construct(ObjectManager $objectManager,
36
        $objectName,
37
        $archiveObjectName,
38
        $runClass,
39
        $runArchiveClass)
40
    {
41 9
        $this->objectManager = $objectManager;
42 9
        $this->objectName = $objectName;
43 9
        $this->archiveObjectName = $archiveObjectName;
44 9
        $this->runClass = $runClass;
45 9
        $this->runArchiveClass = $runArchiveClass;
46 9
    }
47
48
    /**
49
     * @return ObjectManager
50
     */
51 26
    public function getObjectManager()
52
    {
53 26
        return $this->objectManager;
54
    }
55
56
    /**
57
     * @return string
58
     */
59 25
    public function getObjectName()
60
    {
61 25
        return $this->objectName;
62
    }
63
64
    /**
65
     * @return string
66
     */
67 19
    public function getArchiveObjectName()
68
    {
69 19
        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 4
    public function getRunArchiveClass()
84
    {
85 4
        return $this->runArchiveClass;
86
    }
87
88
    /**
89
     * @return ObjectRepository
90
     */
91 19
    public function getRepository()
92
    {
93 19
        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 2
        }
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 8
    protected function addWorkerNameMethod(array &$criterion, $workerName = null, $method = null)
128
    {
129 8
        if (null !== $workerName) {
130 3
            $criterion['workerName'] = $workerName;
131 3
        }
132 8
        if (null !== $method) {
133 3
            $criterion['method'] = $method;
134 3
        }
135 8
    }
136
137 2
    public function pruneExpiredJobs($workerName = null, $method = null)
138
    {
139 2
        $count = $this->updateExpired($workerName, $method);
140 2
        $criterion = ['status' => Job::STATUS_EXPIRED];
141 2
        $this->addWorkerNameMethod($criterion, $workerName, $method);
142 2
        $objectManager = $this->getObjectManager();
143 2
        $repository = $this->getRepository();
144 2
        $finalCount = 0;
145 2
        for ($i = 0; $i < $count; $i += static::FETCH_COUNT) {
146 2
            $expiredJobs = $repository->findBy($criterion, null, static::FETCH_COUNT, $i);
147 2
            if (!empty($expiredJobs)) {
148 2
                foreach ($expiredJobs as $expiredJob) {
149
                    /* @var Job $expiredJob */
150 2
                    $expiredJob->setStatus(Job::STATUS_EXPIRED);
151 2
                    $objectManager->remove($expiredJob);
152 2
                    ++$finalCount;
153 2
                }
154 2
            }
155 2
            $this->flush();
156 2
        }
157
158 2
        return $finalCount;
159
    }
160
161 6
    protected function flush()
162
    {
163 6
        $this->getObjectManager()->flush();
164 6
    }
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 4
                    }
191 4
                }
192 4
            }
193 4
        }
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 2
            }
214 2
        }
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 4
                    }
238 4
                }
239 4
            }
240 4
        }
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
    abstract protected function getJobCurrentStatus(Job $job);
257
258 2
    protected function runStalledLoop($i, $count, array $stalledJobs, &$countProcessed)
259
    {
260 2
        $objectManager = $this->getObjectManager();
261 2
        for ($j = $i, $max = $i + static::FETCH_COUNT; $j < $max && $j < $count; ++$j) {
262
            /* RetryableJob $job */
263 2
            $job = $stalledJobs[$j];
264 2
            $status = $this->getJobCurrentStatus($job);
265
266
            // Query the data store to make sure the job is still marked running
267 2
            if (BaseJob::STATUS_RUNNING !== $status) {
268
                continue;
269
            }
270
271 2
            $job->setStalledCount($job->getStalledCount() + 1);
272 2
            if ($this->updateMaxStatus($job, RetryableJob::STATUS_MAX_STALLED, $job->getMaxStalled(), $job->getStalledCount()) ||
273 2
                $this->updateMaxStatus($job, RetryableJob::STATUS_MAX_RETRIES, $job->getMaxRetries(), $job->getRetries())) {
274 2
                $objectManager->remove($job);
275 2
                continue;
276
            }
277
278 2
            $job->setRetries($job->getRetries() + 1);
279 2
            $job->setStatus(BaseJob::STATUS_NEW);
280 2
            $job->setLocked(null);
281 2
            $job->setLockedAt(null);
282 2
            $objectManager->persist($job);
283 2
            ++$countProcessed;
284 2
        }
285 2
    }
286
287 2
    public function resetStalledJobs($workerName = null, $method = null)
288
    {
289 2
        $stalledJobs = $this->getStalledJobs($workerName, $method);
290
291 2
        $countProcessed = 0;
292 2
        for ($i = 0, $count = count($stalledJobs); $i < $count; $i += static::FETCH_COUNT) {
293 2
            $this->runStalledLoop($i, $count, $stalledJobs, $countProcessed);
294 2
            $this->flush();
295 2
        }
296
297 2
        return $countProcessed;
298
    }
299
300
    /**
301
     * @param string $workerName
302
     * @param string $method
303
     */
304 2
    public function pruneStalledJobs($workerName = null, $method = null)
305
    {
306 2
        $stalledJobs = $this->getStalledJobs($workerName, $method);
307 2
        $objectManager = $this->getObjectManager();
308
309 2
        $countProcessed = 0;
310 2
        for ($i = 0, $count = count($stalledJobs); $i < $count; $i += static::FETCH_COUNT) {
311 2
            for ($j = $i, $max = $i + static::FETCH_COUNT; $j < $max && $j < $count; ++$j) {
312
                /** @var RetryableJob $job */
313 2
                $job = $stalledJobs[$j];
314 2
                $job->setStalledCount($job->getStalledCount() + 1);
315 2
                $job->setStatus(BaseJob::STATUS_ERROR);
316 2
                $job->setMessage('stalled');
317 2
                $this->updateMaxStatus($job, RetryableJob::STATUS_MAX_STALLED, $job->getMaxStalled(), $job->getStalledCount());
318 2
                $objectManager->remove($job);
319 2
                ++$countProcessed;
320 2
            }
321 2
            $this->flush();
322 2
        }
323
324 2
        return $countProcessed;
325
    }
326
327 8
    public function deleteJob(\Dtc\QueueBundle\Model\Job $job)
328
    {
329 8
        $objectManager = $this->getObjectManager();
330 8
        $objectManager->remove($job);
331 8
        $objectManager->flush();
332 8
    }
333
334 1
    public function saveHistory(\Dtc\QueueBundle\Model\Job $job)
335
    {
336 1
        $this->deleteJob($job); // Should cause job to be archived
337 1
    }
338
339 22
    protected function prioritySave(\Dtc\QueueBundle\Model\Job $job)
340
    {
341
        // Generate crc hash for the job
342 22
        $hashValues = array($job->getClassName(), $job->getMethod(), $job->getWorkerName(), $job->getArgs());
343 22
        $crcHash = hash('sha256', serialize($hashValues));
344 22
        $job->setCrcHash($crcHash);
345 22
        $objectManager = $this->getObjectManager();
346
347 22
        if (true === $job->getBatch()) {
348 2
            $oldJob = $this->updateNearestBatch($job);
349 2
            if ($oldJob) {
350 1
                return $oldJob;
351
            }
352 1
        }
353
354
        // Just save a new job
355 22
        $this->resetSaveOk(__FUNCTION__);
356 22
        $objectManager->persist($job);
357 22
        $objectManager->flush();
358
359 22
        return $job;
360
    }
361
362
    abstract protected function updateNearestBatch(Job $job);
363
364
    /**
365
     * @param string $objectName
366
     */
367
    abstract protected function stopIdGenerator($objectName);
368
369
    abstract protected function restoreIdGenerator($objectName);
370
371
    /**
372
     * @param array $criterion
373
     * @param int   $limit
374
     * @param int   $offset
375
     */
376 2
    private function resetJobsByCriterion(
377
        array $criterion,
378
        $limit,
379
        $offset)
380
    {
381 2
        $objectManager = $this->getObjectManager();
382 2
        $this->resetSaveOk(__FUNCTION__);
383 2
        $objectName = $this->getObjectName();
384 2
        $archiveObjectName = $this->getArchiveObjectName();
385 2
        $jobRepository = $objectManager->getRepository($objectName);
386 2
        $jobArchiveRepository = $objectManager->getRepository($archiveObjectName);
387 2
        $className = $jobRepository->getClassName();
388 2
        $metadata = $objectManager->getClassMetadata($className);
389 2
        $this->stopIdGenerator($objectName);
390 2
        $identifierData = $metadata->getIdentifier();
391 2
        $idColumn = isset($identifierData[0]) ? $identifierData[0] : 'id';
392 2
        $results = $jobArchiveRepository->findBy($criterion, [$idColumn => 'ASC'], $limit, $offset);
393 2
        $countProcessed = 0;
394
395 2
        foreach ($results as $jobArchive) {
396 2
            $this->resetJob($jobArchive, $className, $countProcessed);
397 2
        }
398 2
        $objectManager->flush();
399
400 2
        $this->restoreIdGenerator($objectName);
401
402 2
        return $countProcessed;
403
    }
404
405 16
    protected function resetSaveOk($function)
406
    {
407 16
    }
408
409
    /**
410
     * @param RetryableJob $jobArchive
411
     * @param $className
412
     * @param $countProcessed
413
     */
414 2
    protected function resetJob(RetryableJob $jobArchive, $className, &$countProcessed)
415
    {
416 2
        $objectManager = $this->getObjectManager();
417 2
        if ($this->updateMaxStatus($jobArchive, RetryableJob::STATUS_MAX_RETRIES, $jobArchive->getMaxRetries(), $jobArchive->getRetries())) {
418 2
            $objectManager->persist($jobArchive);
419
420 2
            return;
421
        }
422
423
        /** @var RetryableJob $job */
424 2
        $job = new $className();
425
426 2
        Util::copy($jobArchive, $job);
427 2
        $job->setStatus(BaseJob::STATUS_NEW);
428 2
        $job->setLocked(null);
429 2
        $job->setLockedAt(null);
430 2
        $job->setMessage(null);
431 2
        $job->setFinishedAt(null);
432 2
        $job->setStartedAt(null);
433 2
        $job->setElapsed(null);
434 2
        $job->setRetries($job->getRetries() + 1);
435
436 2
        $objectManager->persist($job);
437 2
        $objectManager->remove($jobArchive);
438 2
        ++$countProcessed;
439 2
    }
440
}
441