getConnection(); if (!$connection->getSchemaBuilder()->hasTable('user') || !$connection->getSchemaBuilder()->hasTable('shop')) { throw new \RuntimeException('请先在全新业务数据库导入 web/sql/ss.sql'); } AnnouncementSchema::upgrade($connection); self::upgradeReferralSchema($connection); ReferralConfig::clearCache(); 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' ); } $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); }); } if (!$shopSchema->hasColumn('shop', 'created_at')) { $shopSchema->table('shop', static function ($table) { $table->unsignedBigInteger('created_at')->default(0); }); } if (!$shopSchema->hasColumn('shop', 'updated_at')) { $shopSchema->table('shop', static function ($table) { $table->unsignedBigInteger('updated_at')->default(0); }); } self::ensureMultiHostDefaults($connection); self::upgradeCloudInstance($connection); self::upgradeInvoicePayments($connection); User::getConnectionResolver()->connection('log')->unprepared(self::schema('cloud_log.sql')); self::exportEngineConfig(); echo "虚拟化业务表、指标日志表与私有引擎配置已准备。未连接或修改任何宿主机。\n"; return true; } /** * Seed feature switches only when absent. * * Regions, default lines, pools, capacity policies, offers and IP rows are * operator-owned records and are never invented by cloudInit. Keeping the * line dimension disabled by default changes presentation only; the data * model remains available before differentiated network products are sold. */ private static function ensureMultiHostDefaults($connection): void { $connection->table('configurations')->insertOrIgnore([ 'name' => 'cloud_network_lines_enabled', 'value' => 'false', ]); } /** * Apply the referral-code migration as part of the online-update path. * * The standalone SQL file is also used for manual upgrades, while this * call makes `php xcat cloudInit` safe for existing installations. The * statements are idempotent for MariaDB and preserve existing codes. */ private static function upgradeReferralSchema($connection): void { $schema = $connection->getSchemaBuilder(); if (!$schema->hasTable('ss_invite_code')) { throw new \RuntimeException( '缺少 ss_invite_code 表,请先导入 web/sql/ss.sql 后再执行 cloudInit' ); } $connection->unprepared(self::schema('referral_affiliate_code.sql')); } /** 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 || base64_encode($decoded) !== $secret) { 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); } } }