<?php
namespace Uniski\CMSBundle\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Uniski\ResourceBundle\Controller\BaseController;
/**
* Controlador de healthcheck para monitoreo de la infraestructura.
*
* Verifica: conexión a BD, PHP-FPM, y espacio en disco.
* Usado por el healthcheck de Docker y monitoreo externo.
* Migrado a BaseController (AbstractController) para Symfony 4.4
*/
class HealthController extends BaseController
{
/**
* Endpoint de healthcheck simple (para Docker healthcheck de Nginx).
* Devuelve "ok" si PHP-FPM responde.
*
* @Route("/health", name="health_check", methods={"GET"})
*/
public function healthAction()
{
$checks = array();
$allOk = true;
// 1. PHP-FPM está respondiendo (si llegamos aquí, funciona)
$checks['php_fpm'] = array(
'status' => 'ok',
'version' => PHP_VERSION,
);
// 2. Conexión a base de datos
try {
$em = $this->get('doctrine.orm.entity_manager');
$conn = $em->getConnection();
$conn->query('SELECT 1');
$checks['database'] = array(
'status' => 'ok',
'driver' => $conn->getDriver()->getName(),
);
} catch (\Exception $e) {
$checks['database'] = array(
'status' => 'error',
'message' => 'No se pudo conectar a la BD',
);
$allOk = false;
}
// 3. Espacio en disco disponible
$diskFree = disk_free_space('/var/www/uniski');
$diskTotal = disk_total_space('/var/www/uniski');
$diskUsedPercent = round((1 - ($diskFree / $diskTotal)) * 100, 1);
$diskFreeGb = round($diskFree / 1073741824, 2);
// Alerta si queda menos del 10% libre
$diskOk = $diskUsedPercent < 90;
$checks['disk'] = array(
'status' => $diskOk ? 'ok' : 'warning',
'free_gb' => $diskFreeGb,
'used_percent' => $diskUsedPercent . '%',
);
if (!$diskOk) {
$allOk = false;
}
// 4. Directorio de cache escribible
$cacheDir = $this->getParameter('kernel.cache_dir');
$cacheWritable = is_writable($cacheDir);
$checks['cache'] = array(
'status' => $cacheWritable ? 'ok' : 'error',
);
if (!$cacheWritable) {
$allOk = false;
}
$response = array(
'status' => $allOk ? 'ok' : 'degraded',
'timestamp' => date('c'),
'checks' => $checks,
);
$statusCode = $allOk ? Response::HTTP_OK : Response::HTTP_SERVICE_UNAVAILABLE;
return new JsonResponse($response, $statusCode);
}
/**
* Endpoint mínimo para healthcheck rápido de Docker.
* Solo devuelve "ok" si PHP-FPM procesa la petición.
*
* @Route("/ping", name="health_ping", methods={"GET"})
*/
public function pingAction()
{
return new Response('ok', Response::HTTP_OK, array(
'Content-Type' => 'text/plain',
));
}
}