Completed
Pull Request — master (#127)
by Matthew
17:18
created

QueueController::runs()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 0
dl 0
loc 11
ccs 7
cts 7
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Dtc\QueueBundle\Controller;
4
5
use Dtc\QueueBundle\Doctrine\DoctrineJobManager;
6
use Dtc\QueueBundle\Exception\UnsupportedException;
7
use Dtc\QueueBundle\Model\BaseJob;
8
use Dtc\QueueBundle\Model\Worker;
9
use Symfony\Component\DependencyInjection\ContainerInterface;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\StreamedResponse;
12
13
class QueueController
14
{
15
    use ControllerTrait;
16
17
    private $container;
18
19
    public function __construct(ContainerInterface $container) {
20
        $this->container = $container;
21
    }
22
23
    /**
24
     * Summary stats.
25
     */
26
    public function status()
27 1
    {
28
        $params = [];
29 1
        $jobManager = $this->container->get('dtc_queue.manager.job');
30 1
31
        $params['status'] = $jobManager->getStatus();
32 1
        $this->addCssJs($params);
33 1
34
        return $this->render('@DtcQueue/Queue/status.html.twig', $params);
35 1
    }
36
37
    /**
38
     * List jobs in system by default.
39
     *
40
     * @throws UnsupportedException|\Exception
41
     */
42
    public function jobsAll()
43
    {
44
        $this->validateManagerType('dtc_queue.manager.job');
45 1
        $this->checkDtcGridBundle();
46
47 1
        $class1 = $this->container->getParameter('dtc_queue.class.job');
48 1
        $class2 = $this->container->getParameter('dtc_queue.class.job_archive');
49
        $label1 = 'Non-Archived Jobs';
50 1
        $label2 = 'Archived Jobs';
51 1
52 1
        $params = $this->getDualGridParams($class1, $class2, $label1, $label2);
53 1
54
        return $this->render('@DtcQueue/Queue/grid.html.twig', $params);
55 1
    }
56
57 1
    /**
58
     * @throws UnsupportedException
59
     */
60
    public function archive(Request $request)
61
    {
62
        return $this->streamResults($request, 'archiveAllJobs');
63
    }
64
65
    /**
66 1
     * @return StreamedResponse
67
     * @throws UnsupportedException
68 1
     */
69
    public function resetStalled(Request $request)
70
    {
71
        return $this->streamResults($request, 'resetStalledJobs');
72
    }
73
74
    /**
75
     * @return StreamedResponse
76
     *
77
     * @throws UnsupportedException
78
     */
79
    public function pruneStalled(Request $request)
80
    {
81
        return $this->streamResults($request, 'pruneStalledJobs');
82
    }
83
84
    /**
85
     * @param $functionName
86
     *
87
     * @return StreamedResponse
88
     *
89
     * @throws UnsupportedException
90
     */
91
    protected function streamResults(Request $request, $functionName)
92
    {
93
        $jobManager = $this->container->get('dtc_queue.manager.job');
94
        if (!$jobManager instanceof DoctrineJobManager) {
95
            throw new UnsupportedException('$jobManager must be instance of '.DoctrineJobManager::class);
96
        }
97
98
        $streamingResponse = new StreamedResponse($this->getStreamFunction($request, $functionName));
99
        $streamingResponse->headers->set('Content-Type', 'application/x-ndjson');
100
        $streamingResponse->headers->set('X-Accel-Buffering', 'no');
101
102 1
        return $streamingResponse;
103
    }
104 1
105 1
    /**
106
     * @param string $functionName
107
     *
108
     * @return \Closure
109 1
     */
110 1
    protected function getStreamFunction(Request $request, $functionName)
111 1
    {
112
        $jobManager = $this->container->get('dtc_queue.manager.job');
113 1
        $workerName = $request->get('workerName');
114
        $methodName = $request->get('method');
115
        $total = null;
116
        $callback = function ($count, $totalCount) use (&$total) {
117
            if (null !== $totalCount && null === $total) {
118
                $total = $totalCount;
119
                echo json_encode(['total' => $total]);
120
                echo "\n";
121 1
                flush();
122
123 1
                return;
124 1
            }
125 1
            echo json_encode(['count' => $count]);
126 1
            echo "\n";
127 1
            flush();
128
        };
129
130
        return function () use ($jobManager, $callback, $workerName, $methodName, $functionName, &$total) {
131
            switch ($functionName) {
132
                case 'archiveAllJobs':
133
                    $total = $jobManager->countLiveJobs($workerName, $methodName);
134
                    echo json_encode(['total' => $total]);
135
                    echo "\n";
136
                    flush();
137
                    if ($total > 0) {
138
                        $jobManager->archiveAllJobs($workerName, $methodName, $callback);
139 1
                    }
140
                    break;
141 1
                default:
142
                    $jobManager->$functionName($workerName, $methodName, $callback);
143
                    break;
144
            }
145
        };
146
    }
147
148
    /**
149
     * List jobs in system by default.
150
     *
151
     * @throws UnsupportedException|\Exception
152
     */
153
    public function jobs()
154
    {
155
        $this->validateManagerType('dtc_queue.manager.job');
156 1
        $this->checkDtcGridBundle();
157
        $managerType = $this->container->getParameter('dtc_queue.manager.job');
158
        $rendererFactory = $this->container->get('dtc_grid.renderer.factory');
159
        $renderer = $rendererFactory->create('datatables');
160
        $gridSource = $this->container->get('dtc_queue.grid_source.jobs_waiting.'.('mongodb' === $managerType ? 'odm' : $managerType));
161
        $renderer->bind($gridSource);
162
        $params = $renderer->getParams();
163
        $this->addCssJs($params);
164
165
        $params['worker_methods'] = $this->container->get('dtc_queue.manager.job')->getWorkersAndMethods();
166
        $params['prompt_message'] = 'This will archive all non-running jobs';
167 1
168
        return $this->render('@DtcQueue/Queue/jobs.html.twig', $params);
169 1
    }
170 1
171 1
    /**
172 1
     * List jobs in system by default.
173 1
     *
174 1
     * @throws UnsupportedException|\Exception
175 1
     */
176 1
    public function jobsRunning()
177 1
    {
178
        $this->validateManagerType('dtc_queue.manager.job');
179 1
        $this->checkDtcGridBundle();
180 1
        $managerType = $this->container->getParameter('dtc_queue.manager.job');
181
        $rendererFactory = $this->container->get('dtc_grid.renderer.factory');
182 1
        $renderer = $rendererFactory->create('datatables');
183
        $gridSource = $this->container->get('dtc_queue.grid_source.jobs_running.'.('mongodb' === $managerType ? 'odm' : $managerType));
184
        $renderer->bind($gridSource);
185
        $params = $renderer->getParams();
186
        $this->addCssJs($params);
187
188
        $params['worker_methods'] = $this->container->get('dtc_queue.manager.job')->getWorkersAndMethods(BaseJob::STATUS_RUNNING);
189
        $params['prompt_message'] = 'This will prune all stalled jobs';
190
191
        return $this->render('@DtcQueue/Queue/jobs_running.html.twig', $params);
192
    }
193 1
194
    /**
195 1
     * @param string $class1
196 1
     * @param string $class2
197 1
     * @param string $label1
198 1
     * @param string $label2
199 1
     *
200 1
     * @return array
201 1
     *
202 1
     * @throws \Exception
203 1
     */
204
    protected function getDualGridParams($class1, $class2, $label1, $label2)
205 1
    {
206 1
        $rendererFactory = $this->container->get('dtc_grid.renderer.factory');
207
        $renderer = $rendererFactory->create('datatables');
208 1
        $gridSource = $this->container->get('dtc_grid.manager.source')->get($class1);
209
        $renderer->bind($gridSource);
210
        $params = $renderer->getParams();
211
212
        $renderer2 = $rendererFactory->create('datatables');
213
        $gridSource = $this->container->get('dtc_grid.manager.source')->get($class2);
214
        $renderer2->bind($gridSource);
215
        $params2 = $renderer2->getParams();
216
217
        $params['archive_grid'] = $params2['dtc_grid'];
218
219
        $params['dtc_queue_grid_label1'] = $label1;
220
        $params['dtc_queue_grid_label2'] = $label2;
221 2
        $this->addCssJs($params);
222
223 2
        return $params;
224 2
    }
225 2
226 2
    /**
227 2
     * List jobs in system by default.
228
     *
229 2
     * @throws UnsupportedException|\Exception
230 2
     */
231 2
    public function runs()
232 2
    {
233
        $this->validateRunManager();
234 2
        $this->checkDtcGridBundle();
235
        $class1 = $this->container->getParameter('dtc_queue.class.run');
236 2
        $class2 = $this->container->getParameter('dtc_queue.class.run_archive');
237 2
        $label1 = 'Live Runs';
238 2
        $label2 = 'Archived Runs';
239
240 2
        $params = $this->getDualGridParams($class1, $class2, $label1, $label2);
241
        return $this->render('@DtcQueue/Queue/grid.html.twig', $params);
242
    }
243
244
    /**
245
     * List registered workers in the system.
246
     *
247
     */
248
    public function workers()
249
    {
250 1
        $workerManager = $this->container->get('dtc_queue.manager.worker');
251
        $workers = $workerManager->getWorkers();
252 1
253 1
        $workerList = [];
254 1
        foreach ($workers as $workerName => $worker) {
255 1
            /* @var Worker $worker */
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
256 1
            $workerList[$workerName] = get_class($worker);
257 1
        }
258
        $params = ['workers' => $workerList];
259 1
        $this->addCssJs($params);
260
261 1
        return $this->render('@DtcQueue/Queue/workers.html.twig', $params);
262
    }
263
264
    /**
265
     * Validates that DtcGridBundle exists.
266
     *
267
     * @throws UnsupportedException
268
     */
269
    protected function checkDtcGridBundle()
270 1
    {
271
        if (!class_exists('Dtc\GridBundle\DtcGridBundle')) {
272 1
            throw new UnsupportedException('DtcGridBundle (mmucklo/grid-bundle) needs to be installed.');
273 1
        }
274
    }
275
}
276