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/Command/CloudSetup.php

155 lines
6.4 KiB
PHP

<?php
namespace App\Command;
use App\Models\User;
use App\Services\Config;
/** Explicit local initialization; never connects to or changes a hypervisor. */
final class CloudSetup
{
public static function initialize(): bool
{
if (Config::get('enable_log', 'false') !== 'true') {
throw new \RuntimeException('请启用并配置日志数据库,虚拟机指标必须写入日志库');
}
if ((string) Config::get('db_prefix', '') !== '') {
throw new \RuntimeException('虚拟化集成使用独立表名,请将 db_prefix 留空');
}
$connection = (new User())->getConnection();
if (!$connection->getSchemaBuilder()->hasTable('user') || !$connection->getSchemaBuilder()->hasTable('shop')) {
throw new \RuntimeException('请先在全新业务数据库导入 web/sql/ss.sql');
}
$connection->unprepared(self::schema('cloud.sql'));
if (!$connection->getSchemaBuilder()->hasColumn('shop', 'host_id')) {
$connection->getSchemaBuilder()->table('shop', static function ($table) {
$table->unsignedBigInteger('host_id')->nullable();
});
}
User::getConnectionResolver()->connection('log')->unprepared(self::schema('cloud_log.sql'));
self::exportEngineConfig();
echo "虚拟化业务表、指标日志表与私有引擎配置已准备。未连接或修改任何宿主机。\n";
return true;
}
public static function exportEngineConfig(): bool
{
if (Config::get('enable_log', 'false') !== 'true') {
throw new \RuntimeException('引擎需要单独的日志数据库连接');
}
$root = dirname(BASE_PATH);
$hmacFile = (string) Config::get('cloud_engine_hmac_file', $root . '/runtime/php/engine.hmac');
$payloadFile = (string) Config::get('cloud_payload_key_file', $root . '/runtime/php/payload.key');
$hmac = self::secret('cloud_engine_hmac_key', $hmacFile);
self::secret('cloud_payload_key', $payloadFile);
$dataDir = (string) Config::get('cloud_engine_data_dir', $root . '/runtime/engine');
$target = (string) Config::get('cloud_engine_config_file', $root . '/runtime/engine.json');
self::privateDirectory(dirname($target));
$config = [
'main_database' => self::database(Config::getDbConfig()),
'log_database' => self::database(Config::getLogDbConfig()),
'service_secret' => $hmac,
'data_dir' => $dataDir,
'master_key_file' => $dataDir . '/master.key',
'php_introspection_url' => (string) Config::get('cloud_introspection_url', 'http://127.0.0.1/api/internal/cloud/session-introspection'),
'php_introspection_host' => (string) Config::get('cloud_introspection_host', ''),
];
self::privateWrite($target, json_encode($config, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES) . "\n");
echo '已导出私有引擎配置:' . $target . "(密钥和数据库密码不输出)\n";
return true;
}
private static function schema(string $name): string
{
$sql = file_get_contents(BASE_PATH . '/sql/' . $name);
if ($sql === false || trim($sql) === '') {
throw new \RuntimeException('缺少虚拟化建表脚本:' . $name);
}
return $sql;
}
private static function database(array $config): array
{
if ($config['driver'] !== 'mysql') {
throw new \RuntimeException('虚拟化引擎需要 MariaDB/MySQL 数据库');
}
if ((string) $config['database'] === '' || (string) $config['username'] === '') {
throw new \RuntimeException('请完整配置业务和日志数据库');
}
return array_intersect_key($config, array_flip(['host', 'port', 'database', 'username', 'password']));
}
private static function secret(string $configKey, string $file): string
{
$configured = trim((string) Config::get($configKey, ''));
if ($configured !== '') {
self::validateSecret($configured);
return $configured;
}
if (is_file($file)) {
$secret = trim((string) file_get_contents($file));
self::validateSecret($secret);
return $secret;
}
self::privateDirectory(dirname($file));
$secret = base64_encode(random_bytes(32));
$oldMask = umask(0077);
try {
$stream = fopen($file, 'x');
if ($stream === false) {
// Another initializer may have won; never overwrite a live key.
if (is_file($file)) {
$secret = trim((string) file_get_contents($file));
self::validateSecret($secret);
return $secret;
}
throw new \RuntimeException('无法创建私有密钥文件');
}
try {
if (fwrite($stream, $secret . "\n") !== strlen($secret) + 1) {
throw new \RuntimeException('私有密钥写入失败');
}
fflush($stream);
} finally {
fclose($stream);
}
chmod($file, 0600);
} finally {
umask($oldMask);
}
return $secret;
}
private static function validateSecret(string $secret): void
{
$decoded = base64_decode($secret, true);
if ($decoded === false || strlen($decoded) !== 32) {
throw new \RuntimeException('独立加密/签名密钥必须是 base64 编码的 32 字节随机数');
}
}
private static function privateDirectory(string $path): void
{
if (!is_dir($path) && !mkdir($path, 0700, true) && !is_dir($path)) {
throw new \RuntimeException('无法创建私有运行目录');
}
}
private static function privateWrite(string $path, string $contents): void
{
$oldMask = umask(0077);
$temporary = $path . '.' . bin2hex(random_bytes(8)) . '.tmp';
try {
$written = file_put_contents($temporary, $contents, LOCK_EX);
if ($written !== strlen($contents) || !chmod($temporary, 0600) || !rename($temporary, $path)) {
throw new \RuntimeException('写入引擎配置失败');
}
} finally {
if (is_file($temporary)) {
unlink($temporary);
}
umask($oldMask);
}
}
}