feat: reserve dual-stack migration targets

go
codex 3 weeks ago
parent 65bab59375
commit 80055cd2aa

@ -314,7 +314,8 @@ final class CloudInstanceMigrationService
$restore->ready_at = null;
$restore->created_at = $restore->updated_at = time();
$restore->save();
$placement = CloudPlacementService::reserveBackupRestore(
$placement = CloudPlacementService::
reserveMaintenanceMigrationTarget(
$restore,
(int) $locked->user_id,
$resources,
@ -338,10 +339,12 @@ final class CloudInstanceMigrationService
409
);
}
CloudPublicNetworkAllocationService::currentClaimSet(
(int) $sourceReservation->id,
'committed',
(int) $locked->id
);
$reservation = $placement['reservation'];
$reservation->instance_id = (int) $locked->id;
$reservation->updated_at = time();
$reservation->save();
$restore->reservation_id = (int) $reservation->id;
$restore->updated_at = time();
$restore->save();

@ -478,14 +478,32 @@ final class CloudPlacementService
]);
$pendingByHost = self::pendingUsageByHost($candidates);
$networkByHostLine = CloudPlacementNetworkService::
advisoryAvailableHostLineDetails($candidates);
advisoryDualStackBundleEvidence($candidates);
$result = [];
foreach ($candidates as $candidate) {
$hostId = (int) $candidate->id;
$lineId = (int) $candidate->resource_pool_line_id;
$network = $networkByHostLine[$hostId][$lineId] ?? null;
if (!is_array($network)
|| (int) ($network['available_ip_count'] ?? 0) < 1
$network = $networkByHostLine[$hostId][$lineId] ?? [];
$availableBundles = 0;
$selectors = [];
foreach ($network as $bundle) {
if (!is_array($bundle)
|| !CloudNetworkSelector::isValid(
$bundle['network_selector'] ?? null
)) {
continue;
}
$count = min(
(int) ($bundle['ipv4']['available_units'] ?? 0),
(int) ($bundle['ipv6']['available_units'] ?? 0)
);
if ($count < 1) {
continue;
}
$availableBundles += $count;
$selectors[(string) $bundle['network_selector']] = true;
}
if ($availableBundles < 1
|| !self::hasCapacity(
$candidate,
$pendingByHost[$hostId] ?? self::emptyUsage(),
@ -507,10 +525,10 @@ final class CloudPlacementService
(string) $candidate->resource_pool_id,
'resource_pool' =>
(string) $candidate->resource_pool_name,
'network_selectors' =>
array_values($network['network_selectors'] ?? []),
'available_ip_count' =>
(int) $network['available_ip_count'],
'network_selectors' => array_keys($selectors),
// Keep the presentation key while changing its unit from a
// lone IPv4 row to one complete IPv4+IPv6 bundle.
'available_ip_count' => $availableBundles,
'is_source_host' => $hostId === $sourceHostId,
];
}
@ -538,6 +556,153 @@ final class CloudPlacementService
));
}
/**
* Reserve one exact dual-stack target for a still-gated maintenance
* migration. Legacy singular address columns deliberately remain NULL;
* the two active claim rows are the only network ownership authority.
*
* @return array{reservation:CloudResourceReservation,host:CloudHost,
* public_network:CloudPublicNetworkSnapshot,
* target_agent_revision:int}
*/
public static function reserveMaintenanceMigrationTarget(
CloudBackupRestore $restore,
int $userId,
array $resources,
int $requiredResourcePoolId,
int $additionalDiskGib = 0
): array {
if ($restore->backup_id !== null
|| (string) $restore->state !== 'reserved'
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $restore->operation_id) !== 1) {
throw new CloudError('维护迁移目标意图无效', 409);
}
$resources = self::upgradeResources($resources);
$capacityResources = $resources;
$capacityResources['disk_gib'] += max(0, $additionalDiskGib);
$hostId = (int) $restore->target_host_id;
if ($hostId < 1 || $userId < 1 || $requiredResourcePoolId < 1) {
throw new CloudError('维护迁移目标身份无效', 409);
}
return (new CloudResourceReservation())->getConnection()->transaction(
static function () use (
$restore,
$userId,
$resources,
$capacityResources,
$hostId,
$requiredResourcePoolId
): array {
$poolRef = CloudResourcePool::find($requiredResourcePoolId);
$lineRef = $poolRef === null ? null
: CloudNetworkLine::find((int) $poolRef->line_id);
$region = $lineRef === null ? null
: CloudRegion::where('id', (int) $lineRef->region_id)
->lockForUpdate()->first();
$line = $lineRef === null ? null
: CloudNetworkLine::where('id', (int) $lineRef->id)
->lockForUpdate()->first();
$pool = $poolRef === null ? null
: CloudResourcePool::where('id', (int) $poolRef->id)
->lockForUpdate()->first();
$host = CloudHost::where('id', $hostId)
->lockForUpdate()->first();
$membership = CloudHostResourcePoolMembership::where(
'host_id',
$hostId
)->where('resource_pool_id', $requiredResourcePoolId)
->lockForUpdate()->first();
$policy = CloudHostCapacityPolicy::where('host_id', $hostId)
->lockForUpdate()->first();
$storage = CloudHostStorageConfiguration::where(
'host_id',
$hostId
)->lockForUpdate()->first();
$agent = CloudHostAgent::where('host_id', $hostId)
->lockForUpdate()->first();
if ($host === null || $membership === null || $pool === null
|| $line === null || $region === null || $policy === null
|| $storage === null || !$storage->isApplied()
|| $agent === null || !$agent->isReady()
|| !(bool) $host->enabled
|| (string) $membership->scheduler_state !== 'active'
|| (int) $membership->resource_pool_id
!== $requiredResourcePoolId
|| (int) $pool->id !== $requiredResourcePoolId
|| (int) $pool->line_id !== (int) $line->id
|| (int) $line->region_id !== (int) $region->id
|| (string) $pool->status !== 'active'
|| (string) $line->status !== 'active'
|| (string) $region->status !== 'active') {
throw new CloudError(
'所选目标宿主机暂不支持维护迁移',
409
);
}
$reservations = CloudResourceReservation::where(
'host_id',
$hostId
)->whereIn('state', ['held', 'uncertain', 'committed'])
->orderBy('id')->lockForUpdate()->get();
if (!self::hasCapacity(
$policy,
CloudPanelUsageService::forHost($hostId, $reservations),
$capacityResources
)) {
throw new CloudError('目标宿主机没有足够的可用容量', 409);
}
$reservation = new CloudResourceReservation();
$reservation->reservation_key = bin2hex(random_bytes(16));
$reservation->operation_id = (string) $restore->operation_id;
$reservation->order_id = null;
$reservation->backup_restore_id = (int) $restore->id;
$reservation->backup_restore_attempt_key = null;
$reservation->migration_source_debt_id = null;
$reservation->offer_id = null;
$reservation->resource_pool_id = (int) $pool->id;
$reservation->host_id = $hostId;
$reservation->user_id = $userId;
$reservation->instance_id = null;
$reservation->network_attachment_id = null;
$reservation->public_ip_pool_id = null;
$reservation->public_ip_id = null;
$reservation->cpu_cores = $resources['cpu_cores'];
$reservation->memory_mib = $resources['memory_mib'];
$reservation->disk_gib = $capacityResources['disk_gib'];
$reservation->state = 'held';
$reservation->expires_at = null;
$reservation->released_at = null;
$reservation->release_reason = '';
$reservation->created_at =
$reservation->updated_at = time();
$reservation->save();
try {
$publicNetwork = CloudPublicNetworkAllocationService::
reserveBundle(
$hostId,
(int) $line->id,
(int) $reservation->id,
(string) $restore->operation_id
);
} catch (CloudPublicNetworkCapacityUnavailable) {
throw new CloudError(
'目标宿主机没有可分配的双栈公网地址',
409
);
}
return [
'reservation' => $reservation,
'host' => $host,
'public_network' => $publicNetwork,
'target_agent_revision' => (int) $agent->revision,
];
},
3
);
}
/**
* Reserve target capacity and a fresh IPv4 for an administrator restore.
* The restore row and operation ID are created before this method runs.

@ -159,6 +159,8 @@ namespace {
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudMoney;
use App\Services\Cloud\CloudPlatformTestNetworkPolicy;
use App\Services\Cloud\CloudPlacementService;
use App\Services\Cloud\CloudPublicNetworkAllocationService;
use App\Services\Cloud\CloudPublicNetworkTransitionCommand;
use App\Services\Cloud\CloudPublicNetworkTransitionWorkflow;
use App\Services\Cloud\CloudDeploymentPageService;
@ -299,11 +301,11 @@ namespace {
$schema->create('cloud_platform_test_policy_rules', function (Blueprint $t) { $t->increments('id'); $t->string('rule_key', 32)->unique(); $t->string('service', 120); $t->string('protocol', 8); $t->integer('port_from'); $t->integer('port_to'); $t->string('direction', 8); $t->string('reason', 500); $t->integer('created_by'); $t->integer('updated_by'); $t->integer('deleted_by')->nullable(); $t->integer('deleted_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'offer_id', 'resource_pool_id'] as $v) { $t->integer($v); } $t->integer('host_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->integer('deployment_snapshot_id')->nullable(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('currency')->default('USD'); $t->string('status'); $t->text('spec_json'); $t->text('sealed_payload')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); });
$schema->create('cloud_order_items', function (Blueprint $t) { $t->increments('id'); $t->integer('order_id'); $t->string('code'); $t->string('label'); $t->string('amount'); $t->string('currency')->default('USD'); $t->text('snapshot_json'); $t->integer('created_at'); $t->unique(['order_id', 'code']); });
$schema->create('cloud_resource_reservations', function (Blueprint $t) { $t->increments('id'); $t->string('reservation_key')->unique(); $t->string('operation_id')->unique(); $t->integer('order_id')->nullable(); $t->integer('backup_restore_id')->nullable(); $t->integer('offer_id')->nullable(); foreach (['resource_pool_id', 'host_id', 'user_id'] as $v) { $t->integer($v); } $t->integer('instance_id')->nullable(); $t->integer('network_attachment_id')->nullable(); $t->integer('public_ip_pool_id')->nullable(); $t->integer('public_ip_id')->nullable(); foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $v) { $t->integer($v); } $t->string('state'); $t->integer('expires_at')->nullable(); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique('backup_restore_id'); });
$schema->create('cloud_resource_reservations', function (Blueprint $t) { $t->increments('id'); $t->string('reservation_key')->unique(); $t->string('operation_id')->unique(); $t->integer('order_id')->nullable(); $t->integer('backup_restore_id')->nullable(); $t->string('backup_restore_attempt_key')->nullable(); $t->integer('migration_source_debt_id')->nullable(); $t->integer('offer_id')->nullable(); foreach (['resource_pool_id', 'host_id', 'user_id'] as $v) { $t->integer($v); } $t->integer('instance_id')->nullable(); $t->integer('network_attachment_id')->nullable(); $t->integer('public_ip_pool_id')->nullable(); $t->integer('public_ip_id')->nullable(); foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $v) { $t->integer($v); } $t->string('state'); $t->integer('expires_at')->nullable(); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique('backup_restore_id'); });
$schema->create('cloud_resource_reservation_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('reservation_id'); $t->integer('address_family'); $t->integer('claim_generation')->default(1); $t->integer('active_claim')->nullable()->default(1); $t->integer('network_attachment_id'); $t->integer('public_ip_pool_id'); $t->integer('public_ip_id'); $t->string('operation_id'); $t->string('state'); $t->integer('created_at'); $t->integer('updated_at'); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->unique(['reservation_id', 'address_family', 'active_claim']); $t->unique(['reservation_id', 'claim_generation', 'address_family']); });
$schema->create('cloud_public_network_transitions', function (Blueprint $t) { $t->increments('id'); $t->string('transition_key')->unique(); $t->string('operation_id')->unique(); $t->string('kind'); $t->integer('instance_id'); $t->integer('host_id'); $t->integer('reservation_id'); $t->integer('invoice_id')->nullable()->unique(); $t->integer('pool_replacement_batch_item_id')->nullable()->unique(); $t->integer('requested_by_user_id'); $t->integer('source_network_attachment_id'); $t->integer('target_network_attachment_id'); $t->string('source_claim_set_sha256'); $t->string('target_claim_set_sha256'); $t->text('source_public_network_json'); $t->string('source_public_network_sha256'); $t->text('target_public_network_json'); $t->string('target_public_network_sha256'); $t->string('state'); $t->string('effect_resolution'); $t->integer('active_transition')->nullable(); $t->string('last_error_code'); $t->integer('effect_resolved_at')->nullable(); $t->integer('terminal_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['instance_id', 'active_transition']); $t->unique(['reservation_id', 'active_transition']); });
$schema->create('cloud_public_network_transition_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('transition_id'); $t->integer('address_family'); $t->integer('source_claim_id'); $t->integer('target_claim_id')->nullable()->unique(); $t->boolean('changed'); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['transition_id', 'address_family']); });
$schema->create('cloud_backup_restores', function (Blueprint $t) { $t->increments('id'); $t->string('restore_key')->unique(); $t->integer('backup_id'); $t->integer('target_host_id'); $t->integer('target_instance_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->integer('job_id')->nullable(); $t->string('operation_id')->unique(); $t->string('new_uuid'); $t->string('new_name'); $t->string('state'); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_backup_restores', function (Blueprint $t) { $t->increments('id'); $t->string('restore_key')->unique(); $t->integer('backup_id')->nullable(); $t->integer('target_host_id'); $t->integer('target_instance_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->integer('job_id')->nullable(); $t->string('operation_id')->unique(); $t->string('new_uuid'); $t->string('new_name'); $t->string('state'); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_backup_recoveries', function (Blueprint $t) { $t->increments('id'); $t->integer('instance_id'); $t->string('state'); });
$schema->create('cloud_instance_migrations', function (Blueprint $t) { $t->increments('id'); $t->integer('instance_id'); $t->integer('restore_id'); $t->integer('source_host_id'); $t->integer('source_reservation_id'); $t->integer('target_host_id'); $t->integer('target_reservation_id'); $t->string('state'); });
$schema->create('cloud_instance_backups', function (Blueprint $t) { $t->increments('id'); $t->string('backup_key')->unique(); $t->integer('source_instance_id'); $t->integer('source_host_id'); $t->integer('user_id'); $t->string('source_uuid'); $t->string('name'); $t->string('purpose')->default('portable'); $t->string('source')->default('manual'); $t->integer('subscription_id')->nullable(); $t->integer('scheduled_for')->nullable(); $t->string('state')->default('creating'); $t->string('consistency'); $t->string('object_key')->unique(); $t->integer('object_size_bytes')->default(0); $t->integer('virtual_size_bytes')->default(0); $t->string('sha256')->default(''); $t->text('spec_json'); $t->text('sealed_storage_runtime'); $t->text('sealed_credential')->nullable(); $t->integer('storage_revision'); $t->text('source_portable_restore_contract_json')->default('{}'); $t->string('source_portable_restore_contract_sha256', 64)->default(''); $t->integer('active_job_id')->nullable(); $t->string('last_operation_id')->nullable(); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['subscription_id', 'scheduled_for']); });
@ -665,6 +667,67 @@ namespace {
&& CloudOffer::find(1)->stock === 10,
'Address admission failure created finance state or consumed stock.');
CloudPublicIp::query()->update(['state' => 'available', 'updated_at' => time()]);
$migrationPlacementReservationCount = CloudResourceReservation::count();
$migrationPlacementClaimCount = Capsule::table(
'cloud_resource_reservation_ips'
)->count();
$migrationPlacementConnection = Capsule::connection('default');
$migrationPlacementConnection->beginTransaction();
try {
$migrationRestore = new CloudBackupRestore();
$migrationRestore->restore_key = str_repeat('7', 32);
$migrationRestore->backup_id = null;
$migrationRestore->target_host_id = (int) $host->id;
$migrationRestore->target_instance_id = null;
$migrationRestore->reservation_id = null;
$migrationRestore->job_id = null;
$migrationRestore->operation_id = str_repeat('8', 32);
$migrationRestore->new_uuid =
'77777777-7777-4777-8777-777777777777';
$migrationRestore->new_name = 'migration-target-fixture';
$migrationRestore->state = 'reserved';
$migrationRestore->error_code = '';
$migrationRestore->ready_at = null;
$migrationRestore->created_at =
$migrationRestore->updated_at = time();
$migrationRestore->save();
$migrationPlacement = CloudPlacementService::
reserveMaintenanceMigrationTarget(
$migrationRestore,
1,
[
'cpu_cores' => 2,
'memory_mib' => 2048,
'disk_gib' => 20,
'bandwidth_mbps' => 100,
],
(int) $pool->id,
5
);
$migrationReservation = $migrationPlacement['reservation'];
$migrationNetwork = $migrationPlacement['public_network'];
$migrationClaimSet = CloudPublicNetworkAllocationService::
currentClaimSet((int) $migrationReservation->id, 'held');
$assert((string) $migrationReservation->state === 'held'
&& $migrationReservation->instance_id === null
&& $migrationReservation->network_attachment_id === null
&& $migrationReservation->public_ip_pool_id === null
&& $migrationReservation->public_ip_id === null
&& (int) $migrationReservation->disk_gib === 25
&& (int) $migrationPlacement['target_agent_revision'] === 1
&& $migrationNetwork->toArray()
=== $migrationClaimSet->publicNetwork()->toArray()
&& $migrationClaimSet->publicNetwork()->address(4) !== ''
&& $migrationClaimSet->publicNetwork()->address(6) !== '',
'Maintenance migration target did not reserve one exact held dual-stack bundle.');
} finally {
$migrationPlacementConnection->rollBack();
}
$assert(CloudResourceReservation::count()
=== $migrationPlacementReservationCount
&& Capsule::table('cloud_resource_reservation_ips')->count()
=== $migrationPlacementClaimCount,
'Rolled-back migration target placement leaked a reservation or address claim.');
$first = CloudOrderService::purchase($input, $actor);
$same = CloudOrderService::purchase($input, $actor);
$firstSpec = json_decode(

Loading…
Cancel
Save