121 lines
3.5 KiB
PHP
121 lines
3.5 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
class ErpMonitor
|
|
{
|
|
public static function checkAll(): array
|
|
{
|
|
$companies = CompanyRepository::findAll();
|
|
$results = [];
|
|
|
|
foreach ($companies as $company) {
|
|
$results[] = self::check($company);
|
|
}
|
|
|
|
return $results;
|
|
}
|
|
|
|
public static function check(array $company): array
|
|
{
|
|
$baseUrl = rtrim($company['api_base_url'] ?? '', '/');
|
|
$healthUrl = $baseUrl !== '' ? $baseUrl . '/health' : '';
|
|
$apiKey = $company['api_key'] ?? '';
|
|
|
|
if ($healthUrl === '') {
|
|
return [
|
|
'company_id' => (int)$company['id'],
|
|
'company_name' => $company['name'] ?? '',
|
|
'status' => 'unknown',
|
|
'latency_ms' => null,
|
|
'error' => 'Sin URL configurada',
|
|
'last_check' => date('Y-m-d H:i:s'),
|
|
];
|
|
}
|
|
|
|
$start = microtime(true);
|
|
|
|
$ch = curl_init($healthUrl);
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_TIMEOUT => 10,
|
|
CURLOPT_CONNECTTIMEOUT => 5,
|
|
CURLOPT_HTTPHEADER => [
|
|
'X-API-Key: ' . $apiKey,
|
|
'User-Agent: bot-palmas360-monitor/1.0',
|
|
],
|
|
]);
|
|
|
|
$response = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$error = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
$latency = (int)((microtime(true) - $start) * 1000);
|
|
|
|
if ($error !== '') {
|
|
return [
|
|
'company_id' => (int)$company['id'],
|
|
'company_name' => $company['name'] ?? '',
|
|
'status' => 'down',
|
|
'latency_ms' => $latency,
|
|
'error' => $error,
|
|
'last_check' => date('Y-m-d H:i:s'),
|
|
];
|
|
}
|
|
|
|
if ($httpCode >= 200 && $httpCode < 400) {
|
|
return [
|
|
'company_id' => (int)$company['id'],
|
|
'company_name' => $company['name'] ?? '',
|
|
'status' => 'up',
|
|
'latency_ms' => $latency,
|
|
'error' => null,
|
|
'last_check' => date('Y-m-d H:i:s'),
|
|
];
|
|
}
|
|
|
|
return [
|
|
'company_id' => (int)$company['id'],
|
|
'company_name' => $company['name'] ?? '',
|
|
'status' => 'degraded',
|
|
'latency_ms' => $latency,
|
|
'error' => "HTTP {$httpCode}",
|
|
'last_check' => date('Y-m-d H:i:s'),
|
|
];
|
|
}
|
|
|
|
public static function checkById(int $companyId): ?array
|
|
{
|
|
$company = CompanyRepository::findById($companyId);
|
|
if ($company === null) return null;
|
|
return self::check($company);
|
|
}
|
|
|
|
public static function summary(): array
|
|
{
|
|
$results = self::checkAll();
|
|
$up = 0;
|
|
$down = 0;
|
|
$degraded = 0;
|
|
$unknown = 0;
|
|
|
|
foreach ($results as $r) {
|
|
match ($r['status']) {
|
|
'up' => $up++,
|
|
'down' => $down++,
|
|
'degraded' => $degraded++,
|
|
default => $unknown++,
|
|
};
|
|
}
|
|
|
|
return [
|
|
'total' => count($results),
|
|
'up' => $up,
|
|
'down' => $down,
|
|
'degraded' => $degraded,
|
|
'unknown' => $unknown,
|
|
'results' => $results,
|
|
];
|
|
}
|
|
}
|