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

244 lines
11 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?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');
}
self::retireLegacyBought($connection);
$connection->unprepared(self::schema('cloud.sql'));
$column = $connection->selectOne(
"SELECT IS_NULLABLE AS nullable_state FROM information_schema.COLUMNS "
. "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'cloud_instances' "
. "AND COLUMN_NAME = 'order_id'"
);
if ($column !== null && strtoupper((string) $column->nullable_state) !== 'YES') {
$connection->unprepared(
'ALTER TABLE cloud_instances MODIFY order_id BIGINT UNSIGNED NULL'
);
}
if (!$connection->getSchemaBuilder()->hasColumn('shop', 'host_id')) {
$connection->getSchemaBuilder()->table('shop', static function ($table) {
$table->unsignedBigInteger('host_id')->nullable();
});
}
$shopSchema = $connection->getSchemaBuilder();
if (!$shopSchema->hasColumn('shop', 'validity_days')) {
$shopSchema->table('shop', static function ($table) {
$table->unsignedInteger('validity_days')->default(30);
});
}
if (!$shopSchema->hasColumn('shop', 'traffic_quota_bytes')) {
$shopSchema->table('shop', static function ($table) {
$table->unsignedBigInteger('traffic_quota_bytes')->default(0);
});
}
self::upgradeCloudInstance($connection);
self::upgradeInvoicePayments($connection);
User::getConnectionResolver()->connection('log')->unprepared(self::schema('cloud_log.sql'));
self::exportEngineConfig();
echo "虚拟化业务表、指标日志表与私有引擎配置已准备。未连接或修改任何宿主机。\n";
return true;
}
/** Remove the retired pre-cloud purchase ledger once, without discarding data. */
private static function retireLegacyBought($connection): void
{
$schema = $connection->getSchemaBuilder();
if (!$schema->hasTable('bought')) {
return;
}
if ($connection->table('bought')->limit(1)->exists()) {
throw new \RuntimeException(
'旧 bought 表仍有数据,已停止升级;请先核对并迁移后再执行 cloudInit'
);
}
$schema->drop('bought');
}
private static function upgradeCloudInstance($connection): void
{
$schema = $connection->getSchemaBuilder();
$columns = [
'plan_id' => 'BIGINT UNSIGNED NULL',
'current_period_id' => 'BIGINT UNSIGNED NULL',
'service_status' => "VARCHAR(32) NOT NULL DEFAULT 'exempt'",
'network_status' => "VARCHAR(32) NOT NULL DEFAULT 'active'",
'expires_at' => 'BIGINT UNSIGNED NULL',
'renewal_price' => 'DECIMAL(12,2) NULL',
'renewal_days' => 'INT UNSIGNED NOT NULL DEFAULT 0',
'renewal_traffic_bytes' => 'BIGINT UNSIGNED NOT NULL DEFAULT 0',
'traffic_quota_bytes' => 'BIGINT UNSIGNED NOT NULL DEFAULT 0',
'traffic_download_bytes' => 'BIGINT UNSIGNED NOT NULL DEFAULT 0',
'traffic_upload_bytes' => 'BIGINT UNSIGNED NOT NULL DEFAULT 0',
'lifetime_download_bytes' => 'BIGINT UNSIGNED NOT NULL DEFAULT 0',
'lifetime_upload_bytes' => 'BIGINT UNSIGNED NOT NULL DEFAULT 0',
'traffic_synced_at' => 'BIGINT UNSIGNED NOT NULL DEFAULT 0',
'suspended_at' => 'BIGINT UNSIGNED NULL',
'network_suspended_at' => 'BIGINT UNSIGNED NULL',
];
foreach ($columns as $name => $definition) {
if (!$schema->hasColumn('cloud_instances', $name)) {
$connection->statement('ALTER TABLE cloud_instances ADD COLUMN ' . $name . ' ' . $definition);
}
}
if (!$schema->hasColumn('cloud_renewals', 'period_id')) {
$connection->statement('ALTER TABLE cloud_renewals ADD COLUMN period_id BIGINT UNSIGNED NULL AFTER plan_id');
}
$connection->statement('ALTER TABLE cloud_instances ADD INDEX IF NOT EXISTS '
. 'cloud_instance_lifecycle (service_status, expires_at, id)');
$connection->statement('ALTER TABLE cloud_jobs ADD INDEX IF NOT EXISTS '
. 'cloud_job_instance_state (instance_id, status, id)');
}
private static function upgradeInvoicePayments($connection): void
{
// Payment-provider tables are optional. When they are already
// installed, cloudInit only verifies that the common provider order
// identifiers required by invoice payment mapping remain available.
foreach (['yipay_orders', 'paytaro_orders', 'usdt_payment_orders'] as $table) {
if ($connection->getSchemaBuilder()->hasTable($table)
&& !$connection->getSchemaBuilder()->hasColumn($table, 'order_no')) {
throw new \RuntimeException('支付表缺少商户订单号字段:' . $table);
}
}
}
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,
'project_dir' => $root,
'data_dir' => $dataDir,
'master_key_file' => $dataDir . '/master.key',
'update_php_fpm_unit' => (string) Config::get('cloud_update_php_fpm_unit', 'php-fpm.service'),
'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 数据库(PDO 驱动名为 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);
}
}
}