CronCommand.php 6.6 KB

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