Total Complexity | 58 |
Total Lines | 488 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like RunCommand often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use RunCommand, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
25 | class RunCommand extends ContainerAwareCommand |
||
|
|||
26 | { |
||
27 | protected static $defaultName = 'setono:scheduler:run'; |
||
28 | |||
29 | /** |
||
30 | * @var EntityManager |
||
31 | */ |
||
32 | private $entityManager; |
||
33 | |||
34 | /** |
||
35 | * @var EventDispatcherInterface |
||
36 | */ |
||
37 | private $eventDispatcher; |
||
38 | |||
39 | /** |
||
40 | * @var JobManager |
||
41 | */ |
||
42 | private $jobManager; |
||
43 | |||
44 | /** |
||
45 | * @var JobRepository |
||
46 | */ |
||
47 | private $jobRepository; |
||
48 | |||
49 | /** |
||
50 | * @var string |
||
51 | */ |
||
52 | private $env; |
||
53 | |||
54 | /** |
||
55 | * @var bool |
||
56 | */ |
||
57 | private $verbose; |
||
58 | |||
59 | /** |
||
60 | * @var OutputInterface |
||
61 | */ |
||
62 | private $output; |
||
63 | |||
64 | /** |
||
65 | * @var array |
||
66 | */ |
||
67 | private $runningJobs = []; |
||
68 | |||
69 | /** |
||
70 | * @var bool |
||
71 | */ |
||
72 | private $shouldShutdown = false; |
||
73 | |||
74 | /** |
||
75 | * @param JobManager $jobManager |
||
76 | * @param JobRepository $jobRepository |
||
77 | * @param EntityManager $entityManager |
||
78 | * @param EventDispatcherInterface $eventDispatcher |
||
79 | */ |
||
80 | public function __construct( |
||
81 | JobManager $jobManager, |
||
82 | JobRepository $jobRepository, |
||
83 | EntityManager $entityManager, |
||
84 | EventDispatcherInterface $eventDispatcher |
||
85 | ) { |
||
86 | $this->jobManager = $jobManager; |
||
87 | $this->jobRepository = $jobRepository; |
||
88 | $this->entityManager = $entityManager; |
||
89 | $this->eventDispatcher = $eventDispatcher; |
||
90 | |||
91 | parent::__construct(); |
||
92 | } |
||
93 | |||
94 | /** |
||
95 | * @noinspection ReturnTypeCanBeDeclaredInspection |
||
96 | */ |
||
97 | protected function configure() |
||
98 | { |
||
99 | $this |
||
100 | ->setDescription('Runs jobs from the queue.') |
||
101 | ->addOption('max-runtime', 'r', InputOption::VALUE_REQUIRED, 'The maximum runtime in seconds.', '900') |
||
102 | ->addOption('max-concurrent-jobs', 'j', InputOption::VALUE_REQUIRED, 'The maximum number of concurrent jobs.', '4') |
||
103 | ->addOption('idle-time', null, InputOption::VALUE_REQUIRED, 'Time to sleep when the queue ran out of jobs.', '2') |
||
104 | ->addOption('queue', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Restrict to one or more queues.', []) |
||
105 | ->addOption('worker-name', null, InputOption::VALUE_REQUIRED, 'The name that uniquely identifies this worker process.') |
||
106 | ; |
||
107 | } |
||
108 | |||
109 | /** |
||
110 | * {@inheritdoc} |
||
111 | * |
||
112 | * @noinspection ReturnTypeCanBeDeclaredInspection |
||
113 | */ |
||
114 | protected function execute(InputInterface $input, OutputInterface $output) |
||
115 | { |
||
116 | $startTime = time(); |
||
117 | |||
118 | $maxRuntime = (int) $input->getOption('max-runtime'); |
||
119 | if ($maxRuntime <= 0) { |
||
120 | throw new InvalidArgumentException('The maximum runtime must be greater than zero.'); |
||
121 | } |
||
122 | |||
123 | if ($maxRuntime > 600) { |
||
124 | $maxRuntime += random_int(-120, 120); |
||
125 | } |
||
126 | |||
127 | $maxJobs = (int) $input->getOption('max-concurrent-jobs'); |
||
128 | if ($maxJobs <= 0) { |
||
129 | throw new InvalidArgumentException('The maximum number of jobs per queue must be greater than zero.'); |
||
130 | } |
||
131 | |||
132 | $idleTime = (int) $input->getOption('idle-time'); |
||
133 | if ($idleTime <= 0) { |
||
134 | throw new InvalidArgumentException('Time to sleep when idling must be greater than zero.'); |
||
135 | } |
||
136 | |||
137 | $restrictedQueues = $input->getOption('queue'); |
||
138 | |||
139 | /** @var string|null $workerName */ |
||
140 | $workerName = $input->getOption('worker-name'); |
||
141 | if ($workerName === null) { |
||
142 | $workerName = gethostname() . '-' . getmypid(); |
||
143 | } elseif (\strlen($workerName) > 50) { |
||
144 | throw new \RuntimeException(sprintf( |
||
145 | '"worker-name" must not be longer than 50 chars, but got "%s" (%d chars).', |
||
146 | $workerName, |
||
147 | \strlen($workerName) |
||
148 | )); |
||
149 | } |
||
150 | |||
151 | $this->env = (string) $input->getOption('env'); |
||
152 | $this->verbose = (string) $input->getOption('verbose'); |
||
153 | $this->output = $output; |
||
154 | $this->entityManager->getConnection()->getConfiguration()->setSQLLogger(null); |
||
155 | |||
156 | if ($this->verbose) { |
||
157 | $this->output->writeln('Cleaning up stale jobs'); |
||
158 | } |
||
159 | |||
160 | $this->cleanUpStaleJobs($workerName); |
||
161 | |||
162 | $this->runJobs( |
||
163 | $workerName, |
||
164 | $startTime, |
||
165 | $maxRuntime, |
||
166 | $idleTime, |
||
167 | $maxJobs, |
||
168 | $restrictedQueues, |
||
169 | $this->getContainer()->getParameter('setono_sylius_scheduler.queue_options_defaults'), // @todo DI |
||
170 | $this->getContainer()->getParameter('setono_sylius_scheduler.queue_options') // @todo DI |
||
171 | ); |
||
172 | } |
||
173 | |||
174 | /** |
||
175 | * @param string|null $workerName |
||
176 | * @param int $startTime |
||
177 | * @param int $maxRuntime |
||
178 | * @param int $idleTime |
||
179 | * @param int $maxJobs |
||
180 | * @param array $restrictedQueues |
||
181 | * @param array $queueOptionsDefaults |
||
182 | * @param array $queueOptions |
||
183 | */ |
||
184 | private function runJobs(?string $workerName, int $startTime, int $maxRuntime, int $idleTime, int $maxJobs, array $restrictedQueues, array $queueOptionsDefaults, array $queueOptions): void |
||
185 | { |
||
186 | $hasPcntl = \extension_loaded('pcntl'); |
||
187 | |||
188 | if ($this->verbose) { |
||
189 | $this->output->writeln('Running jobs'); |
||
190 | } |
||
191 | |||
192 | if ($hasPcntl) { |
||
193 | $this->setupSignalHandlers(); |
||
194 | if ($this->verbose) { |
||
195 | $this->output->writeln('Signal Handlers have been installed.'); |
||
196 | } |
||
197 | } elseif ($this->verbose) { |
||
198 | $this->output->writeln('PCNTL extension is not available. Signals cannot be processed.'); |
||
199 | } |
||
200 | |||
201 | while (true) { |
||
202 | if ($hasPcntl) { |
||
203 | pcntl_signal_dispatch(); |
||
204 | } |
||
205 | |||
206 | if ($this->shouldShutdown || time() - $startTime > $maxRuntime) { |
||
207 | break; |
||
208 | } |
||
209 | |||
210 | $this->checkRunningJobs(); |
||
211 | $this->startJobs($workerName, $idleTime, $maxJobs, $restrictedQueues, $queueOptionsDefaults, $queueOptions); |
||
212 | |||
213 | $waitTimeInMs = random_int(500, 1000); |
||
214 | usleep($waitTimeInMs * 1000); |
||
215 | } |
||
216 | |||
217 | if ($this->verbose) { |
||
218 | $this->output->writeln('Entering shutdown sequence, waiting for running jobs to terminate...'); |
||
219 | } |
||
220 | |||
221 | while (!empty($this->runningJobs)) { |
||
222 | sleep(5); |
||
223 | $this->checkRunningJobs(); |
||
224 | } |
||
225 | |||
226 | if ($this->verbose) { |
||
227 | $this->output->writeln('All jobs finished, exiting.'); |
||
228 | } |
||
229 | } |
||
230 | |||
231 | private function setupSignalHandlers(): void |
||
232 | { |
||
233 | pcntl_signal(SIGTERM, function () { |
||
234 | if ($this->verbose) { |
||
235 | $this->output->writeln('Received SIGTERM signal.'); |
||
236 | } |
||
237 | |||
238 | $this->shouldShutdown = true; |
||
239 | }); |
||
240 | } |
||
241 | |||
242 | /** |
||
243 | * @param string|null $workerName |
||
244 | * @param int $idleTime |
||
245 | * @param int $maxJobs |
||
246 | * @param array $restrictedQueues |
||
247 | * @param array $queueOptionsDefaults |
||
248 | * @param array $queueOptions |
||
249 | */ |
||
250 | private function startJobs(?string $workerName, int $idleTime, int $maxJobs, array $restrictedQueues, array $queueOptionsDefaults, array $queueOptions): void |
||
268 | } |
||
269 | } |
||
270 | |||
271 | /** |
||
272 | * @param array $queueOptionsDefaults |
||
273 | * @param array $queueOptions |
||
274 | * @param int $maxConcurrentJobs |
||
275 | * |
||
276 | * @return array |
||
277 | */ |
||
278 | private function getExcludedQueues(array $queueOptionsDefaults, array $queueOptions, int $maxConcurrentJobs): array |
||
279 | { |
||
280 | $excludedQueues = []; |
||
281 | foreach ($this->getRunningJobsPerQueue() as $queue => $count) { |
||
282 | if ($count >= $this->getMaxConcurrentJobs($queue, $queueOptionsDefaults, $queueOptions, $maxConcurrentJobs)) { |
||
283 | $excludedQueues[] = $queue; |
||
284 | } |
||
285 | } |
||
286 | |||
287 | return $excludedQueues; |
||
288 | } |
||
289 | |||
290 | /** |
||
291 | * @param string $queue |
||
292 | * @param array $queueOptionsDefaults |
||
293 | * @param array $queueOptions |
||
294 | * @param int $maxConcurrentJobs |
||
295 | * |
||
296 | * @return int |
||
297 | */ |
||
298 | private function getMaxConcurrentJobs(string $queue, array $queueOptionsDefaults, array $queueOptions, int $maxConcurrentJobs): int |
||
299 | { |
||
300 | if (isset($queueOptions[$queue]['max_concurrent_jobs'])) { |
||
301 | return (int) $queueOptions[$queue]['max_concurrent_jobs']; |
||
302 | } |
||
303 | |||
304 | if (isset($queueOptionsDefaults['max_concurrent_jobs'])) { |
||
305 | return (int) $queueOptionsDefaults['max_concurrent_jobs']; |
||
306 | } |
||
307 | |||
308 | return $maxConcurrentJobs; |
||
309 | } |
||
310 | |||
311 | /** |
||
312 | * @return array |
||
313 | */ |
||
314 | private function getRunningJobsPerQueue(): array |
||
315 | { |
||
316 | $runningJobsPerQueue = []; |
||
317 | foreach ($this->runningJobs as $jobDetails) { |
||
318 | /** @var JobInterface $job */ |
||
319 | $job = $jobDetails['job']; |
||
320 | |||
321 | $queue = $job->getQueue(); |
||
322 | if (!isset($runningJobsPerQueue[$queue])) { |
||
323 | $runningJobsPerQueue[$queue] = 0; |
||
324 | } |
||
325 | ++$runningJobsPerQueue[$queue]; |
||
326 | } |
||
327 | |||
328 | return $runningJobsPerQueue; |
||
329 | } |
||
330 | |||
331 | private function checkRunningJobs(): void |
||
406 | } |
||
407 | |||
408 | /** |
||
409 | * @param JobInterface $job |
||
410 | */ |
||
411 | private function startJob(JobInterface $job): void |
||
412 | { |
||
413 | $event = new StateChangeEvent($job, JobInterface::STATE_RUNNING); |
||
414 | $this->eventDispatcher->dispatch(SetonoSyliusSchedulerPluginEvent::JOB_STATE_CHANGED, $event); |
||
415 | $newState = $event->getNewState(); |
||
416 | |||
417 | if (JobInterface::STATE_CANCELED === $newState) { |
||
418 | $this->jobManager->closeJob($job, JobInterface::STATE_CANCELED); |
||
419 | |||
420 | return; |
||
421 | } |
||
422 | |||
423 | if (JobInterface::STATE_RUNNING !== $newState) { |
||
424 | throw new \LogicException(sprintf('Unsupported new state "%s".', $newState)); |
||
425 | } |
||
426 | |||
427 | $job->setState(JobInterface::STATE_RUNNING); |
||
428 | |||
429 | $this->entityManager->persist($job); |
||
430 | $this->entityManager->flush($job); |
||
431 | |||
432 | $args = $this->getBasicCommandLineArgs(); |
||
433 | $args[] = $job->getCommand(); |
||
434 | // $args[] = '--jms-job-id=' . $job->getId(); |
||
435 | |||
436 | foreach ($job->getArgs() as $arg) { |
||
437 | $args[] = $arg; |
||
438 | } |
||
439 | |||
440 | $process = new Process($args); |
||
441 | $process->start(); |
||
442 | $this->output->writeln(sprintf( |
||
443 | 'Started %s.', |
||
444 | (string) $job |
||
445 | )); |
||
446 | |||
447 | $this->runningJobs[] = [ |
||
448 | 'process' => $process, |
||
449 | 'job' => $job, |
||
450 | 'start_time' => time(), |
||
451 | 'output_pointer' => 0, |
||
452 | 'error_output_pointer' => 0, |
||
453 | ]; |
||
454 | } |
||
455 | |||
456 | /** |
||
457 | * Cleans up stale jobs. |
||
458 | * |
||
459 | * A stale job is a job where this command has exited with an error |
||
460 | * condition. Although this command is very robust, there might be cases |
||
461 | * where it might be terminated abruptly (like a PHP segfault, a SIGTERM signal, etc.). |
||
462 | * |
||
463 | * In such an error condition, these jobs are cleaned-up on restart of this command. |
||
464 | * |
||
465 | * @param string $workerName |
||
466 | */ |
||
467 | private function cleanUpStaleJobs(string $workerName): void |
||
492 | )); |
||
493 | } |
||
494 | } |
||
495 | } |
||
496 | |||
497 | /** |
||
498 | * @return array |
||
499 | */ |
||
500 | private function getBasicCommandLineArgs(): array |
||
513 | } |
||
514 | } |
||
515 |