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.
1419 lines
57 KiB
PHP
1419 lines
57 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudBackupRestore;
|
|
use App\Models\CloudInstance;
|
|
use App\Models\CloudInstanceBackup;
|
|
use App\Models\CloudInstanceFirewall;
|
|
use App\Models\CloudInstanceMigration;
|
|
use App\Models\CloudJob;
|
|
use App\Models\CloudOrder;
|
|
use App\Models\CloudPublicIp;
|
|
use App\Models\CloudResourceReservation;
|
|
|
|
/** Cold host maintenance migration while retaining one logical service row. */
|
|
final class CloudInstanceMigrationService
|
|
{
|
|
private const STORAGE_PURPOSE = 'object-storage-backup-runtime';
|
|
private const TRANSFER_URL_SECONDS = 604800;
|
|
private const OPEN_STATES = [
|
|
'backing_up', 'restoring', 'cutover', 'cleanup_pending',
|
|
'firewall_running', 'firewall_failed', 'firewall_uncertain',
|
|
'activation_running', 'activation_failed', 'activation_uncertain',
|
|
'rollback_running', 'rollback_failed', 'rollback_uncertain',
|
|
'cleanup_running',
|
|
'cleanup_uncertain', 'source_retained', 'uncertain',
|
|
];
|
|
|
|
public static function assertStartAvailable(CloudInstance $instance,
|
|
int $targetHostId, array $resources,
|
|
int $snapshotDiskGib = 0,
|
|
?int $excludeMigrationId = null): void
|
|
{
|
|
if (!in_array((string) $instance->service_status,
|
|
['active', 'exempt', 'expired_grace', 'suspended_expired'], true)
|
|
|| !in_array((string) $instance->network_status,
|
|
['active', 'blocked_traffic', 'blocked_expired'], true)) {
|
|
throw new CloudError(
|
|
'实例服务或网络状态正在变化,暂不能维护迁移',
|
|
409
|
|
);
|
|
}
|
|
if ($targetHostId === (int) $instance->host_id) {
|
|
throw new CloudError('维护迁移必须选择其他宿主机', 409);
|
|
}
|
|
if ((int) ($instance->reservation_id ?? 0) < 1
|
|
|| (int) ($instance->order_id ?? 0) < 1
|
|
|| (int) ($instance->resource_pool_id ?? 0) < 1) {
|
|
throw new CloudError('只有具备完整订单和资源预留的实例可以维护迁移', 409);
|
|
}
|
|
$open = CloudInstanceMigration::where(
|
|
'instance_id', (int) $instance->id
|
|
)->whereIn('state', self::OPEN_STATES);
|
|
if ($excludeMigrationId !== null) {
|
|
$open->where('id', '<>', $excludeMigrationId);
|
|
}
|
|
if ($open->exists()) {
|
|
throw new CloudError('实例已有未完成的维护迁移', 409);
|
|
}
|
|
$allowed = array_filter(
|
|
CloudPlacementService::maintenanceMigrationTargets(
|
|
$instance,
|
|
$resources,
|
|
$snapshotDiskGib
|
|
),
|
|
static fn (array $target): bool =>
|
|
(int) ($target['id'] ?? 0) === $targetHostId
|
|
);
|
|
if ($allowed === []) {
|
|
throw new CloudError(
|
|
'目标宿主机必须位于同一资源池并具备可用容量、br0 和公网 IP',
|
|
409
|
|
);
|
|
}
|
|
CloudFirewallService::assertMaintenanceMigrationReady($instance);
|
|
}
|
|
|
|
public static function createLedgerLocked(CloudInstance $instance,
|
|
CloudInstanceBackup $backup, CloudJob $job, int $targetHostId,
|
|
string $cleanupMode, array $resources): CloudInstanceMigration
|
|
{
|
|
if (!in_array($cleanupMode, ['retain', 'delete'], true)
|
|
|| (int) $backup->source_instance_id !== (int) $instance->id
|
|
|| (int) $job->backup_id !== (int) $backup->id
|
|
|| (int) $job->instance_id !== (int) $instance->id) {
|
|
throw new \LogicException('Invalid maintenance migration ledger');
|
|
}
|
|
$migration = new CloudInstanceMigration();
|
|
$migration->migration_key = (string) $backup->backup_key;
|
|
$migration->instance_id = (int) $instance->id;
|
|
$migration->backup_id = (int) $backup->id;
|
|
$migration->restore_id = null;
|
|
$migration->source_host_id = (int) $instance->host_id;
|
|
$migration->source_uuid = strtolower((string) $instance->uuid);
|
|
$migration->source_reservation_id = (int) $instance->reservation_id;
|
|
$migration->target_host_id = $targetHostId;
|
|
$migration->target_uuid = self::uuidV4();
|
|
$migration->target_reservation_id = null;
|
|
$migration->backup_job_id = (int) $job->id;
|
|
$migration->restore_job_id = null;
|
|
$migration->firewall_job_id = null;
|
|
$migration->activate_job_id = null;
|
|
$migration->rollback_job_id = null;
|
|
$migration->cleanup_job_id = null;
|
|
$migration->cleanup_mode = $cleanupMode;
|
|
$migration->state = 'backing_up';
|
|
$migration->source_was_running = null;
|
|
$migration->source_autostart_enabled = null;
|
|
$migration->source_service_status = (string) $instance->service_status;
|
|
$migration->source_network_status = (string) $instance->network_status;
|
|
$migration->error_code = '';
|
|
$migration->cutover_at = null;
|
|
$migration->completed_at = null;
|
|
$migration->created_at = $migration->updated_at = time();
|
|
$migration->save();
|
|
|
|
// Hold the target capacity and address before the backup task can stop
|
|
// the source VM. A later restore finalizer consumes this exact
|
|
// reservation; it never performs a second best-effort scheduler pass
|
|
// after downtime has started.
|
|
$restore = new CloudBackupRestore();
|
|
$restore->restore_key = bin2hex(random_bytes(16));
|
|
$restore->backup_id = (int) $backup->id;
|
|
$restore->target_host_id = $targetHostId;
|
|
// Independent restores bind their newly created instance here. A
|
|
// maintenance restore deliberately keeps the original instance row, so
|
|
// leaving this nullable also permits future migrations of that service.
|
|
$restore->target_instance_id = null;
|
|
$restore->reservation_id = null;
|
|
$restore->job_id = null;
|
|
$restore->operation_id = bin2hex(random_bytes(16));
|
|
$restore->new_uuid = (string) $migration->target_uuid;
|
|
$restore->new_name = (string) $instance->name;
|
|
$restore->state = 'reserved';
|
|
$restore->error_code = '';
|
|
$restore->ready_at = null;
|
|
$restore->created_at = $restore->updated_at = time();
|
|
$restore->save();
|
|
$placement = CloudPlacementService::reserveBackupRestore(
|
|
$restore,
|
|
(int) $instance->user_id,
|
|
$resources,
|
|
(int) $instance->resource_pool_id,
|
|
CloudMigrationBundleService::additionalDiskGib(
|
|
CloudMigrationBundleService::freezeSnapshotsLocked($instance)
|
|
)
|
|
);
|
|
$reservation = $placement['reservation'];
|
|
$reservation->instance_id = (int) $instance->id;
|
|
$reservation->updated_at = time();
|
|
$reservation->save();
|
|
$restore->reservation_id = (int) $reservation->id;
|
|
$restore->updated_at = time();
|
|
$restore->save();
|
|
$migration->restore_id = (int) $restore->id;
|
|
$migration->target_reservation_id = (int) $reservation->id;
|
|
$migration->updated_at = time();
|
|
$migration->save();
|
|
return $migration;
|
|
}
|
|
|
|
public static function display(CloudInstanceMigration $migration): array
|
|
{
|
|
$state = (string) $migration->state;
|
|
return [
|
|
'id' => (string) $migration->id,
|
|
'state' => $state,
|
|
'cleanup_mode' => (string) $migration->cleanup_mode,
|
|
'source_host_id' => (string) $migration->source_host_id,
|
|
'target_host_id' => (string) $migration->target_host_id,
|
|
'backup_id' => (string) $migration->backup_id,
|
|
'backup_task_id' => (string) $migration->backup_job_id,
|
|
'restore_task_id' => $migration->restore_job_id === null
|
|
? null : (string) $migration->restore_job_id,
|
|
'cleanup_task_id' => $migration->cleanup_job_id === null
|
|
? null : (string) $migration->cleanup_job_id,
|
|
'firewall_task_id' => $migration->firewall_job_id === null
|
|
? null : (string) $migration->firewall_job_id,
|
|
'activation_task_id' => $migration->activate_job_id === null
|
|
? null : (string) $migration->activate_job_id,
|
|
'rollback_task_id' => $migration->rollback_job_id === null
|
|
? null : (string) $migration->rollback_job_id,
|
|
'source_retained' => in_array($state,
|
|
['source_retained', 'cleanup_uncertain'], true),
|
|
'can_cleanup' => $state === 'source_retained',
|
|
'error_code' => (string) $migration->error_code,
|
|
'cutover_at' => $migration->cutover_at === null
|
|
? null : (int) $migration->cutover_at,
|
|
'completed_at' => $migration->completed_at === null
|
|
? null : (int) $migration->completed_at,
|
|
'created_at' => (int) $migration->created_at,
|
|
'updated_at' => (int) $migration->updated_at,
|
|
];
|
|
}
|
|
|
|
public static function ownsRestore(int $restoreId): bool
|
|
{
|
|
return self::catalogAvailable()
|
|
&& CloudInstanceMigration::where('restore_id', $restoreId)->exists();
|
|
}
|
|
|
|
public static function ownsBackupJob(int $jobId): bool
|
|
{
|
|
return self::catalogAvailable()
|
|
&& CloudInstanceMigration::where(
|
|
'backup_job_id', $jobId
|
|
)->exists();
|
|
}
|
|
|
|
public static function hasOpenMigration(int $instanceId): bool
|
|
{
|
|
return $instanceId > 0
|
|
&& self::catalogAvailable()
|
|
&& CloudInstanceMigration::where('instance_id', $instanceId)
|
|
->whereIn('state', self::OPEN_STATES)->exists();
|
|
}
|
|
|
|
/** Keep ordinary mutations away from a service with two host identities. */
|
|
public static function assertInstanceMutationAvailable(
|
|
CloudInstance $instance
|
|
): void {
|
|
if (self::hasOpenMigration((int) $instance->id)) {
|
|
throw new CloudError(
|
|
'实例正在维护迁移,请先完成状态核对或清理源副本',
|
|
409
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Called after the ordinary backup finalizer in the same worker lock. */
|
|
public static function finishJobLocked(CloudJob $job, string $status,
|
|
$result, array $payload): void
|
|
{
|
|
if (!self::catalogAvailable()) {
|
|
return;
|
|
}
|
|
if ((string) $job->kind === 'backup_create') {
|
|
$migration = CloudInstanceMigration::where(
|
|
'backup_job_id', (int) $job->id
|
|
)->lockForUpdate()->first();
|
|
if ($migration !== null) {
|
|
self::finishBackupLocked(
|
|
$migration,
|
|
$job,
|
|
$status,
|
|
$result
|
|
);
|
|
}
|
|
return;
|
|
}
|
|
if ((string) $job->kind === 'backup_restore') {
|
|
$migration = CloudInstanceMigration::where(
|
|
'restore_job_id', (int) $job->id
|
|
)->lockForUpdate()->first();
|
|
if ($migration !== null) {
|
|
self::finishRestoreLocked(
|
|
$migration,
|
|
$job,
|
|
$status,
|
|
$result,
|
|
$payload
|
|
);
|
|
}
|
|
return;
|
|
}
|
|
if ((string) $job->kind === 'instance_migration_cleanup') {
|
|
$migration = CloudInstanceMigration::where(
|
|
'cleanup_job_id', (int) $job->id
|
|
)->lockForUpdate()->first();
|
|
if ($migration !== null) {
|
|
self::finishCleanupLocked($migration, $job, $status, $result);
|
|
}
|
|
return;
|
|
}
|
|
if ((string) $job->kind === 'firewall_apply') {
|
|
$migration = CloudInstanceMigration::where(
|
|
'firewall_job_id', (int) $job->id
|
|
)->lockForUpdate()->first();
|
|
if ($migration !== null) {
|
|
self::finishFirewallLocked($migration, $job, $status);
|
|
}
|
|
return;
|
|
}
|
|
if ((string) $job->kind === 'instance_migration_activate') {
|
|
$migration = CloudInstanceMigration::where(
|
|
'activate_job_id', (int) $job->id
|
|
)->lockForUpdate()->first();
|
|
if ($migration !== null) {
|
|
self::finishActivationLocked(
|
|
$migration,
|
|
$job,
|
|
$status,
|
|
$result
|
|
);
|
|
}
|
|
return;
|
|
}
|
|
if ((string) $job->kind === 'instance_migration_rollback') {
|
|
$migration = CloudInstanceMigration::where(
|
|
'rollback_job_id', (int) $job->id
|
|
)->lockForUpdate()->first();
|
|
if ($migration !== null) {
|
|
self::finishRollbackLocked($migration, $job, $status, $result);
|
|
}
|
|
}
|
|
}
|
|
|
|
public static function markJobUncertain(CloudJob $job): void
|
|
{
|
|
if (!self::catalogAvailable()) {
|
|
return;
|
|
}
|
|
$field = match ((string) $job->kind) {
|
|
'backup_create' => 'backup_job_id',
|
|
'backup_restore' => 'restore_job_id',
|
|
'firewall_apply' => 'firewall_job_id',
|
|
'instance_migration_activate' => 'activate_job_id',
|
|
'instance_migration_rollback' => 'rollback_job_id',
|
|
'instance_migration_cleanup' => 'cleanup_job_id',
|
|
default => null,
|
|
};
|
|
if ($field === null) {
|
|
return;
|
|
}
|
|
CloudInstanceMigration::where($field, (int) $job->id)
|
|
->whereIn('state', self::OPEN_STATES)
|
|
->update([
|
|
'state' => match ((string) $job->kind) {
|
|
'instance_migration_cleanup' => 'cleanup_uncertain',
|
|
'firewall_apply' => 'firewall_uncertain',
|
|
'instance_migration_activate' => 'activation_uncertain',
|
|
'instance_migration_rollback' => 'rollback_uncertain',
|
|
default => 'uncertain',
|
|
},
|
|
'error_code' => 'finalization_incident',
|
|
'updated_at' => time(),
|
|
]);
|
|
}
|
|
|
|
/** Queue an explicit later cleanup only after a proven non-applied failure. */
|
|
public static function cleanupRetained(CloudInstance $instance,
|
|
array $actor, array $input): CloudJob
|
|
{
|
|
CloudAccess::manage($actor);
|
|
CloudInput::only($input, ['confirm_source_cleanup']);
|
|
if (($input['confirm_source_cleanup'] ?? false) !== true) {
|
|
throw new CloudError('请确认删除源宿主机上的旧副本');
|
|
}
|
|
return $instance->getConnection()->transaction(function () use (
|
|
$instance,
|
|
$actor
|
|
): CloudJob {
|
|
$locked = CloudInstance::where('id', (int) $instance->id)
|
|
->lockForUpdate()->firstOrFail();
|
|
$migration = CloudInstanceMigration::where(
|
|
'instance_id', (int) $locked->id
|
|
)->where('state', 'source_retained')->orderByDesc('id')
|
|
->lockForUpdate()->first();
|
|
if ($migration === null) {
|
|
throw new CloudError('当前没有可安全清理的迁移源副本', 409);
|
|
}
|
|
return self::queueCleanupLocked($migration, $locked, $actor);
|
|
}, 3);
|
|
}
|
|
|
|
private static function finishBackupLocked(CloudInstanceMigration $migration,
|
|
CloudJob $job, string $status, $result): void
|
|
{
|
|
if ((int) $migration->backup_id !== (int) $job->backup_id
|
|
|| (int) $migration->instance_id !== (int) $job->instance_id
|
|
|| (int) $migration->source_host_id !== (int) $job->host_id) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移备份任务与迁移账本不一致',
|
|
409
|
|
);
|
|
}
|
|
if ($status === 'running') {
|
|
return;
|
|
}
|
|
if ($status === 'uncertain') {
|
|
self::setState($migration, 'uncertain', 'operation_effect_unknown');
|
|
return;
|
|
}
|
|
if ($status === 'failed') {
|
|
if ((string) $migration->state === 'failed') {
|
|
return;
|
|
}
|
|
self::releasePreparedTargetLocked(
|
|
$migration,
|
|
'migration_backup_failed'
|
|
);
|
|
self::setState($migration, 'failed', 'migration_backup_failed');
|
|
return;
|
|
}
|
|
if (!is_array($result)
|
|
|| ($result['source_stopped'] ?? null) !== true
|
|
|| ($result['source_autostart_disabled'] ?? null) !== true
|
|
|| !is_bool($result['source_was_running'] ?? null)
|
|
|| !is_bool($result['source_autostart_enabled'] ?? null)) {
|
|
throw new CloudError('Agent 未确认迁移源实例已安全停止', 502);
|
|
}
|
|
$migration->source_was_running = $result['source_was_running'];
|
|
$migration->source_autostart_enabled =
|
|
$result['source_autostart_enabled'];
|
|
CloudMigrationBundleService::finishExportLocked($migration, $result);
|
|
self::queueRestoreLocked($migration, $job);
|
|
}
|
|
|
|
/** Release a target that was held before any source-side mutation ran. */
|
|
private static function releasePreparedTargetLocked(
|
|
CloudInstanceMigration $migration,
|
|
string $errorCode
|
|
): void {
|
|
$restore = CloudBackupRestore::where(
|
|
'id',
|
|
(int) $migration->restore_id
|
|
)->lockForUpdate()->first();
|
|
if ($restore === null) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移缺少目标预留目录',
|
|
409
|
|
);
|
|
}
|
|
if ((string) $restore->state === 'failed') {
|
|
return;
|
|
}
|
|
$placement = CloudPlacementService::preparedBackupRestorePlacement(
|
|
$restore,
|
|
(int) $migration->instance_id
|
|
);
|
|
CloudPlacementService::finishBackupRestore(
|
|
$restore,
|
|
(int) $migration->instance_id,
|
|
(string) $placement['network']['public_ip_cidr'],
|
|
'failed'
|
|
);
|
|
$restore->state = 'failed';
|
|
$restore->error_code = $errorCode;
|
|
$restore->updated_at = time();
|
|
$restore->save();
|
|
}
|
|
|
|
private static function queueRestoreLocked(CloudInstanceMigration $migration,
|
|
CloudJob $backupJob): void
|
|
{
|
|
if (!in_array((string) $migration->state,
|
|
['backing_up', 'uncertain'], true)) {
|
|
if ($migration->restore_job_id !== null) {
|
|
return;
|
|
}
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移不能从当前状态创建目标恢复任务',
|
|
409
|
|
);
|
|
}
|
|
$backup = CloudInstanceBackup::where(
|
|
'id', (int) $migration->backup_id
|
|
)->lockForUpdate()->first();
|
|
$instance = CloudInstance::where(
|
|
'id', (int) $migration->instance_id
|
|
)->lockForUpdate()->first();
|
|
if ($backup === null || $instance === null
|
|
|| (string) $backup->state !== 'ready'
|
|
|| (int) $instance->host_id !== (int) $migration->source_host_id
|
|
|| !hash_equals(strtolower((string) $instance->uuid),
|
|
strtolower((string) $migration->source_uuid))
|
|
|| (int) $instance->reservation_id
|
|
!== (int) $migration->source_reservation_id
|
|
|| !hash_equals((string) $migration->source_service_status,
|
|
(string) $instance->service_status)
|
|
|| !hash_equals((string) $migration->source_network_status,
|
|
(string) $instance->network_status)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移源实例在备份完成前发生变化',
|
|
409
|
|
);
|
|
}
|
|
$spec = self::decodeSpec((string) $backup->spec_json);
|
|
$resources = self::resources($spec);
|
|
$restore = CloudBackupRestore::where(
|
|
'id', (int) $migration->restore_id
|
|
)->lockForUpdate()->first();
|
|
if ($restore === null
|
|
|| (int) $restore->backup_id !== (int) $backup->id
|
|
|| (int) $restore->target_host_id
|
|
!== (int) $migration->target_host_id
|
|
|| $restore->target_instance_id !== null
|
|
|| (int) $restore->reservation_id
|
|
!== (int) $migration->target_reservation_id
|
|
|| $restore->job_id !== null
|
|
|| (string) $restore->state !== 'reserved'
|
|
|| !hash_equals(
|
|
strtolower((string) $restore->new_uuid),
|
|
strtolower((string) $migration->target_uuid)
|
|
)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移目标预留目录不一致',
|
|
409
|
|
);
|
|
}
|
|
$placement = CloudPlacementService::preparedBackupRestorePlacement(
|
|
$restore,
|
|
(int) $instance->id
|
|
);
|
|
$reservation = $placement['reservation'];
|
|
$network = $placement['network'];
|
|
$runtime = self::storageRuntime($backup);
|
|
$sourceUrl = (new CloudObjectStorageS3Client())->presignedGet(
|
|
$runtime['config'],
|
|
$runtime['credentials'],
|
|
(string) $backup->object_key,
|
|
self::TRANSFER_URL_SECONDS
|
|
);
|
|
$snapshotSources = CloudMigrationBundleService::restoreSources(
|
|
$migration,
|
|
$runtime
|
|
);
|
|
$now = time();
|
|
$operationId = (string) $restore->operation_id;
|
|
$policy = $spec['platform_network_policy_snapshot'] ?? [];
|
|
if (!is_array($policy) || array_is_list($policy)) {
|
|
$policy = [];
|
|
}
|
|
$body = [
|
|
'uuid' => (string) $migration->target_uuid,
|
|
'source' => '',
|
|
'name' => (string) $instance->name,
|
|
'description' => '',
|
|
'vcpu' => $resources['cpu_cores'],
|
|
'memory_mib' => $resources['memory_mib'],
|
|
'disk_gib' => $resources['disk_gib'],
|
|
'bandwidth_mbps' => $resources['bandwidth_mbps'],
|
|
'network' => 'bridge:br0',
|
|
'template_id' => '',
|
|
'template_revision' => 0,
|
|
'template_generation_token' => '',
|
|
'startup_script' => '',
|
|
'hostname' => CloudInput::hostname((string) (
|
|
$spec['guest_hostname'] ?? $instance->name
|
|
)),
|
|
'guest_ssh_public_key' => '',
|
|
'root_password' => '',
|
|
'public_pool_key' => (string) $network['public_pool_key'],
|
|
'public_pool_cidr' => (string) $network['public_pool_cidr'],
|
|
'public_ip_cidr' => (string) $network['public_ip_cidr'],
|
|
'gateway' => (string) $network['gateway'],
|
|
'dns_servers' => array_values($network['dns_servers']),
|
|
'platform_network_policy_snapshot' => $policy,
|
|
'debian_12_network_fix' =>
|
|
($spec['debian_12_network_fix'] ?? null) === true,
|
|
'backup_key' => (string) $backup->backup_key,
|
|
'source_url' => $sourceUrl,
|
|
'source_size_bytes' => (int) $backup->object_size_bytes,
|
|
'source_sha256' => (string) $backup->sha256,
|
|
'migration_bundle' => [
|
|
'version' => CloudMigrationBundleService::VERSION,
|
|
'stage_powered_off' => true,
|
|
'network_suspended' =>
|
|
(string) $migration->source_network_status !== 'active',
|
|
'snapshots' => $snapshotSources,
|
|
],
|
|
];
|
|
[$restoreJob, $created] = CloudJobService::reserveStandaloneAgentMutation(
|
|
[
|
|
'user_id' => (int) $backupJob->user_id,
|
|
'request_idempotency_key' =>
|
|
'migration-restore-' . (string) $migration->migration_key,
|
|
],
|
|
(int) $migration->target_host_id,
|
|
'backup_restore',
|
|
'POST',
|
|
'/v1/vms/' . rawurlencode((string) $migration->target_uuid)
|
|
. '/restore-backup',
|
|
$body,
|
|
[
|
|
'owner_id' => (int) $instance->user_id,
|
|
'can_manage' => true,
|
|
'backup_key' => (string) $backup->backup_key,
|
|
'restore_key' => (string) $restore->restore_key,
|
|
'reservation_id' => (int) $reservation->id,
|
|
'maintenance_migration_id' => (int) $migration->id,
|
|
],
|
|
[
|
|
'migration_id' => (int) $migration->id,
|
|
'backup_id' => (int) $backup->id,
|
|
'target_host_id' => (int) $migration->target_host_id,
|
|
'target_uuid' => (string) $migration->target_uuid,
|
|
],
|
|
$operationId,
|
|
'/v1/instance-maintenance-migrations/'
|
|
. (int) $migration->id . '/restore'
|
|
);
|
|
if (!$created) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移目标恢复任务幂等冲突',
|
|
409
|
|
);
|
|
}
|
|
$restoreJob->instance_id = (int) $instance->id;
|
|
$restoreJob->backup_id = (int) $backup->id;
|
|
$restoreJob->backup_restore_id = (int) $restore->id;
|
|
$restoreJob->save();
|
|
$restore->job_id = (int) $restoreJob->id;
|
|
$restore->state = 'restoring';
|
|
$restore->updated_at = $now;
|
|
$restore->save();
|
|
$migration->restore_job_id = (int) $restoreJob->id;
|
|
$migration->state = 'restoring';
|
|
$migration->error_code = '';
|
|
$migration->updated_at = $now;
|
|
$migration->save();
|
|
}
|
|
|
|
private static function finishRestoreLocked(
|
|
CloudInstanceMigration $migration,
|
|
CloudJob $job,
|
|
string $status,
|
|
$result,
|
|
array $payload
|
|
): void {
|
|
$restore = CloudBackupRestore::where(
|
|
'id', (int) $migration->restore_id
|
|
)->lockForUpdate()->first();
|
|
$backup = CloudInstanceBackup::where(
|
|
'id', (int) $migration->backup_id
|
|
)->lockForUpdate()->first();
|
|
$instance = CloudInstance::where(
|
|
'id', (int) $migration->instance_id
|
|
)->lockForUpdate()->first();
|
|
if ($restore === null || $backup === null || $instance === null
|
|
|| (int) $job->backup_restore_id !== (int) $restore->id
|
|
|| (int) $job->backup_id !== (int) $backup->id
|
|
|| (int) $job->instance_id !== (int) $instance->id
|
|
|| (int) $job->host_id !== (int) $migration->target_host_id
|
|
|| (int) ($payload['maintenance_migration_id'] ?? 0)
|
|
!== (int) $migration->id
|
|
|| !hash_equals((string) $restore->operation_id,
|
|
(string) $job->operation_id)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移目标恢复任务与迁移账本不一致',
|
|
409
|
|
);
|
|
}
|
|
if ($status === 'running') {
|
|
return;
|
|
}
|
|
$requestedIp = $payload['body']['public_ip_cidr'] ?? null;
|
|
if (!is_string($requestedIp)) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移目标恢复缺少公网 IP 快照',
|
|
409
|
|
);
|
|
}
|
|
$now = time();
|
|
if ($status === 'uncertain') {
|
|
CloudPlacementService::finishBackupRestore(
|
|
$restore,
|
|
(int) $instance->id,
|
|
$requestedIp,
|
|
'uncertain'
|
|
);
|
|
$restore->state = 'uncertain';
|
|
$restore->error_code = 'operation_effect_unknown';
|
|
self::setState($migration, 'uncertain', 'operation_effect_unknown');
|
|
} elseif ($status === 'failed') {
|
|
CloudPlacementService::finishBackupRestore(
|
|
$restore,
|
|
(int) $instance->id,
|
|
$requestedIp,
|
|
'failed'
|
|
);
|
|
$restore->state = 'failed';
|
|
$restore->error_code = 'backup_restore_failed';
|
|
if ((bool) $migration->source_autostart_enabled) {
|
|
self::queueRollbackLocked(
|
|
$migration,
|
|
$instance,
|
|
(int) $job->user_id,
|
|
'migration_restore_failed'
|
|
);
|
|
} else {
|
|
self::setState(
|
|
$migration,
|
|
'rolled_back',
|
|
'migration_restore_failed'
|
|
);
|
|
$migration->completed_at = $now;
|
|
$migration->save();
|
|
}
|
|
} elseif ($status === 'succeeded') {
|
|
$vm = is_array($result['vm'] ?? null) ? $result['vm'] : $result;
|
|
if (!is_array($result) || !is_array($vm)
|
|
|| !hash_equals((string) $backup->backup_key,
|
|
(string) ($result['backup_key'] ?? ''))
|
|
|| !hash_equals((string) $backup->sha256,
|
|
(string) ($result['sha256'] ?? ''))
|
|
|| !hash_equals(strtolower((string) $migration->target_uuid),
|
|
strtolower((string) ($vm['uuid'] ?? '')))
|
|
|| !hash_equals($requestedIp,
|
|
(string) ($vm['public_ip_cidr'] ?? ''))
|
|
|| !hash_equals(
|
|
(string) ($payload['body']['public_pool_key'] ?? ''),
|
|
(string) ($vm['public_pool_key'] ?? '')
|
|
)) {
|
|
throw new CloudError('Agent 迁移恢复结果与目标资源不一致', 502);
|
|
}
|
|
CloudMigrationBundleService::finishRestoreLocked(
|
|
$migration,
|
|
$result
|
|
);
|
|
$rootDiskGib = filter_var(
|
|
$payload['body']['disk_gib'] ?? null,
|
|
FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]
|
|
);
|
|
$reservation = CloudResourceReservation::where(
|
|
'id', (int) $migration->target_reservation_id
|
|
)->lockForUpdate()->first();
|
|
$sourceReservation = CloudResourceReservation::where(
|
|
'id', (int) $migration->source_reservation_id
|
|
)->lockForUpdate()->first();
|
|
$expectedClaim = $rootDiskGib === false ? 0
|
|
: (int) $rootDiskGib
|
|
+ CloudMigrationBundleService::artifactDiskGib($migration);
|
|
if ($reservation === null || $sourceReservation === null
|
|
|| $rootDiskGib === false
|
|
|| !in_array((string) $reservation->state,
|
|
['held', 'uncertain'], true)
|
|
|| (int) $reservation->disk_gib !== $expectedClaim
|
|
|| (string) $sourceReservation->state !== 'committed'
|
|
|| (int) $sourceReservation->host_id
|
|
!== (int) $migration->source_host_id
|
|
|| (int) $sourceReservation->instance_id
|
|
!== (int) $instance->id
|
|
|| (int) $sourceReservation->disk_gib
|
|
!== (int) $rootDiskGib) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移目标快照容量预留账本不一致',
|
|
409
|
|
);
|
|
}
|
|
// Snapshot rows now account for their target-host volumes. Keep
|
|
// only the root disk in the ordinary instance reservation; the
|
|
// source duplicate remains claimed by restored bundle artifacts
|
|
// until source cleanup is proven.
|
|
$reservation->disk_gib = (int) $rootDiskGib;
|
|
$reservation->updated_at = $now;
|
|
$reservation->save();
|
|
$sourceReservation->disk_gib = $expectedClaim;
|
|
$sourceReservation->updated_at = $now;
|
|
$sourceReservation->save();
|
|
CloudPlacementService::finishBackupRestore(
|
|
$restore,
|
|
(int) $instance->id,
|
|
$requestedIp,
|
|
'succeeded'
|
|
);
|
|
$reservation = CloudResourceReservation::where(
|
|
'id', (int) $migration->target_reservation_id
|
|
)->lockForUpdate()->first();
|
|
if ($reservation === null
|
|
|| (string) $reservation->state !== 'committed') {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移目标资源没有完成提交',
|
|
409
|
|
);
|
|
}
|
|
$spec = self::decodeSpec((string) $instance->spec_json);
|
|
$spec = CloudInstanceMetadata::merge($spec, $vm);
|
|
$spec['managed'] = true;
|
|
$spec['migrated_from_host_id'] = (int) $migration->source_host_id;
|
|
$spec['migrated_from_uuid'] = (string) $migration->source_uuid;
|
|
$spec['maintenance_migration_key'] =
|
|
(string) $migration->migration_key;
|
|
$spec['traffic_counter_generation'] = [
|
|
'host_id' => (int) $migration->target_host_id,
|
|
'uuid' => strtolower((string) $migration->target_uuid),
|
|
'download_base_bytes' =>
|
|
max(0, (int) $instance->lifetime_download_bytes),
|
|
'upload_base_bytes' =>
|
|
max(0, (int) $instance->lifetime_upload_bytes),
|
|
];
|
|
$instance->host_id = (int) $migration->target_host_id;
|
|
$instance->uuid = strtolower((string) $migration->target_uuid);
|
|
$instance->resource_pool_id = (int) $reservation->resource_pool_id;
|
|
$instance->reservation_id = (int) $reservation->id;
|
|
$instance->spec_json = json_encode(
|
|
$spec,
|
|
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
|
| JSON_UNESCAPED_UNICODE
|
|
);
|
|
$instance->service_status = (string) $migration->source_service_status;
|
|
$instance->network_status = (string) $migration->source_network_status;
|
|
// The target Agent starts a new durable counter generation. Its
|
|
// first sample must be allowed to advance the carried lifetime
|
|
// base even when the source host clock was ahead.
|
|
$instance->traffic_synced_at = 0;
|
|
$instance->updated_at = $now;
|
|
$instance->save();
|
|
$restore->state = 'ready';
|
|
$restore->error_code = '';
|
|
$restore->ready_at = $now;
|
|
$migration->cutover_at = $now;
|
|
$migration->state = 'cutover';
|
|
$migration->error_code = '';
|
|
$migration->updated_at = $now;
|
|
$migration->save();
|
|
CloudInstanceRuntimeService::seed(
|
|
(int) $instance->id,
|
|
(int) $instance->host_id,
|
|
(string) $instance->uuid
|
|
);
|
|
$firewallJob = CloudFirewallService::
|
|
queueMaintenanceMigrationReapplyLocked(
|
|
$instance,
|
|
$migration,
|
|
(int) $job->user_id
|
|
);
|
|
if ($firewallJob !== null) {
|
|
$migration->firewall_job_id = (int) $firewallJob->id;
|
|
$migration->state = 'firewall_running';
|
|
$migration->error_code = '';
|
|
$migration->updated_at = $now;
|
|
$migration->save();
|
|
} else {
|
|
self::advanceAfterTargetReadyLocked(
|
|
$migration,
|
|
$instance,
|
|
(int) $job->user_id
|
|
);
|
|
}
|
|
}
|
|
$restore->updated_at = $now;
|
|
$restore->save();
|
|
}
|
|
|
|
private static function queueRollbackLocked(
|
|
CloudInstanceMigration $migration,
|
|
CloudInstance $instance,
|
|
int $actorUserId,
|
|
string $errorCode
|
|
): CloudJob {
|
|
if ((int) $instance->host_id !== (int) $migration->source_host_id
|
|
|| !hash_equals(strtolower((string) $instance->uuid),
|
|
strtolower((string) $migration->source_uuid))
|
|
|| $migration->rollback_job_id !== null) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移源实例回滚账本不一致',
|
|
409
|
|
);
|
|
}
|
|
[$job, $created] = CloudJobService::reserveStandaloneAgentMutation(
|
|
[
|
|
'user_id' => $actorUserId,
|
|
'request_idempotency_key' => 'migration-rollback-'
|
|
. (string) $migration->migration_key,
|
|
],
|
|
(int) $migration->source_host_id,
|
|
'instance_migration_rollback',
|
|
'POST',
|
|
'/v1/vms/' . rawurlencode((string) $migration->source_uuid)
|
|
. '/service/resume',
|
|
[
|
|
'reason' => 'maintenance_migration_rollback',
|
|
'start_if_suspended' =>
|
|
(bool) $migration->source_was_running,
|
|
],
|
|
[
|
|
'owner_id' => (int) $instance->user_id,
|
|
'can_manage' => true,
|
|
'maintenance_migration_id' => (int) $migration->id,
|
|
],
|
|
[
|
|
'migration_id' => (int) $migration->id,
|
|
'source_host_id' => (int) $migration->source_host_id,
|
|
'source_uuid' => (string) $migration->source_uuid,
|
|
'source_was_running' =>
|
|
(bool) $migration->source_was_running,
|
|
],
|
|
null,
|
|
'/v1/instance-maintenance-migrations/'
|
|
. (int) $migration->id . '/rollback'
|
|
);
|
|
if (!$created) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移源实例回滚任务幂等冲突',
|
|
409
|
|
);
|
|
}
|
|
$job->instance_id = (int) $instance->id;
|
|
$job->backup_id = (int) $migration->backup_id;
|
|
$job->backup_restore_id = (int) $migration->restore_id;
|
|
$job->save();
|
|
$migration->rollback_job_id = (int) $job->id;
|
|
$migration->state = 'rollback_running';
|
|
$migration->error_code = $errorCode;
|
|
$migration->updated_at = time();
|
|
$migration->save();
|
|
return $job;
|
|
}
|
|
|
|
private static function finishRollbackLocked(
|
|
CloudInstanceMigration $migration,
|
|
CloudJob $job,
|
|
string $status,
|
|
$result
|
|
): void {
|
|
$instance = CloudInstance::where(
|
|
'id', (int) $migration->instance_id
|
|
)->lockForUpdate()->first();
|
|
if ($instance === null
|
|
|| (int) $migration->rollback_job_id !== (int) $job->id
|
|
|| (int) $job->instance_id !== (int) $instance->id
|
|
|| (int) $job->host_id !== (int) $migration->source_host_id
|
|
|| (int) $instance->host_id !== (int) $migration->source_host_id
|
|
|| !hash_equals(strtolower((string) $instance->uuid),
|
|
strtolower((string) $migration->source_uuid))) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移源实例回滚任务与源实例不一致',
|
|
409
|
|
);
|
|
}
|
|
if ($status === 'running') {
|
|
return;
|
|
}
|
|
if ($status === 'uncertain') {
|
|
self::setState(
|
|
$migration,
|
|
'rollback_uncertain',
|
|
'operation_effect_unknown'
|
|
);
|
|
return;
|
|
}
|
|
if ($status === 'failed') {
|
|
self::setState(
|
|
$migration,
|
|
'rollback_failed',
|
|
'migration_source_rollback_failed'
|
|
);
|
|
return;
|
|
}
|
|
$state = is_array($result) ? ($result['state'] ?? null) : null;
|
|
$running = in_array($state, ['running', 'blocked'], true);
|
|
if (!is_array($result)
|
|
|| !hash_equals(strtolower((string) $migration->source_uuid),
|
|
strtolower((string) ($result['uuid'] ?? '')))
|
|
|| ((bool) $migration->source_was_running && !$running)
|
|
|| (!(bool) $migration->source_was_running && $running)) {
|
|
throw new CloudError('Agent 未确认迁移源实例已恢复原电源状态', 502);
|
|
}
|
|
self::setState($migration, 'rolled_back', 'migration_restore_failed');
|
|
$migration->completed_at = time();
|
|
$migration->save();
|
|
}
|
|
|
|
private static function finishFirewallLocked(
|
|
CloudInstanceMigration $migration,
|
|
CloudJob $job,
|
|
string $status
|
|
): void {
|
|
$instance = CloudInstance::where(
|
|
'id', (int) $migration->instance_id
|
|
)->lockForUpdate()->first();
|
|
if ($instance === null
|
|
|| (int) $migration->firewall_job_id !== (int) $job->id
|
|
|| (int) $job->instance_id !== (int) $instance->id
|
|
|| (int) $job->host_id !== (int) $migration->target_host_id
|
|
|| (int) $instance->host_id !== (int) $migration->target_host_id
|
|
|| !hash_equals(strtolower((string) $instance->uuid),
|
|
strtolower((string) $migration->target_uuid))) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移防火墙任务与目标实例不一致',
|
|
409
|
|
);
|
|
}
|
|
if ($status === 'running') {
|
|
return;
|
|
}
|
|
if ($status === 'uncertain') {
|
|
self::setState(
|
|
$migration,
|
|
'firewall_uncertain',
|
|
'firewall_result_uncertain'
|
|
);
|
|
return;
|
|
}
|
|
if ($status === 'failed') {
|
|
self::setState(
|
|
$migration,
|
|
'firewall_failed',
|
|
'firewall_apply_failed'
|
|
);
|
|
return;
|
|
}
|
|
$policy = CloudInstanceFirewall::where(
|
|
'instance_id', (int) $instance->id
|
|
)->lockForUpdate()->first();
|
|
if ($policy === null
|
|
|| (int) $policy->host_id !== (int) $instance->host_id
|
|
|| (string) $policy->sync_state !== 'active'
|
|
|| (int) $policy->desired_revision
|
|
!== (int) $policy->applied_revision) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移目标防火墙没有完成收敛',
|
|
409
|
|
);
|
|
}
|
|
self::advanceAfterTargetReadyLocked(
|
|
$migration,
|
|
$instance,
|
|
(int) $job->user_id
|
|
);
|
|
}
|
|
|
|
private static function advanceAfterTargetReadyLocked(
|
|
CloudInstanceMigration $migration,
|
|
CloudInstance $instance,
|
|
int $actorUserId
|
|
): void {
|
|
if (!(bool) $migration->source_autostart_enabled) {
|
|
self::setState($migration, 'activated', '');
|
|
self::advanceAfterActivationLocked(
|
|
$migration,
|
|
$instance,
|
|
$actorUserId
|
|
);
|
|
return;
|
|
}
|
|
self::queueActivationLocked($migration, $instance, $actorUserId);
|
|
}
|
|
|
|
private static function queueActivationLocked(
|
|
CloudInstanceMigration $migration,
|
|
CloudInstance $instance,
|
|
int $actorUserId
|
|
): CloudJob {
|
|
if ($migration->activate_job_id !== null) {
|
|
$existing = CloudJob::find((int) $migration->activate_job_id);
|
|
if ($existing === null) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移目标激活任务目录缺失',
|
|
409
|
|
);
|
|
}
|
|
return $existing;
|
|
}
|
|
[$job, $created] = CloudJobService::reserveStandaloneAgentMutation(
|
|
[
|
|
'user_id' => $actorUserId,
|
|
'request_idempotency_key' => 'migration-activate-'
|
|
. (string) $migration->migration_key,
|
|
],
|
|
(int) $migration->target_host_id,
|
|
'instance_migration_activate',
|
|
'POST',
|
|
'/v1/vms/' . rawurlencode((string) $migration->target_uuid)
|
|
. '/service/resume',
|
|
[
|
|
'reason' => 'maintenance_migration_activate',
|
|
'start_if_suspended' => (bool) $migration->source_was_running,
|
|
],
|
|
[
|
|
'owner_id' => (int) $instance->user_id,
|
|
'can_manage' => true,
|
|
'maintenance_migration_id' => (int) $migration->id,
|
|
],
|
|
[
|
|
'migration_id' => (int) $migration->id,
|
|
'target_host_id' => (int) $migration->target_host_id,
|
|
'target_uuid' => (string) $migration->target_uuid,
|
|
'source_was_running' => (bool) $migration->source_was_running,
|
|
],
|
|
null,
|
|
'/v1/instance-maintenance-migrations/'
|
|
. (int) $migration->id . '/activate'
|
|
);
|
|
if (!$created) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移目标激活任务幂等冲突',
|
|
409
|
|
);
|
|
}
|
|
$job->instance_id = (int) $instance->id;
|
|
$job->backup_id = (int) $migration->backup_id;
|
|
$job->backup_restore_id = (int) $migration->restore_id;
|
|
$job->save();
|
|
$migration->activate_job_id = (int) $job->id;
|
|
$migration->state = 'activation_running';
|
|
$migration->error_code = '';
|
|
$migration->updated_at = time();
|
|
$migration->save();
|
|
return $job;
|
|
}
|
|
|
|
private static function finishActivationLocked(
|
|
CloudInstanceMigration $migration,
|
|
CloudJob $job,
|
|
string $status,
|
|
$result
|
|
): void {
|
|
$instance = CloudInstance::where(
|
|
'id', (int) $migration->instance_id
|
|
)->lockForUpdate()->first();
|
|
if ($instance === null
|
|
|| (int) $migration->activate_job_id !== (int) $job->id
|
|
|| (int) $job->instance_id !== (int) $instance->id
|
|
|| (int) $job->host_id !== (int) $migration->target_host_id
|
|
|| (int) $instance->host_id !== (int) $migration->target_host_id
|
|
|| !hash_equals(strtolower((string) $instance->uuid),
|
|
strtolower((string) $migration->target_uuid))) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移目标激活任务与目标实例不一致',
|
|
409
|
|
);
|
|
}
|
|
if ($status === 'running') {
|
|
return;
|
|
}
|
|
if ($status === 'uncertain') {
|
|
self::setState(
|
|
$migration,
|
|
'activation_uncertain',
|
|
'operation_effect_unknown'
|
|
);
|
|
return;
|
|
}
|
|
if ($status === 'failed') {
|
|
self::setState(
|
|
$migration,
|
|
'activation_failed',
|
|
'migration_target_activation_failed'
|
|
);
|
|
return;
|
|
}
|
|
$state = is_array($result) ? ($result['state'] ?? null) : null;
|
|
$running = in_array($state, ['running', 'blocked'], true);
|
|
if (!is_array($result)
|
|
|| !hash_equals(strtolower((string) $migration->target_uuid),
|
|
strtolower((string) ($result['uuid'] ?? '')))
|
|
|| ((bool) $migration->source_was_running && !$running)
|
|
|| (!(bool) $migration->source_was_running && $running)) {
|
|
throw new CloudError('Agent 未确认迁移目标恢复原电源状态', 502);
|
|
}
|
|
self::setState($migration, 'activated', '');
|
|
self::advanceAfterActivationLocked(
|
|
$migration,
|
|
$instance,
|
|
(int) $job->user_id
|
|
);
|
|
}
|
|
|
|
private static function advanceAfterActivationLocked(
|
|
CloudInstanceMigration $migration,
|
|
CloudInstance $instance,
|
|
int $actorUserId
|
|
): void {
|
|
if ((string) $migration->cleanup_mode === 'delete') {
|
|
self::queueCleanupLocked($migration, $instance, [
|
|
'user_id' => $actorUserId,
|
|
'request_idempotency_key' => 'migration-cleanup-'
|
|
. (string) $migration->migration_key . '-1',
|
|
]);
|
|
return;
|
|
}
|
|
self::setState($migration, 'source_retained', '');
|
|
}
|
|
|
|
private static function queueCleanupLocked(CloudInstanceMigration $migration,
|
|
CloudInstance $instance, array $actor): CloudJob
|
|
{
|
|
if (!in_array((string) $migration->state,
|
|
['activated', 'source_retained'], true)) {
|
|
throw new CloudError('当前迁移状态不能清理源副本', 409);
|
|
}
|
|
[$job, $created] = CloudJobService::reserveStandaloneAgentMutation(
|
|
$actor,
|
|
(int) $migration->source_host_id,
|
|
'instance_migration_cleanup',
|
|
'DELETE',
|
|
'/v1/vms/' . rawurlencode((string) $migration->source_uuid),
|
|
['remove_managed_disks' => true],
|
|
[
|
|
'owner_id' => (int) $instance->user_id,
|
|
'can_manage' => true,
|
|
'maintenance_migration_id' => (int) $migration->id,
|
|
],
|
|
[
|
|
'migration_id' => (int) $migration->id,
|
|
'source_host_id' => (int) $migration->source_host_id,
|
|
'source_uuid' => (string) $migration->source_uuid,
|
|
],
|
|
null,
|
|
'/v1/instance-maintenance-migrations/'
|
|
. (int) $migration->id . '/source'
|
|
);
|
|
if (!$created) {
|
|
if ((int) $migration->cleanup_job_id === (int) $job->id) {
|
|
return $job;
|
|
}
|
|
throw new CloudError('源副本清理请求幂等冲突', 409);
|
|
}
|
|
$job->instance_id = (int) $instance->id;
|
|
$job->backup_id = (int) $migration->backup_id;
|
|
$job->backup_restore_id = (int) $migration->restore_id;
|
|
$job->save();
|
|
$migration->cleanup_job_id = (int) $job->id;
|
|
$migration->state = 'cleanup_running';
|
|
$migration->error_code = '';
|
|
$migration->updated_at = time();
|
|
$migration->save();
|
|
return $job;
|
|
}
|
|
|
|
private static function finishCleanupLocked(
|
|
CloudInstanceMigration $migration,
|
|
CloudJob $job,
|
|
string $status,
|
|
$result
|
|
): void {
|
|
if ((int) $job->instance_id !== (int) $migration->instance_id
|
|
|| (int) $job->host_id !== (int) $migration->source_host_id) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移源副本清理任务与迁移账本不一致',
|
|
409
|
|
);
|
|
}
|
|
if ($status === 'running') {
|
|
return;
|
|
}
|
|
if ($status === 'uncertain') {
|
|
self::setState(
|
|
$migration,
|
|
'cleanup_uncertain',
|
|
'operation_effect_unknown'
|
|
);
|
|
return;
|
|
}
|
|
if ($status === 'failed') {
|
|
self::setState(
|
|
$migration,
|
|
'source_retained',
|
|
'migration_cleanup_failed'
|
|
);
|
|
return;
|
|
}
|
|
if (!is_array($result)
|
|
|| ($result['deleted'] ?? null) !== true
|
|
|| ($result['managed_artifacts_absent'] ?? null) !== true) {
|
|
throw new CloudError('Agent 未确认迁移源实例和托管磁盘均已删除', 502);
|
|
}
|
|
self::finalizePlacementLocked($migration);
|
|
self::setState($migration, 'completed', '');
|
|
$migration->completed_at = time();
|
|
$migration->save();
|
|
}
|
|
|
|
private static function finalizePlacementLocked(
|
|
CloudInstanceMigration $migration
|
|
): void {
|
|
$instance = CloudInstance::where(
|
|
'id', (int) $migration->instance_id
|
|
)->lockForUpdate()->first();
|
|
$source = CloudResourceReservation::where(
|
|
'id', (int) $migration->source_reservation_id
|
|
)->lockForUpdate()->first();
|
|
$target = CloudResourceReservation::where(
|
|
'id', (int) $migration->target_reservation_id
|
|
)->lockForUpdate()->first();
|
|
$sourceIp = $source === null ? null : CloudPublicIp::where(
|
|
'id', (int) $source->public_ip_id
|
|
)->lockForUpdate()->first();
|
|
$targetIp = $target === null ? null : CloudPublicIp::where(
|
|
'id', (int) $target->public_ip_id
|
|
)->lockForUpdate()->first();
|
|
$order = $instance === null || $instance->order_id === null ? null
|
|
: CloudOrder::where('id', (int) $instance->order_id)
|
|
->lockForUpdate()->first();
|
|
if ($instance === null || $source === null || $target === null
|
|
|| $sourceIp === null || $targetIp === null || $order === null
|
|
|| (int) $instance->host_id !== (int) $migration->target_host_id
|
|
|| !hash_equals(strtolower((string) $instance->uuid),
|
|
strtolower((string) $migration->target_uuid))
|
|
|| (int) $instance->reservation_id !== (int) $target->id
|
|
|| (int) $source->order_id !== (int) $order->id
|
|
|| (int) $source->instance_id !== (int) $instance->id
|
|
|| (string) $source->state !== 'committed'
|
|
|| (int) $target->backup_restore_id !== (int) $migration->restore_id
|
|
|| (int) $target->instance_id !== (int) $instance->id
|
|
|| (string) $target->state !== 'committed'
|
|
|| (int) $sourceIp->reservation_id !== (int) $source->id
|
|
|| (int) $targetIp->reservation_id !== (int) $target->id) {
|
|
throw new CloudRecoveryInstanceStateConflict(
|
|
'维护迁移切换后的资源预留账本不一致',
|
|
409
|
|
);
|
|
}
|
|
$now = time();
|
|
$sourceIp->state = 'available';
|
|
$sourceIp->reservation_id = null;
|
|
$sourceIp->instance_id = null;
|
|
$sourceIp->operation_id = null;
|
|
$sourceIp->updated_at = $now;
|
|
$sourceIp->save();
|
|
|
|
foreach (['resource_pool_id', 'host_id', 'network_attachment_id',
|
|
'public_ip_pool_id', 'public_ip_id', 'cpu_cores', 'memory_mib',
|
|
'disk_gib'] as $field) {
|
|
$source->{$field} = $target->{$field};
|
|
}
|
|
$source->instance_id = (int) $instance->id;
|
|
$source->state = 'committed';
|
|
$source->expires_at = null;
|
|
$source->released_at = null;
|
|
$source->release_reason = '';
|
|
$source->updated_at = $now;
|
|
$source->save();
|
|
|
|
$targetIp->reservation_id = (int) $source->id;
|
|
$targetIp->instance_id = (int) $instance->id;
|
|
$targetIp->operation_id = (string) $source->operation_id;
|
|
$targetIp->state = 'assigned';
|
|
$targetIp->updated_at = $now;
|
|
$targetIp->save();
|
|
|
|
$target->instance_id = null;
|
|
$target->network_attachment_id = null;
|
|
$target->public_ip_pool_id = null;
|
|
$target->public_ip_id = null;
|
|
$target->state = 'released';
|
|
$target->released_at = $now;
|
|
$target->release_reason = 'maintenance_migration_transferred';
|
|
$target->updated_at = $now;
|
|
$target->save();
|
|
|
|
$instance->reservation_id = (int) $source->id;
|
|
$instance->resource_pool_id = (int) $source->resource_pool_id;
|
|
$instance->updated_at = $now;
|
|
$instance->save();
|
|
$order->host_id = (int) $source->host_id;
|
|
$order->resource_pool_id = (int) $source->resource_pool_id;
|
|
$order->reservation_id = (int) $source->id;
|
|
$order->updated_at = $now;
|
|
$order->save();
|
|
}
|
|
|
|
private static function setState(CloudInstanceMigration $migration,
|
|
string $state, string $errorCode): void
|
|
{
|
|
$migration->state = $state;
|
|
$migration->error_code = $errorCode;
|
|
$migration->updated_at = time();
|
|
$migration->save();
|
|
}
|
|
|
|
private static function catalogAvailable(): bool
|
|
{
|
|
try {
|
|
return (new CloudInstanceMigration())->getConnection()
|
|
->getSchemaBuilder()->hasTable('cloud_instance_migrations');
|
|
} catch (\Throwable $error) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private static function storageRuntime(CloudInstanceBackup $backup): array
|
|
{
|
|
$runtime = CloudSecrets::decrypt(
|
|
(string) $backup->sealed_storage_runtime,
|
|
self::STORAGE_PURPOSE
|
|
);
|
|
if (!is_array($runtime['config'] ?? null)
|
|
|| !is_array($runtime['credentials'] ?? null)
|
|
|| (int) ($runtime['revision'] ?? -1)
|
|
!== (int) $backup->storage_revision) {
|
|
throw new CloudError('备份对象存储快照无效', 503);
|
|
}
|
|
return $runtime;
|
|
}
|
|
|
|
private static function resources(array $spec): array
|
|
{
|
|
$values = [
|
|
'cpu_cores' => $spec['vcpu'] ?? $spec['cpu_cores'] ?? null,
|
|
'memory_mib' => $spec['memory_mib'] ?? $spec['ram_mib'] ?? null,
|
|
'disk_gib' => $spec['disk_gib'] ?? null,
|
|
'bandwidth_mbps' => $spec['bandwidth_mbps'] ?? null,
|
|
];
|
|
foreach ($values as $field => $value) {
|
|
$parsed = filter_var($value, FILTER_VALIDATE_INT,
|
|
['options' => ['min_range' => 1]]);
|
|
if ($parsed === false) {
|
|
throw new CloudError('实例缺少可信的资源规格快照', 409);
|
|
}
|
|
$values[$field] = (int) $parsed;
|
|
}
|
|
return $values;
|
|
}
|
|
|
|
private static function decodeSpec(string $encoded): array
|
|
{
|
|
$spec = json_decode($encoded, true);
|
|
if (!is_array($spec) || array_is_list($spec)) {
|
|
throw new CloudError('实例备份规格快照损坏', 409);
|
|
}
|
|
return $spec;
|
|
}
|
|
|
|
private static function uuidV4(): string
|
|
{
|
|
$bytes = random_bytes(16);
|
|
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
|
|
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
|
|
$hex = bin2hex($bytes);
|
|
return substr($hex, 0, 8) . '-' . substr($hex, 8, 4) . '-'
|
|
. substr($hex, 12, 4) . '-' . substr($hex, 16, 4) . '-'
|
|
. substr($hex, 20, 12);
|
|
}
|
|
}
|