Files
MageSail/Magesail/Cron/DailyMonitor.php
T

64 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
namespace MageSail\Magesail\Cron;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Psr\Log\LoggerInterface;
use MageSail\Magesail\Model\MagesailLog;
use MageSail\Magesail\Model\TunnelManager;
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 DirectoryList $directoryList,
private readonly TunnelStatus $tunnelStatus,
private readonly TunnelManager $tunnelManager,
private readonly ScopeConfigInterface $scopeConfig,
private readonly MagesailLog $magesailLog
) {
}
public function execute(): void
{
$pidFile = $this->directoryList->getPath(DirectoryList::VAR_DIR) . '/magesail.pid';
$hadPidFile = \is_file($pidFile);
$wasRunning = false;
if ($hadPidFile) {
$pid = (int) trim((string) file_get_contents($pidFile));
$wasRunning = $pid > 0 && $this->tunnelStatus->isProcessAlive($pid);
}
if (!$wasRunning && $hadPidFile) {
$this->tunnelStatus->cleanupStaleState();
$this->magesailLog->add('Cron: tunnel process gone; cleaned PID/key files');
$this->logger->warning('Magesail tunnel crashed; cleaned up PID files.');
$autoRestart = (bool) $this->scopeConfig->getValue(self::XML_AUTO_RESTART);
if ($autoRestart) {
$secure = (bool) $this->scopeConfig->getValue('magesail/settings/mode');
$port = filter_var($this->scopeConfig->getValue('magesail/settings/port') ?: 80, FILTER_VALIDATE_INT);
if ($port && \in_array($port, [80, 443], true)) {
$result = $this->tunnelManager->start($port, $secure);
if ($result['ok']) {
$this->magesailLog->add(sprintf('Cron auto-restart OK PID %s', $result['pid']));
$this->logger->info('Magesail tunnel auto-restarted by cron.');
} else {
$this->magesailLog->add('Cron auto-restart failed: ' . ($result['error'] ?? 'unknown'));
$this->logger->warning('Magesail auto-restart failed: ' . ($result['error'] ?? ''));
}
} else {
$this->magesailLog->add('Cron auto-restart skipped: invalid port');
}
}
}
$this->logger->info('Magesail cron monitor executed.');
}
}