|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Symfony\Bundle\FrameworkBundle\Command; |
| 4 | + |
| 5 | +use Symfony\Component\Amqp\Worker\ConfigurableLoopInterface; |
| 6 | +use Symfony\Component\Console\Input\InputArgument; |
| 7 | +use Symfony\Component\Console\Input\InputInterface; |
| 8 | +use Symfony\Component\Console\Input\InputOption; |
| 9 | +use Symfony\Component\Console\Output\OutputInterface; |
| 10 | + |
| 11 | +class WorkerRunCommand extends ContainerAwareCommand |
| 12 | +{ |
| 13 | + protected function configure() |
| 14 | + { |
| 15 | + $this |
| 16 | + ->setName('worker:run') |
| 17 | + ->setDescription('Run a worker') |
| 18 | + ->setDefinition(array( |
| 19 | + new InputArgument('worker', InputArgument::REQUIRED, 'The worker'), |
| 20 | + new InputOption('name', null, InputOption::VALUE_REQUIRED, 'A name, useful for stats/monitoring. Defaults to worker name.'), |
| 21 | + )) |
| 22 | + ; |
| 23 | + } |
| 24 | + |
| 25 | + protected function execute(InputInterface $input, OutputInterface $output) |
| 26 | + { |
| 27 | + $loop = $this->getLoop($input); |
| 28 | + |
| 29 | + $loopName = $input->getOption('name') ?: $loop->getName(); |
| 30 | + |
| 31 | + if ($loop instanceof ConfigurableLoopInterface) { |
| 32 | + $loop->setName($loopName); |
| 33 | + } |
| 34 | + |
| 35 | + $processName = sprintf('%s_%s', $this->getContainer()->getParameter('worker.cli_title_prefix'), $loopName); |
| 36 | + |
| 37 | + // On OSX, it may raise an error: |
| 38 | + // Warning: cli_set_process_title(): cli_set_process_title had an error: Not initialized correctly |
| 39 | + @cli_set_process_title($processName); |
| 40 | + |
| 41 | + pcntl_signal(SIGTERM, function () use ($loop) { |
| 42 | + $loop->stop('Signaled with SIGTERM.'); |
| 43 | + }); |
| 44 | + pcntl_signal(SIGINT, function () use ($loop) { |
| 45 | + $loop->stop('Signaled with SIGINT.'); |
| 46 | + }); |
| 47 | + |
| 48 | + $loop->run(); |
| 49 | + } |
| 50 | + |
| 51 | + private function getLoop(InputInterface $input) |
| 52 | + { |
| 53 | + $workers = $this->getContainer()->getParameter('worker.workers'); |
| 54 | + |
| 55 | + $workerName = $input->getArgument('worker'); |
| 56 | + |
| 57 | + if (!array_key_exists($workerName, $workers)) { |
| 58 | + throw new \InvalidArgumentException(sprintf( |
| 59 | + 'The worker "%s" does not exist. Available ones are: "%s".', |
| 60 | + $workerName, implode('", "', array_keys($workers)) |
| 61 | + )); |
| 62 | + } |
| 63 | + |
| 64 | + return $this->getContainer()->get($workers[$workerName]); |
| 65 | + } |
| 66 | +} |
0 commit comments