CronCommand.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. <?php
  2. namespace App\Commands;
  3. use App\Service\Cron\CronjobInterface;
  4. use App\Service\Cron\UI\ConsoleUI;
  5. use App\Service\ServiceIterator\CronjobIterator;
  6. use Psr\Log\LoggerInterface;
  7. use Symfony\Component\Console\Attribute\AsCommand;
  8. use Symfony\Component\Console\Command\Command;
  9. use Symfony\Component\Console\Command\LockableTrait;
  10. use Symfony\Component\Console\Helper\FormatterHelper;
  11. use Symfony\Component\Console\Input\InputArgument;
  12. use Symfony\Component\Console\Input\InputInterface;
  13. use Symfony\Component\Console\Input\InputOption;
  14. use Symfony\Component\Console\Output\OutputInterface;
  15. use Symfony\Contracts\Service\Attribute\Required;
  16. /**
  17. * CLI Command to run the cron-jobs.
  18. *
  19. * Ex:
  20. *
  21. * bin/console ot:cron list
  22. * bin/console ot:cron run clean-db --preview
  23. * bin/console ot:cron run clean-db
  24. *
  25. * @see ~/src/Service/Cron/Readme.md
  26. */
  27. #[AsCommand(
  28. name: 'ot:cron',
  29. description: 'Executes cron jobs'
  30. )]
  31. class CronCommand extends Command
  32. {
  33. use LockableTrait;
  34. private const ACTION_LIST = 'list';
  35. private const ACTION_RUN = 'run';
  36. private const ACTION_RUN_ALL = 'all';
  37. private const ACTIONS = [
  38. self::ACTION_LIST => 'List registered jobs',
  39. self::ACTION_RUN => 'Run the given job',
  40. self::ACTION_RUN_ALL => 'Successively run all the registered cron jobs',
  41. ];
  42. private OutputInterface $output;
  43. private LoggerInterface $logger;
  44. private CronjobIterator $cronjobIterator;
  45. #[Required]
  46. /** @see https://symfony.com/doc/current/logging/channels_handlers.html#how-to-autowire-logger-channels */
  47. public function setLoggerInterface(LoggerInterface $cronLogger): void
  48. {
  49. $this->logger = $cronLogger;
  50. }
  51. #[Required]
  52. public function setCronjobIterator(CronjobIterator $cronjobIterator): void
  53. {
  54. $this->cronjobIterator = $cronjobIterator;
  55. }
  56. /**
  57. * Configures the command.
  58. */
  59. protected function configure(): void
  60. {
  61. $this->addArgument(
  62. 'action',
  63. InputArgument::REQUIRED,
  64. 'Action to execute among : '.
  65. implode(
  66. ', ',
  67. array_map(
  68. static function ($v, $k) { return "'".$k."' (".$v.')'; },
  69. self::ACTIONS,
  70. array_keys(self::ACTIONS)
  71. )
  72. )
  73. );
  74. $this->addArgument(
  75. 'jobs',
  76. InputArgument::OPTIONAL,
  77. "Name(s) of the cron-job(s) to execute with '".self::ACTION_RUN."' (comma-separated)"
  78. );
  79. $this->addOption(
  80. 'preview',
  81. 'p',
  82. InputOption::VALUE_NONE,
  83. 'Only preview the operations instead of executing them'
  84. );
  85. }
  86. /**
  87. * Executes the command.
  88. */
  89. final protected function execute(InputInterface $input, OutputInterface $output): int
  90. {
  91. $this->output = $output;
  92. /** @var FormatterHelper $formatter */
  93. $formatter = $this->getHelper('formatter');
  94. $action = $input->getArgument('action');
  95. $jobNames = $input->getArgument('jobs');
  96. $preview = $input->getOption('preview');
  97. $jobs = [];
  98. if (!array_key_exists($action, self::ACTIONS)) {
  99. $this->output->writeln($formatter->formatBlock('Error: unrecognized action', 'error'));
  100. return Command::INVALID;
  101. }
  102. if (self::ACTION_LIST === $action) {
  103. $this->listJobs();
  104. return Command::SUCCESS;
  105. }
  106. if (self::ACTION_RUN_ALL === $action) {
  107. $jobs = $this->cronjobIterator->getAll();
  108. }
  109. if (self::ACTION_RUN === $action) {
  110. foreach (explode(',', $jobNames) as $name) {
  111. try {
  112. $jobs[] = $this->cronjobIterator->getByName($name);
  113. } catch (\RuntimeException $e) {
  114. $this->output->writeln($e->getMessage());
  115. $this->listJobs();
  116. return Command::INVALID;
  117. }
  118. }
  119. }
  120. $this->logger->info(
  121. 'CronCommand will '.
  122. ($preview ? 'preview' : 'execute').' '.
  123. implode(', ', array_map(static function ($job) { return $job->name(); }, $jobs))
  124. );
  125. $results = [];
  126. foreach ($jobs as $job) {
  127. $results[] = $this->runJob($job, $preview);
  128. }
  129. return (int) max($results); // If there is one failure result, the whole command is shown as a failure too
  130. }
  131. /**
  132. * List all available cron jobs.
  133. */
  134. private function listJobs(): void
  135. {
  136. $availableJobs = $this->cronjobIterator->getAll();
  137. if (empty($availableJobs)) {
  138. $this->output->writeln('No cronjob found');
  139. return;
  140. }
  141. $this->output->writeln('Available cron jobs : ');
  142. foreach ($this->cronjobIterator->getAll() as $job) {
  143. $this->output->writeln('* '.$job->name());
  144. }
  145. }
  146. /**
  147. * Run one Cronjob.
  148. */
  149. private function runJob(CronjobInterface $job, bool $preview = false): int
  150. {
  151. /** @var FormatterHelper $formatter */
  152. $formatter = $this->getHelper('formatter');
  153. if (!$this->lock($job->name())) {
  154. $msg = 'The command '.$job->name().' is already running in another process. Abort.';
  155. $this->output->writeln($formatter->formatBlock($msg, 'error'));
  156. $this->logger->error($msg);
  157. return Command::FAILURE;
  158. }
  159. $t0 = microtime(true);
  160. $this->output->writeln(
  161. $formatter->formatSection($job->name(), 'Start'.($preview ? ' [PREVIEW MODE]' : ''))
  162. );
  163. // Establish communication between job and the console
  164. $ui = new ConsoleUI($this->output);
  165. $job->setUI($ui);
  166. try {
  167. if ($preview) {
  168. $job->preview();
  169. } else {
  170. $job->execute();
  171. }
  172. } catch (\RuntimeException $e) {
  173. $this->logger->critical($e);
  174. $this->output->write('An error happened while running the process : '.$e);
  175. return Command::FAILURE;
  176. }
  177. $t1 = microtime(true);
  178. $msg = 'Job has been successfully executed ('.round($t1 - $t0, 2).' sec.)'.($preview ? ' [PREVIEW MODE]' : '');
  179. $this->output->writeln($formatter->formatSection($job->name(), $msg));
  180. $this->logger->info($job->name().' - '.$msg);
  181. return Command::SUCCESS;
  182. }
  183. }