CronCommand.php 8.1 KB

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