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

956 lines
42 KiB
PHTML

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudHostCapacityPolicy;
use App\Models\CloudHostNetworkAttachment;
use App\Models\CloudHostResourcePoolMembership;
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\Shop;
/**
* Database-only, payment-time placement and resource reservation.
*
* The caller owns the surrounding wallet transaction. No engine 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;
}
/**
* 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, not a resumable legacy 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();
}
/** 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 engine 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;
}
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();
if ($host === null || $membership === null || $policy === null
|| (string) $membership->scheduler_state !== 'active'
|| !(bool) $host->enabled
|| (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['resource'] ?? null) !== '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_ip_cidr'] = (string) $ip->address . '/'
. (int) $ip->prefix_length;
// For a configured host pool the engine owns these trusted values.
$payload['body']['gateway'] = '';
$payload['body']['dns_servers'] = [];
return $payload;
}
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 encrypted engine 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'
)->where('pool_membership.resource_pool_id', $poolId)
->where('pool_membership.scheduler_state', 'active')
->where('cloud_hosts.enabled', 1)
->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',
]);
}
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 engine/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,
];
}
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');
}
/**
* Nullable identities keep pre-migration in-flight jobs operable. A row
* that has started adopting the new identity must be complete and exact.
*/
private static function reservationNetworkMatches(
CloudResourceReservation $reservation, CloudPublicIp $ip): bool
{
if ($reservation->network_attachment_id === null
&& $reservation->public_ip_pool_id === null) {
return true;
}
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;
}
}