RunWorkersCommand.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php declare(strict_types=1);
  2. namespace Packagist\WebBundle\Command;
  3. use Symfony\Component\Console\Input\InputInterface;
  4. use Symfony\Component\Console\Input\InputOption;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. use Symfony\Component\Filesystem\LockHandler;
  7. use Symfony\Component\Console\Command\Command;
  8. use Seld\Signal\SignalHandler;
  9. use Packagist\WebBundle\Service\QueueWorker;
  10. use Psr\Log\LoggerInterface;
  11. class RunWorkersCommand extends Command
  12. {
  13. private $logger;
  14. private $worker;
  15. public function __construct(LoggerInterface $logger, QueueWorker $worker)
  16. {
  17. $this->logger = $logger;
  18. $this->worker = $worker;
  19. parent::__construct();
  20. }
  21. protected function configure()
  22. {
  23. $this
  24. ->setName('packagist:run-workers')
  25. ->setDescription('Run worker services')
  26. ->addOption('messages', null, InputOption::VALUE_OPTIONAL, 'Amount of messages to process before exiting', 5000)
  27. ->addOption('worker-id', 'w', InputOption::VALUE_OPTIONAL, 'Unique worker ID', '1')
  28. ;
  29. }
  30. protected function execute(InputInterface $input, OutputInterface $output)
  31. {
  32. \Monolog\ErrorHandler::register($this->logger);
  33. $lock = new LockHandler('packagist_run_' . $input->getOption('worker-id'));
  34. ini_set('memory_limit', '1G');
  35. // another dumper is still active
  36. if (!$lock->lock()) {
  37. if ($input->getOption('verbose')) {
  38. $output->writeln('Aborting, another of the same worker is still active');
  39. }
  40. return;
  41. }
  42. try {
  43. $this->logger->notice('Worker started successfully');
  44. $this->logger->reset();
  45. $this->worker->processMessages((int) $input->getOption('messages'));
  46. $this->logger->notice('Worker exiting successfully');
  47. } finally {
  48. $lock->release();
  49. }
  50. }
  51. }