feat(ogcore): infraestructura journal-pull y endpoint de logs de disco #119

Merged
narenas merged 23 commits from devel into main 2026-05-18 15:50:07 +02:00
20 changed files with 453 additions and 16 deletions

View File

@ -1,5 +1,57 @@
# Changelog
## [1.8.2] - 2026-05-18
### Improved
- Modificada accion RemoveCacheImage para montar la cache y luego eliminar la imagen deseada
## [1.8.1] - 2026-05-18
### Fixed
- Corregido fallo setRemotePc en la entidad Imagen al sincronizar un repositorio
## [1.8.0] - 2026-05-18
### Added
- Infraestructura journal-pull: servicio plantilla `journal-pull@.service` para
extraer journals de componentes por IP vía `systemd-journal-gatewayd`, con
filtros para ogcore, ogdhcp, ogboot, ogrepo, kea, tftpd-hpa y samba
- `JournalPullService` y `JournalPullSubscriber`: habilitación y deshabilitación
automática de `journal-pull@<IP>` al registrar o eliminar un BootServer,
DhcpServer o ImageRepository desde el GUI; protección contra borrado de IP
compartida entre varios componentes en la misma máquina
- `DiskLogsAction`: soporte de múltiples `SYSLOG_IDENTIFIER` separados por coma
o en array, salida estructurada en JSON y lectura desde fichero de journal
remoto (`/var/log/journal/remote/<IP>.journal`) cuando se indica el parámetro host
- La retención de los journals remotos se delega en `systemd-journald` de cada
componente (configurado por oginstaller: 500MB máx, 10 días); los ficheros
pulled en ogcore quedan acotados sin necesidad de logrotate local
### Fixed
- `journal-pull@.service`: `Restart=always` para reconectar tras salida limpia
(sin entradas); `ExecStartPre` elimina el fichero solo si está vacío para
evitar cursor inválido tras fallos previos; `--split-mode=none` requerido
para escritura a fichero único por IP
- `JournalPullSubscriber`: al cambiar la IP de un servidor se verifica que
ninguna otra entidad usa la IP anterior antes de eliminarla del fichero de
configuración
- postinst: añadido `--no-interaction` al comando de generación de claves JWT
para evitar bloqueo en instalación desatendida
- postinst: permisos `775` en `api/var/` para evitar errores de caché de Doctrine
- postinst: permisos de acceso al journal para el usuario `opengnsys`
(`systemd-journal` y `systemd-journal-remote`)
- postinst (upgrade): añadidos symlinks faltantes en actualizaciones —
`mercure.conf` en nginx, unidades `journal-pull@`, `journal-pull-sync`;
`chmod +x` en `journal-pull-sync.sh`; propietario y permisos de
`journal-pull-sources.conf`; cambiado `ln -s` por `ln -sf` en las
unidades journal-pull para evitar fallo cuando el fichero existe como
fichero regular en lugar de symlink
- `systemd-journal-remote` y `logrotate` añadidos como dependencias del paquete
## [1.7.12] - 2026-05-14
### Fixed
- Corregida migracion de perfiles hardware y software, los tipos de software y hardware no se guardaban en base de datos antes de tener que ser usados por los perfiles.
## [1.7.11] - 2026-05-14
### Fixed
- Corregido error "Call to undefined method App\Entity\Image::setRemotePc()" al importar una imagen desde un repositorio. La propiedad `remotePc` fue eliminada de la entidad `Image` en la versión 1.7.0 pero la llamada a `setRemotePc()` no fue eliminada del controlador `ImportAction`.

View File

