Files
MageSail/Magesail/Cron/DailyMonitor.php
T
2026-03-21 03:01:08 -05:00

76 lines
2.8 KiB
PHP

<?php
declare(strict_types=1);
namespace MageSail\Magesail\Cron;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Psr\Log\LoggerInterface;
use MageSail\Magesail\Model\MagesailLog;
use MageSail\Magesail\Model\TunnelManager;
use MageSail\Magesail\Model\TunnelProcessPaths;
use MageSail\Magesail\Model\TunnelRegistry;
use MageSail\Magesail\Model\TunnelStatus;
class DailyMonitor
{
private const XML_AUTO_RESTART = 'magesail/settings/auto_restart';
public function __construct(
private readonly LoggerInterface $logger,
private readonly TunnelStatus $tunnelStatus,
private readonly TunnelManager $tunnelManager,
private readonly ScopeConfigInterface $scopeConfig,
private readonly MagesailLog $magesailLog,
private readonly TunnelRegistry $tunnelRegistry,
private readonly TunnelProcessPaths $tunnelProcessPaths
) {
}
public function execute(): void
{
$autoRestart = (bool) $this->scopeConfig->getValue(self::XML_AUTO_RESTART);
foreach ($this->tunnelRegistry->listTunnels() as $tunnel) {
$tunnelId = (string) ($tunnel['id'] ?? '');
if ($tunnelId === '') {
continue;
}
$pidFile = $this->tunnelProcessPaths->getPidFilePath($tunnelId);
if (!\is_file($pidFile)) {
continue;
}
$pid = (int) trim((string) file_get_contents($pidFile));
$wasRunning = $pid > 0 && $this->tunnelStatus->isProcessAlive($pid);
if ($wasRunning) {
continue;
}
$this->tunnelStatus->cleanupStaleStateForTunnel($tunnelId);
$this->magesailLog->add(sprintf('Cron: tunnel %s process gone; cleaned PID/key files', $tunnelId));
$this->logger->warning(sprintf('MageSail tunnel %s crashed; cleaned up PID files.', $tunnelId));
if ($autoRestart) {
$result = $this->tunnelManager->start($tunnelId);
if ($result['ok'] ?? false) {
$this->magesailLog->add(sprintf('Cron auto-restart OK tunnel %s PID %s', $tunnelId, $result['pid'] ?? ''));
$this->logger->info(sprintf('MageSail tunnel %s auto-restarted by cron.', $tunnelId));
} else {
$this->magesailLog->add(sprintf(
'Cron auto-restart failed tunnel %s: %s',
$tunnelId,
$result['error'] ?? 'unknown'
));
$this->logger->warning(sprintf(
'MageSail auto-restart failed for %s: %s',
$tunnelId,
$result['error'] ?? ''
));
}
}
}
$this->logger->info('MageSail cron monitor executed.');
}
}