- .NET 10 Migration: Alle .NET-Projekte auf net10.0 umgestellt (#459) - Client-SDK: ResolveAgentPath bereinigt und DLL-Pruefung ergaenzt (#458) - Packager: Commit-Ermittlung aus publishDir / Assembly InformationalVersion (#456) - BuildInfo.targets: ExitCode-Abfang und Regex-Validierung gegen Git-Fehlertexte (#363) - UpdateService: Re-Publish erhaelt bestehende Manifeste und Werte (#457) - Bugtracker API: on_roadmap-Filter in manage?action=list durchgereicht (#349) - Watchdog API: project_slug-Filter in GET /status ergaenzt (#420) - UpdateService API: no_release_for_platform mit verfuegbaren Plattformen (#421) - Bugtracker Core: Fehler-Normalisierung gegen zersplitterte error_hashes (#419) - UpdateAgent: Kopfloser Installationsmodus via --answers (#89) - Installer & Agent: Automatische Selbstaktualisierung beim Start - Tooling: AGENTS.md, CLAUDE.md und Standalone-CLI scripts/dc.py hinzugefuegt
312 lines
11 KiB
PHP
312 lines
11 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Watchdog API
|
|
*
|
|
* POST /api/watchdog/v1/ping Heartbeat (Scope watchdog:ping)
|
|
* POST /api/watchdog/v1/event Ereignis protokollieren
|
|
* GET /api/watchdog/v1/status Alle Monitore (Scope watchdog:read)
|
|
* GET /api/watchdog/v1/events Ereignisprotokoll
|
|
* GET /api/watchdog/v1/evaluate Evaluationslauf (Shared Key oder Session)
|
|
*
|
|
* Der Evaluate-Endpunkt ist neu und die eigentliche Ergaenzung: er stuft
|
|
* Monitore anhand ihres erwarteten Intervalls auf warning bzw. down. Ohne ihn
|
|
* blieb ein ausgefallener Server dauerhaft gruen, weil der Zustand sich nur
|
|
* beim Eintreffen eines Heartbeats aenderte.
|
|
*
|
|
* Cron-Eintrag (minuetlich). Bevorzugt intern, ohne HTTP und ohne Schluessel
|
|
* im Crontab:
|
|
* * * * * * /usr/bin/php /pfad/zum/deploymentcenter/cli/tick.php --quiet
|
|
*
|
|
* Ueber die Schnittstelle, wenn der Cron woanders laeuft:
|
|
* * * * * * curl -fsS -H "Authorization: Bearer <SHARED_KEY>" \
|
|
* https://dc.example.com/api/watchdog/v1/evaluate > /dev/null
|
|
*
|
|
* Authentifizierung fuer Agenten: sowohl die zentralen Master-/Sub-Tokens
|
|
* (dc_tokens, Scope watchdog:ping) als auch die aelteren Agent-Tokens aus
|
|
* watchdog_agent_tokens werden akzeptiert.
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/../../../../src/bootstrap.php';
|
|
|
|
use Deploymentcenter\Core\ApiAuth;
|
|
use Deploymentcenter\Core\Db;
|
|
use Deploymentcenter\Core\Http;
|
|
use Deploymentcenter\Modules\Watchdog\Evaluator;
|
|
use Deploymentcenter\Modules\Watchdog\EventLog;
|
|
use Deploymentcenter\Modules\Watchdog\MetricStore;
|
|
use Deploymentcenter\Modules\Watchdog\MonitorRepo;
|
|
use Deploymentcenter\Modules\Watchdog\TokenManager as LegacyTokenManager;
|
|
|
|
Http::beginJson(['GET', 'POST', 'OPTIONS'], true);
|
|
|
|
$db = Db::init();
|
|
|
|
$monitorRepo = new MonitorRepo($db);
|
|
$eventLog = new EventLog($db);
|
|
|
|
$action = resolveWatchdogAction();
|
|
|
|
switch ($action) {
|
|
|
|
case 'ping':
|
|
requirePost();
|
|
|
|
$source = Http::str('source');
|
|
if ($source === null) {
|
|
Http::fail(400, 'missing_source', 'Das Feld "source" wird benoetigt.');
|
|
}
|
|
|
|
$pingKontext = authorizeSource($db, $source);
|
|
|
|
$instance = Http::str('instance') ?? 'default';
|
|
$metrics = Http::input('metrics');
|
|
|
|
// Das Projekt kommt aus der Token-Bindung, nicht aus dem Body - wie
|
|
// bei report.php. Ein Monitor soll nicht behaupten koennen, zu einem
|
|
// fremden Projekt zu gehoeren.
|
|
//
|
|
// null bleibt es nur bei einem ungebundenen Zugang (Shared Key,
|
|
// Session oder ein Alt-Token aus watchdog_agent_tokens). Dann
|
|
// ueberschreibt der Ping eine frueher bekannte Zuordnung nicht,
|
|
// sondern laesst sie stehen - siehe COALESCE in upsertHeartbeat().
|
|
$pingProjekt = $pingKontext !== null ? ApiAuth::homeProject($pingKontext) : null;
|
|
|
|
$monitor = $monitorRepo->upsertHeartbeat(
|
|
$source,
|
|
$instance,
|
|
Http::str('type') ?? 'heartbeat',
|
|
Http::int('interval', 0) ?: Http::int('expected_interval_sec', 60),
|
|
$metrics,
|
|
strtolower(Http::str('status') ?? 'ok'),
|
|
Http::str('message') ?? Http::str('reason'),
|
|
Http::str('group') ?? Http::str('group_key'),
|
|
Http::str('os'),
|
|
// Gesundheitszustand, den die Anwendung selbst ermittelt hat.
|
|
Http::input('checks'),
|
|
// Welche Version laeuft hier? Optional - bestehende Agenten
|
|
// schicken das Feld nicht und laufen unveraendert weiter.
|
|
Http::str('version') ?? Http::str('app_version'),
|
|
$pingProjekt
|
|
);
|
|
|
|
// Numerische Werte in den Verlauf uebernehmen, damit sich Trends
|
|
// erkennen lassen statt nur der letzte Moment.
|
|
$recordedMetrics = (new MetricStore($db))->record($source, $instance, $metrics);
|
|
|
|
// Zustandswechsel im Ereignisprotokoll festhalten.
|
|
if (!empty($monitor['_state_changed'])) {
|
|
$previous = (string)$monitor['_previous_state'];
|
|
$current = (string)$monitor['state'];
|
|
|
|
$eventLog->logEvent(
|
|
$source,
|
|
(string)$monitor['instance'],
|
|
$current === 'up' ? 'recovered' : ($current === 'warning' ? 'warning_raised' : 'hard_error'),
|
|
$previous,
|
|
$current,
|
|
$current === 'up' ? 'info' : ($current === 'warning' ? 'warning' : 'alarm'),
|
|
'Zustandswechsel durch Heartbeat.'
|
|
);
|
|
}
|
|
|
|
Http::ok([
|
|
'message' => 'Heartbeat empfangen.',
|
|
'monitor' => [
|
|
'source' => $monitor['source'],
|
|
'instance' => $monitor['instance'],
|
|
'state' => $monitor['state'],
|
|
'last_status' => $monitor['last_status'],
|
|
'last_seen_utc' => $monitor['last_seen_utc'],
|
|
'app_version' => $monitor['app_version'] ?? null,
|
|
// Wohin dieser Monitor gehoert. Steht hier null, erben seine
|
|
// Befunde das Scheinprojekt "default" und sind unter dem
|
|
// eigenen Projekt nicht auffindbar - der Melder soll das an
|
|
// der Antwort sehen und nicht erst am ausbleibenden Befund.
|
|
'project_slug' => $monitor['project_slug'] ?? null,
|
|
'state_changed' => (bool)($monitor['_state_changed'] ?? false),
|
|
'failing_checks' => $monitor['_failing_checks'] ?? [],
|
|
],
|
|
'metrics_recorded' => $recordedMetrics,
|
|
]);
|
|
|
|
case 'event':
|
|
requirePost();
|
|
|
|
$source = Http::str('source');
|
|
if ($source === null) {
|
|
Http::fail(400, 'missing_source', 'Das Feld "source" wird benoetigt.');
|
|
}
|
|
|
|
authorizeSource($db, $source);
|
|
|
|
$meta = Http::input('meta');
|
|
$eventId = $eventLog->logEvent(
|
|
$source,
|
|
Http::str('instance') ?? 'default',
|
|
Http::str('kind') ?? 'started',
|
|
Http::str('from_state'),
|
|
Http::str('to_state'),
|
|
Http::str('severity') ?? 'info',
|
|
Http::str('message'),
|
|
is_array($meta) ? $meta : null
|
|
);
|
|
|
|
Http::ok(['event_id' => $eventId], 201);
|
|
|
|
case 'status':
|
|
$context = ApiAuth::requireScope($db, 'watchdog:read');
|
|
$requestedSlug = Http::str('project_slug') ?? Http::str('project');
|
|
$boundProject = ApiAuth::projectFilter($context);
|
|
$projectSlug = $boundProject ?? $requestedSlug;
|
|
|
|
$monitors = $monitorRepo->getAllMonitors($projectSlug);
|
|
Http::ok(array_merge(
|
|
['count' => count($monitors), 'monitors' => $monitors],
|
|
ApiAuth::scopeNotice($requestedSlug, (string)($projectSlug ?? 'all'))
|
|
));
|
|
|
|
case 'events':
|
|
ApiAuth::requireScope($db, 'watchdog:read');
|
|
$events = $eventLog->getRecentEvents(
|
|
Http::int('limit', 50),
|
|
Http::str('source'),
|
|
Http::str('instance'),
|
|
Http::str('severity')
|
|
);
|
|
Http::ok(['count' => count($events), 'events' => $events]);
|
|
|
|
case 'metrics':
|
|
ApiAuth::requireScope($db, 'watchdog:read');
|
|
|
|
$source = Http::str('source');
|
|
if ($source === null) {
|
|
Http::fail(400, 'missing_source', 'Der Parameter "source" wird benoetigt.');
|
|
}
|
|
|
|
$store = new MetricStore($db);
|
|
$instance = Http::str('instance') ?? 'default';
|
|
$metricKey = Http::str('metric');
|
|
|
|
if ($metricKey === null) {
|
|
Http::ok([
|
|
'source' => $source,
|
|
'metrics' => $store->keysFor($source, $instance),
|
|
'hint' => 'Mit &metric=<name> den Verlauf abrufen.',
|
|
]);
|
|
}
|
|
|
|
Http::ok([
|
|
'source' => $source,
|
|
'metric' => $metricKey,
|
|
'hours' => Http::int('hours', 24),
|
|
'history' => $store->history($source, $metricKey, Http::int('hours', 24), $instance, Http::int('bucket', 15)),
|
|
'deviation' => $store->deviation($source, $metricKey, $instance),
|
|
]);
|
|
|
|
case 'evaluate':
|
|
// Bewusst nur fuer Shared Key oder eine angemeldete Sitzung -
|
|
// ein Agenten-Token soll den Zustand aller Monitore nicht umschreiben.
|
|
ApiAuth::requireScope($db, 'watchdog:evaluate');
|
|
|
|
$reportRes = null;
|
|
if (Http::str('force_report') === '1' || Http::str('report') === '1') {
|
|
$reportRes = \Deploymentcenter\Modules\Notify\RocketChatNotifier::sendStatusReport($db, true);
|
|
}
|
|
|
|
$result = Evaluator::run($db);
|
|
Http::ok($result + [
|
|
'rocketchat_report' => $reportRes,
|
|
'message' => sprintf(
|
|
'%d Monitor(e) geprueft, %d Zustandswechsel.',
|
|
$result['checked'],
|
|
$result['changed']
|
|
)
|
|
]);
|
|
|
|
default:
|
|
Http::fail(404, 'unknown_action', 'Endpunkt nicht gefunden.', null, [
|
|
'available' => ['ping', 'event', 'status', 'events', 'metrics', 'evaluate'],
|
|
]);
|
|
}
|
|
|
|
// ======================================================================
|
|
|
|
function requirePost(): void
|
|
{
|
|
if (Http::method() !== 'POST') {
|
|
Http::fail(405, 'method_not_allowed', 'Diese Aktion erwartet POST.');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Prueft die Berechtigung, fuer eine bestimmte Source zu melden, und LIEFERT
|
|
* DEN KONTEXT ZURUECK.
|
|
*
|
|
* Akzeptiert zentrale Tokens (dc_tokens, Scope watchdog:ping) und die
|
|
* aelteren, an eine Source gebundenen Agent-Tokens.
|
|
*
|
|
* Die Rueckgabe ist neu: Vorher gab die Funktion void zurueck und warf den
|
|
* Kontext weg - samt der Projektbindung des Tokens.
|
|
* Genau die fehlte danach beim Anlegen des Monitors, und die Befunde landeten
|
|
* im Scheinprojekt "default" (#404). Die Angabe wurde also gelesen und
|
|
* anschliessend fallengelassen.
|
|
*
|
|
* null heisst "berechtigt, aber ohne Kontext": ein Alt-Token aus
|
|
* watchdog_agent_tokens. Diese Token kennen kein Projekt.
|
|
*
|
|
* @return ?array Kontext aus ApiAuth::resolve(), oder null bei einem Alt-Token.
|
|
*/
|
|
function authorizeSource(PDO $db, string $source): ?array
|
|
{
|
|
// Zentrale Token-Hierarchie, Shared Key oder Session
|
|
$context = ApiAuth::resolve($db, 'watchdog:ping', null, true);
|
|
if ($context !== null) {
|
|
return $context;
|
|
}
|
|
|
|
// Alt-Tokens aus watchdog_agent_tokens
|
|
$presented = Http::bearerToken();
|
|
if ($presented !== null) {
|
|
$legacy = new LegacyTokenManager($db);
|
|
if ($legacy->validateToken($presented, $source)) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
Http::fail(
|
|
401,
|
|
'unauthorized',
|
|
sprintf('Kein gueltiges Token fuer die Source "%s".', $source),
|
|
null,
|
|
['required_scope' => 'watchdog:ping']
|
|
);
|
|
}
|
|
|
|
function resolveWatchdogAction(): string
|
|
{
|
|
$explicit = Http::str('action');
|
|
if ($explicit !== null) {
|
|
return strtolower($explicit);
|
|
}
|
|
|
|
$segments = array_values(array_filter(
|
|
explode('/', trim(Http::path(), '/')),
|
|
static fn(string $s): bool => $s !== ''
|
|
));
|
|
|
|
$last = strtolower((string)end($segments));
|
|
|
|
return match ($last) {
|
|
'ping', 'heartbeat' => 'ping',
|
|
'event' => 'event',
|
|
'events' => 'events',
|
|
'status' => 'status',
|
|
'evaluate' => 'evaluate',
|
|
'metrics' => 'metrics',
|
|
default => 'status',
|
|
};
|
|
}
|