@ -61,6 +61,19 @@ pipeline {
}
}
stage('Generate Changelog (Devel)') {
when {
branch 'devel'
}
steps {
script {
def devName = params.DEV_NAME ? params.DEV_NAME : env.DEFAULT_DEV_NAME
def devEmail = params.DEV_EMAIL ? params.DEV_EMAIL : env.DEFAULT_DEV_EMAIL
generateDebianChangelog(env.BUILD_DIR, devName, devEmail, "devel")
}
}
}
stage('Build') {
steps {
script {
@ -96,6 +109,19 @@ pipeline {
}
}
}
stage ('Publish to Debian Repository (Devel)') {
when {
branch 'devel'
}
agent { label 'debian-repo' }
steps {
script {
def versionPattern = "-${env.BUILD_NUMBER}~devel"
publicarEnAptly('/var/tmp/opengnsys/debian-repo/ogcore', 'devel', versionPattern)
}
}
}
}
post {
success {
@ -108,6 +134,13 @@ pipeline {
string(name: 'TRIGGERED_BY', value: "${env.JOB_NAME}-${env.BUILD_NUMBER}")
]
}
if (env.BRANCH_NAME == 'devel') {
build job: 'Aptly publish develop repository',
wait: false,
parameters: [
string(name: 'TRIGGERED_BY', value: "${env.JOB_NAME}-${env.BUILD_NUMBER}")
]
}
}
}

2
debian/control vendored
View File

@ -10,7 +10,7 @@ Architecture: all
Depends: ${misc:Depends}, mariadb-server, systemd, nginx, libzip-dev, zip, unzip,
php8.3-opcache, php8.3-bcmath, php8.3-cli, php8.3-curl, php8.3-fpm,
php8.3-gd, php8.3-ldap, php8.3-mbstring, php8.3-mysql, php8.3-common,
php8.3-xml, php8.3-zip, mercure
php8.3-xml, php8.3-zip, mercure, systemd-journal-remote, logrotate
Description: OpenGnsys Core
OgCore package is responsible about management of Opengnsys platform
OpenGnsys Core is a platform for system management.

View File

