Merge pull request 'Añadida nueva ruta para cambiar la plantilla de un cliente /clients/set-boot-mode, recibe el nombre de la plantilla, el modo 0=temporal, 1=permanente y puede enviarse mac, ip o nombre del cliente o nombre del aula.' (#113) from setbootmode into main
testing/ogcore-api/pipeline/head There was a failure building this commit Details
ogcore-debian-package/pipeline/head This commit looks good Details

Reviewed-on: #113
pull/114/head
Juan Manuel Bardallo 2026-05-12 14:57:15 +02:00
commit 01d39e00a5
4 changed files with 200 additions and 1 deletions

View File

@ -1,5 +1,11 @@
# Changelog
## [1.7.9] - 2026-05-12
### Added
- Añadida nueva ruta para cambiar la plantilla de un cliente /clients/set-boot-mode, recibe el nombre de la plantilla, el modo 0=temporal, 1=permanente y puede enviarse mac, ip o nombre del cliente o nombre del aula.
### Fixed
- Modificado script de importación de base de datos OG 1.1 para añadir las tablas grupos y gruposordenadores como obligatorias junto con centros y aulas.
## [1.7.8] - 2026-05-11
### Fixed
- En la importación de clientes, se inicializan con estado "off"

View File

@ -153,7 +153,7 @@ class ImportLegacyDbCommand extends Command
$commands = [
'opengnsys:migration:organizational-unit' => [
'desc' => 'Migrating Organizational Units',
'tables' => ['centros', 'aulas']
'tables' => ['centros', 'aulas', 'grupos', 'gruposordenadores']
],
'opengnsys:migration:os' => [
'desc' => 'Migrating Operative Systems',

View File

@ -0,0 +1,66 @@
<?php
namespace App\Command;
use App\Controller\OgBoot\PxeBootFile\PostAction as PostPxeAction;
use App\Repository\ClientRepository;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(
name: 'opengnsys:pxe:sync',
description: 'Sincroniza el fichero PXE de un cliente basándose en su plantilla asignada en BD.',
)]
class PxeSyncCommand extends Command
{
public function __construct(
private readonly ClientRepository $clientRepository,
private readonly PostPxeAction $postPxeAction
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addArgument('mac', InputArgument::REQUIRED, 'Dirección MAC del cliente')
->addArgument('delay', InputArgument::OPTIONAL, 'Tiempo de espera en segundos antes de sincronizar', 0);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$mac = $input->getArgument('mac');
$delay = (int) $input->getArgument('delay');
if ($delay > 0) {
$output->writeln("Esperando $delay segundos...");
sleep($delay);
}
$client = $this->clientRepository->findOneBy(['mac' => $mac]);
if (!$client) {
$output->writeln("<error>Cliente con MAC $mac no encontrado</error>");
return Command::FAILURE;
}
$template = $client->getTemplate();
if (!$template) {
$output->writeln("<error>El cliente no tiene una plantilla asignada</error>");
return Command::FAILURE;
}
$output->writeln("Sincronizando PXE para el cliente {$client->getName()} ({$mac}) con la plantilla {$template->getName()}...");
try {
$this->postPxeAction->__invoke($client, $template);
$output->writeln("<info>Sincronización completada con éxito</info>");
return Command::SUCCESS;
} catch (\Exception $e) {
$output->writeln("<error>Error durante la sincronización: " . $e->getMessage() . "</error>");
return Command::FAILURE;
}
}
}

View File

@ -0,0 +1,127 @@
<?php
namespace App\Controller\OgBoot;
use App\Controller\OgBoot\PxeBootFile\PostAction as PostPxeAction;
use App\Entity\Client;
use App\Entity\PxeTemplate;
use App\Repository\ClientRepository;
use App\Repository\OrganizationalUnitRepository;
use App\Repository\PxeTemplateRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class SetClientBootModeAction extends AbstractController
{
public function __construct(
private readonly ClientRepository $clientRepository,
private readonly OrganizationalUnitRepository $ouRepository,
private readonly PxeTemplateRepository $pxeTemplateRepository,
private readonly PostPxeAction $postPxeAction
) {}
#[Route('/clients/set-boot-mode', name: 'api_clients_set_boot_mode', methods: ['POST'])]
#[IsGranted('ROLE_OGCLIENT_API')]
public function __invoke(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$clientData = $data['client'] ?? null;
$ouData = $data['ou'] ?? null;
$templateName = $data['template'] ?? null;
$mode = $data['mode'] ?? 0; // 0: TEMP, 1: PERM
if ((!$clientData && !$ouData) || !$templateName) {
return new JsonResponse(['error' => 'Faltan parámetros: se requiere "client" u "ou", y "template"'], Response::HTTP_BAD_REQUEST);
}
// 1. Obtener la lista de clientes afectados de forma explícita
$clients = [];
if ($clientData) {
// Búsqueda específica de cliente (Prioridad: MAC > Nombre > IP)
if (isset($clientData['mac'])) {
$c = $this->clientRepository->findOneBy(['mac' => $clientData['mac']]);
if ($c) $clients[] = $c;
} elseif (isset($clientData['name'])) {
$c = $this->clientRepository->findOneBy(['name' => $clientData['name']]);
if ($c) $clients[] = $c;
} elseif (isset($clientData['ip'])) {
$c = $this->clientRepository->findOneBy(['ip' => $clientData['ip']]);
if ($c) $clients[] = $c;
}
} elseif ($ouData) {
// Búsqueda específica de Aula (OU)
if (isset($ouData['name'])) {
$ou = $this->ouRepository->findOneBy(['name' => $ouData['name']]);
if ($ou) {
$clients = $this->clientRepository->findBy(['organizationalUnit' => $ou]);
}
} elseif (isset($ouData['id'])) {
$ou = $this->ouRepository->find($ouData['id']);
if ($ou) {
$clients = $this->clientRepository->findBy(['organizationalUnit' => $ou]);
}
}
}
if (empty($clients)) {
return new JsonResponse(['error' => "No se encontró ningún cliente que coincida con los criterios."], Response::HTTP_NOT_FOUND);
}
$count = 0;
$errors = [];
foreach ($clients as $client) {
/** @var Client $client */
$bootServer = $client->getBootServer() ?? $client->getOrganizationalUnit()?->getNetworkSettings()?->getBootServer();
if (!$bootServer) {
$errors[] = "El cliente {$client->getName()} no tiene un servidor de arranque asignado.";
continue;
}
/** @var PxeTemplate|null $template */
$template = $this->pxeTemplateRepository->findOneBy([
'name' => $templateName,
'bootServer' => $bootServer
]);
if (!$template) {
$errors[] = "No se encontró la plantilla '$templateName' en el servidor {$bootServer->getName()} para el cliente {$client->getName()}.";
continue;
}
if ($mode == 1) {
// MODO PERMANENTE: Actualizamos el objeto (PostAction hará el flush)
$client->setTemplate($template);
}
// Generar el fichero PXE
try {
$this->postPxeAction->__invoke($client, $template);
$count++;
if ($mode == 0) {
$projectDir = $this->getParameter('kernel.project_dir');
$mac = $client->getMac();
$cmd = sprintf('php %s/bin/console opengnsys:pxe:sync %s 60 > /dev/null 2>&1 &', $projectDir,escapeshellarg($mac));
exec($cmd);
}
} catch (\Exception $e) {
$errors[] = "Error en {$client->getName()}: " . $e->getMessage();
}
}
return new JsonResponse([
'status' => count($errors) > 0 && $count == 0 ? 'error' : 'success',
'clients_processed' => $count,
'errors' => $errors,
'mode' => ($mode == 1 ? 'PERMANENT' : 'TEMPORARY')
]);
}
}