some progress

This commit is contained in:
Doar Mihai
2026-01-17 16:42:43 +02:00
parent 030a105992
commit 3665a1d5a3
57 changed files with 5804 additions and 3 deletions
+267
View File
@@ -0,0 +1,267 @@
<?php
namespace App\Jobs;
use App\Models\DnsRecord;
use App\Notifications\DnsRecordAlert;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class CheckDnsRecord implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries = 3;
/**
* The number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout = 30;
/**
* Create a new job instance.
*/
public function __construct(
public DnsRecord $dnsRecord
) {}
/**
* Execute the job.
*/
public function handle(): void
{
try {
Log::info('CheckDnsRecord: Starting check', [
'dns_record_id' => $this->dnsRecord->id,
'domain' => $this->dnsRecord->domain,
'record_type' => $this->dnsRecord->record_type,
]);
// Perform DNS lookup
$result = $this->performDnsLookup();
$wasValid = $this->dnsRecord->is_valid;
$isValid = $result['is_valid'];
$actualValue = $result['actual_value'];
$errorMessage = $result['error_message'];
// Update DNS record
$this->dnsRecord->update([
'last_checked_at' => now(),
'is_valid' => $isValid,
'actual_value' => $actualValue,
'error_message' => $errorMessage,
]);
Log::info('CheckDnsRecord: Check completed', [
'dns_record_id' => $this->dnsRecord->id,
'is_valid' => $isValid,
'actual_value' => $actualValue,
]);
// Send notification if status changed from valid to invalid
if ($wasValid === true && $isValid === false) {
$this->dnsRecord->site->user->notify(new DnsRecordAlert(
$this->dnsRecord,
'invalid',
$actualValue,
$errorMessage
));
Log::warning('CheckDnsRecord: Invalid alert sent', [
'dns_record_id' => $this->dnsRecord->id,
'error_message' => $errorMessage,
]);
}
// Send notification when DNS is restored
if ($wasValid === false && $isValid === true) {
$this->dnsRecord->site->user->notify(new DnsRecordAlert(
$this->dnsRecord,
'valid',
$actualValue
));
Log::info('CheckDnsRecord: Valid alert sent', [
'dns_record_id' => $this->dnsRecord->id,
]);
}
} catch (\Exception $e) {
Log::error('CheckDnsRecord: Unexpected error', [
'dns_record_id' => $this->dnsRecord->id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
$this->dnsRecord->update([
'last_checked_at' => now(),
'is_valid' => false,
'error_message' => 'Unexpected error: ' . $e->getMessage(),
]);
throw $e;
}
}
/**
* Perform DNS lookup and validation.
*/
protected function performDnsLookup(): array
{
try {
// Map record type to DNS_* constant
$dnsType = $this->getDnsTypeConstant($this->dnsRecord->record_type);
if ($dnsType === null) {
return [
'is_valid' => false,
'actual_value' => null,
'error_message' => "Unsupported DNS record type: {$this->dnsRecord->record_type}",
];
}
// Perform DNS lookup
$records = @dns_get_record($this->dnsRecord->domain, $dnsType);
if ($records === false) {
$error = error_get_last();
return [
'is_valid' => false,
'actual_value' => null,
'error_message' => 'DNS lookup failed: ' . ($error['message'] ?? 'Unknown error'),
];
}
if (empty($records)) {
return [
'is_valid' => false,
'actual_value' => null,
'error_message' => "No {$this->dnsRecord->record_type} records found for {$this->dnsRecord->domain}",
];
}
// Extract values based on record type
$actualValues = $this->extractDnsValues($records, $this->dnsRecord->record_type);
// If no expected value, just return that records exist
if (empty($this->dnsRecord->expected_value)) {
return [
'is_valid' => true,
'actual_value' => $actualValues,
'error_message' => null,
];
}
// Validate against expected value
$isValid = $this->validateDnsValue($actualValues, $this->dnsRecord->expected_value);
return [
'is_valid' => $isValid,
'actual_value' => $actualValues,
'error_message' => $isValid ? null : 'DNS record does not match expected value',
];
} catch (\Exception $e) {
return [
'is_valid' => false,
'actual_value' => null,
'error_message' => 'DNS lookup error: ' . $e->getMessage(),
];
}
}
/**
* Get DNS type constant for dns_get_record().
*/
protected function getDnsTypeConstant(string $recordType): ?int
{
return match (strtoupper($recordType)) {
'A' => DNS_A,
'AAAA' => DNS_AAAA,
'CNAME' => DNS_CNAME,
'MX' => DNS_MX,
'TXT' => DNS_TXT,
'NS' => DNS_NS,
'SOA' => DNS_SOA,
'PTR' => DNS_PTR,
'SRV' => DNS_SRV,
default => null,
};
}
/**
* Extract DNS values from records.
*/
protected function extractDnsValues(array $records, string $recordType): array
{
$values = [];
foreach ($records as $record) {
$value = match (strtoupper($recordType)) {
'A' => $record['ip'] ?? null,
'AAAA' => $record['ipv6'] ?? null,
'CNAME' => $record['target'] ?? null,
'MX' => isset($record['target']) ? "{$record['pri']} {$record['target']}" : null,
'TXT' => $record['txt'] ?? null,
'NS' => $record['target'] ?? null,
'SOA' => isset($record['mname']) ? $record['mname'] : null,
'PTR' => $record['target'] ?? null,
'SRV' => isset($record['target']) ? "{$record['pri']} {$record['weight']} {$record['port']} {$record['target']}" : null,
default => null,
};
if ($value !== null) {
$values[] = $value;
}
}
return $values;
}
/**
* Validate DNS value against expected value.
*/
protected function validateDnsValue(array $actualValues, string $expectedValue): bool
{
// Normalize expected value
$expectedValue = trim($expectedValue);
// Check if any actual value matches expected
foreach ($actualValues as $actualValue) {
// Exact match
if (strcasecmp($actualValue, $expectedValue) === 0) {
return true;
}
// Partial match for MX and SRV records (check target only)
if (stripos($actualValue, $expectedValue) !== false) {
return true;
}
}
return false;
}
/**
* Handle a job failure.
*/
public function failed(\Throwable $exception): void
{
Log::error('CheckDnsRecord: Job failed after all retries', [
'dns_record_id' => $this->dnsRecord->id,
'exception' => $exception->getMessage(),
]);
}
}
+255
View File
@@ -0,0 +1,255 @@
<?php
namespace App\Jobs;
use App\Models\HealthCheck;
use App\Notifications\HealthCheckAlert;
use App\Notifications\PerformanceAlert;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class CheckHealthEndpoint implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries = 3;
/**
* The number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout = 60;
/**
* Create a new job instance.
*/
public function __construct(
public HealthCheck $healthCheck
) {}
/**
* Execute the job.
*/
public function handle(): void
{
try {
$client = new Client([
'timeout' => 10,
'connect_timeout' => 5,
'allow_redirects' => [
'max' => 3,
'track_redirects' => true,
],
'http_errors' => false,
]);
$url = $this->healthCheck->full_url;
$startTime = microtime(true);
Log::info('CheckHealthEndpoint: Starting check', [
'health_check_id' => $this->healthCheck->id,
'url' => $url,
]);
$response = $client->get($url, [
'headers' => [
'Accept' => 'application/json',
'User-Agent' => 'IsMySiteUp Health Monitor/1.0',
],
]);
$endTime = microtime(true);
$responseTime = (int) round(($endTime - $startTime) * 1000);
$statusCode = $response->getStatusCode();
$body = (string) $response->getBody();
// Try to decode JSON
$responseData = null;
$isValidJson = false;
try {
$responseData = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
$isValidJson = true;
} catch (\JsonException $e) {
Log::warning('CheckHealthEndpoint: Invalid JSON response', [
'health_check_id' => $this->healthCheck->id,
'error' => $e->getMessage(),
'body_preview' => substr($body, 0, 500),
]);
}
// Determine if endpoint is healthy
$isHealthy = $this->determineHealth($statusCode, $isValidJson, $responseData);
$wasHealthy = $this->healthCheck->is_healthy;
// Update health check record
$this->healthCheck->update([
'last_checked_at' => now(),
'is_healthy' => $isHealthy,
'response_data' => $responseData,
'response_time_ms' => $responseTime,
'status_code' => $statusCode,
]);
Log::info('CheckHealthEndpoint: Check completed', [
'health_check_id' => $this->healthCheck->id,
'is_healthy' => $isHealthy,
'status_code' => $statusCode,
'response_time_ms' => $responseTime,
]);
// Send notification if health status changed from healthy to unhealthy
if ($wasHealthy === true && $isHealthy === false) {
$this->healthCheck->site->user->notify(new HealthCheckAlert(
$this->healthCheck,
'unhealthy',
$statusCode,
$responseTime
));
Log::warning('CheckHealthEndpoint: Unhealthy alert sent', [
'health_check_id' => $this->healthCheck->id,
'status_code' => $statusCode,
]);
}
// Optionally send notification when health is restored
if ($wasHealthy === false && $isHealthy === true) {
$this->healthCheck->site->user->notify(new HealthCheckAlert(
$this->healthCheck,
'healthy',
$statusCode,
$responseTime
));
Log::info('CheckHealthEndpoint: Healthy alert sent', [
'health_check_id' => $this->healthCheck->id,
]);
}
// Check performance threshold and send alert if exceeded
if ($this->healthCheck->performance_threshold && $responseTime > $this->healthCheck->performance_threshold) {
$this->healthCheck->site->user->notify(new PerformanceAlert(
resourceType: 'Health Check',
resourceName: $this->healthCheck->endpoint,
responseTime: $responseTime,
threshold: $this->healthCheck->performance_threshold,
url: $this->healthCheck->full_url,
resourceId: $this->healthCheck->site_id
));
Log::warning('CheckHealthEndpoint: Performance threshold exceeded', [
'health_check_id' => $this->healthCheck->id,
'response_time_ms' => $responseTime,
'threshold_ms' => $this->healthCheck->performance_threshold,
]);
}
} catch (ConnectException $e) {
// Connection timeout or DNS failure
Log::error('CheckHealthEndpoint: Connection failed', [
'health_check_id' => $this->healthCheck->id,
'error' => $e->getMessage(),
]);
$this->healthCheck->update([
'last_checked_at' => now(),
'is_healthy' => false,
'response_data' => ['error' => 'Connection failed: ' . $e->getMessage()],
'response_time_ms' => null,
'status_code' => null,
]);
} catch (RequestException $e) {
// HTTP error occurred
$statusCode = $e->getResponse() ? $e->getResponse()->getStatusCode() : null;
Log::error('CheckHealthEndpoint: Request failed', [
'health_check_id' => $this->healthCheck->id,
'status_code' => $statusCode,
'error' => $e->getMessage(),
]);
$this->healthCheck->update([
'last_checked_at' => now(),
'is_healthy' => false,
'response_data' => ['error' => 'Request failed: ' . $e->getMessage()],
'response_time_ms' => null,
'status_code' => $statusCode,
]);
} catch (\Exception $e) {
// Any other exception
Log::error('CheckHealthEndpoint: Unexpected error', [
'health_check_id' => $this->healthCheck->id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
$this->healthCheck->update([
'last_checked_at' => now(),
'is_healthy' => false,
'response_data' => ['error' => 'Unexpected error: ' . $e->getMessage()],
'response_time_ms' => null,
'status_code' => null,
]);
throw $e;
}
}
/**
* Determine if the endpoint is healthy based on response.
*/
protected function determineHealth(int $statusCode, bool $isValidJson, ?array $responseData): bool
{
// Check if status code is successful (2xx)
if ($statusCode < 200 || $statusCode >= 300) {
return false;
}
// Check if response is valid JSON
if (!$isValidJson) {
return false;
}
// Validate expected JSON keys if configured
if (!empty($this->healthCheck->expected_json_keys)) {
if (!$this->healthCheck->validateResponseKeys($responseData ?? [])) {
Log::warning('CheckHealthEndpoint: Missing expected JSON keys', [
'health_check_id' => $this->healthCheck->id,
'expected_keys' => $this->healthCheck->expected_json_keys,
'response_keys' => array_keys($responseData ?? []),
]);
return false;
}
}
return true;
}
/**
* Handle a job failure.
*/
public function failed(\Throwable $exception): void
{
Log::error('CheckHealthEndpoint: Job failed after all retries', [
'health_check_id' => $this->healthCheck->id,
'exception' => $exception->getMessage(),
]);
}
}
+261
View File
@@ -0,0 +1,261 @@
<?php
namespace App\Jobs;
use App\Models\Site;
use App\Models\UptimeCheck;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class CheckSitePing implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries = 3;
/**
* The number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout = 60;
/**
* Create a new job instance.
*/
public function __construct(
public Site $site
) {}
/**
* Execute the job.
*/
public function handle(): void
{
try {
$host = $this->extractHost($this->site->url);
if (!$host) {
Log::error('CheckSitePing: Invalid URL', [
'site_id' => $this->site->id,
'url' => $this->site->url,
]);
// Record failed check due to invalid URL
UptimeCheck::create([
'site_id' => $this->site->id,
'check_type' => 'ping',
'status_code' => null,
'response_time_ms' => null,
'is_online' => false,
'checked_at' => now(),
]);
return;
}
$result = $this->ping($host);
Log::info('CheckSitePing: Raw result', [
'site_id' => $this->site->id,
'host' => $host,
'result' => $result,
]);
UptimeCheck::create([
'site_id' => $this->site->id,
'check_type' => 'ping',
'status_code' => null, // ICMP doesn't have HTTP status codes
'response_time_ms' => $result['avg_time'],
'is_online' => $result['is_online'],
'checked_at' => now(),
]);
Log::info('CheckSitePing: Ping completed', [
'site_id' => $this->site->id,
'host' => $host,
'is_online' => $result['is_online'],
'avg_time' => $result['avg_time'],
]);
} catch (\Exception $e) {
Log::error('CheckSitePing: Failed', [
'site_id' => $this->site->id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
// Record failed check
UptimeCheck::create([
'site_id' => $this->site->id,
'check_type' => 'ping',
'status_code' => null,
'response_time_ms' => null,
'is_online' => false,
'checked_at' => now(),
]);
throw $e;
}
}
/**
* Extract host from URL.
*/
protected function extractHost(string $url): ?string
{
$parsed = parse_url($url);
return $parsed['host'] ?? null;
}
/**
* Execute ping command and parse results.
*/
protected function ping(string $host): array
{
$isWindows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
// Check if ping command exists
$pingPath = $this->findPingCommand($isWindows);
if (!$pingPath) {
// Ping command not found, use TCP connection as fallback
Log::warning('CheckSitePing: ping command not found, using TCP fallback', [
'site_id' => $this->site->id,
'host' => $host,
]);
return $this->tcpCheck($host);
}
// Build ping command based on OS
if ($isWindows) {
$command = sprintf('%s -n 4 %s 2>&1', $pingPath, escapeshellarg($host));
} else {
$command = sprintf('%s -c 4 -W 5 %s 2>&1', $pingPath, escapeshellarg($host));
}
$output = [];
$returnVar = 0;
exec($command, $output, $returnVar);
$isOnline = $returnVar === 0;
$avgTime = null;
// Parse average response time
if ($isOnline) {
$avgTime = $this->parseAverageTime($output, $isWindows);
}
return [
'is_online' => $isOnline,
'avg_time' => $avgTime,
'output' => implode("\n", $output),
'return_code' => $returnVar,
'command' => $command,
];
}
/**
* Find ping command path.
*/
protected function findPingCommand(bool $isWindows): ?string
{
if ($isWindows) {
return 'ping';
}
// Check common Linux locations
$locations = ['/bin/ping', '/usr/bin/ping', '/sbin/ping', '/usr/sbin/ping'];
foreach ($locations as $location) {
if (file_exists($location) && is_executable($location)) {
return $location;
}
}
// Try to find using which
exec('which ping 2>&1', $whichOutput, $whichReturn);
if ($whichReturn === 0 && !empty($whichOutput[0])) {
return trim($whichOutput[0]);
}
return null;
}
/**
* TCP connection check as fallback when ping is not available.
*/
protected function tcpCheck(string $host): array
{
$port = 80;
$timeout = 5;
$startTime = microtime(true);
$fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
$endTime = microtime(true);
$responseTime = (int) round(($endTime - $startTime) * 1000);
$isOnline = $fp !== false;
if ($fp) {
fclose($fp);
}
return [
'is_online' => $isOnline,
'avg_time' => $isOnline ? $responseTime : null,
'output' => $isOnline ? "TCP connection successful on port {$port}" : "TCP connection failed: {$errstr}",
'return_code' => $isOnline ? 0 : $errno,
'command' => "fsockopen({$host}, {$port}, {$timeout}s)",
];
}
/**
* Parse average response time from ping output.
*/
protected function parseAverageTime(array $output, bool $isWindows): ?int
{
$outputText = implode("\n", $output);
if ($isWindows) {
// Windows format: "Average = 23ms"
if (preg_match('/Average\s*=\s*(\d+)ms/i', $outputText, $matches)) {
return (int) $matches[1];
}
} else {
// Linux format: "rtt min/avg/max/mdev = 12.345/23.456/34.567/8.901 ms"
if (preg_match('/rtt min\/avg\/max\/mdev = [\d.]+\/([\d.]+)\/[\d.]+\/[\d.]+ ms/i', $outputText, $matches)) {
return (int) round((float) $matches[1]);
}
// Alternative Linux format: "round-trip min/avg/max = 12.345/23.456/34.567 ms"
if (preg_match('/round-trip min\/avg\/max = [\d.]+\/([\d.]+)\/[\d.]+ ms/i', $outputText, $matches)) {
return (int) round((float) $matches[1]);
}
}
return null;
}
/**
* Handle a job failure.
*/
public function failed(\Throwable $exception): void
{
Log::error('CheckSitePing: Job failed after all retries', [
'site_id' => $this->site->id,
'exception' => $exception->getMessage(),
]);
}
}
+185
View File
@@ -0,0 +1,185 @@
<?php
namespace App\Jobs;
use App\Models\TcpPort;
use App\Notifications\TcpPortAlert;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class CheckTcpPort implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries = 3;
/**
* The number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout = 30;
/**
* Create a new job instance.
*/
public function __construct(
public TcpPort $tcpPort
) {}
/**
* Execute the job.
*/
public function handle(): void
{
try {
$host = $this->extractHost($this->tcpPort->site->url);
if (!$host) {
Log::error('CheckTcpPort: Invalid URL', [
'tcp_port_id' => $this->tcpPort->id,
'site_id' => $this->tcpPort->site_id,
'url' => $this->tcpPort->site->url,
]);
$this->tcpPort->update([
'is_open' => false,
'response_time_ms' => null,
'last_checked_at' => now(),
]);
return;
}
$result = $this->checkPort($host, $this->tcpPort->port);
$wasOpen = $this->tcpPort->is_open;
$this->tcpPort->update([
'is_open' => $result['is_open'],
'response_time_ms' => $result['response_time'],
'last_checked_at' => now(),
]);
Log::info('CheckTcpPort: Check completed', [
'tcp_port_id' => $this->tcpPort->id,
'site_id' => $this->tcpPort->site_id,
'host' => $host,
'port' => $this->tcpPort->port,
'is_open' => $result['is_open'],
'response_time_ms' => $result['response_time'],
]);
// Send notification if port status changed from open to closed
if ($wasOpen === true && $result['is_open'] === false) {
$this->tcpPort->site->user->notify(new TcpPortAlert(
$this->tcpPort,
'closed'
));
Log::warning('CheckTcpPort: Port closed alert sent', [
'tcp_port_id' => $this->tcpPort->id,
'port' => $this->tcpPort->port,
]);
}
// Optionally send notification if port opened
if ($wasOpen === false && $result['is_open'] === true) {
$this->tcpPort->site->user->notify(new TcpPortAlert(
$this->tcpPort,
'opened'
));
Log::info('CheckTcpPort: Port opened alert sent', [
'tcp_port_id' => $this->tcpPort->id,
'port' => $this->tcpPort->port,
]);
}
} catch (\Exception $e) {
Log::error('CheckTcpPort: Failed', [
'tcp_port_id' => $this->tcpPort->id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
$this->tcpPort->update([
'is_open' => false,
'response_time_ms' => null,
'last_checked_at' => now(),
]);
throw $e;
}
}
/**
* Extract host from URL.
*/
protected function extractHost(string $url): ?string
{
$parsed = parse_url($url);
return $parsed['host'] ?? null;
}
/**
* Check if a TCP port is open.
*/
protected function checkPort(string $host, int $port): array
{
$timeout = 5;
$startTime = microtime(true);
$errno = 0;
$errstr = '';
// Suppress warnings and capture errors
$fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
$endTime = microtime(true);
$responseTime = (int) round(($endTime - $startTime) * 1000);
$isOpen = $fp !== false;
if ($fp) {
fclose($fp);
}
if (!$isOpen) {
Log::debug('CheckTcpPort: Port check failed', [
'host' => $host,
'port' => $port,
'errno' => $errno,
'errstr' => $errstr,
'response_time_ms' => $responseTime,
]);
}
return [
'is_open' => $isOpen,
'response_time' => $isOpen ? $responseTime : null,
'error_code' => $errno,
'error_message' => $errstr,
];
}
/**
* Handle a job failure.
*/
public function failed(\Throwable $exception): void
{
Log::error('CheckTcpPort: Job failed after all retries', [
'tcp_port_id' => $this->tcpPort->id,
'exception' => $exception->getMessage(),
]);
}
}
+2
View File
@@ -87,8 +87,10 @@ class CheckUptime implements ShouldQueue
// Store the uptime check result
UptimeCheck::create([
'site_id' => $this->site->id,
'check_type' => 'http',
'status_code' => $statusCode,
'response_time_ms' => $responseTime,
'is_online' => $statusCode !== null && $statusCode < 400,
'checked_at' => now(),
]);