Files
Deploymentcenter/public/api/watchdog/v1/index.php
T

123 lines
4.9 KiB
PHP

<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../../../src/Core/Db.php';
require_once __DIR__ . '/../../../../src/Modules/Watchdog/MonitorRepo.php';
require_once __DIR__ . '/../../../../src/Modules/Watchdog/EventLog.php';
require_once __DIR__ . '/../../../../src/Modules/Watchdog/TokenManager.php';
use Deploymentcenter\Core\Db;
use Deploymentcenter\Modules\Watchdog\MonitorRepo;
use Deploymentcenter\Modules\Watchdog\EventLog;
use Deploymentcenter\Modules\Watchdog\TokenManager;
function sendResponse(array $data, int $statusCode = 200): void {
http_response_code($statusCode);
echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}
try {
$config = require __DIR__ . '/../../../../config/config.php';
$pdo = Db::init($config);
$uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
$authHeader = $_SERVER['HTTP_X_WATCHDOG_KEY'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['HTTP_X_AGENT_TOKEN'] ?? null;
if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
$authHeader = substr($authHeader, 7);
}
$sharedKey = $config['security']['shared_key'] ?? '';
$isAdminAuth = ($authHeader && hash_equals($sharedKey, $authHeader));
$tokenManager = new TokenManager($pdo);
$monitorRepo = new MonitorRepo($pdo);
$eventLog = new EventLog($pdo);
$verifyToken = function(string $source) use ($isAdminAuth, $authHeader, $tokenManager) {
if ($isAdminAuth) return true;
if (empty($authHeader)) {
sendResponse(['error' => 'Unauthorized', 'message' => 'Missing authorization token.'], 401);
}
if (!$tokenManager->validateToken($authHeader, $source)) {
sendResponse(['error' => 'Forbidden', 'message' => "Token unauthorized for source '{$source}'."], 403);
}
return true;
};
$rawInput = file_get_contents('php://input');
$inputData = !empty($rawInput) ? (json_decode($rawInput, true) ?? []) : $_POST;
// Heartbeat / Ping
if ((str_ends_with($uri, '/ping') || str_ends_with($uri, '/heartbeat')) && $method === 'POST') {
$source = trim($inputData['source'] ?? '');
$instance = trim($inputData['instance'] ?? 'default');
$type = trim($inputData['type'] ?? 'heartbeat');
$interval = (int)($inputData['interval'] ?? $inputData['expected_interval_sec'] ?? 60);
$metrics = $inputData['metrics'] ?? null;
$status = strtolower(trim($inputData['status'] ?? 'ok'));
$message = $inputData['message'] ?? $inputData['reason'] ?? null;
$groupKey = $inputData['group'] ?? $inputData['group_key'] ?? null;
$os = $inputData['os'] ?? null;
if (empty($source)) {
sendResponse(['error' => 'Bad Request', 'message' => 'Field "source" is required.'], 400);
}
$verifyToken($source);
$monitor = $monitorRepo->upsertHeartbeat($source, $instance, $type, $interval, $metrics, $status, $message, $groupKey, $os);
sendResponse([
'status' => 'success',
'message' => 'Heartbeat received',
'monitor' => [
'source' => $monitor['source'],
'instance' => $monitor['instance'],
'state' => $monitor['state'],
'last_status' => $monitor['last_status'],
'last_seen_utc' => $monitor['last_seen_utc'],
]
]);
}
// Log Event
if (str_ends_with($uri, '/event') && $method === 'POST') {
$source = trim($inputData['source'] ?? '');
$instance = trim($inputData['instance'] ?? 'default');
$kind = trim($inputData['kind'] ?? 'started');
$severity = trim($inputData['severity'] ?? 'info');
$message = $inputData['message'] ?? null;
$meta = $inputData['meta'] ?? null;
if (empty($source)) sendResponse(['error' => 'Bad Request', 'message' => 'Field "source" is required.'], 400);
$verifyToken($source);
$eventId = $eventLog->logEvent($source, $instance, $kind, null, null, $severity, $message, $meta);
sendResponse(['status' => 'success', 'event_id' => $eventId]);
}
// Status / Monitore auflisten
if (str_ends_with($uri, '/status') && $method === 'GET') {
$monitors = $monitorRepo->getAllMonitors();
sendResponse(['count' => count($monitors), 'monitors' => $monitors]);
}
// Events auflisten
if (str_ends_with($uri, '/events') && $method === 'GET') {
$limit = (int)($_GET['limit'] ?? 50);
$events = $eventLog->getRecentEvents($limit);
sendResponse(['count' => count($events), 'events' => $events]);
}
sendResponse(['error' => 'Not Found', 'message' => 'Endpoint not found'], 404);
} catch (Throwable $t) {
sendResponse(['error' => 'Server Error', 'message' => $t->getMessage()], 500);
}