@ -54,7 +54,7 @@ if [ "$1" = "configure" ] && [ -z "$2" ]; then
echo ">>> Creando par de claves para JWT"
php bin/console lexik:jwt:generate-keypair --overwrite
php bin/console lexik:jwt:generate-keypair --overwrite --no-interaction
echo ">>> Creando base de datos"
php bin/console doctrine:database:create --if-not-exists
@ -79,12 +79,28 @@ if [ "$1" = "configure" ] && [ -z "$2" ]; then
ln -s /opt/opengnsys/ogcore/etc/nginx/sites-available/mercure.conf /etc/nginx/sites-enabled/mercure.conf
ln -s /opt/opengnsys/ogcore/etc/php/8.3/fpm/pool.d/ogcore-fpm.conf /etc/php/8.3/fpm/pool.d/ogcore-fpm.conf
ln -s /opt/opengnsys/ogcore/etc/systemd/system/og-mercure.service /etc/systemd/system/og-mercure.service
ln -s /opt/opengnsys/ogcore/etc/systemd/system/journal-pull@.service /etc/systemd/system/journal-pull@.service
ln -s /opt/opengnsys/ogcore/etc/systemd/system/journal-pull-sync.path /etc/systemd/system/journal-pull-sync.path
ln -s /opt/opengnsys/ogcore/etc/systemd/system/journal-pull-sync.service /etc/systemd/system/journal-pull-sync.service
ln -s /opt/opengnsys/ogcore/etc/logrotate.d/ogclients /etc/logrotate.d/ogclients
chown root:root /opt/opengnsys/ogcore/etc/logrotate.d/ogclients
echo ">>> Configurando journal-pull"
touch /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
chmod +x /opt/opengnsys/ogcore/etc/bin/journal-pull-sync.sh
mkdir -p /var/log/journal/remote
chown systemd-journal-remote:systemd-journal-remote /var/log/journal/remote
echo ">>> Configurando permisos de archivos"
chown opengnsys:www-data /opt/opengnsys/
chown -R opengnsys:www-data /opt/opengnsys/ogcore
chmod -R 775 /opt/opengnsys/ogcore/api/var/
chown www-data:www-data /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
chmod 664 /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
usermod -aG systemd-journal opengnsys
usermod -aG systemd-journal-remote opengnsys
systemctl daemon-reload
systemctl enable og-mercure
systemctl enable --now journal-pull-sync.path
systemctl restart mariadb.service
systemctl restart og-mercure
systemctl restart nginx
@ -143,8 +159,21 @@ elif [ "$1" = "configure" ] && [ -n "$2" ]; then
php bin/console cache:clear
echo ">>> Configurando servidor web y servicios"
[ ! -L /etc/nginx/sites-enabled/ogcore.conf ] && ln -s /opt/opengnsys/ogcore/etc/nginx/sites-available/ogcore.conf /etc/nginx/sites-enabled/ogcore.conf
[ ! -L /etc/nginx/sites-enabled/mercure.conf ] && ln -s /opt/opengnsys/ogcore/etc/nginx/sites-available/mercure.conf /etc/nginx/sites-enabled/mercure.conf
[ ! -L /etc/php/8.3/fpm/pool.d/ogcore-fpm.conf ] && ln -s /opt/opengnsys/ogcore/etc/php/8.3/fpm/pool.d/ogcore-fpm.conf /etc/php/8.3/fpm/pool.d/ogcore-fpm.conf
[ ! -L /etc/systemd/system/og-mercure.service ] && ln -s /opt/opengnsys/ogcore/etc/systemd/system/og-mercure.service /etc/systemd/system/og-mercure.service
ln -sf /opt/opengnsys/ogcore/etc/systemd/system/journal-pull@.service /etc/systemd/system/journal-pull@.service
ln -sf /opt/opengnsys/ogcore/etc/systemd/system/journal-pull-sync.path /etc/systemd/system/journal-pull-sync.path
ln -sf /opt/opengnsys/ogcore/etc/systemd/system/journal-pull-sync.service /etc/systemd/system/journal-pull-sync.service
ln -sf /opt/opengnsys/ogcore/etc/logrotate.d/ogclients /etc/logrotate.d/ogclients
chown root:root /opt/opengnsys/ogcore/etc/logrotate.d/ogclients
chmod +x /opt/opengnsys/ogcore/etc/bin/journal-pull-sync.sh
if [ ! -f /opt/opengnsys/ogcore/etc/journal-pull-sources.conf ]; then
touch /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
chown www-data:www-data /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
chmod 664 /opt/opengnsys/ogcore/etc/journal-pull-sources.conf
fi
[ ! -d /var/log/journal/remote ] && mkdir -p /var/log/journal/remote && chown systemd-journal-remote:systemd-journal-remote /var/log/journal/remote
echo ">>> Configurando permisos de archivos"
chown opengnsys:www-data /opt/opengnsys/
chown -R opengnsys:www-data /opt/opengnsys/ogcore
@ -159,6 +188,10 @@ elif [ "$1" = "configure" ] && [ -n "$2" ]; then
chown root:root /etc/cron.d/opengnsys-check-clients
fi
systemctl enable og-mercure
systemctl enable --now journal-pull-sync.path 2>/dev/null || true
usermod -aG systemd-journal opengnsys 2>/dev/null || true
usermod -aG systemd-journal-remote opengnsys 2>/dev/null || true
chmod -R 775 /opt/opengnsys/ogcore/api/var/ 2>/dev/null || true
systemctl daemon-reload
systemctl restart og-mercure
systemctl restart php8.3-fpm

View File

