You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudRuntimeHealthService.php

230 lines
10 KiB
PHTML

<?php
namespace App\Services\Cloud;
use App\Models\User;
use App\Services\Config;
use Predis\Client;
/** Read-only checks; a successful check is not a host or guest health claim. */
final class CloudRuntimeHealthService
{
private const DATABASE_TIMEOUT_SECONDS = 2;
private \Closure $databaseProbe;
private \Closure $engineProbe;
private \Closure $redisProbe;
private \Closure $heartbeatProbe;
public function __construct(?callable $databaseProbe = null, ?callable $engineProbe = null,
?callable $redisProbe = null, ?callable $heartbeatProbe = null)
{
$this->databaseProbe = \Closure::fromCallable($databaseProbe ?? [self::class, 'probeDatabase']);
$this->engineProbe = \Closure::fromCallable($engineProbe ?? static function (array $actor): bool {
$result = (new CloudEngineClient(null, 4.0))->request('GET', '/internal/v1/health', $actor);
return ($result['status'] ?? null) === 'ok';
});
$this->redisProbe = \Closure::fromCallable($redisProbe ?? static function (): bool {
// Do not change the application's shared Redis client's timeouts.
$client = new Client([
'scheme' => Config::get('redis_scheme', 'tcp'),
'host' => Config::get('redis_host'),
'port' => Config::get('redis_port', 6379),
'password' => Config::get('redis_password'),
'database' => Config::get('redis_database', 0),
'timeout' => 1.0, 'read_write_timeout' => 1.0,
]);
try {
return strtoupper((string) $client->ping()) === 'PONG';
} finally {
$client->disconnect();
}
});
$this->heartbeatProbe = \Closure::fromCallable($heartbeatProbe
?? [CloudRuntimeHeartbeat::class, 'snapshot']);
}
public function snapshot(array $actor): array
{
if (!($actor['is_admin'] ?? false) || (int) ($actor['user_id'] ?? 0) < 1) {
throw new CloudError('需要管理员权限', 403);
}
$checks = [$this->databaseCheck('default', 'main_database', '业务数据库',
'已完成只读查询;不代表所有业务表与数据均正常。',
'业务数据库读取失败,请检查连接和服务日志。')];
if (Config::get('enable_log', 'false') === 'true') {
$checks[] = $this->databaseCheck('log', 'log_database', '日志数据库',
'已完成只读查询;不代表指标采集程序正在运行。',
'日志数据库读取失败,请检查连接和服务日志。');
} else {
$checks[] = $this->row('log_database', '日志数据库', 'disabled',
'未启用日志数据库;虚拟化指标依赖该配置。');
}
$checks[] = $this->check('engine', '私有引擎',
fn (): bool => ($this->engineProbe)($actor) === true,
'签名接口及引擎存储检查通过;未探测宿主机或虚拟机。',
'引擎检查失败或超时,请检查引擎服务、签名配置及存储。');
if (trim((string) Config::get('redis_host', '')) !== '') {
$checks[] = $this->check('redis', 'Redis',
fn (): bool => ($this->redisProbe)() === true,
'PING 响应正常;不验证缓存内容或所有 Redis 权限。',
'Redis 检查失败或超时,请检查配置与服务状态。');
} else {
$checks[] = $this->row('redis', 'Redis', 'disabled', '未配置 Redis,未执行检查。');
}
try {
$heartbeats = ($this->heartbeatProbe)();
} catch (\Throwable $exception) {
$heartbeats = [];
}
foreach (['worker' => '普通任务处理', 'policy' => '策略任务处理', 'lifecycle' => '到期与流量调度'] as $key => $label) {
$found = null;
foreach (is_array($heartbeats) ? $heartbeats : [] as $row) {
if (is_array($row) && ($row['key'] ?? null) === $key) {
$found = $row;
break;
}
}
// The private reader returns fixed messages, never raw errors or file names.
$checks[] = $found === null
? $this->row($key, $label, 'unknown', '无法读取运行记录,请检查服务与心跳目录权限。')
: array_intersect_key($found, array_flip(['key', 'label', 'status', 'message',
'checked_at', 'last_seen_at', 'last_success_at', 'active_count']));
}
return ['checked_at' => time(), 'checks' => $checks];
}
private static function probeDatabase(string $name): ?bool
{
// Accessing configuration does not open the application's lazy PDO.
$connection = User::getConnectionResolver()->connection($name);
$config = $connection->getConfig();
if (($config['driver'] ?? '') === 'sqlite') {
return (int) $connection->selectOne('SELECT 1 AS ready')->ready === 1;
}
if (($config['driver'] ?? '') !== 'mysql' || !extension_loaded('pdo_mysql')
|| !array_key_exists('mysqlnd', (new \ReflectionExtension('pdo_mysql'))->getDependencies())) {
return null;
}
$arguments = self::mysqlProbeArguments($config);
// mysqlnd copies this INI value into each NEW connection. Existing
// application connections keep their own timeout; never setAttribute
// on a shared PDO or reuse a persistent connection for a health check.
// https://www.php.net/manual/en/mysqlnd.config.php
return self::withReadTimeout(static function () use ($arguments): bool {
$pdo = null;
$statement = null;
try {
$pdo = new \PDO(...$arguments);
$statement = $pdo->query('SELECT 1 AS ready');
return $statement !== false && (int) $statement->fetchColumn() === 1;
} finally {
$statement = null;
$pdo = null;
}
});
}
private static function mysqlProbeArguments(array $config): array
{
$parts = [];
if (!empty($config['unix_socket'])) {
$parts['unix_socket'] = $config['unix_socket'];
} else {
$parts['host'] = $config['host'] ?? '127.0.0.1';
$port = $config['port'] ?? 3306;
if ((!is_int($port) && !is_string($port))
|| !ctype_digit((string) $port) || (int) $port < 1 || (int) $port > 65535) {
throw new \InvalidArgumentException('Invalid database probe port');
}
$parts['port'] = (string) $port;
}
$parts['dbname'] = $config['database'] ?? '';
if (!empty($config['charset'])) {
$parts['charset'] = $config['charset'];
}
$dsn = [];
foreach ($parts as $key => $value) {
if (!is_string($value) || $value === '' || preg_match('/[;\x00-\x1f\x7f]/', $value)) {
throw new \InvalidArgumentException('Invalid database probe configuration');
}
$dsn[] = $key . '=' . $value;
}
$options = [\PDO::ATTR_TIMEOUT => self::DATABASE_TIMEOUT_SECONDS,
\PDO::ATTR_PERSISTENT => false, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];
// Preserve configured TLS verification, but not arbitrary init commands,
// persistent handles, local-file access or shared connection options.
foreach (['MYSQL_ATTR_SSL_KEY', 'MYSQL_ATTR_SSL_CERT', 'MYSQL_ATTR_SSL_CA',
'MYSQL_ATTR_SSL_CAPATH', 'MYSQL_ATTR_SSL_CIPHER', 'MYSQL_ATTR_SSL_VERIFY_SERVER_CERT',
'MYSQL_ATTR_SERVER_PUBLIC_KEY'] as $constant) {
// PDO's driver-constant aliases are deprecated in PHP 8.5.
$modern = 'Pdo\\Mysql::' . substr($constant, strlen('MYSQL_'));
$name = defined($modern) ? $modern : 'PDO::' . $constant;
if (defined($name)) {
$key = constant($name);
if (array_key_exists($key, $config['options'] ?? [])) {
$options[$key] = $config['options'][$key];
}
}
}
return ['mysql:' . implode(';', $dsn), $config['username'] ?? null,
$config['password'] ?? null, $options];
}
/** Return unknown if a short read timeout cannot be installed, never retry unbounded. */
private static function withReadTimeout(callable $probe,
string $setting = 'mysqlnd.net_read_timeout'): ?bool
{
$original = ini_get($setting);
if ($original === false || !function_exists('ini_set')) {
return null;
}
$changed = false;
try {
if (@ini_set($setting, (string) self::DATABASE_TIMEOUT_SECONDS) === false) {
return null;
}
$changed = true;
if (ini_get($setting) !== (string) self::DATABASE_TIMEOUT_SECONDS) {
return null;
}
return $probe() === true;
} finally {
if ($changed && (@ini_set($setting, $original) === false || ini_get($setting) !== $original)) {
throw new \RuntimeException('Database probe timeout restoration failed');
}
}
}
private function databaseCheck(string $connection, string $key, string $label,
string $success, string $failure): array
{
try {
$result = ($this->databaseProbe)($connection);
} catch (\Throwable $exception) {
$result = false;
}
if ($result === null) {
return $this->row($key, $label, 'unknown',
'当前 PHP 数据库驱动或配置不支持短超时探测,未执行连接检查;不能据此判断数据库故障。');
}
return $this->row($key, $label, $result === true ? 'ok' : 'error',
$result === true ? $success : $failure);
}
private function check(string $key, string $label, callable $probe, string $success, string $failure): array
{
try {
$ok = $probe() === true;
} catch (\Throwable $exception) {
// SQL and transport errors can contain credentials; never expose them.
$ok = false;
}
return $this->row($key, $label, $ok ? 'ok' : 'error', $ok ? $success : $failure);
}
private function row(string $key, string $label, string $status, string $message): array
{
return compact('key', 'label', 'status', 'message') + ['checked_at' => time()];
}
}