You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudPlacementService.php

1817 lines
80 KiB
PHP

This file contains ambiguous Unicode characters!

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

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudHostAgent;
use App\Models\CloudBackupRestore;
use App\Models\CloudHostCapacityPolicy;
use App\Models\CloudHostNetworkAttachment;
use App\Models\CloudHostResourcePoolMembership;
use App\Models\CloudHostStorageConfiguration;
use App\Models\CloudInstance;
use App\Models\CloudNetworkLine;
use App\Models\CloudOffer;
use App\Models\CloudPublicIp;
use App\Models\CloudPublicIpPool;
use App\Models\CloudRegion;
use App\Models\CloudResourcePool;
use App\Models\CloudResourceReservation;
use App\Models\CloudOrder;
use App\Models\CloudTemplate;
use App\Models\CloudTemplateReplica;
use App\Models\Shop;
/**
* Database-only, payment-time placement and resource reservation.
*
* The caller owns the surrounding wallet transaction. No Agent or network
* request is permitted here: capacity comes from the configured host policy
* and the durable reservation/IP ledgers, with every mutable scheduling row
* locked before it is consumed.
*/
final class CloudPlacementService
{
private const GIB = 1073741824;
private const MAX_PUBLIC_IPS_PER_POOL = 254;
/**
* Advisory capacity check for an already-authorized active pool chain.
*
* Catalog construction has already joined and filtered the offer, plan,
* pool, line and region. Keeping this method resource-only avoids loading
* those models once per public offer while sharing the scheduler's exact
* host, reservation and address predicates.
*/
public static function isPoolCapacityAvailable(int $poolId, int $cpuCores,
int $memoryMib, int $diskGib): bool
{
$availability = self::poolCapacityAvailability(['single' => [
'pool_id' => $poolId,
'cpu_cores' => $cpuCores,
'memory_mib' => $memoryMib,
'disk_gib' => $diskGib,
]]);
return $availability['single'] ?? false;
}
/**
* Advisory same-host capacity check for a grow-only instance upgrade.
*
* The current committed reservation is removed from the usage projection
* before the target vector is evaluated. enqueue() repeats this under the
* host/policy/reservation locks; this read is only for hiding options that
* are already known not to fit.
*/
public static function isUpgradeCapacityAvailable(
CloudInstance $instance,
array $targetResources
): bool {
$resources = self::upgradeResources($targetResources);
$reservation = $instance->reservation_id === null ? null
: CloudResourceReservation::where(
'id',
(int) $instance->reservation_id
)->first();
$policy = CloudHostCapacityPolicy::where(
'host_id',
(int) $instance->host_id
)->first();
if ($reservation === null || $policy === null
|| (string) $reservation->state !== 'committed'
|| (int) ($reservation->instance_id ?? 0) !== (int) $instance->id
|| (int) $reservation->host_id !== (int) $instance->host_id
|| (int) $reservation->resource_pool_id
!== (int) ($instance->resource_pool_id ?? 0)) {
return false;
}
$rows = CloudResourceReservation::where(
'host_id',
(int) $instance->host_id
)->whereIn('state', ['held', 'uncertain', 'committed'])->get();
$usage = CloudPanelUsageService::forHost(
(int) $instance->host_id,
$rows
);
$withoutCurrent = self::usageWithoutUpgradeReservation(
$usage,
$reservation
);
return $withoutCurrent !== null
&& self::hasCapacity($policy, $withoutCurrent, $resources);
}
/**
* Reserve the target vector on the instance's existing reservation.
*
* The caller owns the wallet/instance transaction. This method locks the
* fixed placement hierarchy and every active reservation before replacing
* the current row, so two paid upgrades cannot consume the same capacity.
*/
public static function reserveUpgradeCapacityLocked(
CloudInstance $instance,
int $targetOfferId,
array $sourceResources,
array $targetResources
): CloudResourceReservation {
$source = self::upgradeResources($sourceResources);
$target = self::upgradeResources($targetResources);
[$policy, $reservation, $rows] = self::lockUpgradePlacement(
$instance,
true
);
if ((int) $reservation->offer_id !== (int) ($instance->offer_id ?? 0)
|| (int) $reservation->cpu_cores !== $source['cpu_cores']
|| (int) $reservation->memory_mib !== $source['memory_mib']
|| (int) $reservation->disk_gib !== $source['disk_gib']) {
throw new CloudError('实例当前资源预留与套餐快照不一致', 409);
}
$usage = CloudPanelUsageService::forHost(
(int) $instance->host_id,
$rows
);
$withoutCurrent = self::usageWithoutUpgradeReservation(
$usage,
$reservation
);
if ($withoutCurrent === null
|| !self::hasCapacity($policy, $withoutCurrent, $target)) {
throw new CloudError('当前宿主机没有足够资源完成套餐升级', 409);
}
$reservation->offer_id = $targetOfferId;
$reservation->cpu_cores = $target['cpu_cores'];
$reservation->memory_mib = $target['memory_mib'];
$reservation->disk_gib = $target['disk_gib'];
$reservation->updated_at = time();
$reservation->save();
return $reservation;
}
/**
* Converge the capacity ledger after the original Agent operation.
* Unknown effects deliberately keep the target vector reserved.
*/
public static function finishUpgradeCapacityLocked(
CloudInstance $instance,
int $reservationId,
int $sourceOfferId,
int $targetOfferId,
array $sourceResources,
array $targetResources,
string $resolution
): void {
if (!in_array($resolution, ['applied', 'not_applied', 'unknown'], true)) {
throw new CloudError('实例升级容量结论无效', 409);
}
$source = self::upgradeResources($sourceResources);
$target = self::upgradeResources($targetResources);
[, $reservation] = self::lockUpgradePlacement($instance, false);
if ((int) $reservation->id !== $reservationId
|| (int) $reservation->offer_id !== $targetOfferId
|| (int) $reservation->cpu_cores !== $target['cpu_cores']
|| (int) $reservation->memory_mib !== $target['memory_mib']
|| (int) $reservation->disk_gib !== $target['disk_gib']) {
throw new CloudRecoveryInstanceStateConflict(
'实例升级的目标容量预留账本不一致',
409
);
}
if ($resolution !== 'not_applied') {
return;
}
$reservation->offer_id = $sourceOfferId;
$reservation->cpu_cores = $source['cpu_cores'];
$reservation->memory_mib = $source['memory_mib'];
$reservation->disk_gib = $source['disk_gib'];
$reservation->updated_at = time();
$reservation->save();
}
/**
* Batch advisory availability without locks or resource reservation.
*
* @param array<string,array{pool_id:int,cpu_cores:int,memory_mib:int,
* disk_gib:int}> $requests
* @return array<string,bool>
*/
public static function poolCapacityAvailability(array $requests): array
{
$availability = [];
$byPool = [];
foreach ($requests as $key => $resources) {
$availability[$key] = false;
if (!is_array($resources)) {
continue;
}
$poolId = (int) ($resources['pool_id'] ?? 0);
$normalized = [
'cpu_cores' => (int) ($resources['cpu_cores'] ?? 0),
'memory_mib' => (int) ($resources['memory_mib'] ?? 0),
'disk_gib' => (int) ($resources['disk_gib'] ?? 0),
];
if ($poolId < 1 || min($normalized) < 1) {
continue;
}
$byPool[$poolId][$key] = $normalized;
}
foreach ($byPool as $poolId => $poolRequests) {
$candidateRows = self::candidateHostRows((int) $poolId);
if ($candidateRows->isEmpty()) {
continue;
}
$pendingByHost = self::pendingUsageByHost($candidateRows);
$availableIpHosts = self::availableIpHosts($candidateRows);
foreach ($poolRequests as $key => $resources) {
foreach ($candidateRows as $candidate) {
$hostId = (int) $candidate->id;
if (isset($availableIpHosts[$hostId])
&& self::hasCapacity($candidate,
$pendingByHost[$hostId] ?? self::emptyUsage(),
$resources)) {
$availability[$key] = true;
break;
}
}
}
}
return $availability;
}
/**
* Select a host and reserve one concrete public IP exactly once.
*
* @return array{host: CloudHost, reservation: CloudResourceReservation,
* public_ip: CloudPublicIp, payload: array}
*/
public static function reserve(CloudOrder $order, CloudOffer $offer,
Shop $plan, array $payload): array
{
self::assertOrderOffer($order, $offer, $plan);
$resources = self::orderResources($order, $payload);
// The caller already owns the order row lock, and queued/terminal
// orders return before placement. A missing-row FOR UPDATE here would
// take an InnoDB right-edge gap lock for every new order; concurrent
// payments for different offers could then deadlock that gap against
// the shared region/pool locks when each inserts its reservation.
// Atomic payment plus UNIQUE(order_id) are the durable idempotency
// guards. A pre-existing row on an awaiting-payment order is therefore
// an invariant violation rather than a resumable state.
if (CloudResourceReservation::where('order_id', (int) $order->id)->exists()) {
throw new CloudError('待支付订单已存在异常资源预留,请联系管理员', 409);
}
// Resolve the hierarchy without trusting it yet, then lock it in the
// same parent-to-child order used by the administrator resource UI.
// This prevents a default-line update (region -> line) from cycling
// with a payment placement transaction.
$poolRef = CloudResourcePool::find((int) $offer->resource_pool_id);
$lineRef = $poolRef === null ? null
: CloudNetworkLine::find((int) $poolRef->line_id);
$regionId = $lineRef === null ? 0 : (int) $lineRef->region_id;
$region = $regionId < 1 ? null
: CloudRegion::where('id', $regionId)->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();
if ($pool === null || (int) $pool->id !== (int) $offer->resource_pool_id
|| (string) $pool->status !== 'active') {
throw new CloudError('该销售方案的资源池暂不可用', 409);
}
if ($line === null || (int) $pool->line_id !== (int) $line->id
|| (string) $line->status !== 'active'
|| $region === null || (int) $line->region_id !== (int) $region->id
|| (string) $region->status !== 'active') {
throw new CloudError('该销售地区或线路暂不可用', 409);
}
if (!CloudNetworkLineFeature::enabled() && !(bool) $line->is_default) {
throw new CloudError('当前未开放线路选择,该销售方案暂不可购买', 409);
}
$candidateRows = self::candidateHostRows((int) $pool->id);
$pendingByHost = self::pendingUsageByHost($candidateRows);
$candidates = $candidateRows->map(static function ($row) use ($pendingByHost): array {
$pending = $pendingByHost[(int) $row->id] ?? self::emptyUsage();
return ['id' => (int) $row->id,
'score' => self::capacityScore($row, $pending)];
})->sort(static fn (array $left, array $right): int =>
($left['score'] <=> $right['score']) ?: ($left['id'] <=> $right['id'])
)->values()->all();
foreach ($candidates as $candidate) {
$placement = self::tryHost(
(int) $candidate['id'], $pool, $order, $offer, $resources, $payload
);
if ($placement !== null) {
return $placement;
}
}
throw new CloudError('当前地区暂时没有足够的可用资源或公网 IP,请稍后重试', 409);
}
public static function commit(CloudOrder $order, int $instanceId,
string $confirmedPublicIpCidr): void
{
[, $reservation] = self::lockedHostAndReservation($order);
if ($reservation === null || (string) $reservation->state === 'released') {
throw new CloudError('开通任务缺少有效的资源预留', 409);
}
$ip = CloudPublicIp::where('id', (int) $reservation->public_ip_id)
->lockForUpdate()->first();
if ($ip === null || (int) $ip->host_id !== (int) $reservation->host_id
|| !self::reservationNetworkMatches($reservation, $ip)
|| (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id
|| !hash_equals((string) $reservation->operation_id,
(string) ($ip->operation_id ?? ''))
|| !hash_equals(
(string) $ip->address . '/' . (int) $ip->prefix_length,
$confirmedPublicIpCidr
)
|| !in_array((string) $reservation->state,
['held', 'uncertain', 'committed'], true)
|| ((string) $reservation->state === 'held'
&& (string) $ip->state !== 'reserved')
|| ((string) $reservation->state === 'uncertain'
&& (string) $ip->state !== 'uncertain')
|| ((string) $reservation->state === 'committed'
&& (string) $ip->state !== 'assigned')) {
throw new CloudError('开通任务的公网 IP 预留不一致', 409);
}
if ((string) $reservation->state === 'committed') {
if ((string) $ip->state !== 'assigned'
|| (int) ($reservation->instance_id ?? 0) !== $instanceId
|| (int) ($ip->instance_id ?? 0) !== $instanceId) {
throw new CloudError('已交付实例的公网 IP 账本不一致', 409);
}
return;
}
$now = time();
$reservation->state = 'committed';
$reservation->instance_id = $instanceId;
$reservation->expires_at = null;
$reservation->updated_at = $now;
$reservation->save();
$ip->state = 'assigned';
$ip->instance_id = $instanceId;
$ip->updated_at = $now;
$ip->save();
}
/**
* Return advisory restore targets for one immutable backup specification.
* Admission repeats every predicate while holding the target-host ledger.
*/
public static function backupRestoreTargets(int $sourceHostId,
array $resources): array
{
$resources = self::upgradeResources($resources);
$result = [];
$hosts = CloudHost::where('enabled', 1)
->orderBy('id')->get();
foreach ($hosts as $host) {
if ((string) $host->default_network !== 'bridge:br0') {
continue;
}
$memberships = CloudHostResourcePoolMembership::where(
'host_id', (int) $host->id
)->where('scheduler_state', 'active')->orderBy('id')->get();
$membership = $memberships->count() === 1
? $memberships->first() : null;
$pool = $membership === null ? null
: CloudResourcePool::find((int) $membership->resource_pool_id);
$line = $pool === null ? null
: CloudNetworkLine::find((int) $pool->line_id);
$region = $line === null ? null
: CloudRegion::find((int) $line->region_id);
$policy = CloudHostCapacityPolicy::find((int) $host->id);
$agent = CloudHostAgent::find((int) $host->id);
$storage = CloudHostStorageConfiguration::find((int) $host->id);
if ($pool === null || $line === null || $region === null
|| (string) $pool->status !== 'active'
|| (string) $line->status !== 'active'
|| (string) $region->status !== 'active'
|| $policy === null || $agent === null || !$agent->isReady()
|| $storage === null || !$storage->isApplied()
|| !self::hasCapacity(
$policy,
CloudPanelUsageService::forHost((int) $host->id),
$resources
)) {
continue;
}
$attachmentIds = CloudHostNetworkAttachment::where(
'host_id', (int) $host->id
)->where('line_id', (int) $line->id)
->where('network_selector', 'bridge:br0')
->where('state', 'active')->where('sync_state', 'applied')
->whereColumn('observed_revision', '>=', 'desired_revision')
->pluck('id')->all();
if ($attachmentIds === []) {
continue;
}
$availableIpCount = CloudPublicIp::query()
->join('cloud_public_ip_pools as restore_pool',
'restore_pool.id', '=', 'cloud_public_ips.public_ip_pool_id')
->where('cloud_public_ips.host_id', (int) $host->id)
->whereIn('restore_pool.network_attachment_id', $attachmentIds)
->where('restore_pool.state', 'active')
->where('restore_pool.sync_state', 'applied')
->whereColumn('restore_pool.observed_revision', '>=',
'restore_pool.desired_revision')
->where('cloud_public_ips.state', 'available')
->whereNull('cloud_public_ips.reservation_id')
->whereNull('cloud_public_ips.instance_id')
->whereNull('cloud_public_ips.operation_id')->count();
if ((int) $availableIpCount < 1) {
continue;
}
$result[] = [
'id' => (string) $host->id,
'name' => (string) $host->name,
'region' => (string) $region->name,
'resource_pool_id' => (string) $pool->id,
'resource_pool' => (string) $pool->name,
'network' => 'bridge:br0',
'available_ip_count' => (int) $availableIpCount,
'is_source_host' => (int) $host->id === $sourceHostId,
];
}
return $result;
}
/** Same-pool, different-host candidates for a cold maintenance migration. */
public static function maintenanceMigrationTargets(CloudInstance $instance,
array $resources, int $additionalDiskGib = 0): array
{
$poolId = (int) ($instance->resource_pool_id ?? 0);
if ($poolId < 1) {
return [];
}
$capacityResources = self::upgradeResources($resources);
$capacityResources['disk_gib'] += max(0, $additionalDiskGib);
return array_values(array_filter(
self::backupRestoreTargets(
(int) $instance->host_id,
$capacityResources
),
static fn (array $target): bool =>
(int) ($target['id'] ?? 0) !== (int) $instance->host_id
&& (int) ($target['resource_pool_id'] ?? 0) === $poolId
));
}
/**
* Reserve target capacity and a fresh IPv4 for an administrator restore.
* The restore row and operation ID are created before this method runs.
*
* @return array{reservation:CloudResourceReservation,host:CloudHost,
* public_ip:CloudPublicIp,network:array<string,mixed>}
*/
public static function reserveBackupRestore(CloudBackupRestore $restore,
int $userId, array $resources,
?int $requiredResourcePoolId = null,
int $additionalDiskGib = 0): array
{
$resources = self::upgradeResources($resources);
$capacityResources = $resources;
$capacityResources['disk_gib'] += max(0, $additionalDiskGib);
$hostId = (int) $restore->target_host_id;
$host = CloudHost::where('id', $hostId)->lockForUpdate()->first();
$memberships = CloudHostResourcePoolMembership::where('host_id', $hostId)
->orderBy('id')->lockForUpdate()->get();
$membership = $memberships->first(static fn ($row): bool =>
(string) $row->scheduler_state === 'active');
if ($memberships->filter(static fn ($row): bool =>
(string) $row->scheduler_state === 'active')->count() !== 1) {
$membership = null;
}
$pool = $membership === null ? null
: CloudResourcePool::where('id', (int) $membership->resource_pool_id)
->lockForUpdate()->first();
$line = $pool === null ? null
: CloudNetworkLine::where('id', (int) $pool->line_id)
->lockForUpdate()->first();
$region = $line === null ? null
: CloudRegion::where('id', (int) $line->region_id)
->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) $host->default_network !== 'bridge:br0'
|| (string) $pool->status !== 'active'
|| (string) $line->status !== 'active'
|| (string) $region->status !== 'active') {
throw new CloudError('所选目标宿主机暂不支持备份恢复', 409);
}
if ($requiredResourcePoolId !== null
&& (int) $pool->id !== $requiredResourcePoolId) {
throw new CloudError('维护迁移只能选择同一资源池的宿主机', 409);
}
$attachments = CloudHostNetworkAttachment::where('host_id', $hostId)
->where('line_id', (int) $line->id)
->where('network_selector', 'bridge:br0')
->where('state', 'active')->where('sync_state', 'applied')
->whereColumn('observed_revision', '>=', 'desired_revision')
->orderBy('id')->lockForUpdate()->get();
if ($attachments->isEmpty()) {
throw new CloudError('目标宿主机的 br0 网络接入尚未就绪', 409);
}
$attachmentById = $attachments->keyBy('id');
$pools = CloudPublicIpPool::where('host_id', $hostId)
->whereIn('network_attachment_id', $attachments->pluck('id')->all())
->where('state', 'active')->where('sync_state', 'applied')
->whereColumn('observed_revision', '>=', 'desired_revision')
->orderBy('id')->lockForUpdate()->get();
$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);
}
$selectedPool = null;
$ip = null;
foreach ($pools as $candidatePool) {
if (preg_match('/^[a-f0-9]{32}$/D',
(string) $candidatePool->pool_key) !== 1) {
continue;
}
foreach (self::availablePublicIpQuery(
$hostId,
(int) $candidatePool->id,
(int) $candidatePool->guest_prefix_length
)->limit(self::MAX_PUBLIC_IPS_PER_POOL + 1)
->lockForUpdate()->get() as $candidateIp) {
if (self::publicIpBelongsToPool($candidateIp, $candidatePool)) {
$selectedPool = $candidatePool;
$ip = $candidateIp;
break 2;
}
}
}
if ($selectedPool === null || $ip === null) {
throw new CloudError('目标宿主机没有可分配的公网 IP', 409);
}
$attachment = $attachmentById->get(
(int) $selectedPool->network_attachment_id
);
if ($attachment === null) {
throw new CloudError('目标宿主机公网地址池关系不完整', 409);
}
$dns = self::poolDnsServers($selectedPool);
$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->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 = (int) $attachment->id;
$reservation->public_ip_pool_id = (int) $selectedPool->id;
$reservation->public_ip_id = (int) $ip->id;
$reservation->cpu_cores = $resources['cpu_cores'];
$reservation->memory_mib = $resources['memory_mib'];
// A maintenance restore reserves the root disk plus every transported
// snapshot volume. The finalizer normalizes this temporary claim back
// to the root disk once the snapshot catalog is atomically rebound.
$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();
$ip->state = 'reserved';
$ip->reservation_id = (int) $reservation->id;
$ip->instance_id = null;
$ip->operation_id = (string) $restore->operation_id;
$ip->updated_at = time();
$ip->save();
return [
'reservation' => $reservation,
'host' => $host,
'public_ip' => $ip,
'network' => [
'network' => 'bridge:br0',
'public_pool_key' => (string) $selectedPool->pool_key,
'public_pool_cidr' => (string) $selectedPool->cidr,
'public_ip_cidr' => (string) $ip->address . '/'
. (int) $ip->prefix_length,
'gateway' => (string) $selectedPool->gateway,
'dns_servers' => $dns,
'resource_pool_id' => (int) $pool->id,
'resource_pool_name' => (string) $pool->name,
'line_id' => (int) $line->id,
'line_name' => (string) $line->name,
'region_id' => (int) $region->id,
'region_name' => (string) $region->name,
'country_code' => strtoupper((string) $region->country_code),
],
];
}
/**
* Re-open an already held restore placement without selecting new capacity.
*
* Maintenance migration reserves its target before the source is stopped.
* The backup finalizer must therefore consume that exact host/address
* reservation instead of racing a second scheduler pass after downtime has
* begun.
*
* @return array{reservation:CloudResourceReservation,network:array<string,mixed>}
*/
public static function preparedBackupRestorePlacement(
CloudBackupRestore $restore,
int $instanceId
): array {
$reservation = CloudResourceReservation::where(
'backup_restore_id',
(int) $restore->id
)->lockForUpdate()->first();
$ip = $reservation === null ? null : CloudPublicIp::where(
'id',
(int) $reservation->public_ip_id
)->lockForUpdate()->first();
$pool = $reservation === null ? null : CloudPublicIpPool::where(
'id',
(int) $reservation->public_ip_pool_id
)->lockForUpdate()->first();
$attachment = $reservation === null ? null
: CloudHostNetworkAttachment::where(
'id',
(int) $reservation->network_attachment_id
)->lockForUpdate()->first();
if ($reservation === null || $ip === null || $pool === null
|| $attachment === null
|| (int) $restore->reservation_id !== (int) $reservation->id
|| (int) $restore->target_host_id !== (int) $reservation->host_id
|| (int) $reservation->backup_restore_id !== (int) $restore->id
|| (int) $reservation->instance_id !== $instanceId
|| (string) $reservation->state !== 'held'
|| (int) $pool->host_id !== (int) $reservation->host_id
|| (int) $pool->network_attachment_id !== (int) $attachment->id
|| (int) $ip->host_id !== (int) $reservation->host_id
|| (int) $ip->public_ip_pool_id !== (int) $pool->id
|| (string) $ip->state !== 'reserved'
|| (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id
|| $ip->instance_id !== null
|| !hash_equals(
(string) $restore->operation_id,
(string) $reservation->operation_id
)
|| !hash_equals(
(string) $reservation->operation_id,
(string) ($ip->operation_id ?? '')
)
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $pool->pool_key) !== 1
|| (string) $attachment->network_selector !== 'bridge:br0') {
throw new CloudRecoveryInstanceStateConflict(
'维护迁移目标预留在源实例停机后发生变化',
409
);
}
return [
'reservation' => $reservation,
'network' => [
'network' => 'bridge:br0',
'public_pool_key' => (string) $pool->pool_key,
'public_pool_cidr' => (string) $pool->cidr,
'public_ip_cidr' => (string) $ip->address . '/'
. (int) $ip->prefix_length,
'gateway' => (string) $pool->gateway,
'dns_servers' => self::poolDnsServers($pool),
'resource_pool_id' => (int) $reservation->resource_pool_id,
],
];
}
/** Commit, release, or fence one restore reservation after exact evidence. */
public static function finishBackupRestore(CloudBackupRestore $restore,
int $instanceId, string $publicIpCidr, string $status): void
{
$host = CloudHost::where('id', (int) $restore->target_host_id)
->lockForUpdate()->first();
$reservation = CloudResourceReservation::where(
'backup_restore_id', (int) $restore->id
)->lockForUpdate()->first();
$ip = $reservation === null ? null : CloudPublicIp::where(
'id', (int) $reservation->public_ip_id
)->lockForUpdate()->first();
if ($host === null || $reservation === null || $ip === null
|| (int) $reservation->host_id !== (int) $host->id
|| (int) $reservation->backup_restore_id !== (int) $restore->id
|| !hash_equals((string) $reservation->operation_id,
(string) $restore->operation_id)
|| !hash_equals((string) $ip->address . '/'
. (int) $ip->prefix_length, $publicIpCidr)) {
throw new CloudError('备份恢复的资源预留账本不一致', 409);
}
if ((string) $reservation->state === 'committed') {
if ((string) $ip->state !== 'assigned'
|| (int) $reservation->instance_id !== $instanceId
|| (int) $ip->instance_id !== $instanceId
|| (int) $ip->reservation_id !== (int) $reservation->id
|| !hash_equals((string) $reservation->operation_id,
(string) $ip->operation_id)) {
throw new CloudError('已恢复实例的资源账本不一致', 409);
}
if ($status !== 'succeeded' && $status !== 'uncertain') {
throw new CloudError('已恢复实例不能回滚资源预留', 409);
}
return;
}
if ((string) $reservation->state === 'released') {
if ((string) $ip->state !== 'available'
|| $ip->reservation_id !== null
|| $ip->instance_id !== null
|| $ip->operation_id !== null) {
throw new CloudError('已释放的备份恢复资源账本不一致', 409);
}
if ($status !== 'failed') {
throw new CloudError('已释放的备份恢复不能重新提交资源', 409);
}
return;
}
if (!in_array((string) $reservation->state,
['held', 'uncertain'], true)
|| !in_array((string) $ip->state,
['reserved', 'uncertain'], true)
|| (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id
|| !hash_equals((string) $reservation->operation_id,
(string) ($ip->operation_id ?? ''))
|| (int) ($reservation->instance_id ?? 0) !== $instanceId) {
throw new CloudError('备份恢复的资源预留状态无效', 409);
}
$now = time();
if ($status === 'succeeded') {
$reservation->state = 'committed';
$reservation->instance_id = $instanceId;
$reservation->expires_at = null;
$ip->state = 'assigned';
$ip->instance_id = $instanceId;
} elseif ($status === 'failed') {
$reservation->state = 'released';
$reservation->released_at = $now;
$reservation->release_reason = 'backup_restore_not_applied';
$reservation->expires_at = null;
$ip->state = 'available';
$ip->reservation_id = null;
$ip->instance_id = null;
$ip->operation_id = null;
} elseif ($status === 'uncertain') {
$reservation->state = 'uncertain';
$reservation->expires_at = null;
$ip->state = 'uncertain';
} else {
throw new \InvalidArgumentException('Invalid backup restore result');
}
$reservation->updated_at = $ip->updated_at = $now;
$reservation->save();
$ip->save();
}
/** Keep an ambiguous create and its address unavailable for reconciliation. */
public static function markUncertain(CloudOrder $order): void
{
[, $reservation] = self::lockedHostAndReservation($order);
if ($reservation === null || (string) $reservation->state === 'released') {
return;
}
$ip = CloudPublicIp::where('id', (int) $reservation->public_ip_id)
->lockForUpdate()->first();
if ($ip === null || (int) $ip->host_id !== (int) $reservation->host_id
|| !self::reservationNetworkMatches($reservation, $ip)
|| (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id
|| !hash_equals((string) $reservation->operation_id,
(string) ($ip->operation_id ?? ''))) {
throw new CloudError('开通任务的公网 IP 预留不一致', 409);
}
// A late exception after a successful commit must never roll a live
// instance and its address back to an ambiguous creation state.
if ((string) $reservation->state === 'committed') {
if ((string) $ip->state !== 'assigned'
|| (int) ($reservation->instance_id ?? 0) < 1
|| (int) ($ip->instance_id ?? 0) !== (int) $reservation->instance_id) {
throw new CloudError('已交付实例的公网 IP 账本不一致', 409);
}
return;
}
if (!in_array((string) $reservation->state, ['held', 'uncertain'], true)
|| !in_array((string) $ip->state, ['reserved', 'uncertain'], true)) {
throw new CloudError('开通任务的资源预留状态无效', 409);
}
$now = time();
$reservation->state = 'uncertain';
$reservation->expires_at = null;
$reservation->updated_at = $now;
$reservation->save();
$ip->state = 'uncertain';
$ip->updated_at = $now;
$ip->save();
}
/** Release only when the Agent outcome proves that no guest owns the IP. */
public static function release(CloudOrder $order, string $reason,
bool $includeCommitted = false): void
{
[, $reservation] = self::lockedHostAndReservation($order);
if ($reservation === null || (string) $reservation->state === 'released') {
return;
}
self::releaseLockedReservation(
$reservation,
$reason,
$includeCommitted
);
}
/** Release the instance's current placement after proven host deletion. */
public static function releaseDeletedInstance(CloudInstance $instance,
string $reason): void
{
if ((string) $instance->status !== 'deleted') {
throw new CloudError('实例尚未确认删除,不能释放资源', 409);
}
$reservationId = (int) ($instance->reservation_id ?? 0);
if ($reservationId < 1) {
if ($instance->order_id === null) {
return;
}
$order = CloudOrder::where('id', (int) $instance->order_id)
->lockForUpdate()->first();
if ($order === null) {
throw new CloudError('已删除实例的开通订单不存在', 409);
}
self::release($order, $reason, true);
return;
}
$host = CloudHost::where('id', (int) $instance->host_id)
->lockForUpdate()->first();
$reservation = CloudResourceReservation::where('id', $reservationId)
->lockForUpdate()->first();
if ($host === null || $reservation === null
|| (int) $reservation->host_id !== (int) $host->id
|| (int) $reservation->instance_id !== (int) $instance->id
|| (int) $reservation->resource_pool_id
!== (int) ($instance->resource_pool_id ?? 0)) {
throw new CloudError('已删除实例的资源预留账本不一致', 409);
}
$orderId = (int) ($reservation->order_id ?? 0);
$restoreId = (int) ($reservation->backup_restore_id ?? 0);
if ($orderId > 0 && $restoreId === 0
&& (int) ($reservation->offer_id ?? 0) > 0) {
$order = CloudOrder::where('id', $orderId)
->lockForUpdate()->first();
if ($order === null
|| (int) ($instance->order_id ?? 0) !== (int) $order->id
|| (int) ($order->reservation_id ?? 0)
!== (int) $reservation->id
|| (int) ($order->host_id ?? 0) !== (int) $instance->host_id) {
throw new CloudError('已删除实例的订单资源账本不一致', 409);
}
} elseif ($orderId === 0 && $restoreId > 0
&& (int) ($reservation->offer_id ?? 0) === 0) {
$restore = CloudBackupRestore::where('id', $restoreId)
->lockForUpdate()->first();
if ($restore === null || $instance->order_id !== null
|| (int) $restore->target_host_id !== (int) $instance->host_id
|| (int) $restore->target_instance_id !== (int) $instance->id
|| (int) $restore->reservation_id !== (int) $reservation->id
|| (string) $restore->state !== 'ready'
|| !hash_equals(
(string) $restore->operation_id,
(string) $reservation->operation_id
)) {
throw new CloudError('已删除恢复实例的资源账本不一致', 409);
}
} else {
throw new CloudError('已删除实例的资源来源无效', 409);
}
self::releaseLockedReservation($reservation, $reason, true);
}
private static function releaseLockedReservation(
CloudResourceReservation $reservation,
string $reason,
bool $includeCommitted
): void {
if ((string) $reservation->state === 'released') {
return;
}
if ((string) $reservation->state === 'committed' && !$includeCommitted) {
throw new CloudError('已交付实例的资源不能按失败任务释放', 409);
}
$ip = CloudPublicIp::where('id', (int) $reservation->public_ip_id)
->lockForUpdate()->first();
if ($ip === null || (int) $ip->host_id !== (int) $reservation->host_id
|| !self::reservationNetworkMatches($reservation, $ip)
|| (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id
|| !hash_equals((string) $reservation->operation_id,
(string) ($ip->operation_id ?? ''))
|| !in_array((string) $reservation->state,
['held', 'uncertain', 'committed'], true)
|| ((string) $reservation->state === 'held'
&& (string) $ip->state !== 'reserved')
|| ((string) $reservation->state === 'uncertain'
&& (string) $ip->state !== 'uncertain')
|| ((string) $reservation->state === 'committed'
&& (string) $ip->state !== 'assigned')) {
throw new CloudError('待释放资源的公网 IP 账本不一致', 409);
}
if ((string) $reservation->state === 'committed'
&& ((string) $ip->state !== 'assigned'
|| (int) ($ip->instance_id ?? 0) !== (int) ($reservation->instance_id ?? 0))) {
throw new CloudError('已交付实例的公网 IP 账本不一致', 409);
}
$reason = preg_replace('/[^a-z0-9_.-]/', '', strtolower($reason)) ?? '';
$reason = substr($reason === '' ? 'released' : $reason, 0, 64);
$now = time();
$reservation->state = 'released';
$reservation->released_at = $now;
$reservation->release_reason = $reason;
$reservation->expires_at = null;
$reservation->updated_at = $now;
$reservation->save();
$ip->state = 'available';
$ip->reservation_id = null;
$ip->instance_id = null;
$ip->operation_id = null;
$ip->updated_at = $now;
$ip->save();
}
/** Atomically settle the PHP-side address ledger for a network-change job. */
public static function finishNetworkChange(CloudInstance $instance,
string $operationId, int $sourceIpId, int $targetIpId,
int $networkAttachmentId, int $sourcePoolId, int $targetPoolId,
string $outcome): void
{
if (!in_array($outcome, ['succeeded', 'failed', 'uncertain'], true)
|| preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1
|| min($sourceIpId, $targetIpId, $networkAttachmentId,
$sourcePoolId, $targetPoolId) < 1
|| $sourceIpId === $targetIpId) {
throw new CloudError('公网 IP 变更账本参数无效', 409);
}
$host = CloudHost::where('id', (int) $instance->host_id)
->lockForUpdate()->first();
// Host is the sentinel for every host-scoped writer. Lock attachment
// and pool rows in numeric order before the reservation/IP ledger so
// placement and network changes cannot invert their lock hierarchy.
$attachment = CloudHostNetworkAttachment::where('id', $networkAttachmentId)
->lockForUpdate()->first();
$poolIds = array_values(array_unique([$sourcePoolId, $targetPoolId]));
sort($poolIds, SORT_NUMERIC);
$pools = CloudPublicIpPool::whereIn('id', $poolIds)->orderBy('id')
->lockForUpdate()->get()->keyBy('id');
$sourcePool = $pools->get($sourcePoolId);
$targetPool = $pools->get($targetPoolId);
$reservation = $instance->reservation_id === null ? null
: CloudResourceReservation::where('id', (int) $instance->reservation_id)
->lockForUpdate()->first();
$reservationPool = $reservation === null ? null
: CloudResourcePool::find((int) $reservation->resource_pool_id);
if ($host === null || $attachment === null
|| $sourcePool === null || $targetPool === null
|| $reservationPool === null
|| (int) $attachment->host_id !== (int) $host->id
|| (int) $reservation->resource_pool_id
!== (int) ($instance->resource_pool_id ?? 0)
|| (int) $attachment->line_id !== (int) $reservationPool->line_id
|| (int) $sourcePool->host_id !== (int) $host->id
|| (int) $targetPool->host_id !== (int) $host->id
|| (int) $sourcePool->network_attachment_id !== $networkAttachmentId
|| (int) $targetPool->network_attachment_id !== $networkAttachmentId
|| preg_match('/^[a-f0-9]{32}$/D', (string) $targetPool->pool_key) !== 1
|| $reservation === null
|| (string) $reservation->state !== 'committed'
|| (int) $reservation->host_id !== (int) $host->id
|| (int) ($reservation->instance_id ?? 0) !== (int) $instance->id
|| (int) ($reservation->network_attachment_id ?? 0)
!== $networkAttachmentId
|| (int) ($reservation->public_ip_pool_id ?? 0) !== $sourcePoolId
|| (int) $reservation->public_ip_id !== $sourceIpId) {
throw new CloudError('虚拟机公网 IP 资源预留不一致', 409);
}
$ipIds = [$sourceIpId, $targetIpId];
sort($ipIds, SORT_NUMERIC);
$ips = CloudPublicIp::whereIn('id', $ipIds)->orderBy('id')
->lockForUpdate()->get()->keyBy('id');
$source = $ips->get($sourceIpId);
$target = $ips->get($targetIpId);
if ($source === null || $target === null
|| (int) $source->host_id !== (int) $host->id
|| (int) $target->host_id !== (int) $host->id
|| (int) ($source->public_ip_pool_id ?? 0) !== $sourcePoolId
|| (int) ($target->public_ip_pool_id ?? 0) !== $targetPoolId
|| (string) $source->state !== 'assigned'
|| (int) ($source->reservation_id ?? 0) !== (int) $reservation->id
|| (int) ($source->instance_id ?? 0) !== (int) $instance->id
|| !hash_equals((string) $reservation->operation_id,
(string) ($source->operation_id ?? ''))
|| !in_array((string) $target->state, ['changing', 'uncertain'], true)
|| $target->reservation_id !== null
|| (int) ($target->instance_id ?? 0) !== (int) $instance->id
|| !hash_equals($operationId, (string) ($target->operation_id ?? ''))) {
throw new CloudError('公网 IP 变更账本关联不一致', 409);
}
if ($outcome === 'succeeded'
&& (!self::publicIpBelongsToPool($source, $sourcePool)
|| !self::publicIpBelongsToPool($target, $targetPool))) {
throw new CloudError('公网 IP 变更结果与地址池账本不一致', 409);
}
$now = time();
if ($outcome === 'uncertain') {
$target->state = 'uncertain';
$target->updated_at = $now;
$target->save();
return;
}
if ($outcome === 'failed') {
$target->state = 'available';
$target->reservation_id = null;
$target->instance_id = null;
$target->operation_id = null;
$target->updated_at = $now;
$target->save();
return;
}
// reservation_id is unique: release the old row before binding the new
// one, while both rows and the reservation remain locked.
$source->state = 'available';
$source->reservation_id = null;
$source->instance_id = null;
$source->operation_id = null;
$source->updated_at = $now;
$source->save();
$reservation->public_ip_id = $targetIpId;
$reservation->network_attachment_id = $networkAttachmentId;
$reservation->public_ip_pool_id = $targetPoolId;
$reservation->save();
$target->state = 'assigned';
$target->reservation_id = (int) $reservation->id;
$target->instance_id = (int) $instance->id;
$target->operation_id = (string) $reservation->operation_id;
$target->updated_at = $now;
$target->save();
}
private static function tryHost(int $hostId, CloudResourcePool $pool,
CloudOrder $order, CloudOffer $offer, array $resources,
array $payload): ?array
{
// Every host-scoped writer starts with the host row. This serializes
// placement and administrator policy changes before any concrete IP
// row is locked.
$host = CloudHost::where('id', $hostId)->lockForUpdate()->first();
$membership = CloudHostResourcePoolMembership::where('host_id', $hostId)
->where('resource_pool_id', (int) $pool->id)
->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();
$body = $payload['body'] ?? null;
$orderSpec = json_decode((string) $order->spec_json, true);
$deploymentSnapshotSource = is_array($orderSpec)
&& !array_is_list($orderSpec)
&& ($orderSpec['source'] ?? null) === 'deployment_snapshot';
$templateId = is_array($body) ? ($body['template_id'] ?? null) : null;
$templateRevision = is_array($body)
? filter_var($body['template_revision'] ?? null,
FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]])
: false;
$generation = is_array($body)
? ($body['template_generation_token'] ?? null) : null;
$template = $deploymentSnapshotSource || !is_string($templateId)
? null : CloudTemplate::find($templateId);
$replica = $deploymentSnapshotSource || !is_string($templateId)
|| $templateRevision === false || !is_string($generation) ? null
: CloudTemplateReplica::query()->where('host_id', $hostId)
->where('template_id', $templateId)->lockForUpdate()->first();
$sourceReady = $deploymentSnapshotSource
? is_array($body)
&& ($body['source'] ?? null) === ''
&& $templateId === ''
&& ($body['template_revision'] ?? null) === 0
&& $generation === ''
: $template instanceof CloudTemplate
&& $replica instanceof CloudTemplateReplica
&& (int) $template->revision === (int) $templateRevision
&& hash_equals(
(string) $template->generation_token,
(string) $generation
)
&& CloudTemplateReplicaCoordinator::isExactReplica(
$template,
$replica
);
if ($host === null || $membership === null || $policy === null
|| !CloudNetworkSelector::isValid($host->default_network)
|| $agent === null || !$agent->isReady()
|| $storage === null || !$storage->isApplied()
|| (string) $membership->scheduler_state !== 'active'
|| !(bool) $host->enabled
|| !$sourceReady
|| (int) $policy->configured_cpu_cores < 1
|| (int) $policy->configured_memory_mib < 1
|| (int) $policy->configured_disk_gib < 1) {
return null;
}
$attachments = CloudHostNetworkAttachment::where('host_id', $hostId)
->where('line_id', (int) $pool->line_id)
->where('network_selector', (string) $host->default_network)
->where('state', 'active')
->where('sync_state', 'applied')
->whereColumn('observed_revision', '>=', 'desired_revision')
->orderBy('id')->lockForUpdate()->get();
if ($attachments->isEmpty()) {
return null;
}
$attachmentById = $attachments->keyBy('id');
$publicPools = CloudPublicIpPool::where('host_id', $hostId)
->whereIn('network_attachment_id', $attachments->pluck('id')->all())
->where('state', 'active')
->where('sync_state', 'applied')
->whereColumn('observed_revision', '>=', 'desired_revision')
// Lock pool rows in primary-key order. Selection preference is
// applied in memory only after the complete row set is locked.
->orderBy('id')->lockForUpdate()->get();
$eligiblePools = [];
foreach ($publicPools as $publicPool) {
if (preg_match('/^[a-f0-9]{32}$/D',
(string) $publicPool->pool_key) === 1) {
$eligiblePools[] = $publicPool;
}
}
usort($eligiblePools, static function ($left, $right) use ($attachmentById): int {
$leftAttachment = $attachmentById->get((int) $left->network_attachment_id);
$rightAttachment = $attachmentById->get((int) $right->network_attachment_id);
return ((int) $leftAttachment->priority <=> (int) $rightAttachment->priority)
?: ((int) $left->priority <=> (int) $right->priority)
?: ((int) $leftAttachment->id <=> (int) $rightAttachment->id)
?: ((int) $left->id <=> (int) $right->id);
});
if ($eligiblePools === []) {
return null;
}
// This must be a current locking read, not an aggregate consistent
// read. Every reservation writer locks the host first, so after this
// host lock is acquired the row set is stable and the locking read
// sees the latest committed state.
$reservationRows = CloudResourceReservation::where('host_id', $hostId)
->whereIn('state', ['held', 'uncertain', 'committed'])
->orderBy('id')->lockForUpdate()->get([
'id', 'instance_id', 'state', 'cpu_cores', 'memory_mib', 'disk_gib',
'updated_at',
]);
$pending = CloudPanelUsageService::forHost($hostId, $reservationRows);
if (!self::hasCapacity($policy, $pending, $resources)) {
return null;
}
$ip = null;
$selectedPool = null;
foreach ($eligiblePools as $publicPool) {
$candidateIps = self::availablePublicIpQuery(
$hostId, (int) $publicPool->id,
(int) $publicPool->guest_prefix_length
)->limit(self::MAX_PUBLIC_IPS_PER_POOL + 1)->lockForUpdate()->get();
if ($candidateIps->count() > self::MAX_PUBLIC_IPS_PER_POOL) {
continue;
}
foreach ($candidateIps as $candidateIp) {
if (self::publicIpBelongsToPool($candidateIp, $publicPool)) {
$ip = $candidateIp;
$selectedPool = $publicPool;
break 2;
}
}
}
if ($ip === null || $selectedPool === null) {
return null;
}
$selectedAttachment = $attachmentById->get(
(int) $selectedPool->network_attachment_id
);
if ($selectedAttachment === null) {
throw new CloudError('公网地址池与网络接入关联不一致', 409);
}
$operationId = bin2hex(random_bytes(16));
$reservation = new CloudResourceReservation();
$reservation->reservation_key = bin2hex(random_bytes(16));
$reservation->operation_id = $operationId;
$reservation->order_id = $order->id;
$reservation->offer_id = $offer->id;
$reservation->resource_pool_id = $pool->id;
$reservation->host_id = $hostId;
$reservation->user_id = $order->user_id;
$reservation->instance_id = null;
$reservation->network_attachment_id = $selectedAttachment->id;
$reservation->public_ip_pool_id = $selectedPool->id;
$reservation->public_ip_id = $ip->id;
$reservation->cpu_cores = $resources['cpu_cores'];
$reservation->memory_mib = $resources['memory_mib'];
$reservation->disk_gib = $resources['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();
$ip->state = 'reserved';
$ip->reservation_id = $reservation->id;
$ip->instance_id = null;
$ip->operation_id = $operationId;
$ip->updated_at = time();
$ip->save();
$order->resource_pool_id = $pool->id;
$order->host_id = $hostId;
$order->reservation_id = $reservation->id;
$order->updated_at = time();
$order->save();
return [
'host' => $host,
'reservation' => $reservation,
'public_ip' => $ip,
'payload' => self::placementPayload(
$payload, $selectedAttachment, $selectedPool, $ip
),
];
}
private static function placementPayload(array $payload,
CloudHostNetworkAttachment $attachment, CloudPublicIpPool $publicPool,
CloudPublicIp $ip): array
{
if (($payload['method'] ?? null) !== 'POST'
|| ($payload['request_target'] ?? null) !== '/v1/vms'
|| !is_array($payload['body'] ?? null)) {
throw new CloudError('开通订单的加密请求无效', 409);
}
$payload['body']['network'] = (string) $attachment->network_selector;
$payload['body']['public_pool_key'] = (string) $publicPool->pool_key;
$payload['body']['public_pool_cidr'] = (string) $publicPool->cidr;
$payload['body']['public_ip_cidr'] = (string) $ip->address . '/'
. (int) $ip->prefix_length;
$payload['body']['gateway'] = (string) $publicPool->gateway;
$payload['body']['dns_servers'] = self::poolDnsServers($publicPool);
return $payload;
}
/** Return the validated DNS snapshot frozen on one public address pool. */
private static function poolDnsServers(CloudPublicIpPool $pool): array
{
try {
$dnsServers = json_decode(
(string) $pool->dns_servers_json,
true,
16,
JSON_THROW_ON_ERROR
);
} catch (\Throwable $error) {
throw new CloudError('公网地址池 DNS 配置损坏', 409);
}
if (!is_array($dnsServers) || !array_is_list($dnsServers)
|| $dnsServers === []
|| count($dnsServers) > 4
|| count(array_filter($dnsServers, static fn ($value): bool =>
is_string($value) && filter_var(
$value,
FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4
) !== false
)) !== count($dnsServers)) {
throw new CloudError('公网地址池 DNS 配置损坏', 409);
}
return array_values($dnsServers);
}
private static function assertOrderOffer(CloudOrder $order, CloudOffer $offer,
Shop $plan): void
{
if ((int) $order->offer_id !== (int) $offer->id
|| (int) $offer->plan_id !== (int) $plan->id
|| (int) $order->plan_id !== (int) $plan->id
|| (int) $order->resource_pool_id !== (int) $offer->resource_pool_id) {
throw new CloudError('订单与销售方案快照不匹配', 409);
}
}
/**
* Capacity must follow the immutable order snapshot, never the mutable
* current plan. The sealed Agent request is checked against the same
* values so reservation and eventual guest creation cannot drift apart.
*
* @return array{cpu_cores:int,memory_mib:int,disk_gib:int}
*/
private static function orderResources(CloudOrder $order, array $payload): array
{
$spec = json_decode((string) $order->spec_json, true);
$body = $payload['body'] ?? null;
if (!is_array($spec) || array_is_list($spec)
|| !is_array($body) || array_is_list($body)) {
throw new CloudError('订单的资源规格快照无效', 409);
}
$fields = [
'cpu_cores' => 'vcpu',
'memory_mib' => 'memory_mib',
'disk_gib' => 'disk_gib',
];
$resources = [];
foreach ($fields as $resource => $payloadField) {
$snapshotValue = filter_var(
$spec[$payloadField] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => PHP_INT_MAX]]
);
$payloadValue = filter_var(
$body[$payloadField] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => PHP_INT_MAX]]
);
if ($snapshotValue === false || $payloadValue === false
|| (int) $snapshotValue !== (int) $payloadValue) {
throw new CloudError('订单的资源规格快照与开通请求不一致', 409);
}
$resources[$resource] = (int) $snapshotValue;
}
if ((int) ($spec['plan_id'] ?? 0) !== (int) $order->plan_id
|| (int) ($spec['offer_id'] ?? 0) !== (int) $order->offer_id
|| (int) ($spec['resource_pool_id'] ?? 0) !== (int) $order->resource_pool_id) {
throw new CloudError('订单的销售与资源池快照不一致', 409);
}
$specPolicy = CloudPlatformTestNetworkPolicy::assertSnapshot(
$spec['platform_network_policy_snapshot'] ?? null
);
$payloadPolicy = CloudPlatformTestNetworkPolicy::assertSnapshot(
$body['platform_network_policy_snapshot'] ?? null
);
if ($specPolicy !== $payloadPolicy) {
throw new CloudError('订单与开通请求的平台网络策略快照不一致', 409);
}
return $resources;
}
/** @return array{0: ?CloudHost, 1: ?CloudResourceReservation} */
private static function lockedHostAndReservation(CloudOrder $order): array
{
$host = $order->host_id === null ? null
: CloudHost::where('id', (int) $order->host_id)->lockForUpdate()->first();
$reservation = CloudResourceReservation::where('order_id', (int) $order->id)
->lockForUpdate()->first();
if ($reservation !== null
&& ($host === null || (int) $reservation->host_id !== (int) $host->id)) {
throw new CloudError('订单的宿主机与资源预留不一致', 409);
}
return [$host, $reservation];
}
private static function candidateHostRows(int $poolId)
{
return CloudHost::query()->join(
'cloud_host_resource_pool_memberships as pool_membership',
'pool_membership.host_id', '=', 'cloud_hosts.id'
)->join(
'cloud_resource_pools as membership_pool',
'membership_pool.id', '=', 'pool_membership.resource_pool_id'
)->join(
'cloud_host_capacity_policies as capacity_policy',
'capacity_policy.host_id', '=', 'cloud_hosts.id'
)->join(
'cloud_host_agents as host_agent',
'host_agent.host_id', '=', 'cloud_hosts.id'
)->join(
'cloud_host_storage_configurations as host_storage',
'host_storage.host_id', '=', 'cloud_hosts.id'
)->where('pool_membership.resource_pool_id', $poolId)
->where('pool_membership.scheduler_state', 'active')
->where('cloud_hosts.enabled', 1)
->where('host_agent.enabled', 1)
->where('host_agent.last_test_status', 'healthy')
->where('host_agent.tested_revision', '>', 0)
->whereColumn('host_agent.tested_revision',
'host_agent.revision')
->where('host_storage.state', 'applied')
->where('capacity_policy.configured_cpu_cores', '>', 0)
->where('capacity_policy.configured_memory_mib', '>', 0)
->where('capacity_policy.configured_disk_gib', '>', 0)
->distinct()
->get([
'cloud_hosts.id',
'cloud_hosts.default_network',
'membership_pool.line_id as resource_pool_line_id',
'capacity_policy.configured_cpu_cores',
'capacity_policy.configured_memory_mib',
'capacity_policy.configured_disk_gib',
'capacity_policy.safety_cpu_cores',
'capacity_policy.safety_memory_mib',
'capacity_policy.safety_disk_gib',
'capacity_policy.max_instances',
])->filter(static fn ($host): bool =>
CloudNetworkSelector::isValid($host->default_network));
}
private static function pendingUsageByHost($candidateRows): array
{
$candidateIds = $candidateRows->pluck('id')->map(
static fn ($id): int => (int) $id
)->unique()->values()->all();
if ($candidateIds === []) {
return [];
}
return CloudPanelUsageService::forHosts($candidateIds);
}
/**
* Return hosts with at least one concrete address in an eligible pool.
*
* This remains an advisory, non-locking read. The payment path repeats
* every predicate under the host, attachment, pool and IP row locks.
*
* @return array<int,bool>
*/
private static function availableIpHosts($candidateRows): array
{
$hostIds = $candidateRows->pluck('id')->map(
static fn ($id): int => (int) $id
)->unique()->values()->all();
if ($hostIds === []) {
return [];
}
$lineId = (int) ($candidateRows->first()->resource_pool_line_id ?? 0);
if ($lineId < 1) {
return [];
}
// Management, gateway, DNS and other operator-owned addresses are
// removed from the ledger when the pool's reserved_ips is materialized.
// cloud_hosts intentionally has no Agent/SSH host-address column.
$rows = CloudPublicIp::query()->join(
'cloud_public_ip_pools as public_pool',
'public_pool.id', '=', 'cloud_public_ips.public_ip_pool_id'
)->join(
'cloud_host_network_attachments as network_attachment',
'network_attachment.id', '=', 'public_pool.network_attachment_id'
)->join(
'cloud_hosts as eligible_host',
'eligible_host.id', '=', 'cloud_public_ips.host_id'
)->whereIn('cloud_public_ips.host_id', $hostIds)
->where('cloud_public_ips.state', 'available')
->whereNull('cloud_public_ips.reservation_id')
->whereNull('cloud_public_ips.instance_id')
->whereNull('cloud_public_ips.operation_id')
->whereColumn('cloud_public_ips.host_id', 'public_pool.host_id')
->whereColumn('cloud_public_ips.prefix_length',
'public_pool.guest_prefix_length')
->whereColumn('cloud_public_ips.host_id', 'network_attachment.host_id')
->whereColumn('network_attachment.network_selector',
'eligible_host.default_network')
->where('network_attachment.line_id', $lineId)
->where('network_attachment.state', 'active')
->where('network_attachment.sync_state', 'applied')
->whereColumn('network_attachment.observed_revision', '>=',
'network_attachment.desired_revision')
->where('public_pool.state', 'active')
->where('public_pool.sync_state', 'applied')
->whereColumn('public_pool.observed_revision', '>=',
'public_pool.desired_revision')
->distinct()->get([
'cloud_public_ips.host_id', 'cloud_public_ips.address',
'public_pool.pool_key', 'public_pool.cidr',
]);
$available = [];
foreach ($rows as $row) {
if (preg_match('/^[a-f0-9]{32}$/D', (string) $row->pool_key) === 1
&& self::ipv4BelongsToCidr(
(string) $row->address, (string) $row->cidr
)) {
$available[(int) $row->host_id] = true;
}
}
return $available;
}
private static function emptyUsage(): array
{
return [
'instance_count' => 0,
'cpu_sum' => 0,
'memory_sum' => 0,
'disk_sum' => 0,
];
}
/** @return array{cpu_cores:int,memory_mib:int,disk_gib:int} */
private static function upgradeResources(array $resources): array
{
$normalized = [];
foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $field) {
$value = filter_var(
$resources[$field] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => PHP_INT_MAX]]
);
if ($value === false) {
throw new CloudError('实例升级资源规格无效', 409);
}
$normalized[$field] = (int) $value;
}
return $normalized;
}
/**
* Lock the exact placement chain shared by admission and finalization.
*
* @return array{0:CloudHostCapacityPolicy,1:CloudResourceReservation,
* 2:mixed}
*/
private static function lockUpgradePlacement(
CloudInstance $instance,
bool $requireReady
): array {
$poolRef = CloudResourcePool::find(
(int) ($instance->resource_pool_id ?? 0)
);
$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', (int) $instance->host_id)
->lockForUpdate()->first();
$membership = CloudHostResourcePoolMembership::where(
'host_id',
(int) $instance->host_id
)->where(
'resource_pool_id',
(int) ($instance->resource_pool_id ?? 0)
)->lockForUpdate()->first();
$policy = CloudHostCapacityPolicy::where(
'host_id',
(int) $instance->host_id
)->lockForUpdate()->first();
$storage = CloudHostStorageConfiguration::where(
'host_id',
(int) $instance->host_id
)->lockForUpdate()->first();
$agent = CloudHostAgent::where(
'host_id',
(int) $instance->host_id
)->lockForUpdate()->first();
if ($region === null || $line === null || $pool === null
|| $host === null || $membership === null || $policy === null
|| (int) $line->region_id !== (int) $region->id
|| (int) $pool->line_id !== (int) $line->id
|| (int) $pool->id !== (int) ($instance->resource_pool_id ?? 0)
|| (int) $membership->host_id !== (int) $host->id
|| (int) $membership->resource_pool_id !== (int) $pool->id) {
throw new CloudRecoveryInstanceStateConflict(
'实例升级的固定资源池账本不完整',
409
);
}
if ($requireReady
&& ((string) $region->status !== 'active'
|| (string) $line->status !== 'active'
|| (string) $pool->status !== 'active'
|| !(bool) $host->enabled
|| (string) $membership->scheduler_state !== 'active'
|| $agent === null || !$agent->isReady()
|| $storage === null || !$storage->isApplied()
|| (int) $policy->configured_cpu_cores < 1
|| (int) $policy->configured_memory_mib < 1
|| (int) $policy->configured_disk_gib < 1)) {
throw new CloudError('实例所在宿主机暂不支持套餐升级', 409);
}
$rows = CloudResourceReservation::where(
'host_id',
(int) $host->id
)->whereIn('state', ['held', 'uncertain', 'committed'])
->orderBy('id')->lockForUpdate()->get();
$reservation = $rows->first(static fn ($row): bool =>
(int) $row->id === (int) ($instance->reservation_id ?? 0));
if ($reservation === null
|| (string) $reservation->state !== 'committed'
|| (int) ($reservation->instance_id ?? 0) !== (int) $instance->id
|| (int) $reservation->user_id !== (int) $instance->user_id
|| (int) $reservation->host_id !== (int) $instance->host_id
|| (int) $reservation->resource_pool_id !== (int) $pool->id) {
throw new CloudRecoveryInstanceStateConflict(
'实例升级缺少有效的已提交资源预留',
409
);
}
return [$policy, $reservation, $rows];
}
/** Remove the current instance from a complete usage projection. */
private static function usageWithoutUpgradeReservation(
array $usage,
CloudResourceReservation $reservation
): ?array {
if ((int) ($usage['unknown'] ?? 0) > 0
|| (int) ($usage['instance_count'] ?? 0) < 1
|| (int) ($usage['cpu_sum'] ?? 0) < (int) $reservation->cpu_cores
|| (int) ($usage['memory_sum'] ?? 0) < (int) $reservation->memory_mib
|| (int) ($usage['disk_sum'] ?? 0) < (int) $reservation->disk_gib) {
return null;
}
return [
'unknown' => 0,
'instance_count' => (int) $usage['instance_count'] - 1,
'cpu_sum' => (int) $usage['cpu_sum']
- (int) $reservation->cpu_cores,
'memory_sum' => (int) $usage['memory_sum']
- (int) $reservation->memory_mib,
'disk_sum' => (int) $usage['disk_sum']
- (int) $reservation->disk_gib,
];
}
private static function capacityState($policy, array $usage): array
{
$cpuLimit = max(0, (int) $policy->configured_cpu_cores
- (int) $policy->safety_cpu_cores);
$memoryLimit = max(0, (int) $policy->configured_memory_mib
- (int) $policy->safety_memory_mib);
$configuredDisk = (int) $policy->configured_disk_gib * self::GIB;
$safetyDisk = (int) $policy->safety_disk_gib * self::GIB;
$diskLimit = max(0, $configuredDisk - $safetyDisk);
return [
'cpu_limit' => $cpuLimit,
'memory_limit' => $memoryLimit,
'disk_limit' => $diskLimit,
'cpu_used' => $usage['cpu_sum'],
'memory_used' => $usage['memory_sum'],
'disk_used' => $usage['disk_sum'] * self::GIB,
'instances' => $usage['instance_count'],
'max_instances' => (int) $policy->max_instances,
];
}
private static function hasCapacity($policy, array $usage, array $resources): bool
{
if ((int) ($usage['unknown'] ?? 0) > 0) {
return false;
}
$state = self::capacityState($policy, $usage);
return $state['cpu_used'] + $resources['cpu_cores'] <= $state['cpu_limit']
&& $state['memory_used'] + $resources['memory_mib']
<= $state['memory_limit']
&& $state['disk_used'] + ($resources['disk_gib'] * self::GIB)
<= $state['disk_limit']
&& ($state['max_instances'] < 1
|| $state['instances'] + 1 <= $state['max_instances']);
}
private static function capacityScore($policy, array $usage): float
{
$state = self::capacityState($policy, $usage);
$instanceScore = $state['max_instances'] > 0
? $state['instances'] / $state['max_instances'] : 0.0;
return max(
$state['cpu_used'] / max(1, $state['cpu_limit']),
$state['memory_used'] / max(1, $state['memory_limit']),
$state['disk_used'] / max(1, $state['disk_limit']),
$instanceScore
);
}
private static function availablePublicIpQuery(int $hostId, int $publicPoolId,
int $prefixLength)
{
return CloudPublicIp::query()->where('host_id', $hostId)
->where('public_ip_pool_id', $publicPoolId)
->where('prefix_length', $prefixLength)
->where('state', 'available')
->whereNull('reservation_id')->whereNull('instance_id')
->whereNull('operation_id')->orderBy('id');
}
/** Require the complete immutable network identity of a reservation. */
private static function reservationNetworkMatches(
CloudResourceReservation $reservation, CloudPublicIp $ip): bool
{
return (int) ($reservation->network_attachment_id ?? 0) > 0
&& (int) ($reservation->public_ip_pool_id ?? 0) > 0
&& (int) ($ip->public_ip_pool_id ?? 0)
=== (int) $reservation->public_ip_pool_id;
}
private static function publicIpBelongsToPool(CloudPublicIp $ip,
CloudPublicIpPool $pool): bool
{
if ((int) $ip->prefix_length !== (int) $pool->guest_prefix_length) {
return false;
}
if (!self::ipv4BelongsToCidr(
(string) $ip->address, (string) $pool->cidr
)) {
return false;
}
$blocked = [(string) $pool->gateway];
$managementAddress = CloudPanelUsageService::managementAddress(
CloudHost::find((int) $pool->host_id)
);
if ($managementAddress !== null) {
$blocked[] = $managementAddress;
}
foreach (['dns_servers_json', 'reserved_ips_json'] as $field) {
try {
$values = json_decode((string) $pool->{$field}, true,
16, JSON_THROW_ON_ERROR);
} catch (\Throwable $error) {
return false;
}
if (!is_array($values) || !array_is_list($values)) {
return false;
}
foreach ($values as $value) {
if (!is_string($value)
|| filter_var($value, FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4) === false) {
return false;
}
$blocked[] = $value;
}
}
return !in_array((string) $ip->address, $blocked, true);
}
private static function ipv4BelongsToCidr(string $addressValue,
string $cidr): bool
{
$parts = explode('/', $cidr, 2);
if (count($parts) !== 2 || !ctype_digit($parts[1])) {
return false;
}
$prefix = (int) $parts[1];
$address = self::ipv4Number($addressValue);
$network = self::ipv4Number($parts[0]);
if ($address === null || $network === null || $prefix < 24 || $prefix > 30) {
return false;
}
$block = 2 ** (32 - $prefix);
$base = (int) (floor($network / $block) * $block);
return $address > $base && $address < $base + $block - 1;
}
private static function ipv4Number(string $value): ?int
{
if (filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
return null;
}
$packed = inet_pton($value);
if ($packed === false || strlen($packed) !== 4) {
return null;
}
$parts = unpack('Nnumber', $packed);
return is_array($parts) && isset($parts['number'])
? (int) sprintf('%u', $parts['number']) : null;
}
}