@ -0,0 +1,30 @@
#!/bin/bash
# Syncs journal-pull@ systemd instances with /etc/opengnsys/journal-pull-sources.conf.
# Triggered by journal-pull-sync.path whenever the config file changes.
set -euo pipefail
CONF=/opt/opengnsys/ogcore/etc/journal-pull-sources.conf
[[ -f "$CONF" ]] || exit 0
mapfile -t WANTED < <(grep -v '^\s*#' "$CONF" | grep -v '^\s*$' | sort -u)
mapfile -t CURRENT < <(
systemctl list-units 'journal-pull@*.service' --all --plain --no-legend \
| awk '{print $1}' | sed 's/journal-pull@//;s/\.service//' | sort -u
)
for ip in "${WANTED[@]:-}"; do
[[ -z "$ip" ]] && continue
if ! printf '%s\n' "${CURRENT[@]:-}" | grep -qxF "$ip"; then
systemctl enable --now "journal-pull@${ip}.service"
echo "journal-pull-sync: enabled journal-pull@${ip}"
fi
done
for ip in "${CURRENT[@]:-}"; do
[[ -z "$ip" ]] && continue
if ! printf '%s\n' "${WANTED[@]:-}" | grep -qxF "$ip"; then
systemctl disable --now "journal-pull@${ip}.service"
echo "journal-pull-sync: disabled journal-pull@${ip}"
fi
done

View File

@ -0,0 +1,9 @@
/var/log/ogclients/*/*.log {
daily
rotate 10
compress
missingok
copytruncate
dateext
delaycompress
}

View File

@ -0,0 +1,8 @@
[Unit]
Description=Watch journal-pull sources config
[Path]
PathModified=/opt/opengnsys/ogcore/etc/journal-pull-sources.conf
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,7 @@
[Unit]
Description=Sync journal-pull instances from config
After=network-online.target
[Service]
Type=oneshot
ExecStart=/opt/opengnsys/ogcore/etc/bin/journal-pull-sync.sh

View File

@ -0,0 +1,15 @@
[Unit]
Description=Pull OpenGNSYS journal from %i
After=network-online.target
Wants=network-online.target
[Service]
User=systemd-journal-remote
Group=systemd-journal-remote
ExecStartPre=/bin/sh -c 'f=/var/log/journal/remote/%i.journal; [ -f "$f" ] && journalctl --file="$f" -n 1 --no-pager 2>/dev/null | grep -q "." || rm -f "$f"'
ExecStart=/usr/lib/systemd/systemd-journal-remote --url=http://%i:19531/entries?SYSLOG_IDENTIFIER=ogcore&SYSLOG_IDENTIFIER=oggui&SYSLOG_IDENTIFIER=ogdhcp&SYSLOG_IDENTIFIER=ogboot&SYSLOG_IDENTIFIER=ogrepo-api&SYSLOG_IDENTIFIER=ogrepo-api_DEBUG&SYSLOG_IDENTIFIER=kea-dhcp4&SYSLOG_IDENTIFIER=kea-ctrl-agent&SYSLOG_IDENTIFIER=DhcpLFC&SYSLOG_IDENTIFIER=kea-dhcp6&SYSLOG_IDENTIFIER=tftpd-hpa&SYSLOG_IDENTIFIER=%%28smbd%%29&SYSLOG_IDENTIFIER=%%28nmbd%%29 --split-mode=none --output=/var/log/journal/remote/%i.journal
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target

View File

@ -59,6 +59,7 @@ class MigrateHardwareAndHardwareProfileCommand extends Command
$this->entityManager->persist($hardwareProfileEntity);
}
$this->entityManager->flush();
/** Obtener los hardware de la base de datos antigua **/
$rsmHardware = new ResultSetMapping();
@ -97,6 +98,7 @@ class MigrateHardwareAndHardwareProfileCommand extends Command
$this->entityManager->persist($hardwareEntity);
}
$this->entityManager->flush();
/**
* In OpenGnsys 2.0, HardwareProfile is linked OneToOne with Client and is mandatory.

View File

@ -7,6 +7,7 @@ namespace App\Command\Migration;
use App\Entity\Client;
use App\Entity\Image;
use App\Entity\ImageRepository;
use App\Entity\ImageImageRepository;
use App\Entity\OrganizationalUnit;
use App\Model\ImageStatus;
use App\Model\OrganizationalUnitTypes;
@ -80,16 +81,20 @@ class MigrateImagesCommand extends Command
$imageEntity->setMigrationId((string) $image['idimagen']);
$imageEntity->setName($image['nombreca']);
$imageEntity->setClient($clientEntity);
//$imageEntity->setOrganizationalUnit($ouEntity);
$imageEntity->setRemotePc(false);
$imageEntity->setStatus(ImageStatus::SUCCESS);
$imageEntity->setRepository($repository);
$imageEntity->setRevision((string) $image['revision']);
$imageEntity->setDescription($image['descripcion']);
$imageEntity->setComments($image['comentarios']);
}
$imageEntity->setType('monolithic');
$imageEntity->setIsGlobal(false);
$this->entityManager->persist($imageEntity);
$this->entityManager->persist($imageEntity);
$imageImageRepository = new ImageImageRepository();
$imageImageRepository->setImage($imageEntity);
$imageImageRepository->setRepository($repository);
$imageImageRepository->setName($image['nombreca']);
$imageImageRepository->setStatus(ImageStatus::SUCCESS);
$imageImageRepository->setVersion(is_numeric($image['revision']) ? (int) $image['revision'] : null);
$imageImageRepository->setDescription($image['descripcion']);
$imageImageRepository->setRemotePc(false);
$this->entityManager->persist($imageImageRepository);
}
$this->entityManager->flush();
}

View File

@ -73,6 +73,7 @@ class MigrateSoftwareAndSoftwareProfileCommand extends Command
$this->entityManager->persist($softwareEntity);
}
$this->entityManager->flush();
/** Obtener los perfiles software de la base de datos antigua **/
$rsmSoftwareProfiles = new ResultSetMapping();
@ -104,6 +105,7 @@ class MigrateSoftwareAndSoftwareProfileCommand extends Command
$this->entityManager->persist($softwareProfileEntity);
}
$this->entityManager->flush();
/** Obtener los software, y asignarselos a los perfiles software **/
$rsmSoftwareProfilesRelation = new ResultSetMapping();

