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.
747 lines
33 KiB
PHP
747 lines
33 KiB
PHP
<?php
|
|
|
|
namespace App\Command;
|
|
|
|
use App\Models\User;
|
|
use App\Services\Config;
|
|
|
|
/** Initializes only the clean-break PHP business and Agent log schemas. */
|
|
final class CloudSetup
|
|
{
|
|
private const SCHEMA_VERSION = 'go-agent-wss-v13-vpc-l3-v6-repair';
|
|
private const MAIN_TABLES = [
|
|
'cloud_regions', 'cloud_network_lines', 'cloud_resource_pools',
|
|
'cloud_hosts', 'cloud_host_agents',
|
|
'cloud_host_storage_configurations', 'cloud_templates',
|
|
'cloud_template_replicas', 'cloud_user_isos',
|
|
'cloud_user_iso_replicas', 'cloud_rescue_template_deletions',
|
|
'cloud_rescue_template_imports', 'cloud_upload_staging',
|
|
'cloud_host_resource_pool_memberships',
|
|
'cloud_host_network_attachments', 'cloud_public_ip_pools',
|
|
'cloud_host_vpc_transports', 'cloud_vpc_cidr_pools',
|
|
'cloud_host_capacity_policies', 'cloud_public_ips', 'cloud_offers',
|
|
'cloud_instances', 'cloud_vpcs', 'cloud_vpc_ports',
|
|
'cloud_vpc_host_states', 'cloud_vpc_membership_batches',
|
|
'cloud_vpc_membership_batch_items', 'cloud_instance_firewalls',
|
|
'cloud_instance_firewall_versions', 'cloud_instance_firewall_rules',
|
|
'cloud_platform_test_policy_state',
|
|
'cloud_platform_test_policy_rules', 'cloud_instance_snapshots',
|
|
'cloud_backup_subscriptions', 'cloud_backup_period_entitlements',
|
|
'cloud_instance_backups', 'cloud_deployment_snapshots',
|
|
'cloud_backup_restores', 'cloud_backup_recoveries',
|
|
'cloud_instance_migrations', 'cloud_peer_migration_artifacts',
|
|
'cloud_instance_runtime', 'cloud_orders', 'cloud_order_items',
|
|
'cloud_resource_reservations', 'cloud_service_periods',
|
|
'cloud_renewals', 'cloud_invoices', 'cloud_invoice_items',
|
|
'cloud_invoice_payments',
|
|
'cloud_mail_outbox', 'cloud_jobs', 'cloud_agent_completion_events',
|
|
'cloud_ssh_keys',
|
|
'cloud_sessions', 'cloud_console_tickets',
|
|
];
|
|
private const LOG_TABLES = [
|
|
'cloud_vm_metric_samples', 'cloud_vm_traffic_checkpoints',
|
|
'cloud_vm_traffic_totals',
|
|
];
|
|
/** Refusal-only denylist: never read, import, rename or migrate these rows. */
|
|
private const RETIRED_LOG_TABLES = [
|
|
'engine_vm_metric_samples',
|
|
'engine_vm_traffic_checkpoints', 'engine_vm_traffic_totals',
|
|
];
|
|
private const REQUIRED_MAIN_COLUMNS = [
|
|
'cloud_offers' => [
|
|
'backup_price',
|
|
],
|
|
'cloud_jobs' => [
|
|
'id', 'operation_id', 'request_idempotency_key',
|
|
'request_fingerprint', 'parent_job_id', 'user_id', 'host_id',
|
|
'backup_id', 'backup_restore_id', 'backup_recovery_id',
|
|
'vpc_id', 'vpc_port_id', 'vpc_batch_id',
|
|
'kind', 'execution_mode', 'phase', 'outcome', 'status',
|
|
'attempts', 'dispatch_attempts', 'dispatch_deadline_at',
|
|
'dispatch_started_at', 'agent_accepted_at',
|
|
'receipt_deadline_at', 'terminal_at',
|
|
'effect_may_have_applied', 'safe_to_resubmit',
|
|
'effect_resolution', 'finalization_incident',
|
|
'finalization_error_code', 'completion_event_id', 'read_at',
|
|
'lease_token', 'lease_until', 'available_at', 'error_code',
|
|
'result_json', 'created_at', 'updated_at',
|
|
],
|
|
'cloud_host_vpc_transports' => [
|
|
'host_id', 'transport_address', 'transport_prefix_length',
|
|
'transport_interface', 'transport_mode', 'mtu',
|
|
'desired_revision', 'observed_revision', 'sync_state',
|
|
'last_operation_id', 'last_error_code', 'last_verified_at',
|
|
'created_at', 'updated_at',
|
|
],
|
|
'cloud_vpc_cidr_pools' => [
|
|
'id', 'pool_key', 'region_id', 'name', 'cidr',
|
|
'prefix_length', 'allocation_prefix', 'state',
|
|
'revision', 'created_at', 'updated_at',
|
|
],
|
|
'cloud_vpcs' => [
|
|
'id', 'vpc_key', 'user_id', 'region_id', 'cidr_pool_id',
|
|
'name', 'cidr', 'prefix_length', 'gateway', 'active_claim', 'state',
|
|
'desired_revision', 'deleted_at', 'created_at', 'updated_at',
|
|
],
|
|
'cloud_vpc_ports' => [
|
|
'id', 'port_key', 'vpc_id', 'instance_id',
|
|
'migration_host_id', 'user_id',
|
|
'private_ip', 'mac_address', 'active_claim', 'state',
|
|
'desired_revision', 'applied_revision', 'last_operation_id',
|
|
'last_error_code', 'attached_at', 'released_at',
|
|
'created_at', 'updated_at',
|
|
],
|
|
'cloud_vpc_host_states' => [
|
|
'id', 'vpc_id', 'host_id', 'desired_revision',
|
|
'applied_revision', 'desired_digest', 'applied_digest',
|
|
'sync_state', 'last_operation_id', 'last_error_code',
|
|
'last_success_at', 'last_failure_at', 'created_at', 'updated_at',
|
|
],
|
|
'cloud_vpc_membership_batches' => [
|
|
'id', 'batch_key', 'vpc_id', 'user_id', 'parent_job_id',
|
|
'kind', 'state', 'desired_revision', 'active_claim',
|
|
'last_error_code', 'terminal_at', 'created_at', 'updated_at',
|
|
],
|
|
'cloud_vpc_membership_batch_items' => [
|
|
'id', 'batch_id', 'user_id', 'instance_id', 'vpc_port_id',
|
|
'host_id', 'child_job_id', 'state', 'last_error_code',
|
|
'created_at', 'updated_at',
|
|
],
|
|
'cloud_agent_completion_events' => [
|
|
'event_id', 'host_id', 'operation_id', 'payload_sha256',
|
|
'outcome', 'effect_may_have_applied', 'safe_to_resubmit',
|
|
'error_code', 'result_json', 'disposition', 'received_at',
|
|
'applied_at',
|
|
],
|
|
'cloud_backup_subscriptions' => [
|
|
'id', 'instance_id', 'user_id', 'offer_id', 'enabled',
|
|
'renew_next_period', 'frequency', 'weekday', 'retention_count',
|
|
'timezone', 'price', 'currency', 'price_version', 'next_run_at',
|
|
'last_scheduled_at', 'last_backup_id', 'created_at', 'updated_at',
|
|
],
|
|
'cloud_backup_period_entitlements' => [
|
|
'id', 'subscription_id', 'instance_id', 'service_period_id',
|
|
'user_id', 'offer_id', 'invoice_id', 'starts_at', 'ends_at',
|
|
'amount', 'full_period_price', 'currency', 'price_version',
|
|
'source', 'paid_at', 'created_at', 'updated_at',
|
|
],
|
|
'cloud_instance_backups' => [
|
|
'id', 'backup_key', 'source_instance_id', 'source_host_id',
|
|
'user_id', 'source_uuid', 'name', 'purpose', 'source',
|
|
'subscription_id', 'scheduled_for', 'state', 'consistency',
|
|
'object_key', 'object_size_bytes', 'virtual_size_bytes',
|
|
'sha256', 'object_etag', 'object_version_id', 'spec_json',
|
|
'sealed_storage_runtime',
|
|
'sealed_credential', 'storage_revision', 'active_job_id',
|
|
'last_operation_id', 'delete_operation_id', 'delete_generation',
|
|
'delete_cycle_attempts', 'delete_presence_confirmations',
|
|
'delete_requested_at', 'delete_last_checked_at',
|
|
'delete_next_check_at', 'delete_attention_at', 'error_code',
|
|
'ready_at', 'created_at', 'updated_at',
|
|
],
|
|
'cloud_deployment_snapshots' => [
|
|
'id', 'snapshot_key', 'user_id', 'backup_id',
|
|
'source_instance_id', 'name', 'state', 'idempotency_key',
|
|
'request_hash', 'error_code', 'ready_at', 'deleted_at',
|
|
'created_at', 'updated_at',
|
|
],
|
|
'cloud_orders' => [
|
|
'deployment_snapshot_id',
|
|
],
|
|
'cloud_backup_restores' => [
|
|
'id', 'restore_key', 'backup_id', 'target_host_id',
|
|
'target_instance_id', 'reservation_id', 'job_id', 'operation_id',
|
|
'new_uuid', 'new_name', 'state', 'error_code', 'ready_at',
|
|
'created_at', 'updated_at',
|
|
],
|
|
'cloud_backup_recoveries' => [
|
|
'id', 'recovery_key', 'backup_id', 'instance_id', 'job_id',
|
|
'operation_id', 'state', 'error_code', 'completed_at',
|
|
'created_at', 'updated_at',
|
|
],
|
|
'cloud_order_items' => [
|
|
'id', 'order_id', 'code', 'label', 'amount', 'currency',
|
|
'snapshot_json', 'created_at',
|
|
],
|
|
'cloud_invoice_items' => [
|
|
'id', 'invoice_id', 'order_item_id', 'code', 'label', 'amount',
|
|
'currency', 'snapshot_json', 'created_at',
|
|
],
|
|
'cloud_instance_migrations' => [
|
|
'id', 'migration_key', 'instance_id', 'vpc_port_id', 'restore_id',
|
|
'source_host_id', 'source_uuid', 'source_reservation_id',
|
|
'target_host_id', 'target_uuid', 'target_reservation_id',
|
|
'source_prepare_job_id', 'target_receive_job_id',
|
|
'firewall_job_id',
|
|
'activate_job_id', 'rollback_job_id', 'cleanup_job_id',
|
|
'cleanup_mode', 'state', 'recovery_action', 'retry_generation',
|
|
'source_endpoint', 'peer_trust_id', 'manifest_digest',
|
|
'source_was_running', 'source_autostart_enabled',
|
|
'source_service_status', 'source_network_status', 'error_code',
|
|
'cutover_at', 'completed_at', 'created_at', 'updated_at',
|
|
],
|
|
'cloud_peer_migration_artifacts' => [
|
|
'id', 'migration_id', 'artifact_id', 'role',
|
|
'source_snapshot_id', 'snapshot_key', 'name', 'consistency',
|
|
'object_size_bytes',
|
|
'virtual_size_bytes', 'sha256', 'state', 'snapshot_created_at',
|
|
'created_at', 'updated_at',
|
|
],
|
|
'cloud_resource_reservations' => [
|
|
'id', 'reservation_key', 'operation_id', 'order_id',
|
|
'backup_restore_id', 'offer_id', 'resource_pool_id', 'host_id',
|
|
'user_id', 'instance_id', 'network_attachment_id',
|
|
'public_ip_pool_id', 'public_ip_id', 'cpu_cores', 'memory_mib',
|
|
'disk_gib', 'state', 'expires_at', 'released_at',
|
|
'release_reason', 'created_at', 'updated_at',
|
|
],
|
|
];
|
|
private const REQUIRED_LOG_COLUMNS = [
|
|
'cloud_vm_metric_samples' => [
|
|
'host_scope', 'vm_uuid', 'host_id', 'user_id', 'sampled_at',
|
|
'cpu_percent', 'memory_used_mib', 'memory_total_mib',
|
|
'disk_read_bps', 'disk_write_bps', 'network_rx_bps',
|
|
'network_tx_bps', 'network_rx_bytes', 'network_tx_bytes',
|
|
],
|
|
'cloud_vm_traffic_totals' => [
|
|
'host_scope', 'vm_uuid', 'host_id', 'user_id',
|
|
'last_observed_at', 'network_signature',
|
|
'network_baseline_json', 'download_rx_bytes',
|
|
'upload_tx_bytes', 'updated_at',
|
|
],
|
|
'cloud_vm_traffic_checkpoints' => [
|
|
'host_scope', 'vm_uuid', 'checkpoint_hour', 'host_id',
|
|
'user_id', 'first_observed_at', 'download_rx_bytes',
|
|
'upload_tx_bytes',
|
|
],
|
|
];
|
|
private const REQUIRED_CHECKS = [
|
|
'cloud_host_vpc_transports' => [
|
|
'chk_cloud_host_vpc_transport_prefix',
|
|
'chk_cloud_host_vpc_transport_mode',
|
|
'chk_cloud_host_vpc_transport_mtu',
|
|
'chk_cloud_host_vpc_transport_state',
|
|
'chk_cloud_host_vpc_transport_revision',
|
|
],
|
|
'cloud_vpc_cidr_pools' => [
|
|
'chk_cloud_vpc_cidr_pool_prefix',
|
|
'chk_cloud_vpc_cidr_pool_state',
|
|
],
|
|
'cloud_vpcs' => [
|
|
'chk_cloud_vpc_prefix', 'chk_cloud_vpc_active_claim',
|
|
'chk_cloud_vpc_state',
|
|
'chk_cloud_vpc_deleted_at',
|
|
],
|
|
'cloud_vpc_ports' => [
|
|
'chk_cloud_vpc_port_active_claim',
|
|
'chk_cloud_vpc_port_state', 'chk_cloud_vpc_port_release',
|
|
'chk_cloud_vpc_port_revision', 'chk_cloud_vpc_port_migration',
|
|
],
|
|
'cloud_vpc_host_states' => [
|
|
'chk_cloud_vpc_host_state', 'chk_cloud_vpc_host_revision',
|
|
],
|
|
'cloud_vpc_membership_batches' => [
|
|
'chk_cloud_vpc_membership_batch_kind',
|
|
'chk_cloud_vpc_membership_batch_state',
|
|
'chk_cloud_vpc_membership_batch_claim',
|
|
],
|
|
'cloud_vpc_membership_batch_items' => [
|
|
'chk_cloud_vpc_membership_batch_item_state',
|
|
],
|
|
'cloud_backup_subscriptions' => [
|
|
'chk_cloud_backup_subscription_frequency',
|
|
'chk_cloud_backup_subscription_weekday',
|
|
'chk_cloud_backup_subscription_retention',
|
|
],
|
|
'cloud_backup_period_entitlements' => [
|
|
'chk_cloud_backup_entitlement_source',
|
|
'chk_cloud_backup_entitlement_window',
|
|
],
|
|
'cloud_deployment_snapshots' => [
|
|
'chk_cloud_deployment_snapshot_state',
|
|
],
|
|
'cloud_invoice_payments' => [
|
|
'chk_cloud_invoice_payment_status',
|
|
],
|
|
'cloud_jobs' => [
|
|
'chk_cloud_job_dispatch_once', 'chk_cloud_job_attempt_shape',
|
|
'chk_cloud_job_phase', 'chk_cloud_job_outcome',
|
|
'chk_cloud_job_effect_resolution',
|
|
'chk_cloud_job_finalization_incident',
|
|
'chk_cloud_job_terminal_shape', 'chk_cloud_job_dispatch_shape',
|
|
'chk_cloud_job_target_shape', 'chk_cloud_job_effect_shape',
|
|
],
|
|
'cloud_resource_reservations' => [
|
|
'chk_cloud_resource_reservation_source',
|
|
],
|
|
'cloud_agent_completion_events' => [
|
|
'chk_cloud_completion_outcome',
|
|
'chk_cloud_completion_disposition',
|
|
],
|
|
];
|
|
private const REQUIRED_INDEXES = [
|
|
'cloud_host_vpc_transports' => [
|
|
'PRIMARY', 'cloud_host_vpc_transport_operation',
|
|
'cloud_host_vpc_transport_state',
|
|
],
|
|
'cloud_vpc_cidr_pools' => [
|
|
'PRIMARY', 'cloud_vpc_cidr_pool_key',
|
|
'cloud_vpc_cidr_pool_region', 'cloud_vpc_cidr_pool_catalog',
|
|
],
|
|
'cloud_vpcs' => [
|
|
'PRIMARY', 'cloud_vpc_key', 'cloud_vpc_region_cidr',
|
|
'cloud_vpc_owner', 'cloud_vpc_region_state',
|
|
'cloud_vpc_pool_state',
|
|
],
|
|
'cloud_vpc_ports' => [
|
|
'PRIMARY', 'cloud_vpc_port_key', 'cloud_vpc_port_ip_claim',
|
|
'cloud_vpc_port_instance_claim', 'cloud_vpc_port_mac',
|
|
'cloud_vpc_port_operation', 'cloud_vpc_port_owner',
|
|
'cloud_vpc_port_vpc_state',
|
|
],
|
|
'cloud_vpc_host_states' => [
|
|
'PRIMARY', 'cloud_vpc_host_identity',
|
|
'cloud_vpc_host_operation', 'cloud_vpc_host_sync',
|
|
],
|
|
'cloud_vpc_membership_batches' => [
|
|
'PRIMARY', 'cloud_vpc_membership_batch_key',
|
|
'cloud_vpc_membership_batch_job',
|
|
'cloud_vpc_membership_batch_active',
|
|
'cloud_vpc_membership_batch_owner',
|
|
],
|
|
'cloud_vpc_membership_batch_items' => [
|
|
'PRIMARY', 'cloud_vpc_membership_batch_instance',
|
|
'cloud_vpc_membership_batch_port',
|
|
'cloud_vpc_membership_batch_child',
|
|
'cloud_vpc_membership_batch_item_owner',
|
|
'cloud_vpc_membership_batch_item_state',
|
|
],
|
|
'cloud_jobs' => [
|
|
'PRIMARY', 'uniq_cloud_operation', 'uniq_cloud_job_request',
|
|
'uniq_cloud_job_completion_event', 'uniq_cloud_provision_order',
|
|
'cloud_job_poll', 'cloud_job_receipt_deadline',
|
|
'cloud_job_backup', 'cloud_job_backup_restore',
|
|
'cloud_job_backup_recovery',
|
|
'cloud_job_vpc', 'cloud_job_vpc_port', 'cloud_job_vpc_batch',
|
|
'cloud_job_supersedes', 'cloud_job_vpc_repair_root',
|
|
],
|
|
'cloud_agent_completion_events' => [
|
|
'PRIMARY', 'uniq_cloud_completion_operation',
|
|
],
|
|
'cloud_backup_subscriptions' => [
|
|
'PRIMARY', 'cloud_backup_subscription_instance',
|
|
'cloud_backup_subscription_due',
|
|
'cloud_backup_subscription_owner',
|
|
],
|
|
'cloud_backup_period_entitlements' => [
|
|
'PRIMARY', 'cloud_backup_entitlement_period',
|
|
'cloud_backup_entitlement_subscription',
|
|
'cloud_backup_entitlement_instance',
|
|
'cloud_backup_entitlement_owner',
|
|
'cloud_backup_entitlement_invoice',
|
|
],
|
|
'cloud_instance_backups' => [
|
|
'PRIMARY', 'cloud_instance_backup_key',
|
|
'cloud_instance_backup_object', 'cloud_instance_backup_schedule',
|
|
'cloud_instance_backup_source',
|
|
'cloud_instance_backup_owner', 'cloud_instance_backup_operation',
|
|
'cloud_instance_backup_delete_due',
|
|
],
|
|
'cloud_deployment_snapshots' => [
|
|
'PRIMARY', 'cloud_deployment_snapshot_key',
|
|
'cloud_deployment_snapshot_backup',
|
|
'cloud_deployment_snapshot_request',
|
|
'cloud_deployment_snapshot_owner',
|
|
'cloud_deployment_snapshot_source',
|
|
],
|
|
'cloud_orders' => [
|
|
'cloud_order_deployment_snapshot',
|
|
],
|
|
'cloud_backup_restores' => [
|
|
'PRIMARY', 'cloud_backup_restore_key',
|
|
'cloud_backup_restore_operation',
|
|
'cloud_backup_restore_reservation',
|
|
'cloud_backup_restore_instance', 'cloud_backup_restore_backup',
|
|
'cloud_backup_restore_host',
|
|
],
|
|
'cloud_backup_recoveries' => [
|
|
'PRIMARY', 'cloud_backup_recovery_key',
|
|
'cloud_backup_recovery_operation', 'cloud_backup_recovery_job',
|
|
'cloud_backup_recovery_instance', 'cloud_backup_recovery_backup',
|
|
],
|
|
'cloud_order_items' => [
|
|
'PRIMARY', 'cloud_order_item_code', 'cloud_order_item_order',
|
|
],
|
|
'cloud_invoice_items' => [
|
|
'PRIMARY', 'cloud_invoice_item_code',
|
|
'cloud_invoice_item_invoice', 'cloud_invoice_item_order_item',
|
|
],
|
|
'cloud_instance_migrations' => [
|
|
'PRIMARY', 'cloud_instance_migration_key',
|
|
'cloud_instance_migration_restore',
|
|
'cloud_instance_migration_prepare_job',
|
|
'cloud_instance_migration_receive_job',
|
|
'cloud_instance_migration_firewall_job',
|
|
'cloud_instance_migration_activate_job',
|
|
'cloud_instance_migration_rollback_job',
|
|
'cloud_instance_migration_cleanup_job',
|
|
'cloud_instance_migration_instance',
|
|
'cloud_instance_migration_vpc_port',
|
|
'cloud_instance_migration_source',
|
|
'cloud_instance_migration_target',
|
|
],
|
|
'cloud_peer_migration_artifacts' => [
|
|
'PRIMARY', 'cloud_peer_migration_artifact',
|
|
'cloud_peer_migration_snapshot',
|
|
'cloud_peer_migration_source_snapshot',
|
|
'cloud_peer_migration_state',
|
|
],
|
|
'cloud_resource_reservations' => [
|
|
'PRIMARY', 'cloud_resource_reservation_key',
|
|
'cloud_resource_reservation_operation',
|
|
'cloud_resource_reservation_order',
|
|
'cloud_resource_reservation_backup_restore',
|
|
'cloud_resource_reservation_host',
|
|
'cloud_resource_reservation_pool',
|
|
'cloud_resource_reservation_instance',
|
|
'cloud_resource_reservation_network',
|
|
'cloud_resource_reservation_ip',
|
|
],
|
|
];
|
|
private const REQUIRED_FOREIGN_KEYS = [
|
|
'cloud_jobs' => ['fk_cloud_job_user'],
|
|
];
|
|
|
|
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();
|
|
$schema = $connection->getSchemaBuilder();
|
|
if (!$schema->hasTable('user') || !$schema->hasTable('shop')) {
|
|
throw new \RuntimeException('请先在全新业务数据库导入 web/sql/ss.sql');
|
|
}
|
|
|
|
$logConnection = User::getConnectionResolver()->connection('log');
|
|
// MySQL advisory lock names are limited to 64 characters. Lock both
|
|
// schemas in a fixed order: one main database can never be installed
|
|
// concurrently with two log targets, and one shared log database can
|
|
// never receive concurrent DDL from two main installations.
|
|
$mainLockName = 'virt-cloud-main:' . substr(hash('sha256',
|
|
(string) $connection->getDatabaseName()), 0, 48);
|
|
$logLockName = 'virt-cloud-log:' . substr(hash('sha256',
|
|
(string) $logConnection->getDatabaseName()), 0, 48);
|
|
$mainLocked = false;
|
|
$logLocked = false;
|
|
try {
|
|
$locked = $connection->selectOne(
|
|
'SELECT GET_LOCK(?, 30) AS acquired', [$mainLockName]
|
|
);
|
|
$mainLocked = (int) ($locked->acquired ?? 0) === 1;
|
|
if (!$mainLocked) {
|
|
throw new \RuntimeException(
|
|
'无法取得云业务数据库初始化锁,请稍后重试'
|
|
);
|
|
}
|
|
$locked = $logConnection->selectOne(
|
|
'SELECT GET_LOCK(?, 30) AS acquired', [$logLockName]
|
|
);
|
|
$logLocked = (int) ($locked->acquired ?? 0) === 1;
|
|
if (!$logLocked) {
|
|
throw new \RuntimeException(
|
|
'无法取得云日志数据库初始化锁,请稍后重试'
|
|
);
|
|
}
|
|
$installed = self::assertFreshSchemaBoundary(
|
|
$connection, $logConnection
|
|
);
|
|
if (!$installed) {
|
|
// MySQL DDL commits implicitly. A failed first install is
|
|
// intentionally not repaired: without the final marker the
|
|
// next run rejects the partial database and requires a fresh
|
|
// one, exactly matching the no-migration deployment contract.
|
|
$connection->unprepared(self::schema('cloud.sql'));
|
|
$logConnection->unprepared(self::schema('cloud_log.sql'));
|
|
self::assertInstalledSchema($connection, $logConnection);
|
|
self::ensureMultiHostDefaults($connection);
|
|
// One atomic insert publishes both the source version and the
|
|
// exact installed information_schema signature. The version
|
|
// row is therefore never visible without its fingerprint.
|
|
$connection->table('configurations')->insert([
|
|
[
|
|
'name' => 'cloud_schema_fingerprint',
|
|
'value' => self::installedSchemaFingerprint(
|
|
$connection, $logConnection
|
|
),
|
|
],
|
|
[
|
|
'name' => 'cloud_schema_version',
|
|
'value' => self::schemaMarker(),
|
|
],
|
|
]);
|
|
} else {
|
|
self::ensureMultiHostDefaults($connection);
|
|
}
|
|
} finally {
|
|
if ($logLocked) {
|
|
$logConnection->selectOne(
|
|
'SELECT RELEASE_LOCK(?) AS released', [$logLockName]
|
|
);
|
|
}
|
|
if ($mainLocked) {
|
|
$connection->selectOne(
|
|
'SELECT RELEASE_LOCK(?) AS released', [$mainLockName]
|
|
);
|
|
}
|
|
}
|
|
|
|
echo "云业务表与 Agent 指标日志表已准备。未连接或修改任何宿主机。\n";
|
|
return true;
|
|
}
|
|
|
|
/** Seed only immutable/default control rows in an otherwise fresh schema. */
|
|
private static function ensureMultiHostDefaults($connection): void
|
|
{
|
|
$connection->table('configurations')->insertOrIgnore([
|
|
'name' => 'cloud_network_lines_enabled',
|
|
'value' => 'false',
|
|
]);
|
|
$connection->table('configurations')->insertOrIgnore([
|
|
'name' => 'cloud_vpc_enabled',
|
|
'value' => 'false',
|
|
]);
|
|
}
|
|
|
|
/** Refuse to mix the Go/Agent schema with any unmarked cloud database. */
|
|
private static function assertFreshSchemaBoundary($connection,
|
|
$logConnection): bool
|
|
{
|
|
$marker = $connection->table('configurations')
|
|
->where('name', 'cloud_schema_version')->first(['value']);
|
|
if ($marker !== null) {
|
|
if (!hash_equals(self::schemaMarker(), (string) $marker->value)) {
|
|
throw new \RuntimeException(
|
|
'虚拟化数据库版本不兼容,请使用全新数据库'
|
|
);
|
|
}
|
|
foreach (self::RETIRED_LOG_TABLES as $retiredTable) {
|
|
if ($logConnection->getSchemaBuilder()->hasTable($retiredTable)) {
|
|
throw new \RuntimeException(
|
|
'日志库包含已废弃的 Python Engine 表,请使用全新日志库'
|
|
);
|
|
}
|
|
}
|
|
self::assertInstalledSchema($connection, $logConnection);
|
|
$fingerprint = $connection->table('configurations')
|
|
->where('name', 'cloud_schema_fingerprint')->first(['value']);
|
|
$actual = self::installedSchemaFingerprint(
|
|
$connection, $logConnection
|
|
);
|
|
if ($fingerprint === null
|
|
|| !is_string($fingerprint->value)
|
|
|| preg_match('/^[a-f0-9]{64}$/D',
|
|
$fingerprint->value) !== 1
|
|
|| !hash_equals($fingerprint->value, $actual)) {
|
|
throw new \RuntimeException(
|
|
'虚拟化数据库结构已变化,请使用全新数据库'
|
|
);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
if ($connection->table('configurations')
|
|
->where('name', 'cloud_schema_fingerprint')->exists()) {
|
|
throw new \RuntimeException(
|
|
'检测到不完整的云数据库安装标记,请使用全新数据库'
|
|
);
|
|
}
|
|
|
|
foreach (self::MAIN_TABLES as $table) {
|
|
if ($connection->getSchemaBuilder()->hasTable($table)) {
|
|
throw new \RuntimeException(
|
|
'检测到未标记的旧虚拟化数据库,不支持原地升级'
|
|
);
|
|
}
|
|
}
|
|
foreach (array_merge(self::LOG_TABLES, self::RETIRED_LOG_TABLES)
|
|
as $table) {
|
|
if ($logConnection->getSchemaBuilder()->hasTable($table)) {
|
|
throw new \RuntimeException(
|
|
'检测到未标记的虚拟化日志库,不支持原地升级'
|
|
);
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/** Reject a marker that points at a partial, edited or incompatible schema. */
|
|
private static function assertInstalledSchema($connection,
|
|
$logConnection): void
|
|
{
|
|
$schema = $connection->getSchemaBuilder();
|
|
foreach (self::MAIN_TABLES as $table) {
|
|
if (!$schema->hasTable($table)) {
|
|
throw new \RuntimeException(
|
|
'云数据库结构不完整,请使用全新数据库:' . $table
|
|
);
|
|
}
|
|
}
|
|
$logSchema = $logConnection->getSchemaBuilder();
|
|
foreach (self::LOG_TABLES as $table) {
|
|
if (!$logSchema->hasTable($table)) {
|
|
throw new \RuntimeException(
|
|
'云日志数据库结构不完整,请使用全新日志库:' . $table
|
|
);
|
|
}
|
|
}
|
|
foreach (self::REQUIRED_MAIN_COLUMNS as $table => $columns) {
|
|
foreach ($columns as $column) {
|
|
if (!$schema->hasColumn($table, $column)) {
|
|
throw new \RuntimeException(
|
|
'云数据库缺少必需字段,请使用全新数据库:'
|
|
. $table . '.' . $column
|
|
);
|
|
}
|
|
}
|
|
}
|
|
foreach (self::REQUIRED_LOG_COLUMNS as $table => $columns) {
|
|
foreach ($columns as $column) {
|
|
if (!$logSchema->hasColumn($table, $column)) {
|
|
throw new \RuntimeException(
|
|
'云日志数据库缺少必需字段,请使用全新日志库:'
|
|
. $table . '.' . $column
|
|
);
|
|
}
|
|
}
|
|
}
|
|
self::assertNamedDatabaseObjects(
|
|
$connection, 'TABLE_CONSTRAINTS', 'CONSTRAINT_NAME',
|
|
'CONSTRAINT_TYPE', 'CHECK', self::REQUIRED_CHECKS
|
|
);
|
|
self::assertNamedDatabaseObjects(
|
|
$connection, 'STATISTICS', 'INDEX_NAME', null, null,
|
|
self::REQUIRED_INDEXES
|
|
);
|
|
self::assertNamedDatabaseObjects(
|
|
$connection, 'TABLE_CONSTRAINTS', 'CONSTRAINT_NAME',
|
|
'CONSTRAINT_TYPE', 'FOREIGN KEY', self::REQUIRED_FOREIGN_KEYS
|
|
);
|
|
}
|
|
|
|
private static function assertNamedDatabaseObjects($connection,
|
|
string $informationTable, string $nameColumn, ?string $typeColumn,
|
|
?string $type, array $required): void
|
|
{
|
|
$database = (string) $connection->getDatabaseName();
|
|
foreach ($required as $table => $names) {
|
|
$sql = 'SELECT DISTINCT ' . $nameColumn . ' AS object_name FROM '
|
|
. 'information_schema.' . $informationTable
|
|
. ' WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?';
|
|
$bindings = [$database, $table];
|
|
if ($typeColumn !== null && $type !== null) {
|
|
$sql .= ' AND ' . $typeColumn . ' = ?';
|
|
$bindings[] = $type;
|
|
}
|
|
$found = [];
|
|
foreach ($connection->select($sql, $bindings) as $row) {
|
|
$found[(string) ($row->object_name ?? '')] = true;
|
|
}
|
|
foreach ($names as $name) {
|
|
if (!isset($found[$name])) {
|
|
throw new \RuntimeException(
|
|
'云数据库结构校验失败,请使用全新数据库:'
|
|
. $table . '.' . $name
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function schemaMarker(): string
|
|
{
|
|
return self::SCHEMA_VERSION . ':' . hash('sha256',
|
|
self::schema('cloud.sql') . "\0" . self::schema('cloud_log.sql')
|
|
);
|
|
}
|
|
|
|
/** Hash the actual columns, indexes and constraints of both cloud schemas. */
|
|
private static function installedSchemaFingerprint($connection,
|
|
$logConnection): string
|
|
{
|
|
return hash('sha256', json_encode([
|
|
'main' => self::schemaObjects($connection, self::MAIN_TABLES),
|
|
'log' => self::schemaObjects($logConnection, self::LOG_TABLES),
|
|
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
|
| JSON_UNESCAPED_UNICODE));
|
|
}
|
|
|
|
private static function schemaObjects($connection, array $tables): array
|
|
{
|
|
$database = (string) $connection->getDatabaseName();
|
|
$placeholders = implode(',', array_fill(0, count($tables), '?'));
|
|
$bindings = array_merge([$database], $tables);
|
|
$queries = [
|
|
'tables' => 'SELECT TABLE_NAME, ENGINE, TABLE_COLLATION '
|
|
. 'FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? '
|
|
. 'AND TABLE_NAME IN (' . $placeholders . ') '
|
|
. 'ORDER BY TABLE_NAME',
|
|
'columns' => 'SELECT TABLE_NAME, ORDINAL_POSITION, COLUMN_NAME, '
|
|
. 'COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, EXTRA, '
|
|
. 'COLLATION_NAME FROM information_schema.COLUMNS '
|
|
. 'WHERE TABLE_SCHEMA = ? AND TABLE_NAME IN ('
|
|
. $placeholders . ') ORDER BY TABLE_NAME, ORDINAL_POSITION',
|
|
'indexes' => 'SELECT TABLE_NAME, INDEX_NAME, NON_UNIQUE, '
|
|
. 'SEQ_IN_INDEX, COLUMN_NAME, SUB_PART, INDEX_TYPE '
|
|
. 'FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = ? '
|
|
. 'AND TABLE_NAME IN (' . $placeholders . ') '
|
|
. 'ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX',
|
|
'constraints' => 'SELECT tc.TABLE_NAME, tc.CONSTRAINT_NAME, '
|
|
. 'tc.CONSTRAINT_TYPE, cc.CHECK_CLAUSE '
|
|
. 'FROM information_schema.TABLE_CONSTRAINTS tc LEFT JOIN '
|
|
. 'information_schema.CHECK_CONSTRAINTS cc ON '
|
|
. 'cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA AND '
|
|
. 'cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME '
|
|
. 'WHERE tc.TABLE_SCHEMA = ? AND tc.TABLE_NAME IN ('
|
|
. $placeholders . ') ORDER BY tc.TABLE_NAME, '
|
|
. 'tc.CONSTRAINT_NAME',
|
|
'keys' => 'SELECT TABLE_NAME, CONSTRAINT_NAME, ORDINAL_POSITION, '
|
|
. 'COLUMN_NAME, REFERENCED_TABLE_NAME, '
|
|
. 'REFERENCED_COLUMN_NAME FROM '
|
|
. 'information_schema.KEY_COLUMN_USAGE '
|
|
. 'WHERE TABLE_SCHEMA = ? AND TABLE_NAME IN ('
|
|
. $placeholders . ') ORDER BY TABLE_NAME, CONSTRAINT_NAME, '
|
|
. 'ORDINAL_POSITION',
|
|
'referential' => 'SELECT TABLE_NAME, CONSTRAINT_NAME, '
|
|
. 'UNIQUE_CONSTRAINT_SCHEMA, UNIQUE_CONSTRAINT_NAME, '
|
|
. 'MATCH_OPTION, UPDATE_RULE, DELETE_RULE, '
|
|
. 'REFERENCED_TABLE_NAME FROM '
|
|
. 'information_schema.REFERENTIAL_CONSTRAINTS '
|
|
. 'WHERE CONSTRAINT_SCHEMA = ? AND TABLE_NAME IN ('
|
|
. $placeholders . ') ORDER BY TABLE_NAME, CONSTRAINT_NAME',
|
|
];
|
|
$objects = [];
|
|
foreach ($queries as $name => $sql) {
|
|
$objects[$name] = array_map(static function ($row): array {
|
|
$value = (array) $row;
|
|
ksort($value, SORT_STRING);
|
|
return $value;
|
|
}, $connection->select($sql, $bindings));
|
|
}
|
|
return $objects;
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|