refs #1966. RunScheduleCommand
testing/ogcore-api/pipeline/head This commit looks good Details

pull/30/head
Manuel Aranda Rosales 2025-05-07 16:59:20 +02:00
parent 53a8c04e76
commit d347896158
1 changed files with 90 additions and 0 deletions

View File

@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace App\Command;
use App\Controller\OgAgent\DeployImageAction;
use App\Controller\OgAgent\RunScriptAction;
use App\Dto\Input\CommandExecuteInput;
use App\Dto\Input\DeployImageInput;
use App\Dto\Output\ClientOutput;
use App\Entity\CommandTask;
use App\Repository\CommandTaskRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
#[AsCommand(name: 'opengnsys:run-scheduled-command-tasks', description: 'Run scheduled command tasks')]
class RunScheduledCommandTasksCommand extends Command
{
public function __construct(
private readonly CommandTaskRepository $commandTaskRepository,
private readonly EntityManagerInterface $entityManager,
private readonly RunScriptAction $runScriptAction,
private readonly DeployImageAction $deployImageAction,
)
{
parent::__construct();
}
/**
* @throws \Exception
* @throws TransportExceptionInterface
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$now = new \DateTimeImmutable('now +2 hours');
$now->setTimezone(new \DateTimeZone('Europe/Madrid'));
$nowMinute = $now->format('Y-m-d H:i');
$tasks = $this->commandTaskRepository->findAll();
foreach ($tasks as $task) {
/** @var CommandTask $task */
$nextExecution = $task->getNextExecution();
if (!$nextExecution) {
continue;
}
$taskMinute = $nextExecution->format('Y-m-d H:i');
if ($taskMinute === $nowMinute) {
$output->writeln("Ejecutando tarea: " . $task->getName());
$scripts = $task->getCommandTaskScripts()->toArray();
usort($scripts, fn($a, $b) => $a->getExecutionOrder() <=> $b->getExecutionOrder());
foreach ($scripts as $script) {
try {
$output->writeln(" - Ejecutando script de tipo {$script->getType()} con orden {$script->getExecutionOrder()}");
if ($script->getType() === 'run-script') {
$input = new CommandExecuteInput();
foreach ($task->getOrganizationalUnit()?->getClients() as $client) {
$input->clients[] = new ClientOutput($client);
}
$input->script = $script->getContent();
$this->runScriptAction->__invoke($input);
}
} catch (TransportExceptionInterface $e) {
$output->writeln("Error ejecutando script: " . $e->getMessage());
continue;
}
}
$task->setLastExecution(new \DateTime());
$task->setNextExecution($task->calculateNextExecutionDate());
$this->entityManager->persist($task);
}
}
$this->entityManager->flush();
return Command::SUCCESS;
}
}