View File

@ -42,7 +42,7 @@ class RemoveCacheImageAction extends AbstractOgAgentController
continue;
}
$script = 'rm -r /opt/opengnsys/cache/opt/opengnsys/images/' . escapeshellarg($input->imageName) . '*';
$script = 'ogMountCache && rm -r /opt/opengnsys/cache/opt/opengnsys/images/' . escapeshellarg($input->imageName) . '*';
$data = [
'nfn' => 'EjecutarScript',

View File

@ -41,7 +41,6 @@ class ConvertAction extends AbstractOgRepositoryController
$imageEntity = new Image();
$imageEntity->setName($image);
$imageEntity->setType('monolithic');
$imageEntity->setRemotePc(false);
$imageEntity->setIsGlobal(false);
$this->entityManager->persist($imageEntity);
@ -59,6 +58,7 @@ class ConvertAction extends AbstractOgRepositoryController
$imageImageRepositoryEntity->setImage($imageEntity);
$imageImageRepositoryEntity->setRepository($repository);
$imageImageRepositoryEntity->setVersion(1);
$imageImageRepositoryEntity->setRemotePc(false);
$this->entityManager->persist($imageImageRepositoryEntity);

View File

@ -50,7 +50,6 @@ class SyncAction extends AbstractOgRepositoryController
if (!$imageEntity) {
$imageEntity = new Image();
$imageEntity->setName($image['name']);
$imageEntity->setRemotePc(false);
$imageEntity->setIsGlobal(false);
$imageEntity->setType('monolithic');
@ -68,6 +67,7 @@ class SyncAction extends AbstractOgRepositoryController
$imageImageRepositoryEntity->setDatasize(isset($image['datasize']) ? (string) $image['datasize'] : null);
$imageImageRepositoryEntity->setSize(isset($image['size']) ? (string) $image['size'] : null);
$imageImageRepositoryEntity->setStatus(ImageStatus::SUCCESS);
$imageImageRepositoryEntity->setRemotePc(false);
$this->entityManager->persist($imageImageRepositoryEntity);
}

View File

@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace App\Controller\System;
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 DiskLogsAction extends AbstractController
{
private const REMOTE_JOURNAL_DIR = '/var/log/journal/remote';
#[Route('/opengnsys/system/disk-logs', name: 'api_system_disk_logs', methods: ['GET'])]
#[IsGranted('ROLE_USER')]
public function __invoke(Request $request): JsonResponse
{
// Acepta SYSLOG_IDENTIFIER como valor único, array (?SYSLOG_IDENTIFIER[]=a&SYSLOG_IDENTIFIER[]=b)
// o lista separada por comas (?SYSLOG_IDENTIFIER=a,b)
$rawIdentifiers = $request->query->all()['SYSLOG_IDENTIFIER'] ?? $request->query->get('SYSLOG_IDENTIFIER');
if (is_string($rawIdentifiers)) {
$rawIdentifiers = array_map('trim', explode(',', $rawIdentifiers));
}
$identifiers = array_values(array_filter((array) $rawIdentifiers));
$host = $request->query->get('host');
$lines = $request->query->getInt('lines', 100);
if (empty($identifiers)) {
return new JsonResponse(['error' => 'El parámetro SYSLOG_IDENTIFIER es obligatorio.'], Response::HTTP_BAD_REQUEST);
}
$lines = max(1, min(1000, $lines));
$args = ['--no-pager', '--output=json', sprintf('-n %d', $lines)];
if ($host) {
// Host remoto: leer del fichero journal nombrado por IP
$journalFile = sprintf('%s/%s.journal', self::REMOTE_JOURNAL_DIR, $host);
if (!file_exists($journalFile)) {
return new JsonResponse(
['error' => sprintf('No se encontró el journal para el host %s', $host)],
Response::HTTP_NOT_FOUND
);
}
$args[] = sprintf('--file=%s', escapeshellarg($journalFile));
}
// Múltiples SYSLOG_IDENTIFIER se pasan como matches separados → journalctl los aplica con OR
foreach ($identifiers as $identifier) {
$args[] = sprintf('SYSLOG_IDENTIFIER=%s', escapeshellarg($identifier));
}
$command = sprintf('journalctl %s 2>&1', implode(' ', $args));
$output = [];
$returnVar = 0;
exec($command, $output, $returnVar);
if ($returnVar !== 0) {
return new JsonResponse([
'error' => 'Error al ejecutar journalctl',
'output' => implode("\n", $output)
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
// Parsear cada línea como JSON (formato --output=json de journalctl)
$entries = array_values(array_filter(array_map(
static fn(string $line) => json_decode($line, true),
$output
)));
return new JsonResponse([
'identifiers' => $identifiers,
'host' => $host ?? 'local',
'lines' => count($entries),
'entries' => $entries,
]);
}
}

View File

@ -51,7 +51,7 @@ final class HardwareOutput extends AbstractOutput
$this->name = $hardware->getName();
$this->description = $hardware->getDescription();
$this->type = new HardwareTypeOutput($hardware->getType());
$this->type = $hardware->getType() ? new HardwareTypeOutput($hardware->getType()) : null;
$this->createdAt = $hardware->getCreatedAt();
$this->createdBy = $hardware->getCreatedBy();
}

View File

@ -0,0 +1,102 @@
<?php
namespace App\EventSubscriber;
use App\Entity\BootServer;
use App\Entity\DhcpServer;
use App\Entity\ImageRepository;
use App\Service\JournalPullService;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\PostPersistEventArgs;
use Doctrine\ORM\Event\PostRemoveEventArgs;
use Doctrine\ORM\Event\PostUpdateEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
#[AsDoctrineListener(event: Events::postPersist)]
#[AsDoctrineListener(event: Events::postRemove)]
#[AsDoctrineListener(event: Events::preUpdate)]
#[AsDoctrineListener(event: Events::postUpdate)]
class JournalPullSubscriber
{
/** @var array<int, array{old: string, new: string}> */
private array $pendingIpChanges = [];
public function __construct(
private readonly JournalPullService $journalPullService,
private readonly EntityManagerInterface $entityManager,
) {}
private function supports(object $entity): bool
{
return $entity instanceof BootServer
|| $entity instanceof DhcpServer
|| $entity instanceof ImageRepository;
}
public function postPersist(PostPersistEventArgs $args): void
{
$entity = $args->getObject();
if (!$this->supports($entity)) {
return;
}
$this->journalPullService->add($entity->getIp());
}
public function postRemove(PostRemoveEventArgs $args): void
{
$entity = $args->getObject();
if (!$this->supports($entity)) {
return;
}
if (!$this->isIpStillInUse($entity->getIp(), $entity)) {
$this->journalPullService->remove($entity->getIp());
}
}
private function isIpStillInUse(string $ip, object $excludedEntity): bool
{
$types = [BootServer::class, DhcpServer::class, ImageRepository::class];
foreach ($types as $class) {
$results = $this->entityManager->getRepository($class)->findBy(['ip' => $ip]);
foreach ($results as $entity) {
if ($entity !== $excludedEntity) {
return true;
}
}
}
return false;
}
public function preUpdate(PreUpdateEventArgs $args): void
{
$entity = $args->getObject();
if (!$this->supports($entity) || !$args->hasChangedField('ip')) {
return;
}
$this->pendingIpChanges[spl_object_id($entity)] = [
'old' => $args->getOldValue('ip'),
'new' => $args->getNewValue('ip'),
];
}
public function postUpdate(PostUpdateEventArgs $args): void
{
$entity = $args->getObject();
if (!$this->supports($entity)) {
return;
}
$oid = spl_object_id($entity);
if (!isset($this->pendingIpChanges[$oid])) {
return;
}
['old' => $oldIp, 'new' => $newIp] = $this->pendingIpChanges[$oid];
unset($this->pendingIpChanges[$oid]);
if (!$this->isIpStillInUse($oldIp, $entity)) {
$this->journalPullService->remove($oldIp);
}
$this->journalPullService->add($newIp);
}
}

View File

@ -38,7 +38,6 @@ final class ImageFactory extends ModelFactory
'softwareProfile' => SoftwareProfileFactory::new(),
'updatedAt' => self::faker()->dateTime(),
'type' => 'monolithic',
'remotePc' => self::faker()->boolean(),
'isGlobal' => false,
];
}

View File

@ -0,0 +1,56 @@
<?php
namespace App\Service;
use Psr\Log\LoggerInterface;
class JournalPullService
{
private const CONFIG_FILE = '/opt/opengnsys/ogcore/etc/journal-pull-sources.conf';
public function __construct(private readonly LoggerInterface $logger) {}
public function add(string $ip): void
{
$ips = $this->readIps();
if (in_array($ip, $ips, true)) {
return;
}
$ips[] = $ip;
$this->writeIps($ips);
$this->logger->info('journal-pull: added {ip}', ['ip' => $ip]);
}
public function remove(string $ip): void
{
$ips = $this->readIps();
$filtered = array_values(array_filter($ips, fn($i) => $i !== $ip));
if (count($filtered) === count($ips)) {
return;
}
$this->writeIps($filtered);
$this->logger->info('journal-pull: removed {ip}', ['ip' => $ip]);
}
private function readIps(): array
{
if (!file_exists(self::CONFIG_FILE)) {
return [];
}
$lines = file(self::CONFIG_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
return array_values(array_filter($lines, fn($l) => !str_starts_with(trim($l), '#')));
}
private function writeIps(array $ips): void
{
$dir = dirname(self::CONFIG_FILE);
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
file_put_contents(
self::CONFIG_FILE,
$ips ? implode("\n", $ips) . "\n" : '',
LOCK_EX
);
}
}